Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Agent label: rename the writer header, bound it to printable ASCII, cover both transports
garrytana7ad8134287b
diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.mdindex 96de81b1dc..3ee55dce6a 100644--- a/docs/architecture/key-files/core-services-2.md+++ b/docs/architecture/key-files/core-services-2.md@@ -30,7 +30,7 @@ Fact and page purge modules (`src/core/facts/purge*.ts`, `deletion-inventory.ts`- `src/core/ops/read-paging.ts` — paging for the two by-slug row reads that would otherwise return everything: `get_chunks` (`chunks.ts`: `from_index` default 0, `limit` default 50, MCP cap 500; the engine's `getChunkPage` returns the chunk_index range [from_index, from_index + limit) plus `total_chunks` and the highest index) and `get_versions` (`admin.ts`: default 20, MCP cap 100). Both keep a bare-array result; `pagingLimit` resolves the limit (trusted local CLI honors any explicit value; a non-positive-integer is `invalid_params`), and `reportChunkPage` / `reportVersionPage` emit `_meta.pagination` (`from_index`, `limit`, `returned`, `total_chunks`, `next_from_index` / `limit`, `truncated`, `clamped_from`), the model-visible `listing_truncated` notice for remote callers when rows remain (its fix is the next call), and one stderr line for a local call with no limit. Tests: `test/get-chunks-paging.test.ts`, `test/get-versions-defaults.test.ts`.- `src/core/ops/admin.ts` — the admin/diagnostics domain module (`get_stats`, `get_health`, `get_brain_identity`, …). `get_health` adds `embedding_column`, the registry-active vector column its coverage counts were measured on (legacy `embedding` when the registry is unreadable), on both engines (`test/get-health-embedding-column.test.ts` + its Postgres arm). `get_versions` reads an explicit column list (`PAGE_VERSION_COLUMNS` in `engine-sql/pages.ts`), so the write attribution columns never reach a plain `read` caller; trusted local callers and `admin` holders (`canReadWriteAttribution`) also get `written_by` and `archived_by` from `attributeVersions`. It filters protected facts/takes from both canonical body and timeline, preserves legacy missing timeline fields, and retains engine-side current/historical page privacy predicates for every snapshot field. By default it returns metadata only (no `compiled_truth`/`timeline`) for the newest 20 versions; `include_body: true` adds the bodies (remote-sanitized), and `limit` (a positive safe integer; any other explicit value is `invalid_params` without echoing it) takes the newest N, capped at 100 for every caller but the trusted local CLI. The handler probes one row past the limit and reports a cut history through `read-paging.ts`. The bound and the projection run in `engine-sql/pages.ts` `getVersions` (one query, scope and privacy predicates in WHERE before `LIMIT`, `ORDER BY pv.snapshot_at DESC, pv.id DESC`, metadata mode selects no body columns, typed `PageVersionRows`), so hidden versions never shift the prefix; trusted and admin callers keep `written_by`/`archived_by` (`test/get-versions-response-bounds.test.ts`). All three aggregate ops confine remote callers via the same ladder reads use: `ctx.remote === false` keeps the trusted brain-wide view; every other caller gets `sourceScopeOpts(ctx)` (federated array > scalar > the unmatchable `__all__` sentinel, which fail-closes to zeros) threaded into `engine.getStats(scope)`/`getHealth(scope)` — aggregates leak by subtraction, so they scope exactly like reads, and read-scope `get_brain_identity` is confined the same way. `get_health`'s `migrations {pending, pending_fresh_install, partial, wedged, declined, skipped_future}` block (`declined` since #6466: versions the brain's config turns off, read through `declinedMigrations(engine)`) stays GLOBAL for scoped callers by decision: it is a host filesystem ledger with no per-source semantics, a wedged host migration is exactly what a remote agent needs to see to explain degraded behavior, and it is composed at the op layer (not in `BrainEngine.getHealth` — growing the engine interface would force both engines to duplicate a file read). `get_health` serves repeat calls from `src/core/health-memo.ts` and returns `computed_at`, the time its counters were read.-- `src/core/ops/attribution.ts` — write attribution reads (Foundations 1, F1b). `resolveWriteAttributions` turns stored (request id, principal kind, principal id) snapshots into `WriteAttributionView`s (`types.ts`), joining `persistence_requests` (operation, `completed_at`), `oauth_clients.client_name`, `access_tokens.name` and the `persistence_local_writers` lane at read time, one query per table; `origin` is `request`, `maintenance` (principal without request) or `unrecorded` (all NULL). `get_write_attribution` (scope `admin`, `localOnly: false`, CLI `gbrain attribution <slug> [--fact <id>] [--take <row>] [--timeline <id>] [--versions]`) returns `{ target, created, last, live_revision, versions? }`; a page's `created` is the origin of its oldest version snapshot. The page lookup uses `readPolicyOpts`, so remote admins stay inside their source grant; remote fact targets are `world` only and take targets follow `readHolders`. Tests: `test/write-attribution-read.test.ts` (PGLite) and `test/e2e/write-attribution-read-parity.test.ts` (Postgres and PgBouncer).+- `src/core/ops/attribution.ts` — write attribution reads (Foundations 1, F1b). `resolveWriteAttributions` turns stored (request id, principal kind, principal id) snapshots into `WriteAttributionView`s (`types.ts`), joining `persistence_requests` (operation, `completed_at`, and the caller's self-declared `authority.agentLabel` as `agent_label`, #8664: the HTTP transports read it from `X-Gbrain-Agent-Label` via `parseAgentLabel` in `persistence/attribution.ts`; unverified text that nothing authorizes on), `oauth_clients.client_name`, `access_tokens.name` and the `persistence_local_writers` lane at read time, one query per table; `origin` is `request`, `maintenance` (principal without request) or `unrecorded` (all NULL). `get_write_attribution` (scope `admin`, `localOnly: false`, CLI `gbrain attribution <slug> [--fact <id>] [--take <row>] [--timeline <id>] [--versions]`) returns `{ target, created, last, live_revision, versions? }`; a page's `created` is the origin of its oldest version snapshot. The page lookup uses `readPolicyOpts`, so remote admins stay inside their source grant; remote fact targets are `world` only and take targets follow `readHolders`. Tests: `test/write-attribution-read.test.ts` (PGLite) and `test/e2e/write-attribution-read-parity.test.ts` (Postgres and PgBouncer).- `src/core/ops/trust.ts` — `confirm_memory` (#5575 A4, CEO-9, DX-20): the one MCP-visible owner action. Raises a fact, take or page to `user_confirmed` through `trust/owner-actions.ts` after `requireOwnerConfirmation` (a `memory_confirm` connection, or the local CLI's typed-token TTY prompt); agent tokens get `insufficient_scope` with a `tell_user_to_run` fix naming `gbrain trust confirm <ref>`. Trust proposals and holds are not reachable here; the other owner actions are CLI or resident-owner administration only (`trust/owner-ipc.ts`).- `src/core/health-memo.ts` — in-process memo for the `get_health` op only (O-ENG-13). An entry is reused when engine object, scope key (`all`, `scalar:<id>`, `set:<sorted unique ids>`, `empty` for an empty or no-sources grant; derived from the exact scope handed to `engine.getHealth`, so no scope reads another's entry), config generation (hash of the orphan exclusions, embedding column registry keys and schema pack setting), page clock (`page_generation_clock_seq.last_value` plus the `persistence_brain` id) and TTL all match. TTL: `GBRAIN_HEALTH_CACHE_TTL_MS`, else config `health.cache_ttl_ms`, else 30000 ms; 0 disables. The TTL bounds staleness from writes that do not touch `pages` (links, timeline rows, chunks). A failed clock/config read computes uncached. `engine.getHealth` stays uncached, so doctor, remediation, maintain, embedding migration and repair verification always read fresh numbers; `gbrain repair --apply` and `gbrain doctor --remediate` call `clearHealthMemo`. Pinned by `test/health-memo.test.ts`.diff --git a/docs/mcp/ADMIN.md b/docs/mcp/ADMIN.mdindex dd9456a4c9..cd17cdcf68 100644--- a/docs/mcp/ADMIN.md+++ b/docs/mcp/ADMIN.md@@ -572,7 +572,7 @@ gbrain attribution people/alice-example --timeline 17```Each attribution is `{ request_id, operation, principal: { kind, id, name }, at,-origin }`. Branch on `origin`:+agent_label?, origin }`. Branch on `origin`:| `origin` | Meaning || --- | --- |@@ -580,6 +580,18 @@ origin }`. Branch on `origin`:| `maintenance` | Written by a maintenance pass (cycle extraction, repair) as the named principal, with no request. || `unrecorded` | Written before attribution existed, or by a legacy writer that records none. Not an error. |+**Which AI made the write.** One credential often serves several AIs (a hosted+app calling for Claude Code and Codex, say). An HTTP MCP caller can name the AI+on each request with the `X-Gbrain-Agent-Label` header, for example+`X-Gbrain-Agent-Label: Claude Code`. Writes from that request show it as+`agent_label`. It is a label the caller declares and gbrain does not verify:+the principal is still who was authorized, and no grant, access rule or trust+tier reads the label. Any token may send it, and it lands only on that token's+own write requests. A value that is not 1 to 120 printable ASCII characters is+dropped, not refused. Stdio MCP and the local CLI have no request headers and+record no label; their principal already names the lane. Without the header a+write is recorded exactly as before.+Who can read it:- `get_write_attribution` needs `admin` scope (the local CLI always has it).diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 4de468ee8d..b50fd3e990 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -23,7 +23,7 @@ src/core/operations.ts 248 ratchet +1 #7168: graphRankOperations import (ops/grasrc/core/pglite-engine.ts 3103 ratchet +9 #7191: findPages/countPagesBy delegates and imports (SQL in engine-sql/page-lookup.ts); +4 GBRA-283 B1 (#8455): initSchema seeds an engine opened from settings with settings.embedding and refuses a mismatch, and its open skips the snapshot fast path (logic in embedded-engine.ts; engine methods cannot move); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +5 GBRA-67: readPageSnapshotsBatch delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages delegate (SQL in engine-sql/pages.ts); +2 GBRA-76: transaction/transactionDirect take TransactionOptions and refuse an already-aborted signal before BEGIN; +2 #4772 (W14 PR3): entityTypes HealthDeps delegate + import (policy in schema-pack/entity-types.ts, SQL in engine-sql/health.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3023 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates (SQL in engine-sql/pages.ts); +6 large pages Wave A sub-a: getChunkPage delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their imports; +7 LHF wave 2 item 5: request config snapshot delegate lines in getConfig/getAllConfig/setConfig/unsetConfig (logic in config-snapshot.ts); +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move); integrated at the Wave B PR 2 master merge (v0.60.264.0): master 3072 + 3; +5 PR2 fix lane X: keywordBoundedRead runs the read on the engine itself (engine methods cannot move): 3075 + 5; +2 GBRA-130 B-6 (#6860): putDreamVerdict passes its payload through wellFormedJson (engine methods cannot move); +1 GBRA-130 A-1: held option on the stale-page list/count signatures (SQL in engine-sql/pages.ts); +1 GBRA-130 integration: the A-1 (links_extract_failure) and B-6 (wellFormedJson putDreamVerdict) engine hunks composed at the lane merge; +2 #6948: putPage runs assertOriginUnclaimed in its page transaction and restorePage runs assertRevivalUnclaimed (logic in persistence/origin-guard.ts; engine methods cannot move): 3080 + 2; GBRA-130 composed with #6948 at the master 0e0cd27b merge: re-summed to the merged line count (3085); +2 #7159: the frontmatter where clause in searchKeyword and its import (SQL in search/frontmatter-where.ts; engine methods cannot move); +2 GBRA-156 keyword OR rarity: the import and the searchKeyword OR retry through rankOrFallbackByRarity with an orFallback rank parameter like Postgres (logic in search/keyword-or-rarity.ts; engine methods cannot move); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); re-summed at the Wave B PR 4 merge with v0.60.452.0 (3097 measured); +2 GBRA-283 Wave A (#8460): the ENGINE_ROOT import and field (engine identity for per-engine caches; class fields cannot move)src/core/postgres-engine.ts 3178 ratchet +9 #7191: findPages/countPagesBy scoped-read delegates and imports (SQL in engine-sql/page-lookup.ts); +6 GBRA-283 B1 (#8455): an engine opened from settings routes its direct URL and statement-description cache from its settings, and initSchema seeds settings.embedding and refuses a mismatch (logic in embedded-engine.ts; engine methods cannot move); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +1 #5984 single-write fast path composes with the lane apply diet at 2944; +2 #5984 shared parameter types: the instance pool passes shared_types and initSchema clears them after migrations (helpers in db.ts); +2 #6276: the remote alias-resolving readPageSnapshot runs with JIT off (withScopedReadTransaction jitOff); +5 #6278: executeRaw timeoutMs delegate (statement in postgres-engine/bounded-statement.ts); +23 #6278 PR 1.5: cancelSettleMs() and the settle timer in runUnsafe that discards a reserved connection whose cancel a transaction-mode pooler never completed; +3 #6317 lane 2: getPoolDiagnostics().pool from the vendored driver (postgres-engine/pool-stats.ts) and the prepare mark; +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +1 GBRA-69 extract batching: replaceDerivedLinksBatch delegate (batch logic in derived-links.ts); +9 GBRA-75: getBacklinkCounts and getHealth statements run JIT-off through the private jitOffRead transaction helper (engine methods cannot move); +3 GBRA-75 wave 7: searchKeyword and searchVector start the once-per-engine background search statistics guard (logic in search/projection-statistics.ts); +7 GBRA-67: readPageSnapshotsBatch scoped-read delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages scoped-read delegate (SQL in engine-sql/pages.ts); +7 #6383: poolIncidents hooks on the instance/module/connection-manager pools (counter and lines in pool-gauge.ts, budget in db.ts) and stuckDiscards/buildFailures in getPoolDiagnostics; +3 GBRA-76: transaction/transactionDirect take TransactionOptions; transactionOn attaches the begin handle to withTransactionAbort (logic in postgres-engine/transaction-abort.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +1 #5227: schema.sql replay under withSchemaLockTimeout (wave 14 PR1); +1 driver desync tripwire: desyncDiscards in getPoolDiagnostics (counter and line in pool-gauge.ts); +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages scoped-read delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3027 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates, reads scoped (SQL in engine-sql/pages.ts); +12 wave 16 G5.1 (#6495): keywordStatementTimeout memo field, its connect/disconnect resets and the keywordStatementTimeoutSetting accessor, plus one awaited setting per keyword/chunk/CJK transaction (resolver in postgres-engine/keyword-statement-timeout.ts); wave 16 G5.1 gate fix: keywordStatementTimeoutSetting resolves the knob once per connection on the first keyword statement from the saved connect config (connect issues no statement for it; 3042 measured); +7 large pages Wave A sub-a: getChunkPage scoped-read delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their imports; +3 wave 18b lane 2 (#6495): keywordTimeouts negative-cache field and the searchKeyword runner wrap (logic in postgres-engine/keyword-timeout-cache.ts); integrated at wave 18b: master 3082 + 3; +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move); integrated at the Wave B PR 2 master merge (v0.60.264.0): master 3085 + 3; +3 PR2 fix lane E (E1): getChunks/getChunkPage/getChunkWindows run the manifest privilege probe in their scoped transaction (chunkManifestReads in search/safe-chunks.ts); integrated at the lane E merge onto b75a69a6d: 3088 + 3; +6 PR2 fix lane X: searchVector, explainVectorSearch, the hasMore witness and runVectorAttempt pick the chunk-manifest statement form inside each bounded attempt transaction, so its statement_timeout bounds the probe (form memo vectorStatementForms in search/vector-statement.ts; engine methods cannot move): 3091 + 6; +5 PR2 fix lane X: keywordBoundedRead runs the read in withScopedReadTransaction under the keyword statement timeout setting (engine methods cannot move): 3097 + 5; +2 GBRA-130 B-6 (#6860): putDreamVerdict passes its payload through wellFormedJson (engine methods cannot move); +1 GBRA-130 A-1: held option on the stale-page list/count signatures (SQL in engine-sql/pages.ts); +1 GBRA-130 integration: the A-1 (links_extract_failure) and B-6 (wellFormedJson putDreamVerdict) engine hunks composed at the lane merge; +2 #6948: putPage runs assertOriginUnclaimed in its page transaction and restorePage runs assertRevivalUnclaimed (logic in persistence/origin-guard.ts; engine methods cannot move): 3102 + 2; GBRA-130 composed with #6948 at the master 0e0cd27b merge: re-summed to the merged line count (3107); +3 #7159: the frontmatter where clause in the two keyword typesClause sites and its import (SQL in search/frontmatter-where.ts; engine methods cannot move); GBRA-156 retrieval wave (#7201) composed with #7194 at the merge: re-summed (3114 measured); +2 warm CLI socket (#7218): connectedDatabaseUrl getter (the URL the engine connected with, bound into the socket identity), composed over the GBRA-156 retrieval wave (3116 measured); +1 GBRA-133 PR 2b: transactionOn hands the outermost transaction its commit checks (page-state/transactions.ts withCommitChecks), composed with the warm CLI socket at the merge (3117 measured); +18 GBRA-156: the private readTransaction helper behind withScopedReadTransaction and jitOffRead answers a top-level read before its COMMIT settles (engine methods cannot move; 3135 measured); +1 GBRA-156: transactionOn and runUnsafe hold a per-search connection slot (import of search/connection-budget.ts; 3136 measured); +2 GBRA-156: transactionOn passes TransactionOptions.pipelineFirst to the pool begin as { first } (driver gate in vendor/postgres index.js begin); an engine method cannot move; composed with the warm CLI socket and GBRA-133 PR 2b at the master v0.60.344.0 merge (3119 measured); GBRA-151 #7183/#7187/#7188 re-summed at the v0.60.402.0 merge (3135 measured); +2 #7183 (GBRA-151) at the v0.60.412.0 merge: read-write-transactions import and transactionOn wraps its connection in readWriteTransactions (logic in postgres-engine/read-write-transactions.ts; engine methods cannot move): 3135 + 2; +7 GBRA-156: transactionOn opens readOnly transactions as BEGIN READ ONLY and a top-level read inherits its request signal, runUnsafe refuses an aborted request (logic in request-signal.ts; engine methods cannot move): 3137 + 7; +3 GBRA-156 keyword OR rarity: the import and the searchKeyword OR retry through rankOrFallbackByRarity (logic in search/keyword-or-rarity.ts; engine methods cannot move); +2 wave-b PR 4 merged with #7218 (both sides added imports); re-summed at the Wave B PR 4 merge with v0.60.452.0 (3155 measured); +2 GBRA-283 Wave A (#8460): the ENGINE_ROOT import and field (engine identity for per-engine caches; class fields cannot move); +7 GBRA-283 B1 review: the instance pool passes settings connection fields explicitly, initSchema reads the embedding identity again under the schema lock, and reconnect ends the superseded manager (engine methods cannot move); re-summed at the train R merge with v0.60.574.0: 3170 + 4; +4 #6318: withScopedReadTransaction runs a bounded preparation's read under its deadline (read-deadline.ts; reserved-connection envelope runDeadlineRead in postgres-engine/bounded-statement.ts) and adds statement_timeout to the transaction settings (engine methods cannot move): re-summed at the 0.60.583.0 merge: 3174 + 4src/core/search/hybrid.ts 1562 ratchet +5 GBRA-81 item 5 per-stage search timings: HybridSearchOpts._timings (interface field) and the timer bindings and import in hybridSearch/hybridSearchCached (collector logic in search/stage-timings.ts); +2 W5 page-unit ranking cut: HybridSearchOpts.pageRankCut (logic in search/page-rank-cut.ts); +9 W3 confidence-gated reranking: HybridSearchOpts.rerankGate and the gate/lookup threading through rerankAndPin and sizeReturnPool (logic in search/hybrid/rerank-gate.ts, crag.ts gradePreRerank); re-summed at the W3 merge onto master v0.60.168.0 (1641 measured); +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key; +5 green master wave (embedding opt-out): HybridSearchOpts._embeddingOptedOut (interface field) read once per request and threaded to the cache-lookup embed and the keyword-only gate; +24 P2 explain RRF attribution stamp in rrfFusionWeighted, backlink_count stamp, explain_target stage observations, explain/explainTarget opts; +14 fix wave 13 P4.8 #6400: lazyQueryEmbedDeadline (the query-embed deadline starts when the embed starts) and the _queryEmbedDeadline getter; +1 query facts arm: HybridSearchOpts.onQueryEmbedding (interface field; its one-line call is paid inside the ceiling) after the vector arms, so the facts arm reuses the query embedding without a second model call; re-summed at the master a08578ca5 merge (1591 master lines + 3 integration lines: the onQueryEmbedding hook); lowered to 1562: LHF wave 2 item 3 peeled cosineReScore into search/cosine-rescore.ts-src/core/types.ts 2357 ratchet +2 writer signature (Sina 2026-11-05): WriteAttributionView.writer (+ its doc line; the header, record and read live in persistence/attribution.ts and ops/attribution.ts) +3 train R: #7491 SearchOpts identifier-probe field and #7175 keywordPhrase option (interface fields); +2 GBRA-154 #7175: SearchOpts.keywordPhrase (opt-in phrase factor); +4 Wave B PR 1 (1c): Page.body_storage/body_bytes (interface fields; guard logic in page-body/page-shape.ts); +8 W3 confidence-gated reranking: HybridSearchMeta.rerank_gate (RerankGateMeta in search/hybrid/rerank-gate.ts); re-summed at the W3 merge onto master v0.60.168.0 (2279 measured); +7 fix wave 11 W6.2/W6.3 (#5989, #6132): SearchOpts.hnswIterativeScan and cjkKeyword, the keyword_candidates_incomplete stage and HybridSearchMeta.keyword_candidates (logic in engine-sql/cjk-search.ts); +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +6 retrieval feedback: SearchResult feedback_boost/content_hash/relational_path_edges stamps and RelationalFanoutRow.path_edges (interface fields); +2 RelationalFanoutOpts.wide (interface field); 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); +1 green master wave: embedding_disabled degraded reason (closed vocabulary); +2 #5951: Chunk.source_id (get_chunks names each row's source); 1 P2 SearchResult explain fields (rrf attribution, blend_norm_rrf, score_details, backlink_count) + RrfAttribution (interface fields); +11 #5575 (L1b): PageReadScope minTrust/suppressFlagged, SearchResult trust_tier/origin/unconfirmed, TimelineOpts eligibility (interface fields cannot move); +8 #4772 (W14 PR3): BrainHealth.entity_types_status field (interface fields cannot move); +1 C4: question page type row; +6 entity anchoring: optional SearchResult.entity_anchored row stamp (logic in search/entity-anchor.ts); +4 query facts arm: optional SearchResult.fact_row and superseded_claim row fields (logic in search/facts-arm.ts); +2 query facts arm: SearchResult result_type/fact_id/page_slug/follow_up (fact rows are never page-shaped); +9 Cat 40 Hard fix wave (#6271): SearchResult matched_alias/evidence_omitted/provenance, SearchOpts.rankQuery, keyword_count_unavailable stage and rerank_failed reasons; +12 fix wave 15 P2.1 (#6500): PageFilters.slugAfter (single-source slug keyset, interface field + doc) and the updated_desc tiebreaker comment (the keyset walk lives in facts/conversation-enumeration.ts); +2 wave 16 G5.1 (#6495): EngineConfig.keyword_statement_timeout_ms (interface field + doc); +2 GBRA-92: EngineConfig.pglite_shared_buffers (interface field + doc); +11 large pages (Wave A): Chunk/ChunkInput projected_byte_start/end interface fields (span logic in chunkers/recursive.ts, page-window/document.ts); +4 wave 18b lane 2 (#6495): SearchOpts.keywordTimeoutCache, the skipped_after_timeout degraded reason and the useCache doc line; integrated at wave 18b: master 2319 + 4; +2 LHF wave 2 item 3: retrieval meta cosine_rescore field (js_fallback disclosure; logic in search/cosine-rescore.ts); +14 GBRA-154 ranking wave (#4612 #7153 #7156 #7162 #7164): SearchResult collapsed/redirect_to/image_page/rank_prior/rank_score/fused_score stamps and HybridSearchMeta.collapse (interface fields; logic in search/collapse.ts, rank-priors.ts, score-contract.ts); GBRA-151 retrieval P0 x operability wave merge: both sides grew the file, re-summed (2343 measured); GBRA-156 retrieval wave (#7201) composed with #7194 at the merge: re-summed (2345 measured); GBRA-151 #7147 follow-up re-summed at the v0.60.338.0 merge (2347 measured); +2 GBRA-95 G7a follow-up: Page.withheld_source_path field; +2 #7600: SearchResult.quoted (interface field; logic in search/transcript-quote.ts); +1 #8377: ChronicleTimelineRow.trust_tier (interface field; chronicle reads quote rows by tier); re-summed at the train R merge with v0.60.574.0: 2354 + 1+src/core/types.ts 2357 ratchet +2 #8664 agent label: WriteAttributionView.agent_label (+ its doc line; the header, record and read live in persistence/attribution.ts and ops/attribution.ts) +3 train R: #7491 SearchOpts identifier-probe field and #7175 keywordPhrase option (interface fields); +2 GBRA-154 #7175: SearchOpts.keywordPhrase (opt-in phrase factor); +4 Wave B PR 1 (1c): Page.body_storage/body_bytes (interface fields; guard logic in page-body/page-shape.ts); +8 W3 confidence-gated reranking: HybridSearchMeta.rerank_gate (RerankGateMeta in search/hybrid/rerank-gate.ts); re-summed at the W3 merge onto master v0.60.168.0 (2279 measured); +7 fix wave 11 W6.2/W6.3 (#5989, #6132): SearchOpts.hnswIterativeScan and cjkKeyword, the keyword_candidates_incomplete stage and HybridSearchMeta.keyword_candidates (logic in engine-sql/cjk-search.ts); +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +6 retrieval feedback: SearchResult feedback_boost/content_hash/relational_path_edges stamps and RelationalFanoutRow.path_edges (interface fields); +2 RelationalFanoutOpts.wide (interface field); 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); +1 green master wave: embedding_disabled degraded reason (closed vocabulary); +2 #5951: Chunk.source_id (get_chunks names each row's source); 1 P2 SearchResult explain fields (rrf attribution, blend_norm_rrf, score_details, backlink_count) + RrfAttribution (interface fields); +11 #5575 (L1b): PageReadScope minTrust/suppressFlagged, SearchResult trust_tier/origin/unconfirmed, TimelineOpts eligibility (interface fields cannot move); +8 #4772 (W14 PR3): BrainHealth.entity_types_status field (interface fields cannot move); +1 C4: question page type row; +6 entity anchoring: optional SearchResult.entity_anchored row stamp (logic in search/entity-anchor.ts); +4 query facts arm: optional SearchResult.fact_row and superseded_claim row fields (logic in search/facts-arm.ts); +2 query facts arm: SearchResult result_type/fact_id/page_slug/follow_up (fact rows are never page-shaped); +9 Cat 40 Hard fix wave (#6271): SearchResult matched_alias/evidence_omitted/provenance, SearchOpts.rankQuery, keyword_count_unavailable stage and rerank_failed reasons; +12 fix wave 15 P2.1 (#6500): PageFilters.slugAfter (single-source slug keyset, interface field + doc) and the updated_desc tiebreaker comment (the keyset walk lives in facts/conversation-enumeration.ts); +2 wave 16 G5.1 (#6495): EngineConfig.keyword_statement_timeout_ms (interface field + doc); +2 GBRA-92: EngineConfig.pglite_shared_buffers (interface field + doc); +11 large pages (Wave A): Chunk/ChunkInput projected_byte_start/end interface fields (span logic in chunkers/recursive.ts, page-window/document.ts); +4 wave 18b lane 2 (#6495): SearchOpts.keywordTimeoutCache, the skipped_after_timeout degraded reason and the useCache doc line; integrated at wave 18b: master 2319 + 4; +2 LHF wave 2 item 3: retrieval meta cosine_rescore field (js_fallback disclosure; logic in search/cosine-rescore.ts); +14 GBRA-154 ranking wave (#4612 #7153 #7156 #7162 #7164): SearchResult collapsed/redirect_to/image_page/rank_prior/rank_score/fused_score stamps and HybridSearchMeta.collapse (interface fields; logic in search/collapse.ts, rank-priors.ts, score-contract.ts); GBRA-151 retrieval P0 x operability wave merge: both sides grew the file, re-summed (2343 measured); GBRA-156 retrieval wave (#7201) composed with #7194 at the merge: re-summed (2345 measured); GBRA-151 #7147 follow-up re-summed at the v0.60.338.0 merge (2347 measured); +2 GBRA-95 G7a follow-up: Page.withheld_source_path field; +2 #7600: SearchResult.quoted (interface field; logic in search/transcript-quote.ts); +1 #8377: ChronicleTimelineRow.trust_tier (interface field; chronicle reads quote rows by tier); re-summed at the train R merge with v0.60.574.0: 2354 + 1src/core/minions/queue.ts 2547 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keys; +18 Lane D: deferJob (a deferral returns a job to delayed with no attempt counted and no stacktrace growth); the ceiling had 17 lines of slack; +5 agent operator follow-up Item 5 merged over master: claim-time spend fence token and legacy_default stamp (logic in minions/spend-authorization.ts); +5 GBRA-130 A-30: claim excludeWatchdogSuspects option (signature, doc and the mark parameter), the releaseWatchdogClaim delegate, and the co-runner stall call site in handleStalled (logic in minions/watchdog-attribution.ts); +5 GBRA-158 #7239/#7240: failJob result parameter (the #7216 hunk), jsonbSafeJson import and its call in add (sanitizer in text-safe.ts); +2 #7242 lane reservation: claim excludeNames option (doc line and the bound array; policy in minions/lanes.ts); +1 #7241 submitter label import (job-insight.ts) + 1 queue-families type import; #7252 x #7249 merge: both sides grew the file, re-summed (2544 measured); +3 GBRA-133: the stall sweep deletes a drain-lease holder record whose lease lock is gone or expiredsrc/commands/init.ts 1892 ratchet +2 fix wave 9 lane F #5253: leaving deferred setup also clears the DB-plane embedding_disabled row (both init branches); grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 provider normalization; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only init; shared-skills integration on company-ingestion base; retired provider integration removed; retain stored-vector identity on re-init; -14: first-run bundle + quickstart registration helpers live in init-first-run.ts (writeback/skills asks folded into the bundle); +5 agent operator follow-up Item 2: --surface flag (value flag, parse, help line, module-level registration surface, type import) for the printed harness registration; +2 fix wave lane B3: both engine paths stamp a database init created as a fresh install for the behavior_changes notice (core/behavior-change-notice.ts); +4 GBRA-81 item 1: --search-mode value flag, its parse line, module-level choice, help line (picker logic lives in init-mode-picker.ts); +2 D8 funnel: a fresh init counts one clean_install when the opt-in funnel is on (core/funnel.ts); +1 GBRA-199: --surface help line names the default verbs listing; +7 GBRA-248 W0b: the implicit-keyless marker on both zero-key fallbacks, the deferred-hint gate on both engine paths and the kept-identity call in both (logic in commands/init-embedding-plane.ts)src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900)diff --git a/src/commands/serve-http-mcp.ts b/src/commands/serve-http-mcp.tsindex eaeca1799c..efa0acf64a 100644--- a/src/commands/serve-http-mcp.ts+++ b/src/commands/serve-http-mcp.ts@@ -45,7 +45,7 @@ import {import { getBrainHotMemoryMeta } from '../core/facts/meta-hook.ts';import { ON_BEHALF_OF_HEADER } from '../core/access/audience.ts';import { ACTOR_HEADER, EXTERNAL_ID_RE, QM_AUDIENCE_HEADER } from '../core/access/actor-model.ts';-import { parseWriterSignature, WRITER_SIGNATURE_HEADER } from '../core/persistence/attribution.ts';+import { parseAgentLabel, AGENT_LABEL_HEADER } from '../core/persistence/attribution.ts';import { qmMemoryToolResult } from '../core/ops/qm-memory.ts';import { attestableOp } from '../core/access/actor.ts';@@ -78,8 +78,8 @@ interface McpRequestState {actorHeader: string | undefined;/** GST-359 D: the x-qm-audience header (QM's channel audience, wave 2); any request carrying it is refused before any work. */audienceHeader: string | undefined;- /** The AI this request signed itself as (x-gbrain-writer); recorded on the write's attribution, never authority. */- writerSignature: string | undefined;+ /** The caller's self-declared agent label (X-Gbrain-Agent-Label): recorded on its write requests, never authority. */+ agentLabel: string | undefined;}export function mountMcp(app: Express, ctx: ServeHttpContext): void {@@ -192,7 +192,7 @@ export function mountMcp(app: Express, ctx: ServeHttpContext): void {const thinClient = isGbrainThinClient(req.get(GBRAIN_CLIENT_HEADER));const state: McpRequestState = { authInfo, agentName, startTime, mcpOperations, surface, surfaceCeiling, surfaceAllowedOps, resultRows, thinClient,onBehalfOfHeader: req.get(ON_BEHALF_OF_HEADER), actorHeader: req.get(ACTOR_HEADER), audienceHeader: req.get(QM_AUDIENCE_HEADER),- writerSignature: parseWriterSignature(req.get(WRITER_SIGNATURE_HEADER)) };+ agentLabel: parseAgentLabel(req.get(AGENT_LABEL_HEADER)) };const server = createMcpRequestServer(ctx, state, writeback);await serveMcpRequest(server, req, res);}@@ -443,7 +443,7 @@ async function callMcpTool(ctx: ServeHttpContext, state: McpRequestState, reques...(hotMemoryOffIn(request.params) ? { hotMemoryOff: true } : {}),onBehalfOf: { header: state.onBehalfOfHeader, requestMeta: (request.params as { _meta?: unknown })._meta },actor: { header: state.actorHeader, audience: state.audienceHeader },- ...(state.writerSignature ? { writerSignature: state.writerSignature } : {}),+ ...(state.agentLabel ? { agentLabel: state.agentLabel } : {}),takesHoldersAllowList: tokenAllowList,sourceId: tokenSourceId,...(localFederated ? { localFederatedSourceIds: localFederated } : {}),diff --git a/src/core/ops/attribution.ts b/src/core/ops/attribution.tsindex c8d1a1a3db..f5eda2d0b4 100644--- a/src/core/ops/attribution.ts+++ b/src/core/ops/attribution.ts@@ -52,8 +52,8 @@ export async function resolveWriteAttributions(engine: BrainEngine, stored: Storconst requestIds = [...new Set(stored.map(s => s.request_id).filter((id): id is string => !!id))];const localIds = [...ids('local_cli'), ...ids('local_stdio')];const [requests, clients, tokens, writers] = await Promise.all([- requestIds.length ? engine.executeRaw<{ id: string; operation: string; completed_at: Date | string | null; writer: string | null }>(- "SELECT id::text AS id, operation, completed_at, authority->>'writerSignature' AS writer FROM persistence_requests WHERE id = ANY($1::uuid[])", [requestIds]) : [],+ requestIds.length ? engine.executeRaw<{ id: string; operation: string; completed_at: Date | string | null; agent_label: string | null }>(+ "SELECT id::text AS id, operation, completed_at, authority->>'agentLabel' AS agent_label FROM persistence_requests WHERE id = ANY($1::uuid[])", [requestIds]) : [],ids('oauth_client').length ? engine.executeRaw<{ id: string; name: string }>('SELECT client_id AS id, client_name AS name FROM oauth_clients WHERE client_id = ANY($1::text[])', [ids('oauth_client')]) : [],ids('legacy_token').length ? engine.executeRaw<{ id: string; name: string }>(@@ -76,7 +76,7 @@ export async function resolveWriteAttributions(engine: BrainEngine, stored: Storprincipal: s.principal_kind && s.principal_id? { kind: s.principal_kind, id: s.principal_id, name: names.get(`${s.principal_kind}:${s.principal_id}`) ?? null } : null,at: iso(request?.completed_at ?? s.at),- ...(request?.writer ? { writer: request.writer } : {}),+ ...(request?.agent_label ? { agent_label: request.agent_label } : {}),origin: s.request_id ? 'request' : 'maintenance',};});diff --git a/src/core/ops/contract.ts b/src/core/ops/contract.tsindex 430190d9a8..506a6e9819 100644--- a/src/core/ops/contract.ts+++ b/src/core/ops/contract.ts@@ -497,8 +497,8 @@ export interface OperationContext {* transports). Unset is `background`; it is never derived from `remote` (persistence/admission-origin.ts).*/admissionOrigin?: import('../persistence/admission-origin.ts').AdmissionOrigin;- /** The AI the trusted transport read from the write's signature header (persistence/attribution.ts). Descriptive, never authority. */- writerSignature?: string;+ /** The caller's self-declared agent label, read by an HTTP transport from X-Gbrain-Agent-Label (persistence/attribution.ts). Unverified text, never authority. */+ agentLabel?: string;/*** Transport marker for auth-less remote surfaces (#1061). The stdio MCP* dispatch sets 'stdio' — it is deliberately `remote: true` (agent-facing,diff --git a/src/core/persistence/attribution.ts b/src/core/persistence/attribution.tsindex 6a4434c0f7..6a8dbc7f94 100644--- a/src/core/persistence/attribution.ts+++ b/src/core/persistence/attribution.ts@@ -21,17 +21,18 @@ export interface WriteAttribution {export { withWriteAttribution };/**- * The request header a caller uses to sign a write with the AI it is. The hosting- * layer knows which model is calling (Claude, Codex, an OpenClaw job); gbrain does- * not, and every write from one brain otherwise looks alike. Descriptive only: it- * never authorizes, never widens a grant, and a caller that omits it is recorded- * exactly as before.+ * The HTTP MCP request header a caller uses to say which AI made a write ("Claude Code", "Codex", a job name). The+ * host knows which agent is calling through one credential; gbrain does not. It is a label the caller declares and+ * gbrain never verifies: it is stored on the write request and shown as `agent_label` by attribution reads, and+ * nothing that authorizes (grants, access rules, trust tiers) reads it. Not "writer": that word names the principal+ * and the write owner (persistence_local_writers, `gbrain sources writer`). Stdio and the local CLI have no request+ * headers and record none; their principal already names the lane.*/-export const WRITER_SIGNATURE_HEADER = 'x-gbrain-writer';-/** A usable signature, or undefined: 1-120 printable characters and no control characters. */-export function parseWriterSignature(value: string | null | undefined): string | undefined {+export const AGENT_LABEL_HEADER = 'X-Gbrain-Agent-Label';+/** A label safe to store and render, or undefined: 1-120 printable ASCII characters after trimming, else dropped. */+export function parseAgentLabel(value: string | null | undefined): string | undefined {const text = value?.trim();- return text && text.length <= 120 && !/\p{Cc}/u.test(text) ? text : undefined;+ return text && /^[\x20-\x7e]{1,120}$/.test(text) ? text : undefined;}/** A journaled request publishes as itself. */diff --git a/src/core/persistence/authority.ts b/src/core/persistence/authority.tsindex 1c0ce14517..95c0f74023 100644--- a/src/core/persistence/authority.ts+++ b/src/core/persistence/authority.ts@@ -64,7 +64,7 @@ export async function submissionAuthority(ctx: OperationContext, operation: stri// GST-359 C1: an attested call stores its actor (never the bare one-member audience), so publication re-resolves the link.const actingFor: WriteAuthority['actingFor'] = access?.actor ? { ...access.actor } : access?.audience?.length ? [...access.audience] : undefined;const a: WriteAuthority = {- ...(ctx.writerSignature ? { writerSignature: ctx.writerSignature } : {}),+ ...(ctx.agentLabel ? { agentLabel: ctx.agentLabel } : {}),version: 1, principal, remote: ctx.remote !== false, sourceId, sourceIncarnation,// GBRA-231: a channel audience (anything but one member) never relaxes privacy, so its ceiling hides private pages.excludePrivate: (actingFor !== undefined && currentCallerAccess().hidePrivate) || await excludesPrivateWritesAtAdmission(ctx.engine, ctx.remote !== false),diff --git a/src/core/persistence/model.ts b/src/core/persistence/model.tsindex a7017f5296..1d3ca46322 100644--- a/src/core/persistence/model.ts+++ b/src/core/persistence/model.ts@@ -4,8 +4,8 @@ import { assertRecoveryVersion } from './recovery-version.ts';export type Principal = { kind: 'oauth_client' | 'legacy_token' | 'local_cli' | 'local_stdio' | 'application'; id: string };export type RequestState = 'queued' | 'running' | 'recovering' | 'committed' | 'conflict' | 'failed' | 'cancelled';export interface WriteAuthority {- /** The AI the caller signed this write with (x-gbrain-writer). Descriptive, never authority. */- writerSignature?: string;+ /** The caller's self-declared agent label (X-Gbrain-Agent-Label). Unverified text: nothing authorizes on it. */+ agentLabel?: string;version: 1;principal: Principal;remote: boolean;diff --git a/src/core/types.ts b/src/core/types.tsindex 14650c2b27..516c29a4f2 100644--- a/src/core/types.ts+++ b/src/core/types.ts@@ -1875,8 +1875,8 @@ export type { PageVersion } from './page-state/version-types.ts';export interface WriteAttributionView {request_id: string | null; operation: string | null; at: string | null;principal: { kind: string; id: string; name: string | null } | null;- /** The AI the caller signed the write with (x-gbrain-writer), when it declared one. */- writer?: string;+ /** The agent label the caller declared on the write request (X-Gbrain-Agent-Label); unverified, absent when none was sent. */+ agent_label?: string;origin: 'request' | 'maintenance' | 'unrecorded';}/** A `get_versions` row as trusted local and admin callers see it. */diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.tsindex 535d312603..bff0043953 100644--- a/src/mcp/dispatch.ts+++ b/src/mcp/dispatch.ts@@ -184,8 +184,8 @@ export interface DispatchOpts {onBehalfOf?: AudienceChannels;/** #6696 (A5): set by the trusted transport for the user's own agent calls; never from wire params. */admissionOrigin?: OperationContext['admissionOrigin'];- /** The AI this request signed itself as (x-gbrain-writer), already parsed by the transport; recorder only, never authority. */- writerSignature?: string;+ /** The caller's self-declared agent label (X-Gbrain-Agent-Label), parsed by the transport; recorded only, never authority. */+ agentLabel?: string;/** Configuration selected by the resident transport, never populated from wire params. */config?: OperationContext['config'];/** Defaults to true (remote/untrusted). Local CLI callers (`gbrain call`) pass false. */@@ -916,7 +916,7 @@ export function buildOperationContext(...(opts.revealTools ? { revealTools: opts.revealTools } : {}),...(opts.writeWaitMs !== undefined ? { writeWaitMs: opts.writeWaitMs } : {}),...(opts.admissionOrigin ? { admissionOrigin: opts.admissionOrigin } : {}),- ...(opts.writerSignature ? { writerSignature: opts.writerSignature } : {}),+ ...(opts.agentLabel ? { agentLabel: opts.agentLabel } : {}),...(opts.resultRows ? { resultRows: opts.resultRows } : {}),...(opts.thinClient ? { thinClient: true } : {}),isCallable: (opName: string) => (render ??= dispatchRenderContext(opts)).isCallable(opName),diff --git a/src/mcp/http-transport.ts b/src/mcp/http-transport.tsindex 634f346716..57b029dff0 100644--- a/src/mcp/http-transport.ts+++ b/src/mcp/http-transport.ts@@ -40,7 +40,7 @@ import { operations, operationsByName, opAllowedForBoundClient } from '../core/oimport { scopeDeniedError } from '../core/ops/op-fix.ts';import { ON_BEHALF_OF_HEADER } from '../core/access/audience.ts';import { ACTOR_HEADER, QM_AUDIENCE_HEADER, withAttestRight } from '../core/access/actor-model.ts';-import { parseWriterSignature, WRITER_SIGNATURE_HEADER } from '../core/persistence/attribution.ts';+import { parseAgentLabel, AGENT_LABEL_HEADER } from '../core/persistence/attribution.ts';import { qmMemoryToolResult } from '../core/ops/qm-memory.ts';import { isCallable, publishGatesFromDisabled } from '../core/ops/callable.ts';import type { AuthInfo } from '../core/operations.ts';@@ -538,7 +538,7 @@ export async function startHttpTransport(opts: HttpTransportOptions) {const toolName: string = params?.name ?? 'unknown';const args: Record<string, unknown> = params?.arguments ?? {};const op = operationsByName[toolName];- const writerSignature = parseWriterSignature(req.headers.get(WRITER_SIGNATURE_HEADER));+ const agentLabel = parseAgentLabel(req.headers.get(AGENT_LABEL_HEADER));// #5575: cliOnly ops reach the dispatcher's trusted_local_only refusal (the host command), never a grant-widening scope fix.if (op && !op.localOnly && !op.cliOnly && !operationScopesAllowed(auth.auth!.scopes, op)) {logRequest(auth.tokenName!, `tools/call:${toolName}`, 'denied_after_list', Date.now() - startedMs);@@ -572,8 +572,8 @@ export async function startHttpTransport(opts: HttpTransportOptions) {sourceId: auth.sourceId,...(localFederated ? { localFederatedSourceIds: localFederated } : {}), onBehalfOf: { header: req.headers.get(ON_BEHALF_OF_HEADER) ?? undefined, requestMeta: params?._meta },actor: { header: req.headers.get(ACTOR_HEADER) ?? undefined, audience: req.headers.get(QM_AUDIENCE_HEADER) ?? undefined }, // #1336: thread the token's federated_read grant so read ops scope- ...(writerSignature ? { writerSignature } : {}),// to the operator-granted sources via sourceScopeOpts.+ ...(agentLabel ? { agentLabel } : {}),auth: auth.auth,// MEMORY_VERBS v1 [c1/c2]: fail-closed surface enforcement here too....(surfaceAllowedOps ? { allowedOps: surfaceAllowedOps } : {}),diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.jsonindex e82a42ae81..3fcc44218e 100644--- a/test/fixtures/goldens/exports/types.json+++ b/test/fixtures/goldens/exports/types.json@@ -1670,6 +1670,7 @@{"kind": "interface","members": [+ "agent_label?: string | undefined","at: string | null","operation: string | null","origin: \"request\" | \"maintenance\" | \"unrecorded\"",@@ -6793,6 +6794,7 @@"members": ["accessIdentity?: readonly string[] | undefined","admissionOrigin?: AdmissionOrigin | undefined",+ "agentLabel?: string | undefined","allowedSlugPrefixes?: string[] | undefined","applyRemoteReadPolicy?: boolean | undefined","attestedOp?: string | undefined",@@ -10116,6 +10118,7 @@{"kind": "interface","members": [+ "agent_label?: string | undefined","at: string | null","operation: string | null","origin: \"request\" | \"maintenance\" | \"unrecorded\"",diff --git a/test/write-agent-label.test.ts b/test/write-agent-label.test.tsnew file mode 100644index 0000000000..9e38a86032--- /dev/null+++ b/test/write-agent-label.test.ts@@ -0,0 +1,179 @@+/**+ * #8664: a hosted caller can share one credential across several AIs, so the brain recorded which principal wrote a+ * page but not which AI. An HTTP MCP request may now carry the X-Gbrain-Agent-Label header; the write records it on+ * its request's authority and attribution reads show it as agent_label. No column, no migration, no new auth path.+ *+ * Protects: both HTTP transports (the OAuth serve --http mount and the legacy bearer transport) read the header and+ * admission records it, on a managed-worktree brain and on a repo-less brain; an unlabelled write is unchanged; a+ * label is unverified text that never changes what the request may do (the stored authority is otherwise identical,+ * and a read-only token is still refused); a label that is not 1-120 printable ASCII characters is dropped, never+ * stored or refused.+ * Fails when: the header is dropped before admission, invented at read time, read by authorization, or a value that is+ * unsafe to render (controls, bidi or zero-width characters, non-ASCII bytes) reaches the record.+ * Seams: the mounted SDK transport and the legacy Bun transport over real sockets with real bearer tokens, and the+ * attribution op a read already has. PGLite only: this is a header-to-row path, not a database behaviour.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import type { Server } from 'node:http';+import type { AddressInfo } from 'node:net';+import express from 'express';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';+import { sqlQueryForEngine } from '../src/core/sql-query.ts';+import { hashToken } from '../src/core/utils.ts';+import { operationsByName, type OperationContext } from '../src/core/operations.ts';+import { mountMcp } from '../src/commands/serve-http-mcp.ts';+import type { ServeHttpContext } from '../src/commands/serve-http.ts';+import { startHttpTransport } from '../src/mcp/http-transport.ts';+import { RateLimiter } from '../src/mcp/rate-limit.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { registerLocalWriter } from '../src/core/persistence/identity.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { AGENT_LABEL_HEADER, parseAgentLabel } from '../src/core/persistence/attribution.ts';++const CONFIG = { engine: 'pglite', embedding_disabled: true } as const;+const content = (title: string) => '---\ntype: note\ntitle: ' + title + '\n---\n\n# ' + title + '\n\nA synthetic page.\n';++async function freshEngine(): Promise<BrainEngine> {+ const db = new PGLiteEngine();+ await db.connect({});+ await db.initSchema();+ return db;+}+async function addToken(engine: BrainEngine, name: string, token: string, scopes: string): Promise<void> {+ await engine.executeRaw('INSERT INTO access_tokens(name,token_hash,scopes) VALUES($1,$2,$3::text[])', [name, hashToken(token), scopes]);+}+/** One real tools/call put_page; returns the raw response text. */+async function putPage(engine: BrainEngine, url: string, token: string, slug: string, title: string, label?: string): Promise<string> {+ const snapshot = await engine.readPageSnapshot(slug, { sourceId: 'default' });+ const response = await fetch(url, { method: 'POST',+ headers: { authorization: 'Bearer ' + token, 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream', ...(label === undefined ? {} : { [AGENT_LABEL_HEADER]: label }) },+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'put_page',+ arguments: { slug, content: content(title), ...(snapshot ? { expected_revision: snapshot.revision } : {}) } } }) });+ expect(response.status).toBe(200);+ return await response.text();+}+async function put(engine: BrainEngine, url: string, token: string, slug: string, title: string, label?: string): Promise<void> {+ expect((await putPage(engine, url, token, slug, title, label)).includes('"isError":true')).toBe(false);+}+const attributed = async (engine: BrainEngine, slug: string) => await operationsByName.get_write_attribution.handler({+ engine, sourceId: 'default', remote: false, config: CONFIG, logger: { info() {}, warn() {}, error() {} },+} as unknown as OperationContext, { slug }) as Record<string, any>;++test('a label is 1-120 printable ASCII characters after trimming; anything else is dropped', () => {+ expect(parseAgentLabel(' Claude Code ')).toBe('Claude Code');+ expect(parseAgentLabel('codex/gpt-6.1-sol')).toBe('codex/gpt-6.1-sol');+ expect(parseAgentLabel('x'.repeat(120))).toBe('x'.repeat(120));+ for (const bad of [undefined, null, '', ' ', 'x'.repeat(121), 'bad' + String.fromCharCode(7) + 'label', 'line\nbreak', 'tab\there',+ 'caf' + String.fromCharCode(0xe9), 'Codex' + String.fromCharCode(0x202e) + 'edoC', 'zero' + String.fromCharCode(0x200b) + 'width',+ 'sep' + String.fromCharCode(0x2028) + 'arator', 'c1' + String.fromCharCode(0x85) + 'control']) {+ expect(parseAgentLabel(bad)).toBeUndefined();+ }+});++describe('OAuth serve --http mount, managed worktree brain', () => {+ const SLUG = 'notes/labelled-write';+ const TOKEN = 'synthetic-agent-label-' + process.pid;+ const READER = 'synthetic-agent-label-reader-' + process.pid;+ let engine: BrainEngine;+ let root: string;+ let http: Server;+ let url: string;++ beforeAll(async () => {+ engine = await freshEngine();+ root = mkdtempSync(join(tmpdir(), 'gbrain-agent-label-'));+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw('UPDATE sources SET local_path=$1 WHERE id=\'default\'', [root]);+ await claimWorktree(engine, 'default', root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ await registerLocalWriter(engine, 'cli');+ await addToken(engine, 'Synthetic writer token', TOKEN, '{read,write}');+ await addToken(engine, 'Synthetic reader token', READER, '{read}');+ const provider = new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });+ const app = express();+ mountMcp(app, { engine, config: CONFIG, resourceVerifier: provider,+ resourceMetadataUrl: 'http://127.0.0.1/resource', mcpResourceUrl: new URL('http://127.0.0.1/mcp'),+ mcpOperationsBase: Object.values(operationsByName).filter(op => !op.localOnly && !op.cliOnly), broadcastEvent() {} } as unknown as ServeHttpContext);+ http = await new Promise(resolve => { const listener = app.listen(0, '127.0.0.1', () => resolve(listener)); });+ url = 'http://127.0.0.1:' + (http.address() as AddressInfo).port + '/mcp';+ }, 120_000);++ afterAll(async () => {+ await disposePersistenceConsumer(engine);+ if (http) await new Promise<void>(resolve => http.close(() => resolve()));+ await engine.disconnect();+ rmSync(root, { recursive: true, force: true });+ });++ test('a labelled write records the label the caller declared, and attribution reads show it', async () => {+ await put(engine, url, TOKEN, SLUG, 'First by Claude', 'Claude Code');+ expect((await attributed(engine, SLUG)).live_revision.written_by.agent_label).toBe('Claude Code');++ await put(engine, url, TOKEN, SLUG, 'Then by Codex', ' Codex ');+ const second = await attributed(engine, SLUG);+ expect(second.created.agent_label).toBe('Claude Code');+ expect(second.last.agent_label).toBe('Codex');+ expect(second.live_revision.written_by.agent_label).toBe('Codex');++ await put(engine, url, TOKEN, SLUG, 'Unlabelled edit');+ const third = await attributed(engine, SLUG);+ expect(third.live_revision.written_by.agent_label).toBeUndefined();+ expect('agent_label' in third.live_revision.written_by).toBe(false);++ await put(engine, url, TOKEN, SLUG, 'Too long', 'x'.repeat(121));+ expect((await attributed(engine, SLUG)).live_revision.written_by.agent_label).toBeUndefined();+ }, 240_000);++ test('a label is never authority: the stored authority is otherwise identical and a read-only token is still refused', async () => {+ const rows = await engine.executeRaw<{ label: string | null; rest: Record<string, unknown> }>(+ "SELECT authority->>'agentLabel' AS label, authority - 'agentLabel' AS rest FROM persistence_requests WHERE slug=$1 ORDER BY created_at", [SLUG]);+ expect(rows.map(r => r.label)).toEqual(['Claude Code', 'Codex', null, null]);+ const rest = rows.map(r => typeof r.rest === 'string' ? JSON.parse(r.rest) : r.rest);+ for (const other of rest.slice(1)) expect(other).toEqual(rest[0]);++ const refused = await putPage(engine, url, READER, 'notes/reader-attempt', 'Reader attempt', 'admin');+ expect(refused).toContain('"isError":true');+ expect(await engine.readPageSnapshot('notes/reader-attempt', { sourceId: 'default' })).toBeNull();+ }, 240_000);+});++describe('legacy bearer transport, repo-less brain', () => {+ const SLUG = 'notes/repoless-labelled';+ const TOKEN = 'synthetic-agent-label-legacy-' + process.pid;+ let engine: BrainEngine;+ let server: { port: number; stop: (force?: boolean) => unknown };+ let url: string;++ beforeAll(async () => {+ engine = await freshEngine();+ const [source] = await engine.executeRaw<{ local_path: string | null }>("SELECT local_path FROM sources WHERE id='default'");+ expect(source?.local_path ?? null).toBeNull();+ await addToken(engine, 'Synthetic legacy token', TOKEN, '{read,write}');+ server = await startHttpTransport({ port: 0, engine, surface: 'full', limiters: {+ ip: new RateLimiter({ limit: 10_000, windowMs: 60_000, lruCap: 100 }),+ token: new RateLimiter({ limit: 10_000, windowMs: 60_000, lruCap: 100 }),+ } }) as unknown as { port: number; stop: (force?: boolean) => unknown };+ url = 'http://127.0.0.1:' + server.port + '/mcp';+ }, 120_000);++ afterAll(async () => {+ await server?.stop(true);+ await disposePersistenceConsumer(engine);+ await engine.disconnect();+ });++ test('the legacy transport records the label on a repo-less brain and drops a non-ASCII one', async () => {+ await put(engine, url, TOKEN, SLUG, 'Repo-less by Claude', 'Claude Code');+ expect((await attributed(engine, SLUG)).live_revision.written_by.agent_label).toBe('Claude Code');++ await put(engine, url, TOKEN, SLUG, 'Repo-less latin1 label', 'caf' + String.fromCharCode(0xe9));+ const after = await attributed(engine, SLUG);+ expect(after.live_revision.written_by.agent_label).toBeUndefined();+ expect(after.created.agent_label).toBe('Claude Code');+ }, 240_000);+});diff --git a/test/writer-signature.test.ts b/test/writer-signature.test.tsdeleted file mode 100644index 970407220a..0000000000--- a/test/writer-signature.test.ts+++ /dev/null@@ -1,102 +0,0 @@-/**- * Sina's point (2026-11-05): a brain already records which principal wrote a page, but a hosted caller- * that shares one principal with other AIs could not say which AI it was. A request may now sign itself- * with the `x-gbrain-writer` header; the write records it on the request's authority, and the existing- * attribution read shows it — no column, no migration, no new auth path.- *- * Protects: the mounted MCP transport reads the header and admission records it, the signature appears on- * the attribution views a read already returns, an unsigned write is unchanged, and a junk header is- * dropped rather than stored or refused. Fails when: the header is dropped before admission, invented at- * read time, or a malformed value reaches the record.- * Seams: the mounted SDK transport (bearer + worktree claim as a hosted caller would), and the op the- * read already has. PGLite only: this is a header-to-row path, not a database behaviour.- */-import { afterAll, beforeAll, expect, test } from 'bun:test';-import type { Server } from 'node:http';-import type { AddressInfo } from 'node:net';-import express from 'express';-import { mkdtempSync, rmSync } from 'node:fs';-import { tmpdir } from 'node:os';-import { join } from 'node:path';-import type { BrainEngine } from '../src/core/engine.ts';-import { PGLiteEngine } from '../src/core/pglite-engine.ts';-import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';-import { sqlQueryForEngine } from '../src/core/sql-query.ts';-import { hashToken } from '../src/core/utils.ts';-import { operationsByName, type OperationContext } from '../src/core/operations.ts';-import { mountMcp } from '../src/commands/serve-http-mcp.ts';-import type { ServeHttpContext } from '../src/commands/serve-http.ts';-import { claimWorktree } from '../src/core/persistence/ownership.ts';-import { registerLocalWriter } from '../src/core/persistence/identity.ts';-import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';-import { parseWriterSignature } from '../src/core/persistence/attribution.ts';--const SLUG = 'notes/signed-write';-const TOKEN = `synthetic-writer-signature-${process.pid}`;-let engine: BrainEngine;-let root: string;-let http: Server;-let base: string;--beforeAll(async () => {- const db = new PGLiteEngine();- await db.connect({});- await db.initSchema();- engine = db;- root = mkdtempSync(join(tmpdir(), 'gbrain-writer-signature-'));- await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');- await engine.executeRaw('UPDATE sources SET local_path=$1 WHERE id=\'default\'', [root]);- await claimWorktree(engine, 'default', root);- await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');- await registerLocalWriter(engine, 'cli');- await engine.executeRaw("INSERT INTO access_tokens(name,token_hash,scopes) VALUES('Synthetic writer token',$1,'{read,write}')", [hashToken(TOKEN)]);- const provider = new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });- const app = express();- mountMcp(app, { engine, config: { engine: 'pglite', embedding_disabled: true }, resourceVerifier: provider,- resourceMetadataUrl: 'http://127.0.0.1/resource', mcpResourceUrl: new URL('http://127.0.0.1/mcp'),- mcpOperationsBase: Object.values(operationsByName).filter(op => !op.localOnly && !op.cliOnly), broadcastEvent() {} } as unknown as ServeHttpContext);- http = await new Promise(resolve => { const listener = app.listen(0, '127.0.0.1', () => resolve(listener)); });- base = `http://127.0.0.1:${(http.address() as AddressInfo).port}`;-}, 120_000);--afterAll(async () => {- await disposePersistenceConsumer(engine);- if (http) await new Promise<void>(resolve => http.close(() => resolve()));- await engine.disconnect();- rmSync(root, { recursive: true, force: true });-});--const content = (title: string) => `---\ntype: note\ntitle: ${title}\n---\n\n# ${title}\n\nA synthetic page.\n`;-/** One real `tools/call` over the mounted transport, signed with the header (or not). */-async function write(title: string, writer?: string) {- const snapshot = await engine.readPageSnapshot(SLUG, { sourceId: 'default' });- const response = await fetch(`${base}/mcp`, { method: 'POST',- headers: { authorization: `Bearer ${TOKEN}`, 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream', ...(writer ? { 'x-gbrain-writer': writer } : {}) },- body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'put_page',- arguments: { slug: SLUG, content: content(title), ...(snapshot ? { expected_revision: snapshot.revision } : {}) } } }) });- expect(response.status).toBe(200);- expect((await response.text()).includes('"isError":true')).toBe(false);-}-const attributed = async () => await operationsByName.get_write_attribution.handler({- engine, sourceId: 'default', remote: false, config: { engine: 'pglite', embedding_disabled: true },- logger: { info() {}, warn() {}, error() {} },-} as unknown as OperationContext, { slug: SLUG }) as Record<string, any>;--test('a write signed with the header records the AI that declared itself, and the attribution read shows it', async () => {- await write('First by Claude', 'Claude Code');- expect((await attributed()).live_revision.written_by.writer).toBe('Claude Code');-- await write('Then by Codex', 'Codex');- const second = await attributed();- expect(second.created.writer).toBe('Claude Code');- expect(second.last.writer).toBe('Codex');- expect(second.live_revision.written_by.writer).toBe('Codex');-- await write('Unsigned edit');- expect((await attributed()).live_revision.written_by.writer).toBeUndefined();-- expect(parseWriterSignature(' ')).toBeUndefined();- expect(parseWriterSignature(`bad${String.fromCharCode(7)}signature`)).toBeUndefined();- expect(parseWriterSignature('x'.repeat(121))).toBeUndefined();- expect(parseWriterSignature(' Claude Code ')).toBe('Claude Code');-}, 240_000);