diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json
index 9838dcd9686..6ddcdb586b2 100644
--- a/.claude-plugin/marketplace.json
+++ b/.claude-plugin/marketplace.json
@@ -33,7 +33,7 @@
{
"name": "loom-code-skill",
"source": "./",
- "description": "Code search and code intelligence for repositories in a Loom code index (the loom-code Agent Skill: code.* first, then read only that), and the loom Agent Skill: how an agent uses Loom. No hooks; GitHub Copilot CLI also adds the loom MCP server.",
+ "description": "Code search and code intelligence for repositories in a Loom code index (the loom-code Agent Skill), what to save and how (loom-memory), why Loom is quiet (loom-status), and the loom Agent Skill: how an agent uses Loom. No hooks; GitHub Copilot CLI also adds the loom MCP server.",
"license": "Apache-2.0",
"category": "code-intelligence"
}
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 3c3c7a7e127..7cc0b963824 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,9 +1,9 @@
{
"name": "loom-code-skill",
"version": "1.3.0",
- "description": "Code search and code intelligence for repositories in a Loom code index (the loom-code Agent Skill: code.* first, then read only that), and the loom Agent Skill: how an agent uses Loom. Skills only, no hooks.",
+ "description": "Code search and code intelligence for repositories in a Loom code index (the loom-code Agent Skill), what to save and how (loom-memory), why Loom is quiet (loom-status), and the loom Agent Skill: how an agent uses Loom. Skills only, no hooks.",
"author": { "name": "ClickHouse" },
- "homepage": "https://clickhouse.github.io/loom/",
+ "homepage": "https://loom.clickhouse.com/docs/",
"repository": "https://github.com/ClickHouse/loom",
"license": "Apache-2.0",
"keywords": ["code-intelligence", "code-search", "agent-memory", "mcp", "clickhouse", "agent", "skill"],
diff --git a/.claude/rules/code-index.md b/.claude/rules/code-index.md
index 97d67fd5686..803488aa8f7 100644
--- a/.claude/rules/code-index.md
+++ b/.claude/rules/code-index.md
@@ -8,5 +8,5 @@ paths:
- A code change to a module in `extractor_stamp.EXTRACTOR_MODULES` or a grammar in `STAMPED_GRAMMARS` re-runs its stage (`STAGES`: chunk, symbol, edge, guard) for the language families it touches in every indexed repository (hours of ingest). The stamp hashes code tokens only (`extractor_stamp.logic_tokens`), so comments and docstrings can be edited freely. Touch their code only when the extraction itself changes, and say so in the PR.
- Those modules are excluded from formatting; do not reformat them.
- Lane parsers outside the stamp re-ingest their files with `loom code backfill --paths-file`.
-- Mirrors and compiler-tier checkouts are gc'd only by `gc_if_due` in `server/code/app/index/mirrors.py`, with `--no-prune`, because a checkout borrows objects from its mirror through alternates; a new gc path never prunes. A commit fetched by sha is pinned under `refs/loom/merges/` so gc keeps it; a new fetch path pins what it fetches the same way.
+- Mirrors and compiler-tier checkouts are gc'd only by `gc_if_due` in `server/code/app/index/mirrors.py`, with `--no-prune`; a new gc path never prunes. A checkout's packs shared with its mirror are hard links kept by a `.keep`, so its gc rewrites only what they lack. A commit fetched by sha is pinned under `refs/loom/merges/` so gc keeps it; a new fetch path pins what it fetches the same way.
- Guide: [adding-language-support](../../docs/development/adding-language-support.md).
diff --git a/.claude/rules/plugins.md b/.claude/rules/plugins.md
index 6628f8ea926..96c66573a7b 100644
--- a/.claude/rules/plugins.md
+++ b/.claude/rules/plugins.md
@@ -10,12 +10,12 @@ paths:
# Integrations and coding-agent plugins
-- Edit `integrations/claude-code-plugin/`, then `python -m scripts.codegen.agent_plugin_sync` copies its `hooks/*.mjs`, `bin/`, `lib/`, `skills/` and `assets/` to the Codex plugin; never edit a synced copy. Each plugin's manifest, `hooks/hooks.json` and `.mcp.json`, and the Codex `plugin-defaults.json`, differ on purpose and are edited in their own directory.
+- Edit `integrations/claude-code-plugin/`, then `python -m scripts.codegen.agent_plugin_sync` copies its `hooks/*.mjs`, `bin/`, `lib/`, `skills/` and `assets/` to the Codex plugin; never edit a synced copy. A change to the `loom-memory`, `loom-code` or `loom-status` skill also runs `python -m scripts.codegen.standalone_skills`, which rewrites the root `skills/loom-memory/`, `skills/loom-code/` and `skills/loom-status/` (the copies for a client without the plugin; never edit one): text that holds only inside the plugin gets an edit in `scripts/codegen/portable_skills.py`. A change to the `loom-memory` or `loom-code` skill also runs `python -m scripts.codegen.served_skills`, which writes the copies the MCP transport serves (`server/transport/served_skills/`) and fails on text only the plugin can honour. Each plugin's manifest, `hooks/hooks.json` and `.mcp.json`, and the Codex `plugin-defaults.json`, differ on purpose and are edited in their own directory.
- A behaviour change to any file the Claude Code or Codex plugin ships (`hooks/`, `lib/`, `bin/`, `skills/`, `.mcp.json`, the Codex `plugin-defaults.json`) bumps both plugin manifests (`integrations/claude-code-plugin/.claude-plugin/plugin.json`, `integrations/codex-plugin/.codex-plugin/plugin.json`) to a version no other open PR uses: two PRs with one version ship only the first.
- A hook, `lib/` or `bin/` change that calls an op or a field the server does not serve yet says so in its changelog entry ("needs the next server release"), so the release notes list it: that release's pull request raises `MIN_SERVER_VERSION` in `lib/server-version.mjs` to its own version and bumps both plugin versions (clients get it only through a new version); a pull request on `main` before it never raises it (`tests/unit/test_codex_plugin.py` keeps it no newer than the server). Between such a hook's merge and that release, a server of the previous release gets no warning.
- Hooks run inside a user's session: they never throw to the agent, never block past their timeout, never print a token, and degrade to silence when the server is unreachable.
- Before pushing, run the `integrations/` row of `loom-pre-push` §3, which lists every check CI runs here, and, for `.cursor-plugin/` and the root Agent Plugins package (`plugin.json`, `mcp.json`), their own rows; a change to a plugin skill also runs `claude plugin eval integrations/claude-code-plugin` ([evals](../../integrations/claude-code-plugin/evals/README.md)), and a new skill adds a case.
- Anything a hook sends to the server goes through `redactSecrets` / `redactHead`, redacting before truncating, and a diff through `diffHeaders`, which sends only its paths, hunk ranges and function names (`integrations/claude-code-plugin/lib/loom-client.mjs`); a new capture path that skips them is a finding.
- An integration or its README is held to an open-source bar: the happy path runs end to end as written; an experimental feature says so and names the versions it was tested on; an upstream bug is filed upstream and linked; a cheap CI check keeps the example from rotting.
-- The root `skills/loom-code/` and `skills/loom/` skills are not synced: their version is `.claude-plugin/plugin.json` (and `.cursor-plugin/plugin.json` and the root `plugin.json`, whose plugins ship them) plus each `metadata.version`, released with the server; `skills/loom/` is also what `mentor.guide` serves, so the image copies it ([release process](../../docs/development/release-process.md#where-the-version-lives)).
+- The root `skills/` take the server's version, not the plugins': `.claude-plugin/plugin.json` (and `.cursor-plugin/plugin.json` and the root `plugin.json`, whose plugins ship the whole folder) plus each `metadata.version`, released with the server; `skills/loom/` is written by hand and is also what `mentor.guide` serves, so the image copies it ([release process](../../docs/development/release-process.md#where-the-version-lives)).
- The skills here ship to users. Their text is prompt: every line costs tokens in every session, so keep them short and exact.
diff --git a/.claude/rules/wire-ops.md b/.claude/rules/wire-ops.md
index f48af99d1dd..1d36c726d8e 100644
--- a/.claude/rules/wire-ops.md
+++ b/.claude/rules/wire-ops.md
@@ -13,7 +13,7 @@ paths:
- `server/operations/base.py` defines `Operation`, `Role` and `grant_rank`; `server/transport/mcp_primer.py` renders the primer and answers `prompts/*` / `resources/*`; `server/observability/budgets.py::effective_budget_ms` resolves each op's latency budget (runtime and per-consumer overrides).
- Nothing below `server/transport/` imports it (`tests/unit/test_transport_layering.py`), and `package_contract_allowlist.txt` only shrinks: fix the import, never add an exception.
- Models in `server//api/models_.py` import no handler; the `Operation` and its `OPERATIONS` entry live in `ops_.py`. `server/operations/registry.py` imports each list, and the handler in `server//app/` imports its models at module top. Transports discover ops from the registry; a change that edits transport code to add an op is in the wrong place.
-- After any op or field change: `python -m scripts.codegen.` for `sdk_py_gen`, `sdk_py_client_gen`, `sdk_ts_gen`, `sdk_rb_gen`, `docs_reference`, `op_reach_census`. Generated SDK files are never edited by hand.
+- After any op or field change: `python -m scripts.codegen.` for `sdk_py_gen`, `sdk_py_client_gen`, `sdk_ts_gen`, `sdk_rb_gen`, `sdk_rust_gen`, `sdk_rust_gen --fixtures`, `sdk_go_gen`, `docs_reference`, `op_reach_census`. Generated SDK files are never edited by hand.
- Whether an agent calls `memory.set` or `memory.pin` is the model's judgement from the tool description (`server/transport/mcp_descriptions.py`), not a pattern match: change the wording, not a regex.
- A field description is what a model reads when it calls the tool: one sentence on what the value does, its unit and its default.
- The default MCP `tools/list` has a token ceiling (`test_mcp_listing_budget.py`); a new tool joins the default listing only when an agent needs it without asking.
diff --git a/.claude/skills/loom-bench/SKILL.md b/.claude/skills/loom-bench/SKILL.md
index a335bde4f4b..cb74dc49200 100644
--- a/.claude/skills/loom-bench/SKILL.md
+++ b/.claude/skills/loom-bench/SKILL.md
@@ -43,6 +43,16 @@ Before reading a single score, check from the run's own output or the server's l
- recall@K and judged QA accuracy are separate axes; never set one beside the other ([recall and answer accuracy](../../../docs/benchmarks/methodology.md#recall-and-answer-accuracy-are-separate-axes)).
- Report every category, including the one that went down.
+### Native coding-agent comparisons
+
+- Freeze the issue, source, model, instructions and graders across arms. Keep native tool choice. Record advertised tools, actual calls, historical facts delivered before edits and independent verifier outcomes. A one-issue quality tie cannot measure historical memory lift.
+- For a cache-disabled comparison, disable provider prompt caching for every arm and verify zero reads and writes on every model request. With caching enabled, verify each planned starting state from provider usage. If the protocol calls for a cold start, use provider-supported isolation and check the first request for zero cache reads. If it calls for warm reuse, verify the reads on the same arm. A fresh session and an elapsed TTL are setup details. Cache state comes from the receipts. Track Loom-local caching and index preparation separately. See [provider usage fields](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#tracking-cache-performance).
+- Compare like cache states. Split first-request usage from later turns and retain uncached input, cache reads, writes by TTL and output. Use the reported solver cost. Show separately tracked Loom provider charges alongside it. Report agent time and full end-to-end time.
+- Check cost and time targets for the same arm and matched baseline within each cache state. Leave the cost target unresolved when only fallback estimates or incomplete upstream charges are available. Compare memory cost, time and quality with the same index tier alone. Report linked facts delivered alongside hidden tests and the blind judge.
+- Compare complete sessions for the same task, repeat and cache start. Join model usage and tool replies by tool call ID. Inspect the request and available source after a miss. For a hidden-test failure, check the submitted edit against the verifier and inspect the source and lesson states delivered before the edit.
+- Count model responses as well as tools. Check the next model response before crediting a smaller payload or a batched lookup with saving a turn. See [coding-agent overhead](../../../docs/guides/debugging.md#diagnose-coding-agent-overhead).
+- When literal `code.grep` excerpts lead to separate implementation and test reads, replay the original clues with default bodies and the test-name clue in one batch. Scope both roots with globs and omit `path_prefix`. Compare the evidence and size with all original responses. Check the working revision before counting an edited-file read as replaceable.
+
## 5. Write it up
- The PR body carries the numbers, the command that reproduces them, the model and judge, and the item count.
diff --git a/.claude/skills/loom-change/SKILL.md b/.claude/skills/loom-change/SKILL.md
index 0060fd37636..c8334e2cd25 100644
--- a/.claude/skills/loom-change/SKILL.md
+++ b/.claude/skills/loom-change/SKILL.md
@@ -11,7 +11,7 @@ Find the row for the change, read its guide before the first edit, and finish it
| Change | Guide | Also in the same PR |
| --- | --- | --- |
-| Wire op (new, renamed, removed field) | [adding-an-operation](../../../docs/development/adding-an-operation.md) | `python -m scripts.codegen.sdk_py_gen`, `.sdk_py_client_gen`, `.sdk_ts_gen`, `.docs_reference`, `.op_reach_census`; unit test + integration test for a read or write path; MCP listing budget if it is listed by default; its dashboard control, or a `NOT_IN_DASHBOARD` reason in `server/operations/dashboard.py` |
+| Wire op (new, renamed, removed field) | [adding-an-operation](../../../docs/development/adding-an-operation.md) | `python -m scripts.codegen.sdk_py_gen`, `.sdk_py_client_gen`, `.sdk_ts_gen`, `.sdk_rb_gen`, `.sdk_rust_gen`, `.sdk_rust_gen --fixtures`, `.sdk_go_gen`, `.docs_reference`, `.op_reach_census`; unit test + integration test for a read or write path; MCP listing budget if it is listed by default; its dashboard control, or a `NOT_IN_DASHBOARD` reason in `server/operations/dashboard.py` |
| Table or column | [adding-a-table](../../../docs/development/adding-a-table.md) | migration + `make schema-dump`; RMT row builders; `loom.memory_versions` + its view for a `loom.memory` column; erasure step + census row, or a `NO_MEMORY_CONTENT` / `STEP_ONLY_TABLES` entry with its reason; a new table's row in `docs/architecture/storage-layout.md`, its Today cell when the engine, sort key, partition key or TTL changes, its Erasure cell when its census classification changes, its row removed when the table is dropped (with the dump pending, the row test fails until it lands) |
| Migration | [migrations](../../../docs/development/migrations.md) | next free number on current `origin/main`; additive only; `make schema-dump` on a private ClickHouse (with none at hand, leave `schemas/schema.sql` unchanged and report the dump as pending; never hand-edit it); written values N-1 tolerates ([rolling upgrades](../../../docs/architecture/rolling-upgrades.md)), `make test-mixed-version` |
| Setting | [extending-loom](../../../docs/development/extending-loom.md#add-a-setting) | field in its area's section of `server/settings/catalog.py` (models in `Models`) with a comment on what it controls and its values; `python -m scripts.codegen.settings_reference`, `.settings_schema` and `.settings_example`; read as `settings.`; a rename or removal follows the [settings rule](../../rules/settings.md) |
@@ -20,7 +20,7 @@ Find the row for the change, read its guide before the first edit, and finish it
| Provider | [extending-loom](../../../docs/development/extending-loom.md#add-a-provider) | `make bench-quick` evidence before changing a default (ask first — see `loom-bench`) |
| Code-index language | [adding-language-support](../../../docs/development/adding-language-support.md) | stay outside the extractor stamp; backfill plan in the PR |
| CLI command or flag | [code-generation](../../../docs/development/code-generation.md) | `LOOM_UPDATE_CLI_SNAPSHOT=1` snapshot; `python -m scripts.codegen.docs_reference`; a command the chart's hook Jobs run (`deploy/helm/loom/templates/hooks.yaml`) changes there too |
-| Plugin file (hook, `lib/`, `bin/`, skill, `assets/`, `.mcp.json`, Codex `plugin-defaults.json`, a manifest's listing fields) | [integrations](../../../integrations/claude-code-plugin/README.md) | hook scripts, `lib/`, `bin/`, skills and `assets/`: edit `integrations/claude-code-plugin/`, then `python -m scripts.codegen.agent_plugin_sync`; a manifest, `hooks.json`, `.mcp.json` or `plugin-defaults.json`: edit each plugin's own copy (`plugins` rule); for a behaviour change, bump both plugin manifests to a version no other open PR uses |
+| Plugin file (hook, `lib/`, `bin/`, skill, `assets/`, `.mcp.json`, Codex `plugin-defaults.json`, a manifest's listing fields) | [integrations](../../../integrations/claude-code-plugin/README.md) | hook scripts, `lib/`, `bin/`, skills and `assets/`: edit `integrations/claude-code-plugin/`, then `python -m scripts.codegen.agent_plugin_sync`, and `python -m scripts.codegen.standalone_skills` after a change to the `loom-memory`, `loom-code` or `loom-status` skill, and `python -m scripts.codegen.served_skills` after one to `loom-memory` or `loom-code`; a manifest, `hooks.json`, `.mcp.json` or `plugin-defaults.json`: edit each plugin's own copy (`plugins` rule); for a behaviour change, bump both plugin manifests to a version no other open PR uses |
| Dashboard | [dashboard-design](../../../docs/development/dashboard-design.md), [local-development](../../../docs/development/local-development.md#the-dashboard) | `npm --prefix frontend run test`, `npm --prefix frontend run build`, bundle budget, `make lint` (Biome's accessibility rules) |
| Helm chart | [kubernetes](../../../docs/operations/kubernetes.md) | `helm lint --strict` and `kubeconform` on both overlays; a renamed setting as in the Setting row |
| Docs | [documentation-style](../../../docs/development/documentation-style.md) | regenerate generated pages; never hand-edit them |
diff --git a/.claude/skills/loom-debug/SKILL.md b/.claude/skills/loom-debug/SKILL.md
index 7c8ec01f812..b5ed8bc70d5 100644
--- a/.claude/skills/loom-debug/SKILL.md
+++ b/.claude/skills/loom-debug/SKILL.md
@@ -56,3 +56,13 @@ One or two sentences: the line or statement that is wrong, why it produces every
## Report
The failing cases, the pattern, the cause with `file:line`, the fix, the test that now passes, and the other sites checked.
+
+## Trace a coding-agent attempt
+
+- Join the raw model response to its tool results by call ID. Join Loom retrieval stages and the request ledger by trace run ID, organization and namespace. The ledger captures work after retrieval, including inline lessons, without relying on a remote exporter.
+- For zero Loom calls, check whether the native session received the tool catalog. Distinguish an unavailable tool from a deferred tool the agent never discovered and an available tool the agent chose to skip.
+- Compare the request, the returned evidence and what the next response did. Look for a missing source range, a repeated body or lesson, a stale link, or an avoidable discovery round trip. Distinguish source retrieval from edits, Git and tests.
+- For a repeat read, match the path, line range and source text to an earlier result and check for intervening edits. Check whether the editor needed a local read before the write and whether one line would have sufficed. Measure what the lookup replaced in the subsequent steps.
+- If startup is expensive, compare input and cache usage on the first model request. Use the pinned client and a local capture endpoint to isolate tool schemas, discovery metadata and injected instructions before paying for a rerun. Use provider receipts to measure tokens.
+- If the tool is available but skipped or called with the wrong arguments, compare first choices in disposable native sessions. Hold the task, client, model, other tools and prompt cache setting fixed. Stop after selection and verify that any execution guard is absent from the first request. Measure quality, cost and time in a separate complete run.
+- For a failed fix, compare the submitted patch with the verifier and the evidence the agent received before editing. Replay the narrow failing lookup before rerunning the agent.
diff --git a/.claude/skills/loom-pre-push/SKILL.md b/.claude/skills/loom-pre-push/SKILL.md
index 5fed2fdd378..ebde0bedbb0 100644
--- a/.claude/skills/loom-pre-push/SKILL.md
+++ b/.claude/skills/loom-pre-push/SKILL.md
@@ -35,14 +35,14 @@ Use this map to select local checks and inspect the matching CI jobs. Full integ
| --- | --- |
| `schemas/migrations/` | `make schema-dump` against a private, freshly migrated ClickHouse (`loom-dev-setup`), then `make schema-check`; `git diff schemas/schema.sql` shows only your change |
| a migration, a row builder, an enum value, a wire format, worker leasing | `make test-mixed-version` — builds N-1 and N on one throwaway ClickHouse (needs docker; skips without it, CI fails) |
-| `server/**/api/`, op registry | `.venv/bin/python -m scripts.codegen.` for `sdk_py_gen`, `sdk_py_client_gen`, `sdk_ts_gen`, `docs_reference`, `op_reach_census` (without `--check` each regenerates) |
+| `server/**/api/`, op registry | `.venv/bin/python -m scripts.codegen.` for `sdk_py_gen`, `sdk_py_client_gen`, `sdk_ts_gen`, `sdk_rb_gen`, `sdk_rust_gen`, `sdk_rust_gen --fixtures`, `docs_reference`, `op_reach_census` (without `--check` each regenerates) |
| `server/settings/` | `.venv/bin/python -m scripts.codegen.settings_reference` |
| `server/cli/` | `LOOM_UPDATE_CLI_SNAPSHOT=1 .venv/bin/python -m pytest tests/unit/test_cli_surface_snapshot.py` in a 3.12 virtualenv (a newer Python renders the help differently) — then read the snapshot diff |
| a ClickHouse statement builder | `pytest tests/analyzer -q` against a private, migrated ClickHouse; regenerate with `LOOM_ENV_FILE= .venv/bin/python -m tests.analyzer.corpus --write` on fake providers ([analyzer corpus](../../../docs/development/testing.md#the-analyzer-statement-corpus)) |
| `server/workers/` | `LOOM_UPDATE_WORKER_SNAPSHOT=1 .venv/bin/python -m pytest tests/unit/test_worker_registry_snapshot.py` for an intended change |
| server behaviour | the integration suite against a private server (`loom-dev-setup` §7) |
| auth, write paths, erasure, migrations, the worker supervisor | the per-module branch-coverage floors CI enforces: `make test-unit-cov` (about 30 minutes on two cores, less with more) |
-| `integrations/`, `.claude-plugin/` | `.venv/bin/python -m scripts.codegen.agent_plugin_sync`; `claude plugin validate integrations/claude-code-plugin --profile directory --strict` and `claude plugin validate .` (the plugin and the marketplace listing); `node --test integrations/claude-code-plugin/tests/*.test.mjs`, `node --test integrations/grep-shim/tests/*.test.mjs`, `node --test integrations/cline/tests/*.test.mjs`, `bash integrations/cursor/test.sh`, `PYTHON=.venv/bin/python bash integrations/generic/test.sh`, and CI's loops: `node --check` over every hook, helper, shim and adapter `.mjs`, `sh -n` over `integrations/{claude-code-plugin,codex-plugin}/bin/loom-node` and `integrations/cline/hooks/*`, and `test -x` over `integrations/grep-shim/bin/*` and `integrations/cline/hooks/*` (job `agent-plugins` in `.github/workflows/ci.yml`); with `claude` or `codex` installed, `node integrations/claude-code-plugin/tests/e2e/agent-session.mjs claude --bin --port ` (`codex` needs port 7777 free, the URL its plugin ships; the other platforms run in `.github/workflows/plugin-platforms.yml`); for a behaviour change, both manifests bumped to a version no open PR uses |
+| `integrations/`, `.claude-plugin/` | `.venv/bin/python -m scripts.codegen.agent_plugin_sync` and `.venv/bin/python -m scripts.codegen.standalone_skills`; `.venv/bin/python -m scripts.codegen.served_skills` after a `loom-memory` or `loom-code` skill change; `claude plugin validate integrations/claude-code-plugin --profile directory --strict` and `claude plugin validate .` (the plugin and the marketplace listing); `node --test integrations/claude-code-plugin/tests/*.test.mjs`, `node --test integrations/grep-shim/tests/*.test.mjs`, `node --test integrations/cline/tests/*.test.mjs`, `bash integrations/cursor/test.sh`, `PYTHON=.venv/bin/python bash integrations/generic/test.sh`, and CI's loops: `node --check` over every hook, helper, shim and adapter `.mjs`, `sh -n` over `integrations/{claude-code-plugin,codex-plugin}/bin/loom-node` and `integrations/cline/hooks/*`, and `test -x` over `integrations/grep-shim/bin/*` and `integrations/cline/hooks/*` (job `agent-plugins` in `.github/workflows/ci.yml`); with `claude` or `codex` installed, `node integrations/claude-code-plugin/tests/e2e/agent-session.mjs claude --bin --port ` (`codex` needs port 7777 free, the URL its plugin ships; the other platforms run in `.github/workflows/plugin-platforms.yml`); for a behaviour change, both manifests bumped to a version no open PR uses |
| `.cursor-plugin/` | `.venv/bin/python -m pytest tests/unit/test_cursor_plugin.py tests/unit/test_release_prepare.py tests/unit/test_published_links.py`; its version follows the server's and is never bumped on its own |
| `plugin.json`, `mcp.json` (the Agent Plugins package) | `.venv/bin/python -m pytest tests/unit/test_agent_plugin.py tests/unit/test_release_prepare.py tests/unit/test_published_links.py`; its version follows the server's and is never bumped on its own |
| `frontend/` | `npm --prefix frontend run test && npm --prefix frontend run build && npm --prefix frontend run budget`; the Playwright run CI adds (`npx --prefix frontend playwright install chromium` once (its system libraries, `playwright install-deps`, only on a machine you own), then `E2E_PORT= npm --prefix frontend run e2e`); `make lint` covers the accessibility rules |
diff --git a/.claude/skills/loom-release/SKILL.md b/.claude/skills/loom-release/SKILL.md
index 2a76d537974..e4b236680ea 100644
--- a/.claude/skills/loom-release/SKILL.md
+++ b/.claude/skills/loom-release/SKILL.md
@@ -1,6 +1,6 @@
---
name: loom-release
-description: Cuts and checks a Loom release — the version bump and notes (prepare.py), the release PR, a release candidate and its soak, the final tag and the registry dispatch, then the release checked from outside (one-line installer on amd64 and arm64, SDK installs, anonymous pulls, signatures), rollback and patch releases. Use when asked to release, tag, publish or verify a release.
+description: Cuts and checks a Loom release — version and notes, release PR, candidate soak, tags, registries, outside verification and announcements. Use to release, tag, publish or verify a release, or prepare release notes and announcements. Includes rollback and patch releases.
argument-hint: "[X.Y.Z]"
metadata:
internal: true
@@ -45,6 +45,8 @@ With the tags fetched (`git fetch --tags`) and `gh` signed in:
It refuses a prerelease, an older or an already tagged version before the notes, writes `release-notes.md`, then bumps every file. Read the notes: place every entry under "Unclassified", prune the operator-steps items that name no step and check the rest against their pull requests, and rewrite an entry a user could not act on. Open the pull request (`loom-ship-pr`) titled `Release X.Y.Z`, changelog category "Not for changelog", with the notes as its "Release notes" section. Just before it merges, rebase it and run `prepare.py notes X.Y.Z` again, so the notes name every pull request the tag ships.
+Prepare the user-facing opening and announcement in that same review, following [release notes and announcements](../loom-writing/SKILL.md#release-notes-and-announcements). Keep required upgrade actions and compatibility changes near the top. Check highlights against the final tag's contents after a rebase or candidate fix; a merged change on `main` is not evidence that this release ships it.
+
## 3. Release candidate and soak
```bash
@@ -87,7 +89,7 @@ gh api -X POST "repos/ClickHouse/loom/actions/runs/${dispatch:?no dispatch run f
To publish only the images and the GitHub Release, as for a `clickhouse_image` or `allow_clickhouse_downgrade` dispatch that stands in for a stopped tag run ([when the clickhouse job stops](../../../docs/development/release-process.md#when-the-clickhouse-job-stops)), send the POST with `-f state=rejected -f comment="Registries not published for $tag"`. The run then fails on those jobs, while the images and the GitHub Release stay published.
-The final's bundle keeps the ClickHouse release its candidate soaked with. GitHub generates the Release's notes from the previous final (`prepare.py previous`); paste the release pull request's notes above them (release process, step 6). The tag run ends with `release-check` on the published installer. A failed job: `loom-investigate-ci`; the workflow's own recovery paths (a package first pushed private, a refused ClickHouse downgrade, a failed file signing, and [a failed tag or signature](../../../docs/development/release-process.md#a-failed-tag-or-signature)) are in the release process. A failed file signing is recovered with "Re-run failed jobs" on the run that failed, and when that is the tag run, before any dispatch.
+The final's bundle keeps the ClickHouse release its candidate soaked with. GitHub generates the Release's notes from the previous final (`prepare.py previous`); publish the reviewed opening above them as in §5a. The tag run ends with `release-check` on the published installer. A failed job: `loom-investigate-ci`; the workflow's own recovery paths (a package first pushed private, a refused ClickHouse downgrade, a failed file signing, and [a failed tag or signature](../../../docs/development/release-process.md#a-failed-tag-or-signature)) are in the release process. A failed file signing is recovered with "Re-run failed jobs" on the run that failed, and when that is the tag run, before any dispatch.
## 5. Check it from outside
@@ -111,6 +113,14 @@ npm can take several minutes to list a version it has just accepted ("Your packa
The plugins, in a throwaway `HOME`: `claude plugin marketplace add ClickHouse/loom && claude plugin install loom@loom`, and `codex plugin marketplace add ClickHouse/loom` then install `loom` from it; each lists the plugin version on `main`, and its SessionStart against this server prints no `loom:` line about the server's version. Post what you checked, with the run links, on the release pull request (the owner's go-ahead first).
+## 5a. Publish the reviewed summary and announcement
+
+The current workflow generates the changelog but does not import the release pull request's reviewed notes. Carry that text into the release body programmatically: read the approved notes and the existing body, assemble the reviewed opening above the generated changelog in a temporary file, then use `gh release edit vX.Y.Z -R ClickHouse/loom --notes-file `. Preserve the generated detail and subsequent authorized edits; read back the body and check for omissions or duplicate summaries. This edits notes, not the signed release files. When changing release automation, make this transfer part of publication rather than leaving a manual paste step; reruns must preserve the reviewed text without appending it again.
+
+After §5's checks, prepare one short announcement for the version in an ongoing release-announcements discussion. Find and reuse the existing thread; creating one or posting a comment needs authorization. Reuse authorization already given for that action; drafting a release note alone does not authorize a public post. The comment links the release, relevant docs and upgrade instructions. Read before retrying a post so the same version is not announced twice.
+
+Report availability from this release's evidence: artifact publication, registry results and outside checks. A successful tag run does not prove a later registry dispatch passed, and a skipped check did not pass. State known limits and identify a candidate as a prerelease. Link the [knowledge-factory roadmap](https://github.com/ClickHouse/loom/issues/1232) when relevant; label roadmap items as planned and keep them separate from shipped changes. Read back the posted comment and verify its version and links.
+
## 6. Something is wrong
- **The installer or an image is bad**: move back only the tags the bad release took, checking the previous release's signature before moving each ([a failed tag or signature](../../../docs/development/release-process.md#a-failed-tag-or-signature) has the commands), then ship a patch.
diff --git a/.claude/skills/loom-release/evals/triggers.json b/.claude/skills/loom-release/evals/triggers.json
index 7ffdcd8b8f2..f9bbaff8573 100644
--- a/.claude/skills/loom-release/evals/triggers.json
+++ b/.claude/skills/loom-release/evals/triggers.json
@@ -15,6 +15,14 @@
"query": "we need a patch release of 1.2 with the fix from main",
"should_trigger": true
},
+ {
+ "query": "prepare the next release announcement and carry the reviewed summary into its release page",
+ "should_trigger": true
+ },
+ {
+ "query": "announce the shipped release in our existing subscriber discussion with links to its notes and roadmap",
+ "should_trigger": true
+ },
{
"query": "deploy the new build to the blue/green deployment",
"should_trigger": false
diff --git a/.claude/skills/loom-writing/SKILL.md b/.claude/skills/loom-writing/SKILL.md
index 9e0e91d6db7..67b9c01c019 100644
--- a/.claude/skills/loom-writing/SKILL.md
+++ b/.claude/skills/loom-writing/SKILL.md
@@ -1,6 +1,6 @@
---
name: loom-writing
-description: Plain technical English for commit messages, PR and issue text, review comments and replies, code comments and docs, with a checker for filler words and internal details. Use before writing or posting any of them, or when asked to make text read less generated. Owns wording, not sections.
+description: Plain technical English for commits, PRs, issues, release notes and announcements, review replies, code comments and docs, with a prose checker. Use before writing or posting them, or to make text read less generated. Owns wording; loom-release owns release publication.
metadata:
internal: true
---
@@ -40,6 +40,16 @@ Readers are maintainers who skim dozens of PRs, issues and comments a day. A tex
| addresses, handles (vague) | fixes / rejects / retries / returns |
| holistic, cutting-edge, state-of-the-art, best-in-class | delete |
+## Release notes and announcements
+
+- Open with 3–5 user-visible outcomes for a feature release; a small patch can have fewer. Put required upgrade actions and compatibility changes near the top, then the grouped detail and full changelog.
+- Explain each highlight through the previous behavior, resulting behavior, affected users and limits where relevant. Name the task a user can do or the failure they avoid; a list of merged pull request titles is supporting detail.
+- Give a documented upgrade path and state affected versions, migrations, configuration steps or client requirements when applicable. Do not invent an update command or imply all packages and deployment modes become available together.
+- Keep the subscriber announcement short: version and benefit, selected outcomes, required actions and known limits, then links to the full release, relevant docs and roadmap. Link a demo when one exists.
+- Separate shipped capabilities from planned roadmap work. Support availability and verification claims with this version's publication and check results; an earlier successful release proves nothing about the next one.
+
+Use [loom-release](../loom-release/SKILL.md#5a-publish-the-reviewed-summary-and-announcement) for carrying approved notes into the release page and publishing to the ongoing announcement discussion. Writing or reviewing text grants no permission to post it.
+
## Examples
Commit message:
diff --git a/.claude/skills/loom-writing/evals/triggers.json b/.claude/skills/loom-writing/evals/triggers.json
index 573305b9183..6058af970c5 100644
--- a/.claude/skills/loom-writing/evals/triggers.json
+++ b/.claude/skills/loom-writing/evals/triggers.json
@@ -15,6 +15,14 @@
"query": "check this issue text for jargon before I post it",
"should_trigger": true
},
+ {
+ "query": "rewrite these release highlights around what users can do and put upgrade actions first",
+ "should_trigger": true
+ },
+ {
+ "query": "shorten this release announcement and make shipped features distinct from roadmap plans",
+ "should_trigger": true
+ },
{
"query": "fill in the issue form for this bug",
"should_trigger": false
diff --git a/.clusterfuzzlite/Dockerfile b/.clusterfuzzlite/Dockerfile
new file mode 100644
index 00000000000..b6ada5ea924
--- /dev/null
+++ b/.clusterfuzzlite/Dockerfile
@@ -0,0 +1,11 @@
+FROM gcr.io/oss-fuzz-base/base-builder-python@sha256:21f6fab17ace4dc76e1c56de91ee95d3d03da021df94b41056ba036f6c6f55e9
+
+COPY .clusterfuzzlite/requirements.txt /src/loom-fuzz-requirements.txt
+RUN python3 -m pip install --no-cache-dir --only-binary=:all: --require-hashes --no-deps -r /src/loom-fuzz-requirements.txt
+
+COPY server/__init__.py /src/loom/server/__init__.py
+COPY server/core/__init__.py server/core/embedding_space.py /src/loom/server/core/
+COPY tests/__init__.py /src/loom/tests/__init__.py
+COPY tests/fuzz/ /src/loom/tests/fuzz/
+COPY .clusterfuzzlite/build.sh /src/build.sh
+WORKDIR /src/loom
diff --git a/.clusterfuzzlite/build.sh b/.clusterfuzzlite/build.sh
new file mode 100755
index 00000000000..78d87563920
--- /dev/null
+++ b/.clusterfuzzlite/build.sh
@@ -0,0 +1,18 @@
+#!/bin/bash
+set -euo pipefail
+
+# Only this unmodified standard-library module and the maintained oracle are packaged.
+python3 -m tests.fuzz.embedding_identity_fuzzer --replay tests/fuzz/corpus/embedding_identity
+pyinstaller --distpath "$OUT" --onefile --paths /src/loom \
+ --hidden-import server.core.embedding_space \
+ --hidden-import tests.fuzz.embedding_identity_oracle \
+ --name embedding_identity.pkg tests/fuzz/embedding_identity_fuzzer.py
+cat >"$OUT/embedding_identity" <<'WRAPPER'
+#!/bin/sh
+# LLVMFuzzerTestOneInput
+this_dir=$(dirname "$0")
+exec "$this_dir/embedding_identity.pkg" "$@"
+WRAPPER
+chmod +x "$OUT/embedding_identity"
+zip -j "$OUT/embedding_identity_seed_corpus.zip" tests/fuzz/corpus/embedding_identity/*
+printf '[libfuzzer]\nmax_len = 4096\ntimeout = 5\nrss_limit_mb = 512\n' >"$OUT/embedding_identity.options"
diff --git a/.clusterfuzzlite/project.yaml b/.clusterfuzzlite/project.yaml
new file mode 100644
index 00000000000..d1ad0ae50f5
--- /dev/null
+++ b/.clusterfuzzlite/project.yaml
@@ -0,0 +1 @@
+language: python
diff --git a/.clusterfuzzlite/requirements.txt b/.clusterfuzzlite/requirements.txt
new file mode 100644
index 00000000000..fe4958a1e3d
--- /dev/null
+++ b/.clusterfuzzlite/requirements.txt
@@ -0,0 +1,2 @@
+atheris==3.0.0 \
+ --hash=sha256:8a5c8a781467c187da40fd29139784193e2647058831f837f675d0bb8cbd8746
diff --git a/.cursor-plugin/marketplace.json b/.cursor-plugin/marketplace.json
index 67f4d551ddb..52d6eb654bf 100644
--- a/.cursor-plugin/marketplace.json
+++ b/.cursor-plugin/marketplace.json
@@ -8,7 +8,7 @@
{
"name": "clickhouse-loom",
"source": "./",
- "description": "Shared long-term memory, document search and a code index for Cursor from a self-hosted Loom server, over MCP, with the loom and loom-code skills."
+ "description": "Shared long-term memory, document search and a code index for Cursor from a self-hosted Loom server, over MCP, with the loom, loom-memory, loom-code and loom-status skills."
}
]
}
diff --git a/.cursor-plugin/plugin.json b/.cursor-plugin/plugin.json
index a5e7e69544b..eaacb45acb6 100644
--- a/.cursor-plugin/plugin.json
+++ b/.cursor-plugin/plugin.json
@@ -2,9 +2,9 @@
"name": "clickhouse-loom",
"version": "1.3.0",
"displayName": "ClickHouse Loom",
- "description": "Shared long-term memory, document search and a code index for Cursor from a self-hosted ClickHouse Loom server, over MCP, with the loom and loom-code skills that say when to recall, save and ask the code index.",
+ "description": "Shared long-term memory, document search and a code index for Cursor from a self-hosted ClickHouse Loom server, over MCP, with the loom, loom-memory, loom-code and loom-status skills that say when to recall, save and ask the code index.",
"author": { "name": "ClickHouse" },
- "homepage": "https://clickhouse.github.io/loom/features/integrations/cursor/",
+ "homepage": "https://loom.clickhouse.com/docs/features/integrations/cursor/",
"repository": "https://github.com/ClickHouse/loom",
"license": "Apache-2.0",
"keywords": [
diff --git a/.devcontainer/source/Dockerfile b/.devcontainer/source/Dockerfile
index 1936d1f2a28..ea6e1680bf0 100644
--- a/.devcontainer/source/Dockerfile
+++ b/.devcontainer/source/Dockerfile
@@ -2,7 +2,7 @@ FROM python:3.12-slim@sha256:a6e34c598f2467ed0e9a8d349809fcd8b5c603269512df273a0
COPY --from=ghcr.io/astral-sh/uv:0.12.2@sha256:069a51314a7bb6031777a9273205fe1b0b19e914ef418207d1338b268df641dd /uv /usr/local/bin/uv
ARG CONTRIBUTOR_UID=1000
-RUN apt-get update && apt-get install -y --no-install-recommends build-essential ca-certificates git \
+RUN apt-get update && apt-get install -y --no-install-recommends build-essential ca-certificates git golang-go rustfmt \
&& useradd --create-home --uid "$CONTRIBUTOR_UID" developer \
&& mkdir /venv && chown developer:developer /venv
diff --git a/.devcontainer/source/README.md b/.devcontainer/source/README.md
index 081844eb545..4e2a28dac16 100644
--- a/.devcontainer/source/README.md
+++ b/.devcontainer/source/README.md
@@ -3,7 +3,8 @@
Use a task-specific checkout to investigate a small defect, write its regression and
send a reviewable contribution. This configuration builds a Python source environment
with pinned base and installer images, the repository's dependency lock and a private
-virtualenv. It installs compiler dependencies and runs a focused unit check. It starts
+virtualenv. It installs compiler dependencies, `gofmt` and `rustfmt` for the SDK
+generator checks in `make lint`, and runs a focused unit check. It starts
no Loom service, database or provider, and exposes no port.
Select **Loom source contribution** when reopening the checkout in a development
@@ -26,6 +27,9 @@ and requires no provider account. Fork the repository, push a task branch and ch
under **Actions → contributor lab → Run workflow**. Select one track. A relevant change
to the lab itself runs all tracks in its pull request. Each selected test command has a
two-minute limit; the whole disposable-container job has a fifteen-minute limit.
+The workflow limits the check container to two CPUs, 4 GiB of memory and 256 PIDs,
+with a read-only source mount. Its summary records the selected track, check count
+and result.
| Track | Starting check | Useful contribution |
| ---------------- | ------------------------------------------------------- | ------------------------------------------------------------------------- |
@@ -42,6 +46,20 @@ relevant case with synthetic data and preserve its existing assertions and limit
The workflow reports actual check counts and deletes only its own container. It
uploads no artifact and does not run a benchmark or send a provider request.
+## Investigate beyond a seed
+
+The lab's usability seed checks CLI arguments and help; it does not exercise the
+dashboard. For an SDK error or a dashboard task, use the matching
+[test suite](../../docs/development/testing.md#the-suites). A dashboard report should
+state the task, steps, browser and viewport, and any unexpected keyboard or focus
+behavior.
+
+Memory lifecycle, access isolation and concurrent-writer investigations can need an
+[integration environment](../../docs/development/testing.md#integration-tests) or a
+[concurrent-write regression](../../docs/development/testing.md#concurrent-write-regressions).
+Create that environment with synthetic data and remove the exact resources you
+created when finished. The source lab itself starts no services.
+
## Report what failed
Use the repository's existing [issue forms](../../.github/ISSUE_TEMPLATE) for a public
@@ -50,8 +68,18 @@ track, exact command, synthetic reproduction, expected behavior and observed res
Check open work and preserve an existing contributor's claim before starting a fix.
Follow [CONTRIBUTING.md](../../CONTRIBUTING.md) for the patch and required review/CI.
+For a timing or resource regression, use the
+[performance form](../../.github/ISSUE_TEMPLATE/50_performance-issue.yaml). Record the
+workload and input sizes, concurrency, repetition count, CPU and memory limits, and
+the baseline and tested revisions. Compare the same workload and settings, preserve
+existing deadlines and bounds, and distinguish a failed check from a measured
+regression. Review and redact diagnostics before posting them.
+
Security-sensitive findings use [SECURITY.md](../../SECURITY.md). Keep credentials,
personal data and exploit inputs out of public issues. Run experiments only on the
disposable synthetic checkout; deployed services and third-party systems are outside
this lab. Contributions do not require a star, paid tool, mentoring arrangement or
provider account.
+
+Public reports, regression tests and merged patches record contributions. Ask a
+reporter before quoting their report or naming them in a separate write-up.
diff --git a/.env.example b/.env.example
index 28ed3b2efe5..721692e4b59 100644
--- a/.env.example
+++ b/.env.example
@@ -204,8 +204,6 @@ OPENAI_API_KEY=
# LOOM_CODE_GITHUB_TOKEN= # private clones and PR history; empty = public clones, no PR sync
# The stock single-node stack enables the non-LLM indexing workers so repositories
# added in the dashboard make progress without a second setup step.
-# Per-merge fast tier (tree-sitter + embeddings).
-LOOM_CODE_INGEST_ENABLED=true
# LOOM_CODE_PR_HISTORY_ENABLED=true # merged-PR sync (needs the GitHub token)
# Re-embed code rows whose embedding failed.
LOOM_CODE_EMBED_RECOVERY_ENABLED=true
diff --git a/.github/ISSUE_TEMPLATE/10_question.yaml b/.github/ISSUE_TEMPLATE/10_question.yaml
index 51d4dbd0be0..1ef9b84d7bf 100644
--- a/.github/ISSUE_TEMPLATE/10_question.yaml
+++ b/.github/ISSUE_TEMPLATE/10_question.yaml
@@ -5,14 +5,15 @@ body:
- type: markdown
attributes:
value: |
- > Check the [documentation](https://clickhouse.github.io/loom/) first: the [FAQ](https://github.com/ClickHouse/loom/blob/main/docs/faq.md) and [troubleshooting](https://github.com/ClickHouse/loom/blob/main/docs/operations/troubleshooting.md) answer the common ones.
+ > Check the [documentation](https://loom.clickhouse.com/docs/) first: the [FAQ](https://github.com/ClickHouse/loom/blob/main/docs/faq.md) and [troubleshooting](https://github.com/ClickHouse/loom/blob/main/docs/operations/troubleshooting.md) answer the common ones.
> Search [existing issues](https://github.com/ClickHouse/loom/issues?q=is%3Aissue) before asking.
- - type: textarea
+ - type: input
+ id: company
attributes:
- label: Company or project name
- description: Optional. Who you are building with Loom helps us weigh the answer.
+ label: Company
+ description: Your company or organization. Enter "Independent" if filing personally.
validations:
- required: false
+ required: true
- type: textarea
id: question
attributes:
diff --git a/.github/ISSUE_TEMPLATE/20_feature-request.yaml b/.github/ISSUE_TEMPLATE/20_feature-request.yaml
index 3e94ec9566f..4dfcf9210f1 100644
--- a/.github/ISSUE_TEMPLATE/20_feature-request.yaml
+++ b/.github/ISSUE_TEMPLATE/20_feature-request.yaml
@@ -6,12 +6,13 @@ body:
attributes:
value: |
> Search [existing issues](https://github.com/ClickHouse/loom/issues?q=is%3Aissue) first. A change to storage, the identity model, auth or a new external dependency is discussed here before any pull request.
- - type: textarea
+ - type: input
+ id: company
attributes:
- label: Company or project name
- description: Optional. Put your company name or project description here.
+ label: Company
+ description: Your company or organization. Enter "Independent" if filing personally.
validations:
- required: false
+ required: true
- type: dropdown
id: component
attributes:
@@ -25,7 +26,12 @@ body:
- Namespaces, tokens and grants
- MCP server
- Agent plugin (Claude Code, Codex, Cursor)
+ - .NET SDK
+ - Go SDK
+ - Java SDK
- Python SDK
+ - Ruby SDK
+ - Rust SDK
- TypeScript SDK
- CLI
- Dashboard
diff --git a/.github/ISSUE_TEMPLATE/30_bug-report.yaml b/.github/ISSUE_TEMPLATE/30_bug-report.yaml
index f877cd31d96..dc20f16b312 100644
--- a/.github/ISSUE_TEMPLATE/30_bug-report.yaml
+++ b/.github/ISSUE_TEMPLATE/30_bug-report.yaml
@@ -8,12 +8,13 @@ body:
> Search [existing issues](https://github.com/ClickHouse/loom/issues?q=is%3Aissue) first; it may already be tracked or fixed on `main`.
> **Never paste tokens, API keys, JWTs, passwords or customer data.** `loom report` output is safe to paste: it records only whether each secret is set.
> A security issue goes to security@clickhouse.com, not here ([SECURITY.md](https://github.com/ClickHouse/loom/blob/main/SECURITY.md)).
- - type: textarea
+ - type: input
+ id: company
attributes:
- label: Company or project name
- description: Optional. Put your company name or project description here.
+ label: Company
+ description: Your company or organization. Enter "Independent" if filing personally.
validations:
- required: false
+ required: true
- type: dropdown
id: component
attributes:
@@ -27,7 +28,12 @@ body:
- Namespaces, tokens and grants
- MCP server
- Agent plugin (Claude Code, Codex, Cursor)
+ - .NET SDK
+ - Go SDK
+ - Java SDK
- Python SDK
+ - Ruby SDK
+ - Rust SDK
- TypeScript SDK
- CLI
- Dashboard
diff --git a/.github/ISSUE_TEMPLATE/40_recall-quality.yaml b/.github/ISSUE_TEMPLATE/40_recall-quality.yaml
index 8dcc87f2f3d..9b9a6c0e6d1 100644
--- a/.github/ISSUE_TEMPLATE/40_recall-quality.yaml
+++ b/.github/ISSUE_TEMPLATE/40_recall-quality.yaml
@@ -8,12 +8,13 @@ body:
> An error or crash is a bug report. This form is for a result that came back but was wrong.
> **Never paste tokens, API keys, JWTs, passwords or customer data.** `loom report` output is safe to paste: it records only whether each secret is set.
> A security issue goes to security@clickhouse.com, not here ([SECURITY.md](https://github.com/ClickHouse/loom/blob/main/SECURITY.md)).
- - type: textarea
+ - type: input
+ id: company
attributes:
- label: Company or project name
- description: Optional. Put your company name or project description here.
+ label: Company
+ description: Your company or organization. Enter "Independent" if filing personally.
validations:
- required: false
+ required: true
- type: textarea
id: query
attributes:
diff --git a/.github/ISSUE_TEMPLATE/50_performance-issue.yaml b/.github/ISSUE_TEMPLATE/50_performance-issue.yaml
index f7c4368ffe0..be4d3374f2e 100644
--- a/.github/ISSUE_TEMPLATE/50_performance-issue.yaml
+++ b/.github/ISSUE_TEMPLATE/50_performance-issue.yaml
@@ -8,12 +8,13 @@ body:
> [Performance tuning](https://github.com/ClickHouse/loom/blob/main/docs/guides/performance-tuning.md) covers the settings that matter most.
> **Never paste tokens, API keys, JWTs, passwords or customer data.** `loom report` output is safe to paste: it records only whether each secret is set.
> A security issue goes to security@clickhouse.com, not here ([SECURITY.md](https://github.com/ClickHouse/loom/blob/main/SECURITY.md)).
- - type: textarea
+ - type: input
+ id: company
attributes:
- label: Company or project name
- description: Optional. Put your company name or project description here.
+ label: Company
+ description: Your company or organization. Enter "Independent" if filing personally.
validations:
- required: false
+ required: true
- type: dropdown
id: component
attributes:
@@ -27,7 +28,12 @@ body:
- Namespaces, tokens and grants
- MCP server
- Agent plugin (Claude Code, Codex, Cursor)
+ - .NET SDK
+ - Go SDK
+ - Java SDK
- Python SDK
+ - Ruby SDK
+ - Rust SDK
- TypeScript SDK
- CLI
- Dashboard
diff --git a/.github/ISSUE_TEMPLATE/60_upgrade-compatibility.yaml b/.github/ISSUE_TEMPLATE/60_upgrade-compatibility.yaml
index ebc34cb5e3f..5f0b936c2f1 100644
--- a/.github/ISSUE_TEMPLATE/60_upgrade-compatibility.yaml
+++ b/.github/ISSUE_TEMPLATE/60_upgrade-compatibility.yaml
@@ -8,12 +8,13 @@ body:
> Check the release notes of every version you skipped, and [upgrades](https://github.com/ClickHouse/loom/blob/main/docs/operations/upgrades.md), first.
> **Never paste tokens, API keys, JWTs, passwords or customer data.** `loom report` output is safe to paste: it records only whether each secret is set.
> A security issue goes to security@clickhouse.com, not here ([SECURITY.md](https://github.com/ClickHouse/loom/blob/main/SECURITY.md)).
- - type: textarea
+ - type: input
+ id: company
attributes:
- label: Company or project name
- description: Optional. Put your company name or project description here.
+ label: Company
+ description: Your company or organization. Enter "Independent" if filing personally.
validations:
- required: false
+ required: true
- type: textarea
id: what-broke
attributes:
diff --git a/.github/ISSUE_TEMPLATE/70_installation-issue.yaml b/.github/ISSUE_TEMPLATE/70_installation-issue.yaml
index d63f604cacb..ddced46ec43 100644
--- a/.github/ISSUE_TEMPLATE/70_installation-issue.yaml
+++ b/.github/ISSUE_TEMPLATE/70_installation-issue.yaml
@@ -8,12 +8,13 @@ body:
> Run `loom doctor` first: it prints each problem it finds with its fix. [Troubleshooting](https://github.com/ClickHouse/loom/blob/main/docs/operations/troubleshooting.md) covers the common ones.
> **Never paste tokens, API keys, JWTs, passwords or customer data.** `loom report` output is safe to paste: it records only whether each secret is set.
> A security issue goes to security@clickhouse.com, not here ([SECURITY.md](https://github.com/ClickHouse/loom/blob/main/SECURITY.md)).
- - type: textarea
+ - type: input
+ id: company
attributes:
- label: Company or project name
- description: Optional. Put your company name or project description here.
+ label: Company
+ description: Your company or organization. Enter "Independent" if filing personally.
validations:
- required: false
+ required: true
- type: dropdown
id: install-path
attributes:
diff --git a/.github/ISSUE_TEMPLATE/80_documentation-issue.yaml b/.github/ISSUE_TEMPLATE/80_documentation-issue.yaml
index 986983706be..49359a331cc 100644
--- a/.github/ISSUE_TEMPLATE/80_documentation-issue.yaml
+++ b/.github/ISSUE_TEMPLATE/80_documentation-issue.yaml
@@ -6,11 +6,18 @@ body:
attributes:
value: |
> Thanks for helping improve the documentation.
+ - type: input
+ id: company
+ attributes:
+ label: Company
+ description: Your company or organization. Enter "Independent" if filing personally.
+ validations:
+ required: true
- type: input
id: page
attributes:
label: Documentation page
- description: A link to the page, e.g. https://clickhouse.github.io/loom/getting-started/quickstart/
+ description: A link to the page, e.g. https://loom.clickhouse.com/docs/getting-started/quickstart/
validations:
required: true
- type: textarea
diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml
index d57ba4e64ab..f196eecfbff 100644
--- a/.github/ISSUE_TEMPLATE/config.yml
+++ b/.github/ISSUE_TEMPLATE/config.yml
@@ -5,5 +5,5 @@ contact_links:
url: https://github.com/ClickHouse/loom/security/policy
about: Do not open an issue. Email security@clickhouse.com as SECURITY.md describes.
- name: Documentation
- url: https://clickhouse.github.io/loom/
+ url: https://loom.clickhouse.com/docs/
about: Guides, operations and the generated reference for every op and setting.
diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md
index 4ad6d44bd72..eb721db8f3a 100644
--- a/.github/PULL_REQUEST_TEMPLATE.md
+++ b/.github/PULL_REQUEST_TEMPLATE.md
@@ -53,10 +53,11 @@ the change goes here with the command that reproduces it.
### Checklist
- [ ] Local format, lint, type checks and focused tests pass. The full `make test-unit` and applicable integration results are reported by CI; a full local run is not required before pushing.
-- [ ] Generated files are regenerated in this PR, not by hand: the SDK op tables, `docs/reference/configuration.md` and the `docs/reference/` tables (`python scripts/codegen/docs_reference.py`), the reach manifest, `schemas/schema.sql` (`make schema-dump`) and the Codex plugin copies (`python3 scripts/codegen/agent_plugin_sync.py`).
+- [ ] Generated files are regenerated in this PR, not by hand: the SDK op tables, `docs/reference/configuration.md` and the `docs/reference/` tables (`python scripts/codegen/docs_reference.py`), the reach manifest, `schemas/schema.sql` (`make schema-dump`), the Codex plugin copies (`python3 scripts/codegen/agent_plugin_sync.py`) and the standalone skill bundles (`python3 scripts/codegen/standalone_skills.py`).
- [ ] A new migration is additive and numbered after the latest on `main`; no merged migration is edited.
- [ ] A behaviour change to any file a plugin ships (`hooks/`, `lib/`, `bin/`, `skills/`, `.mcp.json`, the Codex `plugin-defaults.json`) bumps both plugin manifests' version, and no other open PR uses that version.
- [ ] The frontend builds (`npm --prefix frontend run build`) and its tests pass, if `frontend/` changed.
- [ ] Docs under `docs/` describe the system as it now is, and this description names any operator steps and wire changes.
- [ ] Repository text has no dates, people, host names, internal namespaces, ticket or decision numbers; the history goes in this description (`tests/unit/test_public_copy.py`).
- [ ] Commits are signed off (`git commit -s`), as CONTRIBUTING.md asks.
+- [ ] I signed the Contributor License Agreement (CLA) if CLA assistant requested a signature.
diff --git a/.github/actions/patch-coverage/action.yml b/.github/actions/patch-coverage/action.yml
new file mode 100644
index 00000000000..c49aa4894e8
--- /dev/null
+++ b/.github/actions/patch-coverage/action.yml
@@ -0,0 +1,44 @@
+name: Changed-line coverage
+description: Report coverage of lines changed by a pull request
+inputs:
+ component:
+ description: Component name for the job summary
+ required: true
+ report:
+ description: Absolute or repository-relative coverage report path
+ required: true
+ working-directory:
+ description: Directory the tests ran in
+ default: "."
+ source-root:
+ description: Source directory for reports with package-relative paths
+ default: "."
+runs:
+ using: composite
+ steps:
+ - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
+ with:
+ version: "0.12.19"
+ enable-cache: false
+ - shell: bash
+ env:
+ COMPONENT: ${{ inputs.component }}
+ COVERAGE_REPORT: ${{ inputs.report }}
+ TEST_DIRECTORY: ${{ inputs.working-directory }}
+ SOURCE_ROOT: ${{ inputs.source-root }}
+ run: |
+ cd "$GITHUB_WORKSPACE/$TEST_DIRECTORY"
+ # The tested pull request merge commit's first parent is the tested base.
+ base=$(git rev-parse --verify HEAD^1)
+ report="$COVERAGE_REPORT"
+ [[ "$report" = /* ]] || report="$GITHUB_WORKSPACE/$report"
+ if [[ ! -s "$report" ]]; then
+ echo "Coverage report is missing or empty: $report" >&2
+ exit 1
+ fi
+ summary="$RUNNER_TEMP/patch-coverage.md"
+ uvx --python 3.12 --from diff-cover==11.0.4 diff-cover \
+ "$report" --compare-branch "$base" --src-roots "$SOURCE_ROOT" \
+ --format "markdown:$summary"
+ printf '## %s changed-line coverage\n\n' "$COMPONENT" >> "$GITHUB_STEP_SUMMARY"
+ cat "$summary" >> "$GITHUB_STEP_SUMMARY"
diff --git a/.github/dependabot.yml b/.github/dependabot.yml
index ee1b9d543de..6e4ec75e1ec 100644
--- a/.github/dependabot.yml
+++ b/.github/dependabot.yml
@@ -1,12 +1,47 @@
-# Keeps the workflows' commit-pinned actions current. Actions only: the
-# Python and npm dependencies move through their lockfiles by hand.
version: 2
updates:
- package-ecosystem: github-actions
directory: /
schedule:
interval: weekly
+ cooldown:
+ default-days: 7
open-pull-requests-limit: 2
groups:
actions:
patterns: ["*"]
+
+ - package-ecosystem: uv
+ directories: [/, /extractor]
+ schedule:
+ interval: weekly
+ cooldown:
+ default-days: 7
+ open-pull-requests-limit: 1
+ versioning-strategy: increase-if-necessary
+ ignore:
+ - dependency-name: "*"
+ update-types: [version-update:semver-major]
+ # These pins move with the lint and type-check baselines.
+ - dependency-name: mypy
+ update-types: [version-update:semver-minor, version-update:semver-patch]
+ - dependency-name: ruff
+ update-types: [version-update:semver-minor, version-update:semver-patch]
+ groups:
+ python-dependencies:
+ patterns: ["*"]
+
+ - package-ecosystem: npm
+ directories: [/docs, /frontend, /sdk/typescript]
+ schedule:
+ interval: weekly
+ cooldown:
+ default-days: 7
+ open-pull-requests-limit: 1
+ versioning-strategy: increase-if-necessary
+ ignore:
+ - dependency-name: "*"
+ update-types: [version-update:semver-major]
+ groups:
+ npm-dependencies:
+ patterns: ["*"]
diff --git a/.github/scripts/rust-dependency-snapshot.py b/.github/scripts/rust-dependency-snapshot.py
new file mode 100644
index 00000000000..a50184bbf33
--- /dev/null
+++ b/.github/scripts/rust-dependency-snapshot.py
@@ -0,0 +1,92 @@
+"""Convert the resolved SDK crate graph to a GitHub dependency snapshot."""
+
+import json
+import os
+import sys
+from datetime import UTC, datetime
+from pathlib import Path
+
+MANIFEST = "sdk/rust/Cargo.toml"
+CRATES_IO = "registry+https://github.com/rust-lang/crates.io-index"
+MAX_SNAPSHOT_BYTES = 96 * 1024
+
+
+def snapshot_output(snapshot):
+ payload = json.dumps(snapshot, ensure_ascii=True, separators=(",", ":"), sort_keys=True)
+ # Leave room below both the job-output and single environment-value limits.
+ if len(payload) > MAX_SNAPSHOT_BYTES:
+ raise ValueError("Dependency snapshot exceeds the job-output size limit")
+ return "snapshot=" + payload + "\n"
+
+
+def runtime_dependencies(root, nodes):
+ pending = [root]
+ reached = {root}
+ while pending:
+ for dep in nodes[pending.pop()]:
+ if dep["pkg"] not in reached and any(
+ kind["kind"] != "dev" for kind in dep["dep_kinds"]
+ ):
+ reached.add(dep["pkg"])
+ pending.append(dep["pkg"])
+ return reached
+
+
+def resolved_dependencies(metadata):
+ root = metadata["resolve"]["root"]
+ nodes = {node["id"]: node["deps"] for node in metadata["resolve"]["nodes"]}
+ runtime = runtime_dependencies(root, nodes)
+ direct = {dep["pkg"] for dep in nodes[root]}
+ purls = {}
+ for package in metadata["packages"]:
+ package_id = package["id"]
+ if package_id == root:
+ continue
+ if package["source"] != CRATES_IO:
+ raise ValueError(f"Unexpected package source for {package['name']}")
+ purls[package_id] = f"pkg:cargo/{package['name']}@{package['version']}"
+
+ if purls.keys() != nodes.keys() - {root} or not purls.keys() - direct:
+ raise ValueError("The resolved SDK graph has missing nodes or no transitive dependencies")
+ return {
+ purl: {
+ "package_url": purl,
+ "relationship": "direct" if package_id in direct else "indirect",
+ "scope": "runtime" if package_id in runtime else "development",
+ "dependencies": sorted({purls[dep["pkg"]] for dep in nodes[package_id]}),
+ }
+ for package_id, purl in purls.items()
+ }
+
+
+def main():
+ metadata_path = Path(sys.argv[1])
+ resolved = resolved_dependencies(json.loads(metadata_path.read_text()))
+ snapshot = {
+ "version": 0,
+ "sha": os.environ["GITHUB_SHA"],
+ "ref": os.environ["GITHUB_REF"],
+ "job": {"id": os.environ["GITHUB_RUN_ID"], "correlator": "loom-rust-sdk"},
+ "detector": {
+ "name": "cargo metadata",
+ "version": os.environ["CARGO_TOOLCHAIN"],
+ "url": "https://doc.rust-lang.org/cargo/commands/cargo-metadata.html",
+ },
+ "scanned": datetime.now(UTC).isoformat(timespec="seconds"),
+ "manifests": {
+ MANIFEST: {
+ "name": MANIFEST,
+ "file": {"source_location": MANIFEST},
+ "resolved": resolved,
+ },
+ },
+ }
+ output = snapshot_output(snapshot)
+ with Path(os.environ["GITHUB_OUTPUT"]).open("a") as stream:
+ stream.write(output)
+ indirect = sum(dep["relationship"] == "indirect" for dep in resolved.values())
+ print(f"Cargo resolved {len(resolved)} packages, including {indirect} transitive packages.")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/.github/scripts/test_rust_dependency_snapshot.py b/.github/scripts/test_rust_dependency_snapshot.py
new file mode 100644
index 00000000000..26d8c7a223c
--- /dev/null
+++ b/.github/scripts/test_rust_dependency_snapshot.py
@@ -0,0 +1,141 @@
+"""Check graph scopes and bounded transport between the workflow jobs."""
+
+import contextlib
+import copy
+import io
+import json
+import os
+import runpy
+import tempfile
+import unittest
+from pathlib import Path
+from unittest.mock import patch
+
+CONVERTER_PATH = Path(__file__).with_name("rust-dependency-snapshot.py")
+CONVERTER = runpy.run_path(str(CONVERTER_PATH))
+LIMIT = CONVERTER["MAX_SNAPSHOT_BYTES"]
+
+
+def metadata():
+ edges = {"root": [("runtime", None), ("dev", "dev")], "runtime": [("leaf", None)]}
+ names = ["root", "runtime", "leaf", "dev"]
+ return {
+ "packages": [
+ {"id": name, "name": name, "version": "1.0.0", "source": CONVERTER["CRATES_IO"]}
+ for name in names
+ ],
+ "resolve": {
+ "root": "root",
+ "nodes": [
+ {
+ "id": name,
+ "deps": [
+ {"pkg": target, "dep_kinds": [{"kind": kind}]}
+ for target, kind in edges.get(name, [])
+ ],
+ }
+ for name in names
+ ],
+ },
+ }
+
+
+def consume(payload, directory):
+ workflow = Path(".github/workflows/rust-dependency-graph.yml").read_text()
+ start = workflow.index(" import json\n")
+ end = workflow.index(" PYTHON", start)
+ code = "\n".join(line[10:] for line in workflow[start:end].splitlines()) + "\n"
+ script = Path(directory, "consumer.py")
+ script.write_text(code)
+ env = {
+ "SNAPSHOT_JSON": payload,
+ "GITHUB_SHA": "a" * 40,
+ "GITHUB_RUN_ID": "123",
+ "RUNNER_TEMP": directory,
+ }
+ with patch.dict(os.environ, env):
+ runpy.run_path(str(script))
+
+
+class SnapshotTests(unittest.TestCase):
+ def test_runtime_closure_and_development_scope(self):
+ resolved = CONVERTER["resolved_dependencies"](metadata())
+ runtime = resolved["pkg:cargo/runtime@1.0.0"]
+ self.assertEqual((runtime["relationship"], runtime["scope"]), ("direct", "runtime"))
+ leaf = resolved["pkg:cargo/leaf@1.0.0"]
+ self.assertEqual((leaf["relationship"], leaf["scope"]), ("indirect", "runtime"))
+ self.assertEqual(resolved["pkg:cargo/dev@1.0.0"]["scope"], "development")
+ self.assertEqual(runtime["dependencies"], ["pkg:cargo/leaf@1.0.0"])
+
+ def test_rejects_an_unexpected_registry(self):
+ graph = metadata()
+ graph["packages"][1]["source"] = "git+https://example.com/unexpected"
+ with self.assertRaises(ValueError):
+ CONVERTER["resolved_dependencies"](graph)
+
+ def test_rejects_missing_graph_nodes(self):
+ graph = metadata()
+ graph["resolve"]["nodes"].pop()
+ with self.assertRaises(ValueError):
+ CONVERTER["resolved_dependencies"](graph)
+
+ def test_size_bound_accepts_the_limit_and_rejects_one_more_byte(self):
+ payload = {"value": ""}
+ empty_size = len(CONVERTER["snapshot_output"](payload)) - len("snapshot=\n")
+ payload["value"] = "a" * (LIMIT - empty_size)
+ self.assertEqual(len(CONVERTER["snapshot_output"](payload)), LIMIT + len("snapshot=\n"))
+ payload["value"] += "a"
+ with self.assertRaises(ValueError):
+ CONVERTER["snapshot_output"](payload)
+
+ def test_output_is_one_ascii_line_and_preserves_data(self):
+ snapshot = {"value": "\nother=1\r$(false) ' \" \u2603"}
+ output = CONVERTER["snapshot_output"](snapshot)
+ self.assertTrue(output.isascii())
+ self.assertEqual(len(output.splitlines()), 1)
+ self.assertEqual(json.loads(output.removeprefix("snapshot=")), snapshot)
+
+ def test_producer_to_actual_consumer(self):
+ with tempfile.TemporaryDirectory() as directory:
+ source = Path(directory, "metadata.json")
+ output = Path(directory, "output")
+ source.write_text(json.dumps(metadata()))
+ output.write_text("earlier=1\n")
+ env = {
+ "GITHUB_OUTPUT": str(output),
+ "GITHUB_SHA": "a" * 40,
+ "GITHUB_REF": "refs/heads/main",
+ "GITHUB_RUN_ID": "123",
+ "CARGO_TOOLCHAIN": "1.84.1",
+ }
+ with patch.dict(os.environ, env), patch("sys.argv", [str(CONVERTER_PATH), str(source)]):
+ with contextlib.redirect_stdout(io.StringIO()):
+ CONVERTER["main"]()
+ lines = output.read_text().splitlines()
+ self.assertEqual(lines[0], "earlier=1")
+ payload = lines[1].removeprefix("snapshot=")
+ consume(payload, directory)
+ self.assertEqual(
+ json.loads(Path(directory, "rust-snapshot.json").read_text()), json.loads(payload)
+ )
+
+ def test_consumer_rejects_another_head_ref_or_run(self):
+ snapshot = {"sha": "a" * 40, "ref": "refs/heads/main", "job": {"id": "123"}}
+ for field in ["sha", "ref", "job"]:
+ invalid = copy.deepcopy(snapshot)
+ invalid[field] = {"id": "other"} if field == "job" else "other"
+ with self.subTest(field=field), tempfile.TemporaryDirectory() as directory:
+ with self.assertRaises(ValueError):
+ consume(json.dumps(invalid), directory)
+ self.assertFalse(Path(directory, "rust-snapshot.json").exists())
+
+ def test_consumer_rejects_empty_oversized_or_non_ascii_payload(self):
+ for payload in ["", "a" * (LIMIT + 1), "\u2603"]:
+ with self.subTest(length=len(payload)), tempfile.TemporaryDirectory() as directory:
+ with self.assertRaises(ValueError):
+ consume(payload, directory)
+ self.assertFalse(Path(directory, "rust-snapshot.json").exists())
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/.github/scripts/workflow_audit_issues.py b/.github/scripts/workflow_audit_issues.py
new file mode 100644
index 00000000000..49dd0f5a84b
--- /dev/null
+++ b/.github/scripts/workflow_audit_issues.py
@@ -0,0 +1,346 @@
+"""Publish non-sensitive workflow maintenance findings from trusted hosted runs."""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import http.client
+import json
+import os
+import re
+import time
+from datetime import datetime
+from pathlib import Path, PurePosixPath
+from typing import Any
+
+_REPO = "ClickHouse/loom"
+_ROOT = "/repos/" + _REPO + "/issues"
+_MAIN_REF = "/repos/" + _REPO + "/git/ref/heads/main"
+_BOT = "github-actions[bot]"
+# These rules describe maintainability, not vulnerability or exploit claims.
+_PUBLIC_RULES = {
+ "anonymous-definition": "Name workflow and job definitions so audit locations are clear.",
+ "superfluous-actions": "Review the action dependency and use a runner tool when equivalent.",
+ "undocumented-permissions": "Document why each explicit workflow permission is needed.",
+}
+_MARKER = re.compile(r"")
+_STATE = re.compile(r"")
+_TITLE = re.compile(r"\[workflow-audit:([a-f0-9]{64})\]$")
+
+
+def fingerprint(rule: str, path: str) -> str:
+ return hashlib.sha256(("zizmor\0" + rule + "\0" + path).encode()).hexdigest()
+
+
+def public_findings(findings: object) -> dict[str, dict[str, Any]]:
+ if not isinstance(findings, list) or len(findings) > 1000:
+ raise ValueError("Expected at most 1000 workflow findings")
+ groups: dict[str, dict[str, Any]] = {}
+ for finding in findings:
+ rule = finding["ident"]
+ if rule not in _PUBLIC_RULES:
+ continue # Complete security findings stay in the hosted audit and Security tab.
+ primary = [item for item in finding["locations"] if item["symbolic"]["kind"] == "Primary"]
+ if len(primary) != 1:
+ raise ValueError("Expected exactly one primary finding location")
+ path = primary[0]["symbolic"]["key"]["Local"]["verbatim_path"].removeprefix("./")
+ parts = PurePosixPath(path).parts
+ if (
+ len(path) > 240
+ or not re.fullmatch(r"\.github/[A-Za-z0-9_./-]+\.ya?ml", path)
+ or ".." in parts
+ ):
+ raise ValueError("Invalid workflow finding path")
+ severity = finding["determinations"]["severity"]
+ confidence = finding["determinations"]["confidence"]
+ if severity not in {"Informational", "Low", "Medium", "High", "Critical", "Unknown"}:
+ raise ValueError("Unknown finding severity")
+ if confidence not in {"Low", "Medium", "High", "Unknown"}:
+ raise ValueError("Unknown finding confidence")
+ # A newly severe determination is routed to security review, never a public issue.
+ if severity not in {"Informational", "Low"}:
+ continue
+ key = fingerprint(rule, path)
+ group = groups.setdefault(key, {"rule": rule, "path": path, "observations": []})
+ group["observations"].append((severity, confidence))
+ for group in groups.values():
+ group["observations"].sort()
+ return groups
+
+
+def state_hash(group: dict[str, Any] | None) -> str:
+ # Exclude commit/run/line positions, so a new run or shifted source cannot spam updates.
+ return hashlib.sha256(json.dumps(group, sort_keys=True).encode()).hexdigest()
+
+
+def status_body(key: str, group: dict[str, Any] | None, run_url: str) -> str:
+ state = state_hash(group)
+ if group is None:
+ message = "This maintenance finding is absent from the current eligible audit results."
+ else:
+ message = (
+ f"The current audit reports {len(group['observations'])} maintenance observation(s) "
+ f"for `{group['rule']}` in `{group['path']}`.\n\n" + _PUBLIC_RULES[group["rule"]]
+ )
+ return (
+ f"\n"
+ f"\n\n"
+ "### Company or project name\n\nClickHouse\n\n"
+ f"{message}\n\n"
+ "This is an automated maintenance task, not a confirmed vulnerability. "
+ "Review the source before changing behavior. Security-sensitive findings follow "
+ "[SECURITY.md](https://github.com/ClickHouse/loom/blob/main/SECURITY.md).\n\n"
+ f"[Hosted audit result]({run_url}). "
+ "Automation preserves issue bodies, titles and closed decisions."
+ )
+
+
+def snapshot_user(author: dict[str, Any] | None) -> dict[str, Any]:
+ user = dict(author or {})
+ if user.get("__typename") == "Bot" and user.get("login") == "github-actions":
+ user["login"] = _BOT
+ return user
+
+
+class ResponseTooLarge(RuntimeError):
+ """The requested page exceeded the API response limit."""
+
+
+class GitHub:
+ """Fixed-host client with bounded calls, responses and wall time; no redirects or retries."""
+
+ def __init__(self, token: str, expected_sha: str | None = None) -> None:
+ self.token = token
+ self.expected_sha = expected_sha
+ self.calls = 0
+ self.deadline = time.monotonic() + 180
+
+ def request(self, method: str, path: str, payload: dict[str, Any] | None = None) -> Any:
+ if self.calls >= 40 or time.monotonic() >= self.deadline:
+ raise RuntimeError("Workflow audit API budget exhausted")
+ if not (
+ (path.startswith(_ROOT) and method in {"GET", "POST"})
+ or (path == "/graphql" and method == "POST")
+ or (path == _MAIN_REF and method == "GET")
+ ):
+ raise ValueError("Unapproved audit API request")
+ if method == "POST" and path.startswith(_ROOT) and self.expected_sha is not None:
+ if self.request("GET", _MAIN_REF)["object"]["sha"] != self.expected_sha:
+ raise RuntimeError("Default branch advanced before workflow issue publication")
+ if self.calls >= 40 or time.monotonic() >= self.deadline:
+ raise RuntimeError("Workflow audit API budget exhausted")
+ self.calls += 1
+ connection = http.client.HTTPSConnection("api.github.com", timeout=10)
+ headers = {
+ "Authorization": "Bearer " + self.token,
+ "Accept": "application/vnd.github+json",
+ "User-Agent": "loom-workflow-audit",
+ "X-GitHub-Api-Version": "2026-03-10",
+ }
+ body = None if payload is None else json.dumps(payload).encode()
+ if body is not None:
+ headers["Content-Type"] = "application/json"
+ try:
+ connection.request(method, path, body=body, headers=headers)
+ response = connection.getresponse()
+ data = response.read(2 * 1024 * 1024 + 1)
+ if response.status != (200 if method == "GET" or path == "/graphql" else 201):
+ raise RuntimeError(f"Workflow audit API returned HTTP {response.status}; no retry")
+ if len(data) > 2 * 1024 * 1024:
+ raise ResponseTooLarge("Workflow audit API response exceeds budget")
+ return json.loads(data)
+ finally:
+ connection.close()
+
+ def issue_snapshot(self) -> list[dict[str, Any]]:
+ # Fetch the latest comment with each issue, rather than one read per unchanged task.
+ query = """query($cursor:String,$size:Int!,$history:Int!) {
+ repository(owner:"ClickHouse",name:"loom") {
+ issues(first:$size,after:$cursor,filterBy:{createdBy:"github-actions[bot]"},
+ states:[OPEN,CLOSED],orderBy:{field:CREATED_AT,direction:ASC}) {
+ nodes { number title body state author {__typename login}
+ comments:timelineItems(last:$history,itemTypes:[ISSUE_COMMENT]) {
+ totalCount nodes { ... on IssueComment {
+ fullDatabaseId createdAt body author {__typename login}
+ } }
+ } }
+ pageInfo {hasNextPage endCursor}
+ }
+ } }"""
+ output: list[dict[str, Any]] = []
+ cursor = None
+ seen: set[str] = set()
+ size = 100
+ history = 100
+ for _ in range(30):
+ variables = {"cursor": cursor, "size": size, "history": history}
+ try:
+ response = self.request(
+ "POST", "/graphql", {"query": query, "variables": variables}
+ )
+ except ResponseTooLarge:
+ if size > 1:
+ size = max(1, size // 2)
+ elif history > 1:
+ history = max(1, history // 2)
+ else:
+ raise
+ continue
+ if response.get("errors"):
+ raise RuntimeError("Workflow issue snapshot query failed; no fallback")
+ page = response["data"]["repository"]["issues"]
+ nodes, info = page["nodes"], page["pageInfo"]
+ if not isinstance(nodes, list) or len(nodes) > size:
+ raise ValueError("Invalid workflow issue snapshot page")
+ for issue in nodes:
+ comments = issue["comments"]
+ latest = comments["nodes"]
+ if not isinstance(latest, list) or len(latest) > history:
+ raise ValueError("Invalid workflow issue comment window")
+ output.append(
+ {
+ "number": issue["number"],
+ "title": issue["title"],
+ "body": issue["body"],
+ "state": issue["state"].lower(),
+ "user": snapshot_user(issue["author"]),
+ "comment_count": comments["totalCount"],
+ "recent_comments": [
+ {
+ "id": int(comment["fullDatabaseId"]),
+ "created_at": comment["createdAt"],
+ "body": comment["body"],
+ "user": snapshot_user(comment["author"]),
+ }
+ for comment in latest
+ ],
+ }
+ )
+ if info["hasNextPage"] is False:
+ return output
+ cursor = info["endCursor"]
+ if not isinstance(cursor, str) or not cursor or cursor in seen:
+ raise ValueError("Invalid workflow issue snapshot cursor")
+ seen.add(cursor)
+ size = 100
+ history = 100
+ raise RuntimeError("Workflow issue snapshot pagination budget exhausted")
+
+
+def managed_issues(issues: list[Any]) -> dict[str, dict[str, Any]]:
+ output = {}
+ for issue in issues:
+ if "pull_request" in issue or issue.get("user", {}).get("login") != _BOT:
+ continue
+ matches = _MARKER.findall(issue.get("body") or "")
+ title = _TITLE.search(issue.get("title") or "")
+ if matches and title and matches[0] != title[1]:
+ raise ValueError("Conflicting workflow issue identity markers")
+ if not matches and title:
+ matches = [title[1]] # A human can replace the body; never overwrite it.
+ if not matches:
+ continue
+ if len(matches) != 1 or matches[0] in output:
+ raise ValueError("Ambiguous managed workflow issue; refusing duplicate publication")
+ if type(issue.get("number")) is not int or issue["number"] <= 0:
+ raise ValueError("Invalid managed workflow issue number")
+ if issue.get("state") not in {"open", "closed"}:
+ raise ValueError("Invalid managed workflow issue state")
+ output[matches[0]] = issue
+ return output
+
+
+def publish(api: Any, groups: dict[str, dict[str, Any]], run_url: str) -> dict[str, int]:
+ issues = api.issue_snapshot()
+ managed = managed_issues(issues)
+ counts = {"created": 0, "updated": 0, "unchanged": 0, "closed_preserved": 0, "deferred": 0}
+ for key in sorted(set(groups) | set(managed)):
+ group, issue = groups.get(key), managed.get(key)
+ if issue is not None and issue["state"] == "closed":
+ counts["closed_preserved"] += 1
+ continue
+ write_limit_reached = counts["created"] + counts["updated"] >= 10
+ if issue is None:
+ if write_limit_reached:
+ counts["deferred"] += 1
+ continue
+ prefix = f"Review {group['rule']} in "
+ suffix = f" [workflow-audit:{key}]"
+ limit = 250 - len(prefix) - len(suffix)
+ path = group["path"]
+ if len(path) > limit:
+ path = path[: limit - 3] + "..."
+ title = prefix + path + suffix
+ api.request("POST", _ROOT, {"title": title, "body": status_body(key, group, run_url)})
+ counts["created"] += 1
+ continue
+ number = issue["number"]
+ states = _STATE.findall(issue.get("body") or "")
+ comments = issue.get("recent_comments", [])
+ recent_states = []
+ # Status authority follows creation, not human edits to an older bot comment.
+ for comment in sorted(
+ comments, key=lambda item: (datetime.fromisoformat(item["created_at"]), item["id"])
+ ):
+ if comment.get("user", {}).get("login") == _BOT:
+ recent_states.extend(_STATE.findall(comment.get("body") or ""))
+ if issue.get("comment_count", 0) > len(comments) and not recent_states:
+ counts["deferred"] += 1
+ continue
+ states.extend(recent_states)
+ # An edited initial body can erase the last observation. Keep the issue
+ # quiet until a later scan can confirm the finding is absent.
+ if not states and group is not None:
+ counts["deferred"] += 1
+ continue
+ if states and state_hash(group) == states[-1]:
+ counts["unchanged"] += 1
+ continue
+ if write_limit_reached:
+ counts["deferred"] += 1
+ continue
+ current = api.request("GET", f"{_ROOT}/{number}")
+ if current.get("state") == "closed":
+ counts["closed_preserved"] += 1
+ continue
+ # Append a deduplicated status update; never PATCH a human-owned title or body.
+ api.request(
+ "POST", f"{_ROOT}/{number}/comments", {"body": status_body(key, group, run_url)}
+ )
+ counts["updated"] += 1
+ return counts
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("findings", type=Path)
+ args = parser.parse_args()
+ if not (
+ os.environ.get("GITHUB_ACTIONS") == "true"
+ and os.environ.get("GITHUB_REPOSITORY") == _REPO
+ and os.environ.get("GITHUB_EVENT_NAME") in {"push", "schedule"}
+ and os.environ.get("GITHUB_REF") == "refs/heads/main"
+ ):
+ raise RuntimeError("Issue publication requires a trusted default-branch hosted run")
+ run = os.environ["GITHUB_RUN_ID"]
+ if not re.fullmatch(r"[1-9][0-9]{0,19}", run):
+ raise ValueError("Invalid hosted run identifier")
+ sha = os.environ["GITHUB_SHA"]
+ if not re.fullmatch(r"[a-f0-9]{40}", sha):
+ raise ValueError("Invalid hosted commit")
+ api = GitHub(os.environ["GH_TOKEN"], expected_sha=sha)
+ if api.request("GET", _MAIN_REF)["object"]["sha"] != sha:
+ print("The audit commit is older than the default branch head")
+ return
+ if args.findings.stat().st_size > 8 * 1024 * 1024:
+ raise ValueError("Workflow findings exceed input budget")
+ groups = public_findings(json.loads(args.findings.read_text()))
+ counts = publish(api, groups, f"https://github.com/{_REPO}/actions/runs/{run}")
+ summary = "Workflow maintenance issues: " + json.dumps(counts, sort_keys=True)
+ print(summary)
+ with open(os.environ["GITHUB_STEP_SUMMARY"], "a", encoding="utf-8") as output:
+ output.write("## Automatic workflow maintenance issues\n\n" + summary + "\n")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/.github/sdk-docs/README.md b/.github/sdk-docs/README.md
new file mode 100644
index 00000000000..72824c08297
--- /dev/null
+++ b/.github/sdk-docs/README.md
@@ -0,0 +1,11 @@
+# SDK documentation tooling
+
+The API documentation command installs this project's locked tools with the
+repository's locked package manager. The patch applies the directory-traversal
+change from [the upstream matcher update](https://github.com/TypeStrong/typedoc/pull/3151).
+The public partial-match API preserves traversal behavior with the patched
+matcher, including negated patterns.
+
+Run `npm --prefix sdk/typescript run docs` to build the SDK reference. CI runs
+the same command. Remove the patch when a compatible upstream release includes
+the matcher update.
diff --git a/.github/sdk-docs/package.json b/.github/sdk-docs/package.json
new file mode 100644
index 00000000000..a18bce47151
--- /dev/null
+++ b/.github/sdk-docs/package.json
@@ -0,0 +1,18 @@
+{
+ "name": "loom-sdk-docs",
+ "private": true,
+ "version": "0.0.0",
+ "packageManager": "pnpm@10.34.9",
+ "dependencies": {
+ "typedoc": "0.28.20",
+ "typescript": "5.9.3"
+ },
+ "pnpm": {
+ "overrides": {
+ "minimatch@>=7 <11.0.1": "11.0.9"
+ },
+ "patchedDependencies": {
+ "typedoc@0.28.20": "patches/typedoc@0.28.20.patch"
+ }
+ }
+}
diff --git a/.github/sdk-docs/patches/typedoc@0.28.20.patch b/.github/sdk-docs/patches/typedoc@0.28.20.patch
new file mode 100644
index 00000000000..fb7a08db8a4
--- /dev/null
+++ b/.github/sdk-docs/patches/typedoc@0.28.20.patch
@@ -0,0 +1,26 @@
+diff --git a/dist/node-utils.js b/dist/node-utils.js
+index 96a483d44c9ca066a5128dc40abcffdb8a3aee4b..10f59a35be1f085502a4302ffd708f6eebef2073 100644
+--- a/dist/node-utils.js
++++ b/dist/node-utils.js
+@@ -316,6 +316,7 @@ function discoverFiles(rootDir, controller) {
+ }
+ function glob(pattern, root, options = {}) {
+ const mini = new Minimatch2(pattern);
++ const recurseMini = new Minimatch2(pattern, { flipNegate: true });
+ const shouldIncludeNodeModules = pattern.includes("node_modules");
+ const controller = {
+ matches(path) {
+@@ -325,12 +326,7 @@ function glob(pattern, root, options = {}) {
+ if (childPath[childPath.length - 1] === "node_modules" && !shouldIncludeNodeModules) {
+ return false;
+ }
+- return mini.set.some((row) => mini.matchOne(
+- childPath,
+- row,
+- /* partial */
+- true
+- ));
++ return recurseMini.match(childPath.join("/"), true);
+ },
+ matchDirectories: options.includeDirectories,
+ followSymlinks: options.followSymlinks
diff --git a/.github/sdk-docs/pnpm-lock.yaml b/.github/sdk-docs/pnpm-lock.yaml
new file mode 100644
index 00000000000..a99128d8acf
--- /dev/null
+++ b/.github/sdk-docs/pnpm-lock.yaml
@@ -0,0 +1,216 @@
+lockfileVersion: "9.0"
+
+settings:
+ autoInstallPeers: true
+ excludeLinksFromLockfile: false
+
+overrides:
+ minimatch@>=7 <11.0.1: 11.0.9
+
+patchedDependencies:
+ typedoc@0.28.20:
+ hash: b23d27e2e7c28e7b544a4b9853b0a3fb73ea03f41da10b3753a8c08c6e69ccd8
+ path: patches/typedoc@0.28.20.patch
+
+importers:
+ .:
+ dependencies:
+ typedoc:
+ specifier: 0.28.20
+ version: 0.28.20(patch_hash=b23d27e2e7c28e7b544a4b9853b0a3fb73ea03f41da10b3753a8c08c6e69ccd8)(typescript@5.9.3)
+ typescript:
+ specifier: 5.9.3
+ version: 5.9.3
+
+packages:
+ "@gerrit0/mini-shiki@3.23.0":
+ resolution:
+ { integrity: sha512-bEMORlG0cqdjVyCEuU0cDQbORWX+kYCeo0kV1lbxF5bt4r7SID2l9bqsxJEM0zndaxpOUT7riCyIVEuqq/Ynxg== }
+
+ "@isaacs/nonrecursive-glob-match@1.1.0":
+ resolution:
+ { integrity: sha512-GPm/Dbvk5RLmhRnxXIa7nTpK0xtl4E0wj0MslsuNiJ1FIROU+2+9lgUC/dgF7Ey4QCWhfEsgxilMRMCdHPfDfw== }
+
+ "@shikijs/engine-oniguruma@3.23.0":
+ resolution:
+ { integrity: sha512-1nWINwKXxKKLqPibT5f4pAFLej9oZzQTsby8942OTlsJzOBZ0MWKiwzMsd+jhzu8YPCHAswGnnN1YtQfirL35g== }
+
+ "@shikijs/langs@3.23.0":
+ resolution:
+ { integrity: sha512-2Ep4W3Re5aB1/62RSYQInK9mM3HsLeB91cHqznAJMuylqjzNVAVCMnNWRHFtcNHXsoNRayP9z1qj4Sq3nMqYXg== }
+
+ "@shikijs/themes@3.23.0":
+ resolution:
+ { integrity: sha512-5qySYa1ZgAT18HR/ypENL9cUSGOeI2x+4IvYJu4JgVJdizn6kG4ia5Q1jDEOi7gTbN4RbuYtmHh0W3eccOrjMA== }
+
+ "@shikijs/types@3.23.0":
+ resolution:
+ { integrity: sha512-3JZ5HXOZfYjsYSk0yPwBrkupyYSLpAE26Qc0HLghhZNGTZg/SKxXIIgoxOpmmeQP0RRSDJTk1/vPfw9tbw+jSQ== }
+
+ "@shikijs/vscode-textmate@10.1.0":
+ resolution:
+ { integrity: sha512-cVBuhDQjBZaNMTwBquYfPydrUP+E3hE6oYGasx8h6ZrODIM7/r+gxLDXdd66oszbrggZHEntdE6j+5gYIVyMWQ== }
+
+ "@types/hast@3.0.5":
+ resolution:
+ { integrity: sha512-rp/ezSWaD1m44dPKICGhiskI13nVr7qTloFwDa/IYkhhf5nzwP+zIQcIJh3WIFSBOy/H1PzB40jPjMDksN4F+g== }
+
+ "@types/unist@3.0.3":
+ resolution:
+ { integrity: sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q== }
+
+ argparse@2.0.1:
+ resolution:
+ { integrity: sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q== }
+
+ balanced-match@4.0.4:
+ resolution:
+ { integrity: sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA== }
+ engines: { node: 18 || 20 || >=22 }
+
+ brace-expansion@5.0.13:
+ resolution:
+ { integrity: sha512-Vh3dmFbc4wZeox7M9I/0L9GfFd83Su4+yCck/OF9Gi/P/dAHn0RT7X4K9R7gMNMhDck3DvhR6QXsnQdjjgwNvQ== }
+ engines: { node: 20 || >=22 }
+
+ entities@4.5.0:
+ resolution:
+ { integrity: sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw== }
+ engines: { node: ">=0.12" }
+
+ linkify-it@5.0.2:
+ resolution:
+ { integrity: sha512-ONTm2jCMAVZjgQa/Fy1kScXsuOoF5NPTsoFBdE1KVIZ2vAh/r9+Bqo+0jINCBYnavTPQZz38QzFTme79ENoN3Q== }
+
+ lunr@2.3.9:
+ resolution:
+ { integrity: sha512-zTU3DaZaF3Rt9rhN3uBMGQD3dD2/vFQqnvZCDv4dl5iOzq2IZQqTxu90r4E5J+nP70J3ilqVCrbho2eWaeW8Ow== }
+
+ markdown-it@14.3.3:
+ resolution:
+ { integrity: sha512-L//tDAkjTjJCU6pBUSBTgs3Kg4InVaZuUZog/b6V12UKhcDQ7S78877ibbCanRExwPuYP1CZD7Gd2dxSy1GXRg== }
+ hasBin: true
+
+ mdurl@2.1.0:
+ resolution:
+ { integrity: sha512-1+HBaOx0zi/dQWht8rNv9MYf9qqpqL/kxI0hXImU6Y547zM6Sni8BQibt7ifgMcYtQg41ao3Ivd6cnSM86inpg== }
+
+ minimatch@11.0.9:
+ resolution:
+ { integrity: sha512-KCFkfyjqerNlSstjlhIGNXIKZGA/6O4V4RlhZ+Dsr621SPPw0mzlypE9D9ZOoPiVefHID+j7/XuMMlqfD/F60Q== }
+ engines: { node: 20 || >=22 }
+
+ punycode.js@2.3.1:
+ resolution:
+ { integrity: sha512-uxFIHU0YlHYhDQtV4R9J6a52SLx28BCjT+4ieh7IGbgwVJWO+km431c4yRlREUAsAmt/uMjQUyQHNEPf0M39CA== }
+ engines: { node: ">=6" }
+
+ typedoc@0.28.20:
+ resolution:
+ { integrity: sha512-uSKqkh8Cr48vllnEy+jdaAgOeR6Y+QCBW7usgUsKj7gJEfR7stw9U/fE49LBnj2tPRKPY0c0EBJSWe9Appmplg== }
+ engines: { node: ">= 18", pnpm: ">= 10" }
+ hasBin: true
+ peerDependencies:
+ typescript: 5.0.x || 5.1.x || 5.2.x || 5.3.x || 5.4.x || 5.5.x || 5.6.x || 5.7.x || 5.8.x || 5.9.x || 6.0.x
+
+ typescript@5.9.3:
+ resolution:
+ { integrity: sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw== }
+ engines: { node: ">=14.17" }
+ hasBin: true
+
+ uc.micro@2.1.0:
+ resolution:
+ { integrity: sha512-ARDJmphmdvUk6Glw7y9DQ2bFkKBHwQHLi2lsaH6PPmz/Ka9sFOBsBluozhDltWmnv9u/cF6Rt87znRTPV+yp/A== }
+
+ yaml@2.9.1:
+ resolution:
+ { integrity: sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw== }
+ engines: { node: ">= 14.6" }
+ hasBin: true
+
+snapshots:
+ "@gerrit0/mini-shiki@3.23.0":
+ dependencies:
+ "@shikijs/engine-oniguruma": 3.23.0
+ "@shikijs/langs": 3.23.0
+ "@shikijs/themes": 3.23.0
+ "@shikijs/types": 3.23.0
+ "@shikijs/vscode-textmate": 10.1.0
+
+ "@isaacs/nonrecursive-glob-match@1.1.0": {}
+
+ "@shikijs/engine-oniguruma@3.23.0":
+ dependencies:
+ "@shikijs/types": 3.23.0
+ "@shikijs/vscode-textmate": 10.1.0
+
+ "@shikijs/langs@3.23.0":
+ dependencies:
+ "@shikijs/types": 3.23.0
+
+ "@shikijs/themes@3.23.0":
+ dependencies:
+ "@shikijs/types": 3.23.0
+
+ "@shikijs/types@3.23.0":
+ dependencies:
+ "@shikijs/vscode-textmate": 10.1.0
+ "@types/hast": 3.0.5
+
+ "@shikijs/vscode-textmate@10.1.0": {}
+
+ "@types/hast@3.0.5":
+ dependencies:
+ "@types/unist": 3.0.3
+
+ "@types/unist@3.0.3": {}
+
+ argparse@2.0.1: {}
+
+ balanced-match@4.0.4: {}
+
+ brace-expansion@5.0.13:
+ dependencies:
+ balanced-match: 4.0.4
+
+ entities@4.5.0: {}
+
+ linkify-it@5.0.2:
+ dependencies:
+ uc.micro: 2.1.0
+
+ lunr@2.3.9: {}
+
+ markdown-it@14.3.3:
+ dependencies:
+ argparse: 2.0.1
+ entities: 4.5.0
+ linkify-it: 5.0.2
+ mdurl: 2.1.0
+ punycode.js: 2.3.1
+ uc.micro: 2.1.0
+
+ mdurl@2.1.0: {}
+
+ minimatch@11.0.9:
+ dependencies:
+ "@isaacs/nonrecursive-glob-match": 1.1.0
+ brace-expansion: 5.0.13
+
+ punycode.js@2.3.1: {}
+
+ typedoc@0.28.20(patch_hash=b23d27e2e7c28e7b544a4b9853b0a3fb73ea03f41da10b3753a8c08c6e69ccd8)(typescript@5.9.3):
+ dependencies:
+ "@gerrit0/mini-shiki": 3.23.0
+ lunr: 2.3.9
+ markdown-it: 14.3.3
+ minimatch: 11.0.9
+ typescript: 5.9.3
+ yaml: 2.9.1
+
+ typescript@5.9.3: {}
+
+ uc.micro@2.1.0: {}
+
+ yaml@2.9.1: {}
diff --git a/.github/workflows/cell-nightly.yml b/.github/workflows/cell-nightly.yml
index b93576d792a..1f68c656d8a 100644
--- a/.github/workflows/cell-nightly.yml
+++ b/.github/workflows/cell-nightly.yml
@@ -45,13 +45,15 @@ jobs:
id: python
with:
python-version: "3.12"
- - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
+ - uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0
with:
version: "0.12.19"
enable-cache: true
cache-dependency-glob: uv.lock
- name: Install the locked native dependencies
- run: uv sync --locked --python "${{ steps.python.outputs.python-path }}" --extra dev --extra code
+ env:
+ PYTHON_PATH: ${{ steps.python.outputs.python-path }}
+ run: uv sync --locked --python "${PYTHON_PATH}" --extra dev --extra code
- name: Check native tools
run: |
command -v docker
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 62879d0e47c..ce29402b451 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -27,6 +27,7 @@ permissions:
env:
PYTHON_VERSION: "3.12"
NODE_VERSION: "22"
+ RUST_CODEGEN_VERSION: "1.84.1"
# The Python jobs install the exact versions in uv.lock with this uv.
UV_VERSION: "0.12.19"
@@ -80,17 +81,33 @@ jobs:
id: python
with:
python-version: ${{ env.PYTHON_VERSION }}
- - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
+ - uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0
with:
version: ${{ env.UV_VERSION }}
- enable-cache: true
- cache-dependency-glob: uv.lock
+ enable-cache: false
- name: Install Loom from uv.lock (dev, code extras)
+ env:
+ PYTHON_PATH: ${{ steps.python.outputs.python-path }}
run: |
- uv sync --locked --python "${{ steps.python.outputs.python-path }}" --extra dev --extra code
+ uv sync --locked --python "${PYTHON_PATH}" --extra dev --extra code
echo "$PWD/.venv/bin" >> "$GITHUB_PATH"
- name: ruff
run: ruff check server extractor sdk/python tests scripts .claude
+ - name: Install Rust formatter for generated contracts
+ run: |
+ rustup toolchain install "$RUST_CODEGEN_VERSION" --profile minimal --component rustfmt
+ rustup override set "$RUST_CODEGEN_VERSION"
+ - name: generated Rust contracts are current
+ run: |
+ python scripts/codegen/sdk_rust_gen.py --check
+ python scripts/codegen/sdk_rust_gen.py --fixtures --check
+ - name: Install Go formatter for generated contracts
+ uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0
+ with:
+ go-version: "1.27.4"
+ cache: false
+ - name: generated Go contracts are current
+ run: python scripts/codegen/sdk_go_gen.py --check
- name: ruff format
run: ruff format --check .
# The Python SDK's op table, TypedDicts and per-op client are generated
@@ -106,6 +123,14 @@ jobs:
# bytes and the executable bit.
- name: codex plugin copies are current (bytes and executable bit)
run: python scripts/codegen/agent_plugin_sync.py --check
+ # The standalone skill bundles are the plugin's memory, code and status
+ # skills made portable; a change to one of those skills must regenerate them.
+ - name: standalone skill bundles are current
+ run: python scripts/codegen/standalone_skills.py --check
+ # The skills the MCP transport serves are generated from the Claude Code
+ # plugin's; a change to one of those must regenerate them.
+ - name: served skills are current
+ run: python scripts/codegen/served_skills.py --check
# docs/reference/ (configuration and the generated tables) and
# server/operations/reach_manifest.py are generated too; the unit suite
# checks them, this step fails faster.
@@ -146,8 +171,7 @@ jobs:
strategy:
fail-fast: false
matrix:
- # The part count, 6, is also in docs/development/testing.md's unit row and
- # the loom-investigate-ci row.
+ # Patch coverage and the unit test instructions also use this part count.
part: [1, 2, 3, 4, 5, 6]
env:
LOOM_CLICKHOUSE_IMAGE: ${{ needs.clickhouse.outputs.image }}
@@ -166,14 +190,16 @@ jobs:
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: ${{ env.NODE_VERSION }}
- - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
+ package-manager-cache: false
+ - uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0
with:
version: ${{ env.UV_VERSION }}
- enable-cache: true
- cache-dependency-glob: uv.lock
+ enable-cache: false
- name: Install Loom from uv.lock (dev, code extras)
+ env:
+ PYTHON_PATH: ${{ steps.python.outputs.python-path }}
run: |
- uv sync --locked --python "${{ steps.python.outputs.python-path }}" --extra dev --extra code
+ uv sync --locked --python "${PYTHON_PATH}" --extra dev --extra code
echo "$PWD/.venv/bin" >> "$GITHUB_PATH"
- name: Fetch origin/main for the migration-number check
run: git fetch --no-tags --depth=1 origin +refs/heads/main:refs/remotes/origin/main
@@ -213,21 +239,21 @@ jobs:
python -m tests.unit.test_native_worker --mechanism
- name: pytest unit (this part, random order)
env:
+ SHARD_PART: ${{ matrix.part }}
LOOM_TEST_SHARD: ${{ matrix.part }}/${{ strategy.job-total }}
COVERAGE_FILE: .coverage.unit-${{ matrix.part }}
run: |
- SEED="${{ github.run_id }}${{ github.run_attempt }}"
+ SEED="${GITHUB_RUN_ID}${GITHUB_RUN_ATTEMPT}"
echo "pytest-randomly seed: $SEED"
NATIVE_ARGS=()
- if [ "${{ matrix.part }}" = 3 ]; then
+ if [ "${SHARD_PART}" = 3 ]; then
ulimit -S -c 0
NATIVE_ARGS=(--native-worker-signatures)
fi
pytest tests/unit -vv -n auto -p randomly -p tests._worker_status --randomly-seed="$SEED" --durations=15 \
"${NATIVE_ARGS[@]}" \
- -o faulthandler_timeout=300 \
--cov=server --cov=sdk/python/loom --cov-branch --cov-report= \
- --junitxml=junit-unit-${{ matrix.part }}.xml
+ --junitxml="junit-unit-${SHARD_PART}.xml"
# Also after a failure: the failing part's test times are what a reader needs.
- name: Upload this part's coverage data and test times
if: always()
@@ -256,14 +282,15 @@ jobs:
id: python
with:
python-version: ${{ env.PYTHON_VERSION }}
- - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
+ - uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0
with:
version: ${{ env.UV_VERSION }}
- enable-cache: true
- cache-dependency-glob: uv.lock
+ enable-cache: false
- name: Install Loom from uv.lock (dev, code extras)
+ env:
+ PYTHON_PATH: ${{ steps.python.outputs.python-path }}
run: |
- uv sync --locked --python "${{ steps.python.outputs.python-path }}" --extra dev --extra code
+ uv sync --locked --python "${PYTHON_PATH}" --extra dev --extra code
echo "$PWD/.venv/bin" >> "$GITHUB_PATH"
- name: Download the parts' coverage data and test times
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
@@ -293,7 +320,7 @@ jobs:
run: python -m tests.inventory.coverage_floors coverage.json
# The published benchmark harnesses' scoring and dataset readers.
- name: pytest bench harnesses
- run: pytest bench -q -p randomly --randomly-seed="${{ github.run_id }}${{ github.run_attempt }}"
+ run: pytest bench -q -p randomly --randomly-seed="${GITHUB_RUN_ID}${GITHUB_RUN_ATTEMPT}"
# The generic ingest script's dry run goes through this checkout's CLI.
- name: generic integration sample
run: PYTHON=python bash integrations/generic/test.sh
@@ -304,6 +331,56 @@ jobs:
name: coverage-xml
path: coverage.xml
+ python-patch-coverage:
+ name: Python changed-line coverage (report only)
+ needs: [validate-ref, unit]
+ if: >-
+ github.event_name == 'pull_request' && !cancelled() &&
+ needs.validate-ref.result == 'success' &&
+ (needs.unit.result == 'success' || needs.unit.result == 'failure')
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ continue-on-error: true
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+ fetch-depth: 2
+ - uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0
+ with:
+ version: ${{ env.UV_VERSION }}
+ enable-cache: false
+ - name: Download the parts' coverage data
+ uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
+ with:
+ pattern: coverage-unit-*
+ merge-multiple: true
+ - name: Combine and export the Python coverage data
+ run: |
+ parts=(.coverage.unit-{1..6})
+ for part in "${parts[@]}"; do
+ test -s "$part"
+ done
+ coverage_package=$(python3 - <<'PY'
+ import tomllib
+ with open("uv.lock", "rb") as lock:
+ packages = tomllib.load(lock)["package"]
+ version = next(package["version"] for package in packages if package["name"] == "coverage")
+ print(f"coverage=={version}")
+ PY
+ )
+ uvx --python "$PYTHON_VERSION" --from "$coverage_package" coverage combine "${parts[@]}"
+ # Coverage can skip unreadable data without failing the combine.
+ for part in "${parts[@]}"; do
+ test ! -e "$part"
+ done
+ uvx --python "$PYTHON_VERSION" --from "$coverage_package" coverage lcov -o "$RUNNER_TEMP/python.lcov"
+ - name: Report Python changed-line coverage
+ uses: ClickHouse/loom/.github/actions/patch-coverage@df405e9ed5d032b8248f6cfa8cf87e856685e490
+ with:
+ component: Python server and SDK
+ report: ${{ runner.temp }}/python.lcov
+
sandbox:
needs: validate-ref
name: repository-job sandbox (real bubblewrap)
@@ -319,14 +396,15 @@ jobs:
id: python
with:
python-version: ${{ env.PYTHON_VERSION }}
- - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
+ - uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0
with:
version: ${{ env.UV_VERSION }}
- enable-cache: true
- cache-dependency-glob: uv.lock
+ enable-cache: false
- name: Install Loom from uv.lock (dev, code extras)
+ env:
+ PYTHON_PATH: ${{ steps.python.outputs.python-path }}
run: |
- uv sync --locked --python "${{ steps.python.outputs.python-path }}" --extra dev --extra code
+ uv sync --locked --python "${PYTHON_PATH}" --extra dev --extra code
echo "$PWD/.venv/bin" >> "$GITHUB_PATH"
# prlimit comes with util-linux. Ubuntu 24.04 restricts unprivileged user
# namespaces through AppArmor; the sandbox needs them.
@@ -339,7 +417,7 @@ jobs:
- name: pytest hostile sandbox suite
env:
LOOM_TEST_REQUIRE_SANDBOX: "1"
- run: pytest tests/unit/test_repo_job_sandbox_hostile.py -q -p randomly --randomly-seed="${{ github.run_id }}${{ github.run_attempt }}"
+ run: pytest tests/unit/test_repo_job_sandbox_hostile.py -q -p randomly --randomly-seed="${GITHUB_RUN_ID}${GITHUB_RUN_ATTEMPT}"
schema-check:
name: schema.sql in sync with migrations
@@ -362,14 +440,15 @@ jobs:
id: python
with:
python-version: ${{ env.PYTHON_VERSION }}
- - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
+ - uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0
with:
version: ${{ env.UV_VERSION }}
- enable-cache: true
- cache-dependency-glob: uv.lock
+ enable-cache: false
- name: Install Loom from uv.lock (no extras)
+ env:
+ PYTHON_PATH: ${{ steps.python.outputs.python-path }}
run: |
- uv sync --locked --python "${{ steps.python.outputs.python-path }}"
+ uv sync --locked --python "${PYTHON_PATH}"
echo "$PWD/.venv/bin" >> "$GITHUB_PATH"
- name: Start ClickHouse (loom config + lemmagen dictionary)
run: bash dev/ci_start_clickhouse.sh
@@ -406,8 +485,7 @@ jobs:
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: ${{ env.NODE_VERSION }}
- cache: npm
- cache-dependency-path: frontend/package-lock.json
+ package-manager-cache: false
- name: Install + build frontend (build runs tsc -b internally)
working-directory: frontend
run: |
@@ -431,6 +509,7 @@ jobs:
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: ${{ env.NODE_VERSION }}
+ package-manager-cache: false
- name: install shfmt v3.10.0
run: |
curl -sSfL -o /usr/local/bin/shfmt https://github.com/mvdan/sh/releases/download/v3.10.0/shfmt_v3.10.0_linux_amd64
@@ -473,8 +552,8 @@ jobs:
# Every optional object on, so each template renders at least once.
on=(--set analyticsExport.enabled=true --set analyticsExport.bucket=ci --set analyticsExport.nameKeySecret.name=ci)
extractor=(--set extractor.enabled=true --set secrets.extractorToken="$(openssl rand -hex 24)")
- assistant=(--set assistant.enabled=true --set assistant.existingSecret=ci)
- # TLS on Loom's port, which the assistant (in "all") cannot reach: its own render.
+ assistant=(--set assistant.nativeEnabled=true --set env.LOOM_ASSISTANT_PROVIDER=fake)
+ # TLS on Loom's port; native tools stay in process.
tls=(--set tls.secretName=ci --set 'ingress.annotations.alb\.ingress\.kubernetes\.io/backend-protocol=HTTPS' --set workers.enabled=true --set networkPolicy.enabled=true "${on[@]}" "${extractor[@]}")
all=(--set workers.enabled=true --set workers.replicaCount=2 --set autoscaling.enabled=true --set networkPolicy.enabled=true --set alerts.prometheusRule.enabled=true --set mustMatchChange.publish=ci --set cellProbe.port=8777 --set settingsFile.memory_ask_recency_weight=0.3 "${on[@]}" "${extractor[@]}" "${assistant[@]}")
# The PrometheusRule's schema: the CRD catalog at a pinned commit.
@@ -511,8 +590,6 @@ jobs:
refused "needs analyticsExport.bucket" "${on[@]}" --set analyticsExport.bucket=
refused "needs analyticsExport.nameKeySecret.name" "${on[@]}" --set analyticsExport.nameKeySecret.name=
refused "expectedBucketOwner must be a quoted string" "${on[@]}" --set analyticsExport.expectedBucketOwner=123456789012
- refused "assistant.existingSecret is required" --set assistant.enabled=true
- refused "assistant.enabled calls Loom's port over plain HTTP" "${assistant[@]}" --set tls.secretName=ci
refused 'set ingress.annotations."alb.ingress.kubernetes.io/backend-protocol" to HTTPS' -f "$chart/values-eks.yaml" --set tls.secretName=ci
# The release Secret (named after the release here) and envFrom Secrets reach every pod.
shared="is a Secret every web and workers pod loads"
@@ -543,7 +620,7 @@ jobs:
# No Loom pod reaches the instance metadata service, with the policy on or off.
- name: metadata egress
run: python3 scripts/gates/helm_metadata_egress.py
- # What LibreChat and its MongoDB can be reached by and reach, read off the render.
+ # Native assistant enablement adds no workload, store or network access.
- name: assistant isolation
run: python3 scripts/gates/helm_assistant_isolation.py
# The Postgres authority's DSN, password, CA mount and egress, and its refusals.
@@ -567,6 +644,7 @@ jobs:
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: ${{ env.NODE_VERSION }}
+ package-manager-cache: false
# The hook scripts have no dependencies and run under any Node >= 18;
# their tests are node:test files beside them.
- name: node --test (hook scripts shared by the Claude Code and Codex plugins)
@@ -605,8 +683,7 @@ jobs:
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: ${{ env.NODE_VERSION }}
- cache: npm
- cache-dependency-path: frontend/package-lock.json
+ package-manager-cache: false
- name: npm ci
working-directory: frontend
run: npm ci --no-audit --no-fund
@@ -615,7 +692,39 @@ jobs:
# isolation. jsdom, no browser.
- name: vitest (unit + component + axe)
working-directory: frontend
- run: npm run test -- --shard=${{ matrix.part }}/${{ strategy.job-total }}
+ env:
+ SHARD: ${{ matrix.part }}/${{ strategy.job-total }}
+ run: npm run test -- --shard="$SHARD"
+
+ frontend-coverage:
+ needs: validate-ref
+ if: github.event_name == 'pull_request'
+ name: Dashboard changed-line coverage (report only)
+ runs-on: ubuntu-latest
+ timeout-minutes: 20
+ continue-on-error: true
+ defaults:
+ run:
+ working-directory: frontend
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+ fetch-depth: 2
+ - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
+ with:
+ node-version: ${{ env.NODE_VERSION }}
+ package-manager-cache: false
+ - name: npm ci
+ run: npm ci --no-audit --no-fund
+ - name: Collect dashboard unit coverage
+ run: npm run test -- --coverage --testTimeout=10000
+ - name: Report dashboard changed-line coverage
+ uses: ClickHouse/loom/.github/actions/patch-coverage@df405e9ed5d032b8248f6cfa8cf87e856685e490
+ with:
+ component: Dashboard
+ working-directory: frontend
+ report: frontend/coverage/lcov.info
# With fullyParallel: false, --shard splits by spec file per project, not by test.
frontend-e2e:
@@ -634,8 +743,7 @@ jobs:
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: ${{ env.NODE_VERSION }}
- cache: npm
- cache-dependency-path: frontend/package-lock.json
+ package-manager-cache: false
- name: npm ci
working-directory: frontend
run: npm ci --no-audit --no-fund
@@ -646,7 +754,9 @@ jobs:
# call answered from fixtures.
- name: playwright (e2e specs)
working-directory: frontend
- run: npm run e2e -- --shard=${{ matrix.part }}/${{ strategy.job-total }}
+ env:
+ SHARD: ${{ matrix.part }}/${{ strategy.job-total }}
+ run: npm run e2e -- --shard="$SHARD"
- name: Upload screenshots and traces
if: always()
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
@@ -721,14 +831,15 @@ jobs:
id: python
with:
python-version: ${{ env.PYTHON_VERSION }}
- - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
+ - uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0
with:
version: ${{ env.UV_VERSION }}
- enable-cache: true
- cache-dependency-glob: uv.lock
+ enable-cache: false
- name: Install Loom from uv.lock (dev, code extras)
+ env:
+ PYTHON_PATH: ${{ steps.python.outputs.python-path }}
run: |
- uv sync --locked --python "${{ steps.python.outputs.python-path }}" --extra dev --extra code
+ uv sync --locked --python "${PYTHON_PATH}" --extra dev --extra code
echo "$PWD/.venv/bin" >> "$GITHUB_PATH"
- name: Start ClickHouse (loom config + lemmagen dictionary)
run: bash dev/ci_start_clickhouse.sh
@@ -739,8 +850,7 @@ jobs:
if: matrix.part == '1'
with:
node-version: ${{ env.NODE_VERSION }}
- cache: npm
- cache-dependency-path: sdk/typescript/package-lock.json
+ package-manager-cache: false
- name: Install native framework clients
if: matrix.part == '1'
run: |
@@ -886,6 +996,17 @@ jobs:
name: pipecat-native-demo
path: ${{ runner.temp }}/pipecat-native-demo.json
if-no-files-found: error
+ - name: Install Rust for live SDK contracts
+ if: matrix.part == 'isolation' && !cancelled() && steps.auth_on.outcome == 'success'
+ run: rustup toolchain install stable --profile minimal
+ - name: Rust SDK live contracts (auth on)
+ if: matrix.part == 'isolation' && !cancelled() && steps.auth_on.outcome == 'success'
+ timeout-minutes: 6
+ env:
+ LOOM_AUTH_REQUIRED: "true"
+ LOOM_BASE_URL: http://localhost:7778
+ RUSTUP_TOOLCHAIN: stable
+ run: pytest -q tests/integration/_rust_sdk_ci.py
- name: pytest isolation gates (auth on)
if: matrix.part == 'isolation' && !cancelled() && steps.auth_on.outcome == 'success'
env:
@@ -979,14 +1100,15 @@ jobs:
id: python
with:
python-version: ${{ env.PYTHON_VERSION }}
- - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
+ - uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0
with:
version: ${{ env.UV_VERSION }}
- enable-cache: true
- cache-dependency-glob: uv.lock
+ enable-cache: false
- name: Install Loom from uv.lock (dev, code extras)
+ env:
+ PYTHON_PATH: ${{ steps.python.outputs.python-path }}
run: |
- uv sync --locked --python "${{ steps.python.outputs.python-path }}" --extra dev --extra code
+ uv sync --locked --python "${PYTHON_PATH}" --extra dev --extra code
echo "$PWD/.venv/bin" >> "$GITHUB_PATH"
- name: Start ClickHouse (loom config + lemmagen dictionary)
run: bash dev/ci_start_clickhouse.sh
@@ -1090,7 +1212,6 @@ jobs:
tests/integration/test_mirror_ask_http.py
tests/integration/test_marked_admin_events_native.py
tests/integration/test_marked_analytics_export_native.py
- tests/integration/test_marked_assistant_ledger_native.py
tests/integration/test_marked_cost_summary_native.py
tests/integration/test_marked_derived_activity_native.py
tests/integration/test_marked_event_readers_native.py
@@ -1244,71 +1365,110 @@ jobs:
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: ${{ env.NODE_VERSION }}
- cache: npm
- cache-dependency-path: frontend/package-lock.json
+ package-manager-cache: false
- uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
id: python
with:
python-version: ${{ env.PYTHON_VERSION }}
- - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
+ - uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0
with:
version: ${{ env.UV_VERSION }}
- enable-cache: true
- cache-dependency-glob: uv.lock
+ enable-cache: false
- name: Install Loom from uv.lock
+ env:
+ PYTHON_PATH: ${{ steps.python.outputs.python-path }}
run: |
- uv sync --locked --python "${{ steps.python.outputs.python-path }}" --extra dev --extra code
+ uv sync --locked --python "${PYTHON_PATH}" --extra dev --extra code
echo "$PWD/.venv/bin" >> "$GITHUB_PATH"
# The base is HEAD~1: the previous commit on a push, and on a pull request the
# first parent of its merge commit, the target branch as the merge was made. The
# target branch's tip can carry a newer migration by the time the run starts.
- name: Mixed-version gate
run: python scripts/gates/mixed_version.py --require --base HEAD~1
- - name: Published build ordinary-event compatibility
- run: python scripts/gates/mixed_version.py --require --base 1cbaf0411114512957b96ec5ea7bbb8058828543
+ # v1.3.0 checks the analyst version before probing retired relations.
+ - name: Published build event-view compatibility
+ run: python scripts/gates/mixed_version.py --require --base 47b479dcdae4c089aef2690428fa4c9a8f54554c
sdk-rust:
needs: validate-ref
- name: rust sdk (${{ matrix.rust }}, fmt, tests, clippy, docs, package)
+ name: rust sdk (${{ matrix.rust }}, ${{ matrix.mode }}, fmt, tests, clippy, docs, package)
runs-on: ubuntu-latest
timeout-minutes: 15
strategy:
fail-fast: false
matrix:
rust: ["1.84.1", stable]
+ mode: [async, blocking]
defaults:
run:
working-directory: sdk/rust
env:
CARGO_RESOLVER_INCOMPATIBLE_RUST_VERSIONS: fallback
+ RUST_SDK_FEATURES: ${{ matrix.mode == 'blocking' && '--features blocking' || '' }}
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
+ fetch-depth: 2
- name: Install Rust with format and lint components
+ env:
+ RUST_TOOLCHAIN: ${{ matrix.rust }}
run: |
- rustup toolchain install "${{ matrix.rust }}" --profile minimal --component rustfmt --component clippy
- rustup override set "${{ matrix.rust }}"
+ rustup toolchain install "${RUST_TOOLCHAIN}" --profile minimal --component rustfmt --component clippy
+ rustup override set "${RUST_TOOLCHAIN}"
+ - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
+ with:
+ python-version: ${{ env.PYTHON_VERSION }}
+ - name: Check the independent Rust SDK version
+ run: python ../../scripts/release/rust_sdk.py check-version
# The library leaves dependency locking to its consumers; each toolchain resolves once.
- name: Resolve dependencies for this toolchain
run: cargo generate-lockfile
- name: Rust formatting
run: cargo fmt --check
+ - name: Install Rust coverage tools
+ id: rust-coverage-tools
+ if: github.event_name == 'pull_request' && matrix.rust == 'stable'
+ continue-on-error: true
+ run: |
+ rustup component add llvm-tools-preview
+ cargo install --locked cargo-llvm-cov --version 0.9.2
- name: Unit, HTTP contract and documentation tests
- run: cargo test --locked
+ env:
+ COLLECT_RUST_COVERAGE: ${{ steps.rust-coverage-tools.outcome == 'success' }}
+ run: |
+ if [[ "$COLLECT_RUST_COVERAGE" == true ]]; then
+ cargo llvm-cov --locked --all-targets $RUST_SDK_FEATURES --no-report
+ else
+ cargo test --locked --all-targets $RUST_SDK_FEATURES
+ fi
+ cargo test --locked --doc $RUST_SDK_FEATURES
+ - name: Export Rust coverage as LCOV
+ id: rust-coverage
+ if: steps.rust-coverage-tools.outcome == 'success'
+ continue-on-error: true
+ run: cargo llvm-cov report $RUST_SDK_FEATURES --lcov --output-path "$RUNNER_TEMP/rust.lcov"
+ - name: Report Rust SDK changed-line coverage
+ if: steps.rust-coverage.outcome == 'success'
+ continue-on-error: true
+ uses: ClickHouse/loom/.github/actions/patch-coverage@df405e9ed5d032b8248f6cfa8cf87e856685e490
+ with:
+ component: Rust SDK
+ working-directory: sdk/rust
+ report: ${{ runner.temp }}/rust.lcov
- name: Lint the library, tests and examples
- run: cargo clippy --locked --all-targets -- -D warnings
+ run: cargo clippy --locked --all-targets $RUST_SDK_FEATURES -- -D warnings
- name: API documentation
env:
RUSTDOCFLAGS: -D warnings
- run: cargo doc --locked --no-deps
+ run: cargo doc --locked --no-deps $RUST_SDK_FEATURES
- name: Verify the distributable crate and its license
run: |
- cargo package --locked
- for archive in target/package/clickhouse-loom-*.crate; do
- package="$(basename "$archive" .crate)"
- tar -xOf "$archive" "$package/LICENSE" | cmp - ../../LICENSE
- done
+ version=$(python ../../scripts/release/rust_sdk.py check-version)
+ cargo package --locked $RUST_SDK_FEATURES
+ python ../../scripts/release/rust_sdk.py verify-package \
+ "target/package/clickhouse-loom-$version.crate" \
+ --expected-commit "$(git rev-parse HEAD)"
sdk-typescript:
needs: validate-ref
@@ -1319,18 +1479,20 @@ jobs:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
+ fetch-depth: 2
- uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
id: python
with:
python-version: ${{ env.PYTHON_VERSION }}
- - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
+ - uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0
with:
version: ${{ env.UV_VERSION }}
- enable-cache: true
- cache-dependency-glob: uv.lock
+ enable-cache: false
- name: Install Loom from uv.lock (no extras)
+ env:
+ PYTHON_PATH: ${{ steps.python.outputs.python-path }}
run: |
- uv sync --locked --python "${{ steps.python.outputs.python-path }}"
+ uv sync --locked --python "${PYTHON_PATH}"
echo "$PWD/.venv/bin" >> "$GITHUB_PATH"
# The SDK's operation table and wire types are generated from the
# server's registry; a server change that alters a
@@ -1340,8 +1502,7 @@ jobs:
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: ${{ env.NODE_VERSION }}
- cache: npm
- cache-dependency-path: sdk/typescript/package-lock.json
+ package-manager-cache: false
- name: npm ci
working-directory: sdk/typescript
run: npm ci --no-audit --no-fund
@@ -1349,13 +1510,26 @@ jobs:
# ts examples type-checked against src, vitest.
- name: lint + type-check + version + README examples + unit tests
working-directory: sdk/typescript
+ env:
+ LOOM_TEST_COVERAGE: ${{ github.event_name == 'pull_request' && '1' || '' }}
run: npm run check
+ - name: Report TypeScript SDK changed-line coverage
+ if: github.event_name == 'pull_request'
+ continue-on-error: true
+ uses: ClickHouse/loom/.github/actions/patch-coverage@df405e9ed5d032b8248f6cfa8cf87e856685e490
+ with:
+ component: TypeScript SDK
+ working-directory: sdk/typescript
+ report: sdk/typescript/coverage/lcov.info
# ESM + CJS build, the dist tests over the exact export
# list, publint and arethetypeswrong — the package must resolve for
# CommonJS consumers and bundlers before it is ever published.
- name: build + dist tests + publint + attw
working-directory: sdk/typescript
run: npm run check:dist
+ - name: SDK API documentation with locked tooling
+ working-directory: sdk/typescript
+ run: npm run docs
# Keep the locked 1.8 baseline above and qualify the other supported band
# against the same source, native tool runner and package exports.
- name: Claude memory tool with Anthropic 1.11
@@ -1392,11 +1566,13 @@ jobs:
- uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
with:
python-version: ${{ matrix.python }}
- - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
+ - uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0
with:
version: ${{ env.UV_VERSION }}
- name: Adapter tests and mypy --strict
- run: make test-sdk-adapters SDK_ADAPTERS_PYTHON="$(which python)" SDK_ADAPTERS_RESOLUTION="${{ matrix.lowest && 'lowest-direct' || 'highest' }}"
+ env:
+ RESOLUTION: ${{ matrix.lowest && 'lowest-direct' || 'highest' }}
+ run: make test-sdk-adapters SDK_ADAPTERS_PYTHON="$(which python)" SDK_ADAPTERS_RESOLUTION="${RESOLUTION}"
sdk-python-package:
needs: validate-ref
@@ -1426,7 +1602,7 @@ jobs:
- uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
with:
python-version: ${{ matrix.python }}
- - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
+ - uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0
with:
version: ${{ env.UV_VERSION }}
- name: Build wheel + sdist
@@ -1462,7 +1638,7 @@ jobs:
- uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
with:
python-version: ${{ matrix.python }}
- - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
+ - uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0
with:
version: ${{ env.UV_VERSION }}
- name: Build the SDK and extension distributions
diff --git a/.github/workflows/codeql-extended-scan.yml b/.github/workflows/codeql-extended-scan.yml
new file mode 100644
index 00000000000..5708e02ee0e
--- /dev/null
+++ b/.github/workflows/codeql-extended-scan.yml
@@ -0,0 +1,76 @@
+name: Scan with CodeQL extended security
+
+on:
+ workflow_call:
+ inputs:
+ publish:
+ description: Upload SARIF to GitHub Security
+ type: boolean
+ required: true
+
+jobs:
+ analyze:
+ name: CodeQL extended (${{ matrix.language }})
+ runs-on: ubuntu-24.04
+ timeout-minutes: 45
+ strategy:
+ fail-fast: false
+ matrix:
+ language: [python, javascript-typescript]
+ steps:
+ - name: Require normal logging for CodeQL
+ if: runner.debug == '1'
+ shell: bash
+ run: |
+ echo "Turn off step debugging so detailed analysis stays in GitHub Security."
+ exit 1
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+ - uses: github/codeql-action/init@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3
+ with:
+ languages: ${{ matrix.language }}
+ build-mode: none
+ dependency-caching: false
+ queries: security-extended
+ config: |
+ paths:
+ - server/
+ - sdk/typescript/src/
+ - frontend/src/
+ paths-ignore:
+ - "**/tests/**"
+ - "**/*.test.ts"
+ - "**/*.test.tsx"
+ - "**/*.test-d.ts"
+ - frontend/src/test/**
+ - id: scan
+ uses: github/codeql-action/analyze@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3
+ with:
+ category: /suite:security-extended/language:${{ matrix.language }}
+ upload: ${{ inputs.publish && 'always' || 'never' }}
+ upload-database: false
+ - name: Report findings by rule
+ shell: bash
+ env:
+ SARIF_DIR: ${{ steps.scan.outputs.sarif-output }}
+ run: |
+ test -d "$SARIF_DIR"
+ shopt -s nullglob
+ reports=("$SARIF_DIR"/*.sarif)
+ test "${#reports[@]}" -gt 0
+ for report in "${reports[@]}"; do
+ jq -s -e '
+ length == 1 and
+ (.[0].runs | type == "array" and length > 0 and all(.[];
+ type == "object" and
+ ((has("results") | not) or (.results | type == "array" and
+ all(.[]; type == "object" and (.ruleId | type) == "string")))
+ ))
+ ' "$report" >/dev/null
+ done
+ jq -s -r '
+ [.[].runs[].results[]?] as $results
+ | "Findings: \($results | length)", "",
+ ($results | group_by(.ruleId)[] | "- \(.[0].ruleId): \(length)")
+ ' "${reports[@]}" >> "$GITHUB_STEP_SUMMARY"
diff --git a/.github/workflows/codeql-extended.yml b/.github/workflows/codeql-extended.yml
new file mode 100644
index 00000000000..fe69455779b
--- /dev/null
+++ b/.github/workflows/codeql-extended.yml
@@ -0,0 +1,38 @@
+name: CodeQL extended security
+
+on:
+ pull_request:
+ branches: [main]
+ paths:
+ - .github/workflows/codeql-extended.yml
+ - .github/workflows/codeql-extended-scan.yml
+ schedule:
+ - cron: "37 4 * * 3"
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+concurrency:
+ group: ${{ github.workflow }}-${{ github.ref }}
+ cancel-in-progress: false
+
+jobs:
+ scan_pr:
+ name: Scan the pull request
+ if: github.event_name == 'pull_request'
+ permissions:
+ contents: read
+ uses: ./.github/workflows/codeql-extended-scan.yml
+ with:
+ publish: false
+
+ publish:
+ name: Publish default-branch findings
+ if: github.repository == 'ClickHouse/loom' && github.ref == 'refs/heads/main' && github.event_name != 'pull_request'
+ permissions:
+ contents: read
+ security-events: write # Upload default-branch SARIF to GitHub Security.
+ uses: ./.github/workflows/codeql-extended-scan.yml
+ with:
+ publish: true
diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml
index 398b68fb541..f99597f1a04 100644
--- a/.github/workflows/codeql.yml
+++ b/.github/workflows/codeql.yml
@@ -31,7 +31,7 @@ jobs:
timeout-minutes: 45
permissions:
contents: read
- security-events: write
+ security-events: write # Upload CodeQL results.
strategy:
fail-fast: false
matrix:
@@ -61,3 +61,265 @@ jobs:
- uses: github/codeql-action/analyze@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3
with:
category: /language:${{ matrix.language }}
+
+ analyze_sdks:
+ name: codeql SDK (${{ matrix.language }})
+ defaults:
+ run:
+ shell: bash
+ runs-on: ubuntu-24.04
+ timeout-minutes: 30
+ permissions:
+ contents: read
+ security-events: write # Upload the SDK CodeQL results.
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - language: go
+ database: go
+ build_mode: manual
+ checkout: sdk/go
+ source: sdk/go
+ suffix: ".go"
+ anchor: sdk/go/client.go
+ bundle_url: https://github.com/github/codeql-action/releases/download/codeql-bundle-v2.27.4/codeql-bundle-go-linux64.tar.zst
+ bundle_sha256: d79b33f86ec8b20af73d3456041349a2780c1081ee8c0eca624b9a25c5cb2e15
+ - language: ruby
+ database: ruby
+ build_mode: none
+ checkout: sdk/ruby
+ source: sdk/ruby/lib
+ suffix: ".rb"
+ anchor: sdk/ruby/lib/clickhouse/loom/client.rb
+ bundle_url: https://github.com/github/codeql-action/releases/download/codeql-bundle-v2.27.4/codeql-bundle-ruby-linux64.tar.zst
+ bundle_sha256: ab3a5abb89263a92a2e8b299dbb786c9f9d7b46593ba2d94c0ff63d8aadb9a15
+ - language: rust
+ database: rust
+ build_mode: none
+ checkout: sdk/rust
+ source: sdk/rust/src
+ suffix: ".rs"
+ anchor: sdk/rust/src/client.rs
+ bundle_url: https://github.com/github/codeql-action/releases/download/codeql-bundle-v2.27.4/codeql-bundle-rust-linux64.tar.zst
+ bundle_sha256: 1c2f867094b80e43c9a0e511090e57e0ea3bf107600b4b3763c52b9020b4ec4b
+ - language: java-kotlin
+ database: java
+ build_mode: none
+ checkout: sdk/java
+ source: sdk/java/src/main
+ suffix: ".java"
+ anchor: sdk/java/src/main/java/com/clickhouse/loom/LoomClient.java
+ bundle_url: https://github.com/github/codeql-action/releases/download/codeql-bundle-v2.27.4/codeql-bundle-java-linux64.tar.zst
+ bundle_sha256: dbeb8e2f4454bf4aad35fe16d8770dcc4a4ce0c3585d8952d57e41905396aff8
+ - language: csharp
+ database: csharp
+ build_mode: none
+ checkout: sdk/dotnet
+ source: sdk/dotnet/src/ClickHouse.Loom
+ suffix: ".cs"
+ anchor: sdk/dotnet/src/ClickHouse.Loom/LoomClient.cs
+ bundle_url: https://github.com/github/codeql-action/releases/download/codeql-bundle-v2.27.4/codeql-bundle-csharp-linux64.tar.zst
+ bundle_sha256: b991d23f6bc44fa34f81d0d4ba159a331f31c2a7f4ff5d53778ed0a19a0b48aa
+ env:
+ SDK_SOURCE: ${{ matrix.source }}
+ SDK_SUFFIX: ${{ matrix.suffix }}
+ SDK_ANCHOR: ${{ matrix.anchor }}
+ SDK_DATABASE: ${{ matrix.database }}
+ steps:
+ - name: Check out only the selected SDK
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+ sparse-checkout: ${{ matrix.checkout }}
+ - name: Require nonzero tracked SDK source before extraction
+ run: |
+ python3 - <<'PYCODE'
+ import hashlib, json, os, subprocess
+ from pathlib import Path
+ root, suffix = os.environ["SDK_SOURCE"], os.environ["SDK_SUFFIX"]
+ names = subprocess.check_output(["git", "ls-files", "--", root], text=True).splitlines()
+ names = [name for name in names if name.endswith(suffix) and not name.endswith("_test.go")]
+ assert 0 < len(names) <= 10000 and os.environ["SDK_ANCHOR"] in names
+ if os.environ["SDK_DATABASE"] == "java":
+ assert not list(Path(root).rglob("*.kt")), "Kotlin requires a built extraction path"
+ expected = {}
+ total = 0
+ for name in names:
+ path = Path(name)
+ assert not path.is_symlink() and path.is_file()
+ size = path.stat().st_size
+ assert 0 < size <= 2 * 1024 * 1024
+ total += size
+ assert total <= 20 * 1024 * 1024
+ expected[str(path.resolve()).lstrip("/")] = hashlib.sha256(path.read_bytes()).hexdigest()
+ destination = Path(os.environ["RUNNER_TEMP"]) / "sdk-codeql-source.json"
+ destination.write_text(json.dumps(expected))
+ print("Tracked production SDK source files:", len(expected))
+ PYCODE
+ - name: Download the pinned per-language analysis bundle
+ env:
+ BUNDLE_URL: ${{ matrix.bundle_url }}
+ BUNDLE_SHA256: ${{ matrix.bundle_sha256 }}
+ run: |
+ curl --fail --location --proto '=https' --tlsv1.2 --max-time 120 --max-filesize 335544320 \
+ "$BUNDLE_URL" --output "$RUNNER_TEMP/sdk-codeql.tar.zst"
+ printf '%s %s\n' "$BUNDLE_SHA256" "$RUNNER_TEMP/sdk-codeql.tar.zst" | sha256sum --check -
+ - name: Install the supported Go compiler for traced extraction
+ if: matrix.language == 'go'
+ uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0
+ with:
+ go-version: "1.27.4"
+ cache: false
+ - name: Install the Java SDK's declared JDK
+ if: matrix.language == 'java-kotlin'
+ uses: actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # v6.3.0
+ with:
+ distribution: temurin
+ java-version: "17"
+ - name: Initialize the selected SDK analysis
+ uses: github/codeql-action/init@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3
+ with:
+ languages: ${{ matrix.language }}
+ tools: ${{ runner.temp }}/sdk-codeql.tar.zst
+ db-location: ${{ runner.temp }}/sdk-codeql-databases
+ build-mode: ${{ matrix.build_mode }}
+ dependency-caching: false
+ config: |
+ paths:
+ - ${{ matrix.source }}
+ paths-ignore:
+ - "**/tests/**"
+ - "**/*_test.go"
+ - name: Build the Go SDK under the extractor
+ if: matrix.language == 'go'
+ working-directory: sdk/go
+ env:
+ GOTOOLCHAIN: local
+ run: go build ./...
+ - name: Analyze and upload security results
+ uses: github/codeql-action/analyze@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3
+ with:
+ category: /language:${{ matrix.language }}
+ # Generated Rust models need more memory during TRAP import.
+ ram: ${{ matrix.language == 'rust' && 6144 || 2048 }}
+ threads: 2
+ - name: Require actual SDK bytes in the extracted source archive
+ run: |
+ python3 - <<'PYCODE'
+ import hashlib, json, os, zipfile
+ from pathlib import Path
+ directory = Path(os.environ["RUNNER_TEMP"])
+ expected = json.loads((directory / "sdk-codeql-source.json").read_text())
+ archive = directory / "sdk-codeql-databases" / os.environ["SDK_DATABASE"] / "src.zip"
+ assert archive.is_file() and archive.stat().st_size <= 100 * 1024 * 1024
+ matched = set()
+ with zipfile.ZipFile(archive) as source:
+ entries = source.infolist()
+ assert len(entries) <= 100000
+ total = 0
+ for entry in entries:
+ name = entry.filename.lstrip("/")
+ if name not in expected:
+ continue
+ assert entry.file_size <= 2 * 1024 * 1024
+ total += entry.file_size
+ assert total <= 20 * 1024 * 1024
+ assert hashlib.sha256(source.read(entry)).hexdigest() == expected[name]
+ matched.add(name)
+ anchor = str((Path(os.environ["GITHUB_WORKSPACE"]) / os.environ["SDK_ANCHOR"]).resolve()).lstrip("/")
+ assert matched and anchor in matched, "The extracted archive contains no SDK client"
+ with open(os.environ["GITHUB_STEP_SUMMARY"], "a") as output:
+ output.write(f"CodeQL 2.27.4 extracted {len(matched)} matching production SDK source files, including the client. Archive bytes match the checkout. This is source-presence evidence, not complete query coverage or a security-clean result.\n")
+ PYCODE
+
+ maintenance:
+ name: Record trusted SDK static analysis failures
+ concurrency:
+ group: sdk-codeql-maintenance
+ cancel-in-progress: false
+ needs: [analyze_sdks]
+ if: >-
+ always() && github.repository == 'ClickHouse/loom' &&
+ github.ref == 'refs/heads/main' &&
+ (github.event_name == 'push' || github.event_name == 'schedule')
+ runs-on: ubuntu-24.04
+ timeout-minutes: 5
+ permissions:
+ contents: read
+ issues: write # Record SDK static analysis failures on trusted main runs only.
+ steps:
+ - name: Reconcile failure tasks without executing project code
+ env:
+ GH_TOKEN: ${{ github.token }}
+ CODEQL_RESULTS: ${{ toJSON(needs) }}
+ run: |
+ python3 - <<'PY'
+ import json, os, re, subprocess
+ from urllib.parse import urlencode
+ repo = "repos/ClickHouse/loom/issues"
+ bot = "github-actions[bot]"
+ marker = re.compile(r"")
+ state = re.compile(r"")
+ titles = {"analyze_sdks": "[sdk-codeql-ci] Restore SDK static analysis"}
+ calls = 0
+ def api(method, endpoint, payload=None):
+ global calls
+ calls += 1
+ assert calls <= 40, "SDK static analysis issue API budget exhausted"
+ command = ["gh", "api", "--method", method, endpoint, "--hostname", "github.com"]
+ if payload is not None:
+ command += ["--input", "-"]
+ result = subprocess.run(command, input=None if payload is None else json.dumps(payload), text=True, capture_output=True, timeout=20, check=True)
+ assert len(result.stdout) <= 2 * 1024 * 1024, "SDK static analysis issue response exceeds budget"
+ return json.loads(result.stdout)
+ managed = {}
+ for page in range(1, 11):
+ issues = api("GET", repo + "?" + urlencode({"state": "all", "creator": bot, "per_page": 100, "page": page}))
+ assert isinstance(issues, list)
+ for issue in issues:
+ if "pull_request" in issue or issue.get("user", {}).get("login") != bot:
+ continue
+ keys = marker.findall(issue.get("body") or "")
+ keys += [key for key, title in titles.items() if issue.get("title") == title]
+ keys = set(keys)
+ assert len(keys) <= 1, "Conflicting SDK static analysis issue markers"
+ if keys:
+ key = keys.pop()
+ assert key not in managed, "Duplicate SDK static analysis task"
+ managed[key] = issue
+ if len(issues) < 100:
+ break
+ else:
+ raise RuntimeError("SDK static analysis issue pagination budget exhausted")
+ results = json.loads(os.environ["CODEQL_RESULTS"])
+ assert set(results) == set(titles)
+ run_id = os.environ["GITHUB_RUN_ID"]
+ assert run_id.isdecimal()
+ url = "https://github.com/ClickHouse/loom/actions/runs/" + run_id
+ changed = 0
+ for key in titles:
+ result = results[key]["result"]
+ assert result in {"success", "failure", "cancelled", "skipped"}
+ issue = managed.get(key)
+ if result not in {"success", "failure"} or (issue and issue["state"] == "closed"):
+ continue
+ text = f"\n\n\n### Company or project name\n\nClickHouse\n\nThe bounded SDK static analysis check reports **{result}** on trusted main. [Read the selected SDK extraction and analysis logs]({url}).\n\nReproduce the SDK static analysis workflow using synthetic data. Keep security-sensitive reports in the private route in SECURITY.md. Automation preserves edited bodies and closed decisions for recognized tasks. Keep the original title or the tracking marker in the body so later runs can identify this task."
+ if issue is None:
+ if result == "failure":
+ api("POST", repo, {"title": titles[key], "body": text})
+ changed += 1
+ continue
+ number = issue["number"]
+ assert isinstance(number, int) and number > 0
+ comments = api("GET", f"{repo}/{number}/comments?per_page=100")
+ assert isinstance(comments, list) and len(comments) < 100, "SDK static analysis comment history budget exhausted"
+ candidates = [issue] + sorted(comments, key=lambda row: (row["created_at"], row["id"]))
+ states = [state.findall(row.get("body") or "") for row in candidates if row.get("user", {}).get("login") == bot]
+ states = [value[-1] for value in states if value]
+ if not states or states[-1] != result:
+ api("POST", f"{repo}/{number}/comments", {"body": text})
+ changed += 1
+ with open(os.environ["GITHUB_STEP_SUMMARY"], "a") as output:
+ output.write(f"SDK static analysis task reconciliation: {changed} task or status writes; closed decisions preserved.\n")
+ PY
diff --git a/.github/workflows/contributor-lab.yml b/.github/workflows/contributor-lab.yml
index 6a3792f8aec..d19ac3a72e3 100644
--- a/.github/workflows/contributor-lab.yml
+++ b/.github/workflows/contributor-lab.yml
@@ -117,8 +117,17 @@ jobs:
output.write("| Track | Checks/tests | Passed |\n| --- | ---: | --- |\n")
for row in rows:
name, count, passed = row["track"], row.get("tests", row.get("checks")), row["passed"]
- assert name in allowed and type(count) is int and 0 < count <= 100000 and type(passed) is bool
- output.write(f"| {name} | {count} | {passed} |\n")
+ assert name in allowed and type(passed) is bool
+ error = row.get("error")
+ if error is not None:
+ assert error in ("timeout", "missing report", "invalid report")
+ assert count is None and passed is False
+ count, result = "unknown", f"False ({error})"
+ else:
+ assert type(count) is int and 0 <= count <= 100000
+ assert count > 0 or passed is False
+ result = str(passed)
+ output.write(f"| {name} | {count} | {result} |\n")
PY
- name: Remove exactly the container created by this run
if: always()
diff --git a/.github/workflows/dify-plugin.yml b/.github/workflows/dify-plugin.yml
index c63c5658ab6..398e66fe348 100644
--- a/.github/workflows/dify-plugin.yml
+++ b/.github/workflows/dify-plugin.yml
@@ -20,8 +20,13 @@ on:
permissions:
contents: read
+concurrency:
+ group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.ref || github.sha }}
+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}
+
jobs:
check:
+ name: Check the Dify plugin
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
@@ -60,7 +65,7 @@ jobs:
- uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
with:
python-version: "3.12"
- - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
+ - uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0
with:
version: "0.12.19"
enable-cache: false
diff --git a/.github/workflows/docker-smoke.yml b/.github/workflows/docker-smoke.yml
index e7352789ae6..25b40f640e7 100644
--- a/.github/workflows/docker-smoke.yml
+++ b/.github/workflows/docker-smoke.yml
@@ -139,8 +139,7 @@ jobs:
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: "22"
- cache: npm
- cache-dependency-path: frontend/package-lock.json
+ package-manager-cache: false
- name: Install dashboard browser-test dependencies
working-directory: frontend
run: |
diff --git a/.github/workflows/docs-site.yml b/.github/workflows/docs-site.yml
index ff35d3117f4..d1e1c5914ab 100644
--- a/.github/workflows/docs-site.yml
+++ b/.github/workflows/docs-site.yml
@@ -1,10 +1,6 @@
name: docs site
-# Builds the documentation site from docs/ on pull requests that touch it and on every push
-# to main, and publishes it to GitHub Pages from main once the repository variable
-# DOCS_SITE_ENABLED is "true" (set it after Pages is switched to "GitHub Actions" in
-# Settings → Pages). Until then the deploy job is skipped, so main stays green. After a
-# deploy, the pages the push changed are submitted to IndexNow (scripts/docs_site/indexnow.py).
+# Publishes legacy redirects and submits changed site URLs after production deploys.
on:
push:
branches: [main]
@@ -33,6 +29,9 @@ jobs:
name: build
runs-on: ubuntu-latest
timeout-minutes: 15
+ permissions:
+ contents: read
+ pages: read # Read the base URL used by the legacy Markdown copies.
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
@@ -43,8 +42,16 @@ jobs:
- name: Install the site builder
run: |
python -m pip install --require-hashes --no-deps --only-binary=:all: -r scripts/docs_site/requirements.txt
- - name: Build
- run: mkdocs build --strict
+ - if: github.ref == 'refs/heads/main' && vars.DOCS_SITE_ENABLED == 'true'
+ name: Read the legacy Pages URL
+ id: pages
+ uses: actions/configure-pages@45bfe0192ca1faeb007ade9deae92b16b8254a0d # v6.0.0
+ - name: Build legacy documentation redirects
+ env:
+ LOOM_LEGACY_DOCS_URL: ${{ steps.pages.outputs.base_url || 'https://loom.clickhouse.com/docs' }}/
+ run: |
+ mkdocs build --strict
+ python -m scripts.docs_site.redirect_pages site "$LOOM_LEGACY_DOCS_URL"
- if: github.event_name != 'pull_request'
uses: actions/upload-pages-artifact@fc324d3547104276b827a68afc52ff2a11cc49c9 # v5.0.0
with:
@@ -57,8 +64,8 @@ jobs:
runs-on: ubuntu-latest
timeout-minutes: 10
permissions:
- pages: write
- id-token: write
+ pages: write # Deploy the built Pages artifact.
+ id-token: write # Authenticate the Pages deployment.
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
@@ -68,14 +75,12 @@ jobs:
indexnow:
name: indexnow
- needs: deploy
+ if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
- timeout-minutes: 5
- # A failed submission only delays indexing; it must not mark the deploy failed.
- continue-on-error: true
+ timeout-minutes: 8
permissions:
contents: read
- actions: read # to find the last successful run, below
+ actions: read # Find an earlier submission that succeeded.
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
@@ -84,17 +89,62 @@ jobs:
- uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
with:
python-version: "3.12"
- - name: Submit the pages changed since the last successful run
+ - name: Submit changed pages after the production deployment
shell: bash
env:
GH_TOKEN: ${{ github.token }}
run: |
set -euo pipefail
- # A push can carry several commits, and a pending run can be cancelled by a newer
- # one, so diff from the last successful run on main. Fall back to HEAD~1 when
- # there is none or it isn't an ancestor of HEAD. A run counts as successful even
- # when its submission failed or the deploy was off, and those pages aren't resent.
- base=$(gh run list -R "$GITHUB_REPOSITORY" --workflow docs-site.yml --branch main \
- --event push --status success --limit 1 --json headSha --jq '.[0].headSha // empty')
- if [ -z "$base" ] || ! git merge-base --is-ancestor "$base" HEAD; then base=HEAD~1; fi
- git diff -z --name-only --no-renames "$base" HEAD | xargs -0 python scripts/docs_site/indexnow.py
+ # Legacy redirect publication has its own result. Only a successful IndexNow
+ # job advances the comparison point so the next run covers a failed submission.
+ base=
+ page=1
+ while [[ -z "$base" ]]; do
+ runs=$(gh api "repos/$GITHUB_REPOSITORY/actions/workflows/docs-site.yml/runs?branch=main&status=completed&per_page=25&page=$page" \
+ --jq '.workflow_runs[] | [.id, .head_sha] | @tsv')
+ if [[ -z "$runs" ]]; then break; fi
+ while IFS=$'\t' read -r run commit; do
+ if ! git merge-base --is-ancestor "$commit" HEAD; then continue; fi
+ submitted=$(gh api "repos/$GITHUB_REPOSITORY/actions/runs/$run/jobs" \
+ --jq 'any(.jobs[]; .name == "indexnow" and .conclusion == "success")')
+ if [[ "$submitted" == true ]]; then
+ base="$commit"
+ break
+ fi
+ done <<< "$runs"
+ page=$((page + 1))
+ done
+
+ changed="$RUNNER_TEMP/indexnow-changes"
+ if [[ -n "$base" ]]; then
+ git diff -z --name-status --no-renames "$base" HEAD > "$changed"
+ else
+ # Without a recent checkpoint, submit the canonical site as a single batch.
+ printf '%s\0' M docs/blume.config.ts > "$changed"
+ fi
+ routes=docs/scripts/public-pages.json
+ previous_routes="$RUNNER_TEMP/indexnow-previous-public-pages.json"
+ if [[ -n "$base" ]] && git cat-file -e "$base:$routes" 2>/dev/null; then
+ git show "$base:$routes" > "$previous_routes"
+ else
+ printf '{}\n' > "$previous_routes"
+ fi
+ urls=$(python scripts/docs_site/indexnow.py --list --previous-public-pages "$previous_routes" --changes-file "$changed")
+ if [[ -z "$urls" ]]; then
+ echo 'indexnow: no public page changed'
+ exit 0
+ fi
+
+ # Read the revision from the live site. Preview and production deployments
+ # share the same GitHub commit status.
+ for attempt in {1..25}; do
+ deployed=$(curl -fsS --max-time 4 \
+ "https://loom.clickhouse.com/.well-known/loom-revision.txt?commit=$GITHUB_SHA&attempt=$attempt") || deployed=
+ if [[ "$deployed" == "$GITHUB_SHA" ]]; then
+ python scripts/docs_site/indexnow.py --previous-public-pages "$previous_routes" --changes-file "$changed"
+ exit 0
+ fi
+ sleep 10
+ done
+ echo 'indexnow: production deployment was not confirmed' >&2
+ exit 1
diff --git a/.github/workflows/external-links.yml b/.github/workflows/external-links.yml
new file mode 100644
index 00000000000..5d7551656d7
--- /dev/null
+++ b/.github/workflows/external-links.yml
@@ -0,0 +1,96 @@
+name: External documentation links
+
+on:
+ pull_request:
+ branches: [main]
+ paths:
+ - ".github/workflows/external-links.yml"
+ push:
+ branches: [main]
+ paths:
+ - ".github/workflows/external-links.yml"
+ schedule:
+ - cron: "23 7 * * 3"
+
+permissions:
+ contents: read
+
+jobs:
+ external-links:
+ if: github.repository == 'ClickHouse/loom'
+ runs-on: ubuntu-24.04
+ timeout-minutes: 10
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+ sparse-checkout: |
+ docs
+ sdk
+ - name: Install Lychee
+ working-directory: ${{ runner.temp }}
+ run: |
+ archive=lychee-x86_64-unknown-linux-gnu.tar.gz
+ curl --fail --silent --show-error --location --proto '=https' --tlsv1.2 \
+ "https://github.com/lycheeverse/lychee/releases/download/lychee-v0.24.2/$archive" -o "$archive"
+ echo "1f4e0ef7f6554a6ed33dd7ac144fb2e1bbed98598e7af973042fc5cd43951c9a $archive" | sha256sum --check --strict
+ tar -xzf "$archive" --strip-components=1 lychee-x86_64-unknown-linux-gnu/lychee
+ - name: Verify the link inventory on workflow changes
+ if: github.event_name == 'pull_request'
+ run: |
+ "$RUNNER_TEMP/lychee" --scheme https --scheme http --exclude-all-private \
+ --dump README.md CONTRIBUTING.md 'docs/getting-started/**/*.md' 'sdk/*/README.md' \
+ > "$RUNNER_TEMP/links.txt"
+ test -s "$RUNNER_TEMP/links.txt"
+ - name: Read the trusted documentation on workflow pull requests
+ if: github.event_name == 'pull_request'
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ ref: ${{ github.event.pull_request.base.sha }}
+ path: link-baseline
+ persist-credentials: false
+ sparse-checkout: |
+ docs
+ sdk
+ - name: Verify VS Code install redirects
+ working-directory: ${{ github.event_name == 'pull_request' && 'link-baseline' || '.' }}
+ run: |
+ python3 - <<'PYTHON'
+ import re
+ import subprocess
+ from pathlib import Path
+ from urllib.parse import parse_qs, urlsplit
+
+ readme = Path("README.md").read_text()
+ for link in re.findall(r"https://(?:insiders\.)?vscode\.dev/redirect\?url=[^\s)>]+", readme):
+ parts = urlsplit(link)
+ target, = parse_qs(parts.query)["url"]
+ app = "vscode-insiders" if parts.hostname == "insiders.vscode.dev" else "vscode"
+ if not target.startswith(f"{app}:mcp/install?"):
+ raise SystemExit(f"Install link has the wrong application target: {link}")
+ status, location = subprocess.check_output(
+ ["curl", "--proto", "=https", "--tlsv1.2", "--silent", "--show-error",
+ "--max-time", "10", "--output", "/dev/null",
+ "--write-out", "%{http_code}\n%{redirect_url}", link],
+ text=True,
+ ).split("\n", 1)
+ if status != "302" or location != target:
+ raise SystemExit(f"Install redirect returned the wrong status or destination: {link}")
+ PYTHON
+ - name: Check public documentation URLs
+ working-directory: ${{ github.event_name == 'pull_request' && 'link-baseline' || '.' }}
+ run: |
+ "$RUNNER_TEMP/lychee" --scheme https --scheme http --exclude-all-private \
+ --exclude '^https?://([^/]+\.)?example\.(com|org|net)([:/]|$)' \
+ --exclude '^https://(insiders\.)?vscode\.dev/redirect\?url=' \
+ --remap '^https://www[.]npmjs[.]com/package/@clickhouse/loom$ https://registry.npmjs.org/@clickhouse/loom/latest' \
+ --exclude '^https?://localhost([:/]|$)' --max-concurrency 8 \
+ --timeout 10 --max-retries 1 --no-progress --format markdown \
+ --output "$RUNNER_TEMP/external-links.md" \
+ README.md CONTRIBUTING.md 'docs/getting-started/**/*.md' 'sdk/*/README.md'
+ - name: Report the checked links
+ if: "!cancelled()"
+ run: |
+ if [ -f "$RUNNER_TEMP/external-links.md" ]; then
+ cat "$RUNNER_TEMP/external-links.md" >> "$GITHUB_STEP_SUMMARY"
+ fi
diff --git a/.github/workflows/go-api.yml b/.github/workflows/go-api.yml
new file mode 100644
index 00000000000..c8fd1d7d9bd
--- /dev/null
+++ b/.github/workflows/go-api.yml
@@ -0,0 +1,47 @@
+name: Go SDK API compatibility
+
+on:
+ pull_request:
+ branches: [main, "release/**"]
+ paths:
+ - "sdk/go/**"
+ - ".github/workflows/go-api.yml"
+ push:
+ branches: [main]
+ paths:
+ - "sdk/go/**"
+ - ".github/workflows/go-api.yml"
+
+permissions:
+ contents: read
+
+jobs:
+ go-api:
+ runs-on: ubuntu-24.04
+ timeout-minutes: 10
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ # The SDK source shipped with Loom v1.3.0.
+ ref: 47b479dcdae4c089aef2690428fa4c9a8f54554c
+ path: release-baseline
+ persist-credentials: false
+ sparse-checkout: sdk/go
+ - uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6
+ with:
+ go-version: "1.26.x"
+ cache: false
+ - name: Check for incompatible exported API changes
+ run: |
+ GOBIN="$RUNNER_TEMP" go install golang.org/x/exp/cmd/apidiff@e1094eeca1b508317bb24413555d977dea6bb30c
+ module=github.com/ClickHouse/loom/sdk/go
+ (cd release-baseline/sdk/go && "$RUNNER_TEMP/apidiff" -m -w "$RUNNER_TEMP/old.api" "$module")
+ (cd sdk/go && "$RUNNER_TEMP/apidiff" -m -w "$RUNNER_TEMP/new.api" "$module")
+ changes=$("$RUNNER_TEMP/apidiff" -m -incompatible "$RUNNER_TEMP/old.api" "$RUNNER_TEMP/new.api")
+ if [ -n "$changes" ]; then
+ printf '%s\n' "$changes"
+ exit 1
+ fi
diff --git a/.github/workflows/help-wanted-label.yml b/.github/workflows/help-wanted-label.yml
index 7affb1cffa7..593ad7877e5 100644
--- a/.github/workflows/help-wanted-label.yml
+++ b/.github/workflows/help-wanted-label.yml
@@ -3,8 +3,8 @@ name: contributor label policy
on:
issues:
types: [opened, reopened, labeled]
- pull_request_target:
- types: [opened, reopened, labeled]
+ schedule:
+ - cron: "13,43 * * * *"
workflow_dispatch:
inputs:
issue_number:
@@ -15,7 +15,7 @@ on:
permissions: {}
concurrency:
- group: ${{ github.workflow }}-${{ github.event.issue.number || github.event.pull_request.number || inputs.issue_number }}
+ group: ${{ github.workflow }}-${{ github.event.issue.number || inputs.issue_number || 'pull-requests' }}
cancel-in-progress: false
jobs:
@@ -27,25 +27,38 @@ jobs:
permissions:
issues: write # The additive labels endpoint also handles pull requests.
steps:
- # Trusted inline metadata processing only; never check out pull request code.
- name: Add the contributor discovery label when needed
env:
GH_TOKEN: ${{ github.token }}
GH_HOST: github.com
- ITEM_NUMBER: ${{ github.event.issue.number || github.event.pull_request.number || inputs.issue_number }}
+ ITEM_NUMBER: ${{ github.event.issue.number || inputs.issue_number }}
shell: bash
run: |
- if ! [[ "$ITEM_NUMBER" =~ ^[1-9][0-9]{0,9}$ ]]; then
- echo "A positive issue or pull request number is required." >&2
- exit 1
- fi
- issue_path="repos/ClickHouse/loom/issues/$ITEM_NUMBER"
- current=$(timeout 30s gh api "$issue_path" --jq '[.labels[].name]')
- jq -e 'type == "array" and all(.[]; type == "string")' <<< "$current" >/dev/null
- if jq -e 'index("help wanted") != null and index("up-for-grabs") == null' <<< "$current" >/dev/null; then
- printf '%s\n' '{"labels":["up-for-grabs"]}' |
- timeout 30s gh api "$issue_path/labels" --method POST --input - >/dev/null
- echo "Added up-for-grabs."
+ mirror_label() {
+ local number="$1" issue_path current
+ if ! [[ "$number" =~ ^[1-9][0-9]{0,9}$ ]]; then
+ echo "A positive issue or pull request number is required." >&2
+ exit 1
+ fi
+ issue_path="repos/ClickHouse/loom/issues/$number"
+ current=$(timeout 30s gh api "$issue_path" --jq '[.labels[].name]')
+ jq -e 'type == "array" and all(.[]; type == "string")' <<< "$current" >/dev/null
+ if jq -e 'index("help wanted") != null and index("up-for-grabs") == null' <<< "$current" >/dev/null; then
+ printf '%s\n' '{"labels":["up-for-grabs"]}' |
+ timeout 30s gh api "$issue_path/labels" --method POST --input - >/dev/null
+ echo "Added up-for-grabs."
+ else
+ echo "No label addition is needed."
+ fi
+ }
+ if [ "$GITHUB_EVENT_NAME" = schedule ]; then
+ pending=$(timeout 2m gh api 'repos/ClickHouse/loom/issues?state=open&labels=help%20wanted&per_page=100' --paginate \
+ --jq '.[] | select(has("pull_request") and ([.labels[].name] | index("up-for-grabs") == null)) | .number')
+ if [ -n "$pending" ]; then
+ while IFS= read -r number; do
+ mirror_label "$number"
+ done <<< "$pending"
+ fi
else
- echo "No label addition is needed."
+ mirror_label "$ITEM_NUMBER"
fi
diff --git a/.github/workflows/http-contract.yml b/.github/workflows/http-contract.yml
new file mode 100644
index 00000000000..c805b2acfb4
--- /dev/null
+++ b/.github/workflows/http-contract.yml
@@ -0,0 +1,188 @@
+name: HTTP schema contract
+
+on:
+ workflow_dispatch:
+ pull_request:
+ branches: [main, "release/**"]
+ paths:
+ - server/transport/**
+ - server/auth/**
+ - server/memory/api/models_blacklist.py
+ - server/memory/app/blacklist.py
+ - tests/contracts/**
+ - pyproject.toml
+ - uv.lock
+ - .github/workflows/http-contract.yml
+ push:
+ branches: [main]
+ paths:
+ - server/transport/**
+ - server/auth/**
+ - server/memory/api/models_blacklist.py
+ - server/memory/app/blacklist.py
+ - tests/contracts/**
+ - pyproject.toml
+ - uv.lock
+ - .github/workflows/http-contract.yml
+ schedule:
+ - cron: "47 5 * * 4"
+
+permissions:
+ contents: read
+
+defaults:
+ run:
+ shell: bash
+
+concurrency:
+ group: http-contract-${{ github.ref }}
+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}
+
+jobs:
+ contract:
+ name: Bounded synthetic HTTP schema and authorization
+ runs-on: ubuntu-24.04
+ timeout-minutes: 10
+ env:
+ LOOM_ENV_FILE: ""
+ LOOM_LLM_PROVIDER: fake
+ LOOM_EMBEDDING_MODEL: fake-ngram-1024
+ LOOM_BACKGROUND_WORKERS: "off"
+ PYTHONDONTWRITEBYTECODE: "1"
+ steps:
+ - name: Check out the transport and exact synthetic test inputs
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+ sparse-checkout-cone-mode: false
+ sparse-checkout: |
+ /README.md
+ /LICENSE*
+ /NOTICE*
+ /pyproject.toml
+ /uv.lock
+ /.gitignore
+ /server/
+ /schemas/
+ /sdk/python/
+ /scripts/
+ /extractor/
+ /tests/__init__.py
+ /tests/_shards.py
+ /tests/conftest.py
+ /tests/unit/__init__.py
+ /tests/unit/conftest.py
+ /tests/unit/mirror_latch_fake.py
+ /tests/unit/claims_fake.py
+ /tests/unit/switch_state.py
+ /tests/contracts/
+ /.github/workflows/http-contract.yml
+ - name: Install the pinned dependency manager
+ uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0
+ with:
+ version: "0.12.19"
+ enable-cache: false
+ - name: Synchronize the locked test-only extra
+ run: uv sync --locked --python 3.12 --extra dev --extra code --extra contract
+ - name: Check the trusted publisher against a synthetic API
+ run: uv run --no-sync python tests/contracts/test_probe_publisher.py
+ - name: Check value-free contract diagnostics
+ run: python3 -m unittest tests.contracts.test_ci_diagnostics
+ - name: Generate bounded requests through the actual HTTP transport
+ run: |
+ timeout --signal=TERM --kill-after=10s 120s uv run --no-sync python -m pytest \
+ -p tests.unit.conftest -p tests.contracts.ci_diagnostics \
+ tests/contracts/test_http_schema.py -v \
+ -o cache_dir="$RUNNER_TEMP/http-contract-cache" \
+ --junitxml="$RUNNER_TEMP/http-contract.xml"
+ - name: Require actual test execution
+ if: always()
+ run: python3 tests/contracts/ci_diagnostics.py
+
+ maintenance:
+ name: Record trusted HTTP contract failures
+ needs: [contract]
+ if: >-
+ always() && github.repository == 'ClickHouse/loom' &&
+ github.ref == 'refs/heads/main' &&
+ (github.event_name == 'push' || github.event_name == 'schedule')
+ runs-on: ubuntu-24.04
+ timeout-minutes: 5
+ permissions:
+ contents: read
+ issues: write # Record HTTP contract failures on trusted main runs only.
+ steps:
+ - name: Reconcile failure tasks without executing project code
+ env:
+ GH_TOKEN: ${{ github.token }}
+ CONTRACT_RESULTS: ${{ toJSON(needs) }}
+ run: |
+ python3 - <<'PY'
+ import json, os, re, subprocess
+ from urllib.parse import urlencode
+ repo = "repos/ClickHouse/loom/issues"
+ bot = "github-actions[bot]"
+ marker = re.compile(r"")
+ state = re.compile(r"")
+ titles = {"contract": "[http-contract-ci] Restore the bounded HTTP contract checks"}
+ calls = 0
+ def api(method, endpoint, payload=None):
+ global calls
+ calls += 1
+ assert calls <= 40, "HTTP contract issue API budget exhausted"
+ command = ["gh", "api", "--method", method, endpoint, "--hostname", "github.com"]
+ if payload is not None:
+ command += ["--input", "-"]
+ result = subprocess.run(command, input=None if payload is None else json.dumps(payload), text=True, capture_output=True, timeout=20, check=True)
+ assert len(result.stdout) <= 2 * 1024 * 1024, "HTTP contract issue response exceeds budget"
+ return json.loads(result.stdout)
+ managed = {}
+ for page in range(1, 11):
+ issues = api("GET", repo + "?" + urlencode({"state": "all", "creator": bot, "per_page": 100, "page": page}))
+ assert isinstance(issues, list)
+ for issue in issues:
+ if "pull_request" in issue or issue.get("user", {}).get("login") != bot:
+ continue
+ keys = marker.findall(issue.get("body") or "")
+ keys += [key for key, title in titles.items() if issue.get("title") == title]
+ keys = set(keys)
+ assert len(keys) <= 1, "Conflicting HTTP contract issue markers"
+ if keys:
+ key = keys.pop()
+ assert key not in managed, "Duplicate HTTP contract task"
+ managed[key] = issue
+ if len(issues) < 100:
+ break
+ else:
+ raise RuntimeError("HTTP contract issue pagination budget exhausted")
+ results = json.loads(os.environ["CONTRACT_RESULTS"])
+ assert set(results) == set(titles)
+ run_id = os.environ["GITHUB_RUN_ID"]
+ assert run_id.isdecimal()
+ url = "https://github.com/ClickHouse/loom/actions/runs/" + run_id
+ changed = 0
+ for key in titles:
+ result = results[key]["result"]
+ assert result in {"success", "failure", "cancelled", "skipped"}
+ issue = managed.get(key)
+ if result not in {"success", "failure"} or (issue and issue["state"] == "closed"):
+ continue
+ text = f"\n\n\n### Company or project name\n\nClickHouse\n\nThe bounded HTTP contract check reports **{result}** on trusted main. [Read the bounded synthetic HTTP transport logs]({url}).\n\nReproduce the HTTP contract workflow using synthetic data. Keep security-sensitive reports in the private route in SECURITY.md. Automation preserves edited bodies and closed decisions for recognized tasks. Keep the original title or the tracking marker in the body so later runs can identify this task."
+ if issue is None:
+ if result == "failure":
+ api("POST", repo, {"title": titles[key], "body": text})
+ changed += 1
+ continue
+ number = issue["number"]
+ assert isinstance(number, int) and number > 0
+ comments = api("GET", f"{repo}/{number}/comments?per_page=100")
+ assert isinstance(comments, list) and len(comments) < 100, "HTTP contract comment history budget exhausted"
+ candidates = [issue] + sorted(comments, key=lambda row: (row["created_at"], row["id"]))
+ states = [state.findall(row.get("body") or "") for row in candidates if row.get("user", {}).get("login") == bot]
+ states = [value[-1] for value in states if value]
+ if not states or states[-1] != result:
+ api("POST", f"{repo}/{number}/comments", {"body": text})
+ changed += 1
+ with open(os.environ["GITHUB_STEP_SUMMARY"], "a") as output:
+ output.write(f"HTTP contract task reconciliation: {changed} task or status writes; closed decisions preserved.\n")
+ PY
diff --git a/.github/workflows/i18n.yml b/.github/workflows/i18n.yml
index 9e61a83ada2..1fcda7179f2 100644
--- a/.github/workflows/i18n.yml
+++ b/.github/workflows/i18n.yml
@@ -13,12 +13,9 @@ on:
- "scripts/docs_site/indexnow.py"
- "scripts/docs_site/paths.py"
- ".github/workflows/i18n.yml"
- workflow_run:
- workflows: [ci]
- types: [completed]
- branches: [i18n/update]
schedule:
- cron: "37 */6 * * *"
+ - cron: "11,26,41,56 * * * *" # Finalize batches after hosted CI passes.
workflow_dispatch:
inputs:
all:
@@ -36,30 +33,41 @@ permissions:
concurrency:
group: ${{ github.workflow }}
cancel-in-progress: false
+ queue: max
jobs:
update:
name: update
- if: github.ref == 'refs/heads/main' && contains(fromJSON('["push","schedule","workflow_dispatch"]'), github.event_name) && vars.LOOM_I18N_RUNNER != ''
+ needs: finalize
+ if: >-
+ !cancelled() && github.ref == 'refs/heads/main' && vars.LOOM_I18N_RUNNER != '' &&
+ (github.event_name == 'push' || github.event_name == 'workflow_dispatch' ||
+ (github.event_name == 'schedule' && github.event.schedule == '37 */6 * * *'))
runs-on: ${{ fromJSON(vars.LOOM_I18N_RUNNER) }}
timeout-minutes: 45
# Environment and runner-group restrictions admit this main-only workflow.
environment: i18n
permissions:
- actions: write
- contents: write
- pull-requests: write
+ actions: write # Dispatch CI for the generated commit.
+ contents: write # Write budget and generated branch commits.
+ pull-requests: write # Open or update the generated pull request.
env:
LOOM_I18N_LANGUAGES: ${{ vars.LOOM_I18N_LANGUAGES }}
LOOM_I18N_BATCH_LANGUAGES: ${{ inputs.languages }}
+ GIT_CONFIG_COUNT: "2"
+ GIT_CONFIG_KEY_0: credential.https://github.com.helper
+ GIT_CONFIG_VALUE_0: ""
+ GIT_CONFIG_KEY_1: credential.https://github.com.helper
+ GIT_CONFIG_VALUE_1: "!gh auth git-credential"
defaults:
run:
shell: bash
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
- ref: ${{ github.sha }}
+ ref: main
fetch-depth: 0
+ persist-credentials: false
- uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
with:
python-version: "3.12"
@@ -69,41 +77,44 @@ jobs:
python -m venv "$RUNNER_TEMP/i18n"
"$RUNNER_TEMP/i18n/bin/python" -m pip install --quiet --require-hashes --no-deps \
--only-binary=:all: -r scripts/i18n/requirements.txt
- echo "$RUNNER_TEMP/i18n/bin" >> "$GITHUB_PATH"
- name: Preserve verified pending pages
id: prepare
- run: python -m scripts.i18n.automation prepare
+ run: |
+ "$RUNNER_TEMP/i18n/bin/python" -m scripts.i18n.automation prepare
- name: Translate a bounded batch
id: translate
env:
+ GH_TOKEN: ${{ github.token }} # Write the budget ledger before calling the provider.
LOOM_I18N_TOTAL_USD: ${{ vars.LOOM_I18N_TOTAL_USD || '0' }}
ALL: ${{ inputs.all }}
run: |
export AWS_REGION="${AWS_REGION:-${AWS_DEFAULT_REGION:-us-east-1}}"
args=()
if [ "$ALL" = "true" ]; then args+=(--all); fi
- python -m scripts.i18n.automation update "${args[@]}" 2>&1 | tee -a "$GITHUB_STEP_SUMMARY"
+ "$RUNNER_TEMP/i18n/bin/python" -m scripts.i18n.automation update "${args[@]}" 2>&1 | tee -a "$GITHUB_STEP_SUMMARY"
- name: Validate and publish for hosted CI
if: ${{ !cancelled() && steps.prepare.outcome == 'success' && steps.translate.outcome != 'skipped' }}
env:
GH_TOKEN: ${{ github.token }}
LOOM_I18N_PENDING_SHA: ${{ steps.prepare.outputs.pending_sha }}
- run: python -m scripts.i18n.automation publish
+ run: |
+ "$RUNNER_TEMP/i18n/bin/python" -m scripts.i18n.automation publish
finalize:
name: merge validated translations
- if: github.ref == 'refs/heads/main' && (github.event_name == 'schedule' || (github.event_name == 'workflow_run' && github.event.workflow_run.event == 'workflow_dispatch'))
+ if: github.ref == 'refs/heads/main' && github.event_name == 'schedule'
runs-on: ubuntu-latest
timeout-minutes: 10
permissions:
- actions: write
- contents: write
- pull-requests: write
+ actions: write # Dispatch the docs deployment after merge.
+ contents: write # Write the validated squash merge to main.
+ pull-requests: write # Squash-merge the validated translation pull request.
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: main
fetch-depth: 0
+ persist-credentials: false
- uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
with:
python-version: "3.12"
diff --git a/.github/workflows/identity-testing.yml b/.github/workflows/identity-testing.yml
new file mode 100644
index 00000000000..39d62384c24
--- /dev/null
+++ b/.github/workflows/identity-testing.yml
@@ -0,0 +1,244 @@
+name: endpoint identity probes
+
+on:
+ pull_request:
+ branches: [main, "release/**"]
+ paths:
+ - server/core/embedding_space.py
+ - tests/fuzz/**
+ - tests/mutation/**
+ - .clusterfuzzlite/**
+ - .github/workflows/identity-testing.yml
+ push:
+ branches: [main]
+ paths:
+ - server/core/embedding_space.py
+ - tests/fuzz/**
+ - tests/mutation/**
+ - .clusterfuzzlite/**
+ - .github/workflows/identity-testing.yml
+ schedule:
+ - cron: "17 4 * * 3"
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+defaults:
+ run:
+ shell: bash
+
+concurrency:
+ group: endpoint-identity-${{ github.workflow }}-${{ github.ref }}
+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}
+
+jobs:
+ replay_and_mutation:
+ name: Endpoint identity corpus and mutation pilot
+ runs-on: ubuntu-24.04
+ timeout-minutes: 8
+ outputs:
+ review_count: ${{ steps.mutation.outputs.review_count }}
+ steps:
+ - name: Check out the maintained target and its probes
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+ sparse-checkout-cone-mode: false
+ sparse-checkout: |
+ /server/__init__.py
+ /server/core/__init__.py
+ /server/core/embedding_space.py
+ /tests/__init__.py
+ /tests/fuzz/
+ /tests/mutation/
+ /.github/workflows/identity-testing.yml
+ - name: Install the selected Python
+ uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
+ with:
+ python-version: "3.12"
+ - name: Create a disposable test environment
+ run: |
+ python3 -m venv "$RUNNER_TEMP/identity-venv"
+ "$RUNNER_TEMP/identity-venv/bin/python" -m pip install --require-hashes --only-binary=:all: -r tests/mutation/requirements.txt
+ - name: Replay the corpus and deterministic public-identity cases
+ run: |
+ "$RUNNER_TEMP/identity-venv/bin/python" -m tests.fuzz.embedding_identity_fuzzer --replay tests/fuzz/corpus/embedding_identity
+ "$RUNNER_TEMP/identity-venv/bin/python" -m unittest tests.mutation.test_embedding_identity tests.mutation.test_equivalence tests.fuzz.test_probe_publisher
+ - name: Mutate only the public-identity function
+ id: mutation
+ env:
+ IDENTITY_MUTATION_REPORT: ${{ runner.temp }}/identity-mutation.json
+ run: '"$RUNNER_TEMP/identity-venv/bin/python" tests/mutation/run_identity.py'
+
+ coverage_guided:
+ name: Endpoint identity coverage-guided fuzzing
+ runs-on: ubuntu-24.04
+ timeout-minutes: 15
+ steps:
+ - name: Check out only the parser and fuzz build inputs
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+ sparse-checkout-cone-mode: false
+ sparse-checkout: |
+ /server/__init__.py
+ /server/core/__init__.py
+ /server/core/embedding_space.py
+ /tests/__init__.py
+ /tests/fuzz/
+ /.clusterfuzzlite/
+ - name: Build the one parser fuzzer
+ id: build
+ uses: docker://gcr.io/oss-fuzz-base/clusterfuzzlite-build-fuzzers@sha256:c531ed554dbd3ed24e2bd11570a0e2dfb042146806236cdfd2d7d0d648b6c473
+ env:
+ LANGUAGE: python
+ SANITIZER: address
+ PROJECT_SRC_PATH: /github/workspace
+ KEEP_UNAFFECTED_FUZZ_TARGETS: "true"
+ UPLOAD_BUILD: "false"
+ BAD_BUILD_CHECK: "true"
+ ALLOWED_BROKEN_TARGETS_PERCENTAGE: "0"
+ DRY_RUN: "false"
+ CFL_PLATFORM: standalone
+ WORKSPACE: /github/workspace
+ FILESTORE: no_filestore
+ FILESTORE_ROOT_DIR: /github/workspace/out/ephemeral
+ NO_CLUSTERFUZZ_DEPLOYMENT: "true"
+ REPOSITORY: loom
+ LOW_DISK_SPACE: "True"
+ - name: Require the one built target
+ run: |
+ test -x build-out/embedding_identity
+ test -s build-out/embedding_identity.pkg
+ - name: Fuzz the parser within the selected time budget
+ id: fuzz
+ uses: docker://gcr.io/oss-fuzz-base/clusterfuzzlite-run-fuzzers@sha256:ec2a38a69babe087df3025a6babcb2a5a3675811a5cf4bfba23cece85c10e8d1
+ env:
+ LANGUAGE: python
+ SANITIZER: address
+ FUZZ_SECONDS: ${{ github.event_name == 'pull_request' && 30 || 180 }}
+ MODE: batch
+ PARALLEL_FUZZING: "false"
+ OUTPUT_SARIF: "true"
+ REPORT_TIMEOUTS: "true"
+ REPORT_OOMS: "true"
+ REPORT_UNREPRODUCIBLE_CRASHES: "false"
+ MINIMIZE_CRASHES: "false"
+ DRY_RUN: "false"
+ CFL_PLATFORM: standalone
+ WORKSPACE: /github/workspace
+ FILESTORE: no_filestore
+ FILESTORE_ROOT_DIR: /github/workspace/out/ephemeral
+ NO_CLUSTERFUZZ_DEPLOYMENT: "true"
+ REPOSITORY: loom
+ LOW_DISK_SPACE: "True"
+ - name: Report the bounded native probe outcome
+ if: always()
+ env:
+ BUILD_OUTCOME: ${{ steps.build.outcome }}
+ FUZZ_OUTCOME: ${{ steps.fuzz.outcome }}
+ run: |
+ python3 - <<'PY'
+ import os
+ allowed = {"success", "failure", "cancelled", "skipped"}
+ build, fuzz = os.environ["BUILD_OUTCOME"], os.environ["FUZZ_OUTCOME"]
+ assert build in allowed and fuzz in allowed
+ text = f"Endpoint identity target: build={build}, bounded fuzzing={fuzz}. Inspect the native log for executed inputs and replay records."
+ print("::notice title=Endpoint identity probe::" + text)
+ with open(os.environ["GITHUB_STEP_SUMMARY"], "a") as output:
+ output.write(text + "\n")
+ PY
+
+ maintenance:
+ name: Record trusted probe maintenance
+ needs: [replay_and_mutation, coverage_guided]
+ if: >-
+ always() && github.repository == 'ClickHouse/loom' &&
+ github.ref == 'refs/heads/main' &&
+ (github.event_name == 'push' || github.event_name == 'schedule' || github.event_name == 'workflow_dispatch')
+ runs-on: ubuntu-24.04
+ timeout-minutes: 5
+ permissions:
+ contents: read
+ issues: write # Record bounded probe maintenance on trusted main runs only.
+ steps:
+ - name: Reconcile failure tasks without executing project code
+ env:
+ GH_TOKEN: ${{ github.token }}
+ PROBE_RESULTS: ${{ toJSON(needs) }}
+ run: |
+ python3 - <<'PY'
+ import json, os, re, subprocess
+ from urllib.parse import urlencode
+ repo = "repos/ClickHouse/loom/issues"
+ bot = "github-actions[bot]"
+ marker = re.compile(r"")
+ state = re.compile(r"")
+ titles = {"replay_and_mutation": "[endpoint-identity-ci] Review the bounded mutation pilot", "coverage_guided": "[endpoint-identity-ci] Diagnose the bounded fuzzer check"}
+ calls = 0
+ def api(method, endpoint, payload=None):
+ global calls
+ calls += 1
+ assert calls <= 40, "Probe issue API budget exhausted"
+ command = ["gh", "api", "--method", method, endpoint, "--hostname", "github.com"]
+ if payload is not None:
+ command += ["--input", "-"]
+ result = subprocess.run(command, input=None if payload is None else json.dumps(payload), text=True, capture_output=True, timeout=20, check=True)
+ assert len(result.stdout) <= 2 * 1024 * 1024, "Probe issue response exceeds budget"
+ return json.loads(result.stdout)
+ managed = {}
+ for page in range(1, 11):
+ issues = api("GET", repo + "?" + urlencode({"state": "all", "creator": bot, "per_page": 100, "page": page}))
+ assert isinstance(issues, list)
+ for issue in issues:
+ if "pull_request" in issue or issue.get("user", {}).get("login") != bot:
+ continue
+ keys = marker.findall(issue.get("body") or "")
+ keys += [key for key, title in titles.items() if issue.get("title") == title]
+ keys = set(keys)
+ assert len(keys) <= 1, "Conflicting Probe issue markers"
+ if keys:
+ key = keys.pop()
+ assert key not in managed, "Duplicate Probe maintenance task"
+ managed[key] = issue
+ if len(issues) < 100:
+ break
+ else:
+ raise RuntimeError("Probe issue pagination budget exhausted")
+ results = json.loads(os.environ["PROBE_RESULTS"])
+ assert set(results) == set(titles)
+ run_id = os.environ["GITHUB_RUN_ID"]
+ assert run_id.isdecimal()
+ url = "https://github.com/ClickHouse/loom/actions/runs/" + run_id
+ changed = 0
+ for key in titles:
+ result = results[key]["result"]
+ if key == "replay_and_mutation" and result == "success":
+ count = results[key]["outputs"]["review_count"]
+ assert count.isdecimal() and 0 <= int(count) <= 10000
+ if int(count):
+ result = "review"
+ assert result in {"success", "failure", "review", "cancelled", "skipped"}
+ issue = managed.get(key)
+ if result not in {"success", "failure", "review"} or (issue and issue["state"] == "closed"):
+ continue
+ text = f"\n\n\n### Company or project name\n\nClickHouse\n\nThe bounded {key} probe reports **{result}** on trusted main. [Read the bounded probe logs and mutation summary]({url}).\n\nReproduce the named workflow job. A mutation survivor needs review for a missing assertion or equivalent mutation; it is not a vulnerability claim. No crash input or source excerpt is published here. Keep security-sensitive reports in the private route in SECURITY.md. Automation preserves edited bodies and closed decisions."
+ if issue is None:
+ if result in {"failure", "review"}:
+ api("POST", repo, {"title": titles[key], "body": text})
+ changed += 1
+ continue
+ number = issue["number"]
+ assert isinstance(number, int) and number > 0
+ comments = api("GET", f"{repo}/{number}/comments?per_page=100")
+ assert isinstance(comments, list) and len(comments) < 100, "Probe comment history budget exhausted"
+ candidates = [issue] + sorted(comments, key=lambda row: (row["created_at"], row["id"]))
+ states = [state.findall(row.get("body") or "") for row in candidates if row.get("user", {}).get("login") == bot]
+ states = [value[-1] for value in states if value]
+ if not states or states[-1] != result:
+ api("POST", f"{repo}/{number}/comments", {"body": text})
+ changed += 1
+ with open(os.environ["GITHUB_STEP_SUMMARY"], "a") as output:
+ output.write(f"Probe task reconciliation: {changed} task or status writes; closed decisions preserved.\n")
+ PY
diff --git a/.github/workflows/langflow-publish.yml b/.github/workflows/langflow-publish.yml
index 06ee326c3b3..a7870c2b83c 100644
--- a/.github/workflows/langflow-publish.yml
+++ b/.github/workflows/langflow-publish.yml
@@ -14,8 +14,13 @@ on:
permissions:
contents: read
+concurrency:
+ group: ${{ github.workflow }}-${{ github.ref }}
+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}
+
jobs:
build:
+ name: Build the Langflow distributions
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
@@ -26,7 +31,7 @@ jobs:
- uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
with:
python-version: "3.11"
- - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
+ - uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0
with:
version: "0.12.19"
- name: Validate package identity and publication tag
@@ -104,6 +109,7 @@ jobs:
retention-days: 14
install:
+ name: Test the installed Langflow extension (${{ matrix.sdk }})
needs: build
runs-on: ubuntu-latest
timeout-minutes: 15
@@ -118,7 +124,7 @@ jobs:
- uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
with:
python-version: "3.11"
- - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
+ - uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0
with:
version: "0.12.19"
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
@@ -167,6 +173,7 @@ jobs:
PY
publish:
+ name: Publish the verified Langflow distributions
if: github.event_name == 'push' && github.ref_type == 'tag'
needs: [build, install]
runs-on: ubuntu-latest
@@ -176,7 +183,7 @@ jobs:
url: https://pypi.org/p/lfx-loom
permissions:
contents: read
- id-token: write
+ id-token: write # Authenticate trusted PyPI publication.
steps:
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
diff --git a/.github/workflows/maven-dependency-graph.yml b/.github/workflows/maven-dependency-graph.yml
new file mode 100644
index 00000000000..d13cc443e8e
--- /dev/null
+++ b/.github/workflows/maven-dependency-graph.yml
@@ -0,0 +1,71 @@
+name: Maven dependency graph
+
+on:
+ pull_request:
+ branches: [main]
+ paths:
+ - "sdk/java/**"
+ - ".github/workflows/maven-dependency-graph.yml"
+ push:
+ branches: [main]
+ paths:
+ - "sdk/java/**"
+ - ".github/workflows/maven-dependency-graph.yml"
+ schedule:
+ - cron: "36 5 * * 2"
+
+permissions:
+ contents: read
+
+jobs:
+ verify:
+ if: github.event_name == 'pull_request'
+ runs-on: ubuntu-24.04
+ timeout-minutes: 12
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+ - uses: actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # v6.3.0
+ with:
+ distribution: temurin
+ java-version: "17"
+ - name: Resolve core and adapter graphs
+ run: |
+ mvn -B -ntp -f sdk/java/pom.xml install -DskipTests
+ for module in sdk/java sdk/java/langchain4j sdk/java/spring-ai; do
+ mvn -B -ntp -f "$module/pom.xml" com.github.ferstl:depgraph-maven-plugin:4.0.3:graph \
+ -DgraphFormat=json
+ done
+
+ submit:
+ if: github.repository == 'ClickHouse/loom' && github.event_name != 'pull_request' && github.ref == 'refs/heads/main'
+ runs-on: ubuntu-24.04
+ timeout-minutes: 12
+ permissions:
+ contents: write
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+ - uses: actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # v6.3.0
+ with:
+ distribution: temurin
+ java-version: "17"
+ - name: Build the local dependencies of the adapters
+ run: mvn -B -ntp -f sdk/java/pom.xml install -DskipTests
+ - name: Submit the core dependencies
+ uses: advanced-security/maven-dependency-submission-action@a64327a7329c9939cf675e458452febe1894a70c # v6.0.1
+ with:
+ directory: sdk/java
+ correlator: loom-java-sdk
+ - name: Submit the LangChain4j dependencies
+ uses: advanced-security/maven-dependency-submission-action@a64327a7329c9939cf675e458452febe1894a70c # v6.0.1
+ with:
+ directory: sdk/java/langchain4j
+ correlator: loom-java-langchain4j
+ - name: Submit the Spring AI dependencies
+ uses: advanced-security/maven-dependency-submission-action@a64327a7329c9939cf675e458452febe1894a70c # v6.0.1
+ with:
+ directory: sdk/java/spring-ai
+ correlator: loom-java-spring-ai
diff --git a/.github/workflows/memory-evaluation.yml b/.github/workflows/memory-evaluation.yml
new file mode 100644
index 00000000000..bf12ddba42f
--- /dev/null
+++ b/.github/workflows/memory-evaluation.yml
@@ -0,0 +1,77 @@
+name: Coding-agent memory evaluation
+
+on:
+ workflow_dispatch:
+ pull_request:
+ branches: [main]
+ paths:
+ - .github/workflows/memory-evaluation.yml
+ - examples/compare_coding_agent_memory.py
+ - examples/run_coding_agent_memory_comparison.sh
+ - examples/coding-agent-memory-comparison/**
+
+permissions:
+ contents: read
+
+concurrency:
+ group: ${{ github.workflow }}-${{ github.ref }}
+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}
+
+jobs:
+ evaluate:
+ name: Evaluate memory on a sample repository
+ runs-on: ubuntu-24.04
+ timeout-minutes: 15
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+ - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
+ id: python
+ with:
+ python-version: "3.12"
+ - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
+ with:
+ node-version: "24"
+ package-manager-cache: false
+ - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
+ with:
+ version: "0.12.19"
+ enable-cache: false
+ - name: Install Loom from the lockfile
+ env:
+ PYTHON_PATH: ${{ steps.python.outputs.python-path }}
+ run: uv sync --locked --python "$PYTHON_PATH" --extra dev --extra code
+ - name: Run the evaluation
+ id: evaluation
+ shell: bash
+ run: bash examples/run_coding_agent_memory_comparison.sh > "$RUNNER_TEMP/memory-evaluation.json"
+ - name: Write the results summary
+ if: ${{ !cancelled() }}
+ env:
+ EVALUATION_OUTCOME: ${{ steps.evaluation.outcome }}
+ shell: bash
+ run: |
+ echo '## Coding-agent memory evaluation' >> "$GITHUB_STEP_SUMMARY"
+ if [[ "$EVALUATION_OUTCOME" != success ]]; then
+ echo 'The evaluation did not complete successfully. See the failed step for details.' >> "$GITHUB_STEP_SUMMARY"
+ exit 0
+ fi
+ cat >> "$GITHUB_STEP_SUMMARY" <<'MARKDOWN'
+
+ | Check | Observed result |
+ | --- | --- |
+ | Memory handoff | A second MCP client retrieved the saved value and memory ID. |
+ | Source change | Loom returned `changed` on `main` and `fresh` on `release`. |
+ | Namespace access | A credential for another project received HTTP 403. |
+ | SQL history | A scoped reader saw both decisions and their writer identities. |
+ | Portability | A fresh namespace restored the corrected decision. |
+
+ Download the `memory-evaluation` artifact for the JSON results.
+ MARKDOWN
+ - name: Upload the evaluation results
+ uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
+ with:
+ name: memory-evaluation
+ path: ${{ runner.temp }}/memory-evaluation.json
+ if-no-files-found: error
diff --git a/.github/workflows/n8n-publish.yml b/.github/workflows/n8n-publish.yml
index 0a7532b06ad..2495549307b 100644
--- a/.github/workflows/n8n-publish.yml
+++ b/.github/workflows/n8n-publish.yml
@@ -14,8 +14,13 @@ on:
permissions:
contents: read
+concurrency:
+ group: ${{ github.workflow }}-${{ github.ref }}
+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}
+
jobs:
check:
+ name: check
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
@@ -24,6 +29,7 @@ jobs:
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: "24"
+ package-manager-cache: false
- name: Install the locked package manager
run: |
npm ci --prefix .github/pnpm --ignore-scripts --no-fund --no-audit
@@ -43,13 +49,14 @@ jobs:
node -e 'for (const path of ["Loom/Loom.node", "LoomMemory/LoomMemory.node"]) require("@clickhouse/n8n-nodes-loom/dist/nodes/" + path + ".js")'
publish:
+ name: publish
if: github.event_name == 'push' && (startsWith(github.ref_name, 'n8n-v') || !contains(github.ref_name, '-'))
needs: check
runs-on: ubuntu-latest
environment: npm-n8n
permissions:
contents: read
- id-token: write
+ id-token: write # Authenticate to npm as the registered publisher.
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
@@ -57,6 +64,7 @@ jobs:
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: "24"
+ package-manager-cache: false
registry-url: https://registry.npmjs.org
- name: Validate the publication tag
id: publication-tag
diff --git a/.github/workflows/pipecat-demo.yml b/.github/workflows/pipecat-demo.yml
index 089ae174838..1854fd07a69 100644
--- a/.github/workflows/pipecat-demo.yml
+++ b/.github/workflows/pipecat-demo.yml
@@ -17,6 +17,7 @@ concurrency:
jobs:
record:
+ name: Record the Pipecat demo
runs-on: ubuntu-24.04
timeout-minutes: 20
defaults:
@@ -70,15 +71,17 @@ jobs:
id: python
with:
python-version: "3.12"
- - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
+ - uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0
with:
version: "0.12.19"
enable-cache: false
- name: Prepare the pinned source fixture
+ env:
+ PYTHON_PATH: ${{ steps.python.outputs.python-path }}
run: |
set -euo pipefail
test "$(git rev-parse HEAD)" = 3c9ae8e1dde82685ee0e27bfe29b1c8d66cb956f
- uv sync --locked --python "${{ steps.python.outputs.python-path }}" --extra dev --extra code
+ uv sync --locked --python "${PYTHON_PATH}" --extra dev --extra code
echo "$PWD/.venv/bin" >> "$GITHUB_PATH"
cp "$GITHUB_WORKSPACE/dev/pipecat_demo/_pipecat_video_ci.py" tests/integration/_pipecat_video_ci.py
image=$(bash dev/clickhouse_release.sh)
diff --git a/.github/workflows/plugin-platforms.yml b/.github/workflows/plugin-platforms.yml
index e9a3912363d..b7753347a6f 100644
--- a/.github/workflows/plugin-platforms.yml
+++ b/.github/workflows/plugin-platforms.yml
@@ -18,6 +18,7 @@ on:
- ".github/workflows/plugin-platforms.yml"
- ".github/agent-clis/**"
- "scripts/code-toolchains/bind-native.cjs"
+ - "dev/test_plugins_wsl.sh"
pull_request:
branches: [main, "release/**"]
paths:
@@ -28,6 +29,7 @@ on:
- ".github/workflows/plugin-platforms.yml"
- ".github/agent-clis/**"
- "scripts/code-toolchains/bind-native.cjs"
+ - "dev/test_plugins_wsl.sh"
concurrency:
group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.ref || github.sha }}
@@ -64,8 +66,10 @@ jobs:
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: ${{ env.NODE_VERSION }}
+ package-manager-cache: false
- name: node --test (plugin suite)
- run: node --test integrations/claude-code-plugin/tests/*.test.mjs
+ # These suites start hook subprocesses with their own deadlines.
+ run: node --test --test-concurrency=2 integrations/claude-code-plugin/tests/*.test.mjs
- name: node --test (grep shim)
if: ${{ !cancelled() }}
run: node --test integrations/grep-shim/tests/*.test.mjs
@@ -88,6 +92,11 @@ jobs:
- name: Codex session
if: ${{ !cancelled() }}
run: node integrations/claude-code-plugin/tests/e2e/agent-session.mjs codex --bin "$CODEX_BIN"
+ # Claude Code keeps LOOM_API_KEY from a plugin's header helper: the
+ # SessionStart hook saves the token where the helper reads it.
+ - name: Claude Code session, token in LOOM_API_KEY
+ if: ${{ !cancelled() }}
+ run: node integrations/claude-code-plugin/tests/e2e/agent-session.mjs claude --bin "$CLAUDE_BIN" --expect-tool Bash --token-env
# Started from the Dock or a desktop launcher, the agent has no node on
# PATH: Claude Code gets it from PATH in its settings env, Codex's
# launcher finds it under a version manager.
@@ -157,36 +166,15 @@ jobs:
name: plugins on WSL 2 (Ubuntu 24.04, Node 18)
runs-on: windows-latest
timeout-minutes: 30
- defaults:
- run:
- shell: wsl-bash {0}
+ env:
+ WSL_DISTRIBUTION: Ubuntu-24.04
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: Vampire/setup-wsl@4c48163d9f981914dd8caa0fc335fe19cca5bff4 # v7.2.0
with:
- distribution: Ubuntu-24.04
+ distribution: ${{ env.WSL_DISTRIBUTION }}
additional-packages: git ca-certificates nodejs npm
- name: suite and sessions in WSL
- run: |
- useradd -m ci
- # A clone inside WSL, with Linux modes and line endings, as a WSL user's is.
- git -c safe.directory='*' clone --quiet --no-local . /home/ci/repo
- chown -R ci /home/ci/repo
- npm ci --prefix /home/ci/repo/.github/agent-clis --ignore-scripts --no-fund --no-audit >/dev/null
- node /home/ci/repo/scripts/code-toolchains/bind-native.cjs /home/ci/repo/.github/agent-clis claude
- root=$(npm root --prefix /home/ci/repo/.github/agent-clis)
- codex=$(ls "$root"/@openai/codex-linux-*/vendor/*/bin/codex | head -1)
- test -n "$codex" && test -x "$codex" || { echo "The locked native agent executable is missing" >&2; exit 1; }
- su ci -s /bin/sh -c "
- set -e
- cd /home/ci/repo
- node --version
- git config --global user.email ci@example.com
- git config --global user.name ci
- node --test integrations/claude-code-plugin/tests/*.test.mjs
- node --test integrations/grep-shim/tests/*.test.mjs
- node integrations/claude-code-plugin/tests/e2e/agent-session.mjs claude --bin $root/@anthropic-ai/claude-code/bin/claude.exe --expect-tool Bash
- node integrations/claude-code-plugin/tests/e2e/agent-session.mjs codex --bin $codex
- "
+ run: wsl.exe --distribution $env:WSL_DISTRIBUTION --user root --exec bash dev/test_plugins_wsl.sh
diff --git a/.github/workflows/release-check.yml b/.github/workflows/release-check.yml
index a0505073fe4..c33c2bc15a8 100644
--- a/.github/workflows/release-check.yml
+++ b/.github/workflows/release-check.yml
@@ -40,6 +40,10 @@ on:
permissions:
contents: read
+concurrency:
+ group: ${{ github.workflow }}-${{ inputs.version }}-${{ inputs.previous_version }}-${{ inputs.sdks }}
+ cancel-in-progress: false
+
jobs:
installer:
name: One-line installer (${{ matrix.arch }})
@@ -150,13 +154,18 @@ jobs:
run: |
mkdir -p "$RUNNER_TEMP/npm" && cd "$RUNNER_TEMP/npm"
npm init -y >/dev/null
- npm install --registry=https://registry.npmjs.org --ignore-scripts --no-audit --no-fund "@clickhouse/loom@$VERSION"
- npm audit signatures
+ npm pkg set "dependencies[@clickhouse/loom]=$VERSION"
+ # Each release check resolves its requested version in a fresh project.
+ npm install --package-lock-only --registry=https://registry.npmjs.org --ignore-scripts --no-audit --no-fund
+ npm ci --registry=https://registry.npmjs.org --ignore-scripts --no-audit --no-fund
+ npm audit signatures --registry=https://registry.npmjs.org
node -e 'const { SDK_VERSION } = require("@clickhouse/loom"); if (SDK_VERSION !== process.argv[1]) { throw new Error(SDK_VERSION) }' "$VERSION"
- name: Install the metadata checker separately from the SDKs
run: |
python -m venv "$RUNNER_TEMP/metadata-check"
- "$RUNNER_TEMP/metadata-check/bin/pip" --isolated install --index-url https://pypi.org/simple packaging==24.2
+ printf '%s\n' 'packaging==24.2 --hash=sha256:09abb1bccd265c01f4a3aa3f7a7db064b36514d2cba19a2f694fe6150451a759' > "$RUNNER_TEMP/metadata-check.txt"
+ "$RUNNER_TEMP/metadata-check/bin/pip" --isolated install --index-url https://pypi.org/simple \
+ --require-hashes --only-binary=:all: -r "$RUNNER_TEMP/metadata-check.txt"
- name: Published SDK metadata matches the release tag
id: sdk-metadata
env:
@@ -242,7 +251,7 @@ jobs:
raise SystemExit(f"published npm {field} differs from the release tag")
peers = source_js.get("peerDependencies", {})
node_rows = [{"peer": "none", "requirement": ""}]
- node_rows += [{"peer": name, "requirement": f"{name}@{peers[name]}"} for name in sorted(peers)]
+ node_rows += [{"peer": name, "requirement": peers[name]} for name in sorted(peers)]
outputs = {
"python_extras": json.dumps({"extra": sorted(extras)}, separators=(",", ":")),
"has_python_extras": str(bool(extras)).lower(),
@@ -292,13 +301,17 @@ jobs:
- name: Install the published SDK with its declared peer
env:
VERSION: ${{ inputs.version }}
- PEER_SPEC: ${{ matrix.requirement }}
+ PEER_NAME: ${{ matrix.peer }}
+ PEER_REQUIREMENT: ${{ matrix.requirement }}
run: |
mkdir -p "$RUNNER_TEMP/peer" && cd "$RUNNER_TEMP/peer"
npm init -y >/dev/null
- packages=("@clickhouse/loom@$VERSION")
- [ -z "$PEER_SPEC" ] || packages+=("$PEER_SPEC")
- npm install --registry=https://registry.npmjs.org --ignore-scripts --no-audit --no-fund "${packages[@]}"
- npm audit signatures
+ npm pkg set "dependencies[@clickhouse/loom]=$VERSION"
+ if [ -n "$PEER_REQUIREMENT" ]; then
+ npm pkg set "dependencies[$PEER_NAME]=$PEER_REQUIREMENT"
+ fi
+ npm install --package-lock-only --registry=https://registry.npmjs.org --ignore-scripts --no-audit --no-fund
+ npm ci --registry=https://registry.npmjs.org --ignore-scripts --no-audit --no-fund
+ npm audit signatures --registry=https://registry.npmjs.org
node -e 'const { SDK_VERSION } = require("@clickhouse/loom"); if (SDK_VERSION !== process.argv[1]) { throw new Error(SDK_VERSION) }' "$VERSION"
npm ls --depth=0
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 63530846f8d..045dfde4151 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -127,7 +127,7 @@ jobs:
# Every version file names the tag's final, the candidate order holds, and the
# chart's own version moved (release-process.md); check-tag skips off the tag's
# commit in a dry run. `previous` is the tag the generated release notes start
- # from (github-release's previous_tag).
+ # from (the release CLI's --notes-start-tag).
- name: Version files, the candidate order and the chart
id: checks
env:
@@ -204,12 +204,14 @@ jobs:
id: python
with:
python-version: ${{ env.PYTHON_VERSION }}
- - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
+ - uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0
with:
version: ${{ env.UV_VERSION }}
- name: Install Loom from uv.lock (no extras)
+ env:
+ PYTHON_PATH: ${{ steps.python.outputs.python-path }}
run: |
- uv sync --locked --python "${{ steps.python.outputs.python-path }}"
+ uv sync --locked --python "${PYTHON_PATH}"
echo "$PWD/.venv/bin" >> "$GITHUB_PATH"
# release_clickhouse.sh decides which release, in order of
# preference. A downgrade is refused here so the run stops before it
@@ -249,6 +251,7 @@ jobs:
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: ${{ env.NODE_VERSION }}
+ package-manager-cache: false
# The SDK sources carry the tag's version, so every published file names it.
# The Python SDK takes its PEP 440 form (1.2.0rc1 for 1.2.0-rc.1): the
# build backend writes the version into METADATA as given, and the verify
@@ -301,6 +304,10 @@ jobs:
zip -q "release/plugins/loom-claude-code-plugin-v${VERSION}.zip" LICENSE NOTICE THIRD_PARTY_NOTICES
zip -q "release/plugins/loom-codex-plugin-v${VERSION}.zip" LICENSE NOTICE THIRD_PARTY_NOTICES
ls -la release/*
+ # The memory, code and status skills for a client without the plugin: a zip
+ # of each and one of all three, under names that do not carry the version.
+ - name: Zip the standalone skill bundles
+ run: python scripts/codegen/standalone_skills.py --zip release/skills
# docs/getting-started/agent-setup.md with this release's version and commit.
- name: Render agent-setup.txt
run: |
@@ -447,6 +454,10 @@ jobs:
print(f"::error::{e}")
sys.exit(1 if errors else 0)
PY
+ # The four skill zips hold what this commit's plugin skills generate, at the
+ # server's version, and nothing else.
+ - name: Skill bundles are the ones the source generates
+ run: python scripts/codegen/standalone_skills.py --check --zip release/skills
# The wheel alone in a clean venv: it imports, talks through a mocked
# transport, and ships py.typed and the license.
- name: Smoke-test the wheel
@@ -478,7 +489,7 @@ jobs:
pin: image.digest
# Title and description are the repository's, metadata-action's defaults.
labels: |
- org.opencontainers.image.documentation=https://clickhouse.github.io/loom/
+ org.opencontainers.image.documentation=https://loom.clickhouse.com/docs/
- artifact: extractor
image: ghcr.io/clickhouse/loom-extractor
file: extractor/Dockerfile
@@ -486,7 +497,7 @@ jobs:
labels: |
org.opencontainers.image.title=loom-extractor
org.opencontainers.image.description=Loom's document extractor service, which parses originals apart from the server
- org.opencontainers.image.documentation=https://clickhouse.github.io/loom/
+ org.opencontainers.image.documentation=https://loom.clickhouse.com/docs/
- arch: amd64
runner: ubuntu-latest
- arch: arm64
@@ -495,7 +506,7 @@ jobs:
timeout-minutes: 60
permissions:
contents: read
- packages: write
+ packages: write # Push release images to the registry.
env:
DRY_RUN: ${{ inputs.dry_run == true }}
steps:
@@ -585,7 +596,7 @@ jobs:
digests: ${{ steps.tag.outputs.digests }}
permissions:
contents: read
- packages: write
+ packages: write # Write release image tags to the registry.
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
@@ -649,7 +660,7 @@ jobs:
timeout-minutes: 10
permissions:
contents: read
- packages: write
+ packages: write # Write image signatures to the registry.
id-token: write # the keyless signature's certificate names this workflow and tag
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
@@ -708,8 +719,7 @@ jobs:
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: "22"
- cache: npm
- cache-dependency-path: frontend/package-lock.json
+ package-manager-cache: false
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
name: release-files
@@ -769,7 +779,7 @@ jobs:
outputs:
latest: ${{ steps.latest.outputs.latest }}
permissions:
- contents: write
+ contents: write # Create the release and attach its artifacts.
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
@@ -817,44 +827,46 @@ jobs:
;;
*) exit "$status" ;;
esac
- # Notes are generated only when this run creates the release: on an existing
- # one the action appends them again, under notes edited by hand.
- name: Is there a release for this tag already
id: existing
env:
GH_TOKEN: ${{ github.token }}
- # Only a 404 means there is none: any other failure would regenerate the notes.
+ # A single lookup includes drafts and keeps API failures distinct from absence.
+ run: |
+ release=$(gh api graphql \
+ -f query='query($owner: String!, $name: String!, $tag: String!) {
+ repository(owner: $owner, name: $name) {
+ release(tagName: $tag) { id }
+ }
+ }' \
+ -f owner="${GITHUB_REPOSITORY%%/*}" -f name="${GITHUB_REPOSITORY#*/}" -f tag="$GITHUB_REF_NAME" \
+ --jq '.data.repository | if has("release") then .release != null else error("Missing release result") end')
+ echo "release=$release" >>"$GITHUB_OUTPUT"
+ - name: Create or update the release with notes and files
+ id: publish-release
+ env:
+ GH_TOKEN: ${{ github.token }}
+ VERSION_EXISTS: ${{ steps.existing.outputs.release }}
+ PREVIOUS_TAG: ${{ needs.version.outputs.previous }}
+ PRERELEASE: ${{ needs.version.outputs.prerelease }}
+ LATEST: ${{ steps.latest.outputs.latest }}
run: |
- if out=$(gh api "repos/$GITHUB_REPOSITORY/releases/tags/$GITHUB_REF_NAME" 2>&1); then
- echo "release=true" >>"$GITHUB_OUTPUT"
- elif grep -q "(HTTP 404)" <<<"$out"; then
- echo "release=false" >>"$GITHUB_OUTPUT"
+ files=(release/python/* release/npm/*.tgz release/plugins/*.zip release/skills/*.zip release/stack/* release/agent/agent-setup.txt)
+ for file in "${files[@]}"; do
+ test -f "$file" || { echo "::error::Missing release file $file"; exit 1; }
+ done
+ if [ "$VERSION_EXISTS" = true ]; then
+ # Keep the existing notes, which may include edits from maintainers.
+ gh release upload "$GITHUB_REF_NAME" "${files[@]}" --clobber --repo "$GITHUB_REPOSITORY"
else
- echo "$out" >&2
- echo "::error::could not tell whether $GITHUB_REF_NAME has a release"
- exit 1
+ notes=(--generate-notes)
+ if [ -n "$PREVIOUS_TAG" ]; then notes+=(--notes-start-tag "$PREVIOUS_TAG"); fi
+ gh release create "$GITHUB_REF_NAME" "${files[@]}" --draft --verify-tag --title "$GITHUB_REF_NAME" \
+ "${notes[@]}" --prerelease="$PRERELEASE" --repo "$GITHUB_REPOSITORY"
fi
- # An existing release for the tag is updated and its other files replaced,
- # so a re-run or the later dispatch leaves the published bytes attached.
- - name: Create or update the release with notes and files
- uses: softprops/action-gh-release@8a0cd651e5b2365bd640854a3fa5dfc70e4875f3 # v3.0.4
- with:
- tag_name: ${{ github.ref_name }}
- name: ${{ github.ref_name }}
- generate_release_notes: ${{ steps.existing.outputs.release != 'true' }}
- # Since the previous final release, not the candidate on this commit.
- previous_tag: ${{ needs.version.outputs.previous }}
- draft: false
- prerelease: ${{ needs.version.outputs.prerelease == 'true' }}
- make_latest: ${{ steps.latest.outputs.latest }}
- overwrite_files: true
- fail_on_unmatched_files: true
- files: |
- release/python/*
- release/npm/*.tgz
- release/plugins/*.zip
- release/stack/*
- release/agent/agent-setup.txt
+ # Publish separately so a failed response leaves the release and its assets available.
+ gh release edit "$GITHUB_REF_NAME" --title "$GITHUB_REF_NAME" --draft=false \
+ --prerelease="$PRERELEASE" --latest="$LATEST" --repo "$GITHUB_REPOSITORY"
# Signs the files the release serves, downloaded as users download them, when
# they are the bytes this run built (sign_release_files.sh). Its own job, so
@@ -902,7 +914,7 @@ jobs:
runs-on: ubuntu-latest
timeout-minutes: 10
permissions:
- contents: write
+ contents: write # Attach signatures to the existing release.
steps:
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
@@ -969,6 +981,7 @@ jobs:
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: "24"
+ package-manager-cache: false
registry-url: https://registry.npmjs.org
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
diff --git a/.github/workflows/rust-api.yml b/.github/workflows/rust-api.yml
new file mode 100644
index 00000000000..8ec40d32b0b
--- /dev/null
+++ b/.github/workflows/rust-api.yml
@@ -0,0 +1,49 @@
+name: Rust SDK API compatibility
+
+on:
+ pull_request:
+ branches: [main, "release/**"]
+ paths:
+ - "sdk/rust/**"
+ - ".github/workflows/rust-api.yml"
+ push:
+ branches: [main]
+ paths:
+ - "sdk/rust/**"
+ - ".github/workflows/rust-api.yml"
+
+permissions:
+ contents: read
+
+jobs:
+ rust-api:
+ runs-on: ubuntu-24.04
+ timeout-minutes: 18
+ env:
+ CARGO_RESOLVER_INCOMPATIBLE_RUST_VERSIONS: fallback
+ RUSTUP_TOOLCHAIN: 1.99.0
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ # The SDK source shipped with Loom v1.3.0.
+ ref: 47b479dcdae4c089aef2690428fa4c9a8f54554c
+ path: release-baseline
+ persist-credentials: false
+ sparse-checkout: sdk/rust
+ - name: Install the supported Rust toolchain
+ run: rustup toolchain install "$RUSTUP_TOOLCHAIN" --profile minimal
+ - name: Install cargo-semver-checks
+ working-directory: ${{ runner.temp }}
+ run: |
+ archive=cargo-semver-checks-x86_64-unknown-linux-gnu.tar.gz
+ curl --fail --silent --show-error --location --proto '=https' --tlsv1.2 \
+ "https://github.com/obi1kenobi/cargo-semver-checks/releases/download/v0.51.0/$archive" -o "$archive"
+ echo "cacadafaa5cd27ae6d05a74a103266917ebab4c5e43c898360e177d4fbf06a65 $archive" | sha256sum --check --strict
+ tar -xzf "$archive" cargo-semver-checks
+ - name: Compare the public Rust SDK with the release baseline
+ run: |
+ "$RUNNER_TEMP/cargo-semver-checks" semver-checks \
+ --manifest-path sdk/rust/Cargo.toml --baseline-root release-baseline/sdk/rust
diff --git a/.github/workflows/rust-dependency-graph.yml b/.github/workflows/rust-dependency-graph.yml
new file mode 100644
index 00000000000..46417f5101f
--- /dev/null
+++ b/.github/workflows/rust-dependency-graph.yml
@@ -0,0 +1,81 @@
+name: Rust dependency graph
+
+on:
+ pull_request:
+ branches: [main]
+ paths:
+ - "sdk/rust/**"
+ - ".github/scripts/rust-dependency-snapshot.py"
+ - ".github/scripts/test_rust_dependency_snapshot.py"
+ - ".github/workflows/rust-dependency-graph.yml"
+ push:
+ branches: [main]
+ paths:
+ - "sdk/rust/**"
+ - ".github/scripts/rust-dependency-snapshot.py"
+ - ".github/scripts/test_rust_dependency_snapshot.py"
+ - ".github/workflows/rust-dependency-graph.yml"
+ schedule:
+ - cron: "43 5 * * 2"
+
+permissions:
+ contents: read
+
+jobs:
+ resolve:
+ runs-on: ubuntu-24.04
+ timeout-minutes: 10
+ outputs:
+ snapshot: ${{ steps.snapshot.outputs.snapshot }}
+ env:
+ CARGO_TOOLCHAIN: "1.84.1"
+ CARGO_RESOLVER_INCOMPATIBLE_RUST_VERSIONS: fallback
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+ - name: Check snapshot conversion and transport
+ run: python3 -m unittest discover -s .github/scripts -p test_rust_dependency_snapshot.py
+ - name: Resolve the SDK dependency graph
+ working-directory: sdk/rust
+ run: |
+ rustup toolchain install "$CARGO_TOOLCHAIN" --profile minimal
+ cargo "+$CARGO_TOOLCHAIN" generate-lockfile
+ cargo "+$CARGO_TOOLCHAIN" metadata --all-features --locked --format-version 1 \
+ > "$RUNNER_TEMP/cargo-metadata.json"
+ - name: Generate a snapshot
+ id: snapshot
+ run: |
+ python3 .github/scripts/rust-dependency-snapshot.py "$RUNNER_TEMP/cargo-metadata.json" \
+ >> "$GITHUB_STEP_SUMMARY"
+
+ submit:
+ if: github.repository == 'ClickHouse/loom' && github.event_name != 'pull_request' && github.ref == 'refs/heads/main'
+ needs: resolve
+ runs-on: ubuntu-24.04
+ timeout-minutes: 5
+ permissions:
+ contents: write
+ steps:
+ - name: Submit this run's snapshot
+ env:
+ GH_TOKEN: ${{ github.token }}
+ SNAPSHOT_JSON: ${{ needs.resolve.outputs.snapshot }}
+ run: |
+ python3 - <<'PYTHON'
+ import json
+ import os
+ from pathlib import Path
+
+ payload = os.environ["SNAPSHOT_JSON"]
+ if not payload.isascii() or len(payload) > 96 * 1024:
+ raise ValueError("Dependency snapshot exceeds the job-output size limit")
+ snapshot = json.loads(payload)
+ expected = (os.environ["GITHUB_SHA"], "refs/heads/main", os.environ["GITHUB_RUN_ID"])
+ actual = (snapshot["sha"], snapshot["ref"], snapshot["job"]["id"])
+ if actual != expected:
+ raise ValueError("Dependency snapshot does not match this commit and run")
+ Path(os.environ["RUNNER_TEMP"], "rust-snapshot.json").write_text(payload + "\n")
+ PYTHON
+ snapshot="$RUNNER_TEMP/rust-snapshot.json"
+ gh api --method POST "repos/$GITHUB_REPOSITORY/dependency-graph/snapshots" --input "$snapshot"
diff --git a/.github/workflows/scorecard.yml b/.github/workflows/scorecard.yml
index 78cb4be1bf0..10c34de3437 100644
--- a/.github/workflows/scorecard.yml
+++ b/.github/workflows/scorecard.yml
@@ -29,12 +29,14 @@ jobs:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- - uses: ossf/scorecard-action@fa7117db83c52d787ae5a89f350999701505d78e # v2.5.0
+ - uses: ossf/scorecard-action@23f22cd43608bae7a1f1fa2603d7314dee9538a5 # v2.6.0
with:
results_file: results.sarif
results_format: sarif
publish_results: true
+ fail_on_publish_error: true
- uses: github/codeql-action/upload-sarif@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3
+ if: ${{ !cancelled() && hashFiles('results.sarif') != '' }}
with:
sarif_file: results.sarif
category: scorecard
diff --git a/.github/workflows/sdk-native.yml b/.github/workflows/sdk-native.yml
new file mode 100644
index 00000000000..52b6c6cdcbd
--- /dev/null
+++ b/.github/workflows/sdk-native.yml
@@ -0,0 +1,432 @@
+name: native SDK packages
+
+on:
+ pull_request:
+ branches: [main, "release/**"]
+ push:
+ branches: [main]
+ schedule:
+ - cron: "41 5 * * 2"
+
+permissions:
+ contents: read
+
+defaults:
+ run:
+ shell: bash
+
+concurrency:
+ group: native-sdk-${{ github.workflow }}-${{ github.ref }}
+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}
+
+jobs:
+ go:
+ name: Go SDK (build, vet, race tests)
+ runs-on: ubuntu-24.04
+ timeout-minutes: 10
+ defaults:
+ run:
+ working-directory: sdk/go
+ steps:
+ - name: Check out the Go source
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+ fetch-depth: 2
+ sparse-checkout: sdk/go
+ - name: Install Go
+ uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0
+ with:
+ go-version: "1.27.4"
+ cache: false
+ - name: Build and vet the module
+ run: |
+ go build ./...
+ go vet ./...
+ - name: Run the real HTTP tests with the race detector
+ run: |
+ coverage=()
+ if [[ "$GITHUB_EVENT_NAME" == pull_request ]]; then
+ coverage=(-coverprofile="$RUNNER_TEMP/go.cover")
+ fi
+ go test -race -count=1 -timeout=3m -json "${coverage[@]}" ./... | tee "$RUNNER_TEMP/go-tests.jsonl"
+ - name: Convert Go coverage to Cobertura
+ id: go-coverage
+ if: github.event_name == 'pull_request'
+ continue-on-error: true
+ run: go run github.com/boumenot/gocover-cobertura@v1.5.0 < "$RUNNER_TEMP/go.cover" > "$RUNNER_TEMP/go.xml"
+ - name: Report Go SDK changed-line coverage
+ if: steps.go-coverage.outcome == 'success'
+ continue-on-error: true
+ uses: ClickHouse/loom/.github/actions/patch-coverage@df405e9ed5d032b8248f6cfa8cf87e856685e490
+ with:
+ component: Go SDK
+ working-directory: sdk/go
+ report: ${{ runner.temp }}/go.xml
+ - name: Require executed tests and report the count
+ run: |
+ python3 - <<'PY'
+ import json, os
+ from pathlib import Path
+ rows = [json.loads(line) for line in (Path(os.environ["RUNNER_TEMP"]) / "go-tests.jsonl").read_text().splitlines()]
+ passed = sum(row.get("Action") == "pass" and bool(row.get("Test")) for row in rows)
+ assert passed > 0, "The Go suite executed no passing test"
+ assert not any(row.get("Action") == "fail" for row in rows)
+ with open(os.environ["GITHUB_STEP_SUMMARY"], "a") as output:
+ output.write(f"Go: build and vet passed; {passed} tests passed with the race detector.\n")
+ PY
+
+ - name: Check known reachable Go vulnerabilities and verify the analyzer
+ env:
+ GOTOOLCHAIN: local
+ GOTELEMETRY: "off"
+ GOMAXPROCS: "2"
+ GOFLAGS: -p=2
+ GOPROXY: https://proxy.golang.org
+ GOSUMDB: sum.golang.org
+ run: |
+ export GOBIN="$RUNNER_TEMP/govulncheck/bin"
+ timeout --kill-after=10s 180s go install golang.org/x/vuln/cmd/govulncheck@v1.10.0
+ control="$RUNNER_TEMP/govulncheck/control"
+ mkdir -p "$control"
+ printf '%s\n' 'package main' 'import "golang.org/x/text/language"' 'func main() { _, _ = language.Parse("en") }' > "$control/main.go"
+ for version in 0.3.6 0.3.7; do
+ printf 'module example.invalid/loom-vulnerability-control\n\ngo 1.22\n\nrequire golang.org/x/text v%s\n' "$version" > "$control/go.mod"
+ (
+ cd "$control"
+ timeout --kill-after=10s 120s go mod tidy
+ timeout --kill-after=10s 120s "$GOBIN/govulncheck" -format=json ./... > "$RUNNER_TEMP/go-vulnerability-$version.json"
+ )
+ done
+ python3 - <<'PYVULN'
+ import json, os
+ from pathlib import Path
+ def reaches_control(path):
+ assert path.stat().st_size <= 4 * 1024 * 1024
+ raw = path.read_text()
+ decoder = json.JSONDecoder()
+ rows = []
+ while raw.strip():
+ row, end = decoder.raw_decode(raw.lstrip())
+ assert isinstance(row, dict)
+ rows.append(row)
+ raw = raw.lstrip()[end:]
+ assert rows, "The analyzer returned no JSON record"
+ return any(
+ row.get("finding", {}).get("osv") == "GO-2021-0113"
+ and any(frame.get("package") == "golang.org/x/text/language" and frame.get("function") == "Parse"
+ for frame in row["finding"].get("trace", []))
+ for row in rows
+ )
+ directory = Path(os.environ["RUNNER_TEMP"])
+ assert reaches_control(directory / "go-vulnerability-0.3.6.json"), "The known vulnerable call was not detected"
+ assert not reaches_control(directory / "go-vulnerability-0.3.7.json"), "The fixed control still reports that call"
+ PYVULN
+ timeout --kill-after=10s 180s "$GOBIN/govulncheck" ./...
+ printf '%s\n' 'Go vulnerability analysis passed for the selected Go 1.27.4 Linux build. The known vulnerable and fixed-call controls passed. This covers known reachable calls under this build, not reflection, all build tags or every supported Go version.' >> "$GITHUB_STEP_SUMMARY"
+
+ java:
+ name: Java SDK (tests and jar consumer)
+ runs-on: ubuntu-24.04
+ timeout-minutes: 10
+ defaults:
+ run:
+ working-directory: sdk/java
+ steps:
+ - name: Check out the core Java source
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+ fetch-depth: 2
+ sparse-checkout: sdk/java
+ - name: Install the declared Java target
+ uses: actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # v6.3.0
+ with:
+ distribution: temurin
+ java-version: "17"
+ - name: Build and run the existing fake-server tests
+ run: |
+ goals=(verify)
+ if [[ "$GITHUB_EVENT_NAME" == pull_request ]]; then
+ goals=(org.jacoco:jacoco-maven-plugin:0.8.16:prepare-agent verify)
+ fi
+ mvn --batch-mode --no-transfer-progress -DfailIfNoTests=true "${goals[@]}"
+ - name: Export Java coverage as JaCoCo XML
+ id: java-coverage
+ if: github.event_name == 'pull_request'
+ continue-on-error: true
+ run: mvn --batch-mode --no-transfer-progress org.jacoco:jacoco-maven-plugin:0.8.16:report
+ - name: Report Java SDK changed-line coverage
+ if: steps.java-coverage.outcome == 'success'
+ continue-on-error: true
+ uses: ClickHouse/loom/.github/actions/patch-coverage@df405e9ed5d032b8248f6cfa8cf87e856685e490
+ with:
+ component: Java SDK
+ source-root: sdk/java/src/main/java
+ report: sdk/java/target/site/jacoco/jacoco.xml
+ - name: Require executed tests and consume the jar
+ run: |
+ python3 - <<'PY'
+ import os, xml.etree.ElementTree as ET
+ from pathlib import Path
+ reports = [ET.parse(path).getroot() for path in Path("target/surefire-reports").glob("TEST-*.xml")]
+ total = sum(int(row.get("tests", "0")) for row in reports)
+ skipped = sum(int(row.get("skipped", "0")) for row in reports)
+ assert total > skipped, "The Java suite executed no test"
+ assert all(int(row.get("failures", "0")) == int(row.get("errors", "0")) == 0 for row in reports)
+ pom = ET.parse("pom.xml").getroot()
+ ns = {"m": "http://maven.apache.org/POM/4.0.0"}
+ jar = Path("target") / (pom.findtext("m:artifactId", namespaces=ns) + "-" + pom.findtext("m:version", namespaces=ns) + ".jar")
+ assert jar.is_file() and jar.stat().st_size > 0
+ (Path(os.environ["RUNNER_TEMP"]) / "java-package-path").write_text(str(jar.resolve()))
+ with open(os.environ["GITHUB_STEP_SUMMARY"], "a") as output:
+ output.write(f"Java core: {total - skipped} tests passed; {skipped} skipped.\n")
+ PY
+ package=$(cat "$RUNNER_TEMP/java-package-path")
+ jar --list --file "$package" | grep -Fx 'com/clickhouse/loom/LoomClient.class'
+ mvn --batch-mode --no-transfer-progress org.apache.maven.plugins:maven-dependency-plugin:3.11.0:copy-dependencies -DincludeScope=runtime -DoutputDirectory="$RUNNER_TEMP/loom-java-dependencies"
+ consumer="$RUNNER_TEMP/loom-java-consumer"
+ mkdir -p "$consumer"
+ printf '%s\n' 'import com.clickhouse.loom.LoomClient;' 'class Consumer { public static void main(String[] args) { var client = LoomClient.builder().baseUrl("http://127.0.0.1:1").org("test").namespace("test").agent("consumer").build(); System.out.println(client.getClass().getName()); } }' > "$consumer/Consumer.java"
+ classpath="$package:$RUNNER_TEMP/loom-java-dependencies/*"
+ javac -cp "$classpath" "$consumer/Consumer.java"
+ java -cp "$classpath:$consumer" Consumer
+
+ dotnet:
+ name: .NET SDK (tests and package consumer)
+ runs-on: ubuntu-24.04
+ timeout-minutes: 10
+ defaults:
+ run:
+ working-directory: sdk/dotnet
+ env:
+ DOTNET_CLI_TELEMETRY_OPTOUT: "1"
+ DOTNET_NOLOGO: "1"
+ # Run the unchanged net8.0 assembly on the supported LTS runtime.
+ DOTNET_ROLL_FORWARD: Major
+ steps:
+ - name: Check out the .NET source
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+ fetch-depth: 2
+ sparse-checkout: sdk/dotnet
+ - name: Select a private SDK installation
+ run: |
+ printf 'DOTNET_INSTALL_DIR=%s/loom-dotnet-sdk\nDOTNET_ROOT=%s/loom-dotnet-sdk\nDOTNET_ROOT_X64=%s/loom-dotnet-sdk\n' "$RUNNER_TEMP" "$RUNNER_TEMP" "$RUNNER_TEMP" >> "$GITHUB_ENV"
+ - name: Install the supported LTS SDK
+ uses: actions/setup-dotnet@0f4a354dd5547a28c70b7853dbd95d5b67886e73 # v6.1.0
+ with:
+ dotnet-version: "10.0.404"
+ - name: Verify the isolated SDK and runtime
+ run: |
+ test "$(dotnet --version)" = '10.0.404'
+ dotnet --list-runtimes | tee "$RUNNER_TEMP/dotnet-runtimes.txt"
+ python3 - <<'PY'
+ import os
+ from pathlib import Path
+ root = Path(os.environ["DOTNET_INSTALL_DIR"]).resolve()
+ rows = [line.split() for line in (Path(os.environ["RUNNER_TEMP"]) / "dotnet-runtimes.txt").read_text().splitlines()]
+ core = [row for row in rows if row[0] == "Microsoft.NETCore.App"]
+ assert len(core) == 1 and core[0][1].startswith("10."), "Unexpected test runtime"
+ assert Path(core[0][2].strip("[]")).resolve().is_relative_to(root)
+ PY
+ - name: Build and run the existing handler and loopback tests
+ run: |
+ coverage=()
+ if [[ "$GITHUB_EVENT_NAME" == pull_request ]]; then
+ coverage=(--collect 'XPlat Code Coverage')
+ fi
+ dotnet test ClickHouse.Loom.sln --configuration Release --logger trx --results-directory "$RUNNER_TEMP/dotnet-results" "${coverage[@]}"
+ - name: Locate the .NET coverage report
+ id: dotnet-coverage
+ if: github.event_name == 'pull_request'
+ continue-on-error: true
+ run: |
+ reports=("$RUNNER_TEMP"/dotnet-results/*/coverage.cobertura.xml)
+ test "${#reports[@]}" -eq 1
+ test -s "${reports[0]}"
+ printf 'report=%s\n' "${reports[0]}" >> "$GITHUB_OUTPUT"
+ - name: Report .NET SDK changed-line coverage
+ if: steps.dotnet-coverage.outcome == 'success'
+ continue-on-error: true
+ uses: ClickHouse/loom/.github/actions/patch-coverage@df405e9ed5d032b8248f6cfa8cf87e856685e490
+ with:
+ component: .NET SDK
+ working-directory: sdk/dotnet
+ report: ${{ steps.dotnet-coverage.outputs.report }}
+ - name: Require executed tests
+ run: |
+ python3 - <<'PY'
+ import os, xml.etree.ElementTree as ET
+ from pathlib import Path
+ reports = list((Path(os.environ["RUNNER_TEMP"]) / "dotnet-results").glob("*.trx"))
+ counters = [ET.parse(path).getroot().find(".//{*}Counters") for path in reports]
+ assert counters and all(row is not None for row in counters), "Missing test counters"
+ executed = sum(int(row.get("executed", "0")) for row in counters)
+ assert executed > 0, "The .NET suite executed no test"
+ assert all(int(row.get("failed", "0")) == int(row.get("error", "0")) == int(row.get("timeout", "0")) == 0 for row in counters)
+ with open(os.environ["GITHUB_STEP_SUMMARY"], "a") as output:
+ output.write(f".NET: {executed} tests executed without failure on the LTS runtime.\n")
+ PY
+ - name: Pack and install into an independent consumer
+ run: |
+ packages="$RUNNER_TEMP/loom-dotnet-packages"
+ consumer="$RUNNER_TEMP/loom-dotnet-consumer"
+ dotnet pack src/ClickHouse.Loom/ClickHouse.Loom.csproj --configuration Release --no-build --output "$packages"
+ python3 - <<'PY'
+ import os, xml.etree.ElementTree as ET
+ from pathlib import Path
+ version = ET.parse("src/ClickHouse.Loom/ClickHouse.Loom.csproj").getroot().findtext(".//Version")
+ package = Path(os.environ["RUNNER_TEMP"]) / "loom-dotnet-packages" / f"ClickHouse.Loom.{version}.nupkg"
+ assert package.is_file() and package.stat().st_size > 0
+ (Path(os.environ["RUNNER_TEMP"]) / "dotnet-package-version").write_text(version)
+ PY
+ version=$(cat "$RUNNER_TEMP/dotnet-package-version")
+ dotnet new console --framework net10.0 --output "$consumer"
+ dotnet add "$consumer" package ClickHouse.Loom --version "$version" --source "$packages"
+ printf '%s\n' 'Console.WriteLine(typeof(ClickHouse.Loom.LoomClient).FullName);' > "$consumer/Program.cs"
+ dotnet run --project "$consumer" --no-restore
+
+ ruby:
+ name: Ruby SDK (tests and installed gem)
+ runs-on: ubuntu-24.04
+ timeout-minutes: 10
+ defaults:
+ run:
+ working-directory: sdk/ruby
+ steps:
+ - name: Check out the Ruby source
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+ fetch-depth: 2
+ sparse-checkout: sdk/ruby
+ - name: Install Ruby
+ uses: ruby/setup-ruby@be3c7df29b3349ec6bcfc6b4792f1cf9f5237d18 # v1.343.0
+ with:
+ ruby-version: "3.4.13"
+ bundler-cache: false
+ - name: Install test dependencies and run the existing tests
+ env:
+ LOOM_TEST_COVERAGE: ${{ github.event_name == 'pull_request' && '1' || '' }}
+ run: |
+ bundle install --jobs 2 --retry 0
+ bundle exec rake test | tee "$RUNNER_TEMP/ruby-tests.txt"
+ - name: Report Ruby SDK changed-line coverage
+ if: github.event_name == 'pull_request'
+ continue-on-error: true
+ uses: ClickHouse/loom/.github/actions/patch-coverage@df405e9ed5d032b8248f6cfa8cf87e856685e490
+ with:
+ component: Ruby SDK
+ working-directory: sdk/ruby
+ report: sdk/ruby/coverage/lcov.info
+ - name: Require executed tests and report the count
+ run: |
+ python3 - <<'PY'
+ import os, re
+ from pathlib import Path
+ text = (Path(os.environ["RUNNER_TEMP"]) / "ruby-tests.txt").read_text()
+ counts = re.findall(r"(\d+) runs, (\d+) assertions, (\d+) failures, (\d+) errors, (\d+) skips", text)
+ assert len(counts) == 1, "Missing or ambiguous Ruby test counters"
+ runs, assertions, failures, errors, skips = map(int, counts[0])
+ assert runs > skips and assertions > 0 and failures == errors == 0
+ with open(os.environ["GITHUB_STEP_SUMMARY"], "a") as output:
+ output.write(f"Ruby: {runs} tests, {assertions} assertions, {skips} skips.\n")
+ PY
+ - name: Build and load the installed gem outside the source tree
+ run: |
+ package="$RUNNER_TEMP/clickhouse-loom.gem"
+ gem build clickhouse-loom.gemspec --output "$package"
+ test -s "$package"
+ gem install --local "$package" --no-document --install-dir "$RUNNER_TEMP/loom-ruby-gems"
+ cd "$RUNNER_TEMP"
+ GEM_HOME="$RUNNER_TEMP/loom-ruby-gems" GEM_PATH="$RUNNER_TEMP/loom-ruby-gems" ruby -rclickhouse/loom -e 'abort "Missing packaged client" unless defined?(ClickHouse::Loom::Client); puts ClickHouse::Loom::VERSION'
+
+ maintenance:
+ name: Record trusted SDK failures
+ needs: [go, java, dotnet, ruby]
+ if: >-
+ always() && github.repository == 'ClickHouse/loom' &&
+ github.ref == 'refs/heads/main' &&
+ (github.event_name == 'push' || github.event_name == 'schedule')
+ runs-on: ubuntu-24.04
+ timeout-minutes: 5
+ permissions:
+ contents: read
+ issues: write # Record synthetic SDK check failures on trusted main runs only.
+ steps:
+ - name: Reconcile failure tasks without executing project code
+ env:
+ GH_TOKEN: ${{ github.token }}
+ SDK_RESULTS: ${{ toJSON(needs) }}
+ run: |
+ python3 - <<'PY'
+ import json, os, re, subprocess
+ from urllib.parse import urlencode
+ repo = "repos/ClickHouse/loom/issues"
+ bot = "github-actions[bot]"
+ marker = re.compile(r"")
+ state = re.compile(r"")
+ titles = {key: f"[native-sdk-ci] Repair the {key} SDK check" for key in ("go", "java", "dotnet", "ruby")}
+ calls = 0
+ def api(method, endpoint, payload=None):
+ global calls
+ calls += 1
+ assert calls <= 40, "SDK issue API budget exhausted"
+ command = ["gh", "api", "--method", method, endpoint, "--hostname", "github.com"]
+ if payload is not None:
+ command += ["--input", "-"]
+ result = subprocess.run(command, input=None if payload is None else json.dumps(payload), text=True, capture_output=True, timeout=20, check=True)
+ assert len(result.stdout) <= 2 * 1024 * 1024, "SDK issue response exceeds budget"
+ return json.loads(result.stdout)
+ managed = {}
+ for page in range(1, 11):
+ issues = api("GET", repo + "?" + urlencode({"state": "all", "creator": bot, "per_page": 100, "page": page}))
+ assert isinstance(issues, list)
+ for issue in issues:
+ if "pull_request" in issue or issue.get("user", {}).get("login") != bot:
+ continue
+ keys = marker.findall(issue.get("body") or "")
+ keys += [key for key, title in titles.items() if issue.get("title") == title]
+ keys = set(keys)
+ assert len(keys) <= 1, "Conflicting SDK issue markers"
+ if keys:
+ key = keys.pop()
+ assert key not in managed, "Duplicate SDK failure task"
+ managed[key] = issue
+ if len(issues) < 100:
+ break
+ else:
+ raise RuntimeError("SDK issue pagination budget exhausted")
+ results = json.loads(os.environ["SDK_RESULTS"])
+ assert set(results) == set(titles)
+ run_id = os.environ["GITHUB_RUN_ID"]
+ assert run_id.isdecimal()
+ url = "https://github.com/ClickHouse/loom/actions/runs/" + run_id
+ changed = 0
+ for key in titles:
+ result = results[key]["result"]
+ assert result in {"success", "failure", "cancelled", "skipped"}
+ issue = managed.get(key)
+ if result not in {"success", "failure"} or (issue and issue["state"] == "closed"):
+ continue
+ text = f"\n\n\n### Company or project name\n\nClickHouse\n\nThe {key} SDK check reports **{result}** on trusted main. [Read the native build, tests and package logs]({url}).\n\nReproduce the named workflow job using the existing SDK tests. Keep security-sensitive reports in the private route in SECURITY.md. Automation preserves edited bodies and closed decisions."
+ if issue is None:
+ if result == "failure":
+ api("POST", repo, {"title": titles[key], "body": text})
+ changed += 1
+ continue
+ number = issue["number"]
+ assert isinstance(number, int) and number > 0
+ comments = api("GET", f"{repo}/{number}/comments?per_page=100")
+ assert isinstance(comments, list) and len(comments) < 100, "SDK comment history budget exhausted"
+ candidates = [issue] + sorted(comments, key=lambda row: (row["created_at"], row["id"]))
+ states = [state.findall(row.get("body") or "") for row in candidates if row.get("user", {}).get("login") == bot]
+ states = [value[-1] for value in states if value]
+ if not states or states[-1] != result:
+ api("POST", f"{repo}/{number}/comments", {"body": text})
+ changed += 1
+ with open(os.environ["GITHUB_STEP_SUMMARY"], "a") as output:
+ output.write(f"SDK task reconciliation: {changed} task or status writes; closed decisions preserved.\n")
+ PY
diff --git a/.github/workflows/workflow-lint.yml b/.github/workflows/workflow-lint.yml
index 8c1ac2133e7..6e4ee2d8760 100644
--- a/.github/workflows/workflow-lint.yml
+++ b/.github/workflows/workflow-lint.yml
@@ -22,18 +22,20 @@ jobs:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- - name: Install actionlint
+ - name: Install the workflow linter
working-directory: ${{ runner.temp }}
run: |
curl --fail --silent --show-error --location --proto '=https' --tlsv1.2 \
- https://github.com/rhysd/actionlint/releases/download/v1.7.12/actionlint_1.7.12_linux_amd64.tar.gz \
- --output actionlint.tar.gz
- echo '8aca8db96f1b94770f1b0d72b6dddcb1ebb8123cb3712530b08cc387b349a3d8 actionlint.tar.gz' | sha256sum --check --strict
- tar -xzf actionlint.tar.gz actionlint
+ --retry 2 --retry-all-errors --retry-max-time 85 --connect-timeout 10 --max-time 40 \
+ https://github.com/jdx/jactionlint/releases/download/v2.6.0/jactionlint_2.6.0_linux_amd64.tar.gz \
+ --output jactionlint.tar.gz
+ echo 'd5400967b8f0d3a5ae9a4cee21f56400a50eb3f05d0cbb4ef17184f17f0760c8 jactionlint.tar.gz' | sha256sum --check --strict
+ tar -xzf jactionlint.tar.gz jactionlint
- name: Install ShellCheck
working-directory: ${{ runner.temp }}
run: |
curl --fail --silent --show-error --location --proto '=https' --tlsv1.2 \
+ --retry 2 --retry-all-errors --retry-max-time 85 --connect-timeout 10 --max-time 40 \
https://github.com/koalaman/shellcheck/releases/download/v0.11.0/shellcheck-v0.11.0.linux.x86_64.tar.xz \
--output shellcheck.tar.xz
echo '8c3be12b05d5c177a04c29e3c78ce89ac86f1595681cab149b65b97c4e227198 shellcheck.tar.xz' | sha256sum --check --strict
@@ -44,4 +46,4 @@ jobs:
SHELLCHECK_OPTS: --severity=warning
run: |
test -x "$RUNNER_TEMP/shellcheck"
- "$RUNNER_TEMP/actionlint" -color -shellcheck="$RUNNER_TEMP/shellcheck" -pyflakes=
+ "$RUNNER_TEMP/jactionlint" --profile correctness --color --shellcheck="$RUNNER_TEMP/shellcheck" --pyflakes=
diff --git a/.github/workflows/zizmor.yml b/.github/workflows/zizmor.yml
new file mode 100644
index 00000000000..6cc1718567e
--- /dev/null
+++ b/.github/workflows/zizmor.yml
@@ -0,0 +1,172 @@
+name: workflow security findings
+
+on:
+ pull_request:
+ branches: [main, "release/**"]
+ push:
+ branches: [main, "release/**"]
+ schedule:
+ - cron: "23 6 * * 1"
+
+concurrency:
+ group: ${{ github.workflow }}-${{ github.ref }}
+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}
+
+permissions:
+ contents: read
+
+jobs:
+ audit:
+ name: Workflow security audit (report only)
+ if: github.event.repository.private == false
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ steps:
+ - name: Check out workflow definitions
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+ sparse-checkout: /.github/
+ sparse-checkout-cone-mode: false
+ - name: Install checksum-verified scanner
+ shell: bash
+ run: |
+ tool_dir="$RUNNER_TEMP/zizmor-tool"
+ mkdir -p "$tool_dir"
+ curl --fail --silent --show-error --location \
+ --retry 2 --retry-all-errors --retry-max-time 85 --connect-timeout 10 --max-time 40 \
+ https://github.com/zizmorcore/zizmor/releases/download/v1.32.0/zizmor-x86_64-unknown-linux-gnu.tar.gz \
+ --output "$tool_dir/zizmor.tar.gz"
+ echo "bb110cc765eca9cd7efb2e284a956be5974c60027b0970f16397d86208a9957b $tool_dir/zizmor.tar.gz" | sha256sum --check
+ tar --extract --gzip --file "$tool_dir/zizmor.tar.gz" --directory "$tool_dir" zizmor
+ test -x "$tool_dir/zizmor"
+ - name: Collect every workflow finding
+ shell: bash
+ run: |
+ "$RUNNER_TEMP/zizmor-tool/zizmor" --offline --strict-collection --no-config --no-ignores \
+ --persona=auditor --collect=workflows,dependabot --no-exit-codes \
+ --format=json . > "$RUNNER_TEMP/zizmor.json"
+ - name: List all findings in the job summary
+ shell: bash
+ run: |
+ python3 - <<'PYTHON'
+ from collections import Counter
+ import html
+ import json
+ import os
+ import secrets
+ from pathlib import Path
+
+ source = Path(os.environ["RUNNER_TEMP"]) / "zizmor.json"
+ if source.stat().st_size > 8 * 1024 * 1024:
+ raise ValueError("Findings exceed the report input budget")
+ findings = json.loads(source.read_text())
+ counts = Counter(finding["ident"] for finding in findings)
+ lines = [f"Total findings: {len(findings)}", ""]
+ lines.extend(f"{rule}: {count}" for rule, count in sorted(counts.items()))
+ lines.append("")
+ for finding in findings:
+ primary = next(location for location in finding["locations"]
+ if location["symbolic"]["kind"] == "Primary")
+ path = primary["symbolic"]["key"]["Local"]["verbatim_path"]
+ line = primary["concrete"]["location"]["start_point"]["row"] + 1
+ severity = finding["determinations"]["severity"]
+ confidence = finding["determinations"]["confidence"]
+ lines.append(f"{path}:{line}: {finding['ident']} [{severity}/{confidence}]")
+ lines.append(f" {finding['desc']}")
+ summary = ("## Workflow security findings\n\n"
+ "Hosted scanner: zizmor 1.32.0; network mode offline; auditor persona; workflows and dependency-update configuration.\n\n"
+ "Report only: findings need source review; a green job is not a clean audit. "
+ "Scanner, collection and reporting errors fail the job. "
+ "Every finding is listed below and in the escaped report log.\n\n"
+ "
" + html.escape("\n".join(lines)) + "
\n")
+ if len(summary.encode("utf-8")) > 900_000:
+ raise ValueError("Complete findings exceed the job summary budget")
+ with open(os.environ["GITHUB_STEP_SUMMARY"], "a", encoding="utf-8") as output:
+ output.write(summary)
+ command_token = secrets.token_hex(16)
+ print(f"::stop-commands::{command_token}")
+ print(json.dumps(
+ {"total": len(findings), "by_rule": dict(sorted(counts.items())), "lines": lines},
+ ensure_ascii=True,
+ ))
+ print(f"::{command_token}::")
+ PYTHON
+ maintenance_issues:
+ name: Publish workflow maintenance issues
+ if: github.repository == 'ClickHouse/loom' && github.event.repository.private == false && github.ref == 'refs/heads/main' && (github.event_name == 'push' || github.event_name == 'schedule')
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ permissions:
+ contents: read
+ issues: write # Create maintenance tasks and append deduplicated status updates.
+ steps:
+ - name: Check out trusted workflow tooling
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+ sparse-checkout: /.github/
+ sparse-checkout-cone-mode: false
+ - name: Install checksum-verified scanner
+ shell: bash
+ run: |
+ tool_dir="$RUNNER_TEMP/zizmor-tool"
+ mkdir -p "$tool_dir"
+ curl --fail --silent --show-error --location \
+ --retry 2 --retry-all-errors --retry-max-time 85 --connect-timeout 10 --max-time 40 \
+ https://github.com/zizmorcore/zizmor/releases/download/v1.32.0/zizmor-x86_64-unknown-linux-gnu.tar.gz \
+ --output "$tool_dir/zizmor.tar.gz"
+ echo "bb110cc765eca9cd7efb2e284a956be5974c60027b0970f16397d86208a9957b $tool_dir/zizmor.tar.gz" | sha256sum --check
+ tar --extract --gzip --file "$tool_dir/zizmor.tar.gz" --directory "$tool_dir" zizmor
+ test -x "$tool_dir/zizmor"
+ - name: Collect trusted maintenance evidence
+ shell: bash
+ run: |
+ "$RUNNER_TEMP/zizmor-tool/zizmor" --offline --strict-collection --no-config --no-ignores \
+ --persona=auditor --collect=workflows,dependabot --no-exit-codes \
+ --format=json . > "$RUNNER_TEMP/zizmor.json"
+ - name: Reconcile automatic maintenance issues
+ env:
+ GH_TOKEN: ${{ github.token }}
+ shell: bash
+ run: python3 .github/scripts/workflow_audit_issues.py "$RUNNER_TEMP/zizmor.json"
+
+ security_alerts:
+ name: Publish workflow code scanning alerts
+ if: github.repository == 'ClickHouse/loom' && github.event.repository.private == false && github.ref == 'refs/heads/main' && (github.event_name == 'push' || github.event_name == 'schedule')
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ permissions:
+ contents: read
+ security-events: write # Send security findings to the existing code scanning view.
+ steps:
+ - name: Check out trusted workflow tooling
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+ sparse-checkout: /.github/
+ sparse-checkout-cone-mode: false
+ - name: Install checksum-verified scanner
+ shell: bash
+ run: |
+ tool_dir="$RUNNER_TEMP/zizmor-tool"
+ mkdir -p "$tool_dir"
+ curl --fail --silent --show-error --location \
+ --retry 2 --retry-all-errors --retry-max-time 85 --connect-timeout 10 --max-time 40 \
+ https://github.com/zizmorcore/zizmor/releases/download/v1.32.0/zizmor-x86_64-unknown-linux-gnu.tar.gz \
+ --output "$tool_dir/zizmor.tar.gz"
+ echo "bb110cc765eca9cd7efb2e284a956be5974c60027b0970f16397d86208a9957b $tool_dir/zizmor.tar.gz" | sha256sum --check
+ tar --extract --gzip --file "$tool_dir/zizmor.tar.gz" --directory "$tool_dir" zizmor
+ test -x "$tool_dir/zizmor"
+ - name: Collect trusted security findings
+ shell: bash
+ run: |
+ "$RUNNER_TEMP/zizmor-tool/zizmor" --offline --strict-collection --no-config --no-ignores \
+ --persona=auditor --collect=workflows,dependabot --no-exit-codes \
+ --format=sarif . > "$RUNNER_TEMP/zizmor.sarif"
+ test "$(wc -c < "$RUNNER_TEMP/zizmor.sarif")" -le 8388608
+ - name: Upload workflow findings to code scanning
+ uses: github/codeql-action/upload-sarif@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3
+ with:
+ sarif_file: ${{ runner.temp }}/zizmor.sarif
+ category: zizmor-workflows
diff --git a/.gitignore b/.gitignore
index a1dc079bda5..22a26a11f48 100644
--- a/.gitignore
+++ b/.gitignore
@@ -15,6 +15,11 @@
*.key
secrets.json
+# Qualification state and results can contain credentials.
+/integrations/librechat/qualification/.state.json
+/integrations/librechat/qualification/results.json
+/integrations/librechat/qualification/results-*.json
+
# ============================================================
# Frontend (React/Vite dashboard served at /) — node deps + build output
# ============================================================
@@ -24,6 +29,7 @@ docs/node_modules/
docs/.blume/
docs/.blume-content/
docs/.vercel/
+docs/public/docs-media/
frontend/dist/
frontend/.vite/
frontend/*.log
@@ -65,6 +71,9 @@ htmlcov/
nosetests.xml
coverage.xml
coverage.json
+/frontend/coverage/
+/sdk/ruby/coverage/
+/sdk/typescript/coverage/
*.cover
*.py,cover
.tox/
diff --git a/.prettierignore b/.prettierignore
index d76f89417ec..caacefdcb6b 100644
--- a/.prettierignore
+++ b/.prettierignore
@@ -26,6 +26,7 @@ scripts/scip_harness/vendor/
# Prompt text agents read verbatim: padding costs tokens on every session.
skills/
integrations/**/skills/
+server/transport/served_skills/
.claude/skills/
.claude/rules/
.claude/agents/
diff --git a/CITATION.cff b/CITATION.cff
index f31f2caf79b..763d0e1228e 100644
--- a/CITATION.cff
+++ b/CITATION.cff
@@ -8,7 +8,7 @@ type: software
authors:
- name: "ClickHouse, Inc."
repository-code: "https://github.com/ClickHouse/loom"
-url: "https://clickhouse.github.io/loom/"
+url: "https://loom.clickhouse.com/docs/"
license: Apache-2.0
keywords:
- agent memory
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 450e4fc299a..72005e89f6a 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -52,6 +52,17 @@ same issue searches to choose a related test, example or small fix for your next
The repository's [contributor history](https://github.com/ClickHouse/loom/graphs/contributors)
and merged pull requests record contributions.
+## Contribute a test report
+
+Reproducing a failure, checking an installation instruction or trying a dashboard task
+is a contribution; a product-code patch is optional. Start with one track in the
+[source contribution lab](.devcontainer/source/README.md#run-a-bounded-check-in-a-public-fork).
+Its disposable checks need no provider account.
+
+Use the lab's [report guidance](.devcontainer/source/README.md#report-what-failed) to
+describe what you tested, the smallest reproduction and the expected result. It also
+explains which investigations need a separate private stack or package check.
+
## Filing an issue
Every issue goes through a form in `.github/ISSUE_TEMPLATE/`; pick the one that fits:
@@ -160,7 +171,8 @@ git config blame.ignoreRevsFile .git-blame-ignore-revs
## Commits and sign-offs (DCO)
- **Messages say why.** The diff says what changed.
-- **Sign off every commit** under the [Developer Certificate of Origin](https://developercertificate.org/): `git commit -s -m "your message"`. There is no CLA.
+- **Sign off every commit** under the [Developer Certificate of Origin](https://developercertificate.org/): `git commit -s -m "your message"`.
+- **Sign the Contributor License Agreement (CLA)** in addition to signing off each commit. If you still need to sign the [ClickHouse Individual Contributor License Agreement](https://gist.github.com/clickhouse-admin/e7369fa5e6541e28e8645f9e095d3596), CLA assistant posts a signing link on your pull request.
- **Comments explain why**, not what or when: no history, dates, names or ticket numbers in source.
## Material changes
@@ -203,7 +215,7 @@ With an allowance and the restricted runner configured, translation follows an E
`python -m scripts.i18n.translate check` reports every missing, stale and obsolete page across all five translation locales. `check --skip-stale` permits pending coverage but still checks present stamps, banners, links, anchors and translated labels, plus the content invariants of current output. Ordinary PR tests follow this asynchronous contract. A changed prompt requires an explicit `update --all`; a generated refresh receipt tracks that request across bounded scheduled batches and pending-branch reuse. Completed source/output proofs prevent repeated calls; the receipt stays until main contains those results. A concurrent main translation is preserved when it differs from the refresh's recorded base output. Model and banner changes invalidate stamps automatically.
-The updater imports only validated generated blobs from `i18n/update`, preserving fresh main output. Owned output outside a selected batch can remain as hidden checkpoint data after its English source changes or disappears. Such archives never become publication routes; activation still requires current source, model and content validation. A conflicting existing checkpoint refuses replacement so both versions remain recoverable. It executes no code from that branch. It dispatches hosted CI for the exact bot commit because PR events created with `GITHUB_TOKEN` do not start CI. A hosted finalizer checks the successful commit, generated diff, current main parent, current language approval and repository review requirements before merging. Required human reviews remain required. After merge it explicitly dispatches the docs-site workflow; publication also requires the site's deployment configuration. A newer main commit defers merging until the producer composes another batch.
+The updater imports only validated generated blobs from `i18n/update`, preserving fresh main output. Owned output outside a selected batch can remain as hidden checkpoint data after its English source changes or disappears. Such archives never become publication routes; activation still requires current source, model and content validation. A conflicting existing checkpoint refuses replacement so both versions remain recoverable. It executes no code from that branch. It dispatches hosted CI for the exact bot commit because PR events created with `GITHUB_TOKEN` do not start CI. A hosted finalizer checks for successful CI on a 15-minute schedule. Finalization checks and translation batches wait in the same queue and run one at a time. It checks the exact commit, generated diff, current main parent, current language approval and repository review requirements before merging. Required human reviews remain required. After merge it explicitly dispatches the docs-site workflow; publication also requires the site's deployment configuration. A newer main commit defers merging until the producer composes another batch.
The script calls Claude Sonnet 5.5 on Amazon Bedrock through `AnthropicBedrock`. Local runs also spend money and require separate authorization. For an authorized run:
@@ -271,7 +283,9 @@ Docs follow the [documentation style guide](./docs/development/documentation-sty
- **Title:** a sentence saying what is now true, as in `git log` (e.g. `MCP reads the bearer from the Authorization header only, never from ?token=`).
- **Body:** fill the template (`.github/PULL_REQUEST_TEMPLATE.md`). It opens with the linked issues (`Closes:` / `Related:`, full URLs) and a **changelog category** with a one- or two-sentence **changelog entry** a user can read without the diff; the release pull request collects those entries into its release notes. Then **Why**, **Scope and risk**, **Compatibility, rollout and rollback** (ops and fields added, changed or removed, operator steps, what a revert leaves behind), **Tests** (what you ran and what it showed) and how AI tools were used. Its checklist matches what CI and repository policy enforce.
- **Measurements** that justify a change go in the description with the command that reproduces them, not in code comments or docs.
-- CI must be green before merge. Squash-merge is the default: one logical change per pull request.
+- Before merge, CI must pass for the current commit, required GitHub approvals must be present, and required review conversations must be resolved. The pull request page shows what remains.
+- A local review report does not submit a GitHub approval. After pushing changes, follow the updated checks and review requirements on the pull request.
+- Squash-merge is the default: one logical change per pull request.
## Working with a coding agent
diff --git a/Dockerfile b/Dockerfile
index 9a45ff68234..868198e911b 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -184,8 +184,6 @@ COPY sdk ./sdk
# at runtime to compute expected-vs-present table drift. Without them
# the endpoint flags every existing table as "extra".
COPY schemas ./schemas
-# The assistant's agent definition, which a boot seeds into the LibreChat beside it.
-COPY integrations/librechat/agent.yaml ./integrations/librechat/agent.yaml
# The compiler-tier workers (code_scip_delta, code_scip_go_delta,
# code_scip_ts_delta, code_scip_py_delta) shell out to scripts/scip_harness/run_*.sh resolved
# relative to server/ — without this COPY every in-container pass reports the
diff --git a/Makefile b/Makefile
index 95e67088b3b..74dabf9df0d 100644
--- a/Makefile
+++ b/Makefile
@@ -315,8 +315,8 @@ bench-clickgap-replay:
# Hygiene: the CI lint job's checks, minus formatting and types (format-check,
# typecheck). Every generated file with a --check (SDK tables, Codex plugin
-# copies, the configuration and docs/reference tables, the reach manifest) must match its
-# source; regenerate with the script named in the failure.
+# copies, the served skills, the configuration and docs/reference tables, the reach
+# manifest) must match its source; regenerate with the script named in the failure.
lint:
$(PYTHON) -m ruff check server extractor sdk/python tests scripts .claude
$(PYTHON) scripts/gates/function_length_gate.py
@@ -326,7 +326,12 @@ lint:
$(PYTHON) scripts/codegen/sdk_py_admin_gen.py --check
$(PYTHON) scripts/codegen/sdk_ts_gen.py --check
$(PYTHON) scripts/codegen/sdk_rb_gen.py --check
+ $(PYTHON) scripts/codegen/sdk_rust_gen.py --check
+ $(PYTHON) scripts/codegen/sdk_rust_gen.py --fixtures --check
+ $(PYTHON) scripts/codegen/sdk_go_gen.py --check
$(PYTHON) scripts/codegen/agent_plugin_sync.py --check
+ $(PYTHON) scripts/codegen/standalone_skills.py --check
+ $(PYTHON) scripts/codegen/served_skills.py --check
$(PYTHON) scripts/codegen/settings_reference.py --check
$(PYTHON) scripts/codegen/settings_schema.py --check
$(PYTHON) scripts/codegen/settings_example.py --check
diff --git a/README.md b/README.md
index dc0f3172041..6e69f4bdbf0 100644
--- a/README.md
+++ b/README.md
@@ -26,7 +26,7 @@
Get started ·
Capabilities ·
Integrations ·
- Documentation
+ Documentation
@@ -42,7 +42,7 @@ read or write roles. [Check shared memory and denied access](./docs/getting-star
Agents connect through MCP, HTTP, Python or TypeScript. Self-host with Docker or
[on Kubernetes with the Helm chart](./docs/operations/kubernetes.md); agent context and
-index data live in [ClickHouse](./docs/use-cases/self-hosted-clickhouse.md), and a
+index data live in [ClickHouse](https://loom.clickhouse.com/docs/use-cases/self-hosted-clickhouse), and a
deployment can choose [Postgres at first boot](./docs/operations/postgres.md) for live
memory and knowledge state. The dashboard brings memories, repositories, tasks and runs
into one place.
@@ -51,27 +51,32 @@ into one place.
- **Long-term memory shared across your coding agents**, with plugins that load context
at session start and capture the session as it runs.
- [Agent memory](./docs/use-cases/agent-memory.md) ·
+ [Memory for coding agents](https://loom.clickhouse.com/docs/use-cases/agent-memory) ·
+ [Choose a memory setup](https://loom.clickhouse.com/agent-memory-selector) ·
+ [Compare memory options](https://loom.clickhouse.com/docs/guides/compare-coding-agent-memory) ·
[Connect a coding agent](./docs/getting-started/connect-a-coding-agent.md)
- **Memory for an agent application**, per user, from the Python or TypeScript
SDK. [Your first agent](./docs/getting-started/first-agent.md)
- **A multi-user MCP memory server** with namespaces, roles and tokens.
[Multi-user mode](./docs/getting-started/quickstart.md#start-in-multi-user-mode) ·
- [Namespaces and sharing](./docs/features/namespaces-and-sharing.md)
+ [Namespaces and sharing](./docs/features/namespaces-and-sharing.md) ·
+ [MCP client setup](https://loom.clickhouse.com/docs/features/integrations/mcp-clients)
- **A code index of your repositories** that coding agents query for definitions,
callers and change impact. [Code index](./docs/use-cases/code-intelligence.md) ·
[Language support and limits](./docs/features/code-index/overview.md#language-support)
- **Memories linked to the code they are about**, which follow it through refactors, are
flagged when it changes and appear when an agent reads or edits it.
- [Memory linked to code](./docs/use-cases/memory-linked-to-code.md)
+ [Memory linked to code](https://loom.clickhouse.com/docs/use-cases/memory-linked-to-code)
- **Lower model cost for coding agents**, as [measured](#measured-results) below.
[Coding-agent cost](./docs/use-cases/coding-agent-cost.md)
- **Document search with citations (RAG)**, including PDF, `.docx` and `.pptx` files the
extractor service converts. [Document search](./docs/use-cases/document-search.md)
+- **A knowledge factory for AI agents** that turns runbooks and lessons from agent work
+ into answers backed by sources. [Build a knowledge factory](https://loom.clickhouse.com/docs/use-cases/knowledge-factory)
- **Shared context for multi-agent workflows**: shared memory, task inboxes and
decisions. [Multi-agent](./docs/use-cases/multi-agent.md)
- **Memory, recall, audit and erasure for autonomous agents.**
- [Autonomous agents](./docs/use-cases/autonomous-agents.md)
+ [Memory for autonomous agents](https://loom.clickhouse.com/docs/use-cases/autonomous-agents)
- **A record of agent work**, with searchable conversations (when recording is on),
session briefs to resume from, runs with their goals, outcomes and model costs when
supplied, and PR and tracker history.
@@ -83,8 +88,8 @@ access with tokens, await required writes and task handoffs in your application,
recheck code-linked lessons against the current source before review. The same service
supports multi-agent workflows and autonomous bots; your orchestration runs the agents,
tests and approvals. Offering a tool does not guarantee the model uses it.
-[Multi-agent workflow](./docs/use-cases/multi-agent.md) ·
-[Autonomous-agent memory](./docs/use-cases/autonomous-agents.md)
+[Software factory memory workflow](https://loom.clickhouse.com/docs/use-cases/multi-agent#memory-for-a-software-factory) ·
+[Autonomous-agent memory](https://loom.clickhouse.com/docs/use-cases/autonomous-agents)
Every use case, and when another tool fits better: [use cases](./docs/use-cases/index.md).
@@ -308,12 +313,12 @@ and the full protocols, models and artifacts.
## Documentation and contributing
For shared agent context, code intelligence and permissioned retrieval, start with the
-[documentation](https://clickhouse.github.io/loom/). For deployment requirements, see the
+[documentation](https://loom.clickhouse.com/docs). For deployment requirements, see the
[prerequisites](./docs/getting-started/overview.md#prerequisites).
[Deployment](./docs/operations/deployment.md) · [FAQ](./docs/faq.md) ·
[Contributing](./CONTRIBUTING.md) · [Security reporting](./SECURITY.md) ·
-[`llms.txt`](https://clickhouse.github.io/loom/llms.txt) ·
-[`llms-full.txt`](https://clickhouse.github.io/loom/llms-full.txt)
+[`llms.txt`](https://loom.clickhouse.com/docs/llms.txt) ·
+[`llms-full.txt`](https://loom.clickhouse.com/docs/llms-full.txt)
Apache-2.0 · [License](./LICENSE) · [Notice](./NOTICE)
diff --git a/SECURITY.md b/SECURITY.md
index a8293760615..34338637131 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -2,7 +2,11 @@
## Reporting a vulnerability
-Email `security@clickhouse.com` with `[loom]` in the subject. Do not open a public GitHub issue for security-sensitive findings.
+Open the repository's [security page](https://github.com/ClickHouse/loom/security),
+select **Report a vulnerability**, and complete the private reporting form.
+The report is shared with repository maintainers without opening a public issue.
+
+You can also email `security@clickhouse.com` with `[loom]` in the subject. Do not open a public GitHub issue for security-sensitive findings.
Please include, where it makes sense:
diff --git a/bench/code_grep_handler.py b/bench/code_grep_handler.py
index 4d2669da643..7ffc3e14e01 100644
--- a/bench/code_grep_handler.py
+++ b/bench/code_grep_handler.py
@@ -159,7 +159,7 @@ def _input(call: dict[str, Any]) -> Any:
"mode": call["m"],
"path_prefix": call["path_prefix"] or "",
}
- for k in ("regex", "case_sensitive", "limit", "neighbours"):
+ for k in ("regex", "case_sensitive", "limit", "neighbours", "include_body"):
if k in args and args[k] is not None:
kw[k] = args[k]
return CodeGrepInput(**kw)
diff --git a/bench/judges.py b/bench/judges.py
index 20ccab5f36f..88bea2a43e0 100644
--- a/bench/judges.py
+++ b/bench/judges.py
@@ -1,6 +1,6 @@
"""One chat call for bench readers and judges, on either provider.
-The request is shaped the way Loom's own clients shape it: `server/llm/openai.py`
+The request is shaped the way Loom's own clients shape it: `server/llm/chat_completions.py`
and `server/llm/anthropic.py` build the payload, and `server/llm/traits.py` learns
each model's refused fields, lowest reasoning effort, output limit and the room
its hidden reasoning needs from the provider's answers; there is no model list here.
@@ -24,6 +24,7 @@
from server.llm import anthropic as _anthropic
from server.llm import openai as _openai
from server.llm import traits
+from server.llm.chat_completions import ChatCompletions
ANTHROPIC_URL = "https://api.anthropic.com/v1/messages"
@@ -58,18 +59,39 @@ async def achat(
def build() -> dict[str, Any]:
return _anthropic._payload(model, system, prompt, max_tokens, 0.0)
- learn, starved = _anthropic._learn_from_refusal, _anthropic._thinking_starved
+ def learn(model_name: str, resp: httpx.Response, sent: dict[str, Any]) -> bool:
+ return _anthropic._refusal(model_name, resp, sent) is not None
+
+ starved = _anthropic._thinking_starved
hidden, cap_field = _anthropic._thinking_tokens, "max_tokens"
else:
key = api_key or os.environ.get("OPENAI_API_KEY", "")
url = openai_chat_url()
headers = {"Authorization": f"Bearer {key}"}
+ wire = ChatCompletions()
+ call = _openai.Call(
+ system=system,
+ user=prompt,
+ max_tokens=max_tokens,
+ response_format=None,
+ temperature=0.0,
+ effort="",
+ )
+
def build() -> dict[str, Any]:
- return _openai._payload(model, system, prompt, max_tokens, None, 0.0)
+ return wire.payload(model, call)
+
+ def learn(model_name: str, resp: httpx.Response, sent: dict[str, Any]) -> bool:
+ return _openai.learn_from_refusal(wire, model_name, resp, sent)
+
+ def starved(data: dict[str, Any]) -> bool:
+ return wire.reply(data).starved
+
+ def hidden(data: dict[str, Any]) -> int:
+ return wire.reply(data).hidden
- learn, starved = _openai._learn_from_refusal, _openai._starved
- hidden, cap_field = _openai._reasoning_tokens, ""
+ cap_field = ""
payload = build()
r = await client.post(url, headers=headers, json=payload, timeout=timeout_s)
diff --git a/bench/models_used.py b/bench/models_used.py
index b51bc8d1113..dd297e776f3 100644
--- a/bench/models_used.py
+++ b/bench/models_used.py
@@ -29,6 +29,7 @@
"memory_extract_verify_models",
"code_search_hyde_model",
"code_search_concept_expand_model",
+ "code_search_pick_model",
}
)
diff --git a/compose.yaml b/compose.yaml
index e4ba7cc1929..55333b1a65c 100644
--- a/compose.yaml
+++ b/compose.yaml
@@ -3,7 +3,6 @@
# COMPOSE_PROFILES=bundled start the clickhouse service below (the default)
# COMPOSE_PROFILES= use the ClickHouse that LOOM_CH_* in .env names:
# a self-managed server or ClickHouse Cloud
-# ...,assistant also run the assistant's LibreChat (librechat below)
#
# install.sh writes .env for either choice, and docs/operations/deployment.md
# covers both. The release bundle ships this file with the repository's layout,
@@ -100,11 +99,10 @@ services:
# this host and the container has no limits, so the image's own default
# (one per host CPU and GiB) could leave it no room.
LOOM_WEB_WORKERS: "${LOOM_WEB_WORKERS:-2}"
- # The assistant profile's LibreChat; unset, the server sets no assistant up.
- LOOM_ASSISTANT_LIBRECHAT_URL: "${LOOM_ASSISTANT_LIBRECHAT_URL:-}"
+ LOOM_ASSISTANT_ENABLED: "${LOOM_ASSISTANT_ENABLED:-false}"
volumes:
- loom-code-repos:/app/var/code_repos
- networks: [default, extractor, assistant]
+ networks: [default, extractor]
healthcheck:
test:
[
@@ -142,64 +140,10 @@ services:
cpus: 1
pids_limit: 64
- # The assistant (`assistant` in COMPOSE_PROFILES): LibreChat runs the agent Loom seeds,
- # headless.
- # Neither it nor its MongoDB publishes a port. The internal `assistant` network
- # joins LibreChat to the loom service alone, and `assistant-db` to its MongoDB
- # alone, so the loom container (which builds repository code) cannot reach that
- # database; LibreChat also has `assistant-egress`, a network of its own, to reach
- # its model provider, so it reaches neither ClickHouse nor the extractor
- # (docs/architecture/assistant.md#deployment).
- librechat:
- profiles: [assistant]
- image: registry.librechat.ai/librechat-ai/librechat:v0.8.8@sha256:5b706bcee1ca154a1e2987303aaeca0eb27f97919cccee4bb604226c2f8abf61
- restart: unless-stopped
- depends_on: [librechat-mongo]
- environment:
- # Its secrets and model key, from .env beside this file
- # (docs/features/integrations/librechat.md#the-deployed-assistant).
- CREDS_KEY: "${LIBRECHAT_CREDS_KEY:-}"
- CREDS_IV: "${LIBRECHAT_CREDS_IV:-}"
- JWT_SECRET: "${LIBRECHAT_JWT_SECRET:-}"
- JWT_REFRESH_SECRET: "${LIBRECHAT_JWT_REFRESH_SECRET:-}"
- # A name of its own: the loom service loads all of .env, and an ANTHROPIC_API_KEY
- # there would become Loom's own model key.
- ANTHROPIC_API_KEY: "${LIBRECHAT_ANTHROPIC_API_KEY:-}"
- # A model server on the Docker host, for LOOM_ASSISTANT_PROVIDER=local.
- LOCAL_LLM_BASE_URL: "${LIBRECHAT_LOCAL_LLM_BASE_URL:-http://host.docker.internal:11434/v1}"
- HOST: 0.0.0.0
- PORT: "3080"
- MONGO_URI: mongodb://librechat-mongo:27017/LibreChat
- CONFIG_PATH: /app/librechat.yaml
- SEARCH: "false"
- ALLOW_REGISTRATION: "true"
- ALLOW_UNVERIFIED_EMAIL_LOGIN: "true"
- BAN_VIOLATIONS: "false"
- extra_hosts:
- - "host.docker.internal:host-gateway"
- volumes:
- - ./deploy/librechat/assistant.librechat.yaml:/app/librechat.yaml:ro
- networks: [assistant, assistant-db, assistant-egress]
-
- librechat-mongo:
- profiles: [assistant]
- image: mongo:8.0.20@sha256:098862b1339f031900ca66cf8fef799e616d6324fa41b9a263f2ec899552c1ef
- restart: unless-stopped
- command: mongod --noauth --quiet
- volumes:
- - librechat-mongo:/data/db
- networks: [assistant-db]
-
networks:
extractor:
internal: true
- assistant:
- internal: true
- assistant-db:
- internal: true
- assistant-egress: {}
volumes:
loom-ch-data:
loom-code-repos:
- librechat-mongo:
diff --git a/deploy/helm/loom/Chart.yaml b/deploy/helm/loom/Chart.yaml
index c7f2145d64c..aed28ce7475 100644
--- a/deploy/helm/loom/Chart.yaml
+++ b/deploy/helm/loom/Chart.yaml
@@ -5,7 +5,7 @@ type: application
version: 0.3.0
appVersion: "1.3.0"
kubeVersion: ">=1.27.0-0"
-home: https://clickhouse.github.io/loom/
+home: https://loom.clickhouse.com/docs/
sources:
- https://github.com/ClickHouse/loom
keywords:
diff --git a/deploy/helm/loom/templates/_helpers.tpl b/deploy/helm/loom/templates/_helpers.tpl
index ddda25aca8c..512d3318a67 100644
--- a/deploy/helm/loom/templates/_helpers.tpl
+++ b/deploy/helm/loom/templates/_helpers.tpl
@@ -48,24 +48,6 @@ app.kubernetes.io/name: {{ include "loom.name" . | trunc 53 | trimSuffix "-" }}-
app.kubernetes.io/instance: {{ .Release.Name }}
{{- end }}
-{{- define "loom.assistantName" -}}
-{{- include "loom.suffixed" (dict "root" . "suffix" "librechat") }}
-{{- end }}
-
-{{- define "loom.assistantSelectorLabels" -}}
-app.kubernetes.io/name: {{ include "loom.name" . | trunc 53 | trimSuffix "-" }}-librechat
-app.kubernetes.io/instance: {{ .Release.Name }}
-{{- end }}
-
-{{- define "loom.assistantMongoName" -}}
-{{- include "loom.suffixed" (dict "root" . "suffix" "librechat-mongo" "max" 52) }}
-{{- end }}
-
-{{- define "loom.assistantMongoSelectorLabels" -}}
-app.kubernetes.io/name: {{ include "loom.name" . | trunc 47 | trimSuffix "-" }}-librechat-mongo
-app.kubernetes.io/instance: {{ .Release.Name }}
-{{- end }}
-
{{- define "loom.serviceAccountName" -}}
{{- if .Values.serviceAccount.create }}
{{- default (include "loom.fullname" .) .Values.serviceAccount.name }}
@@ -239,11 +221,10 @@ LOOM_PG_POOL_MAX_SIZE: {{ $pg.poolMaxSize | quote }}
# The release's extractor (extractor.yaml); its token is in the release Secret.
LOOM_DOCUMENT_EXTRACTOR_URL: {{ printf "http://%s:8790" (include "loom.extractorName" .) | quote }}
{{- end }}
-{{- $ownAssistant := hasKey .Values.env "LOOM_ASSISTANT_LIBRECHAT_URL" }}
-{{- range .Values.extraEnv }}{{ if eq .name "LOOM_ASSISTANT_LIBRECHAT_URL" }}{{ $ownAssistant = true }}{{ end }}{{ end }}
-{{- if and .Values.assistant.enabled (not $ownAssistant) }}
-# The release's LibreChat (assistant.yaml), which runs the agent Loom seeds.
-LOOM_ASSISTANT_LIBRECHAT_URL: {{ printf "http://%s:3080" (include "loom.assistantName" .) | quote }}
+{{- $ownAssistant := hasKey .Values.env "LOOM_ASSISTANT_ENABLED" }}
+{{- range .Values.extraEnv }}{{ if eq .name "LOOM_ASSISTANT_ENABLED" }}{{ $ownAssistant = true }}{{ end }}{{ end }}
+{{- if not $ownAssistant }}
+LOOM_ASSISTANT_ENABLED: {{ dig "nativeEnabled" false (.Values.assistant | default dict) | quote }}
{{- end }}
# The web processes' shared files: serve.sh makes $XDG_RUNTIME_DIR/loom, 0700
# and owned by the pod's user (an emptyDir itself is neither).
@@ -337,7 +318,6 @@ upgraded with --reuse-values from a chart without the block has none. */}}
{{- if $tls.secretName -}}
{{- if not (kindIs "string" $tls.secretName) }}{{ fail "tls.secretName must be the name of a kubernetes.io/tls Secret" }}{{ end -}}
{{- if not (has (toString $tls.minVersion) (list "1.2" "1.3")) }}{{ fail "tls.minVersion must be \"1.2\" or \"1.3\"" }}{{ end -}}
-{{- if dig "enabled" false (.Values.assistant | default dict) }}{{ fail "assistant.enabled calls Loom's port over plain HTTP, which tls.secretName turns off: turn one of them off" }}{{ end -}}
{{- $ingress := .Values.ingress | default dict -}}
{{- if and $ingress.enabled (eq (toString $ingress.className) "alb") -}}
{{- /* The controller also reads these from the Service, where they win over the Ingress's. */}}
diff --git a/deploy/helm/loom/templates/assistant-config.yaml b/deploy/helm/loom/templates/assistant-config.yaml
deleted file mode 100644
index 5503d77e945..00000000000
--- a/deploy/helm/loom/templates/assistant-config.yaml
+++ /dev/null
@@ -1,61 +0,0 @@
-{{- /* The assistant's LibreChat configuration, apart from assistant.yaml so the
-Deployment's checksum/config annotation can hash it. */}}
-{{- with .Values.assistant }}
-{{- if .enabled }}
-{{- $name := include "loom.assistantName" $ }}
-{{- $loom := include "loom.fullname" $ }}
-apiVersion: v1
-kind: ConfigMap
-metadata:
- name: {{ $name }}
- labels:
- {{- include "loom.labels" $ | nindent 4 }}
- app.kubernetes.io/component: assistant
-data:
- # deploy/librechat/assistant.librechat.yaml, with the release's Loom Service
- # as the MCP server (tests/unit/test_assistant_deployment.py keeps them equal).
- librechat.yaml: |
- version: 1.3.17
- cache: true
- interface:
- agents: { use: true, create: true, share: false, public: false }
- remoteAgents: { use: true, create: true, share: false, public: false }
- mcpServers: { use: true, create: false, share: false, public: false }
- sharedLinks: { share: false, public: false }
- memory:
- disabled: true
- registration:
- socialLogins: []
- endpoints:
- anthropic:
- titleConvo: false
- agents:
- capabilities: ["tools"]
- custom:
- # A model server the operator runs, for LOOM_ASSISTANT_PROVIDER=local: Ollama,
- # llama.cpp's server or another chat-completions server at LOCAL_LLM_BASE_URL. It
- # takes no key; LibreChat needs one written. The agent may name a model off the
- # list, which is never fetched, so a deployment without the server logs nothing.
- - name: local
- apiKey: local
- baseURL: "${LOCAL_LLM_BASE_URL}"
- models:
- default: ["qwen2.5:3b"]
- fetch: false
- titleConvo: false
- mcpSettings:
- allowedAddresses:
- - {{ $loom }}:{{ $.Values.service.port }}
- mcpServers:
- loom:
- type: streamable-http
- url: http://{{ $loom }}:{{ $.Values.service.port }}/mcp?toolset=assistant
- requiresOAuth: false
- startup: false
- timeout: 60000
- serverInstructions: false
- headers:
- Authorization: "Bearer {{ "{{" }}LIBRECHAT_BODY_PARENTMESSAGEID{{ "}}" }}"
- X-Loom-Run-Id: "{{ "{{" }}LIBRECHAT_BODY_MESSAGEID{{ "}}" }}"
-{{- end }}
-{{- end }}
diff --git a/deploy/helm/loom/templates/assistant.yaml b/deploy/helm/loom/templates/assistant.yaml
deleted file mode 100644
index 0b389f52d9c..00000000000
--- a/deploy/helm/loom/templates/assistant.yaml
+++ /dev/null
@@ -1,274 +0,0 @@
-{{- /* The assistant: LibreChat runs, headless, the agent Loom seeds, with a MongoDB of
-its own. Neither is exposed. LibreChat admits only the release's Loom pods and
-reaches DNS, its MongoDB, the Loom pods (the agent's tools) and TCP 443 for its model
-provider; MongoDB admits only LibreChat and reaches nothing. Both run non-root on a
-read-only root filesystem. */}}
-{{- with .Values.assistant }}
-{{- if .enabled }}
-{{- if not .existingSecret }}
-{{- fail "assistant.existingSecret is required: a Secret with CREDS_KEY, CREDS_IV, JWT_SECRET, JWT_REFRESH_SECRET and ANTHROPIC_API_KEY (or LOCAL_LLM_BASE_URL for a local assistant)" }}
-{{- end }}
-{{- $name := include "loom.assistantName" $ }}
-{{- $mongo := include "loom.assistantMongoName" $ }}
-apiVersion: apps/v1
-kind: Deployment
-metadata:
- name: {{ $name }}
- labels:
- {{- include "loom.labels" $ | nindent 4 }}
- app.kubernetes.io/component: assistant
-spec:
- # LibreChat keeps its run bookkeeping in memory (no Redis): one replica, never two
- # during a rollout.
- replicas: 1
- strategy:
- type: Recreate
- selector:
- matchLabels:
- {{- include "loom.assistantSelectorLabels" $ | nindent 6 }}
- template:
- metadata:
- labels:
- {{- include "loom.assistantSelectorLabels" $ | nindent 8 }}
- app.kubernetes.io/component: assistant
- annotations:
- # LibreChat reads its configuration at start: a changed one restarts it.
- checksum/config: {{ include (print $.Template.BasePath "/assistant-config.yaml") $ | sha256sum }}
- spec:
- automountServiceAccountToken: false
- enableServiceLinks: false
- {{- with $.Values.imagePullSecrets }}
- imagePullSecrets:
- {{- toYaml . | nindent 8 }}
- {{- end }}
- securityContext:
- runAsNonRoot: true
- runAsUser: 1000
- runAsGroup: 1000
- fsGroup: 1000
- seccompProfile:
- type: RuntimeDefault
- containers:
- - name: librechat
- image: {{ if .image.digest }}{{ printf "%s:%s@%s" .image.repository .image.tag .image.digest }}{{ else }}{{ printf "%s:%s" .image.repository .image.tag }}{{ end }}
- imagePullPolicy: {{ .image.pullPolicy }}
- securityContext:
- allowPrivilegeEscalation: false
- readOnlyRootFilesystem: true
- capabilities:
- drop: [ALL]
- envFrom:
- - secretRef:
- name: {{ .existingSecret }}
- env:
- - { name: HOST, value: "0.0.0.0" }
- - { name: PORT, value: "3080" }
- - { name: MONGO_URI, value: {{ printf "mongodb://%s:27017/LibreChat" $mongo | quote }} }
- - { name: CONFIG_PATH, value: /config/librechat.yaml }
- - { name: SEARCH, value: "false" }
- - { name: ALLOW_REGISTRATION, value: "true" }
- - { name: ALLOW_UNVERIFIED_EMAIL_LOGIN, value: "true" }
- - { name: BAN_VIOLATIONS, value: "false" }
- ports:
- - name: http
- containerPort: 3080
- readinessProbe:
- httpGet: { path: /health, port: http }
- periodSeconds: 10
- resources:
- {{- toYaml .resources | nindent 12 }}
- volumeMounts:
- - { name: config, mountPath: /config, readOnly: true }
- - { name: logs, mountPath: /app/logs }
- - { name: uploads, mountPath: /app/uploads }
- - { name: tmp, mountPath: /tmp }
- volumes:
- - name: config
- configMap:
- name: {{ $name }}
- - { name: logs, emptyDir: {} }
- - { name: uploads, emptyDir: {} }
- - { name: tmp, emptyDir: {} }
- {{- with .nodeSelector }}
- nodeSelector:
- {{- toYaml . | nindent 8 }}
- {{- end }}
- {{- with .tolerations }}
- tolerations:
- {{- toYaml . | nindent 8 }}
- {{- end }}
----
-apiVersion: v1
-kind: Service
-metadata:
- name: {{ $name }}
- labels:
- {{- include "loom.labels" $ | nindent 4 }}
- app.kubernetes.io/component: assistant
-spec:
- type: ClusterIP
- selector:
- {{- include "loom.assistantSelectorLabels" $ | nindent 4 }}
- ports:
- - name: http
- port: 3080
- targetPort: http
----
-apiVersion: apps/v1
-kind: StatefulSet
-metadata:
- name: {{ $mongo }}
- labels:
- {{- include "loom.labels" $ | nindent 4 }}
- app.kubernetes.io/component: assistant-mongo
-spec:
- serviceName: {{ $mongo }}
- replicas: 1
- selector:
- matchLabels:
- {{- include "loom.assistantMongoSelectorLabels" $ | nindent 6 }}
- template:
- metadata:
- labels:
- {{- include "loom.assistantMongoSelectorLabels" $ | nindent 8 }}
- app.kubernetes.io/component: assistant-mongo
- spec:
- automountServiceAccountToken: false
- enableServiceLinks: false
- {{- with $.Values.imagePullSecrets }}
- imagePullSecrets:
- {{- toYaml . | nindent 8 }}
- {{- end }}
- {{- with .nodeSelector }}
- nodeSelector:
- {{- toYaml . | nindent 8 }}
- {{- end }}
- {{- with .tolerations }}
- tolerations:
- {{- toYaml . | nindent 8 }}
- {{- end }}
- securityContext:
- runAsNonRoot: true
- runAsUser: 999
- runAsGroup: 999
- fsGroup: 999
- seccompProfile:
- type: RuntimeDefault
- containers:
- - name: mongo
- image: {{ if .mongo.image.digest }}{{ printf "%s:%s@%s" .mongo.image.repository .mongo.image.tag .mongo.image.digest }}{{ else }}{{ printf "%s:%s" .mongo.image.repository .mongo.image.tag }}{{ end }}
- imagePullPolicy: {{ .mongo.image.pullPolicy }}
- args: ["mongod", "--noauth", "--quiet", "--bind_ip_all"]
- securityContext:
- allowPrivilegeEscalation: false
- readOnlyRootFilesystem: true
- capabilities:
- drop: [ALL]
- ports:
- - name: mongo
- containerPort: 27017
- resources:
- {{- toYaml .mongo.resources | nindent 12 }}
- volumeMounts:
- - { name: data, mountPath: /data/db }
- - { name: tmp, mountPath: /tmp }
- volumes:
- - { name: tmp, emptyDir: {} }
- volumeClaimTemplates:
- - metadata:
- name: data
- spec:
- accessModes: [ReadWriteOnce]
- {{- with .mongo.storageClassName }}
- storageClassName: {{ . }}
- {{- end }}
- resources:
- requests:
- storage: {{ .mongo.storage }}
----
-apiVersion: v1
-kind: Service
-metadata:
- name: {{ $mongo }}
- labels:
- {{- include "loom.labels" $ | nindent 4 }}
- app.kubernetes.io/component: assistant-mongo
-spec:
- type: ClusterIP
- selector:
- {{- include "loom.assistantMongoSelectorLabels" $ | nindent 4 }}
- ports:
- - name: mongo
- port: 27017
- targetPort: mongo
----
-apiVersion: networking.k8s.io/v1
-kind: NetworkPolicy
-metadata:
- name: {{ $name }}
- labels:
- {{- include "loom.labels" $ | nindent 4 }}
- app.kubernetes.io/component: assistant
-spec:
- podSelector:
- matchLabels:
- {{- include "loom.assistantSelectorLabels" $ | nindent 6 }}
- policyTypes: [Ingress, Egress]
- ingress:
- - from:
- - podSelector:
- matchLabels:
- {{- include "loom.selectorLabels" $ | nindent 14 }}
- ports:
- - port: http
- egress:
- - to:
- - namespaceSelector: {}
- podSelector:
- matchLabels:
- k8s-app: kube-dns
- - ipBlock: { cidr: 169.254.20.10/32 }
- ports:
- - { port: 53, protocol: UDP }
- - { port: 53, protocol: TCP }
- - to:
- - podSelector:
- matchLabels:
- {{- include "loom.assistantMongoSelectorLabels" $ | nindent 14 }}
- ports:
- - port: 27017
- # The agent's tools: Loom's MCP server.
- - to:
- - podSelector:
- matchLabels:
- {{- include "loom.selectorLabels" $ | nindent 14 }}
- ports:
- - port: 7777
- # The model provider, which has no fixed range.
- - to:
- {{- include "loom.anywhereBut" $ | nindent 8 }}
- ports:
- - port: 443
----
-apiVersion: networking.k8s.io/v1
-kind: NetworkPolicy
-metadata:
- name: {{ $mongo }}
- labels:
- {{- include "loom.labels" $ | nindent 4 }}
- app.kubernetes.io/component: assistant-mongo
-spec:
- podSelector:
- matchLabels:
- {{- include "loom.assistantMongoSelectorLabels" $ | nindent 6 }}
- # Egress listed with no rule: MongoDB reaches nothing.
- policyTypes: [Ingress, Egress]
- ingress:
- - from:
- - podSelector:
- matchLabels:
- {{- include "loom.assistantSelectorLabels" $ | nindent 14 }}
- ports:
- - port: mongo
-{{- end }}
-{{- end }}
diff --git a/deploy/helm/loom/templates/networkpolicy.yaml b/deploy/helm/loom/templates/networkpolicy.yaml
index 14903323dcc..e31fe9445b9 100644
--- a/deploy/helm/loom/templates/networkpolicy.yaml
+++ b/deploy/helm/loom/templates/networkpolicy.yaml
@@ -33,12 +33,6 @@ spec:
- podSelector:
matchLabels:
{{- include "loom.selectorLabels" $ | nindent 14 }}
- {{- if $.Values.assistant.enabled }}
- # The assistant's agent calls Loom's MCP server.
- - podSelector:
- matchLabels:
- {{- include "loom.assistantSelectorLabels" $ | nindent 14 }}
- {{- end }}
{{- end }}
egress:
- to:
@@ -67,14 +61,6 @@ spec:
ports:
- port: 8790
{{- end }}
- {{- if .Values.assistant.enabled }}
- - to:
- - podSelector:
- matchLabels:
- {{- include "loom.assistantSelectorLabels" . | nindent 14 }}
- ports:
- - port: 3080
- {{- end }}
{{- if .Values.devClickhouse.enabled }}
- to:
- podSelector:
diff --git a/deploy/helm/loom/values.yaml b/deploy/helm/loom/values.yaml
index e9a64498045..c2cb4354088 100644
--- a/deploy/helm/loom/values.yaml
+++ b/deploy/helm/loom/values.yaml
@@ -385,39 +385,9 @@ extractor:
nodeSelector: {}
tolerations: []
-# The assistant: LibreChat runs, headless, the agent Loom seeds
-# (integrations/librechat/agent.yaml), with a MongoDB of its own. Neither is exposed:
-# their NetworkPolicies admit only the release's Loom pods (and LibreChat to its
-# MongoDB), and LibreChat's egress is DNS, the Loom pods and TCP 443 anywhere but
-# `networkPolicy.egressExcept`, for its model provider.
+# The assistant runs in the Loom web process; provider keys use the release Secret.
assistant:
- enabled: false
- # A Secret in the release namespace with CREDS_KEY (64 hex), CREDS_IV (32 hex),
- # JWT_SECRET, JWT_REFRESH_SECRET, and ANTHROPIC_API_KEY while the assistant runs on
- # Anthropic (LOCAL_LLM_BASE_URL instead for LOOM_ASSISTANT_PROVIDER=local); required when
- # enabled.
- existingSecret: ""
- image:
- repository: registry.librechat.ai/librechat-ai/librechat
- tag: v0.8.8
- digest: sha256:5b706bcee1ca154a1e2987303aaeca0eb27f97919cccee4bb604226c2f8abf61
- pullPolicy: IfNotPresent
- resources:
- requests: { cpu: 250m, memory: 512Mi }
- limits: { cpu: "1", memory: 1Gi }
- mongo:
- image:
- repository: mongo
- tag: 8.0.20
- digest: sha256:098862b1339f031900ca66cf8fef799e616d6324fa41b9a263f2ec899552c1ef
- pullPolicy: IfNotPresent
- storage: 2Gi
- storageClassName: ""
- resources:
- requests: { cpu: 100m, memory: 256Mi }
- limits: { cpu: 500m, memory: 512Mi }
- nodeSelector: {}
- tolerations: []
+ nativeEnabled: false
# Ingress to the Loom port from `ingressFrom` only. Egress to DNS, the
# release's web pods, the extractor's pods (with extractor.enabled), the dev
diff --git a/deploy/librechat/assistant.librechat.yaml b/deploy/librechat/assistant.librechat.yaml
deleted file mode 100644
index 6909e0e0cde..00000000000
--- a/deploy/librechat/assistant.librechat.yaml
+++ /dev/null
@@ -1,77 +0,0 @@
-# LibreChat v0.8.8 configuration for the Loom assistant: LibreChat runs headless
-# beside Loom, reachable only from it, and hosts the one agent Loom seeds
-# (integrations/librechat/agent.yaml) under its own service user. People never sign
-# in here: the dashboard chat, the API, the SDKs and MCP reach the agent through Loom
-# (docs/architecture/assistant.md).
-version: 1.3.17
-cache: true
-
-interface:
- # The agents API (/api/agents/v1), which Loom calls with its service user's key.
- agents:
- use: true
- create: true
- share: false
- public: false
- remoteAgents:
- use: true
- create: true
- share: false
- public: false
- mcpServers:
- use: true
- create: false
- share: false
- public: false
- sharedLinks:
- share: false
- public: false
-
-# LibreChat's own memory would keep a second copy of what a caller asks.
-memory:
- disabled: true
-
-registration:
- socialLogins: []
-
-endpoints:
- anthropic:
- titleConvo: false
- agents:
- # Tools only: no actions (which call any URL), code execution, file search, web
- # search, skills or subagents, so the agent's only way out is Loom's tools.
- capabilities: ["tools"]
- custom:
- # A model server the operator runs, for LOOM_ASSISTANT_PROVIDER=local: Ollama,
- # llama.cpp's server or another chat-completions server at LOCAL_LLM_BASE_URL. It
- # takes no key; LibreChat needs one written. The agent may name a model off the
- # list, which is never fetched, so a deployment without the server logs nothing.
- - name: local
- apiKey: local
- baseURL: "${LOCAL_LLM_BASE_URL}"
- models:
- default: ["qwen2.5:3b"]
- fetch: false
- titleConvo: false
-
-mcpSettings:
- allowedAddresses:
- - loom:7777
-
-mcpServers:
- loom:
- type: streamable-http
- url: http://loom:7777/mcp?toolset=assistant
- requiresOAuth: false
- startup: false
- timeout: 60000
- # LibreChat reads server instructions once, at its own start, with no answer's
- # token; the agent's instructions (integrations/librechat/agent.yaml) carry the
- # rules instead.
- serverInstructions: false
- # Each answer's own Loom token, which Loom sends as the request's
- # parent_message_id, and its message id for the ledger. Under `headers`, not
- # `requestHeaders`: those are left off the connection that lists the tools.
- headers:
- Authorization: "Bearer {{LIBRECHAT_BODY_PARENTMESSAGEID}}"
- X-Loom-Run-Id: "{{LIBRECHAT_BODY_MESSAGEID}}"
diff --git a/deploy/standalone/env.example b/deploy/standalone/env.example
index a15f1251fb6..4a2695cc32a 100644
--- a/deploy/standalone/env.example
+++ b/deploy/standalone/env.example
@@ -60,7 +60,6 @@ OPENAI_API_KEY=
# C/C++ compiler indexing needs a project compilation database and scip-clang;
# these are repository build prerequisites, not additional running services.
# LOOM_CODE_REPOS_JSON=[{"org":"dev","namespace":"code-myrepo","repo":"acme/myrepo","git_branch":"main","public":true}]
-LOOM_CODE_INGEST_ENABLED=true
LOOM_CODE_EMBED_RECOVERY_ENABLED=true
LOOM_CODE_GRAPH_STATS_ENABLED=true
LOOM_CODE_SCIP_DELTA_ENABLED=true
@@ -84,14 +83,11 @@ LOOM_MCP_CODE_TOOLS=true
# Or a model server on this machine, no key (Ollama: `ollama pull qwen2.5:3b` first, and
# run it with OLLAMA_CONTEXT_LENGTH=32768, which holds Loom's prompts), with the empty
# per-job models above, the capture verifier, the conflict resolver and entity tagging
-# off, local assistant answers uncharged, and a long request timeout, tried once, that
+# off, and a long request timeout, tried once, that
# the extraction queue's pass outlasts:
# LOOM_LLM_PROVIDER=local
# LOOM_LLM_MODEL=qwen2.5:3b
# LOOM_LOCAL_LLM_BASE_URL=http://host.docker.internal:11434/v1
-# LOOM_ASSISTANT_PROVIDER=local
-# LOOM_ASSISTANT_MODEL=qwen2.5:3b
-# LOOM_ASSISTANT_ANSWER_CEILING_USD=0
# LOOM_MEMORY_EXTRACT_VERIFY_MODELS=
# LOOM_MEMORY_CONFLICT_RESOLVER_ENABLED=false
# LOOM_LLM_REQUEST_TIMEOUT_S=900
diff --git a/deploy/telemetry/README.md b/deploy/telemetry/README.md
new file mode 100644
index 00000000000..d6d0b0bf20c
--- /dev/null
+++ b/deploy/telemetry/README.md
@@ -0,0 +1,155 @@
+# Adoption telemetry collector
+
+Self-hosted servers send a snapshot of each day's domain activity every five minutes
+and an installation report per completed 12-hour UTC window. Both use
+`POST https://loom.clickhouse.com/api/v1/adoption`. The collector validates the payload
+and acknowledges the installation UUID and snapshot timestamp or window start after
+a synchronous insert. The insert token and warehouse views deduplicate retries.
+The same Vercel project serves the dashboard at `/adoption`.
+
+## Provision the warehouse
+
+1. Apply [warehouse.sql](warehouse.sql) to the analytics ClickHouse service. It creates
+ the report, enrollment, and distribution tables and the public views for the
+ adoption site. Apply it as the warehouse owner. Reapplying adds any missing report
+ columns and updates views while preserving rows. Reports expire 400 days after
+ receipt. Domain snapshots expire after two days.
+2. Create a collector user with `INSERT` on
+ `loom_product_analytics.adoption_reports`,
+ `loom_product_analytics.adoption_domain_snapshots`, and
+ `loom_product_analytics.oss_metrics`.
+3. Record internal installation classifications in `adoption_enrollments` and
+ registry metrics in `oss_metrics`. Restrict access to the enrollment table.
+
+## Configure the site
+
+The site's Vercel project is rooted at `docs`. Use the warehouse's approved runtime
+region and set these server-side environment variables in Production.
+
+| Setting | Value |
+| ------------------------------------ | ------------------------------------------------- |
+| `LOOM_TELEMETRY_CLICKHOUSE_URL` | HTTPS address of the analytics ClickHouse service |
+| `LOOM_TELEMETRY_CLICKHOUSE_USER` | Collector's insert-only user |
+| `LOOM_TELEMETRY_CLICKHOUSE_PASSWORD` | Credential for that user |
+| `CRON_SECRET` | Secret for the daily snapshot job |
+
+Vercel calls `/api/oss-snapshot` daily to save GitHub star and fork counts, release
+asset downloads, and GHCR pulls. The metric row key makes repeated runs on the same
+UTC day replace that day's snapshot. Distribution charts show the latest observed
+total and compare snapshots from consecutive complete periods. Set a
+request rate limit on `/api/v1/adoption` in the deployment firewall. Before releasing
+the reporting worker, send a synthetic report to a deployment configured with a test
+warehouse. Verify acknowledgements for a completed report and a domain snapshot.
+Resend both and check that the warehouse uses one report per installation and
+window and one snapshot per installation and day. Apply the warehouse schema and
+deploy the collector before deploying servers that send snapshots.
+
+Run `node --test docs/lib/adoption-collector.test.mjs docs/lib/oss-snapshot.test.mjs`
+to exercise the two endpoints locally.
+
+## Publish adoption metrics
+
+The dashboard reads aggregate metrics and reported contact domain names with a
+dedicated ClickHouse Cloud Query API key. Save [public-adoption.sql](public-adoption.sql)
+in the SQL console and create or update its Query API endpoint. Give the endpoint's
+database role `SELECT` on these views in
+`loom_product_analytics`:
+
+- `public_adoption_totals`
+- `public_adoption_versions`
+- `public_adoption_first_observation`
+- `public_adoption_retention`
+- `public_adoption_activity`
+- `public_adoption_growth`
+- `public_adoption_lifecycle`
+- `public_adoption_domain_directories`
+- `public_adoption_domain_accounts`
+- `public_adoption_company_activity`
+- `public_oss_adoption`
+
+The views run with the schema owner's privileges. Set `readonly = 2` on the
+endpoint role so the Query API can apply HTTP and output-format settings.
+Authorize a dedicated API key for the endpoint and set
+`LOOM_ADOPTION_QUERY_ENDPOINT_URL`, `LOOM_ADOPTION_QUERY_KEY_ID`, and
+`LOOM_ADOPTION_QUERY_KEY_SECRET` in the site's server environment. Use the HTTPS
+`/run/` URL from the endpoint configuration. Redeploy the site after saving
+the variables.
+
+The site refreshes warehouse data every 30 seconds when requested. It caches
+Self-hosted pages with a complete response for one minute. Failed warehouse
+refreshes retry after 15 seconds, and the site leaves those pages uncached.
+
+The site fetches repository and release counts from GitHub, SDK downloads from
+PyPI Stats, npm, and crates.io, and container pulls from the public package page.
+Stored registry metrics fill gaps when the public sources are unavailable. Store
+Rust daily downloads in `oss_metrics` with `source = 'crates.io'`,
+`artifact = 'clickhouse-loom'` and `metric = 'sdk_downloads'`. The page shows
+the latest observation date for each metric and compares reporting periods when
+both periods have coverage on every complete UTC day.
+
+The public page supports 30-, 90-, and 365-day windows. Daily charts are available
+for 30 days. Weekly and monthly charts are available in every window. CSV exports
+use the selected reporting period.
+
+Apply [warehouse.sql](warehouse.sql) and grant `SELECT` on the listed views before
+updating the saved Query API query. Deploy the collector before releasing workers
+that send live snapshots. Publishing the site does not run the warehouse changes.
+When a version 2 sender has already delivered the final window of a UTC day,
+version 3 measurements start with the next completed day.
+
+The Self-hosted summary includes today's completed reporting windows.
+Period comparisons use separate totals from complete UTC days.
+Growth counts each installation once, at the first successful request in its
+retained reports through the latest complete UTC day. Activity groups request,
+feature, transport, model, and installation measures by day, week, and month
+using the same complete-day cutoff.
+
+The first report date comes from the earliest eligible retained window.
+The software versions table counts installations with successful requests and
+uses the version pair from each installation's latest active day in the past
+30 complete UTC days.
+Public metrics exclude internal installations and reports with the smoke test
+version in either software field.
+
+The directory groups installations with successful requests by their sole
+reported email domain, including personal providers. When several domains are
+reported, it uses the sole company domain if present. Installations with
+authentication off or without an unambiguous domain contribute to `—`. The overview adds the directory's request, installation, and
+user counts and counts only named domains. The one-year view uses the 90-day
+directory. Older reports contribute to usage totals without gaining a domain
+label. An installation stays unassigned while its window contains older activity.
+
+The warehouse counts each installation once per period. It prefers completed
+daily request totals over overlapping snapshots. Earlier snapshots report only
+the requests attributed to namespaces and can supply a partial count while a day
+is in progress. Full snapshots supply installation-wide requests and active
+users. Snapshots stay eligible for two hours from observation. Each row uses its
+latest measured UTC day for active users and its latest active day for software
+versions and database hosting labels. The warehouse retains the installation
+identifier and date of an unassigned snapshot for 410 days so a later snapshot
+cannot relabel that day's activity. Account identifiers and serving process
+names stay on the installation.
+
+Rollout order. Deploy the site reader so it can display the `—` row. Apply the
+warehouse SQL to add the nullable columns and install the directory views, then
+deploy the collector. Upgrade reporting workers after the collector accepts the
+new fields. The saved Query API query reads the revised directory rows through its
+existing projection, including the period counts for the **Active domains**
+growth chart. Before rolling the collector back, downgrade reporting
+workers so they stop sending the new fields.
+
+Grant the restricted `loom_adoption_top_domains_30d` view only to authorized
+analytics staff. Its rows contain reported contact domains and attributed counts.
+The `loom_adoption_disclosed_domains` view also contains attributed counts and
+requires restricted access.
+
+## Edit the public site
+
+The public pages live in [docs/pages](../../docs/pages). The site's Vercel project
+uses `docs` as its root directory. Add a page as an `.astro` file, register its
+public path in [mount-site-pages.mjs](../../docs/scripts/mount-site-pages.mjs), and run
+`npm --prefix docs run build`. The build preserves the documentation under `/docs`
+and serves the site pages at the public paths configured by that script.
+
+For local editing, run `npm --prefix docs run dev` and open the page under the
+Blume base path, such as `/docs/home` or `/docs/adoption`.
diff --git a/deploy/telemetry/public-adoption.sql b/deploy/telemetry/public-adoption.sql
new file mode 100644
index 00000000000..8ed239800ed
--- /dev/null
+++ b/deploy/telemetry/public-adoption.sql
@@ -0,0 +1,70 @@
+SELECT
+ (
+ SELECT groupArray(payload) FROM (
+ SELECT formatRowNoNewline('JSONEachRow', *) AS payload
+ FROM loom_product_analytics.public_adoption_totals
+ )
+ ) AS totals,
+ (
+ SELECT groupArray(payload) FROM (
+ SELECT formatRowNoNewline('JSONEachRow', *) AS payload
+ FROM loom_product_analytics.public_adoption_versions
+ ORDER BY active_installations DESC, loom_version, clickhouse_version LIMIT 12
+ )
+ ) AS versions,
+ (
+ SELECT groupArray(payload) FROM (
+ SELECT formatRowNoNewline('JSONEachRow', *) AS payload
+ FROM loom_product_analytics.public_adoption_first_observation
+ )
+ ) AS first_observation,
+ (
+ SELECT groupArray(payload) FROM (
+ SELECT formatRowNoNewline('JSONEachRow', *) AS payload
+ FROM loom_product_analytics.public_adoption_retention ORDER BY age
+ )
+ ) AS retention,
+ (
+ SELECT groupArray(payload) FROM (
+ SELECT formatRowNoNewline('JSONEachRow', *) AS payload
+ FROM loom_product_analytics.public_adoption_activity ORDER BY period
+ )
+ ) AS activity,
+ (
+ SELECT groupArray(payload) FROM (
+ SELECT formatRowNoNewline('JSONEachRow', *) AS payload
+ FROM loom_product_analytics.public_adoption_growth ORDER BY grain, period
+ )
+ ) AS growth,
+ (
+ SELECT groupArray(payload) FROM (
+ SELECT formatRowNoNewline('JSONEachRow', *) AS payload
+ FROM loom_product_analytics.public_adoption_lifecycle ORDER BY bucket
+ )
+ ) AS lifecycle,
+ (
+ SELECT groupArray(payload) FROM (
+ SELECT formatRowNoNewline('JSONEachRow', *) AS payload
+ FROM loom_product_analytics.public_adoption_domain_directories ORDER BY range_days
+ )
+ ) AS domain_directories,
+ (
+ SELECT groupArray(payload) FROM (
+ SELECT formatRowNoNewline('JSONEachRow', *) AS payload
+ FROM loom_product_analytics.public_adoption_domain_accounts ORDER BY range_days, domain
+ )
+ ) AS domain_accounts,
+ (
+ SELECT groupArray(payload) FROM (
+ SELECT formatRowNoNewline('JSONEachRow', *) AS payload
+ FROM loom_product_analytics.public_adoption_company_activity ORDER BY period
+ )
+ ) AS company_trends,
+ (
+ SELECT groupArray(payload) FROM (
+ SELECT formatRowNoNewline('JSONEachRow', *) AS payload
+ FROM loom_product_analytics.public_oss_adoption
+ ORDER BY day, source, metric
+ )
+ ) AS oss
+SETTINGS output_format_json_quote_64bit_integers = 0
diff --git a/deploy/telemetry/warehouse.sql b/deploy/telemetry/warehouse.sql
new file mode 100644
index 00000000000..dc7c791fc29
--- /dev/null
+++ b/deploy/telemetry/warehouse.sql
@@ -0,0 +1,816 @@
+-- Run on the analytics ClickHouse service.
+CREATE DATABASE IF NOT EXISTS loom_product_analytics;
+
+CREATE TABLE IF NOT EXISTS loom_product_analytics.adoption_reports
+(
+ installation_id String,
+ window_start DateTime('UTC'),
+ window_end DateTime('UTC'),
+ day Date,
+ schema_version UInt8,
+ loom_version LowCardinality(String),
+ clickhouse_version LowCardinality(String),
+ clickhouse_hosting LowCardinality(String),
+ postgres_hosting LowCardinality(String),
+ postgres_version LowCardinality(String),
+ auth_required Nullable(Bool),
+ total_namespaces UInt64,
+ requests UInt64,
+ successful_requests UInt64,
+ server_errors UInt64,
+ active_orgs UInt64,
+ active_namespaces UInt64,
+ active_agents UInt64,
+ active_sessions UInt64,
+ memory_requests UInt64,
+ code_requests UInt64,
+ knowledge_requests UInt64,
+ conversation_requests UInt64,
+ tracker_requests UInt64,
+ task_requests UInt64,
+ mcp_requests UInt64,
+ http_requests UInt64,
+ llm_calls UInt64,
+ input_tokens UInt64,
+ output_tokens UInt64,
+ embedding_tokens UInt64,
+ user_domains Array(Tuple(domain String, user_count UInt64, successful_requests UInt64)),
+ active_accounts Nullable(UInt64),
+ serving_processes Nullable(UInt64),
+ daily_successful_requests Nullable(UInt64),
+ domain_activity Array(Tuple(domain String, active_accounts UInt64, successful_requests UInt64, serving_processes Nullable(UInt64))),
+ received_at DateTime64(3, 'UTC') DEFAULT now64(3)
+)
+ENGINE = ReplacingMergeTree(received_at)
+PARTITION BY toYYYYMM(day)
+ORDER BY (installation_id, window_start)
+TTL received_at + INTERVAL 400 DAY
+SETTINGS non_replicated_deduplication_window = 10000;
+
+ALTER TABLE loom_product_analytics.adoption_reports
+ ADD COLUMN IF NOT EXISTS clickhouse_hosting LowCardinality(String),
+ ADD COLUMN IF NOT EXISTS postgres_hosting LowCardinality(String),
+ ADD COLUMN IF NOT EXISTS postgres_version LowCardinality(String),
+ ADD COLUMN IF NOT EXISTS auth_required Nullable(Bool),
+ ADD COLUMN IF NOT EXISTS active_accounts Nullable(UInt64),
+ ADD COLUMN IF NOT EXISTS serving_processes Nullable(UInt64),
+ ADD COLUMN IF NOT EXISTS daily_successful_requests Nullable(UInt64),
+ ADD COLUMN IF NOT EXISTS domain_activity Array(Tuple(domain String, active_accounts UInt64, successful_requests UInt64, serving_processes Nullable(UInt64)));
+
+-- Deduplicate windows even when a retry lands after the insert deduplication window.
+CREATE OR REPLACE VIEW loom_product_analytics.loom_adoption_windows AS
+SELECT * EXCEPT (received_at) FROM loom_product_analytics.adoption_reports FINAL;
+
+CREATE TABLE IF NOT EXISTS loom_product_analytics.adoption_domain_snapshots
+(
+ schema_version UInt8,
+ installation_id String,
+ day Date,
+ observed_at DateTime('UTC'),
+ loom_version LowCardinality(String),
+ clickhouse_version LowCardinality(String),
+ clickhouse_hosting LowCardinality(String),
+ postgres_hosting LowCardinality(String),
+ postgres_version LowCardinality(String),
+ auth_required Nullable(Bool),
+ successful_requests Nullable(UInt64),
+ active_accounts Nullable(UInt64),
+ domain_activity Array(Tuple(domain String, active_accounts UInt64, successful_requests UInt64, serving_processes Nullable(UInt64)))
+)
+ENGINE = ReplacingMergeTree(observed_at)
+ORDER BY (day, installation_id)
+TTL observed_at + INTERVAL 2 DAY
+SETTINGS non_replicated_deduplication_window = 10000;
+
+ALTER TABLE loom_product_analytics.adoption_domain_snapshots
+ ADD COLUMN IF NOT EXISTS clickhouse_hosting LowCardinality(String),
+ ADD COLUMN IF NOT EXISTS postgres_hosting LowCardinality(String),
+ ADD COLUMN IF NOT EXISTS postgres_version LowCardinality(String),
+ ADD COLUMN IF NOT EXISTS auth_required Nullable(Bool),
+ ADD COLUMN IF NOT EXISTS successful_requests Nullable(UInt64),
+ ADD COLUMN IF NOT EXISTS active_accounts Nullable(UInt64);
+
+-- Snapshots count from midnight. Replacing a snapshot must not erase an earlier scope for that day.
+CREATE TABLE IF NOT EXISTS loom_product_analytics.adoption_unassigned_snapshot_days
+(
+ installation_id String,
+ day Date
+)
+ENGINE = ReplacingMergeTree
+PARTITION BY toYYYYMM(day)
+ORDER BY (installation_id, day)
+TTL day + INTERVAL 410 DAY;
+
+CREATE MATERIALIZED VIEW IF NOT EXISTS loom_product_analytics.loom_adoption_record_unassigned_snapshot_day
+TO loom_product_analytics.adoption_unassigned_snapshot_days
+SQL SECURITY DEFINER AS
+SELECT installation_id, day
+FROM loom_product_analytics.adoption_domain_snapshots
+WHERE (NOT ifNull(auth_required, false) OR successful_requests IS NULL)
+ AND loom_version != '0.0.0-smoke' AND clickhouse_version != '0.0.0-smoke';
+
+INSERT INTO loom_product_analytics.adoption_unassigned_snapshot_days (installation_id, day)
+SELECT DISTINCT installation_id, day
+FROM loom_product_analytics.adoption_domain_snapshots
+WHERE (NOT ifNull(auth_required, false) OR successful_requests IS NULL)
+ AND loom_version != '0.0.0-smoke' AND clickhouse_version != '0.0.0-smoke';
+
+CREATE TABLE IF NOT EXISTS loom_product_analytics.adoption_enrollments
+(
+ installation_id String,
+ company_id String,
+ company_name String,
+ is_internal UInt8,
+ managed_stage UInt8,
+ recorded_at DateTime64(3, 'UTC') DEFAULT now64(3)
+)
+ENGINE = ReplacingMergeTree(recorded_at)
+ORDER BY installation_id;
+
+CREATE VIEW IF NOT EXISTS loom_product_analytics.loom_adoption_enrollments AS
+SELECT * EXCEPT (recorded_at) FROM loom_product_analytics.adoption_enrollments FINAL;
+
+CREATE TABLE IF NOT EXISTS loom_product_analytics.oss_metrics
+(
+ day Date,
+ source LowCardinality(String),
+ artifact String,
+ metric LowCardinality(String),
+ value UInt64,
+ recorded_at DateTime64(3, 'UTC') DEFAULT now64(3)
+)
+ENGINE = ReplacingMergeTree(recorded_at)
+ORDER BY (day, source, artifact, metric);
+
+CREATE VIEW IF NOT EXISTS loom_product_analytics.loom_oss_metrics_daily AS
+SELECT * EXCEPT (recorded_at) FROM loom_product_analytics.oss_metrics FINAL;
+
+CREATE OR REPLACE VIEW loom_product_analytics.loom_completed_adoption_windows AS
+SELECT *
+FROM loom_product_analytics.loom_adoption_windows
+WHERE window_end <= now('UTC')
+ AND loom_version != '0.0.0-smoke'
+ AND clickhouse_version != '0.0.0-smoke';
+
+CREATE OR REPLACE VIEW loom_product_analytics.loom_external_adoption_windows AS
+SELECT *
+FROM loom_product_analytics.loom_completed_adoption_windows
+WHERE installation_id NOT IN (
+ SELECT installation_id FROM loom_product_analytics.loom_adoption_enrollments WHERE is_internal = 1
+);
+
+-- Roll up the two reporting windows per day. Distinct identifier counts cannot be added.
+CREATE OR REPLACE VIEW loom_product_analytics.loom_adoption_daily AS
+WITH
+ schema_version = 3 AND window_end = toDateTime(day + 1, 'UTC') AS complete_day,
+ sum(report.successful_requests) AS window_successes,
+ greatest(window_successes, ifNull(maxOrNullIf(daily_successful_requests, complete_day), 0)) AS daily_successes
+SELECT
+ installation_id,
+ day,
+ argMax(loom_version, window_start) AS loom_version,
+ argMax(clickhouse_version, window_start) AS clickhouse_version,
+ argMax(clickhouse_hosting, window_start) AS clickhouse_hosting,
+ argMax(postgres_hosting, window_start) AS postgres_hosting,
+ argMax(postgres_version, window_start) AS postgres_version,
+ argMaxOrNull(auth_required, window_start) AS auth_required,
+ countIf((NOT ifNull(report.auth_required, false) OR schema_version = 1)
+ AND (report.successful_requests > 0 OR ifNull(daily_successful_requests, 0) > 0)) = 0 AS installation_scope,
+ max(window_end) AS reported_at,
+ sum(report.requests) + toUInt64(daily_successes - window_successes) AS requests,
+ daily_successes AS successful_requests,
+ sum(server_errors) AS server_errors,
+ max(total_namespaces) AS total_namespaces,
+ max(active_orgs) AS active_orgs,
+ max(active_namespaces) AS active_namespaces,
+ max(active_agents) AS active_agents,
+ max(active_sessions) AS active_sessions,
+ sum(memory_requests) AS memory_requests,
+ sum(code_requests) AS code_requests,
+ sum(knowledge_requests) AS knowledge_requests,
+ sum(conversation_requests) AS conversation_requests,
+ sum(tracker_requests) AS tracker_requests,
+ sum(task_requests) AS task_requests,
+ sum(mcp_requests) AS mcp_requests,
+ sum(http_requests) AS http_requests,
+ sum(llm_calls) AS llm_calls,
+ sum(input_tokens) AS input_tokens,
+ sum(output_tokens) AS output_tokens,
+ sum(embedding_tokens) AS embedding_tokens,
+ groupBitOr(toUInt8(if(window_start = toDateTime(day, 'UTC'), 1, 2))) AS report_windows,
+ report_windows = 3 OR isNotNull(maxOrNullIf(daily_successful_requests, complete_day)) AS day_complete,
+ maxOrNullIf(active_accounts, complete_day) AS active_accounts,
+ maxOrNullIf(serving_processes, complete_day) AS serving_processes
+FROM loom_product_analytics.loom_completed_adoption_windows AS report
+GROUP BY installation_id, day;
+
+CREATE OR REPLACE VIEW loom_product_analytics.loom_external_adoption_daily AS
+SELECT *
+FROM loom_product_analytics.loom_adoption_daily
+WHERE installation_id NOT IN (
+ SELECT installation_id FROM loom_product_analytics.loom_adoption_enrollments WHERE is_internal = 1
+);
+
+-- Complete-day reports can cover the same requests as earlier half-day reports.
+CREATE OR REPLACE VIEW loom_product_analytics.loom_adoption_domain_daily AS
+WITH
+ schema_version = 3 AND window_end = toDateTime(day + 1, 'UTC') AND daily_successful_requests IS NOT NULL AS complete_day,
+ schema_version = 2 OR complete_day AS disclosed,
+ disclosed AND counts.successful_requests > 0 AS has_activity
+SELECT
+ installation_id,
+ day,
+ counts.domain AS domain,
+ greatest(
+ sumIf(counts.successful_requests, schema_version IN (1, 2)),
+ maxIf(counts.successful_requests, complete_day)
+ ) AS requests,
+ argMax(counts.user_count, window_start) AS accounts,
+ greatest(
+ sumIf(counts.successful_requests, schema_version = 2),
+ maxIf(counts.successful_requests, complete_day)
+ ) AS disclosed_requests,
+ groupBitOrIf(
+ toUInt8(multiIf(complete_day, 3, window_start = toDateTime(day, 'UTC'), 1, 2)),
+ disclosed
+ ) AS disclosed_windows,
+ countIf(disclosed) > 0 AS disclosure_reports,
+ maxIf(window_end, has_activity) AS reported_at,
+ argMaxIf(report.loom_version, window_end, has_activity) AS loom_version,
+ argMaxIf(report.clickhouse_hosting, window_end, has_activity) AS clickhouse_hosting,
+ argMaxIf(report.clickhouse_version, window_end, has_activity) AS clickhouse_version,
+ argMaxIf(report.postgres_hosting, window_end, has_activity) AS postgres_hosting,
+ argMaxIf(report.postgres_version, window_end, has_activity) AS postgres_version
+FROM loom_product_analytics.loom_external_adoption_windows AS report
+LEFT ARRAY JOIN user_domains AS counts
+GROUP BY installation_id, day, domain;
+
+-- Attributed request and account counts stay in the restricted domain view.
+CREATE VIEW IF NOT EXISTS loom_product_analytics.loom_adoption_top_domains_30d
+SQL SECURITY DEFINER AS
+SELECT domain, sum(instance_requests) AS successful_requests, countIf(instance_requests > 0) AS installations,
+ sum(latest_accounts) AS accounts
+FROM (
+ SELECT domain, installation_id, sum(requests) AS instance_requests,
+ argMax(accounts, day) AS latest_accounts
+ FROM loom_product_analytics.loom_adoption_domain_daily
+ WHERE day >= toDate(now('UTC')) - 30 AND day < toDate(now('UTC'))
+ GROUP BY domain, installation_id
+)
+GROUP BY domain
+HAVING successful_requests > 0
+ORDER BY successful_requests DESC, domain
+LIMIT 50;
+
+-- Keep partial counts only while the domain is disclosed and final counts are unavailable.
+CREATE OR REPLACE VIEW loom_product_analytics.loom_adoption_live_domains AS
+SELECT snapshot.day, snapshot.installation_id,
+ if(completed.present = 0, snapshot.loom_version, completed.loom_version) AS loom_version,
+ if(completed.present = 0, snapshot.clickhouse_version, completed.clickhouse_version) AS clickhouse_version,
+ if(completed.present = 0, snapshot.clickhouse_hosting, completed.clickhouse_hosting) AS clickhouse_hosting,
+ if(completed.present = 0, snapshot.postgres_hosting, completed.postgres_hosting) AS postgres_hosting,
+ if(completed.present = 0, snapshot.postgres_version, completed.postgres_version) AS postgres_version,
+ if(completed.present = 0, snapshot.observed_at, completed.window_end) AS reported_at,
+ arrayMap(item -> CAST((
+ item.domain, item.active_accounts,
+ if(completed.present = 0, item.successful_requests, completed.requests[item.domain]),
+ item.serving_processes
+ ), 'Tuple(domain String, active_accounts UInt64, successful_requests UInt64, serving_processes Nullable(UInt64))'),
+ arrayFilter(item -> completed.present = 0 OR (
+ mapContains(completed.requests, item.domain) AND NOT has(completed.measured, item.domain)
+ ), snapshot.domain_activity)) AS domain_activity
+FROM (
+ SELECT day, installation_id, loom_version, clickhouse_version, clickhouse_hosting,
+ postgres_hosting, postgres_version, observed_at, domain_activity
+ FROM loom_product_analytics.adoption_domain_snapshots FINAL
+ WHERE day BETWEEN toDate(now('UTC')) - 1 AND toDate(now('UTC'))
+ AND observed_at BETWEEN now('UTC') - INTERVAL 2 HOUR AND now('UTC')
+ AND loom_version != '0.0.0-smoke'
+ AND clickhouse_version != '0.0.0-smoke'
+ AND installation_id NOT IN (
+ SELECT installation_id FROM loom_product_analytics.loom_adoption_enrollments WHERE is_internal = 1
+ )
+) AS snapshot
+LEFT JOIN (
+ SELECT day, installation_id, loom_version, clickhouse_version, clickhouse_hosting,
+ postgres_hosting, postgres_version, window_end, 1 AS present,
+ mapFromArrays(arrayMap(item -> item.domain, user_domains),
+ arrayMap(item -> item.successful_requests, user_domains)) AS requests,
+ arrayMap(item -> item.domain, domain_activity) AS measured
+ FROM loom_product_analytics.loom_external_adoption_windows
+ WHERE schema_version = 3 AND window_end = toDateTime(day + 1, 'UTC')
+ AND day >= toDate(now('UTC')) - 1
+) AS completed USING (day, installation_id)
+SETTINGS join_use_nulls = 0;
+
+-- Only reports covered by the public domain-sharing notice supply names.
+CREATE OR REPLACE VIEW loom_product_analytics.loom_adoption_disclosed_domain_daily AS
+WITH
+ toDate(now('UTC')) AS today_utc,
+ tuple(report.reported_at, report.completed) AS version_order
+SELECT day, installation_id, domain, max(attributed_requests) AS disclosed_requests,
+ max(report.reported_at) AS reported_at,
+ argMax(report.loom_version, version_order) AS loom_version,
+ argMax(report.clickhouse_hosting, version_order) AS clickhouse_hosting,
+ argMax(report.clickhouse_version, version_order) AS clickhouse_version,
+ argMax(report.postgres_hosting, version_order) AS postgres_hosting,
+ argMax(report.postgres_version, version_order) AS postgres_version
+FROM (
+ SELECT day, installation_id, domain, disclosed_requests AS attributed_requests, 1 AS completed,
+ reported_at, loom_version, clickhouse_hosting, clickhouse_version, postgres_hosting, postgres_version
+ FROM loom_product_analytics.loom_adoption_domain_daily
+ WHERE day <= today_utc AND disclosed_requests > 0
+ UNION ALL
+ SELECT day, installation_id, counts.domain, counts.successful_requests, 0,
+ reported_at, loom_version, clickhouse_hosting, clickhouse_version, postgres_hosting, postgres_version
+ FROM loom_product_analytics.loom_adoption_live_domains
+ ARRAY JOIN domain_activity AS counts
+ WHERE counts.successful_requests > 0
+) AS report
+GROUP BY day, installation_id, domain;
+
+CREATE OR REPLACE VIEW loom_product_analytics.loom_adoption_disclosed_domains AS
+WITH toDate(now('UTC')) AS today_utc
+SELECT
+ domain,
+ sumIf(disclosed_requests, day >= today_utc - 30) AS successful_requests_30d,
+ sum(disclosed_requests) AS successful_requests_90d
+FROM loom_product_analytics.loom_adoption_disclosed_domain_daily
+WHERE day >= today_utc - 90
+GROUP BY domain;
+
+-- Complete reports replace snapshots. Before day close, keep the largest observed request total.
+CREATE OR REPLACE VIEW loom_product_analytics.loom_adoption_installation_activity AS
+SELECT
+ installation_id, day,
+ argMax(activity.successful_requests, ordering) AS successful_requests,
+ argMaxOrNull(activity.active_accounts, ordering) AS active_accounts,
+ argMaxOrNull(activity.auth_required, activity.reported_at) AS auth_required,
+ minIf(activity.installation_scope, activity.successful_requests > 0)
+ AND (installation_id, day) NOT IN (
+ SELECT installation_id, day FROM loom_product_analytics.adoption_unassigned_snapshot_days
+ ) AS installation_scope,
+ argMax(loom_version, ordering) AS loom_version,
+ argMax(clickhouse_version, ordering) AS clickhouse_version,
+ argMax(clickhouse_hosting, ordering) AS clickhouse_hosting,
+ argMax(postgres_version, ordering) AS postgres_version,
+ argMax(postgres_hosting, ordering) AS postgres_hosting,
+ max(activity.day_complete) AS day_complete,
+ max(activity.reported_at) AS reported_at
+FROM (
+ SELECT *, tuple(day_complete, successful_requests, reported_at) AS ordering
+ FROM (
+ SELECT installation_id, day, successful_requests, active_accounts, auth_required,
+ loom_version, clickhouse_version, clickhouse_hosting, postgres_version, postgres_hosting,
+ reported_at, day_complete, installation_scope
+ FROM loom_product_analytics.loom_external_adoption_daily
+ UNION ALL
+ SELECT installation_id, day,
+ ifNull(snapshot.successful_requests, arraySum(item -> item.successful_requests, domain_activity)),
+ active_accounts, auth_required, loom_version, clickhouse_version, clickhouse_hosting,
+ postgres_version, postgres_hosting, observed_at, false,
+ ifNull(auth_required, false) AND isNotNull(snapshot.successful_requests)
+ FROM loom_product_analytics.adoption_domain_snapshots AS snapshot FINAL
+ WHERE day BETWEEN toDate(now('UTC')) - 1 AND toDate(now('UTC'))
+ AND observed_at BETWEEN now('UTC') - INTERVAL 2 HOUR AND now('UTC')
+ AND loom_version != '0.0.0-smoke'
+ AND clickhouse_version != '0.0.0-smoke'
+ AND installation_id NOT IN (
+ SELECT installation_id FROM loom_product_analytics.loom_adoption_enrollments WHERE is_internal = 1
+ )
+ )
+) AS activity
+GROUP BY installation_id, day;
+
+-- Each installation contributes to one row in each directory window.
+-- Keep installations with activity reported under the earlier notice unassigned.
+CREATE OR REPLACE VIEW loom_product_analytics.loom_adoption_installation_domains AS
+WITH
+ toDate(now('UTC')) AS today_utc,
+ ['gmail.com', 'googlemail.com', 'hotmail.com', 'outlook.com', 'live.com', 'msn.com',
+ 'yahoo.com', 'ymail.com', 'rocketmail.com', 'icloud.com', 'me.com', 'mac.com', 'aol.com',
+ 'proton.me', 'protonmail.com', 'pm.me', 'gmx.com', 'gmx.de', 'mail.com', 'fastmail.com',
+ 'hey.com', 'yandex.com', 'yandex.ru', 'qq.com', '163.com', '126.com'] AS personal_domains
+SELECT
+ activity.* EXCEPT (last_auth_required, unassigned_activity),
+ if(ifNull(activity.last_auth_required, false) AND NOT activity.unassigned_activity,
+ coalesce(nullIf(candidate.domain, ''), '-'), '-') AS domain
+FROM (
+ SELECT *, range_days,
+ argMaxIf(auth_required, reported_at, day >= today_utc - range_days) OVER window_scope AS last_auth_required,
+ countIf(day >= today_utc - range_days AND successful_requests > 0 AND NOT installation_scope)
+ OVER window_scope > 0 AS unassigned_activity
+ FROM loom_product_analytics.loom_adoption_installation_activity
+ ARRAY JOIN [30, 90] AS range_days
+ WINDOW window_scope AS (PARTITION BY installation_id, range_days)
+) AS activity
+LEFT JOIN (
+ SELECT installation_id, range_days,
+ multiIf(length(companies) = 1, companies[1],
+ empty(companies) AND length(reported) = 1, reported[1], '') AS domain
+ FROM (
+ SELECT installation_id, range_days,
+ groupUniqArrayIf(2)(domain, domain NOT IN personal_domains) AS companies,
+ groupUniqArray(2)(domain) AS reported
+ FROM loom_product_analytics.loom_adoption_disclosed_domain_daily
+ ARRAY JOIN [30, 90] AS range_days
+ WHERE day >= today_utc - range_days
+ GROUP BY installation_id, range_days
+ )
+) AS candidate USING (installation_id, range_days);
+
+CREATE OR REPLACE VIEW loom_product_analytics.public_adoption_domain_accounts
+SQL SECURITY DEFINER AS
+WITH
+ toDate(now('UTC')) AS today_utc,
+ daily.day >= today_utc - daily.range_days AS in_window,
+ in_window AND daily.active_accounts IS NOT NULL AS measured
+SELECT
+ daily.domain AS domain,
+ daily.range_days AS range_days,
+ argMaxOrNullIf(daily.active_accounts, daily.day, measured) AS active_accounts,
+ maxOrNullIf(daily.day, measured) AS day,
+ sumIf(daily.successful_requests, in_window) AS successful_requests,
+ uniqExactArrayIf(daily.active_installation_ids, in_window) AS active_installations,
+ argMaxOrNullIf(daily.loom_version, daily.day, in_window) AS loom_version,
+ argMaxIf(daily.clickhouse_versions, daily.day, in_window) AS clickhouse_versions,
+ argMaxIf(daily.postgres_versions, daily.day, in_window) AS postgres_versions,
+ min(daily.day) AS first_seen,
+ maxOrNullIf(daily.day, in_window) AS last_seen
+FROM (
+ SELECT
+ domain, range_days, day,
+ sumOrNull(if(auth_required = false, toUInt64(0), active_accounts)) AS active_accounts,
+ sum(successful_requests) AS successful_requests,
+ groupUniqArray(installation_id) AS active_installation_ids,
+ argMax(loom_version, tuple(reported_at, installation_id)) AS loom_version,
+ arraySort(groupUniqArray((clickhouse_hosting, clickhouse_version))) AS clickhouse_versions,
+ arraySort(groupUniqArrayIf((postgres_hosting, postgres_version),
+ postgres_hosting != '' OR postgres_version != '')) AS postgres_versions
+ FROM loom_product_analytics.loom_adoption_installation_domains AS activity
+ WHERE activity.successful_requests > 0 AND (activity.domain = '-' OR activity.installation_scope)
+ GROUP BY domain, range_days, day
+) AS daily
+GROUP BY domain, range_days
+HAVING successful_requests > 0;
+
+CREATE OR REPLACE VIEW loom_product_analytics.public_adoption_domains
+SQL SECURITY DEFINER AS
+SELECT domain FROM loom_product_analytics.public_adoption_domain_accounts WHERE range_days = 90;
+
+CREATE OR REPLACE VIEW loom_product_analytics.loom_adoption_assigned_domain_activity AS
+WITH toDate(now('UTC')) AS today_utc
+SELECT
+ range_days,
+ grain,
+ multiIf(grain = 'day', day, grain = 'week', toStartOfWeek(day, 1), toStartOfMonth(day)) AS period,
+ multiIf(grain = 'day', addDays(period, 1), grain = 'week', addWeeks(period, 1), addMonths(period, 1)) AS period_end,
+ uniqExactIf(domain, activity.successful_requests > 0 AND domain != '-') AS companies,
+ uniqExact(day) AS days_reported,
+ uniqExactIf(day, day_complete) AS complete_days_reported
+FROM loom_product_analytics.loom_adoption_installation_domains AS activity
+ARRAY JOIN ['day', 'week', 'month'] AS grain
+WHERE day >= today_utc - range_days AND day < today_utc
+GROUP BY range_days, grain, period;
+
+CREATE OR REPLACE VIEW loom_product_analytics.public_adoption_domain_directories
+SQL SECURITY DEFINER AS
+SELECT directory.range_days AS range_days, directory.domains AS domains, trends.active_domain_trends AS active_domain_trends
+FROM (
+ SELECT range_days,
+ arrayMap(entry -> entry.4, arraySort(arrayFilter(entry -> entry.1 = range_days, ranked))) AS domains
+ FROM (
+ SELECT groupArray((range_days, domain = '-', -toInt128(successful_requests), domain)) AS ranked
+ FROM loom_product_analytics.public_adoption_domain_accounts
+ )
+ ARRAY JOIN [30, 90] AS range_days
+) AS directory
+LEFT JOIN (
+ SELECT range_days,
+ groupArray(formatRowNoNewline('JSONEachRow', grain, period, period_end, companies,
+ days_reported, complete_days_reported)) AS active_domain_trends
+ FROM loom_product_analytics.loom_adoption_assigned_domain_activity
+ GROUP BY range_days
+) AS trends USING (range_days)
+SETTINGS join_use_nulls = 0;
+
+CREATE OR REPLACE VIEW loom_product_analytics.public_adoption_company_activity
+SQL SECURITY DEFINER AS
+WITH toDate(now('UTC')) AS today_utc
+SELECT
+ grain,
+ multiIf(grain = 'day', day, grain = 'week', toStartOfWeek(day, 1), toStartOfMonth(day)) AS period,
+ multiIf(grain = 'day', addDays(period, 1), grain = 'week', addWeeks(period, 1), addMonths(period, 1)) AS period_end,
+ uniqExactIf(domain, disclosed_requests > 0) AS companies,
+ uniqExact(day) AS days_reported,
+ uniqExactIf(day, day_windows = 3) AS complete_days_reported
+FROM (
+ SELECT day, domain, disclosed_requests, groupBitOr(disclosed_windows) OVER (PARTITION BY day) AS day_windows
+ FROM loom_product_analytics.loom_adoption_domain_daily
+ WHERE disclosure_reports AND day >= today_utc - 365 AND day < today_utc
+)
+ARRAY JOIN ['day', 'week', 'month'] AS grain
+GROUP BY grain, period;
+
+-- The public website reads these aggregate views with a separate read-only user.
+CREATE OR REPLACE VIEW loom_product_analytics.public_adoption_totals
+SQL SECURITY DEFINER AS
+WITH toDate(now('UTC')) AS today_utc
+SELECT
+ range_days,
+ arrayJoin(multiIf(
+ daily.day = today_utc, ['current'],
+ daily.day >= today_utc - range_days, ['current', 'current_complete'],
+ ['previous_complete']
+ )) AS comparison,
+ uniqExactIf(daily.day, daily.day < today_utc) AS days_reported,
+ max(daily.day) AS last_reported,
+ uniqExact(daily.installation_id) AS reporting,
+ uniqExactIf(daily.installation_id, daily.successful_requests > 0) AS active,
+ sum(daily.successful_requests) AS operations,
+ sum(ifNull(attributed.operations, 0)) AS attributed_operations,
+ sum(daily.requests) AS requests,
+ sum(daily.server_errors) AS server_errors,
+ quantileExactOrNullIf(0.5)(daily.total_namespaces, daily.successful_requests > 0) AS median_total_namespaces,
+ quantileExactOrNullIf(0.5)(daily.active_orgs, daily.successful_requests > 0) AS median_active_orgs,
+ quantileExactOrNullIf(0.5)(daily.active_namespaces, daily.successful_requests > 0) AS median_namespaces,
+ quantileExactOrNullIf(0.5)(daily.active_agents, daily.successful_requests > 0) AS median_agents,
+ quantileExactOrNullIf(0.5)(daily.active_sessions, daily.successful_requests > 0) AS median_sessions,
+ sum(daily.memory_requests) AS memory_requests,
+ sum(daily.code_requests) AS code_requests,
+ sum(daily.knowledge_requests) AS knowledge_requests,
+ sum(daily.conversation_requests) AS conversation_requests,
+ sum(daily.tracker_requests) AS tracker_requests,
+ sum(daily.task_requests) AS task_requests,
+ sum(daily.mcp_requests) AS mcp_requests,
+ sum(daily.http_requests) AS http_requests,
+ sum(daily.llm_calls) AS llm_calls,
+ sum(daily.input_tokens) AS input_tokens,
+ sum(daily.output_tokens) AS output_tokens,
+ sum(daily.embedding_tokens) AS embedding_tokens
+FROM loom_product_analytics.loom_external_adoption_daily AS daily
+LEFT JOIN (
+ WITH
+ schema_version = 3 AND window_end = toDateTime(day + 1, 'UTC')
+ AND daily_successful_requests IS NOT NULL AS complete_day,
+ arraySum(item -> item.successful_requests, user_domains) AS disclosed_requests
+ SELECT
+ day,
+ installation_id,
+ coalesce(maxOrNullIf(disclosed_requests, complete_day),
+ sumIf(disclosed_requests, schema_version = 2)) AS operations
+ FROM loom_product_analytics.loom_external_adoption_windows
+ WHERE day BETWEEN today_utc - 730 AND today_utc AND schema_version IN (2, 3)
+ GROUP BY day, installation_id
+) AS attributed USING (day, installation_id)
+ARRAY JOIN [30, 90, 365] AS range_days
+WHERE daily.day >= today_utc - 2 * range_days AND daily.day <= today_utc
+GROUP BY range_days, comparison;
+
+CREATE OR REPLACE VIEW loom_product_analytics.public_adoption_versions
+SQL SECURITY DEFINER AS
+-- Keep the saved Query API's sort field during a warehouse rollout.
+SELECT loom_version, clickhouse_version, count() AS active_installations, active_installations AS installations
+FROM (
+ SELECT installation_id,
+ argMax(loom_version, day) AS loom_version,
+ argMax(clickhouse_version, day) AS clickhouse_version
+ FROM loom_product_analytics.loom_external_adoption_daily
+ WHERE day >= toDate(now('UTC')) - 30 AND day < toDate(now('UTC')) AND successful_requests > 0
+ GROUP BY installation_id
+)
+GROUP BY loom_version, clickhouse_version;
+
+CREATE OR REPLACE VIEW loom_product_analytics.public_adoption_first_observation
+SQL SECURITY DEFINER AS
+SELECT day, loom_version, clickhouse_version
+FROM loom_product_analytics.loom_external_adoption_windows
+ORDER BY window_start, installation_id
+LIMIT 1;
+
+CREATE VIEW IF NOT EXISTS loom_product_analytics.public_adoption_retention
+SQL SECURITY DEFINER AS
+WITH
+ toStartOfWeek(toDate(now('UTC')), 1) AS current_week,
+ activity AS (
+ SELECT installation_id, toStartOfWeek(day, 1) AS week
+ FROM loom_product_analytics.loom_external_adoption_daily
+ WHERE day < current_week AND successful_requests > 0
+ GROUP BY installation_id, week
+ ),
+ first_seen AS (
+ SELECT installation_id, min(week) AS first_week FROM activity GROUP BY installation_id
+ ),
+ observations AS (
+ SELECT installation_id, first_week, age, first_week + toIntervalWeek(age) AS observed_week
+ FROM first_seen
+ ARRAY JOIN range(1, 5) AS age
+ WHERE first_week >= current_week - INTERVAL 13 WEEK AND observed_week < current_week
+ )
+SELECT observations.age AS age, count() AS eligible, countIf(activity.week IS NOT NULL) AS active
+FROM observations
+LEFT JOIN activity
+ ON observations.installation_id = activity.installation_id
+ AND observations.observed_week = activity.week
+GROUP BY observations.age
+SETTINGS join_use_nulls = 1;
+
+CREATE OR REPLACE VIEW loom_product_analytics.public_oss_adoption
+SQL SECURITY DEFINER AS
+SELECT day, source, artifact, metric, value
+FROM loom_product_analytics.loom_oss_metrics_daily
+WHERE day >= toDate(now('UTC')) - 730 AND day < toDate(now('UTC'))
+ AND (metric = 'sdk_downloads' OR day >= toDate(now('UTC')) - 400)
+ AND (source, artifact, metric) IN (
+ ('github', 'ClickHouse/loom', 'stars'),
+ ('github', 'ClickHouse/loom', 'forks'),
+ ('github', 'ClickHouse/loom', 'release_asset_downloads_total'),
+ ('pypi', 'clickhouse-loom', 'sdk_downloads'),
+ ('npm', '@clickhouse/loom', 'sdk_downloads'),
+ ('crates.io', 'clickhouse-loom', 'sdk_downloads'),
+ ('ghcr', 'ghcr.io/clickhouse/loom', 'container_pulls_total')
+ );
+
+-- Count an installation once at its first successful request in retained reports.
+CREATE OR REPLACE VIEW loom_product_analytics.public_adoption_growth
+SQL SECURITY DEFINER AS
+WITH toDate(now('UTC')) AS today_utc
+SELECT
+ grain,
+ period,
+ multiIf(grain = 'day', addDays(period, 1), grain = 'week', addWeeks(period, 1), addMonths(period, 1)) AS period_end,
+ first_active,
+ sum(first_active) OVER (PARTITION BY grain ORDER BY period ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
+ AS cumulative_active
+FROM (
+ SELECT
+ grain,
+ multiIf(grain = 'day', observed_day, grain = 'week', toStartOfWeek(observed_day, 1), toStartOfMonth(observed_day)) AS period,
+ countIf(observed_day = first_active_day) AS first_active
+ FROM (
+ SELECT
+ minOrNullIf(day, successful_requests > 0) AS first_active_day,
+ groupArray(day) AS report_days
+ FROM loom_product_analytics.loom_external_adoption_daily
+ WHERE day < today_utc
+ GROUP BY installation_id
+ )
+ ARRAY JOIN report_days AS observed_day
+ ARRAY JOIN ['day', 'week', 'month'] AS grain
+ GROUP BY grain, period
+);
+
+CREATE OR REPLACE VIEW loom_product_analytics.public_adoption_activity
+SQL SECURITY DEFINER AS
+WITH
+ toDate(now('UTC')) AS today_utc,
+ (SELECT minOrNull(day)
+ FROM loom_product_analytics.loom_external_adoption_daily WHERE day < today_utc) AS first_report
+SELECT
+ grain,
+ multiIf(grain = 'day', day, grain = 'week', toStartOfWeek(day, 1), toStartOfMonth(day)) AS period,
+ uniqExact(installation_id) AS reporting,
+ uniqExactIf(installation_id, successful_requests > 0) AS active,
+ sum(successful_requests) AS operations,
+ uniqExact(day) AS days_reported,
+ uniqExactIf(day, day_windows = 3) AS complete_days_reported,
+ multiIf(grain = 'day', addDays(period, 1), grain = 'week', addWeeks(period, 1), addMonths(period, 1)) AS period_end,
+ period >= first_report AS forecast_eligible,
+ sum(requests) AS requests,
+ sum(server_errors) AS server_errors,
+ sum(memory_requests) AS memory_requests,
+ sum(code_requests) AS code_requests,
+ sum(knowledge_requests) AS knowledge_requests,
+ sum(conversation_requests) AS conversation_requests,
+ sum(tracker_requests) AS tracker_requests,
+ sum(task_requests) AS task_requests,
+ sum(mcp_requests) AS mcp_requests,
+ sum(http_requests) AS http_requests,
+ sum(llm_calls) AS llm_calls,
+ sum(input_tokens) AS input_tokens,
+ sum(output_tokens) AS output_tokens,
+ sum(embedding_tokens) AS embedding_tokens,
+ quantileExactOrNullIf(0.5)(total_namespaces, successful_requests > 0) AS median_total_namespaces,
+ quantileExactOrNullIf(0.5)(active_orgs, successful_requests > 0) AS median_active_orgs,
+ quantileExactOrNullIf(0.5)(active_namespaces, successful_requests > 0) AS median_namespaces,
+ quantileExactOrNullIf(0.5)(active_agents, successful_requests > 0) AS median_agents,
+ quantileExactOrNullIf(0.5)(active_sessions, successful_requests > 0) AS median_sessions,
+ maxOrNull(daily_active_accounts) AS active_accounts,
+ uniqExactIf(day, daily_active_accounts IS NOT NULL) AS accounts_days_reported,
+ argMaxIf(daily_account_installations, tuple(daily_active_accounts, day), daily_active_accounts IS NOT NULL)
+ AS account_reporting_installations,
+ maxOrNull(daily_serving_processes) AS serving_processes,
+ uniqExactIf(day, daily_serving_processes IS NOT NULL) AS processes_days_reported,
+ argMaxIf(daily_process_installations, tuple(daily_serving_processes, day), daily_serving_processes IS NOT NULL)
+ AS process_reporting_installations
+FROM (
+ SELECT
+ *,
+ groupBitOr(report_windows) OVER (PARTITION BY day) AS day_windows,
+ sumOrNull(active_accounts) OVER (PARTITION BY day) AS daily_active_accounts,
+ count(active_accounts) OVER (PARTITION BY day) AS daily_account_installations,
+ sumOrNull(serving_processes) OVER (PARTITION BY day) AS daily_serving_processes,
+ count(serving_processes) OVER (PARTITION BY day) AS daily_process_installations
+ FROM loom_product_analytics.loom_external_adoption_daily
+ WHERE day >= today_utc - 365 AND day < today_utc
+)
+ARRAY JOIN ['day', 'week', 'month'] AS grain
+GROUP BY grain, period;
+
+CREATE OR REPLACE VIEW loom_product_analytics.public_adoption_lifecycle
+SQL SECURITY DEFINER AS
+WITH
+ toDate(now('UTC')) AS today_utc,
+ report_coverage AS (
+ SELECT
+ day, window_start, schema_version,
+ schema_version = 3 AND window_end = toDateTime(day + 1, 'UTC')
+ AND daily_successful_requests IS NOT NULL AS complete_day
+ FROM loom_product_analytics.loom_external_adoption_windows
+ WHERE day >= today_utc - 400 AND day < today_utc
+ ),
+ complete_periods AS (
+ SELECT
+ entity, grain,
+ if(grain = 'week', toStartOfWeek(day, 1), toStartOfMonth(day)) AS bucket,
+ if(grain = 'week', addWeeks(bucket, 1), addMonths(bucket, 1)) AS next_bucket
+ FROM report_coverage
+ ARRAY JOIN if(schema_version = 2 OR complete_day, ['deployment', 'domain'], ['deployment']) AS entity
+ ARRAY JOIN ['week', 'month'] AS grain
+ GROUP BY entity, grain, bucket
+ HAVING next_bucket <= today_utc
+ AND uniqExactArray(if(complete_day, [toDateTime(day, 'UTC'), window_start], [window_start]))
+ = 2 * dateDiff('day', bucket, next_bucket)
+ ),
+ comparable_periods AS (
+ SELECT entity, grain, bucket
+ FROM (
+ SELECT entity, grain, bucket, lagInFrame(next_bucket) OVER (
+ PARTITION BY entity, grain ORDER BY bucket
+ ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
+ ) AS previous_end
+ FROM complete_periods
+ )
+ WHERE previous_end = bucket AND bucket >= today_utc - 365
+ ),
+ entity_activity AS (
+ SELECT 'deployment' AS entity, installation_id AS identity, day, successful_requests AS requests
+ FROM loom_product_analytics.loom_external_adoption_daily
+ UNION ALL
+ SELECT 'domain' AS entity, domain AS identity, day, sum(disclosed_requests) AS requests
+ FROM loom_product_analytics.loom_adoption_domain_daily
+ WHERE disclosed_requests > 0
+ GROUP BY domain, day
+ ),
+ active_periods AS (
+ SELECT
+ entity, identity, grain, min_requests,
+ if(grain = 'week', toStartOfWeek(day, 1), toStartOfMonth(day)) AS period
+ FROM entity_activity
+ ARRAY JOIN ['week', 'month'] AS grain
+ ARRAY JOIN [0, 50000, 1000000] AS min_requests
+ WHERE day < today_utc
+ GROUP BY entity, identity, grain, min_requests, period
+ HAVING sum(requests) > if(grain = 'week', intDiv(min_requests * 7, 30), min_requests)
+ AND if(grain = 'week', addWeeks(period, 1), addMonths(period, 1)) <= today_utc
+ ),
+ transitions AS (
+ SELECT
+ entity, grain, min_requests, period,
+ lagInFrame(period) OVER ordered AS previous,
+ leadInFrame(period) OVER ordered AS following,
+ if(grain = 'week', addWeeks(period, -1), addMonths(period, -1)) AS previous_period,
+ if(grain = 'week', addWeeks(period, 1), addMonths(period, 1)) AS next_period
+ FROM active_periods
+ WINDOW ordered AS (
+ PARTITION BY entity, identity, grain, min_requests ORDER BY period
+ ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
+ )
+ ),
+ counts AS (
+ SELECT
+ entity, grain, min_requests,
+ if(state = 'inactive', next_period, period) AS bucket,
+ countIf(state = 'new') AS new,
+ countIf(state = 'retained') AS retained,
+ countIf(state = 'reactivated') AS reactivated,
+ countIf(state = 'inactive') AS inactive
+ FROM transitions
+ ARRAY JOIN arrayConcat(
+ [multiIf(previous = toDate(0), 'new', previous = previous_period, 'retained', 'reactivated')],
+ if(following != next_period, ['inactive'], [])
+ ) AS state
+ WHERE bucket >= today_utc - 365
+ GROUP BY entity, grain, min_requests, bucket
+ )
+SELECT periods.entity, periods.grain, periods.min_requests, periods.bucket,
+ ifNull(counts.new, 0) AS new,
+ ifNull(counts.retained, 0) AS retained,
+ ifNull(counts.reactivated, 0) AS reactivated,
+ ifNull(counts.inactive, 0) AS inactive,
+ toUInt8(1) AS complete_coverage
+FROM (
+ SELECT grain, bucket, entity, min_requests FROM comparable_periods
+ ARRAY JOIN [0, 50000, 1000000] AS min_requests
+) AS periods
+LEFT JOIN counts USING (entity, grain, min_requests, bucket);
diff --git a/dev/contributor-lab/check.py b/dev/contributor-lab/check.py
index 61f65f74b11..d51ffd0cc73 100644
--- a/dev/contributor-lab/check.py
+++ b/dev/contributor-lab/check.py
@@ -48,9 +48,19 @@ def check(track: str, directory: Path) -> dict[str, object]:
f"--junitxml={report}",
]
result = subprocess.run(command, check=False, timeout=120)
- suites = ET.parse(report).getroot().findall(".//testsuite") if report.is_file() else []
- total = sum(int(suite.get("tests", "0")) for suite in suites)
- skipped = sum(int(suite.get("skipped", "0")) for suite in suites)
+ if not report.is_file():
+ return {"track": track, "passed": False, "error": "missing report"}
+ try:
+ suites = ET.parse(report).getroot().findall(".//testsuite")
+ counts = [
+ (int(suite.get("tests", "-1")), int(suite.get("skipped", "0"))) for suite in suites
+ ]
+ if not counts or any(not 0 <= skipped <= total for total, skipped in counts):
+ raise ValueError("invalid test counts")
+ except (ET.ParseError, ValueError):
+ return {"track": track, "passed": False, "error": "invalid report"}
+ total = sum(total for total, _ in counts)
+ skipped = sum(skipped for _, skipped in counts)
passed = result.returncode == 0 and total > skipped
return {"track": track, "tests": total, "skipped": skipped, "passed": passed}
@@ -75,7 +85,11 @@ def main() -> None:
tracks = choices[:-1] if args.track == "all" else [args.track]
results = []
for track in tracks:
- results.append(check(track, directory))
+ try:
+ result = check(track, directory)
+ except subprocess.TimeoutExpired:
+ result = {"track": track, "passed": False, "error": "timeout"}
+ results.append(result)
(directory / "report.json").write_text(json.dumps(results, indent=2) + "\n")
if not results[-1]["passed"]:
raise SystemExit(1)
diff --git a/dev/contributor-lab/test_lab.py b/dev/contributor-lab/test_lab.py
index 16d90d0fb6b..4aa5aaa5132 100644
--- a/dev/contributor-lab/test_lab.py
+++ b/dev/contributor-lab/test_lab.py
@@ -192,8 +192,9 @@ def test_a_previous_successful_report_is_not_reused(self) -> None:
previous.write_text('')
with patch("subprocess.run", return_value=SimpleNamespace(returncode=0)):
result = self.module.check("functional", Path(directory))
- self.assertFalse(result["passed"])
- self.assertEqual(result["tests"], 0)
+ self.assertEqual(
+ result, {"track": "functional", "passed": False, "error": "missing report"}
+ )
def test_one_failed_quality_check_fails_the_track(self) -> None:
with tempfile.TemporaryDirectory() as directory:
diff --git a/dev/docker-compose.colour.yml b/dev/docker-compose.colour.yml
index f5e11bc70e6..df3e406c2be 100644
--- a/dev/docker-compose.colour.yml
+++ b/dev/docker-compose.colour.yml
@@ -63,8 +63,12 @@ x-colour-common: &colour-common
- loom-net
volumes:
- loom-shared:/app/var/shared
- # Code-plane git mirrors (bare clones); see docker-compose.cloud.yml.
- - ../var/code_repos:/app/var/code_repos
+ # A missing source would otherwise become a root-owned empty directory.
+ - type: bind
+ source: ../var/code_repos
+ target: /app/var/code_repos
+ bind:
+ create_host_path: false
healthcheck:
test:
[
diff --git a/dev/sandbox_probe.sh b/dev/sandbox_probe.sh
index 982fd6c5a72..e07287c37e8 100755
--- a/dev/sandbox_probe.sh
+++ b/dev/sandbox_probe.sh
@@ -1,15 +1,12 @@
#!/usr/bin/env bash
-# Does a freshly started colour run the repository-job sandbox? redeploy.sh
-# runs this after the colour is healthy and before the proxy swaps to it: a
-# profile that loads but refuses bwrap would otherwise leave repository jobs
-# unsandboxed without a word.
+# Can a freshly started colour use the git mirrors and repository-job sandbox?
+# redeploy.sh checks both after readiness and before moving the proxy.
#
# Each container started under the loom-repo-sandbox profile (decided from what
# it runs with, not the compose text) must pass sandbox_available(); one that
# does not run under it is skipped. A container that cannot be inspected or
-# fails the probe stops the deploy, and the colour's containers are removed:
-# the build already replaced the previous one there, so it is no rollback
-# target, and its workers must not take the lease and run jobs unsandboxed.
+# fails a check stops the deploy. Remove the staged containers so a rollback
+# cannot select a colour that failed a check.
#
# Usage: dev/sandbox_probe.sh
# Exit: 0 go · 1 stop (the colour's containers removed)
@@ -21,14 +18,15 @@ containers=("loom-$colour" "loom-$colour-workers")
stop() {
echo "!!! $1; not swapping."
- echo " Removing loom-$colour: --rollback must never start this build, and its workers must"
- echo " not take the lease. See \"Repository-job sandbox\" in docs/operations/code-index-operations.md"
+ echo " Removing the staged loom-$colour containers. See docs/operations/code-index-operations.md."
docker rm -f "${containers[@]}" >/dev/null || true
exit 1
}
for c in "${containers[@]}"; do
opts=$(docker inspect -f '{{.HostConfig.SecurityOpt}}' "$c") || stop "cannot inspect $c"
+ docker exec "$c" sh -c 'test -d "$1" && test -r "$1" && test -w "$1" && test -x "$1"' \
+ sh /app/var/code_repos || stop "$c cannot read and write /app/var/code_repos"
# The whole token: `[seccomp=… apparmor=loom-repo-sandbox systempaths=…]`.
if [[ " ${opts//[\[\]]/ } " != *" apparmor=loom-repo-sandbox "* ]]; then
continue
diff --git a/dev/test_plugins_wsl.sh b/dev/test_plugins_wsl.sh
new file mode 100644
index 00000000000..00a0e3e45d8
--- /dev/null
+++ b/dev/test_plugins_wsl.sh
@@ -0,0 +1,26 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+useradd -m ci
+# A clone inside WSL, with Linux modes and line endings, as a WSL user's is.
+git -c safe.directory='*' clone --quiet --no-local . /home/ci/repo
+chown -R ci /home/ci/repo
+npm ci --prefix /home/ci/repo/.github/agent-clis --ignore-scripts --no-fund --no-audit >/dev/null
+node /home/ci/repo/scripts/code-toolchains/bind-native.cjs /home/ci/repo/.github/agent-clis claude
+root=$(npm root --prefix /home/ci/repo/.github/agent-clis)
+codex=$(ls "$root"/@openai/codex-linux-*/vendor/*/bin/codex | head -1)
+test -n "$codex" && test -x "$codex" || {
+ echo "The locked native agent executable is missing" >&2
+ exit 1
+}
+su ci -s /bin/sh -c "
+ set -e
+ cd /home/ci/repo
+ node --version
+ git config --global user.email ci@example.com
+ git config --global user.name ci
+ node --test integrations/claude-code-plugin/tests/*.test.mjs
+ node --test integrations/grep-shim/tests/*.test.mjs
+ node integrations/claude-code-plugin/tests/e2e/agent-session.mjs claude --bin $root/@anthropic-ai/claude-code/bin/claude.exe --expect-tool Bash
+ node integrations/claude-code-plugin/tests/e2e/agent-session.mjs codex --bin $codex
+"
diff --git a/docs/api/playground/_loom_anchor_state.py b/docs/api/playground/_loom_anchor_state.py
new file mode 100644
index 00000000000..34a2b06bb6d
--- /dev/null
+++ b/docs/api/playground/_loom_anchor_state.py
@@ -0,0 +1,23 @@
+# Generated by docs/scripts/sync-playground-engine.mjs.
+"""Classify a link after its definition has been found."""
+
+from __future__ import annotations
+
+import hashlib
+from collections.abc import Sequence
+from typing import Literal
+
+
+def fingerprint(texts: Sequence[str]) -> str:
+ """Hash the definition's texts in order, normalizing line endings."""
+ joined = "\0".join(text.replace("\r\n", "\n") for text in texts)
+ return hashlib.sha256(joined.encode()).hexdigest() if joined.strip("\0") else ""
+
+
+def definition_state(
+ baseline: str, current: str, *, moved: bool = False, carried: bool = False
+) -> Literal["changed", "moved", "fresh"]:
+ """Compare the resolved definition with the baseline saved on the link."""
+ if carried or (baseline and current and baseline != current):
+ return "changed"
+ return "moved" if moved else "fresh"
diff --git a/docs/api/playground/check.py b/docs/api/playground/check.py
new file mode 100644
index 00000000000..3ad3d0f0e73
--- /dev/null
+++ b/docs/api/playground/check.py
@@ -0,0 +1,47 @@
+"""Run a Loom code-link check on the playground's sample definition."""
+
+import json
+import re
+from http.server import BaseHTTPRequestHandler
+
+from api.playground._loom_anchor_state import definition_state, fingerprint
+
+SAVED_STATUS = 503
+QUERY = re.compile(r"status=([1-5][0-9]{2})")
+
+
+def _source(status: int) -> str:
+ return f"def should_retry(status: int) -> bool:\n return status == {status}"
+
+
+class handler(BaseHTTPRequestHandler):
+ """Vercel discovers the handler by name."""
+
+ def do_GET(self) -> None:
+ match = QUERY.fullmatch(self.path.partition("?")[2])
+ if match is None:
+ self._reply(400, {"error": "Choose an HTTP status from 100 to 599."})
+ return
+ status = int(match[1])
+ source = _source(status)
+ saved = fingerprint([_source(SAVED_STATUS)])
+ current = fingerprint([source])
+ self._reply(
+ 200,
+ {
+ "definition": "retry.py::should_retry",
+ "source": source,
+ "saved_fingerprint": saved,
+ "checked_fingerprint": current,
+ "code_state": definition_state(saved, current),
+ },
+ )
+
+ def _reply(self, status: int, body: dict[str, str]) -> None:
+ data = json.dumps(body).encode()
+ self.send_response(status)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Cache-Control", "no-store")
+ self.send_header("Content-Length", str(len(data)))
+ self.end_headers()
+ self.wfile.write(data)
diff --git a/docs/architecture/assistant.md b/docs/architecture/assistant.md
index 7958ed72f4f..76b709269c9 100644
--- a/docs/architecture/assistant.md
+++ b/docs/architecture/assistant.md
@@ -1,594 +1,112 @@
# Assistant design
-This page is the design of Loom's assistant, which answers questions about what a
-namespace holds and how it is used, with a citation for every claim. It names the
-surfaces, how each caller's identity reaches the agent's tools, the analysis op and its
-isolation, the deployment, what is stored and erased, and the cost. Every part is built
-but the analysis key's rotation, which is design; [the build order](#build-order) lists
-the parts.
-
-LibreChat is the assistant: it hosts the agent (its model, instructions and tools) and
-runs it headless beside Loom, reachable only from Loom. Loom supplies the agent's tools,
-which read under a token of the asker's own subject, and a read-only SQL op that
-ClickHouse itself holds to that token's org and namespaces. People chat in the
-dashboard's Ask AI panel, opened from the header's Ask AI button beside the search
-field, or ask in the header search, which answers a question in place and goes on in the
-panel; agents and scripts reach the same agent over HTTP, MCP and both SDKs, through
-Loom's origin and as themselves.
+Loom's native assistant answers namespace questions through bounded model turns and
+read-only operations, under the caller's identity. It owns context selection, tool
+execution, streaming, cancellation, citations and accounting in the web process.
+It does not require a separate chat runtime or a conversation database.
## Surfaces
+The dashboard Ask AI panel, `POST /v1/assistant/chat/completions`, `assistant.ask`,
+its MCP tool and both SDKs use the same runtime. The chat route accepts OpenAI-shaped
+user and assistant messages, with streaming or whole responses. The op accepts a question
+and history. Callers provide history; Loom stores no conversation for these interfaces.
+A system message, file, tool result or model supplied by a client cannot override the
+server's runtime. The namespace header and existing op identity tuple keep their meaning.
+
```mermaid
flowchart LR
- P["person, signed in"] --> D["dashboard assistant panel"]
- A["agent or script"] --> S["SDK / HTTP / MCP"]
- D --> B["Loom assistant bridge"]
- S --> B
- B -->|"agents API: service key + this answer's token"| LC["LibreChat, headless (the Loom agent)"]
- LC -->|"MCP, that token"| T["assistant toolset"]
- T --> Q["insights.query"]
- Q --> U["ClickHouse user loom_analyst column grants + signed row policies"]
+ Caller["dashboard / SDK / HTTP / MCP"] --> Runtime["native assistant"]
+ Runtime --> Context["bounded host context"]
+ Runtime --> Model["explicit streaming provider"]
+ Model --> Runtime
+ Context --> Transport["authenticated MCP transport"]
+ Runtime --> Transport
+ Transport --> Operations["read-only registry operations"]
+ Operations --> Evidence["answer-owned receipts"]
+ Evidence --> Publication["citation and accounting checks"]
```
-| Surface | What the caller calls |
-| --------------- | ----------------------------------------------------------------------------------------------------------------------- |
-| Dashboard | the assistant panel, streaming from `POST /v1/assistant/chat/completions` with the signed-in session |
-| HTTP | `POST /v1/assistant/chat/completions`: LibreChat's agents API request and response, OpenAI-compatible, streaming or not |
-| SDKs | a thin `assistant` client in Python and TypeScript over that route, with streaming; it holds no agent logic |
-| MCP | the `loom_assistant_ask` tool (op `assistant.ask`), which forwards one question and returns the whole answer |
-| HTTP, op shaped | `POST /v1/assistant.ask` and the generated `ops.assistant.ask` / `loom.assistant.ask` SDK methods, from the same op |
-
-Each request names its namespace: the `X-Loom-Namespace` header on the chat route (the
-token's default namespace when absent), the `namespace` field on `assistant.ask`. The
-caller needs `viewer` there, and the answer's model spend is charged there. The chat
-route, `assistant.ask` and its MCP tool, the generated SDK methods, the SDKs' streaming
-clients (`agent.assistant.stream` in Python, `loom.assistant.stream` in TypeScript) and
-the dashboard's chat are built.
-
-`loom_assistant_ask` is in no curated MCP roster and, while `experimental`, not in the
-`all` listing either: each call spends model budget, so an agent calls it by name on
-purpose, as every unlisted op can be called. It is never in the
-[assistant toolset](../reference/mcp.md#the-assistant-toolset), so the agent cannot call
-itself.
-
-LibreChat's web UI and API are not published: LibreChat listens on an internal network
-only Loom reaches. A person has one sign-in and one URL, Loom's. The
-[LibreChat integration](../features/integrations/librechat.md), in which each person
-runs LibreChat's UI with a pasted token, is a separate, optional client; this
-deployment needs none of it.
-
-**Why LibreChat hosts the agent.** One agent definition, versioned in
-`integrations/librechat/`, serves every surface. LibreChat runs the model, the tool
-loop, streaming and cancellation, which Loom would otherwise build a second time. Loom
-keeps what makes an answer trustworthy: authorization on every tool call, the request
-ledger, the analysis boundary in the database, and the citation check.
-
-**Why a native chat, not LibreChat's UI in a frame.** A frame would put a second origin,
-a second sign-in and LibreChat's look inside the dashboard, and would need LibreChat's
-cookies to work in a third-party frame. The dashboard's assistant panel uses Loom's
-session and components, and links verified citations into the memory and document views
-([the assistant panel](../features/dashboard.md#ask-ai) has its rules).
-
-## The bridge: each caller's own identity
-
-Before checking model spend, the bridge reads the authorized namespace's public
-mirrored-source registrations. Any active registration marks the complete answer,
-even when its tools admit no document. The chat route sends `data: {"mirrored":true}`
-as its first SSE event, or `mirrored: true` as its whole response's first field.
-`assistant.ask` carries the same first field. A marked refusal carries it too. This
-decision also routes the answer's cost row to private storage and suppresses public
-diagnostics before subsequent model, budget or tool work.
-
-Marked operation results carry the same server-owned flag after their typed output is
-serialized. HTTP success responses retain it before post-handler rows. MCP success
-responses retain it in the outer envelope, tool result, structured content and canonical
-JSON text. The search tool's prose summary follows a separate first JSON marker block,
-so consuming its text blocks in order observes protection before the summary. Ordinary
-unmarked results keep their existing shapes.
-
-The answer token keeps the caller's `session_protection` promise and a separate
-`answer_mirrors` admission bit. Only an already marked answer for a declared caller
-receives positive admission. Missing or false admission disables its mirror legs,
-including when a source becomes active during an initially ordinary answer. Ordinary
-namespace reads retain their authorization. Current ACL checks still decide each
-mirrored item; the bit grants no access by itself. Ordinary delegated children omit
-both claims and cannot regain mirror admission through a request header. An answer
-token or any descendant cannot start another assistant answer.
-
-Streaming output is provisional until `[DONE]`. The response owns its required
-accounting lifetime beyond HTTP headers: it closes and joins model and citation work,
-captures final usage once, and confirms private cost delivery before sending `[DONE]`
-or a terminal error. Disconnects join producer cleanup and required delivery before
-propagating cancellation. A failed cost write cannot publish a completed answer.
-Whole answers and checked tool responses retain their accounting-before-publication
-boundary. Incremental text precedes final usage, so its completion boundary is the
-terminal event. A streaming client must reject EOF without `[DONE]` as incomplete.
-
-Mirrored-source creation stays unavailable until every serving build and consumer
-implements the admission, first-output marker, session and accounting boundaries.
-An older verifier accepting an unknown claim does not enforce it; schema equality
-does not establish this capability. The fleet and rollback requirements in
-[rolling upgrades](rolling-upgrades.md) still apply.
-
-LibreChat's agents API authenticates a LibreChat API key and runs the agent as that
-key's LibreChat user. The agent's tools are Loom's MCP server, and what they may read is
-decided by the token on each tool call, never by the LibreChat user. LibreChat v0.8.8
-fills an MCP header from three fields of the request body (`ALLOWED_BODY_FIELDS`:
-`conversationId`, `parentMessageId`, `messageId`), substituting the value as it is. The
-agents API takes `parent_message_id` from the caller as any string and, on a request
-with no `conversation_id`, uses it only for that field and as the anchor of a thread of
-files, which finds nothing with no stored conversation and the file tools off. So the
-bridge sends a token there, and the agent's MCP server sends it back to Loom. The
-LibreChat qualification runs this path, so an upgrade of LibreChat that changes it fails
-there before it ships:
-
-```yaml
-headers:
- Authorization: "Bearer {{LIBRECHAT_BODY_PARENTMESSAGEID}}"
- X-Loom-Run-Id: "{{LIBRECHAT_BODY_MESSAGEID}}"
-```
+## Each caller's own identity
+
+Admission checks the caller's viewer role, narrowed reads, expiry, org model-call
+switch, namespace budget share and concurrency. Org-wide callers and answer tokens
+or their descendants cannot start an answer. A viewer token is delegated from the
+asker's own subject, for this namespace and answer lifetime, ending with the caller's
+session or revocation. No global service account authorizes a tool call.
+
+The namespace's active mirrored-source registrations mark the answer before budget,
+context or model work. Marked responses send the marker first and use private
+accounting. The delegated token retains session protection and the answer's fixed
+mirror-admission bit. Current source ACLs still decide each returned item. A source
+becoming active later cannot widen an unmarked answer. Unknown admission refuses.
-They go under `headers`, not LibreChat's chat-only `requestHeaders`: those are left off
-the connection that lists the tools, whose `tools/list` would then go out without the
-token and leave the agent with no tools.
-
-The bridge (`server/assistant/app/bridge.py`, `routes.py`) serves a request in three
-steps:
-
-1. Verify the caller's Loom token or dashboard session as on any op, and its `viewer`
- role on the request's namespace. The chat route takes the same `Origin` and CSRF
- checks as `POST /v1/{op}`. Refused here, before LibreChat is called: a revoked or
- expired caller, an assistant answer's own token or one delegated from it
- (`ASSISTANT_SELF_CALL`), an org-wide (`*`) token (an answer reads one org), a token
- whose reads are narrower than its namespace (as `insights.query` refuses it), a caller
- whose token has less life left than one answer may run (a dashboard or `loom login`
- caller is not refused for its access token, which a refresh replaces every hour: its
- answer's token ends at sign-out instead), an org whose model calls an admin
- switched off (`org.set_model_calls`), and a namespace over its assistant budget or
- running its most concurrent answers ([Model and cost](#model-and-cost)). A refusal a
- client words for its reader carries `detail.reason`: `ASSISTANT_UNAVAILABLE` names
- `not_configured` (no LibreChat), `auth_off`, `starting` (this process has not set the
- service up yet, or is setting it up again) or `failing` (its last try failed; the setup
- loop retries), and `AUTH_INSUFFICIENT` names `org_wide`, `narrowed` or
- `token_expires_soon` (with `left_s`); a caller without `viewer` on the namespace
- carries none. Where an assistant is configured, `/v1/health/ready` reports an
- `assistant` check, never required (a deployment whose assistant is down still serves
- the rest), whose reason is `starting`, `failing` or `auth_off`; a missing check means
- none is configured.
-2. Delegate the answer's token from the caller's (`server/auth/delegation.py`
- `delegate`): `viewer` on the request's namespace alone, minted for the caller's own
- subject with consumer `loom-assistant` and an id starting with `assistant-answer-`
- (so a token delegated from it is told by its `parents`), as a service-account token
- when the caller's is one, and expiring when an answer may run no longer
- (`LOOM_ASSISTANT_ANSWER_TTL_S`, default ten minutes). Delegation applies every rule a
- minted child follows: the creator's live grant, the end user, the ancestor subjects
- and their issue times, the chain depth limit, and the caller's token id among the
- child's `parents`. The bridge also asks for the caller's sign-in session among the
- `parents` (`delegate`'s `ends_with_session`), so a dashboard or `loom login` caller's
- answer token ends at sign-out, as a third-party client's already does. The token is
- not listed in `loom.service_accounts`: it lives for one answer.
-3. Call LibreChat's agents API with Loom's service key, the seeded agent's id in place
- of any `model` the caller names, the answer token as `parent_message_id`, and the
- text of the caller's `user` and `assistant` messages (no `system` message, which
- would override the agent's instructions, and no files or images). Stream the response
- back with `Accept-Encoding: identity`. A caller that disconnects, or the chat's stop
- button, closes the upstream request, and LibreChat aborts the run. The bridge drops
- any `conversation_id` in the caller's body: on this path LibreChat stores no
- conversation, so it answers 404 for one it is given.
-
-An answer's token reads no more than the caller's own token, and ends no later than it,
-except under a sign-in session: every child of a first-party session takes the lifetime
-it asks for, so an answer's token lives one answer's limit
-(`LOOM_ASSISTANT_ANSWER_TTL_S`) and may outlive the hour-long access token it was
-delegated from, or a session that expires during the answer, by at most that limit. It
-is ended with its caller: revoking the caller's token, its subject, its sign-in session
-or a subject in its `creator` or `parent_subjects` chain ends the answer's token
-too, since delegation puts each of them in its revocation check. LibreChat holds the
-token in memory for the one request and stores it nowhere; the deployment sets none of
-LibreChat's tracing variables, which would export the run's request body, and the
-qualification searches LibreChat's logs for a token it sent.
-
-**One LibreChat user, which reads nothing.** Every answer runs as one LibreChat user,
-Loom's service user, which owns the agent definition. Its API key runs the agent, but
-the agent's tools read only with the token each request carries: a request without one
-gets `401` on every tool call, and a request with one reads as that token. The key is
-therefore not a credential that reads anything in Loom. One row of
-`loom.assistant_service`, a `ReplacingMergeTree(version)` table, holds the service
-user's email, the agent's id, the version and model of the definition last written, and
-one sealed value (`server/core/secrets_at_rest.py`) holding a random password and the
-agents API key together, so a reseal rewrites both at once. `loom secrets reseal` (which
-takes [`analysis.entities`](#provisioning), then `assistant.service`) covers it when the
-root secret (`LOOM_JWT_SECRET`) is replaced, and the deployment carries no second
-secret.
-
-Setting the service up is one step that a boot runs holding the cluster lease
-`assistant.service` (`server/core/leases.py`), so two boots never run it at once; the
-holder re-reads the row (as every read of it, with the read-your-writes setting
-`own_write_reads` in `server/core/ch.py`) and does only what is missing, storing each
-result on the row before the next, and signs in at most once (twice when it registers
-the user), at the first step that needs LibreChat:
-
-1. No row: write the email and a sealed random password.
-2. No key: sign in, registering first only when LibreChat answers that the email does
- not exist (LibreChat words a wrong password the same way but for its text, so the
- qualification pins that answer), delete any key of the service user's that a boot cut
- short left behind (keys carry the definition's name), then create the key.
-3. No agent id: list the service user's agents by the definition's name, keep the oldest
- and delete the rest, or create the agent when there is none, and store its id.
-4. A stored definition older than this build's, or of the same version with another
- model: write it and store its version and model on the row.
-
-A boot that stopped halfway leaves the row at a step the next one finishes, and a boot
-over a complete row checks with the stored key that LibreChat still holds the key and
-the agent, making either again when it does not ([Deployment](#deployment)). Answers run
-on the stored key whatever a sign-in does. Two failures need an operator, and
-`/v1/health` names each as `assistant_service_failing`: a row whose sealed value opens
-with neither `LOOM_JWT_SECRET` nor `LOOM_JWT_SECRET_PREVIOUS` (set the previous secret
-and run `loom secrets reseal`), and a sign-in LibreChat refuses with a 4xx other than
-its 429 limit (its database restored from another deployment, say; v0.8.8 answers a
-wrong password 404 `Incorrect password.`): empty it and run `TRUNCATE TABLE
-loom.assistant_service`, and the next boot recreates both. A 5xx sign-in is LibreChat or
-its database being unavailable, which the next try asks again. A try that registers the
-service user also makes a new key, since that user cannot own the one the row held.
-Until the row has its key and agent id, the assistant answers `ASSISTANT_UNAVAILABLE`.
-
-**Conversations live with the caller.** LibreChat's agents API (the OpenAI-compatible
-`/api/agents/v1/chat/completions`) saves no messages: it runs the agent over the
-messages in the request and records only token counts in its `transactions` collection.
-A multi-turn chat is the caller's message list, which the dashboard keeps in the browser's
-storage and an SDK caller sends each time, as with any OpenAI-compatible API. The agent's MCP
-connection carries request-time headers, so LibreChat opens it for each answer and
-closes it after; each answer pays one MCP `initialize` and `tools/list`.
-
-**Citations.** The agent's instructions require a citation on each claim:
-`[memory:@v]`, `[doc: § ]`, `[code::]`,
-or a fenced `sql` block in the answer that holds the statement exactly as it ran. The
-bridge checks each when the answer ends, inside the answer's slot and for at most ten
-seconds in all (`server/assistant/app/citations.py`). A memory citation is verified when
-one of the answer's own tool calls was returned its key: the exposure rows
-(`loom.memory_exposures`) that the toolset's `memory.search`, `memory.ask`,
-`memory.get`, `memory.list` and `memory.inspect` record under the answer's run,
-whichever user or session the row is under (a search hit on one of a key's chunks counts
-as its key). The assistant toolset drops any `run_id` a call names, so those rows are
-filed under the answer's run; on `memory.search` the argument is also a filter to one
-run's rows, which the assistant gives up. The exposure rows record keys, not versions,
-so a memory citation's version is not compared. Only those reads record exposures: a key
-returned by any other call (`memory.history`, `memory.provenance`, an `insights.query`
-row) is not seen, and its citation comes back unverified with a reason that names the
-reads that count; a fact a query found is cited by the query's `sql` block instead. A
-`sql` block is verified when its digest is the `out_sql_digest` of an `insights.query`
-call ledgered in this answer (`loom.agent_events`). A document citation's section must
-be a heading path of a live document (`knowledge.outline`), and one with no section
-verifies when the document is readable. The document is read through Loom's own routes
-in process with the answer's token, so every gate a read passes applies to it, in a task
-of its own (each check is a task of an `asyncio.gather`) so the read leaves the answer's
-request state alone, and under no run id. A code citation is not checked: a code index
-is a namespace of its own, which the answer's token (viewer on the answer's namespace
-alone) does not reach, so `code.verify_citations` is not called for it. Nor are an
-answer's citations past the fiftieth. The agent's MCP server sends the answer's message
-id on each tool call as `X-Loom-Run-Id` (the agents API fills
-`{{LIBRECHAT_BODY_MESSAGEID}}` with the id every chunk carries). On the assistant
-toolset the MCP transport labels the call's ledger row with that header, in
-`agent_events.run_id`, as HTTP already does; there the header wins over the session's
-run label, and an answer's connection opens no session run, so the bridge reads the
-answer's rows by the org, the namespace, that run id and the caller's subject, its
-`insights.query` rows also by the consumer `loom-assistant` its token carries. A caller
-who knows its answer's run id could plant a row of its own under it; such a row is the
-caller's own call, so a citation it makes verified misleads only the caller. The rows
-are written in the background and a tool call can land on another replica, so the bridge
-waits up to five seconds for them; a citation whose row has not arrived by then, or was
-dropped, comes back unverified. A check Loom refuses (a rate limit, an outage), a ledger
-that cannot be read, an answer with no run id, a check past the ten seconds, or a
-document read whose token expired (an answer that ran to its limit leaves its checks a
-token near its end) leaves its citation unverified with the reason "the check could not
-run", and never fails the answer. With memory reads not recorded
-(`LOOM_MEMORY_EXPOSURE_LEDGER_ENABLED` off) a memory citation's reason is "this
-deployment does not record memory reads". Each citation comes back marked
-`verified` or not, with the reason and its `ref` (the memory key, document source,
-documentation page or code path it names), in a last `loom.citations` event before the
-stream's `[DONE]` (and a `citations` field on a whole answer and on `assistant.ask`),
-with the answer's [support](#support). A streamed answer sends a `loom.text_done` event
-when LibreChat's stream ends, before the checks start, so a client can show the text as
-complete while they run (up to ten seconds); the answer's slot is held until
-`loom.citations`. The dashboard shows "Checking sources…" under every streamed answer in
-that time, since the checks read every streamed answer's run.
-
-A help citation, `[help: § ]` (the section optional, its breadcrumb
-starting with the page title as `help.search` returns it), is checked against the
-replica's own index of the shipped docs: verified when the page is indexed and the
-section is one of its own (its breadcrumb, the breadcrumb without the page title, or a
-tail of it no other section of the page shares), with the section's `anchor`, which the
-dashboard's Sources link to the Help page (`/help?page=#`). A page that is
-not indexed, or a section the page does not have, fails as a document citation does. The
-docs are the same for every caller, so the check reads nothing of Loom's. During a
-rolling upgrade a bridge of the build before the kind does not parse it, and an answer
-resting only on help citations shows as `none` there.
-
-**Names.** The instructions allow an op or setting name only from a tool's result, and
-the tool results stay with the agent, so the bridge checks what it can decide: each
-backticked dotted name whose first part is an op group (`memory`, `knowledge`, ...) and
-each `LOOM_*` name in the answer is known when the build serves it as an op, reads it
-as an environment variable (a setting, `NON_SETTINGS_ENV`, a prefix family), or its
-docs write it; a name ending in `_` is a family, known when one of those starts with
-it. The rest come back in `unknown_names` beside the citations (the event's field and
-`assistant.ask`'s), and an answer that writes one is `unsupported`, whatever it cites:
-it may have invented the name. With no docs to read, none is reported. A name written
-in prose, without backticks or the `LOOM_` prefix, is not checked.
+Every native tool request goes through `/mcp?toolset=assistant` in process, in a
+child task with the answer's bearer and run id. It passes token verification,
+revocation, namespace and row-reach checks, role gates, idempotency and operation
+accounting. The existing assistant roster and forced arguments prevent writes,
+reinforcement, arbitrary run ids and recursive assistant calls. The model sees a
+bounded subset of schemas for relevant read operations, without provider overrides.
+Tool results and history are untrusted data and confer no authority.
### Support
-Each answer comes back with `support` (on the `loom.citations` event, the whole answer
-and `assistant.ask`), which says how far it rests on what Loom holds. The server decides
-it (`server/assistant/domain/support.py`), from the codes its citation checks ended with
-and, for an answer that cites nothing, from what its own tool calls found; the first
-that applies wins:
-
-| `support` | When |
-| ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `none` | The answer has no text; or it cites nothing and either says the abstention sentence the agent's instructions give ("Nothing stored in Loom answers this.", in any case or emphasis) or it made no call to an op whose rows it could cite and none of its calls found data or failed. A greeting, a capability reply and an abstention make no claim. |
-| `supported` | A citation verified. |
-| `unsupported` | It names an op or setting the build neither serves nor documents (`unknown_names`); or a citation failed for a reason of its own (its key was not returned to this answer, its document or section is not there, its statement did not run in this answer); or it cites nothing although a call of an op whose rows it could cite found data, or ran and found nothing while no other call found data or failed (a claim nothing backs). |
-| `unchecked` | Otherwise: its checks could not say (a read failed or ran past its bound, no run id, memory reads not recorded, code citations, past the 50 checked), or it cites nothing and what found data has no citation form (counts and findings: the ops in `ASSISTANT_UNCITABLE_OPS`, such as `namespace.summary` and `namespace.inventory`), or a call failed. |
-
-The ops whose rows an answer can cite, those whose output has no citation form, and
-those that return no namespace data (Loom's own guide, documentation and catalog) are
-sets in `server/operations/toolsets.py`, with the output list each op's ledger row
-counts as `out_hits` (or its `found` flag) to say whether it found anything. A test
-requires every op of the assistant toolset to be in exactly one set and to say how its
-row shows it found nothing. The answer's calls are read by its run, its caller's subject
-and the consumer `loom-assistant`, with no namespace filter (`ledger.run_rows`): a code
-call is ledgered under the code namespace and a refused call under the sentinel. The rows
-land in the background, so two patterns read them:
-
-- A whole answer (`assistant.ask`, the chat route asked without `stream`) reads its calls
- only when it cites nothing: once, and once more after the ledger's flush interval and
- the batched-insert wait unless the first read already found a citable op's data.
-- A streamed answer shows what it read under it ([steps](#steps)), so it reads its calls
- on every answer, cited or not: once, after the same wait, beside its citation checks.
- That one read gives both its support and its steps.
-
-The reads and the waits are bounded at three seconds together, past which the answer is
-`unchecked`. One read takes 200 rows; a run with more is cut, and a cut run keeps only an
-outcome its first 200 rows decide (`unsupported` when a citable op found data there),
-else it is `unchecked`. A presence answer of `code.symbol` finds only where the symbol is
-present.
-
-The rule reads no wording beyond the abstention sentence, and accepts these residuals:
-
-- A greeting, capability reply or uncited question back after a citable call is
- `unsupported` (`unchecked` when only ops with no citation form found data). The
- instructions keep such calls rare: a greeting calls no tool, and a question back lists
- each match with its citation.
-- An uncited fact with no call at all (a later turn restating an earlier one, or a
- first answer from the model's own knowledge, which the instructions forbid), or after
- calls whose rows land past the wait or the re-read, or are dropped (the ledger keeps
- them at most once), is `none`.
-- A run of more than 200 ledger rows is judged on its first 200, so a citable op's data
- past them is not seen: such an answer is `unchecked`, never `none`.
-- A "not found" answer from a lookup that misses (`memory_get`, `code_symbol`) is
- `none` when it ends with the abstention sentence, as the instructions ask for every
- read that finds nothing; worded otherwise, it is `unsupported`.
-- An abstention that also states a fact is `none`.
-- An uncited answer from `help.search` and `help.get` is `none`, but `unsupported` when
- a citable call of the same answer found data; the instructions ask for every docs
- section used to be cited as `[help:...]`, which verifies.
-- A document citation verifies when the document holds the section, whether or not this
- answer read it; the instructions ask for a document to be read again before it is
- cited on a later turn.
-
-**Rendering.** The answer is model output that stored text can steer, so the dashboard
-renders it as text with Markdown emphasis, lists, tables and code only: no HTML, no
-images and no links in the answer's text but its citations, each drawn as a number by
-where it first appears (`citationNumbers` in
-`frontend/src/views/assistant/AnswerText.tsx`), which links to the citation's Sources
-row once the check ends; the panel and the header search's card, a preview of the
-answer, number an answer alike. The dashboard's `img-src 'self' data: blob:` already
-stops a remote image that would carry rows away in its URL. Under a finished answer its
-Sources (`frontend/src/views/assistant/Sources.tsx`) list each citation as the server
-checked it, under one Sources label, each led by its number and named as the reader
-knows it (a memory by its key, its kind and version in the row's tooltip): one found in
-Loom opens, a memory in the memory drawer, a document in the Library and a help citation
-on the Help page at its section, by the citation's `ref`; any other reads "not
-confirmed" with its reason. A label above them says the answer's support in words,
-leading with how many sources were found when some were not: "Checked against what Loom
-holds", "Partly confirmed: n of m sources found in Loom", "Couldn't confirm: 0 of m
-sources found in Loom", "Couldn't confirm: it names …" (an op or setting this Loom does
-not have), "Couldn't confirm: it gives no sources", "Sources not checked" or "Not
-checked: it cites nothing Loom holds"; an answer whose `loom.citations` never came (the
-connection was lost after its text, or the page was left) reads "Check didn't finish".
-Each label's "Why this label" note says why it reads as it does; an answer whose support
-is `none` has no label. A value the dashboard does not know reads as `unchecked`.
+Citations are checked against structured results actually delivered during this answer,
+not an eventually consistent analytics read. A memory citation needs its exact key and
+version; a code citation needs a returned path and line span; a document citation needs
+a returned source and section; a help citation requires text from `help.get` for the
+page or section. An outline from a truncated or continuation read supplies no evidence
+for unread sections.
+A SQL block must match a successful `insights.query` statement. Unknown citations or
+operation and setting names refuse completion. Arbitrary result text cannot supply
+source identifiers for verification. A verified citation proves that evidence was
+returned, not that every sentence is entailed by it. Each citation check records
+whether that source was returned to this answer. Support for an uncited answer derives
+from its tool receipts.
+
+Prior-value questions read `memory.history` after locating the key. A historical
+memory citation binds the requested key to the exact version and value returned in
+that receipt; redacted rows cannot verify it. Current-value questions use current
+reads. Population questions use `namespace.inventory`, keeping its read scope,
+observed-agent and member distinction, totals, bounded top lists and incomplete
+reasons. A complete count does not make a shorter top list exhaustive.
### Steps
-While a streamed answer runs, the bridge reads the answer's own calls from
-`loom.agent_events` as their rows land and sends them as `loom.step` events, each carrying
-the whole list so far (`steps`: `{op, text, ok}` per call, oldest first), so the dashboard
-shows the latest as its working line. The read (`server/assistant/store/ledger.py`
-`live_rows`) runs at once and then after 1 s, 2 s and every 4 s to the answer's end.
-Before the first chunk gives the answer's run id it filters the org, the namespace, the
-caller's subject, the consumer `loom-assistant` and the second before the answer started
-(a second that takes the streaming replica's, the serving replica's and ClickHouse's
-clocks to agree; under more skew a call shows only once the run id is known), so the calls
-of the caller's other answers in the namespace that land before the run id is known
-(another tab's, say) mix in, which progress text accepts. Once the run id is known it
-filters by the run with no namespace (code and refused calls included), so another run's
-calls are not read. Each step's words come from a fixed line per op of the toolset
-(`server/assistant/domain/steps.py`, "Read the audit", "Couldn't search memories" for a
-failed or refused call); a row of any other op is no step. A step shows once its call has
-finished and its row has landed, up to four seconds later. A read that fails ends the
-steps; the answer goes on. The steps are display only and never decide the label.
-
-The `loom.citations` event then carries `steps` from the one read of the run after the
-answer ends (above), which replace the live list: an empty list when the run made no call,
-and no `steps` when that read failed or ran past its bound, when the dashboard keeps what
-it showed live; and `steps_cut: true` when the run held more than 200 ledger rows. These
-events and `loom.text_done` have `choices: []`, the run id (or none yet) as `id`, and no
-model or usage, so a client that guards for no choices skips them; both SDKs skip
-`loom.step` and `loom.text_done` and expose the final list as the answer's `steps`. A
-whole answer and `assistant.ask` carry no steps and no `loom.text_done`.
+Host context and model-selected tools have separate `origin` values in progress events.
+Each tool has a run id and an existing request-ledger row. Model progress records the
+logical turn, physical attempts, duration and usage status. Generations use existing
+trace spans and customer attribution. Streaming text is provisional until `[DONE]`.
+EOF, a failed tool, a malformed model frame, a provider refusal or an exhausted budget
+cannot publish a completed answer. Required private cost delivery precedes `[DONE]`.
+Source proofs retained from tools are renewed after final accounting and before the terminal
+event, including tools whose nested transport runs in another task.
+Disconnects close and join the model and tool work before final accounting.
### Starters and cards
-The dashboard's panel lists starters, one per read that answers a question about the
-namespace exactly: `namespace.inventory`, `namespace.audit`, `memory.inspect`,
-`knowledge.inspect`, `mentor.brief`, `namespace.tune`, and a link to the Graph. A
-starter's card is that read, made by the dashboard with the person's own session, not by
-the answer: it is gated on the read's own role and scope, works while the assistant cannot
-answer, and costs no model call (`frontend/src/views/assistant/cards/`). The starter also
-asks the assistant its question when the person keeps "Also ask the model" on; the
-question names the arguments the card was first read with (the audit's window, the
-mentor's agent; the card's selects read it again with others, which the question then no
-longer names), and its answer gets the same [support](#support) label as any other, the
-card's own line ("Loom's own read") saying the card is exact. The cards live in the
-conversation the browser keeps, a snapshot of up to 32 KB each; a card restored from
-History is read again before any action. A draft's action is the person's own click on the
-existing op under their own role (registering a category, the guide editor on top of the
-guide read now) or a copy of the change; the answer's token stays `viewer` and the
-assistant writes nothing. Cards come only from starters: a free-form question's tool calls
-carry no arguments the dashboard could read again.
+The dashboard's existing namespace starters and draft cards use their existing
+operations. A write remains the person's explicit action under their own role.
### Asking again
-Ask again (Retry on a failed answer), an edit of the last question and "Ask again with
-sources" answer the last turn again under its own id
-(`frontend/src/views/assistant/chatStore.ts`), so another tab's
-stored copy cannot bring the old answer back. The turn keeps its old answer, on screen and
-in storage, until the new text begins: an attempt that fails, is refused, is stopped or
-ends empty first puts the turn back as it was, as does a reload before then.
-
-- **Try again** follows a refusal whose reason the panel shows, and any such ending of an
- edit whose words changed. It answers that turn again with the words, page line and "with
- sources" it was asked with, whatever the field holds. Another question, Cancel edit, a
- new conversation or another one opened drops it.
-- Any other ending of an Ask again (a rate limit, the cost cap, a lost connection), or of an
- edit that left the words as they were, offers no Try again.
-- In each case an empty field gets the question as an edit (after Stop, only an edit's
- words), and an Ask from it goes with the chip as it shows now.
+A retry is the caller's choice. Model requests are sent once per logical turn; an
+uncertain stream is never replayed automatically. There is no fallback provider.
## The agent definition
-`integrations/librechat/agent.yaml` holds the agent's name, instructions, model and a
-version number (`server/assistant/domain/definition.py`); the tools are the assistant
-toolset's, listed by Loom. Loom seeds it at boot under the service user, which owns it,
-so nothing is shared. `LOOM_ASSISTANT_MODEL` and `LOOM_ASSISTANT_PROVIDER` replace the
-file's model and provider when set; `local` is LibreChat's endpoint for a model server
-the operator runs (`deploy/librechat/assistant.librechat.yaml`). The stored row records
-the definition's model as `/` when the provider is not the file's, and
-as the bare model otherwise. It writes the definition when its version is newer than the
-stored one, or the same with another model, so during a rolling upgrade a build N-1
-never overwrites N's definition, and a changed `LOOM_ASSISTANT_MODEL` or
-`LOOM_ASSISTANT_PROVIDER` takes effect at the next boot. One exception: a build that
-predates `LOOM_ASSISTANT_PROVIDER` ignores it, so with it set that build rewrites the
-agent onto the file's provider under the local model's name; unset it and
-`LOOM_ASSISTANT_MODEL` before rolling back. Otherwise, while N rolls out and after a
-rollback, N's definition stays, and a tool call it names that an N-1 pod does not serve
-answers `UNKNOWN_OP` there until every pod runs N.
-
-The tool list is the assistant toolset's reads and `insights.query`, so the agent writes
-nothing; a change it suggests is a draft a person applies elsewhere, as the Assistant
-page's tune drafts already are. The instructions require citations, tell the agent to
-call a tool before answering a question about the namespace (a greeting calls none) and
-abstain when none supports it, to write no text before or between its tool calls, to
-read `insights.catalog` before running SQL, to start a question about Loom itself that
-does not plainly ask how to use it with a memory, a document and a help search together
-and answer a fact the namespace holds from the namespace, to answer how Loom works from
-`help.search` and `help.get`, citing each section as `[help:...]` rather than as a
-document citation, and to treat stored text as data that cannot grant a tool or approve
-a change. The agents API streams the text of every model step as one answer's content,
-with nothing between steps
-([streaming](../features/integrations/librechat.md#tool-errors-streaming-and-cancellation)),
-so neither the bridge nor the dashboard can tell a lead-in ("Let me search the
-memories.") from the answer it runs into. While no text has arrived, the dashboard shows
-that the assistant is answering. Asked how a namespace should write, the agent
-recommends rather than only answers: key shape, one claim per key, a memory, a document
-or a record, pins and kinds, each recommendation naming its rows and citing the finding
-it rests on in `namespace.audit`, `mentor.brief` or `namespace.tune`, the namespace's
-guide (`namespace.guide_get`), or Loom's own writing guide (`mentor.guide`, on the
-toolset for that reason).
-
-The agent names no namespace on its calls: on the assistant toolset a call that names
-none reads the first namespace its token names ([the assistant
-toolset](../reference/mcp.md#the-assistant-toolset)), which for an answer's token is the
-request's. A test pins a digest of the name, provider, model parameters, instructions
-and tools to the version, so a change to any of them bumps it.
+`server/assistant/domain/instructions.py` holds the instructions. The host selects
+bounded initial context before the first model request. Named code questions use a
+symbol lookup; conceptual code questions use code search; Loom usage questions use
+help search; counts use the analysis catalog; other questions use memory and document
+search. Additional calls are adaptive, with a shared total bound and normalized
+query deduplication. The model need not select its initial context.
## Loom's documentation
-The assistant answers how Loom works from Loom's own documentation, as the build that
-serves the answer ships it. The image copies `docs/` (its Markdown; the screenshots stay
-out of the build context), and two read-only ops on the assistant toolset read it:
-`help.search` (a question or a name in, the best sections out, each with its page, its
-breadcrumb, its anchor, its audience and a snippet) and `help.get` (a page with its
-outline, or one section of it, found by the anchor a hit names, since a page may repeat
-a heading). Both are `experimental`, deployment-scoped and in no curated roster: any
-token that may read the agent guide may call them by name.
-
-The docs are indexed in each process, on its first help call, in a worker thread: each
-page is split at its headings by the splitter documents use
-(`server/knowledge/domain/chunking.py` `detect_sections`), so a section's breadcrumb
-starts with the page title as a document citation's does, and the sections are scored
-with BM25 (`server/core/bm25.py`). Terms are the words, plurals and simple suffixes
-folded, plus every whole identifier (`memory.set`, `LOOM_ASSISTANT_MODEL`), so an exact
-op or setting name finds the line that names it. An operator section's score counts
-three quarters, since most askers use Loom rather than run it. The index holds about
-2,200 sections in about 14 MB and builds in about a second; a search reads only the
-postings of its terms, and concurrent first calls share one build. A page that cannot
-be read is left out with a warning, and a process with no docs answers
-`available: false` until it restarts: the docs change only with the build, so a fault
-never rebuilds the index per call. An answer that rests only on `help.search` and
-`help.get` and cites nothing carries no support label, as one resting on `mentor.guide`
-does: the docs are not the namespace's data. A read returns at most 16,000 characters,
-and a cut one names the offset its rest starts at; a page read, or a cut one, adds the
-page's outline.
-
-**The page's context.** The dashboard's panel starts a question with one line about the page
-it is asked from, `Context: page`, and with the item "Ask about this" named,
-`Context: Memories page, memory "" (agent "", user "", session "")`,
-`Context: Library page, document "" (title "")` or `Context: Recall page,
-result , memory "", for the query ""`: a key or source URI the agent reads
-with `memory.get` or `knowledge.get`. A memory's user and session are named when the drawer
-read the row under them (a row filed under a user or a session), since `memory.get` takes
-`user_id` and `session_id` and misses such a row without them; an answer's token reads the
-whole namespace, so naming another user's row is a filter, not a widening. The line quotes
-names that others wrote and the person's own query, each as a JSON string literal, so a quote
-or a line break in one cannot end it: a key, a source URI, a user or a session exactly as
-stored, never cut, and an agent, a title or the query on one line, cut at 200 characters. The
-person sees it as a chip and can remove it before it is sent; it grants nothing, and no
-server or wire field carries it
-([the assistant panel](../features/dashboard.md#ask-ai)).
-
-**The asker's context.** An answer's token is `viewer` on one namespace, so the agent
-cannot tell from it what the person asking may do. The bridge, which holds the caller's
-own credential, puts one line in fixed words as the last line of the question it sends
-LibreChat: `Loom, for how-to answers only: this question comes with , whose
-role in this is .` The credential is `a sign-in session`, `a delegated
-token` (one capped by the grant of whoever made it, a client token's included), `a
-scoped token` (its role per namespace in its claim) or `a token`. The role is the
-highest the gate admits, after the viewer check every answer passes (`admin`, `writer`
-or `viewer`), or `unknown` when a check could not read what it needed. The place is
-`personal collection`, `collection`, `restricted namespace` (the directory's cached
-classification, no read) or `namespace`. The line names no subject and no namespace, so
-nothing the caller controls is in it and no identity goes to the model provider through
-it. It never refuses an answer. The instructions read it as Loom's only in that place,
-treat it as granting nothing, and answer how a role is raised from the documentation for
-that credential and place, naming the namespace's admins from `grants.list`. A bridge of
-an earlier build sends no line, and an answer that depends on the person's role then
-says it does not know it.
-
-**Why not a knowledge source.** Knowledge rows are tenant data: an org and namespace on
-every row, erasure coverage, and a copy per org or a read path across tenants. Indexing
-them spends embedding calls, and replicas of two builds would share one copy during a
-rolling upgrade, so one build would answer from the other's docs. The docs are the
-same text for every caller, hold no tenant data and change only with the build, so
-help keeps them out of ClickHouse: nothing is written, erased or embedded.
-
-**Nothing is withheld by role.** Every page is in the public source tree, and
-`tests/unit/test_public_copy.py` keeps hosts, keys and internal names out of it, so a
-page withheld from a viewer would protect nothing. Each hit says its audience instead:
-`operator` for running or building Loom (`operations/`, `architecture/`,
-`benchmarks/`), `user` for the rest. The contributor pages (`development/`) are not
-indexed. Help reads no environment, setting value or secret.
+Help searches read the build's bundled documentation. A model must fetch a returned
+section before citing it. The source's audience distinguishes operating Loom from
+using it, and examples are not deployment facts.
## The analysis op
@@ -601,16 +119,13 @@ call it directly, on any transport, and it joins the
`read_scope` is narrower than its namespaces is refused it, as every op outside
`SCOPED_OPS` and `NARROW_SAFE_OPS` is.
-The event catalog relation is `loom.analysis_agent_events`. It retains authorized request
-participation and neutralizes marked model, spend, work and outcome fields before caller
-filters, joins or aggregates. It unions ordinary `loom.agent_events` with
-`loom.agent_events_private`; the analyst has no grant on the private table. The
-ordinary table retains signed, namespace-scoped access for both serving builds and
-rejects marked events and reserved mirror namespaces through its permanent CHECK.
-The view's definer query applies the same signed org/namespace predicate as
-the physical tables' row policies; it does not use SQL-account grants. The typed projection
-is passed from the maintained event reader definition into the pure access-entity builder.
-Its shape, signed predicate and security mode are part of the entity version digest.
+The event catalog has two views. Use `loom.analysis_ordinary_agent_events` for ordinary
+requests and worker events, or `loom.analysis_agent_events` for the request ledger with
+marked model, spend, work and outcome fields masked. Both views enforce the signed
+organization and namespace before returning rows. Their definer reads the physical
+event tables and the analyst holds column grants on the views. Both physical tables
+and their storage metadata are outside those grants. The projections, signed
+predicates and definer clauses are included in the entity version digest.
### The boundary is the database user
@@ -696,7 +211,7 @@ one row of `loom.analysis_secrets`. The password holds a lower and an upper case
digit and a symbol, which ClickHouse Cloud requires of a user's password. The row is
sealed with `server/core/secrets_at_rest.py` in the shape `loom secrets reseal` rewrites
(`SEALED` in `server/cli/secrets.py`). The reseal reads under `own_write_reads`, skips
-a row that is gone and holds the analysis lease; with [part 2](#build-order) the CLI
+a row that is gone and holds the analysis lease; with [analysis key rotation](#analysis-key-rotation-limits) the CLI
rotation holds it too, so they never interleave, and the printed rotation, which takes
no lease, stores its row at a version from ClickHouse's clock at insert time in
nanoseconds, far above any reseal's `version + 1`. A row a reseal puts back during a
@@ -742,7 +257,7 @@ the cut shortens. All of these are read only by whoever administers the ClickHou
who can read every row anyway, and by Loom's own user where it has `SHOW ROW POLICIES`;
that user can already open the sealed row.
-**Why not ClickHouse credentials in LibreChat.** A ClickHouse login in the agent would
+**Why the model receives no ClickHouse credentials.** A ClickHouse login in the agent would
read every org, skip the request ledger and the exposure records, and keep no link to
the asker's token. The analysis op runs inside Loom's request path: the token is
verified first, the namespaces are checked as on any read, and the call is ledgered.
@@ -761,27 +276,22 @@ stored key. Elsewhere an admin uses one of two commands:
rules below (it holds the lease and writes unless the stored version is newer than its
own), so it is also the repair on a server that cannot write them. It draws the row
only when there is none and no analyst user exists; over a lost row with the user
- still there, it refuses: until the rotation of [part 2](#build-order), the recovery is
+ still there, it refuses: until the rotation of [analysis key rotation](#analysis-key-rotation-limits), the recovery is
to drop the analyst user and run it again.
- `loom ch-setup --apply-analyst-sql`, run with explicitly configured existing
access-management credentials, applies only the analyst entities under the same
- lease and lost-key rules. It does not rebuild the reader user. Its live
- [event cutover](rolling-upgrades.md#analyst-event-storage-cutover) proves writer,
- CHECK and policy visibility before grants. A shared service endpoint can supply
- checked sessions for all replicas; separate replica addresses are not required.
- If that endpoint cannot reach every writer, `LOOM_CH_ANALYSIS_OBSERVER_URLS` adds
- trusted HTTP origins using the configured service credentials. Missing writers
- and changes in a checked session refuse provisioning.
+ lease and lost-key rules. It reads the native policy definitions for Loom's
+ database before writing the policies and grants. The setup creates the analyst
+ login on first use and keeps its existing password on later writes.
`loom ch-setup --print-analyst-sql` refuses with a nonzero result and prints no
-statements or secrets. An unchecked SQL file cannot enforce the native access-catalog
-proof, including a catalog hidden by its own policies. General `--print-sql` still
-prints database and reader preparation with a password placeholder. Entity writes
-cut their query-log text and disable local statement capture so policy expressions
-and passwords do not enter either log.
+statements or secrets. The setup verifies the live policy definitions before it
+writes. General `--print-sql` prints database and reader preparation with a password
+placeholder. Entity writes cut their query-log text and disable local statement
+capture so policy expressions and passwords stay out of both logs.
The allowlist lives in code with the column comments that become the agent's catalog, so
-the grants, the policies, the masked event view and the catalog come from one definition. The rules a write
+the grants, the policies, the event views and the catalog come from one definition. The rules a write
keeps:
- **One writer at a time.** A write holds the cluster lease `analysis.entities`
@@ -800,7 +310,7 @@ keeps:
They come before every grant, so a new pin is in force before the grant it guards. A
first draw by a boot or `loom ch-setup`, made while no analyst user exists, stores the
secrets row before it creates the user. A rotation, by the CLI or the printed SQL
- (both with [part 2](#build-order)), is a short maintenance step that keeps analysis
+ (both with [analysis key rotation](#analysis-key-rotation-limits)), is a short maintenance step that keeps analysis
unavailable while it runs:
1. It deletes the secrets row, which only decides what a rotation cut short looks
@@ -866,7 +376,7 @@ keeps:
their own: a write holding the lease (a boot, `loom ch-setup`) writes them when the
stored ones differ from its settings, the printed SQL always writes them, and nothing
else does, so they never touch the version. They are read at boot, not live; with
- [part 2](#build-order), `loom doctor` reports a caps profile that differs from the
+ [analysis key rotation](#analysis-key-rotation-limits), `loom doctor` reports a caps profile that differs from the
server's settings.
- **No granted table without its policy.** By default ClickHouse lets a user with no
policy on a table read every row of it, so each policy is replaced in place, every
@@ -878,10 +388,10 @@ keeps:
- **The key never changes by itself.** The secrets row is drawn once, and every read of
it, the one under the lease included, runs with the read-your-writes setting Loom uses
across replicas (`own_write_reads` in `server/core/ch.py`). A replica reads the key
- from the row at each probe (with [part 2](#build-order), before each statement); a
+ from the row at each probe (with [analysis key rotation](#analysis-key-rotation-limits), before each statement); a
rotation's `KILL QUERY` (the order of a write) ends the statements already running. A
row that does not open, or is gone while the analyst user exists, answers
- `ANALYSIS_UNAVAILABLE` and is a `loom doctor` problem. Until [part 2](#build-order)
+ `ANALYSIS_UNAVAILABLE` and is a `loom doctor` problem. Until [analysis key rotation](#analysis-key-rotation-limits)
the recovery is to drop the analyst user and run `loom ch-setup` again; with it, the
recovery is `loom ch-setup --rotate-analysis-key`, which runs from a CLI at least as
new as the stored version, first proves its `LOOM_JWT_SECRET` is the deployment's
@@ -938,7 +448,7 @@ driver's text and the names of policies and databases go to the server log, and
a caller gets names no cause. Unless the stored version is newer than its own, a replica
that writes the entities itself writes them again under the lease after a check failed
with a definite answer that a write repairs: a table without its policy, a canary under
-another key (with [part 2](#build-order), checked again once three settle times have
+another key (with [analysis key rotation](#analysis-key-rotation-limits), checked again once three settle times have
passed since the row's stored time, as `loom doctor` does, since a server still applying
a rotation looks the same), a grant outside the allowlist. Elsewhere `loom doctor` names
`loom ch-setup` as the fix. A policy Loom did not write, which a write cannot remove, is
@@ -997,7 +507,8 @@ Each call writes one `agent_events` row with its row count and latency (identifi
in `server/observability/event_args.py`) and the statement's digest and length. The
`sql` argument joins the ledger's text keys, which record a digest, never the text; a
restricted namespace drops text keys from the ledger, so the op also records the digest
-as `sql_digest`, an identifier key, which the citation check reads. The analyst profile
+as `sql_digest`, an identifier key. Citation verification matches SQL against the
+arguments of a successful request-owned `insights.query` receipt. The analyst profile
holds `log_queries_cut_to_length = 1` and `log_formatted_queries = 0` as `CONST`, so
`system.query_log`, the span log and the server log record each statement the analyst
runs without its text: its user, timing, rows read and settings, the scope and its
@@ -1014,421 +525,116 @@ which ClickHouse's logs keep ([stored data](#stored-data-and-erasure)).
## Isolation proof
-`tests/integration/test_analysis_isolation.py`, in the style of
-`tests/integration/test_cross_principal_leakage.py`, seeds two orgs, each with a
-canary memory and a canary ledger row, and calls `insights.query` with the first org's
-viewer token. Each case must be refused or return no canary:
-
-- a filter on the other org, a namespace outside the token, a `JOIN` or subquery over
- the same table, `UNION ALL`, `view(...)`, `merge(...)`, and a `throwIf` or
- `sleepEachRow` on the other org's rows;
-- `system.query_log`, `system.processes`, `system.row_policies`, `system.users`,
- `information_schema`, `SHOW CREATE TABLE`, `DESCRIBE`, `KILL QUERY … TEST`,
- `loom.signing_keys`, `loom.revoked_tokens` and a column outside the allowlist;
-- `EXPLAIN` in each form, also after a `)` or comment that tries to leave the wrapper,
- `mergeTreeIndex()`, `url()`, `file()`, `s3()`, `remote()`, `cluster()`,
- `executable()`, `input()` and `aiGenerate()` with a named collection;
-- on `loom.memory` itself: a deleted memory, a memory tombstoned by an erasure, and a
- version a later one replaced, with `SETTINGS final = 0` and
- `apply_row_policy_after_final = 0`;
-- `SETTINGS send_logs_level`, `use_query_condition_cache` or `max_threads` past the
- profile, and statements that set `log_queries_cut_to_length` or
- `log_formatted_queries`, whose text stays out of `system.query_log`;
-- `toUInt64(memory_key)` in the select list, `WHERE` and `PREWHERE`, also with
- short-circuit evaluation off, filters moved or merged, and
- `format_display_secrets_in_show_and_select = 1`: each is refused, and its error, in
- the answer and in `system.query_log`, quotes only the caller's own row and no
- spelling of the key;
-- `SETTINGS` that change the scope, the caps, `readonly` or `use_query_cache`, the same
- statement text run first by one org with the query cache and then by the other, a
- scope sent with an expired or forged signature, and a scope one statement read with
- `getSetting` sent with a later one by another org's token;
-- a statement that is not a `SELECT`: `INSERT`, `ALTER`, `CREATE TEMPORARY TABLE`;
-- both orgs' statements running at once;
-- `SETTINGS` that set a scope value to a number, an array or a malformed string: no
- answer quotes the policy or its key;
-- an extra grant (`GRANT SELECT ON loom.* TO loom_analyst`) and a table with its policy
- dropped, each of which the probe turns into `ANALYSIS_UNAVAILABLE` (under the
- configuration Loom ships, a dropped policy reads nothing meanwhile; under the server
- default, the probe closes the window), with and without access management for Loom's
- user; a table taken off the allowlist, which reads nothing whether or not its grant is
- still there;
-- two boots writing at once (a build N-1 beside N with a table taken off the allowlist),
- which the lease serialises, and a build N-1 beside N, which keeps answering on N's
- entities and never writes them;
-- a statement run while a write replaces the policies, which reads the right rows;
-- an extra policy that widens what the analyst reads (`USING 1 TO loom_analyst`), which
- the reserved-scope read catches and no write tries to repair; a build N-1 beside an N
- that added a column and took a table off the allowlist, which keeps answering; and two
- replicas with different cap settings, which write the caps at boot only;
-- a canary under another key, which the probe catches, and a secrets row that does not
- open or is gone while the user is not, which answers `ANALYSIS_UNAVAILABLE`;
-- `--rotate-analysis-key` after a lost row and with `--live` on a healthy one, and, on a
- server whose Loom user cannot list users, the printed SQL run in full on a first
- install, over a lost row and over a healthy row, each followed by a statement that
- answers with the right rows; `--rotate-analysis-key` refused when the CLI's secrets
- are not the deployment's, and plain `loom ch-setup` refused over a lost row;
-- cut short at every step, the rotation, the printed SQL and a first draw from storing
- the row to writing the version, each of which leaves `ANALYSIS_UNAVAILABLE` or a state
- the next run finishes with the stored key;
-- `loom.analysis_secrets` and `loom.analysis_canary` read directly, and neither the
- statement's text nor the key or its pads in `system.query_log` or the server log's
- errors;
-- reseal races:
- - a reseal whose read comes before a printed rotation and whose insert after it, which
- leaves the new key;
- - one whose insert lands between the printed delete and the printed insert, which
- answers the right rows or `ANALYSIS_UNAVAILABLE` (on one server, never an empty
- answer), and then the new key;
-- a rotation on one server:
- - a statement running when it starts, which the `KILL QUERY` ends and which answers
- `ANALYSIS_UNAVAILABLE`;
- - a statement whose key was read before the delete and sent after the password change,
- and one signed from a row a reseal put back, each of which answers
- `ANALYSIS_UNAVAILABLE`;
-- a lagging server, on the settle-time path:
- - an old-credential statement, which reads the rows of the scope it signs until the
- server applies the password change and fails to sign in after;
- - a server that applies access changes within the settle time, which answers no wrong
- row, and one slower than it, where a statement it serves returns no rows or fails to
- sign in and a probe that reaches it answers `ANALYSIS_UNAVAILABLE`;
-- the `clusterAllReplicas` confirmation:
- - a rotation that stores its row only once every server's policy carries the new key;
- - an old-key statement a lagging server started before its policy changed and still
- running then, which the second `KILL QUERY` ends before the row is stored;
- - a server down during the wait, which leaves the row unstored and analysis
- unavailable;
-- `loom doctor` and the probe's repair:
- - within three settle times of the row's stored time, a finished rotation seen through
- a lagging server, for which doctor names a longer settle time and the probe defers
- its canary repair;
- - past that, some probes passing and others failing, which it names as those servers'
- problem, with the servers where the policy read shows them;
- - a rotation stopped after the password change with a row a reseal put back, where
- every probe fails to sign in:
- - stopped before the policies, every server on the row's key: with the policy read,
- on a cluster and on a single server, doctor names `--live`;
- - stopped after them, every server on one other key: it names `--live`;
- - without the policy read: it names both causes;
- - every probe failing with servers on two keys, the row's and another, on any split
- and behind a load balancer that pins every probe to one of them: it names the
- admin's problem with both groups and asks to be run again once they agree;
- - a load balancer that pins every probe to one server, with no policy read, where
- every probe fails, for which it names both causes.
-
-The cases for the key's rotation, the reseal races, lagging servers, `loom doctor`, two
-builds side by side and a Loom user without access management come with part 2 of
-[the build order](#build-order).
-
-The same file shows that a revoked token stops new calls and that an erased memory
-is gone from the next statement. A unit test pins the generated grants and policies to
-the allowlist. The bridge's tests (`tests/unit/test_assistant_bridge.py`,
-`test_delegation.py`, `test_assistant_service.py`, and `test_mcp_unauthenticated.py` for
-the MCP endpoint) show that:
-
-- an answer's token is never wider than the caller's token, never outlives it (under a
- sign-in session, the answer's limit instead), and ends with the caller's token,
- subject, creator or sign-out; a dashboard caller in the last minutes of its access
- token is answered;
-- a request to LibreChat without a token reads nothing, and one with a token reads as
- it;
-- a revoked caller, an answer token or its child, an org-wide token, a narrowed
- `read_scope`, a caller about to expire and an org with model calls switched off are
- refused before LibreChat is called;
-- two replicas booting at once register one service user and keep one key, a service row
- its maker left at any step is finished by the next boot, registration never runs where
- LibreChat would log the password, `loom secrets reseal` rewrites both sealed rows
- while a boot waits for the lease, and a boot whose read of the service row hits a
- lagging replica still sees the row.
-
-Not yet tested: a `sql` citation in a restricted namespace, and one whose tool call
-landed on another replica (the five-second wait is what covers the second).
-
-A probe of this boundary on ClickHouse 26.9, with a scratch table, user and policy of
-this shape, showed each refusal in the table above, the query cache keeping the two
-orgs' results apart, `EXPLAIN PLAN` printing the folded filter
-(`has(['a1'], namespace) AND org = 'acme'`) with no key, and `aiGenerate()` refused for
-want of a `NAMED COLLECTION` grant. On a `ReplacingMergeTree(version)` table with
-`tombstoned_at`, as `loom.memory` is, the live predicate under forced `FINAL` hid a key
-whose latest version was a tombstone and a key an `ALTER … UPDATE tombstoned_at` erased
-on every version, brought back neither's earlier version, and refused
-`SETTINGS apply_row_policy_after_final = 0`. Loom's own user kept ClickHouse's trivial
-count optimization on a table with the `USING 1` policy. With the policy after `FINAL`,
-one org of a thousand in a five-million-row table read 49,152 rows: the policy's `org`
-filter still selects the parts and granules to read. The profile's `CONST` and `MAX`
-pins refused `send_logs_level = 'trace'`, `use_query_condition_cache = 1` and a
-`max_threads` above the cap, and admitted a lower one.
+The operation transport and database analysis-user checks remain the authorization
+boundaries. Native runtime fixtures must cover scope replacement, token revocation,
+model-selected tools outside the roster, forged citations, interrupted streams and
+required private delivery. Mocked tests do not establish a deployed provider or a
+real database boundary; those integration checks require an isolated admitted stack.
+
+## Analysis key rotation limits
+
+The analysis-key rotation described in the analysis sections is a separate design,
+not a capability added by the native model runtime. Existing recovery procedures and
+maintenance limits continue to apply. The native runtime changes no database-user
+provisioning or rotation algorithm and does not establish a rotation integration test.
## Deployment
-LibreChat runs beside Loom with its MongoDB in every deployment shape, reachable only
-from Loom, and both run its v0.8.8 configuration,
-`deploy/librechat/assistant.librechat.yaml`:
-
-- **Compose:** the `assistant` profile starts `librechat` and `librechat-mongo`; neither
- publishes a port. LibreChat shares the internal `assistant` network with the `loom`
- service and the internal `assistant-db` network with MongoDB alone, so the `loom`
- container, which builds repository code, cannot reach the database. LibreChat alone is
- also on `assistant-egress`, a network of its own with a route out, for its model
- provider (with `LOOM_ASSISTANT_PROVIDER=local`, a model server on the Docker host,
- reached as `host.docker.internal`). Its secrets and model key come from `.env` beside
- `compose.yaml` (`LIBRECHAT_CREDS_KEY`, `LIBRECHAT_CREDS_IV`, `LIBRECHAT_JWT_SECRET`,
- `LIBRECHAT_JWT_REFRESH_SECRET`, `LIBRECHAT_ANTHROPIC_API_KEY`,
- `LIBRECHAT_LOCAL_LLM_BASE_URL`, each named apart from
- anything Loom reads, since the `loom` service loads the same `.env`), and its
- configuration from
- `deploy/librechat/assistant.librechat.yaml`, which the release's stack bundle ships.
-- **Helm:** `assistant.enabled` adds LibreChat's Deployment and Service and a MongoDB
- StatefulSet (`templates/assistant.yaml`), with the same configuration in a ConfigMap
- naming the release's Loom Service, and the secrets from `assistant.existingSecret`.
- LibreChat's NetworkPolicy admits only Loom's pods and lets it reach DNS, its MongoDB,
- Loom's pods and TCP 443; MongoDB's admits only LibreChat and reaches nothing, and
- Loom's own policy admits LibreChat when it names its peers. LibreChat runs one pod,
- replaced rather than rolled, and restarts when its configuration changes. Both run
- non-root on a read-only root filesystem; LibreChat writes its logs and uploads to
- `emptyDir` volumes (`scripts/gates/helm_assistant_isolation.py` checks the render).
-- **Settings:** `LOOM_ASSISTANT_LIBRECHAT_URL` names LibreChat's internal address; unset,
- Loom sets up nothing, and the dashboard, which learns it from its boot snippet
- (`window.__LOOM_ASSISTANT`), shows the panel without its chat: the starters still read.
- `LOOM_ASSISTANT_MODEL` and `LOOM_ASSISTANT_PROVIDER` replace the definition's model and
- provider.
-
-Each replica sets the service up in its background at boot. Over a row that has its key
-and agent, a boot asks LibreChat, with the stored key and no sign-in, whether the agent
-is still there (`GET /api/agents/v1/models/`): a key LibreChat no longer knows
-(`401`, its database replaced) makes the key step again, and a missing agent (`404`) the
-agent step, so the next boot repairs either. A failed try is tried again after
-`LOOM_ASSISTANT_SETUP_RETRY_S`, the wait doubling after each next failure up to 16 times
-as long; from the first failed try until one succeeds `/v1/health` shows
-`assistant_service_failing`, with the failure's kind and the text in the log only. Each
-try signs in at most once (twice on the boot that registers the service user), every
-process of a replica counts toward LibreChat's limit of
-seven sign-ins per address in five minutes, and a sign-in refused for that limit is named
-as such. LibreChat's signed-in routes refuse a client that is not a browser (they answer
-status 200 with an `Illegal request` event), so the setup sends a browser user agent,
-and its service user is named `loom-assistant` (LibreChat wants three characters).
-
-LibreChat's configuration keeps the integration's memory off and search index out, and
-gives the agents endpoint no capability but tools (no actions, which call any URL, and
-no code execution, file search, skills, subagents or web search), so the agent's only
-way out is Loom's tools. Its MCP server instructions are off: LibreChat reads them once,
-at its own start and with no answer's token, so the agent's instructions carry the
-rules. Its log level stays at `info`, which writes no message text. The deployment turns
-violation bans off (`BAN_VIOLATIONS=false`) and the unverified-user expiry off
-(`ALLOW_UNVERIFIED_EMAIL_LOGIN=true`, so LibreChat never deletes the service user it
-registered without a mail server), so a burst of replica restarts cannot lock Loom out;
-only Loom reaches LibreChat, so the bans protect nothing there, and registration stays
-on (`ALLOW_REGISTRATION=true`) because only Loom can register. Within Loom, repository
-code runs sandboxed with no route to LibreChat (`--unshare-net`; a job's egress proxy
-reaches public hosts on ports 443 and 22 alone), except an operator repository's build
-on a host without the sandbox, which already runs with Loom's own environment
-([the repository-job sandbox](../operations/code-index-operations.md#repository-job-sandbox)).
-The configuration's agent and remote-agent permissions apply to every LibreChat role, so
-the service user needs no particular one. LibreChat runs without Redis, so one replica
-runs, and its run bookkeeping (each run's agent, model and ids, never the request) stays
-in its own memory. LibreChat's registration logs its request, password included, when
-the email is already in use or the request is malformed; Loom registers only under the
-lease and only after LibreChat said the email does not exist, and the qualification
-searches LibreChat's logs and database for the service user's password as it does for a
-token.
+The assistant runs in the Loom web image. `LOOM_ASSISTANT_ENABLED` enables it, and
+`assistant.nativeEnabled` renders the setting in Helm. Paid answers require an explicit
+native provider and model with a completion price. Provider credentials and gateway
+transport use the existing Loom mechanisms. No additional service, ingress peer,
+container image or database is rendered. See [operator steps](../operations/assistant.md).
## Stored data and erasure
-| Where | What the assistant leaves | How it is deleted |
-| ------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `loom.assistant_service` | one row: the service user's email and agent id, its sealed password and agents API key | holds no memory content (a `NO_MEMORY_CONTENT` entry) |
-| `loom.analysis_secrets` | one row: the analysis key and the analyst's password, sealed | holds no memory content (a `NO_MEMORY_CONTENT` entry) |
-| `loom.analysis_canary` | one constant row in a reserved scope, which the probe reads | holds no memory content (a `NO_MEMORY_CONTENT` entry) |
-| `loom.agent_events` | one row per bridge request and per tool call, under the answer's token | as every ledger row |
-| LibreChat users, API keys, agents, sessions | the service user, its key, the agent definition and the sign-in sessions of each boot that signs in | kept; no memory content |
-| LibreChat `transactions` | token counts per answer and its message id, no content | kept, a few hundred bytes per answer |
-| LibreChat logs | the service user's id and email and request ids, no message text, token or password | LibreChat's default: one file per day, kept 14 days |
-| ClickHouse's `system.query_log`, server log | each analyst statement without its text; a refused one's error, which can quote an allowlisted value | `system.query_log` and `system.text_log`: 30 days on the bundled and dev ClickHouse, no TTL in ClickHouse's default configuration; the file log rotates by size; erasure reaches neither |
-| the dashboard | the person's conversations, in the browser's local storage | 30 days from last use; deleted at sign-out, by another person's sign-in, or by Delete |
-
-An error ClickHouse raises on a statement can quote the value it failed on: a
-`toUInt64(title)` refused on a title quotes the title. That value is one of the caller's
-own allowlisted metadata columns (a key, a title, a user id), never a memory value or
-document text. It is kept in `system.query_log`'s `exception` column and in the server
-log (`system.text_log` included), which records every error whatever `log_queries` says,
-on every install. ClickHouse Cloud pins `log_queries_min_type`, so the error rows cannot
-be left out of `system.query_log` there, and Loom writes one profile for every install.
-Erasure does not reach either log. The bundled ClickHouse and the Helm chart's dev
-ClickHouse keep 30 days of `system.query_log` and `system.text_log`
-(`deploy/clickhouse-config/system_logs.xml`).
-ClickHouse's default configuration sets no TTL on either one, so on a self-managed server
-the rows stay until an operator bounds them
-([log retention](../operations/deployment.md#log-retention)). Both are
-read only by whoever administers ClickHouse and by Loom's own user.
-
-The agents API stores no questions, answers or tool outputs, so LibreChat holds nothing
-an erasure must reach. An answer is computed from the rows the answer's token reads at
-that moment, so an erased memory is absent from every answer that starts after the
-erasure. An answer streaming while an erasure runs can quote a row it read before; it
-goes to its caller only and is stored nowhere, as any read in flight.
+Live answer state consists of request-owned tasks, bounded messages and receipts. It
+is discarded when the request ends. A disconnected request is not resumable. No live
+cancellable state is put in an analytical table. Existing request and cost ledgers,
+audit and exposure records keep their current storage and erasure rules. This change
+adds no content table, identity database or schema migration.
+
+Caller-held dashboard history is still managed by its existing protected session
+rules. External chat archives stay outside Loom; the offline history converter checks
+owner bindings and retains stable conversation, message and parent identities. It
+produces caller-held data for the existing history input, not a second server store.
+Retained provisioning metadata and database volumes are not erased by a code upgrade.
## Model and cost
-The model is the agent definition's: `LOOM_ASSISTANT_MODEL` when set (Loom writes
-it into the definition when it seeds), `claude-haiku-4-5` otherwise. The model runs in
-LibreChat, on its own Anthropic key or on the operator's model server
-(`LOOM_ASSISTANT_PROVIDER=local`), so Loom's provider layer does not call it, but Loom
-holds its spend to the same budget as its own model calls:
-
-- Before calling LibreChat, the bridge checks the namespace's daily model cost cap
- (`server/observability/budget.py`, `daily_cost_cap_usd`, default
- `LOOM_DEFAULT_DAILY_COST_CAP_USD`) through `operation_over_share`, which raises on a
- failed read: an unreadable spend refuses as `BACKEND_UNAVAILABLE` with a one-second
- retry, apart from a spent share (`RATE_LIMITED`). The assistant is held to its own
- share of the cap (`LOOM_ASSISTANT_BUDGET_SHARE`, default half), so questions cannot
- spend what extraction and the conflict resolver need. Both surfaces record their
- spend under one operation, `assistant.ask`, which the share check sums.
-- The check reads spend already recorded, so answers running at once could each pass it;
- each web process runs at most a set number of answers per namespace at once
- (`LOOM_ASSISTANT_CONCURRENT_ANSWERS`, default 2), which bounds the overshoot to that
- many answers per web process: replicas × `LOOM_WEB_WORKERS` × the setting in all. One
- answer's cost is its own usage: a request carries at most 50 turns of history and a
- question, each at most 20,000 characters, and runs for at most
- `LOOM_ASSISTANT_ANSWER_TTL_S`.
-- When the answer ends, the bridge prices the token usage of the agents API's final
- chunk with the model's rate and records it as `upstream_cost_usd` on the answer's
- `agent_events` row, where every model spend is counted. An answer cut before its final
- chunk (a disconnect, the stop button, a timeout), or on a model Loom has no rate for,
- is charged a per-answer ceiling (`LOOM_ASSISTANT_ANSWER_CEILING_USD`, default $0.10)
- instead. `0` charges nothing, which is what the local-model preset sets
- ([a model server on your machine](../getting-started/models-and-keys.md#a-model-server-on-your-machine-no-api-key)).
-
-At the default cap of $1 a day, half of it buys about 15 answers at the mean of $0.033
-per answer that the [qualification](../features/integrations/librechat.md#qualification)
-of the assistant toolset measured on that model, and 11 at its maximum of $0.043; a
-namespace that asks more raises its `daily_cost_cap_usd`. The deployed agent's
-qualification measured a mean of $0.033 and a maximum of $0.048 per answer over its 28
-cases asked of LibreChat directly, and a mean of $0.027 and a maximum of $0.047 asked
-through the chat route ([the deployed assistant](../features/integrations/librechat.md#the-deployed-assistant)).
+OpenAI and Anthropic use the shared guarded HTTP model pool; Bedrock uses a signed
+Converse stream through that pool. The fake route is explicit and offline. Real
+providers need configured credentials and a known price. `assistant_price_model`
+names a price-table reference for an alias; its operator must verify that rate for
+the selected route. Usage records preserve cache reads and both cache-write TTLs;
+reasoning tokens remain unknown when the provider does not report them. No default
+temperature or speculative 400 negotiation is sent.
+
+Bounds cover total time, model steps, tool count, context bytes, tool result size,
+answer size, per-turn output tokens, total tokens and model cost. Each model turn
+reserves an upper estimate before sending. A failed request with incomplete usage
+retains the reservation as an estimate, not fabricated tokens; its ledger arguments
+mark `out_cost_estimated` and `out_model_usage_status`. Reported usage is charged once,
+including failures after usage arrived.
+
+Host context and model-selected tools share the answer's remaining cost allowance.
+The shared model HTTP sender reserves a priced upper bound before every provider
+send, including retries and redirects. Only text inputs use the serialized-byte
+input bound; image, audio, document and provider-owned tool payloads refuse.
+Serialized request bytes bound text input tokens;
+the output cap and largest cache-write rate bound completion cost. Unpriced models,
+unbounded output and protocols without a bounded price refuse before dispatch.
+Prices are specific to embedding or completion protocols and to the provider route;
+a completion rate cannot admit an embedding or a native provider alias. Offline
+fake-model prices cannot authorize an HTTP inference send. Built-in
+LLM reranking uses the completion reservation. External reranking and native
+embedding routes without a configured price contract refuse before sending.
+Authentication token exchange is separate from inference. A swallowed tool refusal
+still refuses the answer.
+
+Tool reservations remain charged to the answer allowance after failure or
+cancellation. Reported charges remain on the tool's own ledger row; sends without
+reported usage leave reservation estimates on the answer ledger, with no invented
+token counts. Known charges are never reported a second time. Reservations are
+conservative and can refuse further work before actual reported spend reaches the
+ceiling. A zero cost ceiling refuses calls.
## Who can use it
-Any token with `viewer` or higher on the namespace, and any person signed in to the
-dashboard with that role. Every tool call checks the answer's token again, and that
-token never reads more than the caller's own.
+Authentication and viewer access to the namespace are required. A model-call switch
+or an unreadable budget refuses further work. The analysis user remains a separate
+read-only database boundary; a model never receives database credentials.
## Rolling upgrades
-`insights.query`, `insights.catalog`, `help.search`, `help.get` and `assistant.ask` are
-ops, and `/v1/assistant/chat/completions` a route, that a build before them does not
-know: it answers `UNKNOWN_OP` or 404, so a client points at them once every replica
-serves them. The agent's tools come from the definition the newest build writes, so
-during an upgrade a help call that reaches an older replica answers `UNKNOWN_OP`, and
-that answer goes without the docs. The analyst user, its grants and policies,
-`loom.analysis_secrets`, `loom.analysis_canary` and `loom.assistant_service` live in
-ClickHouse and are shared by every replica; the agent definition is written as
-[the agent definition](#the-agent-definition) says, never by an older build.
-
-A streamed answer from an older replica sends no `loom.step` events, no `steps` and no
-`loom.text_done`, and its mentor hints no `plane`: the dashboard then shows "Answering…"
-until the text comes, no "What it read" list, keeps Stop until `loom.citations` lands, and
-shows a hint without a page link. An older dashboard or SDK skips `loom.step` and
-`loom.text_done` as events it does not know and ignores the fields. A dashboard tab of the
-older build that shares the browser's stored conversations reads a starter's card-only
-turn as a question with no answer: it shows an empty answer and sends that question as
-history, until the tab is reloaded on the new build. Such a tab also leaves out a turn
-stored while its sources were checked, as any turn still answering, and reads it as
-stopped once it is cut off; shows a turn whose check was cut off (`checkLost`) as done
-with no label; sends a question asked with sources without " Cite your sources." in its
-history and shows no "With sources" tag; and offers no Retry, ignoring a turn's
-`retryable` and a card's `again` mark, so a starter's turn asked again shows its stored
-card there.
-
-An `/assistant` entry an older dashboard pushed opens the assistant over the landing page
-on Back ([rolling upgrades](rolling-upgrades.md), rule 46).
-
-## Build order
-
-1. `insights.query`, `insights.catalog` and the analyst user, written at boot and by
- `loom ch-setup` and probed, with the isolation proof's cases for them, and
- `users_without_row_policies_can_read_rows = false` in the ClickHouse Loom configures:
- `deploy/clickhouse-config/access_control.xml`, mounted by `compose.yaml` and
- `dev/ci_start_clickhouse.sh`, and a key of the chart's development ClickHouse
- ConfigMap with its `volumeMount`. The dropped-policy case reads the setting from the
- server's behaviour and runs on either. Built.
-2. The key's rotation: `loom ch-setup --rotate-analysis-key` and `--live`, the printed
- SQL as a complete rotation, the key read from the row before each statement, the
- probe's deferral within three settle times, the policy read and `loom doctor`'s
- outcomes, and the isolation proof's cases for them, for two builds side by side and
- for a Loom user without access management, with CI running the dropped-policy case
- on a second ClickHouse with the server default.
-3. LibreChat deployed headless, the seeded agent definition, re-qualified with analysis
- and recommendation questions
- ([the deployed assistant](../features/integrations/librechat.md#the-deployed-assistant)).
- Built.
-4. The bridge: the chat route and `assistant.ask`, with the answer's token, the
- refusals, the budget share, the per-process limit, the spend on the answer's ledger
- row, the answer's id on its tool calls' rows, the citation check and the SDKs'
- streaming clients. Built.
-5. The dashboard's Ask AI panel, on the signed-in session and the header's namespace,
- with a Stop button that closes the request, Copy, Ask again and an edit of the last
- question, each answer's checked citations under it, the reasons it cannot answer, the
- conversations kept in the browser, the page's chip on each question and "Ask about
- this" on a memory, a document and a Recall result
- ([Ask AI](../features/dashboard.md#ask-ai)). Built.
-6. Loom's documentation in the image, `help.search` and `help.get` on the toolset
- ([Loom's documentation](#looms-documentation)). Built.
-
-Each part moves its section of this page from design to the description of what is
-built.
+No schema is changed. Historical additive migrations and retained metadata stay
+readable by an older build. Runtime replacement is a capability cutover, not proof
+that old and new assistant implementations can share every deployment setting.
+Keep the assistant disabled during a mixed serving fleet until its native path is
+verified. Keep mirrored-source creation unavailable until all serving builds and
+consumers enforce its publication boundaries. Do not restart a retired runtime to
+roll back: its durable queues may execute work. The [cutover procedure](../operations/assistant.md#retention-and-cutover)
+requires an approved maintenance window and a separately reviewed rollback plan.
## Source entry points
-- `server/operations/toolsets.py` (`MCP_ASSISTANT_OPS`, `ASSISTANT_FORCED_ARGS`): the
- assistant toolset the agent's tools come from.
-- `server/core/ch.py` (`caller_shaped`, `_reader_auth`): how a read runs as another
- ClickHouse user under caps.
-- `server/cli/ch_setup.py`: provisioning of the reader user, which the analyst user
- follows.
-- `server/auth/delegation.py` (`delegate`): how an answer's token is derived from the
- caller's and inherits its revocation.
-- `server/observability/budget.py`: the namespace cost cap the assistant's spend counts
- toward.
-- `server/assistant/app/citations.py` (`verify`) and `server/assistant/app/support.py`
- (`answer_support`, `streamed_calls`), with the rule in
- `server/assistant/domain/support.py`: an answer's checked citations and its support.
-- `server/assistant/app/bridge.py` (`stream`) and `server/assistant/domain/steps.py`: a
- streamed answer's steps.
-- `server/assistant/app/service.py`: the service user and agent set up at boot;
- `server/assistant/store/service.py`: `loom.assistant_service`.
-- `integrations/librechat/`: the agent definition (`agent.yaml`) and the qualification
- harness.
-- `server/help/`: `help.search` and `help.get`, and the index over the shipped docs.
-- `deploy/librechat/assistant.librechat.yaml`: the deployed LibreChat's configuration.
+- `server/assistant/app/runtime.py`: admission, mirror marking and publication.
+- `server/assistant/app/agent.py`: bounded host and model orchestration.
+- `server/assistant/app/tools.py`: registry schemas and authenticated MCP dispatch.
+- `server/assistant/app/evidence.py`: citation receipts.
+- `server/llm/agent.py`, `agent_http.py`, `agent_bedrock.py`: streaming model protocol.
+- `server/assistant/app/routes.py`, `ask.py`: chat and op surfaces.
## Invariants
-- The analysis boundary is ClickHouse's: grants, the settings profile and signed row
- policies.
-- Every tool call the agent makes reads under a token delegated from the caller's, never
- wider than it, never longer-lived except under a sign-in session, and then by at most
- `LOOM_ASSISTANT_ANSWER_TTL_S`, and revoked with it, and is ledgered as consumer
- `loom-assistant`.
-- LibreChat stores no Loom token: each answer carries its own, and the service user's
- key reads nothing without one.
-- LibreChat stores no question, answer or tool output.
-- The assistant writes no memory, document or grant.
-- The assistant never calls itself: calls between Loom and LibreChat go one way per hop,
- and only the assistant's two entry points (the `assistant.ask` op and
- `POST /v1/assistant/chat/completions`) ask LibreChat for an answer; boot setup
- (`server/assistant/app/service.py`) only registers the service user, its key and the
- agent. Both entry points refuse an answer's own token (consumer `loom-assistant`) and
- any token delegated from one with `ASSISTANT_SELF_CALL` (403), ledgered as a refused
- answer, on every transport and toolset: an answer token's id starts with
- `assistant-answer-`, so a descendant is told by its parents. No model endpoint Loom
- serves for LibreChat's model calls may be an assistant op or call the assistant.
-- The headless LibreChat's configuration keeps LibreChat's own memory off
- (`memory: disabled: true` in `deploy/librechat/assistant.librechat.yaml` and the Helm
- copy), so what a person tells the assistant is not kept a second time outside Loom.
+Each tool authorizes the asker's subject and fixed scope. A result cannot grant access.
+Each answer has one run, finite work and one model usage capture per sent turn. Required
+private delivery and source checks precede completion. No background model job or
+resume queue is created. No operator data is deleted as part of runtime replacement.
## Related
-- [The assistant toolset](../reference/mcp.md#the-assistant-toolset)
-- [LibreChat integration](../features/integrations/librechat.md)
-- [Security](security.md)
+- [Storage authority](storage-authority.md)
- [Rolling upgrades](rolling-upgrades.md)
+- [LLM architecture](llm-architecture.md)
+- [Assistant setup](../operations/assistant.md)
diff --git a/docs/architecture/clickhouse.md b/docs/architecture/clickhouse.md
index bdc988ab57f..bdf2604ce2e 100644
--- a/docs/architecture/clickhouse.md
+++ b/docs/architecture/clickhouse.md
@@ -473,6 +473,7 @@ read it; the erasure saga deletes from it. A new `memory` column goes into
| `memory_exposure_breadth_hourly_refresh` | `REFRESH EVERY 1 MINUTE APPEND` | `memory_exposures` → `memory_exposure_breadth_hourly` |
| `subject_last_seen_refresh` | `REFRESH EVERY 1 MINUTE APPEND` | `agent_events` → `subject_last_seen` |
| `loom_telemetry.sli_minute_refresh` | `REFRESH EVERY 1 MINUTE APPEND` | `agent_events` → `loom_telemetry.sli_minute` |
+| `code_term_df_refresh` | `REFRESH AFTER 1 HOUR` | `code_term_freq`, `code_doc_stats` → `code_term_df` |
**Insert-time or refreshable.** An insert-time view writes one part per source insert. That
suits a low-rate source or a target read back in the same request (`memory_versions`). A
@@ -482,6 +483,18 @@ keep their mark in a sentinel row (`org = ''`, `namespace = ''`, `term = ''`) ca
minute, and `memory.search` merges the newer source rows (`LOOM_MEMORY_SEARCH_BM25_LIVE_TAIL`,
on), so BM25 scores are exact.
+**The code term snapshot.** `code_term_df_refresh` replaces `code_term_df` whole, so it is
+the one refresh whose cost follows the size of the index, not the rows written since
+the last pass. The snapshot holds one row with `org = ''` and `namespace = ''` whose `term`
+is a hash of the active parts (name and row count) of `code_term_freq` and
+`code_doc_stats` at the refresh that computed it, read from part metadata. Every insert,
+merge, mutation and delete gives a part a name not used before, so a refresh that finds
+the same hash writes the stored rows back and merges no `uniqExact` state; any other
+refresh rebuilds the table. On an index of 620,000 chunks a rebuild reads 719 MiB of
+states and the unchanged pass reads the snapshot's 62 MiB. The hour counts from the end
+of a refresh: a document frequency is at most one hour and one refresh old, and a refresh
+that outlasts the hour is followed by an hour without one.
+
**The events stream.** `loom.events` carries budget violations only:
`server/observability/events_stream.py` queues them and writes one committed insert per
flush. Every other telemetry writer (audit rows, exposures, search traces, query nodes,
diff --git a/docs/architecture/code-index-architecture.md b/docs/architecture/code-index-architecture.md
index 190f4d643dc..15acf9312f7 100644
--- a/docs/architecture/code-index-architecture.md
+++ b/docs/architecture/code-index-architecture.md
@@ -190,7 +190,9 @@ flowchart LR
2. **Re-indexes exactly the changed files** of each commit (`ingest_file` in
`code/app/index/ingest.py`): parse, chunk, symbols, edges, call guards, the file
row, and a context pack and review brief for the merged PR the commit names. Then it
- advances `git_head`. A crash re-runs from the last complete commit.
+ advances `git_head`. A crash re-runs from the last complete commit. Across entries
+ the pass takes one commit per entry per round, so a long backlog never holds another
+ entry's new commits; a round the budget ends resumes next pass at the entry (org and namespace) it missed.
3. **Walks** with the share `LOOM_CODE_INGEST_WALK_BUDGET_SHARE` leaves: reconciliation
heals and extractor re-chunks (below).
@@ -209,6 +211,13 @@ Lanes help because a lane waits on ClickHouse round trips, not CPU.
(`code/app/index/denylist.py`, `LOOM_CODE_INGEST_EXCLUDE`,
`LOOM_CODE_INGEST_IGNORE_FILE`), is binary, or exceeds `LOOM_CODE_INGEST_MAX_FILE_BYTES`.
So `coverage_floor: true` on a grep means every admitted chunk, not every byte.
+A path the entry's `embed_exclude` globs name (`LOOM_CODE_EMBED_EXCLUDE` for the scalar
+entry) is admitted, chunked and mapped, but its chunks are neither described nor embedded:
+they carry the `unembedded by design` marker, which every writer of a vector or a
+description honours and the coverage counts skip, the `code_summary` pass writes no card
+for them, and code.search reaches them through the lexical leg only. A changed glob
+applies to chunks written after it, in both directions (the operations guide's
+`embed_exclude` notes name the repair).
### Choosing a parser
@@ -247,6 +256,8 @@ Tree-sitter modules import lazily, so a server with the code workers off boots w
| `file_header` | Leading comments and includes. |
| `other` | The rest, grouped. |
+Python search responses omit a prefixed class docstring when the skeleton already contains its text.
+
Files without a tree fall back to whole-line windows; lanes without a grammar cut on
their symbol spans (`lane_units.span_chunks`). A chunk id is
`uuid5("loom://code/{namespace}/{path}#{scope}@{sha16}")`. It is content-addressed, so
@@ -378,17 +389,33 @@ locations to `code.enclosing` with `include_body=true`. It returns complete
enclosing definitions together. `code.symbol` resolves a named definition or
one location; the batch avoids a separate lookup for every located definition.
+`code.read` reads several known line ranges in one request. It uses a local
+Git mirror and checks the blob's hash against each indexed file record.
+Only files indexed for text search qualify. Projected notebook cells and
+reference fixtures with omitted text are unavailable. The response gives
+inclusive line numbers for each window and marks unavailable ranges, including
+ranges that exceed the request’s source byte limit.
+
+Python SCIP identities use the same placeholder for callables of every
+arity. Definition and enclosing-body responses recover the parameter list
+from a retained declaration with the matching name. Metadata-only responses
+leave the signature empty when the index provides only the placeholder.
+The stored identity and call edges keep their existing keys.
+
Search and grep rank candidate lessons across all selected files by query-term
overlap after constraints and pinned rows. English inflections share stems; equal
matches keep path order, then the listing's confidence and recency order.
The remaining file-lesson reads retain path and listing order.
-The ranking uses the existing namespace-scoped candidates. On trunk, an uncapped
-grep response focuses a file's lessons on matched definitions when the returned
-scopes are known and an exact linked lesson is available. Broader file history
-remains available through `memory.for_file`. Superseded rows and unrelated paths
-remain excluded. Before leaving out a lesson, grep checks its live link set
-for pending and uncertain links within the existing enrichment deadline.
-Ranking and focusing add no model calls.
+The ranking uses the existing namespace-scoped candidates. On trunk, uncapped
+grep responses focus lessons on the definitions their matches name. Search
+focuses a file's lessons when a returned definition has an exact linked lesson.
+Whole-file search hits use file-level selection. Grep omits a candidate by scope
+only if its link was checked at the same revision as the matched chunks. Matches
+outside a named definition also keep candidates with overlapping or unverified
+link ranges. Read the broader file history with `memory.for_file`. Before
+omitting a lesson by scope, the enrichment checks its live link set for pending
+and uncertain links within the request's enrichment deadline. Ranking and
+focusing add no model calls.
File and symbol lessons carry complete memory text, including source references.
The internal file listing reads complete values; the pre-edit block keeps its own
@@ -471,8 +498,10 @@ reports the count.
## Watermarks and coverage
`code_index_state` (`ReplacingMergeTree(version)`, keyed `(org, namespace, state_key)`)
-holds `git_head`, the per-producer SCIP watermarks, the extractor stamps, cursors and
-`dependents_pending`. The `as_of` block on every answer and
+holds `git_head`, the per-producer SCIP watermarks, the extractor stamps, cursors,
+`dependents_pending` and `history_until`, where `git_head` sits in the merged-PR
+ledger's clock ([the bound](../features/code-index/history-and-prs.md#history-stays-inside-the-indexed-head)).
+The `as_of` block on every answer and
`loom.code.tier_lag_seconds{tier}` are computed from these rows and the mirror, not from
a producer's log. Per-commit coverage (`code/app/index/commit_coverage.py`) is one
`git merge-base --is-ancestor` per tier on the mirror, never a watermark comparison.
@@ -533,6 +562,7 @@ after one on N. Other processes keep the rows they read for up to
| `code_edges` | RMT(`version`), `(org, namespace, tier, to_symbol_id, edge_kind, from_symbol_id, path, line)` | Callers are a key range; projections `by_from` (callees) and `by_path`. |
| `code_call_sites_unresolved`, `code_caller_guards` | RMT(`version`) | Declined call sites by callee name; guards around each caller's call sites. |
| `code_term_freq`, `code_doc_stats` | AMT, RMT; filled by `code_term_freq_mv`, `code_doc_stats_mv` | BM25 statistics for the lexical leg. |
+| `code_term_df` | MT, `(org, namespace, term)`; replaced whole by `code_term_df_refresh` | The same statistics as plain numbers; rebuilt within an hour of a change to those tables. |
| `code_unit_signal` | `SummingMergeTree((positive, negative))` | Outcome counters per unit from `code.outcome`. |
| `code_search_trace`, `code_search_outcome`, `code_search_memo` | MT with 180-day TTL; RMT with 60-minute TTL | Per-query traces and outcomes; a short-lived memo of served `code.search` responses. |
@@ -542,11 +572,13 @@ Every column is in the generated [schema reference](../reference/schema.md).
A file-qualified symbol request (`src/module.py:Type.method` or
`src/Type.cpp:Namespace::Type::method`) keeps the filename as a hard constraint.
-Candidate discovery reads that file's symbol rows; the authoritative live read
-checks the filename again before ranking and limiting. It never retries the name
-against other files. `resolved_by: file_symbol` discloses the binding; stored
-symbol names and ids stay intact. The shared resolver applies this spelling to
-structural code operations.
+The exact indexed path takes precedence even when it lacks the requested symbol.
+If it is absent, an unanchored relative path with two or more components can match
+the complete suffix of one live indexed file in the namespace. A `./` or absolute
+path keeps the lookup exact. Both symbol reads use the selected path before ranking
+and limiting. The response includes `resolved_by: file_symbol`, the canonical
+indexed path, and the stored symbol name and id. The shared resolver applies this
+spelling to structural code operations.
Python import spellings use the bounded short-name candidate read after an exact
symbol miss. Read-side matching preserves dotted module scopes and treats a package's
@@ -560,19 +592,85 @@ in `pkg/json/__init__.py`; its stored qualified name remains intact. Constructor
names remain explicit, and ambiguous matches stay unlinked unless the memory's
file scope selects one definition.
-| Op | Path | How |
-| -------------------------------- | ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `code.search` | `code/app/search/pipeline.py` | Routes first (pattern, path, history question), then runs legs under the deadline (`gather.py`): lexical (idf-weighted token count), vector (a scan with no vector index, or twin shortlist), PR history, fuzzy symbol vote. `fusion.py` fuses by reciprocal rank (k = 60); `serve.py` pages into the token budget or abstains. A repeat within the memo window is one read of `code_search_memo`. |
-| `code.grep` | `code/store/index/grep.py` | The 3-gram index narrows granules; `position()` or `match()` decides; each hit joins its enclosing unit. `mode=presence` spans up to eight branch namespaces. |
-| `code.symbol` | `code/app/symbol/` | A qualified name is a key-prefix read of `code_symbols`; a short name goes through `code_symbol_names`; several definitions rank by `near_paths` or the PR under review. |
-| `code.callers`, `code.impact` | `code/store/index/edges.py` | Callers are the `to_symbol_id` range of `code_edges`, compiler rows preferred, with the unresolved count. `code.impact` maps diff hunks to seed symbols and walks outward; an empty walk answers `no_indexed_paths`, `no_seeds_in_hunks` or `no_static_callers`. |
-| `code.outline`, `code.enclosing` | — | Per-path reads of `code_symbols` and `code_chunks` spans. |
+| Op | Path | How |
+| -------------------------------- | ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `code.search` | `code/app/search/pipeline.py` | Routes first (pattern, path, history question), then runs legs under the deadline (`gather.py`): lexical (idf-weighted token count), vector (a scan with no vector index, or twin shortlist), PR history, the definitions the query names (`definitions.py`: the functions of the innermost two frames inside the repository of a pasted Python traceback, read by file and name, then the first name the rest of the query spells out as code, three definitions in all; a traceback whose frames name nothing in the index adds no name of its own), fuzzy symbol vote. `fusion.py` fuses by reciprocal rank (k = 60); `rank.py` applies the priors and then serves the named definitions directly after the first unit, at its score; `serve.py` pages into the token budget or abstains. A repeat within the memo window is one read of `code_search_memo`. |
+| `code.grep` | `code/store/index/grep.py` | The 3-gram index narrows granules; `position()` or `match()` decides; each hit joins its enclosing unit. `mode=presence` spans up to eight branch namespaces. |
+| `code.symbol` | `code/app/symbol/` | A qualified name is a key-prefix read of `code_symbols`; a short name goes through `code_symbol_names`; several definitions rank by `near_paths` or the PR under review. |
+| `code.callers`, `code.impact` | `code/store/index/edges.py` | Callers are the `to_symbol_id` range of `code_edges`, compiler rows preferred, with the unresolved count. `code.impact` maps diff hunks to seed symbols and walks outward; an empty walk answers `no_indexed_paths`, `no_seeds_in_hunks` or `no_static_callers`. |
+| `code.outline`, `code.enclosing` | — | Per-path reads of `code_symbols` and `code_chunks` spans. |
+| `code.trace` | `code/app/symbol/trace.py` | Reads the frames of the text: qualified `a::b` names, C/C++ `dir/file.cpp:N` locations, and Python frames in the interpreter, notebook and test-runner forms, which `frames` returns as `path:line in function`. A name resolves through the symbol table and a location to the innermost symbol that holds its line. A Python frame resolves to the definition of its function in the file under the longest tail of its printed path, as written or under `src/` or `lib/`; its line chooses only among several definitions of the name. Over `max_frames` a native backtrace keeps its first frames and a Python traceback its last. |
The lexical text-index gate tokenizes the query with `splitByNonAlpha`, matching the
index tokenizer. The score counts only whole app lexemes and rejects partial matches
from the gate. Underscore-only lexemes use the exact score within the same tenant,
model and path scope because the text index has no token for them.
+ClickHouse returns rows that are equal in a sort in the order it read them, which
+changes with the parts of the table and the threads of the read. So that the same
+request gets the same answer, every ranked read of the search ends its order in keys
+that identify the row:
+
+- **Chunks:** the path, the start line and the chunk id, so the earlier lines of a file
+ come first. The lexical leg, the definition leg, the chunks a history or card vote
+ brings, the exact rescore of a shortlist and `track_path` close their order this way.
+- **Pull requests:** the newer merge, then the higher number.
+- **Symbols:** the path, the start line and the symbol id after the ranking keys.
+- **The vector leg and the card leg:** the statement sorts on the distance alone, the
+ one sort the codes-first read takes, and the rows it returns are put in the chunk
+ order (the path, for a card) afterwards. Chunks with one text have one vector, so
+ equal distances are common. Which of the rows at the read's last distance come back
+ is still ClickHouse's choice, as is the shortlist the codes-first read rescores.
+
+Fusion and the stages after it sort stably, so they keep the legs' order among equal
+scores.
+
+`retrieval_confidence` says whether the index holds an answer at all. It is the vector
+leg's best cosine, read on the embedder's calibrated scale before any prior reorders
+the rows (`code/domain/index/search_confidence.py`, `code/app/search/calibrate.py`):
+
+- **The scale.** 0 at the midpoint between the abstain threshold and the cosine of a
+ confident hit (`rerank_skip_above` in the namespace's calibration, else in the
+ embedder's boot calibration, else `LOOM_LLM_RERANK_SKIP_ABOVE`), 1 at that cosine.
+ An absolute cosine is not comparable across embedding models: one scores unrelated
+ text 0.2, another 0.7. The boot calibration's probes are prose, so a namespace
+ `code.calibrate` has not seeded reads its code on a prose scale: where the model
+ scores a right code hit lower than a right prose answer, an answerable search reads
+ `medium` or `high`
+ ([seed each code namespace](../operations/code-index-operations.md#first-index)).
+- **What it separates.** A question the index can answer usually scores near 1, and
+ one about another repository or another subject usually scores lower. It is a
+ tendency, not a rule: measured on issue prompts with one embedding model, the median
+ prompt sent to another repository's index scored 0.30 and about one in five still
+ read `low`.
+- **What it does not separate.** Among questions the index can answer, a result that
+ holds the file to change and one that does not score alike. A high confidence is
+ not evidence that the first result is the right one.
+- **No cosine.** A search with no vector leg (no embedder, a lexical-only request, a
+ failed leg), or one whose vector leg returned no row, reads 0.5, which never bands
+ `low`.
+- **No scale.** A confident-hit cosine that is not above the abstain threshold leaves
+ no range to read a cosine on: a calibration whose question-to-answer cosines fall
+ into its distractor range, or, with no calibration,
+ `LOOM_MEMORY_SEARCH_ABSTAIN_THRESHOLD` set at or over `LOOM_LLM_RERANK_SKIP_ABOVE`.
+ The search reads 0.5 then too, and `calibration_explanation` says so.
+- **No results.** An abstain that returns no result reads 0.0.
+- **A second vector model.** The scale is the served embedder's. A request's
+ `vector_model` with no shortlist ranks on its own cosines, which are read on that
+ scale all the same, as its abstention is.
+- **No vector leg to read.** An exact symbol match reads a fixed 0.95 and the history
+ route 0.5.
+- **Not abstention.** Abstention is decided apart from the confidence, on the fused
+ list: its top cosine under the abstain threshold (`below_threshold`), or a
+ route-aware score (that cosine, its margin over the second hit, route agreement and
+ the pool size) under `LOOM_CODE_SEARCH_ABSTAIN_CONFIDENCE_BELOW`
+ (`low_calibrated_confidence`).
+
+`retrieval_risk` bands the confidence of a result the search does not abstain on:
+`high` below `LOOM_CODE_SEARCH_MEDIUM_RISK_FROM` (0.35), `medium` from it, `low` from
+`LOOM_CODE_SEARCH_LOW_RISK_FROM` (0.70). It reads `abstain` when the search abstains.
+`route_agreement` is reported beside the confidence and is not part of it.
+
After relevance ranking, per-file saturation spreads broad search results across
files. It is skipped for an explicit path, a symbol route, test intent, or a
code-shaped identifier named in the query that matches a qualified symbol
@@ -581,6 +679,149 @@ questions about a named identifier. An unmatched identifier does not disable
saturation. Per-symbol deduplication still removes repeated chunks of one definition,
and continuation pages retain the final served order.
+A reranker (`rerank` in the request, or `LOOM_CODE_SEARCH_RERANK_DEFAULT`) orders the
+units it reads and leaves their scores as they were, so the scores of a reranked page
+do not descend. The reply serves those units in the reranker's order, apart from the
+named definitions:
+
+- **The personal tie-break** runs before the reranker, on the fused order, and stands
+ only for the units the reranker did not order. A swap it made on a reranked page
+ reads `user_tiebreak=before_rerank` in `score_explanation`.
+- **Named definitions** are served directly after the reranker's first unit, as they
+ are after the first unit without a reranker, whether or not the reranker read them.
+- **Per-file saturation** spreads only the units after the last one the reranker
+ ordered, and counts the files of the units before them. `score_explanation` then
+ reads `saturation=(below_reranked)`, or `saturation=skipped(reranked)` when no
+ unit is after it.
+
+History anchors and `sort_by: "fan_in"` apply after the reranker, as they do after
+every relevance stage, and saturation leaves every unit up to the last one the
+reranker ordered where they put it.
+
+`rerank: "builtin:pick"` is the listwise pick, a reranker for a query that reads as a
+bug report: twelve words or more, or the vocabulary of a failure. One call of the
+deployment's pick model reads the report, cut at 4,000 characters, against one line for
+each of the first 100 distinct units of the ranking (`path:lines symbol — declaration`,
+no body), and answers with at most 8 of them, the most likely to change first, and one
+word for how sure it is:
+
+- **The picks are served first**, in the model's order. The named definitions are
+ placed before the call, so the model reads them as candidates, and the picks go ahead
+ of them. Saturation spreads the units after the last pick.
+- **`pick_confidence`** in the reply is the model's word: `high` when it is confident
+ its first pick is a definition the fix changes, `medium` when one of its picks
+ probably is, `low` when probably none is. A caller that sends the results on only
+ when the word is `high` sends fewer lists and fewer wrong ones. The word is of the
+ ranking the pick handed on, its first pick first: a reply whose first result is
+ another unit (a history anchor, or a request's `exclude_unit_ids`, `min_fan_in` or
+ `sort_by: "fan_in"`) carries none, with or without a pick, and neither does a later
+ page of a cursor.
+- **It is off unless the deployment names a model.** `LOOM_CODE_SEARCH_PICK_MODEL` is
+ empty by default, and the request then gets the ranking as it is, as does a query
+ that does not read as a bug report and an LLM-free read. The deployment's default
+ reranker never names the pick, and a search of several namespaces makes no pick call:
+ each namespace is searched as with `rerank: "none"`.
+- **A failed call keeps the ranking.** `retrieval_work.pick_failed` is `1` when the call
+ failed or its reply was not the object asked for, and that answer is not memoized. A
+ reply whose word has no candidate to be about is such a reply: `high` when its first
+ number is not on the list, `high` or `medium` when none of its numbers is.
+- **It costs a model call**: about 7,000 input and 250 output tokens for 100 lines, and
+ two to three seconds on a provider's smallest model. Under `deadline_ms` it is skipped
+ when less than 2.5 seconds are left, the floor of the search's other model calls, and
+ cut at the deadline otherwise. A namespace over its LLM cost cap makes no pick call
+ and gets the answer of `rerank: "none"`. A cursor whose stored ranking is gone is
+ searched again, with a second pick call.
+
+The pick was measured on bug reports of public repositories that a model may know.
+About three quarters of its gain was on reports where the model could name the changed
+function with no index at all, so the gain on private code is unconfirmed.
+
+For a question about the implementation, ranking multiplies the score of a test,
+example, fuzzer or benchmark path by 0.35 and the score of a prose file by
+`LOOM_CODE_SEARCH_PROSE_PENALTY`: such a file is ranked lower, never dropped. The prose
+penalty is off for a search constrained to paths and for a symbol lookup.
+
+A question asks for tests when it holds a test word (`test`, `pytest`, `fixture`,
+`ci`), and for documentation when it holds a documentation word (`docs`, `changelog`,
+`tutorial`). Test intent turns off the test-path penalty, the fan-in prior, the kind
+prior and per-file saturation, and lets the definition leg return a definition on a
+test path; documentation intent turns off the prose penalty. A
+question with more lexemes than `LOOM_CODE_SEARCH_QUERY_MAX_TOKENS` is an issue body,
+where such a word names where a fault showed: a traceback path, a version listing, a
+link. Only its first 16 lexemes are read for intent, which hold the title of a report
+or the request a long prompt opens with. They are counted in the question as sent, so a
+template's headings before the title are among them. A long prompt that states its
+request after that opening is ranked as a report.
+
+Under the `functions_first` kind prior (`LOOM_CODE_SEARCH_KIND_PRIOR`, or `kind_prior`
+on a request) a question that long is ranked functions first: the fix of a report most
+often edits a function, and a class skeleton or a module-level chunk that repeats the
+report's words otherwise outscores it by more than a bounded factor takes back. Only
+the length is read, so a design question or a task prompt past the cap is ranked the
+same way. The default stays `flat`, which ranks every question by its bounded table:
+functions first gains places on the first page for a changed function and gives up
+reach for a changed class or module-level chunk (see Cost).
+
+- **Order.** Every unit takes the table's score; the factors are those of `flat`. The
+ other kinds of a file that holds function chunks (its class skeletons, module-level
+ chunks, comment blocks and header) are then moved behind the functions among the
+ first 25 units: one factor puts the best of them level with the lowest of those
+ functions, never above it. They follow those functions and are served among the
+ functions that score below. When the first 25 units hold no function, nothing is
+ moved: a first page without one says the answer is not a function. 25 is the largest
+ page a request can ask for, so the anchor is the same for every `top_k`.
+ `score_explanation` reads `kind_prior=functions_first:moved` when a unit was moved,
+ and `kind_prior=functions_first` when none was. Three later stages read those
+ scores:
+ - The outcome signal. A function it scales down is served after the moved units it
+ then scores below. A moved unit that it scales up, by at most 35%, is served ahead
+ of the functions it then outscores, the last ones of those 25 units.
+ - The personal tie-break. It serves the best moved unit ahead of the function it is
+ level with when, of the two, only that unit is in a directory of the caller's
+ recent work.
+ - Per-file saturation, which sorts by score. It keeps a file's best function ahead
+ of the moved units; a file's later function that the decay takes below their score
+ is served after them. A moved unit that follows a function of its own file takes
+ the decay too.
+- **These files keep the table's order.** SQL, a config file (YAML, JSON, TOML, XML,
+ INI), a document (Markdown, reStructuredText, MDX, HTML), a style sheet, a Prisma
+ schema, a FlatBuffers schema, an Angular component template, a file of Terraform
+ values (`.tfvars`), a file with no extension, and a language with no parser (Kotlin,
+ Swift, C#, Ruby, PHP). A unit of such a file has no function of its own file to
+ follow, so it stays where the table scores it, among the functions. A namespace
+ whose main language has no parser is therefore ranked as for a shorter question. A
+ CMake file is among them as a config file, although its functions and macros are
+ function chunks: its target outlines are not moved. The path's extension is all that
+ is read.
+- **Named definitions keep their places.** A class the report names is what it asks
+ about: its skeleton is served directly after the first unit, as on every page.
+- **A kind word or the name of a file does not change it.** In a pasted report they
+ say where the fault showed, so they neither skip the prior nor boost a kind.
+- **Unchanged.** These are not ranked functions first:
+ - a long question whose opening asks for tests, which skips the prior, or for
+ documentation, which keeps the bounded table. Under that table a kind word boosts
+ its kind only when the opening holds it;
+ - a search with a reranker to call, which orders the first units itself, the
+ skeletons among them. The listwise pick is one where it has a call to make: it
+ reads the bounded order. The path of a shorter question stays when that call is
+ then skipped under a request budget, cut at the deadline or fails open;
+ - every question under `flat`, `default` or `structural`, where the name of a file
+ skips the prior and a kind word boosts its kind wherever the question holds it.
+- **Cost.** A changed class skeleton or module-level chunk of a file that holds
+ function chunks, when it scores among the first 25 units, is served after the
+ functions among them, unless a definition place holds it. It can leave the first
+ page for a later one, which the `cursor` of a continuation serves up to the 100th
+ unit, or leave those 100 units. A unit that keeps the table's order and scored
+ between the best moved unit and the lowest of those functions is served ahead of
+ the moved units it scored below: a config or document window can pass a class
+ skeleton that outscored it. The definition places hold at most three chunks: the
+ frames of a pasted traceback first, then the first name spelled as code outside it
+ that has a definition. A module-level chunk has no name to spell. Another table
+ serves such a unit where the fusion scored it. Through MCP, whose compact tool
+ schema omits `kind_prior`, a deployment set to `functions_first` serves it at that
+ place for a shorter question; the `cursor` of a continuation reaches it at its
+ moved place on a later page.
+
### Symbol bodies
Literal hits, rendered-message matches and symbol mentions use the same retained-source
diff --git a/docs/architecture/cost-budgets.md b/docs/architecture/cost-budgets.md
index 932ba3cd204..54d008015dc 100644
--- a/docs/architecture/cost-budgets.md
+++ b/docs/architecture/cost-budgets.md
@@ -7,8 +7,10 @@ namespace ceiling. Admission refuses paid synthesis when either is reached, and
routing uses the larger spend fraction. `memory.ask`, including its whole-document
route, `code.ask`, `knowledge.synthesize` and `code.search` query expansion supply the
logical user recorded in the ledger. Namespace-wide workers keep their namespace accounting;
-a token subject is never substituted for an unattributed user. These soft controls do
-not reserve spend or establish a billing identity.
+a token subject is never substituted for an unattributed user. The extraction queue
+is the exception: a replay's row carries the user the deferred request named, so its
+spend counts toward that user's cap and can refuse that user's paid synthesis. These
+soft controls do not reserve spend or establish a billing identity.
`cost.budget_status` shares the policy and spend read with the guards. User mode requires
a namespace and reports the user's cap and verdict, plus `namespace_over_cap`. Exact
diff --git a/docs/architecture/document-sources.md b/docs/architecture/document-sources.md
index 717e95a5359..cac5bb4b72d 100644
--- a/docs/architecture/document-sources.md
+++ b/docs/architecture/document-sources.md
@@ -623,15 +623,11 @@ the public fallback. No reranking provider receives the provisional pools.
consumer total.
- **Private events have separate physical storage.** Ordinary events stay in
`agent_events`; marked requests and mirror workers write `agent_events_private`.
- The ordinary table's CHECK excludes marked rows and mirror namespaces. An analyst
- keeps ordinary signed, namespace-scoped reads and cannot read the private table or
- its physical metadata. Provisioning verifies the CHECK on every writer, drains
- the finite set of prepared INSERTs and refuses any existing private contamination
- before granting access. Checked per-writer HTTP sessions read the native access
- catalog and prove that policies cannot hide the process or event populations.
- Unknown visibility, writer routes or metadata refuse. It preserves existing rows
- for operator resolution. Administrative application uses
- `loom ch-setup --apply-analyst-sql`; unchecked analyst SQL files refuse.
+ The ordinary table's CHECK excludes marked rows and mirror namespaces. Analysts
+ read ordinary events through a signed, namespace-scoped view. Their grants cover
+ neither physical event table, so its storage metadata is also private.
+ `loom ch-setup --apply-analyst-sql` verifies the native policy definitions in
+ Loom's database before granting access to the views.
- **Private event reads are folded and masked.** The analytics export and
`sql_v1_usage_daily` union both stores and fold marked spend into a namespace/day row
with agent and operation `-`. `sql_v1_agent_events` and the signed
@@ -681,7 +677,7 @@ keep the accounting-before-publication boundary above. The answer token's distin
`answer_mirrors` bit fixes mirror admission before model work, so a source activated
during a negative answer cannot introduce an unmarked tool leg. Missing admission is
false; ordinary delegation drops it. See the
-[assistant boundary](assistant.md#the-bridge-each-callers-own-identity).
+[assistant boundary](assistant.md#each-callers-own-identity).
A multi-entry MCP batch refuses every response-bearing marked entry with the same
instruction to send it individually, including denied and empty entries. Notifications
@@ -743,8 +739,8 @@ hook sends with a session's prompt, files or transcript (`context.pack`, `code.s
the latest user message through `memory.search` and persist conversation items through
`memory.set`, so both are session content. Its coalesced delivery through
`memory.bulk_set` has the same class. Automatic tool interception also sends
-`code.test_gate`, `code.symbol`, `code.enclosing` and `tracker.duplicate_check` with
-session-derived inputs. The rule decides; the
+`code.test_gate`, `code.symbol`, `code.outline`, `code.enclosing` and
+`tracker.duplicate_check` with session-derived inputs. The rule decides; the
registry's classes and a test over what the shipped hooks send pin the full set.
Once a session has seen the flag, no Loom hook sends any op from it, reads included, and
diff --git a/docs/architecture/llm-architecture.md b/docs/architecture/llm-architecture.md
index f6d52e087c1..22582e92349 100644
--- a/docs/architecture/llm-architecture.md
+++ b/docs/architecture/llm-architecture.md
@@ -1,20 +1,48 @@
# LLM and embedding architecture
-Loom has two pluggable providers: an embedder (`server/embedding/`) that turns text into
-vectors, and an LLM client (`server/llm/`) that completes prompts. Each is chosen once
-per process from settings. Each falls back to a deterministic fake when its key is
-missing, so a keyless install boots and answers. Operator setup is in
-[deployment](../operations/deployment.md); every setting is in the
+Loom uses pluggable embedders and model clients configured through server settings.
+The embedder (`server/embedding/`) turns text into vectors. The one-shot synthesis
+client (`server/llm/client.py`) can use a deterministic fake when an API key is missing;
+configured workload-token credentials still apply. Native Bedrock uses deployment AWS
+credentials and Vertex AI uses Google Application Default Credentials. Both propagate
+credential failures. The native assistant uses a separate
+streaming tool contract and refuses missing provider credentials. Operator setup is in
+[deployment](../operations/deployment.md); settings are in the
[configuration reference](../reference/configuration.md).
+## Native assistant models
+
+`server/llm/agent.py` defines model turns, tool requests and results, usage and terminal
+validation. The native [assistant runtime](assistant.md) owns the bounded loop and
+initial context. It never treats the one-shot synthesis protocol as an agent.
+OpenAI-compatible and Anthropic streams use the guarded shared HTTP pool. The Bedrock
+route signs Converse requests and decodes bounded event-stream frames through the
+same pool, using the existing AWS dependency. The fake route is explicit, never a
+missing-key fallback. No model fallback or implicit streaming replay is used.
+
+A logical turn has one physical request attempt. Usage is captured once in the turn's
+cleanup path, including failures. Cache reads and writes remain separate from uncached
+input; reasoning remains unknown unless reported. An interrupted stream with missing
+usage retains its cost reservation as an estimate and records that uncertainty in the
+ledger and generation span. A real unpriced route refuses before sending. A configured
+price reference for a model alias is an operator-verified rate, not an invoice.
+
+The model receives only bounded data and read-only schemas for the current context.
+Tool execution returns through Loom's authenticated assistant MCP endpoint under the
+asker's delegated token. Private marking, authorization and cost delivery remain
+server-owned. Model and tool producers are closed before final accounting. EOF without
+the provider's terminal frame, a refusal or malformed usage cannot complete an answer.
+See [assistant setup](../operations/assistant.md) for verification and retained-state
+cutover limits.
+
## Goals and non-goals
-| Goals | Non-goals |
-| --------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- |
-| Every correctness gate on the write path works without an LLM. | A general LLM gateway. Loom calls models for its own features only. |
-| A keyless install boots and says clearly that it runs on fakes. | Provider-agnostic prompts. Prompts are tuned to a model and re-benched on a change. |
-| Swapping the embedder does not silently miscalibrate recall. | Mixing vector spaces. Vectors from different models are never compared. |
-| Every provider call is attributed to the op or worker pass that made it, with its cost. | Runtime prompt management. Prompts are code. |
+| Goals | Non-goals |
+| ------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- |
+| Every correctness gate on the write path works without an LLM. | A general LLM gateway. Loom calls models for its own features only. |
+| A keyless install boots and says clearly that it runs on fakes. | Provider-agnostic prompts. Prompts are tuned to a model and re-benched on a change. |
+| Swapping the embedder does not silently miscalibrate recall. | Mixing vector spaces. Vectors from different models are never compared. |
+| Every provider call is attributed to its op or worker pass, with usage and cost when known. | Runtime prompt management. Prompts are code. |
## Embedders
@@ -25,21 +53,25 @@ once per process:
1. A label resolves first. `prefix::` and `ctx[]:` are views
over the served embedder and cannot be the served model.
-2. `LOOM_EMBEDDING_PROVIDER` (`fake`, `local`, `openai`, `gemini`) when set; any other
- value raises.
+2. `LOOM_EMBEDDING_PROVIDER` (`fake`, `local`, `openai`, `gemini`, `compatible`,
+ `bedrock`) when set; any other value raises.
3. Otherwise inferred from `LOOM_EMBEDDING_MODEL`: `fake-ngram*` is fake, `local` or
- `local:*` is local, `text-embedding-*` is OpenAI, `gemini*` is Gemini. Any other name
- raises `unknown embedding model`.
-
-| Provider | Module | Model names | Needs | Notes |
-| -------- | ---------------------------- | -------------------------------------------------------------------------- | ---------------------------------------- | ------------------------------------------------------------------------- |
-| `fake` | `server/embedding/fake.py` | `fake-ngram-` | nothing | Hashed character trigrams, L2-normalised. Deterministic; the dev default. |
-| `local` | `server/embedding/local.py` | `local` (`bge-small`), `local:bge-small`, `local:bge-base`, `local:minilm` | the `local-embedder` extra (`fastembed`) | CPU ONNX; 384, 768 and 384 dimensions. No network. |
-| `openai` | `server/embedding/openai.py` | `text-embedding-3-small`, `text-embedding-3-large` | `OPENAI_API_KEY` | Requests `dimensions=LOOM_EMBEDDING_DIM`. |
-| `gemini` | `server/embedding/gemini.py` | `gemini-embedding-001` | `GEMINI_API_KEY` or `GOOGLE_API_KEY` | Requests `outputDimensionality=LOOM_EMBEDDING_DIM` (up to 3072). |
-
-**Width.** The served width is `LOOM_EMBEDDING_DIM` (default 3072). OpenAI and Gemini are
-asked for that width; choose a model that supports it. Local models emit their native width. Boot probes the real
+ `local:*` is local, `text-embedding-*` is OpenAI, `gemini*` is Gemini and `bedrock:*`
+ is Bedrock. Any other name raises `unknown embedding model`; a compatible endpoint
+ needs an explicit provider.
+
+| Provider | Module | Model names | Needs | Notes |
+| ------------ | -------------------------------- | -------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
+| `fake` | `server/embedding/fake.py` | `fake-ngram-` | nothing | Hashed character trigrams, L2-normalised. Deterministic; the dev default. |
+| `local` | `server/embedding/local.py` | `local` (`bge-small`), `local:bge-small`, `local:bge-base`, `local:minilm` | the `local-embedder` extra (`fastembed`) | CPU ONNX; 384, 768 and 384 dimensions. No network. |
+| `openai` | `server/embedding/openai.py` | `text-embedding-3-small`, `text-embedding-3-large` | `OPENAI_API_KEY` | Requests `dimensions=LOOM_EMBEDDING_DIM`. |
+| `gemini` | `server/embedding/gemini.py` | `gemini-embedding-001` | `GEMINI_API_KEY` or `GOOGLE_API_KEY` | Requests `outputDimensionality=LOOM_EMBEDDING_DIM` (up to 3072). |
+| `compatible` | `server/embedding/compatible.py` | the endpoint's embedding model ID | `LOOM_EMBEDDING_BASE_URL`, `LOOM_EMBEDDING_API_KEY` or configured workload-token authentication | [OpenAI-compatible embeddings](../getting-started/models-and-keys.md#claude-for-the-llm); optional dimensions parameter. |
+| `bedrock` | `server/embedding/bedrock.py` | Cohere Embed v4 model or inference-profile ID | deployment AWS credentials | [Native Bedrock](#native-bedrock); no API-key fallback. |
+
+**Width.** The served width is `LOOM_EMBEDDING_DIM` (default 3072, or 1536 for native
+Bedrock when unset). OpenAI and Gemini are asked for that width; choose a model that
+supports it. Local models emit their native width. Boot probes the real
width (`probe_embedding_dim`); a mismatch shows as `embedding_dim_mismatch` on
`/v1/health`.
@@ -72,7 +104,12 @@ The `Embedder` protocol is `model_name`, `dim`, `async embed(text)` and
the startup probe) has no org to scope by and skips the cache: a worker's identity
carries the org of the row it last worked on, which is no scope for the next text.
Batch entries use a separate key over the raw text, so the paths never serve each
- other. A cache failure falls through to the provider.
+ other. A cache failure falls through to the provider. The local embedder reads it too:
+ an inference holds every ONNX thread the process has, so the sections of one
+ `context.pack` and the legs of one search, which embed the same query at the same
+ moment, run one. Its entries are keyed by the model's alias and pinned revision. With
+ `LOOM_EMBEDDING_CACHE_SHARED` on, a first-seen query costs it one read of
+ `loom.embedding_cache` before the inference and one insert after it.
- **Batches.** OpenAI and Gemini take up to 100 inputs per request; `memory.set` embeds
value and key in one request.
- **Second vector legs.** `prefix::` (a Matryoshka prefix,
@@ -193,13 +230,13 @@ low.
an inferred provider. `loom doctor`'s `llm_provider` line warns when the key is missing.
The stock `.env` pins `LOOM_LLM_PROVIDER=fake`.
-| Provider | Module | Key |
-| ----------- | ------------------------- | ---------------------------------------------------- |
-| `openai` | `server/llm/openai.py` | `OPENAI_API_KEY` |
-| `anthropic` | `server/llm/anthropic.py` | `ANTHROPIC_API_KEY` |
-| `bedrock` | `server/llm/bedrock.py` | deployment AWS role or SDK credential chain |
-| `local` | `server/llm/local.py` | none: the OpenAI client at `LOOM_LOCAL_LLM_BASE_URL` |
-| `fake` | `server/llm/fake.py` | none |
+| Provider | Module | Key |
+| ----------- | ------------------------- | --------------------------------------------------- |
+| `openai` | `server/llm/openai.py` | `OPENAI_API_KEY` |
+| `anthropic` | `server/llm/anthropic.py` | `ANTHROPIC_API_KEY` |
+| `bedrock` | `server/llm/bedrock.py` | deployment AWS role or SDK credential chain |
+| `local` | `server/llm/local.py` | none: chat completions at `LOOM_LOCAL_LLM_BASE_URL` |
+| `fake` | `server/llm/fake.py` | none |
Per-stage models (`LOOM_MEMORY_ASK_SYNTH_MODEL`, `LOOM_CODE_SUMMARY_MODEL` and the other
`*_model` settings) build their own client with `get_llm_client_for_model`, inferring
@@ -274,6 +311,34 @@ and `aws.bedrock.request.model_id`, including inference-profile IDs as requested
The wire contracts follow [Converse](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Converse.html)
and [Cohere Embed v4](https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-embed-v4.html).
+### Vertex AI
+
+The one-shot client uses Google's [generateContent API](https://docs.cloud.google.com/gemini-enterprise-agent-platform/reference/models/inference)
+for Gemini publisher models. Set `LOOM_LLM_PROVIDER=vertex` with an explicit model,
+project, and location, or use a `vertex:` per-job override. The location
+selects a global, regional, or multi-region Google endpoint. The deployment sets
+these values.
+
+The Google Auth library discovers and refreshes Application Default Credentials
+off the event loop. Workload Identity Federation supplies short-lived credentials
+on GKE. Loom sends the inference request through its shared HTTP client, without
+redirects. A missing credential fails the model call. A deployment that requires
+an inference gateway refuses the native Vertex route before credential lookup.
+
+The client records prompt, cache, and output usage from the provider response,
+including reasoning tokens when reported. The cost table uses standard regional
+text rates for its listed Vertex models. A model outside that table has unknown cost.
+See [Vertex setup](../getting-started/models-and-keys.md#vertex-ai) for deployment and
+rollout.
+
+The [native assistant](../operations/assistant.md) selects its own Vertex model
+with `LOOM_ASSISTANT_PROVIDER=vertex` and uses `streamGenerateContent` with the
+same project, location and credential source. It replays model-generated parts
+with their thought signatures when returning tool results within an answer.
+Stream usage comes from the provider's token counts, including cached input
+and reasoning. The assistant uses the canonical `vertex:` price key
+to reserve budget and account for each turn.
+
### Protocol
`LLMClient` has `provider`, `model` and one method:
@@ -283,11 +348,44 @@ async def complete(system, user, max_tokens=1024, response_format=None) -> LLMRe
```
`LLMResult` carries the text, input and output tokens, cached-input and cache-write
-tokens, the answering provider and model, and `from_cache`. There is no tool-use path.
-
-**Structured output.** Callers pass `response_format={"type": "json_object"}`. The OpenAI
-client passes it through. The Anthropic client has no JSON mode: it appends a JSON
-directive to the system prompt, strips code fences and marks the system block cacheable.
+tokens, the answering provider and model, the stop reason and `from_cache`. There is no
+tool-use path.
+
+**OpenAI's two APIs.** The `openai` client calls the Responses API
+(`POST /responses`); the `local` client calls chat completions
+(`server/llm/chat_completions.py`), which every OpenAI-compatible model server speaks.
+Each owns its request and reply; the retries, the bearer and customer headers, the
+learned request shape, the generation span, provider health (`openai:responses`,
+`local:chat`), the cost report and the content capture are one call in
+`server/llm/openai.py`. A Responses request:
+
+- sends the system prompt as a `developer` message before the user message, not as
+ `instructions`: a `json_object` format needs the word "json" in an input message;
+- sets `store: false`, so the provider keeps no response to retrieve later, and carries
+ no `previous_response_id`, `tools` or `prompt`;
+- always carries an output cap, `max_output_tokens`, of at least 16 (the API's least).
+
+Its reply's text is the `output_text` parts of the `message` items (reasoning items carry
+none), and its status becomes the stop reason in chat completions' words: `completed` is
+`stop`, `incomplete` for `max_output_tokens` is `length`, for `content_filter`
+`content_filter`, and a `refusal` part is `refusal`.
+A reply whose status is `failed` raises the HTTP error that its `error.code` stands for
+(`server_error` a 500, `rate_limit_exceeded` a 429, any other code a 400), so the
+retries, the fallback and provider health treat it as that error.
+
+**Structured output.** Callers pass `response_format={"type": "json_object"}` (or a
+`json_schema` format) in chat completions' shape. The local client passes it through; the
+OpenAI client sends it as the Responses `text.format`, a schema's `name`, `schema` and
+`strict` beside its `type`. The Anthropic client sends a schema as the Messages API's
+structured output (`output_config.format`, beside the effort) and writes it into a JSON
+directive appended to the system prompt, so a model that refuses `output_config` still
+answers in the schema's shape; a `json_object` format gets the directive alone. A refusal
+that names one key of `output_config` drops that key alone for the model, so a refused
+effort leaves the format in place and a refused format leaves the effort. A 400 that points
+inside the sent schema (a keyword the API does not take) rejects that schema, not the
+model's structured output: the call is re-sent without the format, the directive still
+names the schema, and later requests send theirs. It strips code
+fences and marks the system block cacheable.
The caller parses (`server/llm/json_text.py`).
**Request shape per model.** `server/llm/traits.py` seeds documented sampling
@@ -302,11 +400,14 @@ restriction.
Each client builds the rest of its request (the lowest reasoning effort and an
output cap), and provider responses teach other traits once per model per process:
-- a 400 naming a field the model does not take (`temperature`, `reasoning_effort`, an
- `output_config`, the cap field under its other name) drops that field: the call is
- re-sent without it, and later calls leave it out;
+- a 400 naming a field the model does not take (`temperature`, `reasoning_effort` or
+ `reasoning`, an `output_config`, a cap field under its other name) drops that field:
+ the call is re-sent without it, and later calls leave it out. An error `param` that
+ names a field the request cannot go without (`input`, `messages`, the Responses
+ `max_output_tokens`) drops nothing;
- a 400 refusing a reasoning effort settles on the lowest one it lists
- (`LOOM_LLM_OPENAI_REASONING_EFFORT` pins one instead);
+ (`LOOM_LLM_OPENAI_REASONING_EFFORT` pins one instead, never below that lowest); a
+ refused effort above it, pinned or a client's own, drops the effort field;
- a 400 naming the model's output limit clamps caps to it;
- reasoning and thinking tokens count against the output cap, so the tokens a reply
reports become the model's reserve (twice the most seen, at most
@@ -330,7 +431,9 @@ them. `LOOM_LLM_ANTHROPIC_EFFORT` sends a thinking effort to Claude models.
(transport error, retryable status, timeout) or a rejected request (400, 413, 422);
401, 403 and 404 propagate. Each hand-over is logged and counted (`loom.llm.fallback`),
and the result names the model that answered. Fallbacks do not chain.
-- **Missing key.** The client is the fake (`_build_llm_client`), logged at WARNING.
+- **Missing API key.** An OpenAI or Anthropic client without its key uses the fake
+ (`_build_llm_client`), logged at WARNING, unless configured workload-token
+ authentication supplies credentials. Native Bedrock credential failures propagate instead.
- **One identity refused.** With identity headers set, an answer from a gateway host that
`LOOM_INFERENCE_IDENTITY_REFUSALS_JSON` lists is the gateway refusing the call's identity or
asking it to wait ([identity headers](#identity-headers)): never retried, never handed to the
@@ -591,7 +694,8 @@ call a model reads `reads_llm_free()`:
- Reranking: a reranker is a model call, and an LLM-free read makes only the ones it names. A
namespace's `rerank_endpoint` and the code and knowledge search defaults
(`LOOM_CODE_SEARCH_RERANK_DEFAULT`, `LOOM_KNOWLEDGE_SEARCH_RERANK_DEFAULT`) do not run; a
- reranker the request names runs, except `builtin:openai`, which keeps the fused order.
+ reranker the request names runs, except `builtin:openai` and code.search's
+ `builtin:pick`, which keep the fused order.
- `tracker.duplicate_check` and `tracker.answer`: no rerank or uncertainty judge; `code.bisect_candidates`:
no rerank. Each keeps the deterministic answer it already falls back to.
- `memory.ask` and `code.ask` answer 409 `READS_LLM_FREE` naming the setting unless the request
diff --git a/docs/architecture/memory-architecture.md b/docs/architecture/memory-architecture.md
index 25b92680f78..11729fb2748 100644
--- a/docs/architecture/memory-architecture.md
+++ b/docs/architecture/memory-architecture.md
@@ -123,7 +123,8 @@ outcome (refusal, 4xx `rejected`, or `error`) and to attach value-shape advisori
- pinned peer: `rejected` (409);
- under `newest_wins`, a templated substitution of a peer (same subject and
predicate, different object): `refines`, which retires the peer, or `conflict`
- when the peer's `valid_at` is later than the new row's;
+ when the peer's `valid_at` is later than the new row's or its standing is above
+ the new row's ([standing](#standing-of-a-retiring-row));
- peer at or above `LOOM_DUPLICATE_THRESHOLD` with the same content words, unless
each side states a value the other lacks (`values_differ`): `duplicate`;
- any other close peer: `conflict`.
@@ -310,7 +311,9 @@ first `loom.memory_versions` version (wall-clock ns) holding its current content
since the last version that held another, so the order is finer than the second, a
metadata write (touch, pin, tags) does not move it, and a value that came back is
ordered from its return; an explicit `valid_at` earlier than that moves it back. Equal keys, or a peer
-asserted later, flag the pair for review instead. A row is always judged as itself:
+asserted later, flag the pair for review instead, and so does a judged row whose standing
+is below the peer's ([standing](#standing-of-a-retiring-row)): the audit row's pair then
+carries `reason: lower_standing_successor`. A row is always judged as itself:
a newer peer comes to its own turn from its own mark. A retirement goes through `apply_refines`: the older row is superseded behind the
newer (its `superseded_by`), one `memory.auto_supersede` record names it
(reason `conflict_resolver`, so `memory.restore` undoes it), and the triple plane follows
@@ -348,6 +351,8 @@ actions, verdicts and confidences, never the text.
overtook records nothing.
- Only `auto_reinforce` and `newest_wins` retire; `manual_review` only flags, and
`append_only` is never judged, nor is a `definition`, whose key is its identity.
+- A row is retired only behind a row of equal or higher standing; a sure update from a
+ lower-standing source is flagged.
- A pinned row is never retired, flagged or cleared, and is no peer (no call is paid for a
pair no verdict may change); a lock that refuses retirement holds.
- The resolver dates an undone row from its first assertion: the version an Undo
@@ -500,7 +505,7 @@ the later of two statements of one attribute in a batch retires the earlier.
| `loom.drop_session_echoes` | Drops facts that restate what the session's own Loom calls wrote or read. |
| `loom.drop_activity_narration` | Drops narration of tool activity with no durable outcome. |
| `loom.drop_non_durable` | Coding sessions: drops status snapshots, housekeeping and plans. |
-| `loom.verify_durable` | Coding sessions: a verifier pass over the rest. Fails open. |
+| `loom.verify_durable` | Coding sessions: a model pass drops non-durable and already stored facts. Fails open. |
| `loom.hash_dedup` | Drops facts whose canonical hash is already stored. |
| `loom.bulk_write` | Files bot rules to the learnings queue, then writes the rest through `memory.bulk_set`. |
@@ -530,6 +535,54 @@ clear a flag. Under `append_only` nothing is marked, and the resolver never judg
definition: its key is its identity ([conflicts and refusal](../features/memory/conflicts-and-refusal.md)).
The writer's own identity is never a peer: its stored row is the one the write revises.
+### Standing of a retiring row
+
+Every automatic retirement asks one more question before it writes: does the row that
+would retire another stand at least as high as that row? The paths are same-key
+supersession and a templated substitution under `newest_wins`, a templated pair inside
+one bulk batch, the memory behind a repaired single-valued triple, the value-update pass
+and the conflict resolver. Each but the last retires through a `RetirementTracker`
+(`memory/app/auto_resolution.py`), whose `skip` leaves a row above its successor live as
+it leaves a locked or pinned one; the resolver asks before it retires, and the batch
+path before it stamps the earlier row. A write that names its row (`memory.update`,
+`memory.delete`, `conflicts.resolve`, `memory.dedup_resolve`, `memory.consolidate`,
+`memory.restore`) never asks.
+
+- **The order** is the trust rank term's (`memory/domain/standing.py`, from
+ `probation.TRUST_CLASS_SQL`): `asserted` and `observed`, then `extracted` and `derived`,
+ then `imported`, then `external`, plus one unit for an attestation that binds the row's
+ current content. A class the server does not stamp is below `external`. No column
+ stores it.
+- **A `derived` successor** counts no higher than the lowest class among the rows it was
+ derived from (`memory/app/standing.py`): its `derived_from` links in
+ `loom.memory_belief_sources` and the classes its own versions held in
+ `loom.memory_versions`, since a consolidation writes its summary over the head of one
+ merged row. A derived source is followed the same way, for at most eight derived rows and 64
+ sources each. One with no recorded source counts as `derived`.
+- **Fails closed.** A successor, a recorded source or a history that cannot be read
+ counts lowest, so it retires nothing of a known class. The successor is the row the
+ write holds, or a read-your-writes read by id, and its lineage is read the same way. A
+ `derived` successor whose own version the history does not show yet (a commit not yet
+ published) stands on the class it holds and the sources that are recorded.
+- **What a refusal leaves** (`auto_resolution.refuse_outranked`). Nothing is retired. The
+ pair is flagged through `mark_peers_conflicted`, so it is a conflict like any other:
+ both rows are served, the pair is listed by `conflicts.list` inside the caller's read
+ scope, and `conflicts.resolve` settles it. One `memory.auto_supersede_refused` audit
+ row per 200 rows names the rows left live, the row each would have retired behind, the
+ reason (`lower_standing_successor`) and the path. A row already flagged beside that
+ row is not recorded again, and a refusal owes the projection repair nothing: no row
+ changed but the flag.
+- **A write's answer.** A `refines` verdict whose peer was left live answers `conflict`
+ (`domain.conflicts.refused_refines`), from `memory.set`, `memory.update` and each
+ `memory.bulk_set` entry; its `peers` are the rows left live, without the ones that
+ retired. Every other refusal is settled after the verdict and leaves the answer as it
+ was: a same-key refusal and a refusal of a pair inside one batch flag the new row
+ once it is in, so the write still answers its own verdict and the status the row was
+ written with. The flag shows on a read of either row, in `conflicts.list` and in the
+ audit row.
+
+Standing is computed at the retirement: no column, table or setting holds it.
+
**Which row is older.** Only the older statement of a pair ever retires, so two rows
judged from either side never retire both (`conflict_resolver._assertion_order`, read
under the pair's key locks). A row's place is when its value was first asserted: the first
@@ -1148,6 +1201,7 @@ term plus a tag boost can exceed the gap between a good and a mediocre match.
| `reflection_distill`\* | Recent sessions without an outcome | Outcome labels, then `reflection` memories hidden from unfiltered recall | Yes |
| `entity_communities`\* | The co-occurrence graph | `entity_communities` | No |
| `recalibration` | The embedder's score distribution | Calibration thresholds | No |
+| `memory_code_links` | Memory writes, each repository's links and its indexed head | `memory_code_links` rows; a revised version of a memory whose text names renamed code | Yes |
\* Off by default (`LOOM_PROFILE_CONSOLIDATION_ENABLED`,
`LOOM_REFLECTION_DISTILL_ENABLED`, `LOOM_ENTITY_COMMUNITIES_ENABLED`).
@@ -1199,6 +1253,56 @@ tags are the union of its sources'. A summary its writer tags `consolidated` and
tag names a key of the row's own namespace, and a user erasure retires the row only
through a key the user wrote there. A `definition` never joins a cluster.
+`memory_code_links` calls the model only under a namespace's `revise` policy. It is the
+one worker that revises a memory's text unasked: when a link follows a definition
+renamed or moved, with its code unchanged or edited, the pass swaps the old name or path
+for the new one in the memory's text and in its `files`, where the plan of
+`server/memory/domain/code_rename.py` offers the edit, the row is `active`, no person
+pinned, locked or verified the memory, no principal attested its text, the row is held
+in the repository's own code namespace, and the repository is indexed on one branch. A
+row of any other namespace is linked by its `repo:` tag, which its writer set and which
+grants nothing, so its text is never revised: the new name would be served to readers
+who may hold no role on the repository, while every read of a link checks that role.
+The revision goes through `memory.update_by_id`'s
+write (`update.revise_as_pipeline`) on the hash of the text it was planned for. A pin,
+an attestation and a status change leave that hash as it was, so the write checks them
+again on the head it reads under the key's lock and refuses a row someone stands behind
+or that is no longer `active`. A write that changes `files` and keeps the text leaves
+the hash as it was too, so the revision is also refused over a head whose `files` are
+not those it was planned for. It runs with that
+write's blacklist check, conflict check, embedding, audit row and `memory.revised`
+event, and it closes the facts the old value stated, as any revision does. Nobody asked
+for it, so it changes that row alone: it is written only when the conflict check is
+`clear` and owes the conflict resolver no judgement, and it runs no same-key
+supersession. A revision that would mark the row a duplicate, or flag, supersede or
+queue a peer, is refused and the text stays. A revision that fails, or whose model call
+is held for the memory's writer, leaves the memory due and stamps its links as checked,
+so the pass reads the other due memories first. `memory.history` keeps the text it
+replaced ([memories linked to code](../concepts/memory.md#memories-linked-to-code)).
+The pass makes the memory's links from the revised text before it writes, over the files
+the pass has already parsed, and stores them once the text is committed. A file the
+memory names that does not parse, like a failure of the index or the mirror, leaves the
+memory due with its text as it was, and the pass lists the error until the file parses.
+The write runs more steps once the version row is committed: the search document on
+ClickHouse, the late index rows, the follow-ups of the conflict check, the edges and the
+stated relations. When one of them fails, the pass reads the head back from its
+authority and, where it holds the revised text and `files`, stores the links and counts
+the memory as `renamed`; the failure is logged and noted on the worker's pass. Two steps
+past the commit can leave the links to the queue, which makes them again so that they
+read `fresh`: that read of the head, and the insert of the link rows, when either fails
+or the process stops before it. The linker also reads the index's head again as it makes
+the links. A `changed` definition renamed once more between the head the pass rechecked
+and that one is no longer where its link says, so that link is dropped and the one made
+at the new place reads `fresh`. A link
+to a definition whose text changed is not made again, which would read `fresh` against
+the code as it is now: it is written under the revised text with the baseline, the
+`changed` state and the `changed_since` it had, so the name in the text and the state of
+the code are kept apart. A `suggestion` judged for the old text is dropped and its link
+left due for the revised claim. Under the Postgres authority a revision whose
+publication is pending is linked all the same. The policy step drops the links of a due
+memory that were made from another text than the head ClickHouse holds, and leaves those
+made from the head the authority holds until ClickHouse holds it.
+
A worker leg that catches its own failure calls `pass_context.note_failure`, so the
supervisor counts it. A worker that declares `owned_tables` runs its first pass at boot
when one of them is empty for a namespace in scope (`workers/first_pass.py`).
@@ -1388,7 +1492,10 @@ place; retrying the restore writes the snapshot again.
An Undo checks before recording its acceptance. Tombstone-only copies remain allowed.
Rollback restores heads, not exact state. `version` is a wall-clock stamp, so the head
-at T is the largest version at or before T. Triples, records, summaries and aggregates
+at T is the largest version at or before T. The cutoff is computed with integer
+epoch arithmetic, preserving each datetime microsecond without floating-point rounding.
+Naive datetimes are UTC; equivalent timezone representations have the same cutoff.
+Triples, records, summaries and aggregates
are rebuilt by their workers (`memory/domain/rollback.py` plans the rollback,
`memory/app/namespace_rollback.py` applies it, `identity/app/namespace_rollback.py` is the handler).
@@ -1514,9 +1621,11 @@ and drops a hit of any other, so every excerpt is the bound namespace's. The
`loom.code_answers` row of such an answer carries `memory_namespace` and the excerpts'
`memory_keys`: a fact's own key, a chunk's parent fact key. Its `namespace` is the code
namespace the question was asked in. The `code_answers.delete` step deletes every version
-of the rows whose `memory_namespace` is an erased namespace or whose `memory_keys` hold
-one of an erased user's keys, tombstones included, since a tombstone version mirrors the
-text; `memory.redact` deletes the rows that hold the redacted key.
+of the rows whose `namespace` or `memory_namespace` is an erased namespace (an answer asked
+in an erased code namespace quotes its repository's code, whatever memory it quoted) or
+whose `memory_keys` hold one of an erased user's keys, tombstones included, since a
+tombstone version mirrors the text; `memory.redact` deletes the rows that hold the redacted
+key.
An answer is memoized only when its memory namespace is in the asking org and every
excerpt is a fact the user's keys reach or a chunk with a parent key, so these predicates
@@ -1528,16 +1637,20 @@ one whose search could not read a fact's tags (`retrieval_work.tags_unread`). No
cached while an erasure of the org had not completed when the ask began, or completed
since (`ledger_reads.unfinished_since`): that saga's `code_answers.delete` step may
already have passed. A failed erasure holds this until it completes, so while one waits
-for `erasure_recovery` or a re-verify, no answer of the org that quoted memory is cached;
+for `erasure_recovery` or a re-verify, no answer of the org is cached, an abstain's
+negative entry included, which holds the question;
a census that counts an answer whose own delete has not landed yet fails it that way.
Nor is one that quoted a key with a redacted version, ever, since a stamp does not say
when the redact finished scrubbing; every user's profile shares a profile key. An
erasure registers its request, and a redact stamps the version, before either deletes the
cached answers, so code.ask reads both again after storing an answer and, finding
-either, tombstones it and deletes the answers quoting its keys; a process killed between
-the two leaves the answer unchecked. A tombstone of an entry
-keeps no answer text, so one written after such a delete brings nothing back. Answers
-drawn from the code index alone name no memory and stay.
+either, tombstones it and deletes the answers quoting its keys; an answer that quoted no
+memory is only checked against the erasure ledger, and is deleted by its own key. A
+process killed between the two leaves the answer unchecked. A tombstone of an entry
+keeps no answer text, only the question, which a namespace erasure's census counts until its delete runs again. Answers
+drawn from the code index alone name no memory: a redact or a user erasure leaves them,
+and a namespace erasure deletes them with the code namespace they were asked in; its
+census counts every version that holds an answer, citations or a question.
An answer or tombstone written by a build before the columns existed names nothing, and so
does a tombstone that build writes of a stamped entry while both builds serve; an erasure
@@ -1654,6 +1767,15 @@ writes no outbox rows ([rule 22](rolling-upgrades.md#the-rules)).
worker's `users_behind` trust a profile row only when its `actor` is
`worker:structured-profile`, so a caller who writes the profile key with `memory.set`
cannot forge a served profile or mark a user current.
+- The link pass's revision of a memory's text after a rename keeps the row's `actor`
+ (the row stays its writer's: a code-namespace member may still revise and delete the
+ rule they wrote) and never raises its `source_class`: an `asserted` row becomes
+ `derived`, since the text is no longer what the writer stated, and every other class
+ is kept, so an unattested `external` row stays out of `memory.ask` synthesis. Its
+ audit row names `process:code_rename`.
+- No automatic path retires a row behind one of lower standing: the pair is flagged for
+ review ([standing](#standing-of-a-retiring-row)). A write that names its row is not
+ held to it.
- A `high`-sensitivity row and a non-searchable type have no embedding row.
- Every vector leg filters `embedding_dim > 0`.
- Merge, duplicate and pinned rejection are decided before the insert; only the LLM
diff --git a/docs/architecture/provider-reconfiguration.md b/docs/architecture/provider-reconfiguration.md
index 622fb99dc4a..576208e1acc 100644
--- a/docs/architecture/provider-reconfiguration.md
+++ b/docs/architecture/provider-reconfiguration.md
@@ -59,6 +59,18 @@ Canceling a coroutine or exhausting the shutdown budget leaves its row nonretire
A failed startup likewise cannot certify unfinished producers. Model-transition
`drained` is reversible and does not certify permanent retirement.
+A process cannot certify its own retirement on a host that gives no process identity
+(no readable `/proc`), or under ClickHouse storage authority before the deployment has
+recorded that authority (a boot with `LOOM_BOOT_MIGRATE` on records it). The process can
+supply neither itself, so it stops retrying once its writes have settled: a `loom` command
+logs one warning and exits with the status of its work, a server's shutdown logs the
+reason, and the row stays nonretired, so a transition waits for it. No command can retire
+a row written without a process identity, because nothing proves its process stopped, and
+Loom has no other recovery for that row. A deployment that will run a transition runs its
+servers and native commands only on hosts with a readable `/proc`. A command that returned,
+and whose writes or retirement then do not settle within
+`LOOM_NATIVE_COMMAND_DRAIN_TIMEOUT_S`, exits 1 with one line that names its participant.
+
The ninth `host_proof` field, `cell-retirement-v1`, identifies this lifecycle.
Only the guarded shutdown or verified-death writer publishes certified retirement.
The generic heartbeat writer cannot retire or reopen a retired identity; a
diff --git a/docs/architecture/rolling-upgrades.md b/docs/architecture/rolling-upgrades.md
index 14465b2474a..e8bdc357c1e 100644
--- a/docs/architecture/rolling-upgrades.md
+++ b/docs/architecture/rolling-upgrades.md
@@ -110,6 +110,9 @@ See the [participant lifecycle baseline](cells.md#participant-lifecycle-baseline
rows): N reads the old and the new format, and only N+1 writes the new one. Exception:
a cursor for a request N-1 answers for `namespace` alone (a `knowledge.list` naming
`namespaces`) is new in N, and each build refuses the one the other wrote (rule 12).
+ The `code_ingest` resume cursor names each cut as `org/namespace` in N; the other
+ build finds no entry of that name and serves its entries in configured order for
+ that pass.
5. **Signing keys:** rotate with `--activate-in` of at least twice the slowest keyring
refresh interval (the command refuses less), so no process signs with a kid an N-1
replica cannot verify yet.
@@ -930,6 +933,74 @@ See the [participant lifecycle baseline](cells.md#participant-lifecycle-baseline
procedure](cost-budgets.md#activation-and-rollback) defines the maintenance boundary;
the warning fleet check alone does not make a downgrade safe.
+63. **The `embed_exclude` marker** (`unembedded by design: reference (embed_exclude)` in
+ `embed_last_error` on `code_chunks`) extends the reference fixtures' marker, so N-1's
+ recovery, backfill embed phase and coverage counts skip it as they skip a fixture. N-1
+ reads neither `LOOM_CODE_EMBED_EXCLUDE` nor an entry's `embed_exclude`: where it runs,
+ its ingest embeds a matching path's new chunks, its `code_summary` pass writes their
+ cards, and its `loom code reembed` and provider rebuild embed the marked rows under the
+ target model. A chunk N-1 embedded keeps its vector until its content changes.
+
+64. **A compiler tier's checkout shares its mirror's packs** by hard link, each kept by
+ a `.keep` file, only with `LOOM_CODE_COMPILER_SHARE_MIRROR_PACKS`, off by default.
+ N-1's git jobs mount the checkout writable and no shared pack read-only, so they
+ could write the mirror's packs: turn it on only once no N-1 replica serves, and
+ before a rollback turn it off and remove the tier checkouts, which N-1 recreates
+ with its own objects. Off, N's checkout holds its own objects as N-1's does. In
+ `tests/unit/test_code_compiler_checkout.py`, a pass of N, then N-1's fetch,
+ `checkout --force` with the mirror out of sight and gc command, then N again, run
+ on one repository volume with no checkout file shared, and a pass of N with the
+ setting on then shares the packs.
+
+65. **A code namespace being erased** (`server/code/app/index/erasing.py`): N's code
+ writers skip a namespace an unfinished erasure may reach, and N's `code_index.purge`
+ refuses, retryably, while work begun before the erasure was recorded may still write
+ it. N-1's writers do neither and N-1's purge does not wait, so an erasure during the
+ rollout can leave rows written after its purge, as before; `verify.residue` fails
+ the saga on those in `code_chunks` and `code_summaries`, and it is repeated. No gate
+ holds the rollout.
+
+66. **A definition renamed as it moves to another file or scope**
+ (`server/code/domain/successor.py::elsewhere`): the builds differ in which of these
+ the link recheck follows, never in the link rows. One host rechecks a repository at
+ a time, so a range is read by one build, and a link one build followed is read by
+ the other as any followed link. Where N follows a definition and N-1 does not (its
+ tokens in a range of more than 32 changed files or past new definitions in its own
+ scope, its tokens under a name the file had for another text, a text nearly its own
+ under another name, a definition under 30 tokens that went with its scope or under a
+ name that holds its own), N-1 reads the link `missing` or `unresolved`. N weighs an
+ `unresolved` link again from the commit its code was last read at, at its next
+ recheck within 30 days or when its file changes. A `missing` link is never handed to
+ a definition added since, so a link N-1 read `missing` during the rollout stays
+ `missing` under N until its own name returns. Where both follow and differ (N takes
+ the definition's tokens under another name before a definition of its own name with
+ an edit), the link is where the build that read the range put it. `wide_ranges` is a
+ number in the `memory_code_links` pass outcome, which every build serves as stored.
+ No gate holds the rollout.
+
+67. **A memory's text revised after a rename** (`server/memory/app/code_renames.py::revise`):
+ N's link pass marks as due (`policy_due`, an existing column) a link that reads
+ `moved`, and a link to a definition that lands at another path or name reading
+ `changed`, and its policy step revises the memory's text where the swap is certain.
+ A build that marks neither, or only the `moved` one, clears in its policy step a
+ mark N wrote without revising what it does not revise, so a rename followed during
+ the rollout can leave its memory's text as written: `namespace.validate` lists the
+ edit of a `moved` link, as before. A link that read `moved` before N served is
+ marked only when a recheck next rewrites it (its file changed and its lines shifted,
+ for one): until then its memory's text stays as written and listed, and no backfill
+ marks it. A link that read `changed` at its new place before N served is marked
+ only when it moves again, and so is one whose mark an older build's recheck dropped
+ as it rewrote the link outside a `revise` namespace. The revision is a
+ `memory.update_by_id` write, which N-1 reads as any other version; N also writes the
+ row's `files`, an existing column. N links the revised memory itself, and writes a
+ `changed` link under the revised text with the baseline it had: rows of the link
+ table as any other, under the inputs hash of the memory as it is, so N-1's linker
+ finds the memory linked and makes no link again. Under the Postgres authority N
+ writes those rows also while the revision's publication is pending, and its policy
+ step leaves them until ClickHouse holds the head; an N-1 policy step that reads the
+ old head in that window drops them, and the linker then makes them `fresh`.
+ `renamed` is one more number in the pass outcome. No gate holds the rollout.
+
## What checks them
`scripts/gates/mixed_version.py` (`make test-mixed-version`, the `mixed-version` CI job,
@@ -957,63 +1028,29 @@ unreachable; CI passes `--require`, which fails there instead.
### Analyst event storage cutover
-The CHECK proof requires ClickHouse with `system.constraints`, as supplied by the
-pinned deployment release. Upgrade the database before provisioning the event catalog;
-a server without that metadata refuses the cutover.
-
-`agent_events` retains ordinary event rows, its columns and the analyst's signed,
-namespace-scoped grant. Both builds can insert and query ordinary events while the
-entity catalog advances to version 5. The `ordinary_events_only` CHECK rejects marked
-rows and reserved mirror namespaces. Ordinary namespaces matching the reserved
-mirror spelling are refused too; they cannot be used as an alternate private sink.
-
-Marked requests and mirror workers write `agent_events_private`, which has no analyst
-grant. The typed, signed `analysis_agent_events` view unions both stores and masks
-private fields before predicates run. Trusted cost, budget and history-policy reads
-also cover both stores. A row policy on a shared physical table cannot replace this
-split: table metadata could disclose private rows even when a SELECT returns none.
-
-Before granting access, provisioning verifies the exact CHECK and both table UUIDs
-on every configured writer, freezes the identities of all running INSERTs, waits
-for that finite set to finish, and counts forbidden ordinary rows. Internal async
-flushes participate even after their submitting client disconnects. Queued requests
-that have not prepared a pipeline encounter the installed CHECK when they execute.
-An ALTER alone does not settle old pipelines. Missing writers, changed topology,
-unknown metadata, a deadline or any surviving forbidden row refuses provisioning;
-existing rows remain untouched. Writers continue accepting valid ordinary inserts.
-
-Negative observations use one checked administrative HTTP session per writer UUID.
-Loom opens independent sessions through the configured service origin until it
-reaches every expected replica. A shared endpoint does not need separate replica
-addresses. A successful session that reaches an already covered replica is closed;
-its bootstrap is never replayed. Discovery is bounded by five seconds and eight
-times the larger of the writer and configured origin counts in additional attempts,
-within the complete proof deadline. An endpoint
-that cannot reach every replica refuses provisioning.
+The ordinary `agent_events` table keeps the `ordinary_events_only` CHECK. It rejects
+marked rows and reserved mirror namespaces. Marked requests and mirror workers write
+to `agent_events_private`. Readers for trusted cost, budget and history-policy queries
+cover both stores.
-`LOOM_CH_ANALYSIS_OBSERVER_URLS` can add explicit trusted HTTP origins using the
-same existing service credentials. Missing or unexpected writer UUIDs, redirects,
-backend changes and incomplete replies refuse. Each checked session must stay on
-its original backend, and routes must preserve non-replaying POST semantics,
-including any intermediary. HTTPS cannot downgrade. The proof never discovers
-another credential or derives HTTP ports from native cluster addresses.
+The analyst reads `analysis_ordinary_agent_events` for ordinary requests and worker
+events. The signed view excludes marked rows and reserved namespaces. The
+`analysis_agent_events` view combines both stores and masks marked fields before
+returning rows. With column grants only on these views, the analyst cannot inspect
+the physical event tables or their storage metadata.
-Each writer supplies its complete native `SHOW CREATE ROW POLICIES` catalog. A
-SELECT from `system.row_policies` cannot establish visibility because policies can
-filter that catalog too. Policies on process, topology or CHECK metadata sources,
-database-wide policies and unknown event policies refuse. Generated analyst event
-policies require their matching unrestricted policy for other users: an analyst-only
-policy can implicitly hide every row from another user. The observer cannot be the
-analyst user or hold its enabled role. Catalog, backend, principal and table identities
-remain fixed through the drain and census. The complete proof has a ten-second
-deadline; exact owned sessions close concurrently with one bounded cleanup interval.
+Deploy Loom v1.3.0 or later to each serving replica before installing these views.
+During setup, Loom revokes legacy grants on the physical event tables before
+granting the views. Both versions keep the same analyst login and signed canary.
+Once the new version writes its entities, a query that names `loom.agent_events`
+must use `loom.analysis_ordinary_agent_events`. A replica still serving the previous
+build can report the old catalog until it is upgraded.
-Run `loom ch-setup --apply-analyst-sql` with explicitly configured existing
-access-management credentials to apply only the analyst boundary. It uses the same
-live proof and lease without rebuilding the reader user. `--print-analyst-sql` refuses
-with a nonzero result and prints no grants or secrets: an unchecked SQL file cannot
-enforce the native policy-catalog observation. General `--print-sql` still prints
-database and reader preparation with a password placeholder.
+The provisioner checks native `SHOW CREATE ROW POLICIES ON .*` before
+writing Loom's policies and grants. This requires policy visibility in Loom's
+database. The views filter data at read time and the analyst has no storage grants,
+so setup needs no global policy catalog or per-writer proof of the ordinary table's
+contents. `loom ch-setup --apply-analyst-sql` runs the same live checks.
Mirrored creation remains disabled until the fleet, read and session protections
and enablement procedure are complete. Before an older build serves after enablement,
diff --git a/docs/architecture/security.md b/docs/architecture/security.md
index 14d2b5cd244..cbd792a9401 100644
--- a/docs/architecture/security.md
+++ b/docs/architecture/security.md
@@ -276,13 +276,17 @@ authenticated call, from `gates.authorize` in both transports:
creator holds that role somewhere in the org, and on a namespace needs its own claim to reach
the role and the creator's live grant to reach it too (`_check_delegated`; restricted
namespaces also take the restricted gate). Nothing below applies to it.
-3. A restricted namespace goes to the restricted gate only.
-4. A viewer read of an org-readable code namespace (`LOOM_CODE_ORG_READABLE` or the
+3. A restricted namespace goes to the restricted gate, including its repository read
+ exception below.
+4. An authenticated platform administrator using its own unscoped authority reads every
+ configured or registered repository, including closed and restricted entries. Deployment
+ tenancy still applies. This authority does not admit writes or any other namespace kind.
+5. A viewer read of an org-readable code namespace (`LOOM_CODE_ORG_READABLE` or the
entry's `org_readable`) passes for any principal of that org.
-5. A scoped token's `ns_roles` decide for the namespaces they name, in the token's org
+6. A scoped token's `ns_roles` decide for the namespaces they name, in the token's org
only. Grants are not consulted for them, except viewer reads of a code namespace.
-6. A token acts in its own org only (or `*`, or as platform admin).
-7. A flat token's roles apply to every namespace its claims cover. Otherwise a live grant
+7. A token acts in its own org only (or `*`, or as platform admin).
+8. A flat token's roles apply to every namespace its claims cover. Otherwise a live grant
in `loom.namespace_grants` decides: unrevoked and `active` (`grant_sql.LIVE_GRANT`); a
`pending` join request grants nothing. A service account with no grant reads its
creator's. A grant raises a flat token's role, never lowers it. A failed read of
@@ -333,8 +337,8 @@ foreign row and a missing row look the same.
### Restricted namespaces
A namespace classified `restricted` (in `loom.namespaces` or its repository entry; either
-restricts) turns off every widening rule (`_check_restricted` in `server/auth/authz.py`).
-A call passes only when all of these hold:
+restricts) uses `_check_restricted` in `server/auth/authz.py`. Except for the repository
+read authority below, a call passes only when all of these hold:
- the token's org is the namespace's (`*` does not count);
- the token names the namespace literally;
@@ -342,7 +346,34 @@ A call passes only when all of these hold:
- a live direct grant for the token's own subject reaches it (a service account does not
inherit its creator's grant).
-No org-readable rule, `visibility=public`, `org_admin` or `platform_admin` bypasses it. A
+An authenticated `platform_admin` using its own unscoped authority reads every repository
+that `NamespaceDirectory.code_entry` recognizes in the current configuration or registry
+snapshot. This includes restricted, approval and closed repositories across the orgs the
+deployment holds. `authz.is_own_platform_admin` excludes scoped tokens, delegated tokens
+and impersonated subjects, even when their flat roles contain `platform_admin`. Namespace
+`admin` and `org_admin` confer no such authority. A name beginning with `code-` confers
+nothing without a repository entry.
+
+Repository indexes are deployment reference data, so platform administrators need a read
+authority independent of repository membership. Requiring a separate claim and direct
+grant for each repository would make this authority depend on token refreshes and grant
+provisioning. The exception is limited to viewer reads: writes, refreshes, registration,
+grant management and every non-repository namespace keep their existing checks. Collection
+and mirror boundaries run before repository admission; a repository read does not expose
+its document mirrors or internal data.
+
+The member-write fallback checks the ordinary read rules without the platform read
+exception. A live viewer grant alone cannot widen a token's restricted write scope.
+
+Classification must remain available, `restricted_serve=false` refuses restricted reads
+even for platform administrators, and tenancy and token verification still run first.
+Revoked or unverifiable credentials gain no authority. HTTP, MCP, row-scoped checks and
+repository listings share this decision through `check_authorized`. The listing returns
+actual heads and counts only after that gate admits the read. Restricted-access audit
+behavior also applies to platform administrators. No schema or stored-grant migration is
+needed. Auth-off behavior is unchanged.
+
+No org-readable rule, `visibility=public` or `org_admin` bypasses the restricted gate. A
refusal is the generic "cannot access". If the classification cannot be read, access is
denied.
@@ -1507,6 +1538,17 @@ bound parameter, on Loom's server and on any warehouse server that joins with it
bucket's write role is bound to the export's own Kubernetes ServiceAccount, not to the web
pods, and the upload never replaces an object.
+[Adoption telemetry](../features/observability/telemetry.md#self-hosted-adoption)
+is enabled by default and reads 12-hour windows from the ordinary request ledger.
+It sends deployment-wide counts and a reporting UUID derived from the storage
+authority's deployment ID to the Loom HTTPS collector. Reports include eligible
+namespace contact domains, which can come from self-reported addresses. The public
+directory uses aggregate activity for those domains from snapshots sent every five
+minutes and from completed daily reports.
+Set `LOOM_ADOPTION_TELEMETRY_ENABLED=false` to stop all adoption reporting. The
+collector is outside Loom's erasure boundary. Verified company attribution uses
+a separate warehouse enrollment record.
+
## The SQL surface
The [SQL surface](../reference/sql-surface.md) lets an org's own SQL user read a
diff --git a/docs/architecture/server-layout.md b/docs/architecture/server-layout.md
index a488f9e3096..626ed2970b2 100644
--- a/docs/architecture/server-layout.md
+++ b/docs/architecture/server-layout.md
@@ -32,7 +32,7 @@ reading an import error from the contract test.
| `server/tasks/` | The task inbox, the run ledger, their wake-up and webhook loops | see [layers](#layers) |
| `server/identity/` | Namespaces, grants, history policy, read scope, restricted access, the dashboard page and the caller API (`/v1/me/*`) | see [layers](#layers) |
| `server/insights/` | Operator surfaces: `ops.*`, `cost.*`, `agents.*`, `audit.list`, `ui.vitals`, `mentor.brief`, the `/v1/admin/*` routes | see [layers](#layers) |
-| `server/assistant/` | The assistant: its LibreChat service user and agent definition, set up at boot | see [layers](#layers) |
+| `server/assistant/` | The native assistant: bounded streaming model turns and authorized tool execution | see [layers](#layers) |
The platform packages are `core` and the other non-domain packages above: `settings`,
`operations`, `transport`, `cli`, `workers`, `observability`, `auth`, `embedding`, `llm`,
diff --git a/docs/architecture/sharing.md b/docs/architecture/sharing.md
index a3e79819291..ca38d4c85b9 100644
--- a/docs/architecture/sharing.md
+++ b/docs/architecture/sharing.md
@@ -362,3 +362,5 @@ One text serves agents and people, so there is no second copy to drift.
- [Security](security.md): tokens, the gate, restricted namespaces.
- [Identities and namespaces](../concepts/identities-and-namespaces.md).
- [Tokens and grants](../guides/tokens-and-grants.md).
+- [Choose retrieval scope from the audience](../guides/audience-scoped-retrieval.md):
+ what a host adds when a reply has more readers than the person who asked.
diff --git a/docs/architecture/storage-authority.md b/docs/architecture/storage-authority.md
index d02b6c12387..a94d0a9bd3f 100644
--- a/docs/architecture/storage-authority.md
+++ b/docs/architecture/storage-authority.md
@@ -1,3 +1,8 @@
+---
+seo:
+ title: Postgres and ClickHouse storage authority
+---
+
# Storage authority: Postgres for live memory, ClickHouse for search
Loom runs with one of two memory authorities, chosen per deployment by
diff --git a/docs/architecture/storage-layout.md b/docs/architecture/storage-layout.md
index bf249d23016..e8de3ee9429 100644
--- a/docs/architecture/storage-layout.md
+++ b/docs/architecture/storage-layout.md
@@ -1,3 +1,8 @@
+---
+seo:
+ title: Table layout in Postgres and ClickHouse
+---
+
# Storage layout: which store holds each table, and why
Each Loom table belongs in Postgres or ClickHouse by how it is read and written; this
@@ -933,7 +938,7 @@ copies of tables listed here, owned and removed by that run, and erasure reaches
| `provider_configuration` | RMT(version) `config_id` | Postgres `provider_configuration` + rebuild jobs | SoR | no content | 1 | sealed provider envelopes and activation state; a rebuild is a `jobs` row with its ledger ([cursors](#cursors)); named in `server/insights/store/provider_configuration.py`, `server/cli/secrets.py` |
| `embedder_calibration` | RMT(version) `embedder_model` | Postgres `embedder_calibration` | Derived | no content | 1 | one row per embedder model, adopted by every replica; rebuilt by a recalibration, at embedding cost; named in `server/memory/store/calibration.py` |
| `analysis_secrets` | RMT(version) `id` | Postgres `analysis_secrets` | SoR | no content | 1 | sealed `insights.query` scope key and analyst password, written as literals into its ClickHouse's row policies (`server/insights/domain/analysis.py`); named in `server/insights/store/analysis.py`, `server/cli/secrets.py` |
-| `assistant_service` | RMT(version) `id` | Postgres `assistant_service` | SoR | no content | 1 | the sealed password and API key the assistant service logs in with (`server/assistant/app/service.py`), written step by step under a lease: one secret per cell with no org, embedded in no ClickHouse object; named in `server/assistant/store/service.py`, `server/assistant/app/service.py` |
+| `assistant_service` | RMT(version) `id` | Postgres `assistant_service` | SoR | no content | 1 | retained sealed provisioning metadata; no native assistant read or write path; root-key rotation preserves it until operator-approved retirement; named in `server/cli/secrets.py` |
| `sql_access` | RMT(updated_at) `(user_name, org, namespace)` | Postgres `sql_access` + ClickHouse mirror | SoR (head) | no content | 1 | which SQL user may read which org and namespace through the scoped `sql_v1_*` views: a grant, so its head and its revocations are in Postgres; the views read the mirror by `currentUser()` inside ClickHouse, and a revoke answers once its mirror rows have landed; its wildcard grants (`namespace = '*'`, `org = '*'`) are rows like any other; named in `server/insights/store/sql_access.py`, `server/identity/store/namespace_census.py` |
| `analysis_canary` | RMT `id` | stays | SoR | no content | — | must stay in ClickHouse: `insights.query` reads it through the same row policies as real data; named in `server/insights/domain/analysis.py` |
| `storage_authority` | RMT(epoch) `tuple()` | stays | SoR | no content | — | ClickHouse's half of the pairing with Postgres's `authority` row (the deployment id); named in `server/core/pg_profile.py` |
@@ -1072,7 +1077,7 @@ it holds no provider identity or credential.
| `code_search_outcome` | MT `(org, namespace, trace_run_id, ts)`, by `toYYYYMM(ts)`, TTL | stays | Log | census, `code_search_trace.delete` | — | search outcomes, 180-day TTL; named in `server/code/app/outcome.py`, `server/code/store/index/search.py` |
| `code_symbol_ids` | RMT `(org, namespace, symbol_id, tier, qualified_name)` | stays | Derived | step `code_index.purge` | — | `code_symbols` re-keyed by id through `code_symbol_ids_mv`; named in `server/code/store/index/symbols.py` |
| `code_symbol_names` | RMT `(org, namespace, name, tier, qualified_name, symbol_id)` | stays | Derived | step `code_index.purge` | — | `code_symbols` re-keyed by short name through `code_symbol_names_mv`; named in `server/code/store/index/symbols.py` |
-| `code_answers` | RMT(version) `(org, namespace, embedding_model, question_id)` | stays | Cache | census, `code_answers.delete`, user scope too | — | cached model answers that may quote memory, so erasure reaches them; named in `server/code/store/index/answers.py`, `server/memory/store/redaction.py` |
+| `code_answers` | RMT(version) `(org, namespace, embedding_model, question_id)` | stays | Cache | census, `code_answers.delete`, user scope too | — | cached model answers that may quote memory or the repository's code, so erasure reaches them, by the namespace asked in and the memory namespace quoted; named in `server/code/store/index/answers.py`, `server/memory/store/redaction.py` |
| `code_unit_signal` | SMT((positive, negative)) `(org, namespace, unit_id)` | stays | SoR | step `code_index.purge` | — | feedback increments per unit, summed; named in `server/code/store/index/search.py` |
| `code_gh_items` | RMT(version) `(org, namespace, number)` | stays | Derived | step `code_index.purge` | — | issues and pull requests mirrored from the repository host, refetched by `code_pr_history` back to `code_gh_items_backfill_days`; named in `server/code/store/index/gh_items.py` |
| `code_pr_history` | RMT(version) `(org, namespace, pr_number)` | stays | Derived | step `code_index.purge` | — | merged pull requests and their files mirrored from the repository host, refetched by `code_pr_history`; named in `server/code/store/index/pr_history.py`, `server/code/store/index/reviews.py` |
diff --git a/docs/architecture/system-overview.md b/docs/architecture/system-overview.md
index e89239af8b0..3f559102b0d 100644
--- a/docs/architecture/system-overview.md
+++ b/docs/architecture/system-overview.md
@@ -149,7 +149,9 @@ at most once a minute (`gates._fail_open`). Authentication and authorization fai
**Unknown arguments.** Input models ignore unknown keys, so `server/transport/arg_check.py`
names them: the response carries `ignored_args` (and `did_you_mean` for a close field
name), and HTTP sets `X-Loom-Ignored-Args`. Both list first any field the op read but
-declined to apply, then the unread keys. A write op refuses a close match with 422
+declined to apply, then the unread keys. HTTP percent-encodes each UTF-8 name before
+joining the header components with commas; the JSON names stay unchanged.
+A write op refuses a close match with 422
`UNKNOWN_ARGUMENT`. Identity keys and keys the transport reads itself (`consumer`,
`traffic_class`, `explain`, the idempotency key) are never reported.
@@ -199,8 +201,12 @@ and [tool design guidance](https://www.anthropic.com/research/writing-tools-for-
Coding instructions distinguish issue investigation, known-definition reads and
literal searches. Code-linked project knowledge explains what retrieval adds to
a source-file read; argument descriptions carry the inputs for each workflow.
-- **Offer an entrypoint.** Search and operation discovery request upfront schema
- loading where listed; other tools can be discovered when needed. The loading
+- **Offer an entrypoint.** The `coding` toolset requests upfront schema loading
+ for the pre-edit read, literal search and, outside the compact profile, the
+ definition lookup. Every other toolset, a union such as `coding+tracker`
+ included, requests it for general and code search, the definition lookup,
+ literal search and operation discovery where listed. Other tools can be
+ discovered when needed. The loading
setting applies to registry operations and synthetic tools. Clearing it leaves
loading to the client. A loading hint never invokes a tool or widens its roster.
- **Keep one contract.** The operation registry supplies schemas and handlers for
diff --git a/docs/assets/screenshots/assistant-answer.webp b/docs/assets/screenshots/assistant-answer.webp
index c9dab8e6c40..46ee6887c86 100644
Binary files a/docs/assets/screenshots/assistant-answer.webp and b/docs/assets/screenshots/assistant-answer.webp differ
diff --git a/docs/assets/screenshots/audit-log.webp b/docs/assets/screenshots/audit-log.webp
index 70876ca7ffd..c84d06a190a 100644
Binary files a/docs/assets/screenshots/audit-log.webp and b/docs/assets/screenshots/audit-log.webp differ
diff --git a/docs/assets/screenshots/clip-assistant-answer.webm b/docs/assets/screenshots/clip-assistant-answer.webm
index 307689ecd7f..7a1a47eee3f 100644
Binary files a/docs/assets/screenshots/clip-assistant-answer.webm and b/docs/assets/screenshots/clip-assistant-answer.webm differ
diff --git a/docs/assets/screenshots/clip-code-callers.webm b/docs/assets/screenshots/clip-code-callers.webm
index d4de45ad086..b3fee7d1ca9 100644
Binary files a/docs/assets/screenshots/clip-code-callers.webm and b/docs/assets/screenshots/clip-code-callers.webm differ
diff --git a/docs/assets/screenshots/clip-memory-linked-code.webm b/docs/assets/screenshots/clip-memory-linked-code.webm
index 9ffd002a126..08be8fb3dec 100644
Binary files a/docs/assets/screenshots/clip-memory-linked-code.webm and b/docs/assets/screenshots/clip-memory-linked-code.webm differ
diff --git a/docs/assets/screenshots/code-callers.webp b/docs/assets/screenshots/code-callers.webp
index 722856d6e18..df5fbb3c6c3 100644
Binary files a/docs/assets/screenshots/code-callers.webp and b/docs/assets/screenshots/code-callers.webp differ
diff --git a/docs/assets/screenshots/document-search.webp b/docs/assets/screenshots/document-search.webp
index aeaea826912..8211a6072da 100644
Binary files a/docs/assets/screenshots/document-search.webp and b/docs/assets/screenshots/document-search.webp differ
diff --git a/docs/assets/screenshots/memories.webp b/docs/assets/screenshots/memories.webp
index e1837b37588..40a80f2e698 100644
Binary files a/docs/assets/screenshots/memories.webp and b/docs/assets/screenshots/memories.webp differ
diff --git a/docs/assets/screenshots/memory-linked-code.webp b/docs/assets/screenshots/memory-linked-code.webp
index 3a1111ff2b0..6b68afb219a 100644
Binary files a/docs/assets/screenshots/memory-linked-code.webp and b/docs/assets/screenshots/memory-linked-code.webp differ
diff --git a/docs/assets/screenshots/review-queue.webp b/docs/assets/screenshots/review-queue.webp
index ae4930c7b32..7681add2cc2 100644
Binary files a/docs/assets/screenshots/review-queue.webp and b/docs/assets/screenshots/review-queue.webp differ
diff --git a/docs/benchmarks/coverage.md b/docs/benchmarks/coverage.md
index 9fcb841d4e8..be6ae5570bd 100644
--- a/docs/benchmarks/coverage.md
+++ b/docs/benchmarks/coverage.md
@@ -27,7 +27,7 @@ The [results ledger](./results.md) is the source of published numbers; the
| Unknown questions | Does Loom abstain instead of answering from weak evidence? | abstain precision/recall, false-answer rate and answerable recall | **Partial** | LoCoMo adversarial questions and ten code abstain probes are published; a larger calibrated memory abstention set is still required. |
| Corrections and time | Does the current value replace stale facts while historical queries stay correct? | current-value accuracy, stale-answer rate, temporal accuracy and supersession precision | **Harness only** | Publish `pi_llm.py`, `forget_switch_eval.py`, `fama_forgetting.py` and `supersession_audit.py` on one shared public corpus. |
| Cross-tool continuity | Does a fact written by one client help another client in a later session? | cross-client recall, provenance, capture loss and latency | **Harness only** | `cross_tool_validate.py` has six queries; publish a larger Claude Code, Codex and Cursor matrix with raw captures. |
-| Memory efficiency | Does retrieval save context, model spend and turns? | task success, prompt/output tokens, model cost and construction break-even | **Published** | The paired LongMemEval full-history result reports 91% fewer reader tokens and its construction break-even. |
+| Memory efficiency | Does retrieval save context, model spend and turns? | task success, prompt/output tokens, model cost and construction break-even | **Partial** | The paired LongMemEval comparison reports 91% fewer prompt tokens for retrieval and estimates when the saved tokens offset memory construction. It does not measure model spend or turns. |
| Knowledge retrieval | Does document RAG find and cite the right passage? | chunk recall@k, answer accuracy, citation precision, abstention, latency and tokens | **Partial** | [Design decisions](./results.md#design-decisions-from-design-documents) arm 2 measures answer accuracy over `loom_search` knowledge hits (A and D precision and recall against gold), citation precision and recall, abstention and injected tokens, on a private set of five documents with one judge; chunk recall@k, latency and a public set (`narrativeqa.py` with a fixed reader, hard unanswerable and citation cases) are still required. |
| Source formats | Which inputs reach equivalent searchable text? | extraction success, text/table fidelity, OCR quality and failure rate by format | **Partial** | [Document parsing](./results.md#document-parsing) measures text, table and locator fidelity, OCR quality and silent loss for PDF, DOCX and PPTX on a committed corpus against a layout-model baseline; CSV, XLSX, Parquet, HTML and the other text formats, and a licensed real-world corpus, are still required. |
| Code conceptual search | Does issue-shaped text find the implementation? | file hit@k, all-gold hit@k, MRR, abstention, tokens and latency | **Published** | ClickHouse conceptual questions and a 200-instance SWE-bench Verified file-localization sample; this is retrieval, not the official patch-and-test score. |
diff --git a/docs/benchmarks/results.md b/docs/benchmarks/results.md
index 7d7e65c2471..cd22dc11079 100644
--- a/docs/benchmarks/results.md
+++ b/docs/benchmarks/results.md
@@ -50,9 +50,9 @@ reproduction command.
| [Tracker duplicate detection](#duplicate-check-on-public-clickhouse-issues) | Given a new issue draft, find its recorded older duplicate while limiting duplicate verdicts on issues with no recorded duplicate/related link. | 104 recorded duplicate pairs and 100 negative-labelled issues from ClickHouse's public tracker. | `tracker.duplicate_check` receives title and body as of creation time; the draft's issue number and recorded links are withheld. | Older linked issue ranked first and duplicate verdict correctness; a negative label means no recorded link, not proof that two issues are unrelated. |
| [ClickHouse code intelligence](#code-intelligence-on-the-clickhouse-repository) | Find definitions, callers and implementation files for authored questions; abstain on authored out-of-repository probes. | 60 authored questions: 10 definitions, 4 caller sets, 36 conceptual searches and 10 out-of-repository probes. | Public ClickHouse repository index; `code.symbol`, `code.callers` and `code.search` with their normal result limits. | Exact first definition; F1 against expected callers; mean gold-file recall@5/@10, MRR and hit@5; abstention precision/recall. |
| [SWE-bench Verified sample: file localization](#swe-bench-verified-file-localization) | Given a GitHub issue description, rank the pre-existing repository files that its accepted patch later modified. This is retrieval, not patch generation or issue resolution. | Stratified seed-7 sample of 200 eligible instances from the 500-instance dataset, covering all 12 repositories; eligibility requires at least one patch-modified file present at `base_commit`. | Each repository indexed at the issue's `base_commit`; issue text truncated at 2,000 characters; `code.search` first 10 results and a second page to 25 units. | File hit@1, hit@5 and hit@10 (at least one gold file); all-gold@10; MRR; paired against BM25 over the same live files and over Python files only. |
-| [Memory versus full history](#with-and-without-loom) | Answer the same long-conversation question from retrieved memories or from the complete conversation history. | Paired seed-13 sample of 100 LongMemEval-S questions. | Same `gpt-5` reader sees either `memory.search` top 200 or the full history. | Official-judge accuracy and reader prompt tokens; memory construction is excluded from prompt-token totals and reported separately as break-even. |
+| [Memory versus full history](#with-and-without-loom) | Answer the same long-conversation question from retrieved memories or from the complete conversation history. | Paired seed-13 sample of 100 LongMemEval-S questions. | Same `gpt-5` reader sees either `memory.search` top 200 or the full history. | Official-judge accuracy and prompt tokens: reader prompts for full history, reader and judge prompts for retrieval. Memory construction is counted separately. |
| [Coding agents on ClickHouse: with Loom vs without Loom](#with-and-without-loom) | Answer a ClickHouse developer's question: explain a mechanism, list the callers a change must update, find the change behind a behaviour, trace a bug to its fix, find the tests that cover a change. | 48 answer-graded questions × 3 paired runs and 36 conceptual questions × 10 paired runs; checkouts without git history at the verified commit. | Same headless `claude-sonnet-5` in a stock session; baseline has Bash, Read, Grep and Glob, the Loom arm adds the Loom plugin and its MCP `coding` toolset. | Judged key points of a verified reference answer, right file among the up to three the agent is asked to name; model cost, turns and wall time per run. |
-| [Definitions and callers versus grep](#with-and-without-loom) | Find a symbol's definition or all expected callers using Loom or repository text search. | The same 10 definition and 4 caller questions from the ClickHouse code-intelligence set. | Loom's code index versus `git grep` for the bare name and the qualified `Class::name`; grep output tokens estimated as characters divided by four. | Correct file ranked first, expected callers found and context tokens returned. |
+| [Definitions and callers versus grep](#with-and-without-loom) | Find a symbol's definition or all expected callers using Loom or repository text search. | The same 10 definition and 4 caller questions from the ClickHouse code-intelligence set. | Loom's code index versus `git grep`: whole-word bare name and literal substring (`Class::name` where available, bare name otherwise). | Loom's first path under the expected directory prefix, expected caller measures and estimated output tokens. |
| [`code.ask` production cache](#with-and-without-loom) | Measure how often repeated real questions reuse a cached answer and what one hit saves. | 673 non-benchmark calls from one deployment over 30 days; 20 cache hits. | Normal `code.ask` traffic using the shipped cache guard and threshold. | Observed hit rate, answer tokens avoided and latency; this is an operational observation, not a controlled quality comparison. |
| [`code.ask` cache threshold](#codeask-answer-cache-threshold) | Determine whether paraphrased questions can share an answer without sharing across materially different questions. | 42 paraphrase pairs, 43 different-question pairs, 22 one-identifier near-misses and 2 unlabelled pairs. | About 130 embedding calls for each tested embedding model; cosine sweep with and without the identifier guard. | Paraphrase hits versus false hits at each threshold; the shipped threshold requires zero false hits on the 65 labelled different pairs. |
| [Design decisions from design documents](#design-decisions-from-design-documents) | Answer why questions, make change requests whose obvious move a design document rejected, answer questions on reversed or unrecorded decisions, and explain how a feature works, given different design knowledge per arm. | Private set: 5 design documents (4 revised once), 10 why, 15 change, 10 supersession or abstention and 13 feature tasks, 3 samples each. | Nothing, `knowledge.get`, knowledge hits of `loom_search`, gold rows or extracted rows through `memory.for_file` and `loom_search`, or extracted rows with the knowledge hits. | `gpt-6-luna`-judged argument and feature-fact precision/recall, rejected-option avoidance, constraint satisfaction, stale statements and failed abstentions; paired against arm 0, the gold rows, and, for arm 6, the knowledge hits and the extracted rows alone. |
@@ -442,19 +442,23 @@ by `gpt-5` (reasoning effort `medium`) twice: from the whole chat history in the
and from `memory.search`'s top 200 hits over the ingested memory. Both are graded by the
official judge.
-| Reader input | Accuracy | Reader prompt tokens per question |
-| ----------------------- | -------: | --------------------------------: |
-| Whole history | 90% | 103,879 |
-| Loom's top 200 memories | **94%** | **9,443** |
+| Reader input | Accuracy | Prompt tokens per question |
+| ----------------------- | -------: | -------------------------: |
+| Whole history | 90% | 103,879 |
+| Loom's top 200 memories | **94%** | **9,443** |
+
+The whole-history count includes reader prompts only. The retrieval count includes
+reader and judge prompts. The reported retrieval count is 91% lower even with judging
+included. Neither count includes memory construction. The [ingest run](#longmemeval-s) reports about 1.5 million extraction input and output
+tokens per history on `gpt-6-luna` (`longmemeval_s_ingest.csv`). Dividing that average by
+about 94,000 fewer prompt tokens per question gives an estimate of 16 questions over
+the same history. The benchmark used one question per history. The estimate omits
+query embedding, reranking and answer output tokens, and does not price model calls.
Paired, 87 questions are right both ways, 7 only with memory, 3 only with the whole history.
The four-point accuracy difference is descriptive: only 10 outcomes disagree, and a
two-sided exact McNemar test gives p=0.34. This sample does not establish that retrieval is
-more accurate than full history. Memory reads 91% fewer reader prompt tokens per question.
-Those prompt-token totals exclude memory construction. Building the memory costs about
-1.5 M extraction tokens per haystack, once, on `gpt-6-luna`. Against about 94 k
-tokens saved per question, that is repaid after about 16 questions over the same history,
-before the price gap between the extraction model and the reader is counted.
+more accurate than full history.
**Coding agents on ClickHouse, with and without Loom.** Claude Code (`claude-sonnet-5`) answers
each question twice in a stock session (no user or project settings): with Bash, Read, Grep and
@@ -502,19 +506,23 @@ An earlier 12-issue SWE-bench agent sample is withdrawn: its with-Loom agent cal
**Definitions and callers against grep.** The 10 definition and 4 caller questions of
`bench/fixtures/code_intel_qa.jsonl`, replayed as `git grep` over a ClickHouse checkout:
-once for the bare name, as an agent searching for a word would, and once for `Class::name`,
-as a careful one would. Tokens are characters / 4.
-
-| Question | Bare-name grep, median | `Class::name` grep, median | Loom |
-| ----------- | -------------------------------- | ----------------------------- | ---------------------------------------- |
-| Definitions | 29,061 tokens over 227 files | 1,623 tokens over 25 files | 1,678 tokens; right file first, 10 of 10 |
-| Callers | 558 tokens; 4 of 12 callers seen | 101 tokens; misses call sites | 12 of 12 expected callers |
-
-For a method with a distinctive qualified name, a careful grep is as cheap as Loom. For a
-free function or a common type name (`executeQuery`, `parseQuery`, `Field`) grep returns
-35 k to 490 k tokens where Loom returns about 1.2 k to 2.5 k. For callers grep is cheap but
-incomplete: a call site spells the receiver, not the class (`reader.readFromParts(…)`), so
-the qualified grep misses them and the bare grep names a third of them.
+once for the bare name as a whole word, and once for a literal substring. The substring
+search used `Class::name` where available (7 of the 10 definitions) and the bare name
+otherwise. Tokens are characters / 4. The harness counts a definition as a match if
+the first Loom result's path starts with the expected directory prefix.
+
+| Question | Whole-word grep, median | Substring grep, median | Loom |
+| ----------- | --------------------------------------------------------------------- | -------------------------- | -------------------------------------------- |
+| Definitions | 29,061 tokens over 227 files | 1,623 tokens over 25 files | 1,678 tokens; expected prefix first in 10/10 |
+| Callers | 558 tokens; 4 of 12 expected caller entries matched by name substring | 101 tokens | 12 of 12 expected callers |
+
+For the three definition searches that used bare names (`executeQuery`, `parseQuery`,
+`Field`), substring grep returns roughly 35,000 to 490,000 estimated tokens;
+Loom returns about 1,200 to 2,500. For callers, the harness searches the whole-word
+grep output for each unqualified expected caller name as a substring. The searched
+symbols suffice for all four matches: `executeQueryImpl` contains `executeQuery` for
+one entry, and `readFromParts` contains `read` for three entries.
+The harness does not verify call sites or score caller coverage for substring grep.
**Repeated `code.ask` questions.** Over 30 days of one deployment's real (non-bench)
traffic, 20 of 673 `code.ask` calls (3%) were served from the answer cache: each saved a
diff --git a/docs/benchmarks/software-factory-pilot.md b/docs/benchmarks/software-factory-pilot.md
new file mode 100644
index 00000000000..997d914f906
--- /dev/null
+++ b/docs/benchmarks/software-factory-pilot.md
@@ -0,0 +1,183 @@
+# Proposed software factory pilot
+
+This draft measures whether application-owned context retrieval changes objective
+resolution, total calls, tokens, cost per successful resolution and elapsed time.
+It compares three cold arms under the same tools, graders and resource limits.
+It measures controlled context utility; three tasks cannot establish adoption,
+savings or a general quality improvement.
+
+The plan is not frozen or approved. Publishing or merging it authorizes no model
+calls, index ingestion or paid benchmark. No live result is reported here.
+
+## Implementation and tasks
+
+The [factory implementation](https://github.com/ClickHouse/loom/pull/1050) supplies
+offline replay, a bounded controller, injected provider/SDK bindings, authored
+host behavioral checks, attempt accounting and paired analysis. A qualified
+live driver and deployment-specific evidence remain prerequisites.
+The example's offline replay fixtures are separate from the historical pilot.
+
+Use the three historical cases in the implementation's
+[`historical-candidates.json`](https://github.com/ClickHouse/loom/blob/feat/flask-software-factory/examples/software_factory/historical-candidates.json):
+`pallets__flask-4045`, `pallets__flask-4575` and `pallets__flask-4935`.
+Each task pins its exact public source base and dependency image digest. The
+imported official test selectors are diagnostic inputs: candidate Python controls
+its own test process, exit status and reports, so those reports cannot authorize
+a passing final grade. Retain all failures. Do not replace tasks or choose the
+best attempt after observing results.
+
+The proposed objective grader uses narrow authored public-behavior probes:
+dotted blueprint names, redirect method/delegation/override, and nested
+subdomains. The sandbox returns bounded primitive observations; evaluator-owned
+assertions and the final verdict stay outside candidate mounts. This coverage is
+not equivalent to the imported official selectors. The final protocol must
+explicitly choose this coverage and freeze its probe seed, bridge and assertions.
+
+Before running, independently verify passing visible neighbors on the base, a
+failing target check on the base, and passing target/neighbors with the reference
+on every exact image. Candidate syntax/import crashes or malformed output remain
+failed checks so revision can continue; infrastructure, state or cleanup faults
+invalidate grading. Recheck forgery, source-write and output-limit controls.
+Imported receipts and image identity alone do not qualify another grading path.
+
+## Arms and schedule
+
+| Arm | Application behavior | Agent exposure |
+| ------------ | ------------------------------------------------------------------------------------------- | --------------------------------------------- |
+| Baseline | No context client construction or retrieval | No Loom schema, instructions or hooks |
+| Orchestrated | Exact intake lookup, impact before changed-source verification, failure retrieval as needed | Ordinary source tools; no selected-call quota |
+| Natural | No automatic context hooks | Optional exact lookup with zero minimum calls |
+
+All arms share the same provider/model, native response handling, source tools,
+objective graders and per-attempt limits. Only retrieved context and its resulting
+trajectory may differ. The treatment cannot change the source base, hidden tests,
+prices, schedule, provider or retained attempts.
+
+Use 3 tasks × 3 paired repeats × 3 arms = 27 primary attempts. Add 3 tasks × 2
+baseline A/A copies = 6 reference attempts, for 33 attempts total. The 15 baseline
+attempts allow zero Loom requests. All attempts start cold; no cross-task memory
+writes, warm reuse or chronological learning is part of this pilot.
+
+The [proposed schedule](software-factory-schedule.json) uses seed 741 and persists
+all 33 slots before calls. Its `schedule_sha256` covers the canonical attempt
+list. Freeze this order with the final protocol; a seed reproduces the schedule
+and analysis, not the model's responses. Retain failures, nonuse and budget stops
+without replacement attempts, automatic retries or post-hoc exclusions.
+
+## Proposed limits
+
+| Resource | Per attempt | Whole primary and A/A cohort |
+| ------------------------------ | ---------------------------------------------------------- | ---------------------------- |
+| Generation requests | 12 | 396 |
+| Input tokens | 20,000 per generation request, subject to a verified bound | 7,920,000 |
+| Output tokens | 2,048 per generation request | 811,008 |
+| Agent tools | 30 | 990 |
+| Logical Loom reads | 6 in each context arm; zero in baseline | 108 |
+| Physical Loom HTTP requests | 18 in each context arm; zero in baseline | 324 |
+| Serialized transcript | 64,000 characters per generation request | Enforced on every request |
+| Accepted context | 12,000 characters total | Enforced on every attempt |
+| Visible tests | 3 invocations, 30 seconds each | No replacement runs |
+| Independent final hidden grade | 1 invocation, 30 seconds | No model judge |
+| Agent policy deadline | 180 seconds | Serial bounded attempts |
+| Hard controller deadline | 210 seconds, including hidden grading | Retain interrupted attempts |
+
+The physical Loom cap assumes one retrieval and two single-request scope checks
+for each logical read. Auth, discovery, retries, failed dispatches and any extra
+checks consume the same cap. Stop before another physical request would exceed
+it; additional traffic requires a revised protocol and approval.
+
+The generation request cap excludes a token-counting service. If a verified
+counting mechanism needs network requests, freeze a separate ceiling of at most
+396 counting requests, their endpoint, latency and cost before approval. Do not
+silently replace an unsupported counting API or treat characters as token counts.
+The proposed 20,000-input-token bound remains unqualified.
+
+After stopping a controller, reconcile at most four recorded, owned containers.
+Each has a 10-second inspection limit and a 10-second removal limit, for at most
+80 seconds of additional cleanup. Record end-to-end elapsed time including setup,
+independent grading and cleanup. Incomplete cleanup halts the cohort. A timeout
+or unresolved in-flight request remains a failure with unknown usage.
+
+## Provider and spending freeze
+
+Use one exact model through a direct Converse provider, with existing authorized
+configuration, standard inference, no temperature default and no explicit cache
+checkpoints. Preserve native reasoning blocks. Freeze its exact model identifier,
+region, endpoint, API behavior and complete dependency hashes before approval.
+Do not introduce an alternate gateway, provider or credential route to complete a
+run. No infrastructure, permission or credential changes are authorized here.
+
+The working price assumption is $2.20 per million input tokens and $11 per million
+output tokens. These assumptions require account-specific verification for the
+exact model, region, inference class and cache semantics. They are not a promise
+of current pricing or a complete bill.
+
+At the proposed token caps, generation reserves at most
+`7,920,000 / 1,000,000 × 2.20 + 811,008 / 1,000,000 × 11 = $26.345088`.
+The proposed total ceiling is **$30**, conditional on bounding all counting,
+server, transport, auth, cache and infrastructure overhead within the remaining
+**$3.654912**. Unknown overhead is unknown, not zero. If verified token bounds or
+all-in costs do not fit, revise the plan before requesting approval.
+
+No dollar amount in this draft authorizes spending. Freeze the final protocol
+digest, schedule, dependency locks, price table and whole-run reservation, then
+obtain actual owner approval referencing that digest and ceiling. Approval of
+benchmark intent or of a PR does not replace that approval.
+
+## Qualification required before the first request
+
+1. Pin the merged server/SDK integration and factory controller commits. Check the
+ actual integration and its required CI evidence separately.
+2. Freeze public task inputs, the host probe seed and assertions, observation
+ bridge, source allowlists, tool schemas, prompts, runtime locks, controller and
+ trusted worker hashes. Keep evaluator assertions, reference fixes and
+ credentials outside agent access. Official test reports remain diagnostic.
+3. Qualify a source-only checkout per attempt, with no Git history, future
+ objects, sibling mounts, network or credential access. Candidate code runs in
+ an isolated focused grader. Verify traversal, symlink, import, subprocess and
+ egress isolation. Export only allowlisted implementation edits into a separate
+ independent final grader; preserve evaluator tests and runner configuration.
+4. Use a private server and database owned by this pilot; never reuse a production
+ server. Supply authorized immutable index scopes for all three exact source
+ bases using reader credentials. Use exact retrieval only, with no embeddings,
+ conceptual search or model enrichment. Verify repository, full commit, server build,
+ permissions and every required index tier before and after reads. External
+ immutability evidence is mandatory; matching watermarks alone are insufficient.
+ Restricted zero counts mean unknown. No index creation or grants are implied.
+5. Qualify the actual controller/worker and client transport paths, hard deadlines,
+ durable pre-dispatch reservations and cleanup. Baseline constructs no context
+ client. Instrument auth and metadata side traffic or refuse it. Failed or
+ interrupted attempts retain their reservations and require reconciliation.
+6. Verify the input-token bound and complete usage/pricing semantics. Join client
+ request IDs to model and server billing evidence. Count failed and retried
+ physical dispatches. Never record credentials or arbitrary response headers.
+7. Obtain exact protocol and total-spend approval after all evidence exists.
+ Refuse inference when a required field or receipt is missing.
+
+Offline contracts, stubbed transports, scripted replay and proposed schedules
+are preparation evidence. They establish no live model resolution, complete
+billing, index authorization or spending permission.
+
+## Measurement and analysis
+
+Retain every scheduled attempt and its independent objective result, invalid-run
+reason, source and patch hashes, provider/index provenance, failures, nonuse,
+abstentions and stale, repeated or empty contexts. Separate accepted and failed
+calls, host-selected and agent-selected calls, logical reads, physical dispatches
+and retries. Avoid counting an agent-selected Loom call twice in tool totals.
+
+Keep raw input, output and cache usage, priced and unknown cost, component latency
+and total elapsed time. Cost per successful resolution includes failed attempts;
+zero successes has no finite estimate. Unknown usage or pricing suppresses an
+all-in cost estimate. Whole-cohort cost includes A/A references.
+
+Pair by task and repeat. Average repeats within each task and use seed 741 for
+paired bootstrap intervals that resample task clusters with arms kept together.
+Report A/A variation separately. Missing attempts remain visible and suppress
+partial-cohort intervals. Three task clusters support exploratory intervals,
+with no significance, percentage-gain, general adoption or savings claim.
+
+Freeze original outputs before fixing any observed failure. Diagnose a concrete
+pattern, add a focused regression, fix the smallest cause and compare under a
+preserved equivalent protocol. Never tune against hidden solutions. Any rerun
+needs its own reserved budget and approval; it is not a free replacement attempt.
diff --git a/docs/benchmarks/software-factory-schedule.json b/docs/benchmarks/software-factory-schedule.json
new file mode 100644
index 00000000000..0df8f42ac3e
--- /dev/null
+++ b/docs/benchmarks/software-factory-schedule.json
@@ -0,0 +1,238 @@
+{
+ "status": "PROPOSED_NOT_APPROVED",
+ "seed": 741,
+ "attempts": [
+ {
+ "order": 0,
+ "task_id": "pallets__flask-4575",
+ "repeat": 1,
+ "arm": "natural",
+ "mode": "natural"
+ },
+ {
+ "order": 1,
+ "task_id": "pallets__flask-4575",
+ "repeat": 1,
+ "arm": "baseline",
+ "mode": "baseline"
+ },
+ {
+ "order": 2,
+ "task_id": "pallets__flask-4575",
+ "repeat": 1,
+ "arm": "orchestrated",
+ "mode": "orchestrated"
+ },
+ {
+ "order": 3,
+ "task_id": "pallets__flask-4935",
+ "repeat": "aa",
+ "arm": "baseline-a",
+ "mode": "baseline"
+ },
+ {
+ "order": 4,
+ "task_id": "pallets__flask-4935",
+ "repeat": "aa",
+ "arm": "baseline-b",
+ "mode": "baseline"
+ },
+ {
+ "order": 5,
+ "task_id": "pallets__flask-4575",
+ "repeat": "aa",
+ "arm": "baseline-b",
+ "mode": "baseline"
+ },
+ {
+ "order": 6,
+ "task_id": "pallets__flask-4575",
+ "repeat": "aa",
+ "arm": "baseline-a",
+ "mode": "baseline"
+ },
+ {
+ "order": 7,
+ "task_id": "pallets__flask-4045",
+ "repeat": 1,
+ "arm": "natural",
+ "mode": "natural"
+ },
+ {
+ "order": 8,
+ "task_id": "pallets__flask-4045",
+ "repeat": 1,
+ "arm": "orchestrated",
+ "mode": "orchestrated"
+ },
+ {
+ "order": 9,
+ "task_id": "pallets__flask-4045",
+ "repeat": 1,
+ "arm": "baseline",
+ "mode": "baseline"
+ },
+ {
+ "order": 10,
+ "task_id": "pallets__flask-4575",
+ "repeat": 2,
+ "arm": "natural",
+ "mode": "natural"
+ },
+ {
+ "order": 11,
+ "task_id": "pallets__flask-4575",
+ "repeat": 2,
+ "arm": "baseline",
+ "mode": "baseline"
+ },
+ {
+ "order": 12,
+ "task_id": "pallets__flask-4575",
+ "repeat": 2,
+ "arm": "orchestrated",
+ "mode": "orchestrated"
+ },
+ {
+ "order": 13,
+ "task_id": "pallets__flask-4045",
+ "repeat": "aa",
+ "arm": "baseline-a",
+ "mode": "baseline"
+ },
+ {
+ "order": 14,
+ "task_id": "pallets__flask-4045",
+ "repeat": "aa",
+ "arm": "baseline-b",
+ "mode": "baseline"
+ },
+ {
+ "order": 15,
+ "task_id": "pallets__flask-4045",
+ "repeat": 2,
+ "arm": "baseline",
+ "mode": "baseline"
+ },
+ {
+ "order": 16,
+ "task_id": "pallets__flask-4045",
+ "repeat": 2,
+ "arm": "natural",
+ "mode": "natural"
+ },
+ {
+ "order": 17,
+ "task_id": "pallets__flask-4045",
+ "repeat": 2,
+ "arm": "orchestrated",
+ "mode": "orchestrated"
+ },
+ {
+ "order": 18,
+ "task_id": "pallets__flask-4935",
+ "repeat": 1,
+ "arm": "orchestrated",
+ "mode": "orchestrated"
+ },
+ {
+ "order": 19,
+ "task_id": "pallets__flask-4935",
+ "repeat": 1,
+ "arm": "natural",
+ "mode": "natural"
+ },
+ {
+ "order": 20,
+ "task_id": "pallets__flask-4935",
+ "repeat": 1,
+ "arm": "baseline",
+ "mode": "baseline"
+ },
+ {
+ "order": 21,
+ "task_id": "pallets__flask-4935",
+ "repeat": 0,
+ "arm": "baseline",
+ "mode": "baseline"
+ },
+ {
+ "order": 22,
+ "task_id": "pallets__flask-4935",
+ "repeat": 0,
+ "arm": "natural",
+ "mode": "natural"
+ },
+ {
+ "order": 23,
+ "task_id": "pallets__flask-4935",
+ "repeat": 0,
+ "arm": "orchestrated",
+ "mode": "orchestrated"
+ },
+ {
+ "order": 24,
+ "task_id": "pallets__flask-4045",
+ "repeat": 0,
+ "arm": "natural",
+ "mode": "natural"
+ },
+ {
+ "order": 25,
+ "task_id": "pallets__flask-4045",
+ "repeat": 0,
+ "arm": "orchestrated",
+ "mode": "orchestrated"
+ },
+ {
+ "order": 26,
+ "task_id": "pallets__flask-4045",
+ "repeat": 0,
+ "arm": "baseline",
+ "mode": "baseline"
+ },
+ {
+ "order": 27,
+ "task_id": "pallets__flask-4935",
+ "repeat": 2,
+ "arm": "natural",
+ "mode": "natural"
+ },
+ {
+ "order": 28,
+ "task_id": "pallets__flask-4935",
+ "repeat": 2,
+ "arm": "orchestrated",
+ "mode": "orchestrated"
+ },
+ {
+ "order": 29,
+ "task_id": "pallets__flask-4935",
+ "repeat": 2,
+ "arm": "baseline",
+ "mode": "baseline"
+ },
+ {
+ "order": 30,
+ "task_id": "pallets__flask-4575",
+ "repeat": 0,
+ "arm": "natural",
+ "mode": "natural"
+ },
+ {
+ "order": 31,
+ "task_id": "pallets__flask-4575",
+ "repeat": 0,
+ "arm": "orchestrated",
+ "mode": "orchestrated"
+ },
+ {
+ "order": 32,
+ "task_id": "pallets__flask-4575",
+ "repeat": 0,
+ "arm": "baseline",
+ "mode": "baseline"
+ }
+ ],
+ "schedule_sha256": "83f5ba7bc0fd54fc6c5cd75326cbd91e5b2755d7cb8537d3268220496e8910e3"
+}
diff --git a/docs/blume.config.ts b/docs/blume.config.ts
index 72dd7400603..37132789dbb 100644
--- a/docs/blume.config.ts
+++ b/docs/blume.config.ts
@@ -1,29 +1,57 @@
+import react from "@astrojs/react";
import { defineConfig } from "blume";
import { vercel } from "blume/deploy";
+import { gettingStartedOverview } from "./lib/documentation-routes.mjs";
+import { publisher, siteDescription, siteUrl, website } from "./lib/site-identity.mjs";
export default defineConfig({
- title: "ClickHouse Loom",
+ title: website.name,
+ integrations: [
+ react(),
+ {
+ name: "click-ui",
+ hooks: {
+ "astro:config:setup": ({ updateConfig }) => {
+ updateConfig({ vite: { resolve: { noExternal: ["@clickhouse/click-ui"] } } });
+ },
+ },
+ },
+ ],
logo: {
image: "/loom.svg",
- text: "ClickHouse Loom",
+ text: website.name,
},
- description:
- "Self-hosted MCP server that gives AI agents shared long-term memory, document search with citations, and a code index stored in ClickHouse.",
+ description: siteDescription,
deployment: vercel({
- site: "https://loom.clickhouse.com",
+ site: new URL(siteUrl).origin,
base: "/docs",
}),
content: {
root: ".blume-content",
include: ["**/*.{md,mdx}"],
},
+ seo: {
+ sitemap: { alternates: true },
+ jsonLd: {
+ websiteId: website["@id"],
+ organizationId: publisher["@id"],
+ },
+ },
+ lastModified: "frontmatter",
+ export: { pdf: true },
agents: {
+ llmsTxt: {
+ details:
+ "Use the [MCP installation runbook](https://loom.clickhouse.com/docs/llms-install.md) to install Loom for Cline or another MCP client.\n\n" +
+ "Use the [coding-agent memory selector](https://loom.clickhouse.com/agent-memory-selector) to compare memory setups and copy an evaluation checklist.",
+ },
mcp: {
enabled: true,
},
},
i18n: {
defaultLocale: "en",
+ fallbackLocale: null,
locales: [
{ code: "en", label: "English" },
{ code: "es", label: "Español" },
@@ -34,22 +62,61 @@ export default defineConfig({
],
},
theme: {
- mode: "light",
- accent: "#ffcc00",
- action: "#ffcc00",
- background: { light: "#ffffff", dark: "#181818" },
+ mode: "dark",
+ toggle: false,
+ accent: "#faff69",
+ action: "#faff69",
+ background: "#1f1f1c",
radius: "sm",
},
+ search: {
+ popular: [
+ { label: "Install Loom", href: "/getting-started/quickstart", icon: "terminal" },
+ { label: "Connect a coding agent", href: "/getting-started/connect-a-coding-agent", icon: "plug" },
+ { label: "Deploy for a team", href: "/operations/deployment", icon: "server" },
+ { label: "Find an API operation", href: "/reference/operations", icon: "code-2" },
+ ],
+ },
navigation: {
tabs: [
- { label: "Get started", path: "/getting-started" },
- { label: "Guides", path: "/guides" },
- { label: "Features", path: "/features" },
- { label: "Reference", path: "/reference" },
- { label: "Operations", path: "/operations" },
+ {
+ label: {
+ en: "Get started",
+ es: "Comenzar",
+ ja: "はじめる",
+ ko: "시작하기",
+ "pt-BR": "Primeiros passos",
+ "zh-CN": "开始使用",
+ },
+ path: "/getting-started",
+ href: gettingStartedOverview,
+ },
+ {
+ label: { en: "Guides", es: "Guías", ja: "ガイド", ko: "가이드", "pt-BR": "Guias", "zh-CN": "指南" },
+ path: "/guides",
+ },
+ {
+ label: { en: "Features", es: "Funciones", ja: "機能", ko: "기능", "pt-BR": "Recursos", "zh-CN": "功能" },
+ path: "/features",
+ },
+ {
+ label: {
+ en: "Reference",
+ es: "Referencia",
+ ja: "リファレンス",
+ ko: "레퍼런스",
+ "pt-BR": "Referência",
+ "zh-CN": "参考",
+ },
+ path: "/reference",
+ },
+ {
+ label: { en: "Operations", es: "Operación", ja: "運用", ko: "운영", "pt-BR": "Operação", "zh-CN": "运维" },
+ path: "/operations",
+ },
],
sidebar: {
- display: "group",
+ display: "page",
},
},
github: {
diff --git a/docs/components.ts b/docs/components.ts
new file mode 100644
index 00000000000..afcf44395b0
--- /dev/null
+++ b/docs/components.ts
@@ -0,0 +1,13 @@
+import { defineComponents } from "blume";
+import Breadcrumbs from "./components/DocsBreadcrumb.astro";
+import Footer from "./components/DocsFooter.astro";
+import DocsLandingSearch from "./components/DocsLandingSearch.astro";
+import Logo from "./components/DocsLogo.astro";
+import Pagination from "./components/DocsPagination.astro";
+import Search from "./components/DocsSearch.astro";
+import TableOfContents from "./components/DocsOutline.astro";
+
+export default defineComponents({
+ layout: { Breadcrumbs, Footer, Logo, Pagination, Search, TableOfContents },
+ mdx: { DocsLandingSearch },
+});
diff --git a/docs/components/AdoptionActivity.astro b/docs/components/AdoptionActivity.astro
new file mode 100644
index 00000000000..a710e142d5e
--- /dev/null
+++ b/docs/components/AdoptionActivity.astro
@@ -0,0 +1,63 @@
+---
+import { activityPoints, type ChartGrain } from "../lib/adoption-chart-series.mjs";
+import AdoptionMetricPair from "./AdoptionMetricPair.astro";
+
+interface Props {
+ rows: {
+ period: string;
+ operations: number;
+ active: number;
+ days_reported: number;
+ complete_days_reported?: number;
+ current: boolean;
+ active_accounts?: number | null;
+ accounts_days_reported?: number;
+ }[];
+ grain: ChartGrain;
+ rangeStart?: string;
+ rangeEnd?: string;
+ view: "activity" | "accounts" | "requests";
+ firstAccountReport?: string;
+}
+
+const { rows, grain, rangeStart, rangeEnd, view, firstAccountReport } = Astro.props;
+const accountPoints = activityPoints(rows, "active_accounts", grain, "accounts_days_reported");
+---
+
+{view === "activity" && (
+
+)}
+{view === "requests" && (
+
+)}
+{view === "accounts" && (
+
+ )}
diff --git a/docs/components/AdoptionDomainDirectory.astro b/docs/components/AdoptionDomainDirectory.astro
new file mode 100644
index 00000000000..266629d82c5
--- /dev/null
+++ b/docs/components/AdoptionDomainDirectory.astro
@@ -0,0 +1,214 @@
+---
+import { Button } from "@clickhouse/click-ui/Button";
+import { InputElement, InputWrapper } from "@clickhouse/click-ui/InputWrapper";
+import { Panel } from "@clickhouse/click-ui/Panel";
+import { Table } from "@clickhouse/click-ui/Table";
+import { Text } from "@clickhouse/click-ui/Text";
+import { Title } from "@clickhouse/click-ui/Title";
+import AdoptionState from "./AdoptionState.astro";
+
+interface DomainActivity {
+ active_accounts: number | null;
+ successful_requests: number;
+ active_installations: number;
+ day: string | null;
+ loom_version: string | null;
+ clickhouse_versions?: [string, string][];
+ postgres_versions?: [string, string][];
+ first_seen: string | null;
+ last_seen: string | null;
+}
+
+interface Props {
+ names: string[] | null;
+ ranked: boolean;
+ metrics?: Record;
+ days: number;
+ fallback: boolean;
+ path: string;
+ state: Record;
+}
+
+const { names, ranked, metrics = {}, days, fallback, path, state } = Astro.props;
+const pageSize = 12;
+const query = String(state.domain_q ?? "");
+const byName = state.domain_sort === "name";
+const searched = query.toLowerCase();
+const matching = (names ?? []).filter((domain) => domain.toLowerCase().includes(searched));
+if (byName)
+ matching.sort((left, right) => Number(left === "-") - Number(right === "-") || left.localeCompare(right, "en"));
+const lastPage = Math.max(1, Math.ceil(matching.length / pageSize));
+const page = Math.min(lastPage, Math.max(1, Number(state.domain_page) || 1));
+const offset = (page - 1) * pageSize;
+const displayed = matching.slice(offset, offset + pageSize);
+const number = new Intl.NumberFormat("en-US");
+const date = new Intl.DateTimeFormat("en", { month: "short", day: "numeric", year: "numeric", timeZone: "UTC" });
+const total = names?.length ?? 0;
+const formatted = (value?: number | null) => (value == null ? "—" : number.format(value));
+const day = (value?: string | null) => (value ? date.format(Date.parse(value)) : "—");
+const databaseVersions = (pairs?: [string, string][]) =>
+ pairs
+ ?.map(([hosting, version]) => {
+ const label = hosting === "cloud" ? "Cloud" : hosting === "oss" ? "OSS" : "";
+ return [label, version].filter(Boolean).join(" ");
+ })
+ .join(", ") || "—";
+const anchor = "#reported-contact-domains";
+const action = path + anchor;
+const refreshParams = new URLSearchParams(Object.entries(state).map(([key, value]) => [key, String(value)]));
+const headers = [
+ {
+ label: "Domain",
+ scope: "col" as const,
+ overflowMode: "wrap" as const,
+ width: "18%",
+ "aria-sort": byName || !ranked ? ("ascending" as const) : undefined,
+ },
+ { label: "Successful requests", scope: "col" as const, overflowMode: "wrap" as const },
+ { label: "Active users", scope: "col" as const },
+ { label: "Active installations", scope: "col" as const, overflowMode: "wrap" as const },
+ { label: "Loom version", scope: "col" as const },
+ { label: "ClickHouse", scope: "col" as const, overflowMode: "wrap" as const },
+ { label: "Postgres", scope: "col" as const, overflowMode: "wrap" as const },
+ { label: "First seen", scope: "col" as const },
+ { label: "Last active", scope: "col" as const },
+];
+---
+
+
+
+ {names === null ? (
+ Domain reporting is unavailable for this period.
+ ) : total === 0 ? (
+ No installations reported activity in this period.
+ ) : (
+
+ Each installation counts under one reported domain, including personal email domains. Installations with one company domain alongside personal addresses count under the company domain. The — row contains unassigned activity. Requests include live activity reported today. User counts and versions use the latest measured or active UTC day for each row.
+
+ What teams use
+ {usageOptions.some(hasUsagePoints) && }
+
+
+
+ {Number.isFinite(summary?.[selectedUsage.value]) &&
+ {showCount(summary[selectedUsage.value])} {selectedUsage.value.startsWith("median_") ? "median in this window" : "in this window"}
+ }
+
+
+
+
+ {hasLifecycle && (
+
+
+
+ New and returning activity
+ Compare complete UTC periods using successful Loom requests.
+
+
+ How lifecycle is counted
+ New means first observed at the selected threshold. Retained means active in both periods. Reactivated means active again after a gap. Became inactive means active in the prior period only.
+ Net change adds new and reactivated activity and subtracts those that became inactive. Weekly cutoffs use 7/30 of the monthly threshold. A domain combines requests from all of its reporting installations.
+ Telemetry definitions
+
+
+ )}
+
+ {versionRows.length > 0 && (
+
+
Software versions
+ Active installations in the last 30 complete UTC days.
+