diff --git a/docs/api.md b/docs/api.md index 3c007e82..b5a93380 100644 --- a/docs/api.md +++ b/docs/api.md @@ -23,7 +23,7 @@ hit it. Not a settings key: changing it is a rebuild, deliberately. | `GET /api/graph/overview` | Scope-pure Louvain cluster supergraph ("landkarte"); reads precomputed scope-partitioned aggregates, gated on `graph_overview.enabled` (off → 404). Read-only, no LLM. | | `GET /api/graph/cluster` | Cluster ego: the members + neighbour topics of ONE topic handle (see [Cluster ego](#cluster-ego-get-apigraphcluster)). Double-gated on `graph_overview.enabled` **and** `cluster.route_enabled` (both default off → 404, indistinguishable from an absent route). | | `POST /api/synthesize/daily` | Manual trigger of the daily synthesis (Tagesbericht) for the caller's `home_scope` — the same `GenerateDailyReport` path the 03:00 scheduler iteration runs (digest role, constant internal). Concurrency cap 1 per principal (429 fail-fast), dispatch-interactive (429 + `Retry-After` on capacity rejection). Optional `?date=YYYY-MM-DD` (M103) re-synthesizes the report titled that day over its historical window `[date-1 03:00 UTC, date 03:00 UTC)` — the backfill path; the `(category, title, scope)` upsert replaces the old report in place (same block id, embedding regenerates). A malformed date, a window that has not closed yet, or — with `scheduler.writelog_retention_days` set — a window that starts before the write-log horizon or before the eviction boundary the retention recorded on any earlier run, whatever the setting is now (its guard and dream decisions are deleted, and the replacement would lack them; issue #277) ⇒ 400; a boundary the server cannot read ⇒ 500. `{ok, block_id, scope[, date][, reason:"no_activity"]}`. The report language follows the hot `dream.language` setting, read per request: empty (default) keeps the German surface this row describes, any other tag localizes **title and tag together** (`Daily Report ` / `daily-report`) — so a change **starts a new series** instead of continuing the old one, and a backfill after the switch writes a second block for a day that already has a `Tagesbericht`. Deliberate and operator-triggered; see [`CTX_DREAM_LANGUAGE`](operations.md#environment-variables). | -| `GET /api/whoami` | Calling key's identity: `label`, `home_scope`, `read_scopes`, the server-global `admin` tier flag, plus the Model-C tenant identity `tenant_id` + per-tenant `role` (`owner`/`admin`/`member`), and the feature-flag bag `capabilities` (`{workflow: true}` since v4.3.0 — switches the SPA's issues/board surface visible; the field is data, so a later per-tenant gate only changes the value, not the SPA). `capabilities.model_api` carries the gateway policy as data, read per request from the `_global` settings: `{enabled, self_service, key_max_lifetime_s, rotation_grace_s, expiry_warn_s}` = `gateway.enabled`, `gateway.tenant_self_service`, `gateway.key_max_lifetime_app`, `gateway.key_rotation_grace`, `gateway.key_expiry_warn` (durations in whole seconds; the peer lifetime is not carried). Every authenticated caller receives it — server policy, no secret; the SPA derives two capabilities from it, `viewModelApi` and `mintModelKeys`, for the gateway administration surface ([multi-tenancy](multi-tenancy.md#admin-tiers)), while the manage actions enforce their own tiers ([Model consumer administration](#model-consumer-administration)). The SPA login gate probes it, derives its read-only degradation from `admin`, and tells server-admin from tenant-admin. | +| `GET /api/whoami` | Calling key's identity: `label`, `home_scope`, `read_scopes`, the server-global `admin` tier flag, plus the Model-C tenant identity `tenant_id` + per-tenant `role` (`owner`/`admin`/`member`), and the feature-flag bag `capabilities` (`{workflow: true}` since v4.3.0 — switches the SPA's issues/board surface visible; the field is data, so a later per-tenant gate only changes the value, not the SPA). `capabilities.model_api` carries the gateway policy as data, read per request from the `_global` settings: `{enabled, self_service, key_max_lifetime_s, rotation_grace_s, expiry_warn_s}` = `gateway.enabled`, `gateway.tenant_self_service`, `gateway.key_max_lifetime_app`, `gateway.key_rotation_grace`, `gateway.key_expiry_warn` (durations in whole seconds; the peer lifetime is not carried). Every authenticated caller receives it — server policy, no secret; the SPA derives two capabilities from it, `viewModelApi` and `mintModelKeys`, for the gateway administration surface ([multi-tenancy](multi-tenancy.md#admin-tiers)), while the manage actions enforce their own tiers ([Model consumer administration](#model-consumer-administration)). The SPA login gate probes it, derives its read-only degradation from `admin`, and tells server-admin from tenant-admin. Four fields describe the write side and a narrowing: `write_scopes` (the effective write set, home scope first — under a narrowing its write scope alone, or `[]`), `confirm_writes`, `narrowed` (`{read, write}` of a [narrowed request](#scope-narrowing-per-request), `null` otherwise; under a narrowing `read_scopes` is that read set, `admin` is `false` and `role` is `member`), `rate_limit_write` (the write budget per key and 60 s that applies to this key: `query.rate_limit_write` after the settings overlay of the key's home scope, `0` = unlimited; an override set on another scope of the same tenant does not reach this key) and `scope_narrowing` (`optional` or `required`, the key's column; a key with `required` answers nothing unnarrowed but this route). | | `POST /api/manage` | CRUD, Guard API, stats, API-key management, block-type registry (see [manage actions](#manage-actions)). | | `GET /api/types[/{name}]` | Block-type registry reads: effective type list (`_global` ∪ your tenant) and single-type policy config, **member-gated** (any valid key) (see [Block-type registry](#block-type-registry)). | | `PUT\|DELETE /api/types/{name}` | Block-type registry writes (upsert/delete), **admin-or-tenant-admin-gated**: a tenant-admin writes its own tenant namespace, `_global` types are operator-only; DELETE 409s while referenced or on a builtin (see [Block-type registry](#block-type-registry)). | @@ -46,7 +46,7 @@ hit it. Not a settings key: changing it is a rebuild, deliberately. | `GET /api/project/events` | **Member** SSE domain-event stream (`text/event-stream`, workflow W9) for live board / issue-list updates. A key receives IDS-ONLY frames — `project` events `{kind, project_id, op, block_ids}` or the coalesced `{kind:"issues-bulk", project_id, count}`; NEVER title/content/body (the client refetches over the read API). Frames are **scope-filtered at the fan-out**: only the caller's readable project scopes, never another tenant's. Optional `?project_id=` pins the stream to one project (foreign/unknown ⇒ 404 uniform). Per-**tenant** connection cap (`project.events.max_connections`) → 429; `: ping` keepalive; a 10k-import burst collapses to one `issues-bulk` frame per tick (`project.events.flush_interval` / `coalesce_threshold`). In-stream re-auth recomputes the caller's scope tags from the FRESH read set every ~12 flush ticks: a revoked key or a tenant change ends the stream, and a revoked cross-tenant **scope grant** (tenant/role unchanged) drops that scope's frames — separate from the server-admin telemetry `/api/events`. | | `POST /api/digest` | Topic map generation. Rebuilds the linear topic map and — when `root_map.enabled` is on — also renders the **root map** (`root-map-`, cluster-per-line, capped at `root_map.budget_bytes`). It never starts a Louvain rebuild: the map is rendered from the cluster state that already exists, so the route cannot become a lever on a job bounded only by `graph_overview.rebuild_timeout`. Carries its own write rate-limit bucket (`digest`) since the root-map wave. Response gains `rootMapTitle` / `rootMapLength` **additively**; `title`, `blockCount`, `categoryCount` and `contentLength` keep their meaning, and the two corpus counts behind them now run under `root_map.count_timeout` (0 = not measured this round) instead of unbounded. The topic map is capped at 256 KiB (issue #518; [operations](operations.md#the-linear-topic-map-is-capped-at-256-kib)): below the cap it is unchanged, above it each category lists its first titles and the map says so in its text. The response carries, additively, `listedBlocks` — the blocks the map this request wrote lists by line, `0` when it wrote none (`digest.mode` stub or off, an empty window) — and `truncated`, `true` when that map leaves blocks out. Before the cap a window past about 60,000 blocks answered `500` on every call. | | `POST /api/ingest` | Obsidian vault ingestion. **Write scope:** `target_scope` names the scope every chunk of the request is written to and is resolved like `scope` on `POST /api/store`: absent or empty means the key's home scope, and a scope outside the key's writable scopes refuses the whole request with `403`, code `scope_denied` (`Cannot write to requested scope`), before a chunk is written and before the `ingest` bucket is booked. The field `scope` is **not read** on this route: `ctx ingest` through 5.48.2 sends it on every request, `"private"` unless the user named another scope, and the server never read it; honouring it would refuse those runs for every key whose home scope is not `private`, or move them into `private` where the key may write it. A `200` answer carries `scope`, the scope the request wrote to; a server without that field ignores `target_scope` and writes to the key's home scope. Chunk mode (`source_id` + `chunk_index`) needs a `context_sources` row in the scope the request writes to and never overwrites another scope's chunk — absent, foreign or foreign-held all fail the chunk as `source not found`. A chunk whose `(category, title, scope)` another active block holds fails as `another active block in this scope already has this category and title — choose another category or title` (issue #275; before, `insert chunk failed`). ctxd has no endpoint that creates `context_sources` rows; a chunk-mode client needs one created out of band with that `scope` (since 5.29.1 a source in any other scope fails every chunk). **Per-chunk failures do not change the status code:** the request answers `200` with `success: false`, `failed > 0` and `results[i].status = "failed"` plus `results[i].error` for each failed chunk, next to the ones that were `inserted`/`updated`/`skipped` — a client must read the body, not the status. Batch-wide refusals carry their own status (`400`/`413` validation, `403` reserved namespace or `scope_denied`, `429` rate limit). The request body is capped at 10 MB; a body whose JSON does not end within the cap is refused whole with `413`, `request body exceeds 10 MB cap`, before a chunk is written (before, it answered `400`, `Invalid request body`, like a malformed body). Chunk content runs the credentials detector; each accepted request books the `ingest` bucket against `query.rate_limit_write` (429 past it). A block-mode write (no `source_id`) runs the type classifier on title and metadata like `POST /api/store`; a block whose `type_source` is `'manual'` keeps its type. The registry snapshot is resolved once per request, so every block-mode chunk of a batch is classified against the same rules. A chunk answers `skipped` when its content matches the live `(category, title, scope)` row and either the write would change nothing or the matched row is not its `(source_id, chunk_index)` slot as `InsertChunk` writes it (a block-mode row, another source's chunk, a row in that slot whose `lifecycle_state` is no longer `chunk`, or a `source_id` that is not a UUID), because such a write cannot land; the no-op predicate merges request metadata while an actual chunk write replaces it, so same-slot subset metadata can answer `skipped`, and unnamed keys are dropped only when a chunk is written. Chunk-mode writes do not run the classifier; a new chunk row starts with the default type. A chunk write that replaces the slot's title or content keeps the chunk's vector marked stale until the backfill embeds the new text, in the transaction of the write; one that re-sends the same title and content (new tags or metadata only) keeps the vector current (issue #236). | -| `POST /api/blob/*` | Binary storage (store/fetch/search/manage). Write rejections additionally carry a machine-readable `"code"` (Gap-C6-c): the closed vocabulary is `unauthorized`, `invalid_body`, `missing_fields`, `invalid_sensitivity`, `invalid_encoding`, `scope_denied`, `size_cap`, `unknown_type`, `reserved_type`, `parent_required`, `unknown_parent`, `unknown_supersedes`, `unknown_block`, `supersedes_conflict`, `supersedes_not_allowed`, `reserved_category`, `reserved_metadata`, `provenance_protected`, `unknown_action`, `edit_mismatch`, `constraint`, `rate_limit`, `write_conflict`, `internal` — one code per rejection class across `/api/store`, `/api/blob/store` and the MCP `store` tool (there as `structuredContent.code`, the `Content[0].Text` prose is unchanged; a STAGED answer is deliberately uncoded — IsError plus code means refused, IsError without code means staged). Answers without a code keep their exact pre-existing envelope (no empty `code` key). `store` runs on its OWN write budget: `pool.blob_rate_limit_write` (tenant-overridable, default 10) per api key and 60-second window, counted over the separate `blob-write` action in `context_access_log` — a key at its `query.rate_limit_write` block-write limit may still upload, and uploads never consume the block budget. `0`/unset falls back to the VALUE of `query.rate_limit_write` (unlimited needs BOTH at 0). The budget is booked BEFORE the upsert, so a write that ends in a constraint violation still costs it; over budget ⇒ **429**. Each stored blob leaves one audit row referencing it through `context_access_log.blob_id`, which is intentionally unconstrained — the row survives the blob's deletion. **MCP transport (W02-8):** `blob_store` / `blob_fetch` run this same write path — required fields, name caps, base64 decode, the `writableBlockScopes` gate and the `blob-write` budget are ONE shared core (`handler/blob_core.go`), so both surfaces answer the identical code and the identical prose for the identical request. `blob_store` takes the payload as `file` (base64, same `invalid_encoding` verdict) **or** `text` (UTF-8) — exactly one of the two — and takes an optional **`scope`** (E-M4, superseding decision D4, like the `store` tool): absent ⇒ the calling key's `home_scope`, named ⇒ gated through the same `writableBlockScopes` formula the REST route uses, ahead of the budget (`scope_denied` / `Cannot write to requested scope`). A `confirm_writes` key gets the call **staged** (a `payload_hash` instead of an id, `IsError=true`, executed by `confirm`), and a payload above `pool.blob_stage_max_bytes` (tenant-overridable, default 1 MiB; `0` disables blob staging for such keys entirely) is **refused by name** rather than written direct. The budget is charged at stage time, so the confirm books nothing. `blob_fetch` reads a **byte range** of the stored payload (`offset`/`length`, default 262144, max 1048576; a larger `length` is refused, never clamped, so a short answer always means the blob ended) and names its `encoding` (`text` when the window is valid UTF-8, else base64); `meta_only` returns metadata alone. The REST fetch route is unchanged and still answers the whole blob in one piece. **Payload scan + read gate (W02-9):** the shared write core runs the same credentials detector the block path has used since G40 over the decoded payload, on both surfaces, and records the verdict in the blob's JSONB `metadata` (no new column, no migration). It is KIND-differentiated: a structured signal (PEM private-key header, JWT, AWS key id, vendor token prefix, high-entropy secret assignment) sets `metadata.sensitivity` to `credentials` plus `metadata.sensitivity_kind`, upgrade-only over a caller-supplied value; a generic high-entropy hit (64+ hex run, base64 blob) raises NOTHING and is recorded in `metadata.entropy_flags`, because on a payload those artefacts are the evidence a drill-down came for, not a secret. A payload that is not valid UTF-8, or larger than `pool.blob_scan_max_bytes` (tenant-overridable, default 16 MiB; `0` turns the scan off), is STORED with `metadata.sensitivity = "unscanned"` — the write goes through, so binary uploads and the blobs that predate this path are never collateral. A `confirm_writes` key is scanned at STAGE time, so the verdict rides inside the `payload_hash` and confirming cannot alter it. On the read side `blob_fetch` does NOT return the payload of a blob whose `metadata.sensitivity` is `credentials` (named refusal, uncoded like every other fetch refusal); `meta_only` still answers, and a missing or `unscanned` field reads as deliverable — a blob is withheld because something was found, never because nothing was looked for. Every `blob_fetch` answer that carries content is framed for a model context: `untrusted: true`, an `origin` naming blob id/category/title/scope, and a `note` that the bytes are data and not instructions; `meta_only` carries no frame. The REST fetch route keeps all of this OUT — it is an operator path, not a model context, and answers the whole payload of a credentials blob unchanged. **Blob-to-block edge (W02-10):** `context_blobs.context_block_id` finally has a write path. Both store surfaces take an optional `context_block_id` (REST body field, MCP tool field), and the third MCP tool **`blob_link`** `{id, context_block_id}` sets it afterwards in ONE indexed `UPDATE` — no payload on the wire, `file_size`/`checksum`/`updated_at` untouched, which is what makes the two-phase write of a checkpoint (payload first, manifest block second, link third) cost one payload round trip instead of two. A link is a WRITE: it books one `blob-write` row like a store, and the blob must lie in the caller's `writableBlockScopes` — outside them it is `blob not found`, the same answer an id that belongs to nothing gets. The referenced BLOCK must be visible in the caller's read scopes; a block in a foreign scope, an id that exists nowhere and a malformed id all answer `422` / `constraint` / `Referenced context_block_id not found`, byte-identically, so the write surface is no existence oracle over foreign scopes (letting the foreign key decide would have answered *success* for the foreign block and `23503` for the absent one, and built a cross-scope edge on the way). A re-`blob_store` without the field CLEARS the edge — the row is what the last write said. `blob_store`, `blob_fetch` and `blob_link` answer `context_block_id` only when it is set. A `confirm_writes` key gets `blob_link` **staged** like every other write (op `blob_link`, staged under the BLOB's own scope, budget charged at stage time), and the confirm re-validates both the scope and the block's visibility on the un-consumed row. Deleting the block leaves the blob alive with a NULL edge (`ON DELETE SET NULL`). | +| `POST /api/blob/*` | Binary storage (store/fetch/search/manage). Write rejections additionally carry a machine-readable `"code"` (Gap-C6-c): the closed vocabulary is `unauthorized`, `invalid_body`, `missing_fields`, `invalid_sensitivity`, `invalid_encoding`, `scope_denied`, `size_cap`, `unknown_type`, `reserved_type`, `parent_required`, `unknown_parent`, `unknown_supersedes`, `unknown_block`, `supersedes_conflict`, `supersedes_not_allowed`, `reserved_category`, `reserved_metadata`, `provenance_protected`, `unknown_action`, `edit_mismatch`, `constraint`, `rate_limit`, `write_conflict`, `internal`, and the three classes of a request's scope narrowing, `scope_narrowing_invalid`, `scope_narrowing_route` and `scope_narrowing_required` ([below](#scope-narrowing-per-request)) — one code per rejection class across `/api/store`, `/api/blob/store` and the MCP `store` tool (there as `structuredContent.code`, the `Content[0].Text` prose is unchanged; a STAGED answer is deliberately uncoded — IsError plus code means refused, IsError without code means staged). Answers without a code keep their exact pre-existing envelope (no empty `code` key). `store` runs on its OWN write budget: `pool.blob_rate_limit_write` (tenant-overridable, default 10) per api key and 60-second window, counted over the separate `blob-write` action in `context_access_log` — a key at its `query.rate_limit_write` block-write limit may still upload, and uploads never consume the block budget. `0`/unset falls back to the VALUE of `query.rate_limit_write` (unlimited needs BOTH at 0). The budget is booked BEFORE the upsert, so a write that ends in a constraint violation still costs it; over budget ⇒ **429**. Each stored blob leaves one audit row referencing it through `context_access_log.blob_id`, which is intentionally unconstrained — the row survives the blob's deletion. **MCP transport (W02-8):** `blob_store` / `blob_fetch` run this same write path — required fields, name caps, base64 decode, the `writableBlockScopes` gate and the `blob-write` budget are ONE shared core (`handler/blob_core.go`), so both surfaces answer the identical code and the identical prose for the identical request. `blob_store` takes the payload as `file` (base64, same `invalid_encoding` verdict) **or** `text` (UTF-8) — exactly one of the two — and takes an optional **`scope`** (E-M4, superseding decision D4, like the `store` tool): absent ⇒ the calling key's `home_scope`, named ⇒ gated through the same `writableBlockScopes` formula the REST route uses, ahead of the budget (`scope_denied` / `Cannot write to requested scope`). A `confirm_writes` key gets the call **staged** (a `payload_hash` instead of an id, `IsError=true`, executed by `confirm`), and a payload above `pool.blob_stage_max_bytes` (tenant-overridable, default 1 MiB; `0` disables blob staging for such keys entirely) is **refused by name** rather than written direct. The budget is charged at stage time, so the confirm books nothing. `blob_fetch` reads a **byte range** of the stored payload (`offset`/`length`, default 262144, max 1048576; a larger `length` is refused, never clamped, so a short answer always means the blob ended) and names its `encoding` (`text` when the window is valid UTF-8, else base64); `meta_only` returns metadata alone. The REST fetch route is unchanged and still answers the whole blob in one piece. **Payload scan + read gate (W02-9):** the shared write core runs the same credentials detector the block path has used since G40 over the decoded payload, on both surfaces, and records the verdict in the blob's JSONB `metadata` (no new column, no migration). It is KIND-differentiated: a structured signal (PEM private-key header, JWT, AWS key id, vendor token prefix, high-entropy secret assignment) sets `metadata.sensitivity` to `credentials` plus `metadata.sensitivity_kind`, upgrade-only over a caller-supplied value; a generic high-entropy hit (64+ hex run, base64 blob) raises NOTHING and is recorded in `metadata.entropy_flags`, because on a payload those artefacts are the evidence a drill-down came for, not a secret. A payload that is not valid UTF-8, or larger than `pool.blob_scan_max_bytes` (tenant-overridable, default 16 MiB; `0` turns the scan off), is STORED with `metadata.sensitivity = "unscanned"` — the write goes through, so binary uploads and the blobs that predate this path are never collateral. A `confirm_writes` key is scanned at STAGE time, so the verdict rides inside the `payload_hash` and confirming cannot alter it. On the read side `blob_fetch` does NOT return the payload of a blob whose `metadata.sensitivity` is `credentials` (named refusal, uncoded like every other fetch refusal); `meta_only` still answers, and a missing or `unscanned` field reads as deliverable — a blob is withheld because something was found, never because nothing was looked for. Every `blob_fetch` answer that carries content is framed for a model context: `untrusted: true`, an `origin` naming blob id/category/title/scope, and a `note` that the bytes are data and not instructions; `meta_only` carries no frame. The REST fetch route keeps all of this OUT — it is an operator path, not a model context, and answers the whole payload of a credentials blob unchanged. **Blob-to-block edge (W02-10):** `context_blobs.context_block_id` finally has a write path. Both store surfaces take an optional `context_block_id` (REST body field, MCP tool field), and the third MCP tool **`blob_link`** `{id, context_block_id}` sets it afterwards in ONE indexed `UPDATE` — no payload on the wire, `file_size`/`checksum`/`updated_at` untouched, which is what makes the two-phase write of a checkpoint (payload first, manifest block second, link third) cost one payload round trip instead of two. A link is a WRITE: it books one `blob-write` row like a store, and the blob must lie in the caller's `writableBlockScopes` — outside them it is `blob not found`, the same answer an id that belongs to nothing gets. The referenced BLOCK must be visible in the caller's read scopes; a block in a foreign scope, an id that exists nowhere and a malformed id all answer `422` / `constraint` / `Referenced context_block_id not found`, byte-identically, so the write surface is no existence oracle over foreign scopes (letting the foreign key decide would have answered *success* for the foreign block and `23503` for the absent one, and built a cross-scope edge on the way). A re-`blob_store` without the field CLEARS the edge — the row is what the last write said. `blob_store`, `blob_fetch` and `blob_link` answer `context_block_id` only when it is set. A `confirm_writes` key gets `blob_link` **staged** like every other write (op `blob_link`, staged under the BLOB's own scope, budget charged at stage time), and the confirm re-validates both the scope and the block's visibility on the un-consumed row. Deleting the block leaves the blob alive with a NULL edge (`ON DELETE SET NULL`). | | `POST /api/img/sign` | Camo image-proxy **mint**, **auth-gated** + per-key rate-limited. Body `{urls:[…], origin:"assistant"}` ⇒ `{signatures:{url → "/api/img/?url=…&exp=…"}}`; non-proxiable URLs (relative, `data:`, `mailto:`, a query string, userinfo, an escaped path over 512 bytes) are omitted. `origin` is `assistant` (also the default when absent); any other value is **400**, including `issue`, which pre-upgrade bundles sent for issue markdown. One distinct URL per request; more is **400**. The SPA renderer has no signing secret, so it asks the server to sign the one foreign image URL the viewer clicked (see [Camo image proxy](#camo-image-proxy)). Off (404) unless `CTX_CAMO_ENABLED`. | | `GET /api/img/{sig}` | Camo image-proxy **fetch**, **unauthenticated** — a browser `` carries no api key, so the HMAC-SHA256 signature (over `url`+`exp`, keyed by a labeled subkey of `CTX_SECRETS_KEY`) IS the capability. Verifies the sig BEFORE any upstream request (forged ⇒ **403**, expired ⇒ **410**, ZERO fetch either way), then fetches under an SSRF-guarded / redirect-hop-checked / size-capped / content-type-allowlisted policy (SVG excluded — XSS) and streams the bytes from `'self'` with `X-Content-Type-Options: nosniff` + immutable cache. Upstream failure ⇒ **502/415** + `no-store`, no substitute body. Re-hosts remote images so the SPA renders them under `img-src 'self'` WITHOUT widening the CSP, and the viewer's browser never talks to the foreign origin (see [Camo image proxy](#camo-image-proxy)). | | `POST /api/chat/stream` + `/api/chat/sessions[/{id}]` | Web-chat harness (see [Web chat sessions](#web-chat-sessions)). | @@ -55,6 +55,19 @@ hit it. Not a settings key: changing it is a rebuild, deliberately. | `GET /authorize` + `POST /token` | OAuth 2.1 authorization (PKCE) + token exchange. `GET /authorize` validates `client_id` and `redirect_uri` before it renders the consent screen (client name, `client_id`, redirect origin, warning for self-registered clients); the `POST` needs `consent=yes` besides `api_key` — without it no code is issued. `/token` enforces the client's registered `grant_types`: no `refresh_token` in the set → the code exchange returns the access token alone and the refresh grant is `400 unauthorized_client` (DCR default: `authorization_code` + `refresh_token`). | | `GET /` (unregistered paths) | Embedded admin SPA (Svelte 5 + Vite, served from the binary). History-API fallback answers HTML navigations (`Accept: text/html`) only — mistyped API URLs stay 404 for JSON clients. Hashed `/assets/*` are immutable-cached and pre-compressed (`.br`/`.gz`); binaries built without the frontend serve a 503 placeholder while all APIs stay functional. See [development](development.md#web-ui-svelte-5--typescript--vite-bun). | +### Scope narrowing per request + +A request can narrow its key's rights to scopes it names, for that one request (multi-tenancy: [Per-request scope narrowing](multi-tenancy.md#per-request-scope-narrowing)). The client chooses the narrowing; it shrinks what one request may do and never widens it — the boundary stays the key's scope set. `X-Context-Read-Scopes: ,,…` names 1 to 8 scopes, each one the key reads; the request reads those and nothing else — no other scope, no block grant —, in that order. `X-Context-Write-Scope: ` names the one scope the request writes: it must be one of the read scopes and one the key may write (`write_scopes` in whoami without a narrowing); without it the request writes nothing (`/api/store` answers `403 scope_denied`). Every answer of an accepted narrowing carries `X-Context-Narrowed: ;` — the read set as the request ran with it; a client that sent a narrowing and gets a 2xx answer without that header knows the narrowing was lost on the way. + +| Refusal | Status, code | +|---|---| +| `X-Context-Write-Scope` without `X-Context-Read-Scopes`; a header sent twice; an empty header or list element; a scope named twice; more than 8 read scopes | `400 scope_narrowing_invalid` | +| a read scope the key does not read; a write scope outside the read scopes or one the key cannot write | `403 scope_denied` | +| any route but `POST /api/query`, `POST /api/search`, `POST /api/store`, `GET /api/whoami`, `POST /api/manage` (method and path exactly); on `/api/manage` any action but `get` and `type-list`. A listed route spelled with percent escapes (`/api/%73earch`) matches no route and answers `404` before the authentication, with no data | `403 scope_narrowing_route` | +| a request without a narrowing by a key whose `scope_narrowing` is `required` (migration 198), on any route behind the API authentication but `GET /api/whoami` (the sign-in flows accept the key and mint credentials that carry the requirement, [multi-tenancy](multi-tenancy.md#required-narrowing-migration-198)) | `403 scope_narrowing_required` | + +These are decided before the route's handler runs (the `manage` action after the body is decoded, on the one action the dispatcher runs). A narrowed request is never an administration request: it runs as a `member` without the server-admin tier. The key's home scope stays its own — the backend chain, the quota and the settings overlay of a narrowed request are the key's, whatever scope the narrowing names first. A request without the headers runs as before. + ### The write budget of a single update `manage` `update` and the MCP `update` tool count an update that changes the block as one write of the key's write budget (`query.rate_limit_write`), as a store and an update item of a batch count (issue #519). The count and the booking run inside the update's transaction under the key's advisory lock — the one a batch takes —, so the booking commits with the write or not at all, and two updates of one key at the edge of the window get exactly what is left. The update takes that lock last, once it has written its row (an update that does not fit rolls its write back), and holds it until its commit; an update of a key whose budget is already used up is refused before its statement, by a count without the lock, so it writes no row version first: an update waiting for a row another transaction holds keeps no other write of the key waiting, and an update that changes nothing never waits for the lock. An update that does not fit writes nothing and answers `429`, code `rate_limit`, `Rate limit exceeded: max writes per 60 seconds` (MCP: `isError`, the same code and text). An update whose fields already hold what it sends — the batch's no-op test, `updated_at` aside — is still written as before but costs nothing and is not refused. A staged update (a `confirm_writes` key, the web chat's `ctx_update`) pays one write at stage time, in the stage's transaction, and its confirm books nothing; the web chat's staged `ctx_store` pays the same way. The internal writers (guard, dream, digest, forge sync, backfill) never pass through it. @@ -69,11 +82,13 @@ PostgreSQL stores a NUL character (U+0000) neither in text nor in JSON, so no va - **Blocks by id:** `get` (`id`: full UUID or unambiguous prefix) answers `{action, success, block, graph_visible}` for a live block of the caller's read scopes or one granted to its tenant; an unknown, foreign or archived id answers `{success:false, error:"Block not found"}` alike — so does an id or prefix with a character no block id carries (a prefix is lowercase hex digits and hyphens: `%` and `_` are not wildcards, invalid UTF-8 names no block, and a NUL is refused as in every request value, `400` naming the field, issue #519; a full id is a UUID in either case, and any other 36 characters of its shape name no block; issue #547), on every surface that takes an id prefix (`get`, `update`, `delete`, the MCP `get`, `update` and `archive` tools, an update item of a block batch). `delete` archives (`is_archived = true`, never a row delete) a block in a scope the key may write; a block grant gives no write access, and a block carrying a derived `provenance` is refused `403 provenance_protected`. **Reading an archived block** (issue #201): `get` with `include_archived: true` and the **full** block id also answers an archived block — from the key's own scopes only (home and allowed scopes; never through a block grant or a cross-tenant scope grant) — with `block.archived: true` and `graph_visible: false`; an id prefix with `include_archived` is a `400` before any lookup, and an unknown, foreign or granted archived id still answers `Block not found`. Without the field the answer is unchanged. The MCP `get` tool takes the same field, the MCP `archive` tool is `delete`'s twin, and the CLI sends the field with `ctx get --include-archived `. - **Part of a block (issue #407):** `get` takes `fields` (a list of keys of `block`: `id`, `category`, `tags`, `title`, `content`, `metadata`, `scope`, `sensitivity`, `sensitivity_source`, `type`, `lifecycle_state`, `type_source`, `untrusted`, `untrusted_origin`, `archived`, `created_at`, `updated_at`) and a content window, `content_offset` and `content_limit` (integers ≥ 0, counted in Unicode code points, never cutting inside one). With `fields`, `block` carries `id` and exactly the named keys, plus the marks `untrusted`, `untrusted_origin` and `archived` whenever they apply; the `content` and `metadata` columns are read from the database only when named. With the window, `block.content` is the cut — from `content_offset` (default 0), at most `content_limit` characters (default: to the end) — and `block` adds `content_length` (the whole content's length) and `content_truncated` (true when the content goes on after the window; the next window then starts at `content_offset + content_limit`); an offset past the end answers an empty, untruncated `content`. `action`, `success` and `graph_visible` stay around `block`. An unknown name (listed with the valid ones in the error), a value of the wrong type, a negative value, or a window beside a `fields` list without `content` is a `400` before any lookup; an empty list is the whole block, and a key sent as `null` counts as not sent. The projected `block` keeps the key order of the full answer, with `content_length` and `content_truncated` right after `content`. Visibility, the not-found answer, the ambiguous-prefix `matches`, `include_archived` and the read record are those of a full read, and a body without the three keys answers byte for byte as before. The MCP `get` tool takes the same options through the same function — see [MCP `get`](mcp.md#get). +- **Several blocks by id:** `get` with `ids` in place of `id` — a list of 1 to 16 ids, each a full UUID or an unambiguous prefix — answers `{action, success, blocks}` with one entry per asked id, in the order asked. The entry of a found block is the object a single `get` answers under `block` (`fields` and the content window apply to each entry). An id that names no block the caller sees is an entry `{id, code, error}` carrying the id as asked, never a failure of the whole request: code `not_found` with `error: "Block not found"` for an unknown, foreign, ungranted or archived id and for an id with a character no block id carries, alike; `invalid_id` for a prefix shorter than 8 characters; `ambiguous_id` with `matches` for a prefix of more than one visible block. Visibility is that of a single `get` — the read scopes plus the blocks granted to the tenant; under a narrowing ([Scope narrowing per request](#scope-narrowing-per-request)) the named scopes and no block grant. The blocks of all full ids are read with one database statement; a prefix costs the lookup a single `get` makes for it. The read record books each delivered block once and no miss. The answer carries no `graph_visible`. `ids` beside `id`, an empty list or more than 16 ids, a value that is not a list of strings (a `null` element included), and `include_archived` (which reads one block by its full id) are a `400` with code `invalid_body` before any lookup, as are the refusals of `fields` and the window beside `ids` (a single `get` answers those without a code); `ids` sent as `null` counts as not sent, and a body without `ids` answers byte for byte as before. The MCP `get` tool and the CLI's `ctx get` read one id. - **Block listing (issue #212):** `list-meta` answers `{action, success, blocks}`: every live block of the caller's read scopes without content (`id`, `title`, `category`, `tags`, `scope`, `type`, `lifecycle_state`, `type_source`, `updated_at`), ordered by `category, title, scope`, at most 10 000 per answer. It takes the `types` / `types_exclude` filters. An answer cut at 10 000 rows says so: it adds `truncated: true` and `next_after` (`{after_category, after_title, after_scope}`, the position of its last row); send that object back as `after` for the rows that follow (`{}` is the first page; any other value, another cursor's shape included, is a `400`). A complete answer carries neither key, as before. The position is a position only: each page applies the read scopes and filters of its own request. Until #212 the listing stopped at 10 000 rows and the answer looked complete; rows of one category and title in two scopes came in no defined order. - **Scope purge (hard delete, issue #202):** `purge` (tierTenantAdmin) removes block data inside **one** scope for good — the narrow counterpart of `tenant-delete`, for rows that should never have been written (a test or import run into a production tenant); `delete` only archives. `data`: `scope` (required) and optional filters, each of which narrows: `tags` (the block carries **every** listed tag; an empty list is no filter), `category`, `created_before` / `created_after` (RFC 3339, exclusive bounds on `created_at`), `archived_only`; and `keepalive` (below), which is no filter. No filter drains the scope. Unknown fields are `400`, so a misspelt filter cannot widen the purge. A tenant-admin reaches only the scopes its own tenant owns — another tenant's scope and an unknown one answer the same `404 scope not found`; a server-admin reaches every scope; an empty scope and the `_` system namespace are `400`; a key without an admin role is `403`, its home scope included. **Without `confirm_blocks` the call is a dry run** that deletes nothing and answers `{action, success, scope, filter, dry_run: true, as_of, counted: {blocks, cascaded_children, dream_links, blobs, derived_skipped, children_outside_scope, derived_children}, confirm_blocks}`. The real run sends `confirm_blocks` set to the dry run's `counted.blocks`: the purge counts again and deletes only when the number is unchanged (otherwise `409` with the fresh `counted`, nothing deleted), and it never touches a block or blob created after that count (`as_of`): a batch that would take the run past the confirmed number, or reach a child created after `as_of`, rolls back and ends the run with the same `409`. The confirmed run continues when the client disconnects or times out; its result is then in the server log (`manage: scope purged`) and a new dry run shows what is left. A client that waits gets the answer of a long run: the write deadline rolls while the purge works, so the answer is delivered past the server's 120 s write timeout with its status and body unchanged (issue #277). `keepalive: true` also writes one space every 25 s from the start, for a reverse proxy whose read timeout only bytes reset (nginx `proxy_read_timeout`, 60 s by default): the first space commits `200`, a refusal after it is that `200` with `success: false` and the error in the body (leading whitespace is valid JSON), and an answer within the first 25 s keeps its status and body. `ctx manage purge` waits for the answer without the CLI's 120 s timeout. What goes: the matching blocks; the blocks below them through `parent_id` (an issue's comments — `parent_id` cascades, so they count in `blocks` and separately in `cascaded_children`; a child in **another** scope refuses the run with `409`, see `children_outside_scope`, and so does a derivative below a matched block, see `derived_children` — the cascade would take it); every dream link that references one of them; and, only for a purge without any filter, the scope's blobs (a filter describes blocks — a filtered purge keeps the blobs and clears their link to a purged block). Rows that hang on a block by foreign key go or are cleared with it (temporal index, structural links, block grants, cluster membership, the embed-failure memo, the forge sync mapping — a synced project re-imports its issues on the next sync — and the block references of the access and write logs), and a surviving block that a purged block superseded is reconciled as `dream-link-resolve` does. A block carrying a derived `provenance` is never purged and is counted in `derived_skipped`. Context sources, chat sessions, secrets, keys and the scope itself stay. The run answers `dry_run: false`, `counted` and `deleted: {blocks, dream_links, blobs}`; it works in batches of 2 000 matched blocks plus their children, one transaction each (a batch that collides with a dream run — deadlock or serialization failure — is repeated up to three times), so an error after the first batch answers `500` (or the `409` above) with what was already `deleted` — a new dry run shows the rest. Each run that deletes anything writes one audit row before its first delete (`GET /api/audit?entity=scope_purge`, `entity_key` = the scope, `new_value` = filter, counts and `as_of`). REST and CLI only, no MCP tool: `ctx manage purge '' '{"scope":"…","tags":["…"]}'`, then the same with `"confirm_blocks":N`. Operator notes in [operations](operations.md#removing-rows-written-by-mistake-manage-purge). - **Backfill memo release (issue #236):** `embed-backfill-release` (tierTenantAdmin) drops regular embed-backfill failure memos (`context_embed_failures` rows with `migration_id` NULL) so the backfill takes their blocks again — after `embed_backfill.max_tokens` was raised, the embed backend moved to a larger context, or a backend outage ended; without it a parked block came back only through a change of its title or content. `data`: exactly one of `block_id` (a UUID) or `class` (`wire` or `oversize`), optional `limit` (the page size, at most and by default `1000`; a larger value is clamped), and `confirm_memos` together with `as_of`; unknown fields, a second selector, another class, a malformed id, a negative number and a `confirm_memos` without `as_of` (or the reverse) are `400`. A `caller_timeout` memo is never taken, not even by `block_id`: it is no park — the background arm takes such a block at once, and with the arm off the query path retries it after its hold —, and deleting it would hand the block back to the requests' `sync_budget` with its attempts restarted. A tenant-admin reaches the memos of blocks in its own tenant's scopes (a scope or a block granted to the tenant is not its own) — another tenant's block and an unknown one answer the same `counted: 0`; a server-admin reaches every memo; a key without an admin role is `403`. A re-embed migration's memos are never touched. **Without `confirm_memos` the call is a dry run** answering `{action, success, dry_run: true, as_of, counted, confirm_memos, held}` (and `held_until` when `held` is above 0); the real call sends `confirm_memos` and `as_of` of that answer, takes only the memos that were there when the dry run counted (a memo written after `as_of` — a released block that was parked again, a new park — is neither counted nor released, so paging ends), counts them again and releases only when the number is unchanged (otherwise `409` with the fresh `counted` and `confirm_memos`, and the `as_of` the call sent), releases at most `limit` of them — the count and the release decide which memos the reader may release at one instant (one transaction, issue #536), so a hold that ends between the two neither counts nor releases its memo in that call — and answers `{action, success, dry_run: false, as_of, counted, released, remaining, confirm_memos, held}` — `remaining` (and `confirm_memos`, the number to confirm for the next page with the same `as_of`) is what is left of them, including a memo another transaction held at that moment, which the release skips instead of waiting for. Two releases of the same memos at once each count what both may take: one of them releases fewer than it counted and answers a `remaining` the other has already released, and its next page answers `409` with the fresh count. Only memos that keep a block out of the pick (`next_attempt_at` in the future) count. **A server-admin's release deletes the memo; a tenant-admin's keeps it and makes it due**, with its attempts and with the time of the release in `first_seen`, so a block the backend still cannot take is parked again on the same row. A tenant-admin releases such an `oversize` memo again (more than one attempt) only once `embed_backfill.release_hold` × 2^(attempts − 2) has passed since that release, at most `embed_backfill.backoff_cap` (defaults 1 h and 24 h; a cap of 0 sets none; the hold must be above 0, V70); until then it is answered in `held`, with the earliest end in `held_until`. Without the hold a tenant-admin releasing its blocks in a loop while they kept not fitting took one turn of the background arm in every round of the tenants for good, where its way back without the action, an edit per block, costs a write each. The first release of every memo is not held, a `wire` memo is not held (its failure holds the tenant in the arm for `embed_backfill.interval`, and its next failure backs off longer, since the attempts stay), and a server-admin's release and a change of the block's title or content (which deletes the memo) start the count again. For a tenant-admin the count and the page of a class read the tenant's own scopes and their pending blocks, so their cost grows with the tenant's pending blocks, not with other tenants' memos. The next backfill pick of each released block embeds it when it fits now and parks it again after one attempt when it does not. CLI: `ctx admin embed-backfill release --class oversize`, then the same with `--confirm N --as-of T`; `--limit N` is sent as given, so a negative one is answered with the `400` (until issue #536 the CLI left a `--limit` of 0 or below out of the request and the server paged by its maximum). Operator notes in [operations](operations.md#embedding-backend-tuning-cpu-llamacpp), paragraph "Backfill failure memo". - **Block counters (issue #266):** `stats`, `guard-stats` and `list-categories` read per-scope counters that triggers on `context_blocks` keep with every write (migration 170), and so do the per-scope block counts of `scope-overview` (issue #271); the answers are unchanged. `guard-stats`' `pending_count` and `dirty_since` are counted on demand since migration 181: the blocks of the caller's read scopes the guard still has to check, and the oldest `updated_at` among them (`null` when none waits) — before 181 a global count of block writes since the last guard run, the same for every key ([operations](operations.md#migration-181-no-block-writer-waits-on-the-guards-state-row-guard-stats-counts-the-waiting-blocks)). `stats-reconcile` (server-admin) recounts and corrects them: `data` `{}` reconciles every scope, `{"scope": ""}` one; any other field is a `400`. It answers `{action, success, scopes, corrections, corrections_total, pruned, failed}` — `corrections` lists the corrected keys as `{scope, category, is_archived, guard_status, counted, actual}`, at most the first 1 000 of the pass, and `corrections_total` counts all of them (every one is corrected and logged; issue #271), `pruned` the folded counter rows at 0 it removed, `failed` the scopes whose reconcile failed (the pass goes on with the others; then `success` is `false` and the status `500`). The scheduler runs the same pass on `scheduler.block_count_reconcile_interval` — see [operations](operations.md#migration-170-block-counters-behind-stats-guard-stats-and-list-categories). -- **Keys/clients:** `api-key-create` requires `home_scope`; key + MCP-client management and mutating `dream-mode` require an **admin key** since migration 052 (see [security](security.md#admin-tier)). `api-key-create`/`api-key-update` accept optional `write_scopes` (078, E4b) — explicit per-key write scopes that must be ⊆ `allowed_scopes ∪ {home_scope}` (else 400); the effective block-write gate and its double enforcement are in [multi-tenancy](multi-tenancy.md#per-key-write-scopes-e4b-migration-078). Per-tenant scoping of the `api-key-*` actions and the tenant lifecycle (`tenant-*`, `tenant-grant-*`, `scope-*`, `tenant-limit-set`, `tenant-usage-get`, `tenant-quota-*`, `block-grant-*`) are in [multi-tenancy](multi-tenancy.md). +- **Keys/clients:** `api-key-create` requires `home_scope`; key + MCP-client management and mutating `dream-mode` require an **admin key** since migration 052 (see [security](security.md#admin-tier)). `api-key-create`/`api-key-update` accept optional `write_scopes` (078, E4b) — explicit per-key write scopes that must be ⊆ `allowed_scopes ∪ {home_scope}` (else 400); the effective block-write gate and its double enforcement are in [multi-tenancy](multi-tenancy.md#per-key-write-scopes-e4b-migration-078). They also accept `scope_narrowing` (migration 198): `required` makes the key answer every request without a [narrowing](#scope-narrowing-per-request) with `403 scope_narrowing_required`, `GET /api/whoami` excepted; `optional` (every existing key, the default) keeps today's behaviour; any other value is 400. Both answers carry the value; `api-key-list` lists it. Per-tenant scoping of the `api-key-*` actions and the tenant lifecycle (`tenant-*`, `tenant-grant-*`, `scope-*`, `tenant-limit-set`, `tenant-usage-get`, `tenant-quota-*`, `block-grant-*`) are in [multi-tenancy](multi-tenancy.md). +- **Key sets:** `keyset-provision` (tenant-admin, in the caller's own tenant; a server-admin may name `tenant_id`, anyone else naming it gets 403) creates the scopes and the keys of one set — say the groups of one community — in one transaction: either the whole set exists afterwards or nothing of it does. `data`: `scopes` (at most 64 bare scope names, scope-create's rule; the server puts the tenant's `:` in front; a scope the tenant already has is kept) and `keys` (at most 64, each `{label, home_scope, allowed_scopes, write_scopes, scope_narrowing, replace_label}`; a key's scope is a bare name or a full `:` and must be the tenant's own or one the set creates; a name without `:` always gets the prefix, so scopes outside that form — the default tenant's `private`, `work` and `shared` — cannot be named). The answer lists `scopes` as `{scope, created}` and `keys` as `{id, label, home_scope, allowed_scopes, write_scopes, scope_narrowing, api_key}`, both in the order of the call; each `api_key` (the plaintext) is in this answer only. Every key is a `member` key with exactly the scopes it names (no implicit `shared`, also in the default tenant) and its own principal; `scope_narrowing` left out is `required` — the set's keys answer nothing without a [narrowing](#scope-narrowing-per-request) but `GET /api/whoami`, and a key without that requirement is minted only when the call names `optional` (unlike `api-key-create`, whose default stays `optional`). `replace_label: true` deactivates the tenant's active keys with that label in the same transaction, before `max_keys` is counted, so a repeated call leaves one active key per label; on a label an owner, admin or server-admin key carries it refuses the set with `409`. Without `replace_label` a key may not take a label an active key of the tenant already carries: the whole set is refused with `409` and nothing of it is created, no scope either — so two runs of the same set (two machines, a repeated first run) never leave two active keys of one label; a deactivated key of the label does not count, and the label is checked before the set's scopes and limits. The rule is this action's: `api-key-create` and a reactivation through `api-key-update` check no label. Both label refusals answer `{"success": false, "error": "…", "labels": []}` and name no key value. Refusals: a scope of another tenant, or one the tenant neither has nor creates, `403`; `write_scopes ⊄ allowed_scopes ∪ {home_scope}`, a malformed scope name, an unknown field, a label missing or named twice in the set, a value the column cannot hold, a `scope_narrowing` other than `optional`/`required`, more than 64 scopes or keys, `400`; past `max_scopes` or `max_keys`, `429` with `limit`, `count` (the tenant's count before the set; for keys after its replacements) and `requested`; a tenant being deleted, or a scope registered meanwhile past the tenant lock (only a hand edit can), `409`; a top-level `id`, `400` (the target tenant is `data.tenant_id`). A narrowed request never reaches it ([above](#scope-narrowing-per-request)). How it serialises with the other key and scope writes: [multi-tenancy](multi-tenancy.md#key-sets-keyset-provision). - **Block-type registry:** `type-list`/`type-get` are open reads; `type-create`/`type-update`/`type-delete` are the **operator transport** (server-admin, `_global` namespace) of the same store logic the REST `PUT/DELETE /api/types/{name}` surface uses — kept functional for MCP/CLI consumers, not superseded (see [Block-type registry](#block-type-registry)). `manage update` accepts a registry-validated `type` field; `list-meta` accepts the `types`/`types_exclude` filters. - **Issue corpus:** `issue-create`/`issue-update`/`issue-get`/`issue-list`/`issue-comment-create`/`issue-link-create`/`issue-link-delete` are the **operator transport** (all tierOpen; isolation is store-layer scope filtering, not an admin tier) over the same store issue logic the REST `/api/project` issue surface (W6/W7) uses — kept reachable for MCP/CLI operators, not the primary UI surface (see [Issue corpus](#issue-corpus)). - **Backend pool:** `backend-list`/`create`/`update`/`delete`/`test` — see [Backend pool](#backend-pool). @@ -92,6 +107,8 @@ PostgreSQL stores a NUL character (U+0000) neither in text nor in JSON, so no va **The duplicate guard's metadata keys are server-owned (issue #238).** Every metadata key with the prefix `guard_` is the guard's record about a block: its verdict (`guard_status`, `guard_checked_at`, `guard_similarity`, `guard_matched_id`, `guard_is_cross_scope`, the thresholds), a person's `guard-resolve` trace (`guard_resolution`, `guard_resolved_at`) and the repair marks of migrations 121/156/157 (`guard_repair`). A client write cannot set, overwrite or remove one: on every surface that takes a caller's metadata — `POST /api/store` and `/api/store/batch`, `POST /api/ingest` (blocks and chunks), `manage update` (`metadata` and `metadata_merge`, a `null` included), the issue domain's writes, the MCP `store`, `store_batch`, `update` and issue tools, and the `confirm` of a staged card — such keys are **dropped from the request, not refused**, and the block keeps the ones it has. A replacement `metadata` document keeps the stored `guard_*` keys, a merge does not touch them, and a content change drops only `guard_checked_at`, which puts the block up for a check of its new text (a chunk, which the guard never checks, keeps it). A staged card shows the request as it was sent; its `confirm` drops the keys. A client that writes back the metadata it read (`get`, then `update`) keeps working and changes none of them. Before, a caller could write any value there: a `guard_similarity` that is not a number made `guard-list` answer an empty list to every reader of the scope, a `guard_checked_at` lifted the block out of the guard's queue or set the queue's age. `guard-list` now orders by `guard_similarity` only where the value is a JSON number (since issue #536; before #536, where it read as a number, a string such as `"0.97"` or `"NaN"` included) and sorts any other value last, as it sorts a missing one, and a fault of its statement is an error, not an empty list. To count the blocks whose `guard_*` keys no server writer produced (values written before this change), see [operations](operations.md#guard-keys-written-by-a-caller). +**The guard verdict in an answer follows the read scopes (review #595).** The duplicate guard matches a block against the blocks of every scope of its tenant, so its verdict can name a block the caller cannot read. Every answer that returns a block's `metadata` — `get` (one id or `ids`), `search` and `list` with full rows, the MCP `get` and `search` with content, the issue reads, the `manage update` answer, and the write answers of `POST /api/store` and `/api/store/batch` — drops the three keys that name or describe the match, `guard_matched_id`, `guard_similarity` and `guard_is_cross_scope`, when the matched block lies outside the request's read scopes (under a [narrowing](#scope-narrowing-per-request), the named ones). A caller that reads the matched block's scope gets them as stored. The `manage update` and issue-update answers judge against the key's write scopes, a subset of its read scopes, as before. Before, only `guard_matched_id` was dropped, and the write answers of `/api/store` and `/api/store/batch` dropped nothing: an overwrite answered with the stored verdict, the id of a block in another scope included. What remains readable on purpose: the block's own `guard_status` (its review state, not the match's), and `guard-list`, whose rows keep `similarity` for a partner shown `[redacted]` — the review page orders and shows the queue by it. A caller of `guard-list` therefore still learns that a block of its scopes has a near-duplicate somewhere in its tenant and how similar it is, not which block or in which scope. `guard-list` is no route a narrowed request may take. + **The derived layer is not client-claimable (I7).** The block types of the derived layer — `insight` and `catalog` — plus the categories they write into (`session-insights`, `catalog`), the metadata key `provenance`, and any block that already carries such a `provenance` object are **server-reserved on every write surface**: `POST /api/store`, `POST /api/ingest`, `manage update`, `manage delete`, `manage guard-resolve` (`archive`), the whole issue domain (`manage issue-create` / `issue-update` / `issue-comment-create`, their `/api/project/{id}/issues…` REST twins and the MCP `issue_create` / `issue_comment` tools), the MCP `store` / `update` tools, the chat write and update tools, and the `confirm` of a staged card on any of them. The refusals: * naming such a `type` ⇒ **422** `reserved_type` (the type exists — it is simply not the client's to claim, which is why it is not `unknown_type`); diff --git a/docs/cli.md b/docs/cli.md index f1f340a4..6f03a3be 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -110,7 +110,7 @@ Three deliberate exceptions, unchanged: | Command | Description | |---------|-------------| -| `ctx keys create