Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(get_page): as_of reads the page edition in force on a date (GBRA-217 valid time)

garrytan36b517820236
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 76800a8a01..e13506edcd 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,22 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [Unreleased]
+
+### Read a page as it stood on a date
+
+A page can now say when its text takes effect, with `valid_from` and `valid_until` in its frontmatter, and you can ask what was in force on any date: `get_page {slug, as_of: '2026-03-01'}`, or `gbrain get <slug> --as-of 2026-03-01`. Say to your agent: *"What did our refund policy say on March 1?"*
+
+- The answer is the edition with the latest `valid_from` on or before the date, picked across the current page and every version gbrain kept. Its `valid_time` block says whether that edition was `in_force`, `not_in_force`, `not_yet_in_force` or `before_recorded_history`, and whether gbrain held enough history to be sure. Only an `in_force` answer returns the text at the top level, so an agent that skips the status cannot quote expired text as current.
+- When history is missing (pruned versions, a sync that imported several commits at once, a page that came from a file) or the dates look ambiguous (a corrected date and a renewal leave the same trace), the answer says `uncertain: true`, why, and how to recover: the file's `git log`, or asking the user for a backup. It never guesses.
+- Works the same on a brain with no Git repository, the default keyless install.
+- `gbrain get --as-of` exits 15 when no edition was in force, and 16 (`host_upgrade_required`) when the brain host is too old to answer by date, printing nothing historical.
+- Writes say when they keep or change an edition's date (`valid_time_correction`, `valid_time_date_only`, `valid_from_unparsed`), and `get_versions` rows carry each version's `valid_from` and `valid_until`.
+- Behavior change: a plain `get_page` of a page whose own `valid_from` is in the future, or whose `valid_until` has passed, now also carries a `valid_time` status. Pages without those dates read exactly as before.
+- The write `reason` parameter moved to the full MCP surface so `as_of` fits the starter tool list.
+
+Guide: [page history](docs/guides/page-history.md#valid-time).
+
## [0.60.474.0] - 2026-10-27
**A database role that can't read the writer state is now refused instead of let through.**
diff --git a/docs/architecture/key-files/core-services-2-continued.md b/docs/architecture/key-files/core-services-2-continued.md
index d01105a307..5ac88063d3 100644
--- a/docs/architecture/key-files/core-services-2-continued.md
+++ b/docs/architecture/key-files/core-services-2-continued.md
@@ -2,7 +2,7 @@
[Subsystem index](../KEY_FILES.md) · [Previous entries](core-services-2.md). Read only the entries relevant to your change.
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
-The page-state concurrency foundation under `src/core/page-state/` and the shared progressive-batch primitive.
+The page-state concurrency foundation under `src/core/page-state/` and the shared progressive-batch primitive. Dated edition reads (`get_page` `as_of`) are in [Valid time](valid-time.md).
- `src/core/ops/get-page-slice.ts` — get_page `section` / `grep` / `context` (#7180), params `GET_PAGE_SLICE_PARAMS` (full surface only; the get_page description names them on starter, and dispatch accepts them there). `ops/get-page-body.ts` routes a slice here: `parseSliceRequest` makes it a window-mode request carrying `slice`, and `readPartialBody`, after authorization and the quarantine `body_omitted` check, passes its read document's `stream()` (the inline bytes, or `SegmentedDocument.stream()` one segment at a time) with the window's metadata and size. Both scan the read projection line by line, so a segmented page is never held whole (memory: the returned text, one segment, at most `context` paragraphs; a line over 1 MiB is scanned in pieces). `readSection`: the first ATX heading (`HEADING`, outside `FENCE` blocks, as the outline sees them) whose whitespace-folded text equals the request case-insensitively (a leading `##` is ignored), down to the next heading of the same or higher level or the timeline separator; returns `section {heading, level, heading_path, line_start, line_end, text}` and stops reading at the section's end; a miss is `invalid_params` naming up to 20 headings with `detail.total_headings` and an outline fix. `readGrep`: blank-line paragraphs with a line containing the literal term (case-insensitive, no regex), `context` paragraphs either side (default 1, clamped to 5), windows that overlap or touch merged; `grep {term, context, total_matches, returned_matches, omitted_matches, blocks[{line_start, line_end, match_starts, text}]}`. Caps: 50 matching paragraphs and `SLICE_MAX_CHARS` (100,000), fewer when the egress cap is smaller (`sliceCharBudget`); `truncated` says a cap was hit, and a cut section adds `omitted_chars` and a `next` window read. Line numbers are the read view's, the ones `body: 'window'` `lines` reads back. A slice with a selector, include_content, content_only, `view: markdown`, a body other than auto/window, or known_as_of is `invalid_params`. Every get_page shape (whole, content_only, partial, slice) carries `chars`, the characters of page text it holds (`projectGetPage`, `readPartialBody`). Test: `test/get-page-slices.test.ts` (both engines).
diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.md
index 96d74abd8a..5e5ecf008e 100644
--- a/docs/architecture/key-files/core-services-2.md
+++ b/docs/architecture/key-files/core-services-2.md
@@ -42,7 +42,7 @@ Fact and page purge modules (`src/core/facts/purge*.ts`, `deletion-inventory.ts`
- `src/core/ops/links.ts` — the link-domain op module (`add_link`, `remove_link`, `get_links`, `get_backlinks`, `list_link_sources`, `traverse_graph`); `get_backlinks`' `type`/`group`/`limit`/`cursor` live in `backlinks-paged.ts`. Three load-bearing behaviors. (1) Pack vocabulary at the write surface: an EXPLICIT `link_type` on `add_link` must be declared by the active schema pack when one resolves (`schema-pack/write-vocabulary.ts`; no resolvable pack = no enforcement; omitted/empty link_type is the untyped-edge default and stays unchecked; the check runs before the dry-run return so dry runs preview the rejection). (2) `traverse_graph` output shape: trusted local no-filter callers (`ctx.remote === false`, no `link_type`/`direction`) keep the legacy `GraphNode[]` shape that `gbrain graph` renders; remote callers default to `direction: 'both'` and always receive explicit `GraphPath[]` edges, so a page whose typed edges are all inbound does not read as edge absence. An explicit `direction` param wins for every caller. Depth: default 5 (`DEFAULT_TRAVERSE_DEPTH`), except a remote call that let direction default to `both` ALSO defaults depth to `REMOTE_BIDIRECTIONAL_DEFAULT_DEPTH` (2) — bidirectional path enumeration is combinatorial on entity hubs and this is the per-agent-turn path; a `link_type`-only remote call still takes both/2; an explicit depth is honored up to `TRAVERSE_DEPTH_CAP` (10, clamped with a warn). The edge walk runs through `engine.traversePathsDetailed`, and a hit on `TRAVERSE_PATH_ROW_CAP` (`engine-constants.ts`) surfaces as a stderr warn naming the cap (shallowest edges kept) — the `GraphPath[]` wire shape stays unchanged. Pinned by `test/traverse-graph-op-default.test.ts` + `test/traverse-paths-row-cap.test.ts`. (3) Link-read source scope: the three read ops take `source_id` (`parseSourceIdParam`, `__all__` admitted) and `all_sources` (equivalent to `__all__`; both together is `invalid_params`). `resolveLinkReadScope` composes `federatedSearchScope` (grant check, #5081 admission, unqualified no-grant widening to `localFederatedSourceIds`; a grant never widens), then `assertExplicitSourceLive` (so an archived source outside the caller's admission answers `permission_denied`, not `unknown_source`), then `linkReadScopeOpts` (remote scalar promoted to `sourceIds[]` for the engine's all-endpoints branch), then `readPolicyOpts`. A trusted local unqualified read that comes back as the federated `sourceIds[]` runs the scalar read once per federated source (set order, resolved source first) and merges de-duplicated on link identity, keeping the scalar branch's cross-source far endpoints; `traverse_graph` walks the federated set in one query because its scalar walk already scopes every node. A trusted local unqualified link read that returns nothing prints a stderr rerun hint naming sources outside the read that hold links for the slug (quiet under `json`, never for remote callers). CLI names: `links` (alias `get_links`), `backlinks`, `graph`. (4) Row paging (#6876): rows are keyset-paged by `ops/link-paging.ts` (cap after the source/identity merge; see its header). Pinned by `test/link-read-paging.test.ts`. Pinned by `test/federated-link-reads-5827.test.ts`, `test/link-reads-thin-client-5827.serial.test.ts` and `test/e2e/federated-link-reads-postgres.test.ts`. `traverse_graph` `hops` (1-3 `{link_type, toward}`) runs a typed chain through `runRelationalChain` under the op's read scope, returns `{anchor, answers, paths, diagnostics}` with evidence edges (remote context sanitized), refuses `hops` combined with `depth`/`link_type`/`direction` and bad hops as `invalid_params` naming the parameter path, and emits a `relational_chain` notice with the next call when the chain finds nothing. Pinned by `test/traverse-graph-hops.test.ts`. `all_sources` is full-surface-only (starter passes `source_id: '__all__'`).
-- `src/core/ops/pages.ts` — page operations share source validation and the persistence coordinator. Replacements require `expected_revision` or explicit `force`; omitted preconditions permit creation only. The put_page description keeps `Keep a request_id UUID; retry with identical arguments` within its 1,460-character schema budget (pinned by `test/mcp-schema-budget.test.ts` minimum guidance; the description and the content param both keep the get_page include_content:true read that `test/mcp-tool-defs.test.ts` pins). `get_page` and `fetch` use `page-state/snapshot.ts` for exact/alias resolution, content, tags, revision and withdrawal overlays in one SQL snapshot; fuzzy fallback uses a short repeatable-read transaction with the same visibility and source ceilings. `get_page` `content_only` (`ops/get-page-projection.ts`) returns slug, source_id, type, title, revision, tags, content and chars (keys pinned by `test/get-page-content-roundtrip-2225.test.ts`). A put_page `revision_conflict` (`ops/put-page-revision-source.ts`) whose expected_revision is the current revision of the same slug in another source the caller may read (grant via `federatedSearchScope`, private pages excluded for untrusted readers) names that source and gets a re-read fix; otherwise the refusal is unchanged. `get_page` adds `file_held` when sync holds the page's newer file (`persistence/held-reads.ts`; path for trusted local callers only). Missing migration dependencies and connection errors propagate. Capture freezes target/type/timestamp/provenance before admission and resolves same-ID replay first. `persistence/links-preparation.ts` prepares trusted automatic graph reconciliation outside locks, then installs it with canonical projections and the receipt; delayed oneshot reconciliation validates its originating revision. `persistence/page-advisories.ts` prepares bounded, content-free lint findings. Tests cover source/alias ownership, concurrent graph replacements, stale delayed reconciliation, private fences and durable retries. `list_pages` passes `listColumnsOnly` so `engine-sql/pages.ts:listPages` projects identity, type, title and dates without reading page bodies or frontmatter (`list-pages-columns-5154.test.ts`). `delete_page` accepts a strict boolean `purge` only from trusted local callers. Immediate purge uses the same durable journal, observed revision (or explicit `force`), stored/current authority and exact request-ID replay as other page mutations. Owner preparation resolves the recorded file from a coherent snapshot, including tombstones; file removal precedes hard deletion and receipt commitment in the guarded publication transaction. Failed publication preserves the prior active row or existing tombstone and never overwrites unexpected file bytes. The receipt reports the actual filesystem/database persistence outcome and warns that repository history, synced copies, exports and derived artifacts may retain content. The `gbrain delete <slug> --purge` flag derives from the operation contract. `list_pages` probes `limit + 1` rows: a local CLI caller gets a stderr truncation notice; every dispatched caller gets `_meta.pagination` (`truncated`, `limit`, `clamped_from?`, `next?`) and a remote caller whose page was truncated also gets the model-visible `listing_truncated` notice whose `fix.mcp` is the next-page call (`ops/list-pages-pagination.ts`; `next` is the `updated_asc` keyset or an offset). Test: `test/list-pages-truncation.test.ts`. An `updated_after` the database cannot cast (SQLSTATE 22007/22008, the shared `isDatetimeInputError` in `core/utils.ts` that the hybrid lexical arms also use) is `invalid_params` with a read-only list_pages fix, never echoing the value; other SQLSTATEs pass through (`test/list-pages-timestamp-input.test.ts`). put_page (dry runs included) refuses a new `.md`/`.mdx`-suffixed slug (`persistence/suffixed-slug.ts`). #6212: `delete_page` and `restore_page` (dry runs included) go through `persistence/page-mutations.ts:validateMutationSlug`, which admits a legacy stored slug (`ops/context.ts:isLegacyStoredPageSlug`: refused by today's grammar, still accepted by `validateSlug`) only when an existing row in the target source holds it; every other operation keeps `validatePageSlug`, and remote purge stays denied by `assertPurgeParams`. Large pages: `get_page` resolves its body mode first (`parseBodyRequest`, `src/core/ops/get-page-body.ts`) and returns `readPartialBody` for none/outline/window/auto-above-256 KB, `assertFullReadFits` guarding whole remote reads; `fetch` of a page over the inline size returns `fetchWindowResult` (window around the id's chunk anchor, `metadata.next_id`); remote `put_page` runs `assertLargePageAdmission` before queueing. A committed segmented write's outcome records `searchable` (`true`, `'pending'` when its projection runs after commit, `false` when quarantined); `persistence/searchable.ts:liveSearchable` re-reads a pending one whenever the receipt is served (the put_page reply in `page-mutations.ts`, `get_write_request`) and adds `searchable_retry_after_ms` and a `searchable_fix` that reads the receipt again (`test/large-pages/segmented-create-searchable.test.ts`). Only writes load `page-mutations.ts` (`test/cold-read-module-graph.test.ts`). The starter list leaves out (`fullSurfaceOnly`, still accepted) get_page `fuzzy`/`content_only`/`include_deleted`/`include_timeline_entries`/`include_quarantined`, list_pages `offset`/`include_deleted`, put_page `allow_empty`/`drop_timeline` (their refusals name them) and the server-set provenance params, and capture `expected_revision`/`force`/`local_file`.
+- `src/core/ops/pages.ts` — page operations share source validation and the persistence coordinator. Replacements require `expected_revision` or explicit `force`; omitted preconditions permit creation only. The put_page description keeps `Keep a request_id UUID; retry with identical arguments` within its schema budget (pinned by `test/mcp-schema-budget.test.ts` minimum guidance; the description and the content param both keep the get_page include_content:true read that `test/mcp-tool-defs.test.ts` pins). `get_page` and `fetch` use `page-state/snapshot.ts` for exact/alias resolution, content, tags, revision and withdrawal overlays in one SQL snapshot; fuzzy fallback uses a short repeatable-read transaction with the same visibility and source ceilings. `get_page` `content_only` (`ops/get-page-projection.ts`) returns slug, source_id, type, title, revision, tags, content and chars (keys pinned by `test/get-page-content-roundtrip-2225.test.ts`). A put_page `revision_conflict` (`ops/put-page-revision-source.ts`) whose expected_revision is the current revision of the same slug in another source the caller may read (grant via `federatedSearchScope`, private pages excluded for untrusted readers) names that source and gets a re-read fix; otherwise the refusal is unchanged. `get_page` adds `file_held` when sync holds the page's newer file (`persistence/held-reads.ts`; path for trusted local callers only). Missing migration dependencies and connection errors propagate. Capture freezes target/type/timestamp/provenance before admission and resolves same-ID replay first. `persistence/links-preparation.ts` prepares trusted automatic graph reconciliation outside locks, then installs it with canonical projections and the receipt; delayed oneshot reconciliation validates its originating revision. `persistence/page-advisories.ts` prepares bounded, content-free lint findings. Tests: source/alias ownership, concurrent graph replacements, stale delayed reconciliation, private fences, durable retries. `list_pages` passes `listColumnsOnly` so `engine-sql/pages.ts:listPages` projects identity, type, title and dates without reading page bodies or frontmatter (`list-pages-columns-5154.test.ts`). `delete_page` accepts a strict boolean `purge` only from trusted local callers. Immediate purge uses the same durable journal, observed revision (or explicit `force`), stored/current authority and exact request-ID replay as other page mutations. Owner preparation resolves the recorded file from a coherent snapshot, including tombstones; file removal precedes hard deletion and receipt commitment in the guarded publication transaction. Failed publication preserves the prior active row or existing tombstone and never overwrites unexpected file bytes. The receipt reports the actual filesystem/database persistence outcome and warns that repository history, synced copies, exports and derived artifacts may retain content. The `gbrain delete <slug> --purge` flag derives from the operation contract. `list_pages` probes `limit + 1` rows: a local CLI caller gets a stderr truncation notice; every dispatched caller gets `_meta.pagination` (`truncated`, `limit`, `clamped_from?`, `next?`) and a remote caller whose page was truncated also gets the model-visible `listing_truncated` notice whose `fix.mcp` is the next-page call (`ops/list-pages-pagination.ts`; `next` is the `updated_asc` keyset or an offset). Test: `test/list-pages-truncation.test.ts`. An `updated_after` the database cannot cast (SQLSTATE 22007/22008, the shared `isDatetimeInputError` in `core/utils.ts` that the hybrid lexical arms also use) is `invalid_params` with a read-only list_pages fix, never echoing the value; other SQLSTATEs pass through (`test/list-pages-timestamp-input.test.ts`). put_page (dry runs included) refuses a new `.md`/`.mdx`-suffixed slug (`persistence/suffixed-slug.ts`). #6212: `delete_page` and `restore_page` (dry runs included) go through `persistence/page-mutations.ts:validateMutationSlug`, which admits a legacy stored slug (`ops/context.ts:isLegacyStoredPageSlug`: refused by today's grammar, still accepted by `validateSlug`) only when an existing row in the target source holds it; every other operation keeps `validatePageSlug`, and remote purge stays denied by `assertPurgeParams`. Large pages: `get_page` resolves its body mode first (`parseBodyRequest`, `src/core/ops/get-page-body.ts`) and returns `readPartialBody` for none/outline/window/auto-above-256 KB, `assertFullReadFits` guarding whole remote reads; `fetch` of a page over the inline size returns `fetchWindowResult` (window around the id's chunk anchor, `metadata.next_id`); remote `put_page` runs `assertLargePageAdmission` before queueing. A committed segmented write's outcome records `searchable` (`true`, `'pending'` when its projection runs after commit, `false` when quarantined); `persistence/searchable.ts:liveSearchable` re-reads a pending one whenever the receipt is served (the put_page reply in `page-mutations.ts`, `get_write_request`) and adds `searchable_retry_after_ms` and a `searchable_fix` that reads the receipt again (`test/large-pages/segmented-create-searchable.test.ts`). Only writes load `page-mutations.ts` (`test/cold-read-module-graph.test.ts`). The starter list leaves out (`fullSurfaceOnly`, still accepted) get_page `fuzzy`/`content_only`/`include_deleted`/`include_timeline_entries`/`include_quarantined`, list_pages `offset`/`include_deleted`, put_page `allow_empty`/`drop_timeline` (refusals name them), the write ops' `reason` and the server-set provenance params, and capture `expected_revision`/`force`/`local_file`.
- `src/core/persistence/large-page-guard.ts` — put_page against a page over 256 KB: `assertLargePageAdmission` (remote, before queueing) refuses `force` without `expected_revision` (`revision_required`) and content under half the stored body (`page_shrink_refused`) unless `allow_shrink`; `assertLargePageReplacement` re-checks the parsed body against the locked snapshot in preparation (`page-prepare.ts`).
- `src/core/ops/page-edit.ts` — the `edit_page` operation (write scope, starter surface, client slug-fence allowlist): validates edits and the optional `within` range (full surface only), then submits through `submitPageMutation` like put_page; matching and the diff live in `persistence/page-edit.ts`.
diff --git a/docs/architecture/key-files/valid-time.md b/docs/architecture/key-files/valid-time.md
new file mode 100644
index 0000000000..1900186f0b
--- /dev/null
+++ b/docs/architecture/key-files/valid-time.md
@@ -0,0 +1,28 @@
+# Valid time (page editions by date)
+
+GBRA-217. Guide: [page history](../../guides/page-history.md#valid-time). Recorded time (`known_as_of`) is the
+[belief ledger](belief-ledger.md).
+
+- `src/core/valid-time.ts` — the one date normaliser (`validDate` in TypeScript, `validDateSql` in SQL, the same
+ pattern: `YYYY-MM-DD`, a YAML Date or a midnight-UTC timestamp; anything else is undated), the pure status rules
+ (`validTimeVerdict`: status, history `retained|incomplete|unknown`, the one `why`), the plain-read status
+ (`currentValidTime`), the write advisory (`validTimeWriteAdvisory`) and the client's version-skew check
+ (`assertValidTimeEcho`, `host_upgrade_required`). Intervals are half-open, as links are.
+- `src/core/ops/valid-time-read.ts` — `get_page {as_of}`. One REPEATABLE READ transaction: the page identity (a slug in
+ two granted sources refuses), then one statement picks over the current page and its `page_versions` (greatest
+ `valid_from` on or before the date, latest recorded on a tie) with the counts, gap facts and ambiguity window, before
+ any visibility check; a chosen edition the caller may not see is `page_not_found`. Reasons use
+ `replacedBecauseSql`, so their visibility matches `get_versions`. Only `in_force` returns text at the top level;
+ other statuses nest the edition under `last_in_force` / `earliest_known`. Large or segmented editions are windowed;
+ the gpw1 cursor pins `v:<version id>` or the current revision (found again among versions if the page moved on), and
+ an edition that has gone answers `history: incomplete`, `why: edition_pruned`. Recovery fixes: `git log --follow`
+ for a world-visible file in a source with a checkout, else `ask_user` for a backup (always on a repo-less brain).
+- `src/core/persistence/valid-time-advisory.ts` — `withValidTimeAdvisory`, wrapped around `withChangeReason` in
+ `service.ts` for page writes: compares the page before and after the apply and adds `valid_time` to the outcome
+ (`valid_from_unparsed`, `valid_time_correction`, `valid_time_date_only`). Reads only rows the write's transaction
+ produced; changes nothing.
+- `src/cli/page-render.ts` valid-time helpers — `validTimeLine` (stderr header), `printAsOfWindows` (pages a windowed
+ edition by its `next` calls), `asOfExitCode` (15 when no edition is in force). `src/cli/main.ts` calls
+ `assertValidTimeEcho` on every thin-client as_of reply.
+
+Pinned by `test/valid-time-gbra217.test.ts` (PGLite and Postgres).
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 6eafb98264..bdebeb7cc7 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -15,6 +15,7 @@ Under contract v1 an `error` value never changes. Where a surface sends a legacy
| `error` (frozen) | `code` (canonical) | Meaning |
|---|---|---|
+| `invalid_params` | `change_reason_rejected` | The write's reason was refused before anything was admitted: it is longer than 500 characters, or it looks like it holds a secret. |
| `invalid_params` | `fact_withdrawn` | `remember`, or an owner `gbrain trust release` that writes a held fact into its entity page's `## Facts` table (a managed brain), refused a claim that was explicitly forgotten for this subject (wire `invalid_params`, message prefix `fact_withdrawn:`); nothing was saved, and a refused release leaves the fact held. |
| `permission_denied` | `insufficient_scope` | The connection lacks the OAuth scope the operation requires. |
| `invalid_params` | `invalid_fence` | A facts or takes fence in the page cannot be imported without dropping or guessing rows, so the page (or the file) was not written. |
@@ -509,6 +510,18 @@ More: [docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover](../../
|---|---|---|---|---|---|---|
| Shared skill storage is not ready on this brain. | A temporary condition (a lock, a pending write, a rate limit); the same request can succeed later. | Wait briefly, then retry the same request (writes: reuse the same request_id). | agent | `repeat the read that failed` | 1 | yes |
+### change_reason_rejected
+
+<a id="change_reason_rejected"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| The write's reason was refused before anything was admitted: it is longer than 500 characters, or it looks like it holds a secret. | A reason is kept in page history and, on a page that reaches Git, in the commit message, which a push makes permanent; it is checked before the write is journaled so no copy of a refused reason is stored anywhere. | Shorten the reason, or remove the secret from it, and send the write again. | agent | `repeat the read that failed` | 1 | no |
+
+Reasons: `reason_too_long`, `reason_contains_secret`.
+
+More: [docs/guides/page-history.md#reasons](../../docs/guides/page-history.md#reasons)
+
### changed_since_preview
<a id="changed_since_preview"></a>
@@ -609,9 +622,9 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-c
| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
|---|---|---|---|---|---|---|
-| A time parameter got a value on the wrong clock: `known_as_of` (recorded time) needs an instant with a zone, not a calendar date. | Recorded time (`known_as_of`) is when the brain had recorded something; valid time (`as_of`) is when a fact held in the world, as a date. A bare date is ambiguous as a recorded-time instant, so it is refused instead of guessed. | Pass a full instant such as 2026-10-01T12:00:00Z to known_as_of, or use as_of where the tool takes a valid-time date. | agent | `repeat the read that failed` | 1 | no |
+| A time parameter got a value on the wrong clock: `known_as_of` (recorded time) needs an instant with a zone, not a calendar date (`date_for_instant`); get_page `as_of` (valid time) needs a calendar date, not an instant (`instant_for_date`). | Recorded time (`known_as_of`) is when the brain had recorded something; valid time (`as_of`) is when a fact held in the world, as a date. A bare date is ambiguous as a recorded-time instant, and an instant is not an edition date, so each is refused instead of guessed. | Pass a full instant such as 2026-10-01T12:00:00Z to known_as_of, or use as_of where the tool takes a valid-time date. | agent | `repeat the read that failed` | 1 | no |
-Reasons: `date_for_instant`.
+Reasons: `date_for_instant`, `instant_for_date`.
More: [docs/guides/repair.md#clock-mismatch](../../docs/guides/repair.md#clock-mismatch)
@@ -2119,6 +2132,16 @@ More: [docs/guides/write-refusals.md#head-blocked](../../docs/guides/write-refus
More: [docs/guides/troubleshooting.md#host-identity-mismatch](../../docs/guides/troubleshooting.md#host-identity-mismatch)
+### host_upgrade_required
+
+<a id="host_upgrade_required"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| The brain host is older than this client and did not answer the question asked: a get_page reply to an `as_of` read came back without `valid_time.as_of`, so it is the current page, not the edition in force on that date. Nothing historical was printed. | An older host ignores a read parameter it does not know and answers the plain read. Printing that answer as the edition in force on a date would quote the wrong text, so the client fails closed. The error carries the client version, the host version when known, and the minimum host version. | Upgrade gbrain on the brain host (`gbrain upgrade`), or ask its operator to; then run the same read again. | host_admin | `gbrain doctor --json` | 16 | no |
+
+More: [docs/guides/page-history.md#host_upgrade_required](../../docs/guides/page-history.md#host_upgrade_required)
+
### hosted_repo_refused
<a id="hosted_repo_refused"></a>
@@ -4599,6 +4622,16 @@ More: [docs/guides/troubleshooting.md#upstream-rewritten](../../docs/guides/trou
More: [docs/guides/troubleshooting.md#upstream-rewritten](../../docs/guides/troubleshooting.md#upstream-rewritten)
+### valid_time_undeclared
+
+<a id="valid_time_undeclared"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| An `as_of` read found no version of the page that declares a readable `valid_from`, so no edition can be placed on the date. | Valid time comes only from the `valid_from` / `valid_until` frontmatter the page carries; gbrain never infers when text took effect. Only the user knows the date, so the fix asks them before a templated edit_page records it. | Ask the user when the text took effect and record it as a quoted valid_from (the fix carries the edit). For what the brain had recorded at a time, read with known_as_of instead. | agent | `repeat the read that failed` | 1 | no |
+
+More: [docs/guides/page-history.md#valid_time_undeclared](../../docs/guides/page-history.md#valid_time_undeclared)
+
### vector_prewarm_extension_missing
<a id="vector_prewarm_extension_missing"></a>
diff --git a/docs/guides/exit-codes.md b/docs/guides/exit-codes.md
index 5d92702396..b9bacf9511 100644
--- a/docs/guides/exit-codes.md
+++ b/docs/guides/exit-codes.md
@@ -19,6 +19,8 @@ the exit code first, then reads the JSON document (`--json`) for the details:
| 12 | `no_results`: `gbrain recall` (an entity, text, `--grep`, `--question` or `--query` lookup) or `gbrain entity` matched nothing. Opt-in: only with `GBRAIN_FAIL_ON_EMPTY=1`; otherwise a miss exits 0 | recall's list output: `status: "no_results"`; entity: `found: false` | treat it as a miss, not a failure; a script that filters stdout can branch on it |
| 13 | `pending_verify`: `gbrain bootstrap harness --token` wired a PGLite brain while no serve answered; nothing failed, nothing verified yet | the harness result with `status: "pending_verify"` and `fix` | tell the user to start `gbrain serve --http`, then run `fix.command` with the same token; `bootstrap harness --status` stays partial until it passes ([pending verify](bootstrap.md#pending-verify)) |
| 14 | `bootstrap_cleanup_pending`: `gbrain bootstrap harness` (or `--status`) wired and verified the harness, but earlier shared-skills enrollments or carried token ids are not cleaned up yet | the harness result with `status: "cleanup_pending"`, a per-id `cleanup` list and `fix` | follow `fix.next`: `run` re-runs the same command; `tell_user_to_run` relays the owner's revoke or restore step, then re-run ([cleanup pending](bootstrap.md#cleanup-pending)) |
+| 15 | `gbrain get --as-of`: no edition in force on that date | the result with `valid_time` | read `status` and `why`; quote nothing as in force ([valid time](page-history.md#valid-time)) |
+| 16 | `host_upgrade_required`: the host is too old to read by date; nothing printed | error envelope | relay `gbrain upgrade` on the brain host ([details](page-history.md#host_upgrade_required)) |
| 69 | `gbrain serve` exited on its own after its persistence consumer reported `restart_required` for `GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS` (`serve_unhealthy_exit`; opt-in) | `[gbrain serve] error code=serve_unhealthy_exit` line on stderr | nothing: the supervisor (the installed service restarts on failure) starts a fresh serve; if it repeats, follow [the unhealthy exit](../ENGINES.md#serve-unhealthy-exit) |
| 75 | another runner holds the migration lock, or an engine graduation owns the brain (`graduation_in_progress`) | error envelope | wait for the other runner, then retry |
| 124 | the command's own deadline elapsed | error envelope | inspect what is still running (the message names the status command) |
diff --git a/docs/guides/page-history.md b/docs/guides/page-history.md
new file mode 100644
index 0000000000..b0c899295d
--- /dev/null
+++ b/docs/guides/page-history.md
@@ -0,0 +1,167 @@
+# Page history
+
+<!-- GBRA-217: PR A owns the reasons section; PR B wrote the valid-time section. -->
+
+## Reasons
+
+A page write (`put_page`, `edit_page`, `revert_version`, `put_pages`) can carry
+a one-line `reason` (at most 500 characters; a reason that looks like it holds
+a secret is refused `change_reason_rejected`). gbrain keeps it on the version the
+write replaced, and `get_versions` shows it as `replaced_because`. On a page
+whose file is committed, the commit also carries the trailer
+`gbrain-reason: <path>: <text>`.
+
+## Valid time
+
+A page can say when its text takes effect. Put `valid_from` (and, if the text
+stops applying, `valid_until`) in its frontmatter:
+
+```yaml
+---
+title: Refund policy
+valid_from: '2026-07-01'
+valid_until: '2027-01-01'
+---
+```
+
+The dates are part of the page, so on a brain with a Git repository they live
+in the file and in every commit, and gbrain keeps them on each retained version.
+The interval is half-open: the text is in force from `valid_from` up to, but
+not including, `valid_until`, the same rule links use. Write the dates quoted.
+An unquoted YAML date also works; a partial date (`2026-07`), a time of day or
+another zone does not, and the write result warns `valid_from_unparsed`.
+
+**Say to your agent:** *"What did our refund policy say on March 1?"* The agent
+reads the page with `get_page {slug, as_of: '2026-03-01'}` (CLI:
+`gbrain get <slug> --as-of 2026-03-01`).
+
+Nothing changes until a page carries `valid_from` or a caller passes `as_of`.
+There is no config key.
+
+### Which tool records a change in effect
+
+| The change | Record it as | as_of reads |
+|---|---|---|
+| The text of the page changes from a date on (a new edition) | edit the page in place and set `valid_from` to that date (keep the old date for a plain correction) | the edition whose `valid_from` is the latest on or before the date |
+| A separate document changes part of it (an addendum, a rider) | an amendment record: its own page with an `amends` link to this page, dated by its `since` | the page's own edition; amendments dated after that edition and on or before the date are listed in `valid_time.amendments_not_applied`, not merged into the text |
+| A new page replaces this one | a `supersedes` link from the new page | this page's editions only; follow the link for the new page |
+
+### How the edition is chosen
+
+The candidates are the current page and its retained versions. The answer is
+the edition with the greatest `valid_from` on or before the date; when two
+share that date, the one recorded last wins, as a correction of that edition.
+Nothing is excluded by guesswork.
+
+Some histories look alike: a corrected date, a renewal of unchanged text, a
+backfilled old edition and a withdrawn scheduled edition all leave the same
+shape. When the versions around the date have that shape (the same body under
+another `valid_from`, or a version recorded later with an earlier
+`valid_from`), the answer is still the rule's pick, and it says so:
+`valid_time.uncertain: true`, `why: ambiguous_edition_dates`, with
+`competing_version_ids`. Its `fix` asks the user which date the edition took
+effect, then offers an `edit_page` that sets `valid_from`.
+
+If the chosen edition is private (or below the caller's `min_trust`), a remote
+caller gets the answer a private page gets: not found. It never falls back to an
+older edition it may see. Reasons follow the same rule as `get_versions`.
+
+### The answer
+
+`valid_time` is in every answer:
+
+| Field | Meaning |
+|---|---|
+| `as_of` | the date asked about, echoed |
+| `status` | `in_force`, `not_in_force` (its `valid_until` has passed), `not_yet_in_force` (every edition starts later, and gbrain holds the page's whole history), `before_recorded_history` (every known edition starts later, but earlier editions may exist outside gbrain) |
+| `chosen_version_id`, `chosen_is_current` | which edition was picked (`null` id for the current page) |
+| `valid_from`, `valid_until` | the chosen edition's dates |
+| `introduced_because`, `replaced_because` | the reasons given for the write that produced the edition and the one that replaced it |
+| `history` | `retained`, `incomplete` or `unknown` |
+| `uncertain`, `why` | whether to trust the pick, and the one reason not to |
+| `undated_versions` | versions with no readable `valid_from`; they are never picked |
+| `amendments_not_applied` | amendment records in force on the date that the text does not include |
+| `recorded_since` | when gbrain recorded the chosen edition |
+
+Only `in_force` returns the text at the top level. Any other status puts the
+edition under `last_in_force` or `earliest_known`, so a reader that ignores
+the status cannot quote expired or future text as current.
+
+A large edition is returned in windows. Each `next` call carries the slug,
+source, date and a cursor pinned to that edition, so the read stays on it even
+if the page changes meanwhile.
+
+On the CLI, `gbrain get --as-of` prints a `[gbrain] valid_time` line on
+stderr. An `in_force` answer prints the page on stdout and exits 0. Any other
+status prints `status:` and `why:` on stdout, no page, and exits 15
+([exit codes](exit-codes.md)).
+
+A plain read (`get_page`, `gbrain get`) of a page whose own `valid_from` is
+after today, or whose `valid_until` has passed, also carries `valid_time`
+(`status`, `as_of` today and both dates), and the CLI prints it on stderr.
+
+### When history is incomplete
+
+gbrain can only answer from the versions it kept. The answer says when that is
+not enough, and only when it matters for the date asked about:
+
+- `history_pruned` or `history_gap`: versions were pruned, or a sync imported
+ several commits of the file at once, inside the chosen edition's span (or the
+ date is before every retained edition). Dates the retained editions cover
+ after the gap stay certain.
+- `history_unknown`: the page has enough large or segmented versions that a
+ prune may have run before gbrain recorded prunes.
+- `before_recorded_history`: the page came from a file, so editions before
+ its first gbrain version may exist in Git.
+- `edition_pruned`: the edition a window cursor pinned is no longer retained;
+ no text is returned.
+
+The `fix` depends on where the missing history lives. For a page whose file
+sits in a Git checkout, it is `git log --follow -p -- <path>` (a remote caller
+gets it as a command to relay). For a private, database-only or unfiled page,
+and on a brain with no Git repository, it asks the user for a retained copy or
+a backup; retrying the read unchanged gives the same answer.
+
+### Brains with no Git repository
+
+The default keyless install has no Git repository, and valid time works the
+same there: the dates are in the stored frontmatter of each version, the pick
+and every status come from the database, and the recovery asks for a backup
+instead of naming a Git command.
+
+### Writes that keep or change the date
+
+A write result can carry a `valid_time` advisory:
+
+- `valid_time_correction`: the body changed and `valid_from` did not, so
+ the change is read as a correction of the edition in force since that date.
+ Set `valid_from` if the change takes effect later.
+- `valid_time_date_only`: only `valid_from` changed. That is a question, not
+ an error: is this a correction of the earlier date, or a renewal of unchanged
+ text? as_of reads around those dates are marked `ambiguous_edition_dates`.
+- `valid_from_unparsed`: `valid_from` is not a date gbrain can read.
+
+### valid_time_undeclared
+
+No retained version of the page has a readable `valid_from`. gbrain does not
+invent one. The `fix` asks the user when the text took effect, then offers an
+`edit_page` that adds a quoted `valid_from`. To ask what the brain had
+recorded at a moment instead, read with `known_as_of` (recorded time).
+
+### Refusals
+
+`as_of` takes a calendar date. An instant is refused `clock_mismatch` with
+reason `instant_for_date` ([clock mismatch](repair.md#clock-mismatch)). It does
+not combine with `known_as_of`, or with `include_content` or
+`content_only`: writing an old edition back would silently revert the page.
+A slug that exists in two sources you can read is refused until you pass
+`source_id`.
+
+### host_upgrade_required
+
+The gbrain CLI or an MCP client asked a host for `as_of`, and the reply did
+not echo `valid_time.as_of`. An older host ignores the parameter and returns
+the current page, so the client prints nothing and exits 16. The error names
+the client version, the host version and the minimum host version. Run
+`gbrain upgrade` on the brain host, or ask whoever runs it. Without
+`valid_time` in a reply, the reply is the current page.
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index bbb4170780..0d67ace580 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -3622,6 +3622,11 @@ names.
valid time; recorded time needs an instant. Pass a full instant such as
`2026-10-01T12:00:00Z`.
+get_page `as_of` got an instant (`reason: instant_for_date`). `as_of` is valid
+time: the date an edition was in force, so pass the date alone
+(`2026-10-01`). For the page as the brain had recorded it at a moment, pass
+the instant to `known_as_of` instead ([valid time](page-history.md#valid-time)).
+
### Known as of unproven
A change to the page was recorded before the instant, but nothing proves it
diff --git a/docs/protocol/AGENT_OPERATOR_v1.md b/docs/protocol/AGENT_OPERATOR_v1.md
index 2fd96466b5..a73fbd36b9 100644
--- a/docs/protocol/AGENT_OPERATOR_v1.md
+++ b/docs/protocol/AGENT_OPERATOR_v1.md
@@ -1013,6 +1013,8 @@ that work in this conversation.
| 12 | `no_results`: a recall or entity lookup matched nothing (only with `GBRAIN_FAIL_ON_EMPTY=1`) | treat it as a miss, not a failure |
| 13 | `pending_verify`: a harness wired, verification waits for the serve | start the serve, then run `fix.command` |
| 14 | `bootstrap_cleanup_pending`: a harness is wired; old shared-skills enrollments or token ids still await cleanup | follow `fix.next` (re-run, or relay the owner's revoke step), then re-run |
+| 15 | `get --as-of`: no edition in force | read `valid_time`; quote nothing |
+| 16 | `host_upgrade_required` | relay `gbrain upgrade` on the host |
| 75 | another runner holds the migration lock | wait, then retry |
| 124 | the command's deadline elapsed | inspect what is still running |
| 130 | interrupted | ask the user whether to re-run |
diff --git a/llms-full.txt b/llms-full.txt
index 8bb509c82f..f3766b42ea 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -4526,6 +4526,8 @@ that work in this conversation.
| 12 | `no_results`: a recall or entity lookup matched nothing (only with `GBRAIN_FAIL_ON_EMPTY=1`) | treat it as a miss, not a failure |
| 13 | `pending_verify`: a harness wired, verification waits for the serve | start the serve, then run `fix.command` |
| 14 | `bootstrap_cleanup_pending`: a harness is wired; old shared-skills enrollments or token ids still await cleanup | follow `fix.next` (re-run, or relay the owner's revoke step), then re-run |
+| 15 | `get --as-of`: no edition in force | read `valid_time`; quote nothing |
+| 16 | `host_upgrade_required` | relay `gbrain upgrade` on the host |
| 75 | another runner holds the migration lock | wait, then retry |
| 124 | the command's deadline elapsed | inspect what is still running |
| 130 | interrupted | ask the user whether to re-run |
@@ -11099,47 +11101,6 @@ Verify with `gbrain sources status <id> --json` and
---
-## docs/guides/exit-codes.md
-
-Source: https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/exit-codes.md
-
-# Exit codes
-
-Every `gbrain` command exits with one of these statuses. An agent branches on
-the exit code first, then reads the JSON document (`--json`) for the details:
-`code`, `class`, `retryable` and `fix`. The protocol page is
-[AGENT_OPERATOR_v1](../protocol/AGENT_OPERATOR_v1.md); error codes are listed in
-[error codes](error-codes.md).
-
-**Say to your agent:** *"The gbrain command exited 3. What does it need from me?"*
-
-| Exit | Meaning | `--json` document | What the agent does |
-|---|---|---|---|
-| 0 | ok | the result | continue |
-| 1 | failed | error envelope with `class` and `retryable` | follow `fix.next`; retry only when `retryable` is true |
-| 2 | usage error or invalid input | error envelope (`invalid_params`, `unknown_flag`) | correct the command; `gbrain <command> --help` |
-| 3 | `confirmation_required`: nothing ran | consent payload (`effects`, `user_message`, `fix`) | stop, relay `user_message` to the user, run `fix.command` only after they agree |
-| 10 | the write was accepted and is still pending | write receipt | poll the receipt (`gbrain write-request -- <id>`); `--accept-pending` maps this to 0 |
-| 11 | partial, resumable budget stop | result with `remaining_*` and `resume_command` | run `resume_command` (it is safe to re-run) |
-| 12 | `no_results`: `gbrain recall` (an entity, text, `--grep`, `--question` or `--query` lookup) or `gbrain entity` matched nothing. Opt-in: only with `GBRAIN_FAIL_ON_EMPTY=1`; otherwise a miss exits 0 | recall's list output: `status: "no_results"`; entity: `found: false` | treat it as a miss, not a failure; a script that filters stdout can branch on it |
-| 13 | `pending_verify`: `gbrain bootstrap harness --token` wired a PGLite brain while no serve answered; nothing failed, nothing verified yet | the harness result with `status: "pending_verify"` and `fix` | tell the user to start `gbrain serve --http`, then run `fix.command` with the same token; `bootstrap harness --status` stays partial until it passes ([pending verify](bootstrap.md#pending-verify)) |
-| 14 | `bootstrap_cleanup_pending`: `gbrain bootstrap harness` (or `--status`) wired and verified the harness, but earlier shared-skills enrollments or carried token ids are not cleaned up yet | the harness result with `status: "cleanup_pending"`, a per-id `cleanup` list and `fix` | follow `fix.next`: `run` re-runs the same command; `tell_user_to_run` relays the owner's revoke or restore step, then re-run ([cleanup pending](bootstrap.md#cleanup-pending)) |
-| 69 | `gbrain serve` exited on its own after its persistence consumer reported `restart_required` for `GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS` (`serve_unhealthy_exit`; opt-in) | `[gbrain serve] error code=serve_unhealthy_exit` line on stderr | nothing: the supervisor (the installed service restarts on failure) starts a fresh serve; if it repeats, follow [the unhealthy exit](../ENGINES.md#serve-unhealthy-exit) |
-| 75 | another runner holds the migration lock, or an engine graduation owns the brain (`graduation_in_progress`) | error envelope | wait for the other runner, then retry |
-| 124 | the command's own deadline elapsed | error envelope | inspect what is still running (the message names the status command) |
-| 130 | interrupted (SIGINT) | error envelope | ask the user whether to re-run |
-
-`class` and `retryable` live only in the JSON document; the exit code stays
-coarse so shell scripts can branch on it.
-
-Under contract v1, `gbrain mcp expose` and `gbrain google` exit 2 when they
-need the user's confirmation (documented legacy; changing it is a v2 item).
-
-The per-command exit changes that came with contract v1 (v0.60.46.0) are in
-the [CHANGELOG](../../CHANGELOG.md#exit-code-changes-by-command).
-
----
-
## docs/integrations/reliability-repair.md
Source: https://raw.githubusercontent.com/garrytan/gbrain/master/docs/integrations/reliability-repair.md
diff --git a/scripts/llms-config.ts b/scripts/llms-config.ts
index e0118e417e..fe6bbca824 100644
--- a/scripts/llms-config.ts
+++ b/scripts/llms-config.ts
@@ -344,6 +344,8 @@ export const SECTIONS: DocSection[] = [
title: "docs/guides/exit-codes.md",
description: "Exit statuses (3 = confirmation_required only, 10 pending write, 11 resumable budget stop) and what the agent does on each.",
path: "docs/guides/exit-codes.md",
+ // AGENT_OPERATOR_v1.md, inlined in full, carries the same exit table; llms-full.txt sits at its byte budget.
+ includeInFull: false,
},
{
title: "docs/guides/minions-fix.md",
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index bfa01bceb3..421f2b7820 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -3,7 +3,7 @@
# Raising a ceiling is a conscious, reviewer-visible act. Lower ceilings in
# the same commit as any peel (the guard fails on >50 lines of stale slack).
# Columns: path max_lines policy note
-src/cli/main.ts 2956 ratchet +1 #7619: the --flag=value gate call after the handler-free help printers, covering the hand-parsed search subcommands and the exact-token validation-exempt paths (logic, findUnknownFlag included, in cli/flag-equals.ts); +1 W1 belief ledger: `gbrain beliefs --help` in SELF_HELP_WITHOUT_ENGINE; +1 Cat 41 run 4: recall's SELF_HELP_WITHOUT_ENGINE table entry (a dispatch table row cannot move); moved from src/cli.ts at 3214 (cold start: src/cli.ts is now the 66-line entry with the --version/help fast path; the top-level help text moved to cli/top-help.ts and the exit seam became runCli/exitOnFatalCliError); +2 #6340: the sync status / sync unblock preflight skip (logic in commands/sync/operator.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +2 retrieval feedback: answer id line on stderr and additive answer_id on --json search/query rows (logic in feedback/record.ts); +1 feedback help line and its D3 table-dispatch entry (logic in commands/feedback.ts); 6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x engine graduation composition: both deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x foundations-2 composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); +2 entity recall: the human `gbrain entity` card prints referenced_by groups and a non-complete mention coverage; cat40 entity wave merge with v0.60.61.0 (3179 measured); +3 #4772 (W14 PR3): get_health text output says the entity ratios are n/a because the schema pack did not load (entity_types_status); +1 C4: gbrain questions CLI-only dispatch row (its help line is in cli/top-help.ts); +1 #6696 (A4): a local write captures the capacity notices (one call; logic in cli/op-notices.ts captureCapacityNotices); +1 large pages A6: the stdin cap reads PAGE_MAX_BYTES from core/page-size-policy.ts; +3 Wave B PR 2: local gbrain get of a segmented page streams on the page_body_segmented refusal (logic in cli/page-render.ts streamSegmentedGet); +1 #6712 PR 3 (L7): the sync_retry_failed_deprecated notice call (logic in commands/sync/args.ts noteRetryFailedDeprecated);+1 Cat 41 run 4: recall's SELF_HELP_WITHOUT_ENGINE table entry (a dispatch table row cannot move); +1 GBRA-133 PR 2a: sync trigger through a live PGLite serve (logic in commands/sync-delegate.ts maybeTriggerThroughServe); +1 GBRA-133 PR 2a merge: master and the sync trigger serve hand-off each added a dispatch row; +1 GBRA-154 #7171: captureRetrievalNotices call after a search/query op (logic in cli/op-notices.ts); GBRA-151 operability wave x v0.60.332.0 merge: both sides added a line, re-summed (3020 measured); GBRA-151 #7147 follow-up (cold one-shot read snapshot handoff and pool cap) re-summed at the v0.60.333.0 merge (3027 measured); +1 GBRA-156 warm CLI socket: one gated dispatch call before CLI_ONLY (logic in cli/cli-socket-client.ts); -11 GBRA-156: MERGED_CONFIG_BY_ENGINE and its comment moved to core/published-config.ts (serve reads it); lowered at the v0.60.340.0 merge (3018 measured); +5 #7191: search --exact routing call (dispatch, cannot move; rule in cli/command-route.ts) and the search_exact formatter case + imports; +3 GBRA-156 warm CLI startup: page-render, volunteer and operation-load imported lazily where used, so a warm socket hit loads 169 modules instead of 709 (2955 measured)
+src/cli/main.ts 2959 ratchet +1 #7619: the --flag=value gate call after the handler-free help printers, covering the hand-parsed search subcommands and the exact-token validation-exempt paths (logic, findUnknownFlag included, in cli/flag-equals.ts); +1 W1 belief ledger: `gbrain beliefs --help` in SELF_HELP_WITHOUT_ENGINE; +1 Cat 41 run 4: recall's SELF_HELP_WITHOUT_ENGINE table entry (a dispatch table row cannot move); moved from src/cli.ts at 3214 (cold start: src/cli.ts is now the 66-line entry with the --version/help fast path; the top-level help text moved to cli/top-help.ts and the exit seam became runCli/exitOnFatalCliError); +2 #6340: the sync status / sync unblock preflight skip (logic in commands/sync/operator.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +2 retrieval feedback: answer id line on stderr and additive answer_id on --json search/query rows (logic in feedback/record.ts); +1 feedback help line and its D3 table-dispatch entry (logic in commands/feedback.ts); 6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x engine graduation composition: both deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x foundations-2 composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); +2 entity recall: the human `gbrain entity` card prints referenced_by groups and a non-complete mention coverage; cat40 entity wave merge with v0.60.61.0 (3179 measured); +3 #4772 (W14 PR3): get_health text output says the entity ratios are n/a because the schema pack did not load (entity_types_status); +1 C4: gbrain questions CLI-only dispatch row (its help line is in cli/top-help.ts); +1 #6696 (A4): a local write captures the capacity notices (one call; logic in cli/op-notices.ts captureCapacityNotices); +1 large pages A6: the stdin cap reads PAGE_MAX_BYTES from core/page-size-policy.ts; +3 Wave B PR 2: local gbrain get of a segmented page streams on the page_body_segmented refusal (logic in cli/page-render.ts streamSegmentedGet); +1 #6712 PR 3 (L7): the sync_retry_failed_deprecated notice call (logic in commands/sync/args.ts noteRetryFailedDeprecated);+1 Cat 41 run 4: recall's SELF_HELP_WITHOUT_ENGINE table entry (a dispatch table row cannot move); +1 GBRA-133 PR 2a: sync trigger through a live PGLite serve (logic in commands/sync-delegate.ts maybeTriggerThroughServe); +1 GBRA-133 PR 2a merge: master and the sync trigger serve hand-off each added a dispatch row; +1 GBRA-154 #7171: captureRetrievalNotices call after a search/query op (logic in cli/op-notices.ts); GBRA-151 operability wave x v0.60.332.0 merge: both sides added a line, re-summed (3020 measured); GBRA-151 #7147 follow-up (cold one-shot read snapshot handoff and pool cap) re-summed at the v0.60.333.0 merge (3027 measured); +1 GBRA-156 warm CLI socket: one gated dispatch call before CLI_ONLY (logic in cli/cli-socket-client.ts); -11 GBRA-156: MERGED_CONFIG_BY_ENGINE and its comment moved to core/published-config.ts (serve reads it); lowered at the v0.60.340.0 merge (3018 measured); +5 #7191: search --exact routing call (dispatch, cannot move; rule in cli/command-route.ts) and the search_exact formatter case + imports; +3 GBRA-156 warm CLI startup: page-render, volunteer and operation-load imported lazily where used, so a warm socket hit loads 169 modules instead of 709 (2955 measured); +3 GBRA-217: gbrain get --as-of finishes through page-render.ts finishAsOfRead (echo check, exit status, paging), one call on each of the local and thin-client paths
src/commands/autopilot.ts 1662 ratchet refactor wave 1 split target (W4 autopilot, cut line); ceiling rationale: docs/architecture/key-files/commands-1.md entry for src/commands/autopilot.ts; +2 fix wave 5: nosemgrep justifications on the per-brain job launchctl/systemctl calls (#5195); +2 #5813: boot reconcile names attempted and running versions in log + audit; +2 #5855: Bun floor gate before the swap and the swap-refusal hold (logic in core/bun-floor.ts); +3 agent operator wave E9: --dry-run and the persistent_install consent gate before anything is written (logic in autopilot/install-consent.ts); +8 GBRA-130 C-6/A-10: the --retry-global mode row, help line and --phase value flag, and --status reading the brain-wide maintenance verdict into its JSON, text and exit code (logic in core/minions/global-maintenance-stall.ts and autopilot-retry-global.ts); +12 GBRA-133 #7003: --status grades from the daemon's heartbeat sidecar (two report fields and their doc line, the classifier's daemon input and threshold branch, the import and the showStatus read; logic in core/autopilot-heartbeat.ts)
src/commands/doctor.ts 700 ratchet +2 Wave B decision #10: Check.skipped_segmented field (logic in doctor/check-fix.ts withSkippedSegmented); +19 #6696 doctor tiers: Check.elapsed_ms and DoctorReport tier/complete/unknown_sections/elapsed_ms/budget_ms fields, buildChecks/runDoctor deadline params (logic in doctor/budget.ts); +1 agent operator gate fixes: --probe consent gate (logic in doctor/probe-consent.ts); refactor wave 1 split target (W4 doctor); ceiling rationale: docs/architecture/key-files/commands-2.md entry for src/commands/doctor.ts; +4 #7142: DoctorReport.last_known_sections field and the buildChecks last-known/refresh scope params (logic in doctor/last-known.ts); +8 #7276: DoctorReport.unknown_count field and the unknown category/count lines of the text headline (scoring logic in doctor/budget.ts scoredChecks)
src/commands/embed.ts 2306 ratchet +2 agent operator wave D2: --json failure envelope via writeCliError; lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment); #5105: guarded derived projection preparation and read seals; #5105: conditional embedding installer wiring; archived eligibility: active-only dispatch with honest stranded-work reporting; explicit archived admission: live-source snapshots and honest refused-installation failures; +2 fw3: embed --stale --images dispatch (sweep lives in core/embed-stale-images.ts); +5 #5289: dry run reports restamp-only chunks apart from chunks to embed (count lives in core/embedding-invalidation.ts); +6 #4616: keep a partially refused batch in embedPageTexts and name the recovery command in failure samples (guard lives in core/ai/embedding-guard.ts); +5 #5226: embed summary counts distinct pages; +3 #5804: null projection snapshot counted as a failure with one batch summary in embed --stale; +18 wave 8 lane D1: #5527 mixed-space warning subtracts current-model chunks (+4), #5885 takes option/result fields and the stale-drain takes call (pass lives in core/embed-takes.ts); +9 Foundations 1 F4d: time-budget stop result fields, stdout verdict and stop recording in embed --stale (logic in core/embed-budget-stop.ts); +8 green-master lane A: chunkless install re-reads through retryProjectionConflict instead of recording an unavailable page (retry lives in core/page-state/projections.ts, failure line in core/agent-output.ts); +8 fix wave 13 P1.18: runEmbed consent parameter, cost-cap stop wiring and result fields, --slugs parsing to the next flag (cap, verdict and resume logic live in core/embed-cost-cap.ts); +28 large pages A9/T3/T16: --held listing and per-page cap metering on every embed path (logic in core/page-embedding-budget.ts meterPageBatch/spendGrant/heldEmbedArgv), approvedPageCapUsd from --max-usd on --slugs; +1 #6722: an explicit slug embed skips an embed_skip page (it keeps keyword chunks, never vectors); merge v0.60.240.0: large pages and master growth compose at 2265; +39 large pages Wave B lane 1e: segmented pages route to the keyset sweep on the slug, --all and --stale paths, with a dry-run count and provenance stamp (logic in core/page-body/segmented-embedding.ts); +2 agent operator wave D2: --json failure envelope via writeCliError
@@ -40,11 +40,11 @@ src/core/config.ts 2012 ratchet +2 W5: search.page_rank_cut / page_rank_cut_fact
src/core/persistence/sync-run.ts 1686 ratchet new row: crossed the 1500 unlisted cap in #6643 (knock-on re-freeze, checkpoint revival, root cause and the truthful --retry-failed wait all drive the private cursor/gate machinery: holdUnderGate, freezeEntry, saveCursor); classification lives in sync-knock-on.ts, the checkpoint clause in checkpoint-validation.ts; peel the settle path (settleFailedRequest and its recoveries) into a sibling module next; +3 #6722: committed pages' size_state tallied into the cursor and the sync receipt size_states (logic in page-embedding-budget.ts addSizeState); merge v0.60.240.0: large pages and master growth compose at 1687; +2 #6694: the slug-mode checkpoint revival import and its doc line (predicate lives in persistence/sync-slug-mode.ts); +11 #6712 PR 3 (L7): a plain sync retries the recorded failure --retry-failed used to (retryRecordedFailure; the unchanged-refusal replay lives in persistence/sync-stop-class.ts replaysUnchangedRefusal), the moved-checkpoint and company content-refusal exceptions; #6712 PR 3 integration: lanes L7 (retryRecordedFailure, +19) and L8 (#6727 legacy-slug refusal line, #6735 timeout revival, +6) compose at 1762; +2 wave 18a integration: #6729 (lane 2, written against the 1745 ceiling) records identity downgrades in performManagedPass through noteIdentityDowngrades (logic in core/sync-identity-downgrades.ts), composed with master 1762; +14 Wave B PR 2: freezeEntry freezes a Markdown file over the read bound by reference (body_ref) and holdFailedFenceRequest holds a streamed refusal; both set freezeEntry/holdFailedFenceRequest locals (blob, oversize, rawHash) so they stay here, the hashing and preparation live in persistence/sync-streamed.ts and the hold in sync-screen.ts streamedRefusalHold; integrated at the master 4e29d0904 merge: master 1764 + Wave B PR 2 14 = 1778 measured; +4 #6948: freezeEntry holds an entry several live pages claim (hold in sync-screen.ts originConflictHold, verdict in persistence/origin-twins.ts); +1 #7167: managedDryRun reports the writer state (the import of persistence/sync-dry-run-writer.ts, where the read lives); +4 G3 git-canonical: freezeEntry reads a strict source's entry from its commit (pinnedBlob) and carries committedOnly to publication; both use freezeEntry locals (rule in persistence/sync-classify.ts)
src/core/bootstrap/harness.ts 2592 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts); +5 D8 Codex slice: the Codex SessionEnd capture hook obeys the recorded consent (wireCodexCapture: hooks on, capture accepted, never registrar mode) and is disclosed in the consent block; -31 #6743: cleanup gate moved to harness-cleanup.ts; +8 #6798: supersededEnrollments dep (interface field + default) and the --status epoch hint printed only for a superseded enrollment (the brain read lives in harness-skills.ts brainSupersededEnrollments)
src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option
-src/core/ops/pages.ts 728 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose; +1 wave 11 W4.3 (#5969 D3): put_page drop_timeline param; +1 wave 11 security review: purge_deleted_pages yes param + trusted-CLI guard (consent logic in persistence/purge-deleted.ts); +1 Q2 parser gaps: get_page grammar_diagnostics param (report logic in core/line-grammar-report.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +21 large pages (Wave A): get_page body-mode dispatch, fetch window branch, put_page large-page admission and allow_shrink param, description text (logic in ops/get-page-body.ts and persistence/large-page-guard.ts); +1 D8 funnel: committed put_page records a save when the opt-in funnel is on; +1 #6609: restore_page detach param (logic in persistence/detached-pages.ts); +1 Wave B gem A: post-batch auto-link reads a segmented page materialized (helpers in persistence/segmented-apply.ts); merge v0.60.249.0: composes at 707; +4 Wave B PR 2: get_page refuses a segmented page whole and fetch windows one (logic in ops/get-page-body.ts and page-window/segmented.ts); +2 Wave B PR 2 lane F: get_page and fetch pin segmented reads to the authorized snapshot (pin logic in ops/get-page-body.ts authorizedReadPin); +3 W2 page-at-time: get_page known_as_of param and dispatch (logic in ops/known-as-of.ts and belief/page-at-time.ts); GBRA-151 retrieval P0 x operability wave merge: both sides grew the file, re-summed (721 measured); GBRA-151 #7147 follow-up re-summed at the v0.60.334.0 merge (727 measured); +1 #7305: capture dry run applies the hyphen-run slug admission (logic in persistence/suffixed-slug.ts)
+src/core/ops/pages.ts 736 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose; +1 wave 11 W4.3 (#5969 D3): put_page drop_timeline param; +1 wave 11 security review: purge_deleted_pages yes param + trusted-CLI guard (consent logic in persistence/purge-deleted.ts); +1 Q2 parser gaps: get_page grammar_diagnostics param (report logic in core/line-grammar-report.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +21 large pages (Wave A): get_page body-mode dispatch, fetch window branch, put_page large-page admission and allow_shrink param, description text (logic in ops/get-page-body.ts and persistence/large-page-guard.ts); +1 D8 funnel: committed put_page records a save when the opt-in funnel is on; +1 #6609: restore_page detach param (logic in persistence/detached-pages.ts); +1 Wave B gem A: post-batch auto-link reads a segmented page materialized (helpers in persistence/segmented-apply.ts); merge v0.60.249.0: composes at 707; +4 Wave B PR 2: get_page refuses a segmented page whole and fetch windows one (logic in ops/get-page-body.ts and page-window/segmented.ts); +2 Wave B PR 2 lane F: get_page and fetch pin segmented reads to the authorized snapshot (pin logic in ops/get-page-body.ts authorizedReadPin); +3 W2 page-at-time: get_page known_as_of param and dispatch (logic in ops/known-as-of.ts and belief/page-at-time.ts); GBRA-151 retrieval P0 x operability wave merge: both sides grew the file, re-summed (721 measured); GBRA-151 #7147 follow-up re-summed at the v0.60.334.0 merge (727 measured); +1 #7305: capture dry run applies the hyphen-run slug admission (logic in persistence/suffixed-slug.ts); +8 GBRA-217 valid time: get_page as_of param and dispatch (logic in ops/valid-time-read.ts) and the additive plain-read valid_time status (currentValidTime in valid-time.ts); +1 composes over GBRA-217 PR A
src/core/search/mode.ts 1704 ratchet +53 W3 confidence-gated reranking: reranker_gate / reranker_gate_min_gap bundle fields, overrides, config parse and KNOB_CONFIG_KEY rows, knobsHash v=31 rrg=/rrgg=/ecf= parts (parse contracts in crag.ts); +10 System One v1: decide.* snapshot subset in loadSearchModeConfig, append-only dec= knobsHash part; +5 #3617 follow-up: v27 same-knobs behavioral-change note (relaxed-row fusion demotion rides the bump); new row: crossed the 1500 unlisted cap in the 2026-08 eval fix wave — KNOBS_HASH v=27 adaptive-return fold (ar/arem/arom/armk/ari parts + KnobsHashContext.adaptiveReturn field + contamination rationale comments) | merged v0.48.1.0 (+#4787) true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: four knobs (expansion_variant_budget, relational_rerank_pin, keyword_arm_confidence_floor, metadata_boost_gate) + v29 hash parts + doc receipts (+218); #4781 loadSearchModeConfig reads the config table once via loadConfigSnapshot (+6); +4 #4359: update loadSearchModeConfig docstring — the cached path now reads config once (threaded snapshot), not twice; retired provider integration removed; +12 fw3-search: search.source_boosts + search.alias_token_hop read in the mode snapshot; +10 #5691: KnobsHashContext.queryPrefix and its append-only qp= part; P7 relational_planner / relational_orient_onehop knobs (interface docs, bundles, overrides, config parse, hash parts); +18 P7 relational_chain_slots knob (interface doc, bundles, override, config parse, rcs= hash part); +22 GBRA-60 S1 diverse_pool_depth knob (interface doc, bundles, overrides, pick, config parse, append-only dpd= hash part); +35 GBRA-154: collapse and rank_priors knobs (interface docs, bundles, overrides, pick, config parse, append-only col=/rpr= hash parts); GBRA-151 retrieval P0 x operability wave merge: both sides grew the file, re-summed (1704 measured)
src/commands/eval-longmemeval.ts 1545 ratchet new row: crossed the 1500 unlisted cap in fw3-search (#5092 benchmark-brain recycling: configureBrain split + recycler wiring + test seams; the recycler itself lives in src/eval/longmemeval/harness.ts); +1 P6: tokenmax synopsis-tier wiring (logic in eval/longmemeval/synopsis-tier.ts); +13 GBRA-81 lane A: --via-operation query|search (flags, per-call expansion pin, the run's expectExpansion, the op branch in runOneQuestion, row field, via_operation_summary and its FAIL line; logic in eval/longmemeval/via-operation.ts); +12 --call-plan FILE / --call-plan-gate CMD: two LME_FLAGS entries (CLI help lines), two ParsedArgs fields, the parseArgs pairing check and the header invariant (planner lives in eval/longmemeval/call-plan.ts; runEvalLongMemEval is one line shorter); +1 #7619: parseArgs refuses a value on a switch (--judge=false turned the paid judge on)
src/commands/doctor/checks/extraction-sync.ts 1500 ratchet +7 GBRA-130 A-1: links_extraction_lag held bucket and its retry fix (logic in core/extraction-lag.ts heldExtractionReport); +1 undeclared_db_only_pages computes the source Git scope once per source (logic in core/markdown.ts sourceGitScope); new row: crossed the 1500 unlisted cap at the fix wave 9 merge: +7 lane W #5028 (extract_atoms freshness judged by the phase itself) and +3 lane F #5863 (extract_health dates a high halt rate by its last halt), each under the cap alone; +7 #5019: content_hash_duplicates fix pins the pairs' source (GBRAIN_SOURCE) and names a delete that runs; +1 fix wave 10 lane L1 #5556: links_extraction_lag denominator excludes quarantined pages (quarantineFilterFragment import); +11 fix wave 15 P2.8 (#5495): extract_health reads the 7-day halt reasons per kind (halt_reasons, top_halt_reason in details and the top reason in the warn line); the read, the unknown bucket and the ranking live in core/extract/rollup-writer.ts; +20 wave 18b lane 1: links_extraction_lag names the columns its pre-migration degrade reads (#6599 strict predicate), sync_freshness separates sync outcome from freshness for a source with no successful sync (#4960; verdict text, fixes and the attempt read live in doctor/sync-outcome.ts and core/sync-attempt.ts) and exempts read-only skill-pack catalogs (#6076; core/shared-skills/adopted-packs.ts); -51 #6803 (D1): links_extraction_lag reads its counts and verdict from core/extraction-lag.ts (shared with the sync nudge); +1 #7145: content_hash_duplicates reads one group past its list to report a floor ("at least 50")
src/core/search/evidence-delivery.ts 1733 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136); +39 Wave B PR 2 lane 2b: planSegmentedBlock joins the windows search/segmented-evidence.ts reads around a segmented page's hits into one run-marked document (needs the private Doc/Piece/buildDoc/locateAnchor internals), planBlock's unit cut split into blockFromDoc for both, sections bounded by their run, selectionCost counts a gap between runs, and the fetch skips the whole-body fence overlay for a segmented page; +4 segmented pages read at once before planning (segmentedReads; the read is search/segmented-evidence.ts, the statements page-body/read-range.ts); +17 GBRA-156: tail trim plan flag, DeliverOptions.query, DeliveryMeta.tail_trim, the trim call and the frozen-hit score/query library fields (logic in search/evidence-tail-trim.ts; interface fields cannot move)
src/commands/config.ts 1524 ratchet new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts); +2 #6795: config set chat_model/expansion_model help line and the model-pin import (shadow report and file-pin unset live in commands/config/model-pin-shadow.ts); +1 #6712 PR 4b: sync.admission set-time hook (value logic in commands/config/sync-admission-value.ts); +4 #7130: set-time refusal hook for sync.max_deletes / sync.max_delete_ratio (and .source.<id>) / purge.retention_hours (check lives in core/sync-reconcile.ts deleteSafetyConfigRefusal); +1 GBRA-150: sync.metafile_pages set-time route (body in config/sync-metafile-pages-value.ts); re-summed at the v0.60.330.0 merge (1520 measured); +2 #7242 minions.terminal_hook file-plane key and its set branch (logic in minions/terminal-hook.ts); +1 GBRA-161: generations.* set-time route (refusal in commands/config/generations-values.ts); +1 GBRA-207 #7630: sync.repo_path set-time refusal hook (refusal in core/sync-config-keys.ts syncRepoPathRefusal)
src/commands/mcp-expose.ts 1512 ratchet hosted_option: Session carries the gbrain.io coaching notice on the first-receipt run and Tailscale/service friction exits (copy, refs and gating live in core/onboard/hosted-option.ts)
-src/core/behavior-change-notice.ts 1518 ratchet the BEHAVIOR_CHANGES table grows by one row per disclosed change: +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2); the behavior-change table split (#7607) retires this row
+src/core/behavior-change-notice.ts 1520 ratchet the BEHAVIOR_CHANGES table grows by one row per disclosed change: +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2); the behavior-change table split (#7607) retires this row; +2 GBRA-217: the valid_time_plain_read row (rows cannot move)
diff --git a/skills/conventions/agent-operator-protocol.md b/skills/conventions/agent-operator-protocol.md
index 98b8739441..e525b74145 100644
--- a/skills/conventions/agent-operator-protocol.md
+++ b/skills/conventions/agent-operator-protocol.md
@@ -1015,6 +1015,8 @@ that work in this conversation.
| 12 | `no_results`: a recall or entity lookup matched nothing (only with `GBRAIN_FAIL_ON_EMPTY=1`) | treat it as a miss, not a failure |
| 13 | `pending_verify`: a harness wired, verification waits for the serve | start the serve, then run `fix.command` |
| 14 | `bootstrap_cleanup_pending`: a harness is wired; old shared-skills enrollments or token ids still await cleanup | follow `fix.next` (re-run, or relay the owner's revoke step), then re-run |
+| 15 | `get --as-of`: no edition in force | read `valid_time`; quote nothing |
+| 16 | `host_upgrade_required` | relay `gbrain upgrade` on the host |
| 75 | another runner holds the migration lock | wait, then retry |
| 124 | the command's deadline elapsed | inspect what is still running |
| 130 | interrupted | ask the user whether to re-run |
diff --git a/skills/conventions/brain-first.md b/skills/conventions/brain-first.md
index c6348669cf..a9df31d012 100644
--- a/skills/conventions/brain-first.md
+++ b/skills/conventions/brain-first.md
@@ -45,6 +45,22 @@ gbrain list --type meeting --limit 50 # enumerate by t
then reads as "no results". Check the exit code too.
<a id="identity-exact-match"></a>
+## Dated questions: read by valid time
+
+When the user asks what a page said, or what was in force, on a date, read it
+with `get_page {slug, as_of: 'YYYY-MM-DD'}` (CLI: `gbrain get <slug> --as-of
+<date>`), not the current page. Quote text only from an `in_force` answer; any
+other status puts the edition under `last_in_force` or `earliest_known`, and
+says so. When `valid_time.uncertain` is true, tell the user why and follow the
+`fix` (it asks the user for a date or a backup; never invent either). A reply
+without `valid_time` is the current page.
+
+When you edit a page whose text takes effect on a date, keep its `valid_from`
+for a correction, or set a new quoted `valid_from` for a new edition. Read the
+write result's `valid_time` advisory and ask the user when it asks a question.
+Which record to use for a change in effect (edit in place, amendment record,
+`supersedes` link): [page history](../../docs/guides/page-history.md#valid-time).
+
## Identity needs an exact match
Resolving an email sender, a calendar attendee or a contact to a person page is
diff --git a/src/cli/main.ts b/src/cli/main.ts
index 9069c3803e..bfc99dc9ef 100755
--- a/src/cli/main.ts
+++ b/src/cli/main.ts
@@ -720,7 +720,8 @@ async function runSharedOperation(command: string, subArgs: string[], cliOpts: C
// routed path. Date → ISO string; bigint → string (postgres.js shape);
// Buffer → object. Microsecond-cost; eliminates a whole drift bug class.
const { result, stderr: noticeText } = applyCliOpNotices(normalizeLocalResult(rawResult), params.json === true);
- const output = formatResult(op.name, result, params);
+ const paged = op.name === 'get_page' && await (await import('./page-render.ts')).finishAsOfRead(async p => normalizeLocalResult(await op.handler(ctx, p)) as Record<string, any>, result as Record<string, any>, params, writeStdoutFinal); // GBRA-217
+ const output = paged ? '' : formatResult(op.name, result, params);
// Awaited delivery (#3423): queued stdout writes past 64KiB lose their
// tail to a slow pipe reader when the exit grace lapses — see
// writeStdoutFinal.
@@ -835,6 +836,8 @@ async function runThinClientRouted(
if (envelopeMeta?.retrieval) captureRetrievalMeta('retrieval', envelopeMeta.retrieval);
checkHostHonoredParams(op, params, raw);
const result = unpackToolResult(raw);
+ if (op.name === 'get_page' && await (await import('./page-render.ts')).finishAsOfRead(async p => unpackToolResult(await callRemoteTool(cfg, 'get_page', p, { timeoutMs, signal: sigintController.signal })) as Record<string, any>, // GBRA-217: an older host's
+ result as Record<string, any>, params, writeStdoutFinal, { client: VERSION, host: identityCache.get(cfg.remote_mcp!.mcp_url)?.identity.version ?? null })) return; // reply fails closed
hintAmbientNarrowing(op, params, result, ambientScope);
const skew = (await import('../core/search/evidence-delivery.ts')).deliveryVersionSkewWarning(op.name, params, envelopeMeta?.retrieval as Record<string, unknown> | undefined, result);
if (skew) process.stderr.write(skew + '\n');
diff --git a/src/cli/page-render.ts b/src/cli/page-render.ts
index ea02e5a5bb..793a31eb7c 100644
--- a/src/cli/page-render.ts
+++ b/src/cli/page-render.ts
@@ -31,6 +31,9 @@ import { opError } from '../core/ops/contract.ts';
import { readFix } from '../core/ops/op-fix.ts';
import { PAGE_MAX_BYTES } from '../core/page-size-policy.ts';
import { isSegmentedPage } from '../core/page-body/page-shape.ts';
+import { VALID_TIME_NOT_IN_FORCE_EXIT_CODE } from '../core/exit-codes.ts';
+import { assertValidTimeEcho } from '../core/valid-time.ts';
+import { setCliExitVerdict } from '../core/cli-force-exit.ts';
/** Window size the thin client asks for while paging a whole page. */
export const REMOTE_PAGE_WINDOW_BYTES = 512 * 1024;
@@ -74,8 +77,64 @@ function renderSlice(r: GetPageResult): string {
return g.blocks.map((b: GetPageResult) => `-- lines ${b.line_start}-${b.line_end} (match at ${b.match_starts.join(', ')})\n${b.text}\n`).join('');
}
+/** The stderr line for a result's valid_time: an as_of answer's status, edition, history and doubt, or a plain read's status today. */
+export function validTimeLine(vt: GetPageResult): string {
+ if (vt.history === undefined) {
+ return `[gbrain] valid_time: ${vt.status} as of ${vt.as_of} (valid_from ${vt.valid_from ?? '-'}, valid_until ${vt.valid_until ?? '-'}).`;
+ }
+ const edition = vt.chosen_is_current ? 'current page' : vt.chosen_version_id != null ? `version ${vt.chosen_version_id}` : 'none in force';
+ const date = vt.valid_from ?? vt.earliest_known_valid_from ?? '-';
+ return `[gbrain] valid_time as_of ${vt.as_of}: ${vt.status}; edition ${edition} (valid_from ${date}${vt.valid_until ? `, valid_until ${vt.valid_until}` : ''}); history ${vt.history}${vt.uncertain ? `; uncertain: ${vt.why}` : ''}.`;
+}
+
+/** True for an as_of answer with no edition in force: stdout gets the status and why, never a document. */
+export function asOfNotInForce(r: GetPageResult | null | undefined): boolean {
+ return !!r?.valid_time && r.valid_time.history !== undefined && r.valid_time.status !== 'in_force';
+}
+
+/**
+ * `gbrain get --as-of` (GBRA-217): an edition read in windows prints whole, each window fetched with the previous
+ * window's `next` (slug, source, date and the pinned edition); stderr carries the valid_time header once. False when the
+ * result is not a windowed as_of answer (formatGetPage renders it).
+ */
+export async function printAsOfWindows(call: PagedCall, first: GetPageResult, params: Record<string, unknown>, write: (text: string) => Promise<void>): Promise<boolean> {
+ if (params.as_of === undefined || params.cursor !== undefined || params.json === true || first.valid_time?.status !== 'in_force' || !first.window || !first.next) return false;
+ process.stderr.write(validTimeLine(first.valid_time) + '\n');
+ for (let r = first; ;) {
+ if (!r.window) throw new Error(`The edition of ${String(first.slug)} in force on ${String(params.as_of)} is no longer retained (${r.valid_time?.why ?? 'edition_pruned'}); the rest of it was not printed.`);
+ await write(r.window.text);
+ if (!r.next) return true;
+ r = await call(r.next.arguments as Record<string, unknown>);
+ }
+}
+
+/**
+ * After a `gbrain get --as-of` call, locally or over the thin client (`versions` set): a host reply that does not echo
+ * `valid_time.as_of` fails closed (`host_upgrade_required`, on every window too), the exit status is set, and a windowed
+ * edition is paged. True when the edition was printed here.
+ */
+export async function finishAsOfRead(call: PagedCall, result: GetPageResult, params: Record<string, unknown>, write: (text: string) => Promise<void>,
+ versions?: { client: string; host: string | null }): Promise<boolean> {
+ if (params.as_of === undefined) return false;
+ if (versions) assertValidTimeEcho(params, result, versions);
+ const checked: PagedCall = versions ? async p => { const r = await call(p); assertValidTimeEcho(params, r, versions); return r; } : call;
+ const exit = asOfExitCode(result);
+ if (exit) setCliExitVerdict(exit);
+ return printAsOfWindows(checked, result, params, write);
+}
+
+/** The exit status of an as_of answer: 15 when no edition is in force, 1 when the edition's text has gone, 0 otherwise. */
+export function asOfExitCode(r: GetPageResult | null | undefined): number {
+ if (!r?.valid_time || r.valid_time.history === undefined) return 0;
+ if (r.valid_time.status !== 'in_force') return VALID_TIME_NOT_IN_FORCE_EXIT_CODE;
+ return r.compiled_truth === undefined && !r.window ? 1 : 0;
+}
+
/** stdout text for one get_page result; partial responses add a stderr note. */
export function formatGetPage(r: GetPageResult): string {
+ if (r.valid_time) process.stderr.write(validTimeLine(r.valid_time) + '\n');
+ if (asOfNotInForce(r)) return `status: ${r.valid_time.status}\nwhy: ${r.valid_time.why ?? 'none'}\n`;
+ if (r.valid_time?.history !== undefined && r.compiled_truth === undefined && !r.window) return '';
if (r.error === 'ambiguous_slug') {
return `Ambiguous slug. Did you mean:\n${r.candidates.map((c: string) => ` ${c}`).join('\n')}\n`;
}
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 59b8c1aa07..028f61c461 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1320,6 +1320,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.471.0', id: 'door_planned_state', text: 'On a source with `canonical: git`, a page write now commits exactly the bytes it published, or nothing. A file edited on disk while the write was publishing refuses `git_target_changed`: nothing is committed, the edit stays on disk and the source\'s writes pause until `gbrain repair stuck-recovery` resolves it (before, Git committed the edit while the database recorded the write\'s content). A staged change of the page\'s file refuses `git_index_conflict`, with the index untouched; commit or unstage it, then retry (before, the write replaced the staged change in the index). When the index still holds the version from before an earlier gbrain commit whose index update failed, the next write restores it and says so with a `git_index_restored` notice.' },
// #7679 / #7685 orphaned worktree refresh. `since` is stamped at the merge slot.
{ since: '0.60.472.0', id: 'refresh_orphan_7679', text: 'A managed `gbrain sources refresh` whose process died (for example a container replaced mid-refresh) no longer wedges the checkout: the next plain `gbrain sources refresh` on the owner host finishes the orphaned refresh through the `--resume` path before its own refresh and reports it as `recovered`, and the owner completes an orphaned `syncing` refresh once every member has synced to its target. A refresh whose holder is still running, or is recorded on another host, is never taken over. `gbrain sources writer status` and `gbrain sync status` now name the holder and its `liveness` (`live`, `orphaned`, `unknown`) with a fix naming `--resume`. With `--json`, a refusal that carries a structured fix (`refresh_in_progress`, `refresh_diverged`, a git read failure) now prints `fix` as an object (argv, actor, next) instead of a string; the prose stays in `suggestion`, so read that when a script needs text. A plain refresh of a checkout whose interrupted refresh needs a reset decision now refuses `refresh_recovery_required` (it refused `refresh_in_progress`).' },
+ // GBRA-217 valid time. `since` is stamped at the merge slot.
+ { since: '0.60.474.0', id: 'valid_time_plain_read', text: 'A plain get_page (and `gbrain get`) of a page whose own `valid_from` is after today, or whose `valid_until` has passed, now carries an additive `valid_time` block (`status: not_yet_in_force` or `not_in_force`, `as_of` today, both dates); `gbrain get` also prints it on stderr. The page text is returned as before, and a page without those dates reads exactly as before. New: get_page `as_of: YYYY-MM-DD` returns the edition in force on that date (docs/guides/page-history.md#valid-time).' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index b441be94f8..066ed4daf9 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -29,7 +29,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'bootstrap': ['--abbrev-ref', '--accept-visibility-change-consequences', '--active', '--add', '--adopt', '--all', '--allow-unverified-remote', '--auto', '--autostash', '--batch-check', '--bearer-token-env-var', '--brain', '--branch', '--cached', '--confirm', '--count', '--delete-brain', '--diff-filter', '--dim', '--dry-run', '--enable', '--env', '--error-unmatch', '--exclude-standard', '--expect-remote', '--ff-only', '--file', '--force', '--gbrain-bin', '--get', '--get-all', '--git-dir', '--git-path', '--hard', '--harness', '--header', '--heads', '--help', '--home', '--host', '--hostname', '--http', '--id', '--init', '--install', '--is-inside-work-tree', '--issuer-url', '--jq', '--json', '--keep-checkout', '--local', '--local-env-vars', '--mcp-even-if-plugin', '--mcp-only', '--mcp-url', '--minimal', '--name', '--name-only', '--no-autostash', '--no-capture', '--no-cron', '--no-hooks', '--no-seat', '--no-tags', '--no-verify', '--oauth-client-id', '--oauth-client-secret', '--only', '--operations', '--others', '--pat-file', '--path', '--pglite', '--porcelain', '--port', '--private', '--project', '--pull', '--pure', '--push-only', '--quiet', '--rebase', '--refresh-operations', '--refresh-skills', '--remove', '--repair', '--require-clean', '--resolve', '--scope', '--scopes', '--seat', '--set', '--short', '--show', '--show-toplevel', '--skills', '--skip', '--source', '--sources', '--status', '--surface', '--to', '--token', '--token-name', '--unset-all', '--url', '--verify', '--version', '--visibility', '--workspace', '--yes'],
'brainstorm': ['--admin-intent', '--brain', '--confirm-relocated-root', '--dir', '--expected-epoch', '--expected-state', '--force-rechunk', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--manifest', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--path', '--probe', '--resume', '--save', '--self-transfer', '--source', '--source-id', '--stale', '--strict-budget', '--yes'],
'cache': ['--brain', '--help', '--json', '--source', '--yes'],
- 'calibration': ['--access', '--add', '--all', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--dry-run', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--holder', '--http', '--id', '--include-deleted', '--json', '--key-prefix', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--regenerate', '--row', '--scopes', '--scrub-gstack', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--to', '--undo-wave', '--updated-after', '--url', '--with-calibration', '--yes'],
+ 'calibration': ['--access', '--add', '--all', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--dry-run', '--entities', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--holder', '--http', '--id', '--include-deleted', '--json', '--key-prefix', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--regenerate', '--row', '--scopes', '--scrub-gstack', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--to', '--undo-wave', '--updated-after', '--url', '--with-calibration', '--yes'],
'call': ['--brain', '--help', '--json', '--source'],
'capture': ['--accept-pending', '--access', '--add', '--all', '--allowed-operations', '--asof', '--background', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--depth', '--entities', '--expect-tail', '--expected-revision', '--explain', '--federated-read', '--file', '--follow', '--force', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--progress-interval', '--progress-json', '--purge', '--quiet', '--recent', '--refresh-operations', '--region', '--request-id', '--row', '--scopes', '--separator', '--session', '--since', '--slug', '--slugs', '--source', '--sources', '--stale', '--stdin', '--surface', '--timeout', '--timings', '--to', '--type', '--updated-after', '--url', '--wait', '--what', '--where', '--who', '--yes'],
'check-backlinks': ['--accept-pending', '--background', '--brain', '--dir', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--timings', '--wait'],
@@ -49,10 +49,10 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--plan', '--prefer-postgres', '--provenance', '--provider', '--query', '--schema-pack', '--scopes', '--search-mode', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--to', '--url', '--version'],
'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--legacy-lock', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--statement-timeout', '--supabase', '--timeout', '--timings', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],
'decide': ['--accept-all', '--all', '--all-from', '--apply', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--items-out', '--json', '--kind', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--rate', '--reason', '--reason-family', '--recommended', '--remove', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--undo', '--uri-prefix', '--version', '--what-if-threshold', '--yes'],
- 'diag': ['--access', '--add', '--all', '--allowed-operations', '--apply', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--budget-ms', '--client', '--count', '--cursor', '--date', '--dated-since', '--days', '--detach', '--entities', '--expect', '--expected-revision', '--federated-read', '--format', '--from-index', '--full', '--fuzzy', '--group-by', '--held', '--help', '--http', '--id', '--include-ambiguous', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--no-pull', '--no-walk', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--preview', '--purge', '--query', '--recent', '--refresh-operations', '--replace', '--restart-only', '--reverse', '--row', '--scopes', '--session', '--side', '--since', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--state', '--surface', '--to', '--updated-after', '--url', '--yes'],
+ 'diag': ['--access', '--add', '--all', '--allowed-operations', '--apply', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--budget-ms', '--client', '--count', '--cursor', '--date', '--dated-since', '--days', '--detach', '--entities', '--expect', '--expected-revision', '--federated-read', '--follow', '--format', '--from-index', '--full', '--fuzzy', '--group-by', '--held', '--help', '--http', '--id', '--include-ambiguous', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--no-pull', '--no-walk', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--preview', '--purge', '--query', '--recent', '--refresh-operations', '--replace', '--restart-only', '--reverse', '--row', '--scopes', '--session', '--side', '--since', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--state', '--surface', '--to', '--updated-after', '--url', '--yes'],
'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--after', '--aggressive', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--applied', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--batch', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--cached', '--cacheinfo', '--call-site', '--catch-up', '--channel', '--check', '--cherry-mark', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--continue', '--conversation', '--count', '--cursor', '--dataset', '--day', '--db-url', '--deadline', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-remove', '--force-retry', '--force-schema', '--format', '--fresh', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--full-tree', '--fuzzy', '--generation', '--get', '--get-all', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--grammar', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-cross-entity', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--index-info', '--infer-dates', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-count', '--max-facts', '--max-jobs', '--max-requests', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--merge-base', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-commit-id', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-gpg-sign', '--no-hooks', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--no-write-fetch-head', '--non-interactive', '--not', '--now', '--older-than', '--once', '--only', '--operation', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parents', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reader-mode', '--reauth', '--rebase', '--rebuild', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restart-only', '--restore-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--root', '--run', '--sample', '--save', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--segmented', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-object-format', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stop-mcp', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--type', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--write-tree', '--yes'],
'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--phase', '--probe', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],
- 'edge-proposals': ['--access', '--add', '--all', '--all-applied', '--all-held', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],
+ 'edge-proposals': ['--access', '--add', '--all', '--all-applied', '--all-held', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],
'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],
'embed': ['--accept-pending', '--all', '--background', '--batch-size', '--brain', '--break-lock', '--budget-ms', '--catch-up', '--client', '--db-url', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--group', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-null-signature', '--json', '--legacy-lock', '--max-cost', '--max-cost-usd', '--max-facts', '--max-runtime', '--max-usd', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--no-embed', '--no-embedding', '--no-hooks', '--only', '--oversized', '--pace', '--pace-max-concurrency', '--path', '--priority', '--probe', '--progress-interval', '--progress-json', '--quiet', '--replace', '--scopes', '--section', '--show-toplevel', '--slugs', '--source', '--stale', '--status', '--supabase', '--surface', '--timeout', '--timings', '--to', '--wait', '--yes'],
'embeddings': ['--accept-pending', '--background', '--brain', '--db-url', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--help', '--json', '--no-accept-pending', '--no-embedding', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--stale', '--status', '--supabase', '--timeout', '--timings', '--to', '--wait', '--yes'],
@@ -90,14 +90,14 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'mounts': ['--alias', '--brain', '--database-path', '--database-url', '--db-path', '--db-url', '--engine', '--help', '--id', '--json', '--mcp-url', '--path', '--skills-dir', '--source'],
'notability-eval': ['--brain', '--embedding-dimensions', '--embedding-model', '--help', '--in', '--json', '--out', '--repo', '--skip-llm', '--source', '--status', '--target-high', '--target-low', '--target-medium'],
'notices': ['--brain', '--help', '--json', '--source'],
- 'onboard': ['--access', '--add', '--all', '--allowed-operations', '--apply', '--asof', '--auto', '--body', '--bound-slug-prefixes', '--brain', '--check', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--from-index', '--from-pages', '--full', '--fuzzy', '--group-by', '--help', '--history', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--probe', '--purge', '--recent', '--refresh-operations', '--remediate', '--remediation-plan', '--resume', '--row', '--save', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--target-score', '--to', '--updated-after', '--url', '--yes'],
+ 'onboard': ['--access', '--add', '--all', '--allowed-operations', '--apply', '--asof', '--auto', '--body', '--bound-slug-prefixes', '--brain', '--check', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--follow', '--from-index', '--from-pages', '--full', '--fuzzy', '--group-by', '--help', '--history', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--probe', '--purge', '--recent', '--refresh-operations', '--remediate', '--remediation-plan', '--resume', '--row', '--save', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--target-score', '--to', '--updated-after', '--url', '--yes'],
'orphans': ['--accept-pending', '--all', '--background', '--brain', '--count', '--cursor', '--explain', '--follow', '--force', '--help', '--include-pseudo', '--json', '--limit', '--mode', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--timings', '--wait'],
'pages': ['--brain', '--dry-run', '--force', '--help', '--json', '--limit', '--literal-pathspecs', '--name-only', '--older-than', '--quiet', '--retry-parked', '--show-toplevel', '--source', '--source-id', '--state', '--verify', '--yes'],
'pglite-repair': ['--brain', '--break-lock', '--dry-run', '--expect', '--help', '--http', '--json', '--legacy-lock', '--path', '--probe', '--source', '--vectors', '--yes'],
'post-upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--channel', '--check', '--concurrency', '--confirm-quiesced', '--confirm-relocated-root', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expand', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--held', '--help', '--host-dir', '--images', '--inject-bootstrap', '--inline', '--install', '--interval', '--is-ancestor', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-expand', '--no-inject', '--no-restart', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--oversized', '--path', '--pause', '--phase', '--quiet', '--reason', '--refs', '--remediation-plan', '--repo', '--require-db', '--restart-only', '--resume', '--retry-global', '--search-mode', '--segmented', '--self-transfer', '--skills-dir', '--skip-verify', '--slug', '--source', '--stale', '--statement-timeout', '--status', '--stop-mcp', '--swap-only', '--tags', '--target', '--uninstall', '--user', '--value', '--vectors', '--verify', '--version', '--workers', '--yes'],
'pricing': ['--brain', '--help', '--input', '--json', '--max-cost', '--max-runtime', '--output', '--rate', '--source'],
'projections': ['--brain', '--dry-run', '--enable-dcr', '--help', '--http', '--images', '--install', '--json', '--limit', '--now', '--only', '--port', '--public-url', '--remove', '--source', '--stale', '--status', '--surface', '--user'],
- 'protocol': ['--access', '--add', '--all', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--provenance', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--synthesize', '--target', '--to', '--token', '--updated-after', '--url', '--yes'],
+ 'protocol': ['--access', '--add', '--all', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--provenance', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--synthesize', '--target', '--to', '--token', '--updated-after', '--url', '--yes'],
'providers': ['--brain', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--model', '--source', '--status', '--touchpoint'],
'publish': ['--accent', '--bg', '--border', '--brain', '--card-bg', '--code-bg', '--error', '--fg', '--help', '--json', '--link', '--muted', '--out', '--password', '--source', '--title'],
'quarantine': ['--accept-all', '--accept-pending', '--admin-intent', '--all', '--apply', '--background', '--body', '--brain', '--break-lock', '--client', '--confirm-relocated-root', '--db-url', '--dir', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--from', '--help', '--http', '--id', '--include-flagged', '--json', '--kind', '--legacy-lock', '--limit', '--manifest', '--no-accept-pending', '--no-embed', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--reason', '--reason-family', '--remove', '--resume', '--scopes', '--self-transfer', '--since', '--source', '--source-id', '--stale', '--timeout', '--timings', '--undo', '--uri-prefix', '--version', '--wait', '--yes'],
@@ -139,7 +139,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--channel', '--check', '--concurrency', '--confirm-quiesced', '--confirm-relocated-root', '--content-root', '--cost-estimate', '--dry-run', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expand', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--held', '--help', '--host-dir', '--images', '--inject-bootstrap', '--inline', '--install', '--interval', '--is-ancestor', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-expand', '--no-inject', '--no-restart', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--oversized', '--path', '--pause', '--phase', '--quiet', '--reason', '--refs', '--remediation-plan', '--repo', '--require-db', '--restart-only', '--resume', '--retry-global', '--search-mode', '--segmented', '--self-transfer', '--skills-dir', '--skip-verify', '--slug', '--source', '--stale', '--statement-timeout', '--status', '--stop-mcp', '--swap-only', '--tags', '--target', '--uninstall', '--user', '--value', '--vectors', '--verify', '--version', '--workers', '--yes'],
'waiting': ['--all', '--as-of', '--brain', '--dry-run', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],
'watch': ['--brain', '--help', '--json', '--max-pages', '--min-confidence', '--source', '--window-turns'],
- 'whoknows': ['--access', '--add', '--all', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--request-id', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--to', '--updated-after', '--url', '--yes'],
+ 'whoknows': ['--access', '--add', '--all', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--request-id', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--to', '--updated-after', '--url', '--yes'],
};
// Routing flags a fix naming each CLI-only command carries (A1 render-time pin,
diff --git a/src/core/engine-sql/pages.ts b/src/core/engine-sql/pages.ts
index 1539bd0aab..1b5add836d 100644
--- a/src/core/engine-sql/pages.ts
+++ b/src/core/engine-sql/pages.ts
@@ -23,6 +23,7 @@ import { segmentedRevertRefusal } from '../page-state/versions.ts';
import { sanitizeText } from '../batch-rows.ts';
import { SAFE_FENCE_CHUNKER_VERSION, bodyWriteChunkVersion } from '../search/safe-chunks.ts';
import { privatePagesFilterFragment, privateSnapshotFilterFragment } from '../search/private-visibility.ts';
+import { validDateSql } from '../valid-time.ts';
import { quarantineFilterFragment } from '../quarantine.ts';
import { rederiveHiddenSql } from '../eligibility/sql.ts';
import { validateSlug, contentHash, isBlankBody, rowToPage, rowToStalePage, isMissingSchemaObject, warnOncePerProcess } from '../utils.ts';
@@ -1006,6 +1007,9 @@ const PAGE_VERSION_SEGMENTED_COLUMNS = trustedSql('pv.body_storage, pv.body_gene
* pruned (`successor_pruned`: its visibility can no longer be checked, so the reason is withheld). The successor is
* read over every snapshot of the page, never only the rows the reader may see. Shared by get_versions and get_page as_of.
*/
+/** GBRA-217: each version's parsed valid time (the shared normaliser), so a timeline reads in one get_versions call. */
+const VERSION_VALID_TIME_COLUMNS = `${validDateSql("pv.frontmatter->>'valid_from'")} AS valid_from, ${validDateSql("pv.frontmatter->>'valid_until'")} AS valid_until`;
+
export function replacedBecauseSql(pv: string, excludePrivate: boolean): string {
if (!excludePrivate) return `${pv}.change_reason`;
return `CASE WHEN ${pv}.change_reason IS NULL OR COALESCE(${pv}.successor_pruned, false) THEN NULL
@@ -1032,7 +1036,8 @@ export async function getVersions<B extends boolean = true>(
const columns = opts?.includeBody === false ? PAGE_VERSION_METADATA_COLUMNS : PAGE_VERSION_COLUMNS;
const limit = opts?.limit !== undefined ? sqlFragment`LIMIT ${opts.limit}` : sqlFragment``;
const { rows } = await exec.run(sqlFragment`
- SELECT ${columns}, ${PAGE_VERSION_SEGMENTED_COLUMNS}, ${trustedSql(replacedBecauseSql('pv', opts?.excludePrivate === true))} AS replaced_because FROM page_versions pv
+ SELECT ${columns}, ${PAGE_VERSION_SEGMENTED_COLUMNS}, ${trustedSql(replacedBecauseSql('pv', opts?.excludePrivate === true))} AS replaced_because,
+ ${trustedSql(VERSION_VALID_TIME_COLUMNS)} FROM page_versions pv
JOIN pages p ON p.id = pv.page_id
WHERE p.slug = ${slug} ${scope}
${privacy} AND ${trustedSql(rederiveHiddenSql('pages', 'p'))}
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 670323c770..6a20bd6b20 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -107,11 +107,12 @@ export const CODES = {
bootstrap_empty: { class: 'caller', summary: "The benchmark bootstrap produced no tasks." },
bootstrap_pending_review: { class: 'caller', summary: "The bootstrapped benchmark awaits human review." },
bridge_ownership_conflict: { class: 'caller', summary: "The private local CLI registration is invalid." },
+ valid_time_undeclared: { class: 'caller', retryable: false, summary: 'An `as_of` read found no version of the page that declares a readable `valid_from`, so no edition can be placed on the date.', why: 'Valid time comes only from the `valid_from` / `valid_until` frontmatter the page carries; gbrain never infers when text took effect. Only the user knows the date, so the fix asks them before a templated edit_page records it.', docs: 'docs/guides/page-history.md#valid_time_undeclared', suggestion: 'Ask the user when the text took effect and record it as a quoted valid_from (the fix carries the edit). For what the brain had recorded at a time, read with known_as_of instead.' },
bucket_not_found: { class: 'unavailable', summary: "The configured storage bucket does not exist." },
budget_unsatisfiable: { class: 'unavailable', summary: "Reserved by MEMORY_VERBS v1; never returned." },
coverage_from: { class: 'caller', summary: "The belief ledger does not cover that time for this page or source: it starts at the page's baseline cut or the source's watermark.", why: "Recorded history exists only from a page's baseline (or creation) after the ledger was enabled; earlier times are unknown, not empty. A best-effort backfill from retained versions carries source times only, so it never answers a recorded-time read.", reasons: ['not_recorded', 'backfill_only', 'backfill_incomplete'], docs: 'docs/guides/repair.md#coverage-from', suggestion: 'Ask about a time at or after the time the message names; `gbrain beliefs status --source <id>` lists the coverage intervals.' },
coverage_gap: { class: 'caller', summary: "The belief ledger was not recording at that time: coverage was stopped, or a backup restore left a gap between the archive's time and the restore.", why: 'Nothing proves what happened to the page inside the gap, so the read refuses instead of answering from either side.', reasons: ['not_covered', 'restore'], docs: 'docs/guides/repair.md#coverage-gap', suggestion: 'Ask about a time outside the gap; `gbrain beliefs status --source <id>` lists the intervals and gaps.' },
- clock_mismatch: { class: 'caller', summary: 'A time parameter got a value on the wrong clock: `known_as_of` (recorded time) needs an instant with a zone, not a calendar date.', why: 'Recorded time (`known_as_of`) is when the brain had recorded something; valid time (`as_of`) is when a fact held in the world, as a date. A bare date is ambiguous as a recorded-time instant, so it is refused instead of guessed.', reasons: ['date_for_instant'], docs: 'docs/guides/repair.md#clock-mismatch', suggestion: 'Pass a full instant such as 2026-10-01T12:00:00Z to known_as_of, or use as_of where the tool takes a valid-time date.' },
+ clock_mismatch: { class: 'caller', summary: 'A time parameter got a value on the wrong clock: `known_as_of` (recorded time) needs an instant with a zone, not a calendar date (`date_for_instant`); get_page `as_of` (valid time) needs a calendar date, not an instant (`instant_for_date`).', why: 'Recorded time (`known_as_of`) is when the brain had recorded something; valid time (`as_of`) is when a fact held in the world, as a date. A bare date is ambiguous as a recorded-time instant, and an instant is not an edition date, so each is refused instead of guessed.', reasons: ['date_for_instant', 'instant_for_date'], docs: 'docs/guides/repair.md#clock-mismatch', suggestion: 'Pass a full instant such as 2026-10-01T12:00:00Z to known_as_of, or use as_of where the tool takes a valid-time date.' },
extract_write_lost: { class: 'retryable', summary: "A link or timeline write lost during extraction (after the engine's own retries) left its pages unstamped, so they stay due; pages whose writes landed were stamped.", why: "Stamping links_extracted_at for a page whose rows were dropped would hide the loss from every later extraction; leaving it due lets extract --stale, or the cycle's stale drain, write it again.", suggestion: 'Run the retry command the message names (gbrain extract --stale with the source id); it re-extracts only the pages still due.', fix: { argv: ['gbrain', 'doctor', '--only', 'links_extraction_lag', '--json'], consent: [], actor: 'agent', why: 'Read-only: counts the pages still waiting for link extraction.', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'links_extraction_lag', '--json'] } } },
item_failures_systemic: { class: 'server', summary: "Most items of one per-item loop failed (or many failed with one code, or none succeeded), so the failure is systemic and no item was held; the unit stopped instead of skipping every item.",
why: 'A per-item loop holds a bad item and continues (GBRA-130), but a run where most items fail points at a shared cause, and holding every item would hide it.',
@@ -128,6 +129,7 @@ export const CODES = {
suggestion: 'Run the gbrain config set the drain report names on the brain host (gbrain doctor --only persistence_capacity --json prints it), then rerun the same gbrain sync; it resumes at the stored cursor.' },
catalog_capacity_exceeded: { class: 'caller', summary: "The shared-skills catalog visible to this connection exceeds the delivery limits.", docs: 'docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover' },
catalog_unavailable: { class: 'retryable', summary: "Shared skill storage is not ready on this brain." },
+ host_upgrade_required: { class: 'host_only', retryable: false, exit: 16, summary: "The brain host is older than this client and did not answer the question asked: a get_page reply to an `as_of` read came back without `valid_time.as_of`, so it is the current page, not the edition in force on that date. Nothing historical was printed.", why: 'An older host ignores a read parameter it does not know and answers the plain read. Printing that answer as the edition in force on a date would quote the wrong text, so the client fails closed. The error carries the client version, the host version when known, and the minimum host version.', docs: 'docs/guides/page-history.md#host_upgrade_required', suggestion: 'Upgrade gbrain on the brain host (`gbrain upgrade`), or ask its operator to; then run the same read again.' },
change_reason_rejected: { class: 'caller', summary: "The write's reason was refused before anything was admitted: it is longer than 500 characters, or it looks like it holds a secret.", why: 'A reason is kept in page history and, on a page that reaches Git, in the commit message, which a push makes permanent; it is checked before the write is journaled so no copy of a refused reason is stored anywhere.', reasons: ['reason_too_long', 'reason_contains_secret'], legacy_error: 'invalid_params', docs: 'docs/guides/page-history.md#reasons', suggestion: 'Shorten the reason, or remove the secret from it, and send the write again.' },
changed_since_preview: { class: 'caller', summary: "The file changed after its repair was previewed, so nothing was written.", why: "A repair writes exactly the bytes the operator approved; it binds approval to the previewed file hash and refuses when the file moved on.", suggestion: 'Preview the repair again, review the new proposal, and approve its new hash.' },
chronicle_skipped: { class: 'unavailable', summary: "Automatic event extraction (auto_chronicle) skipped or failed this page; `reason` says why and `fix`, when present, is the next step.", reasons: ['auto_chronicle_off', 'auto_chronicle_invalid', 'slug_bound_client', 'operation_bound_client', 'no_extract', 'history', 'not_yet_happened', 'too_short', 'dream_generated', 'page_body_segmented', 'no_write_decision', 'not_chronicle_shaped', 'already_extracted', 'superseded', 'daily_limit', 'judge_llm_unavailable', 'no_pricing', 'budget_exhausted', 'campaign_exhausted', 'judge_chat_error', 'judge_truncated', 'judge_parse_failed', 'malformed_proposal', 'publish_error', 'judge_refused', 'page_missing', 'no_events', 'future_dated', 'date_imprecise', 'no_chat_provider'], docs: 'docs/guides/life-chronicle.md#skip-and-failure-codes', suggestion: 'Read the receipt or doctor `auto_chronicle` check: its `why` explains the reason and its `fix`, when present, is the next step (paid fixes need the user\'s agreement).' },
@@ -863,6 +865,10 @@ export const NOTICE_CODES = {
no_resident: { kind: 'degraded', summary: 'gbrain sync trigger recorded the request (and queued a job or nudged the serve), but no resident (gbrain serve, gbrain jobs work or the autopilot daemon) watches the source, so the recorded request waits until one starts or a sync reaches it; the fix syncs the checkout HEAD now (`gbrain sync --source <id> --no-pull`). docs/guides/on-commit-sync.md#no-resident' },
no_worker: { kind: 'degraded', summary: 'A job was queued but no worker is running to execute it; it waits until a worker runs.' },
config_write_shadowed: { kind: 'degraded', summary: '`gbrain config set chat_model|expansion_model` stored the value in the database, but a models.* config key, an environment variable (GBRAIN_MODEL, GBRAIN_CHAT_MODEL, GBRAIN_EXPANSION_MODEL) or the config.json pin outranks it, so the model in use does not change; `shadowed_by` names it (never its value) and the fix clears it (`gbrain config unset <models key>`, `gbrain config unset <key> --file`, or the user unsets the variable).' },
+ valid_from_unparsed: { kind: 'info', summary: "A page write kept a `valid_from` that is not a calendar date (YYYY-MM-DD, a YAML date or a midnight-UTC timestamp), so that version is undated and get_page `as_of` never picks it; the write result's `valid_time` names it." },
+ valid_time_correction: { kind: 'info', summary: "A page write changed the body and kept `valid_from`, so `as_of` reads treat it as a correction of the edition in force since that date; set `valid_from` if the change takes effect later." },
+ valid_time_date_only: { kind: 'ask', summary: "A page write changed only `valid_from`: a corrected date and a renewal of unchanged text look the same, so `as_of` reads around these dates carry `ambiguous_edition_dates`. Ask the user which one it was." },
+ ambiguous_edition_dates: { kind: 'ask', summary: "A get_page `as_of` answer is the selection rule's pick, but the versions around the date have an ambiguous shape (the same body under another `valid_from`, or a later-recorded version with an earlier one); `valid_time.competing_version_ids` names them and the fix asks which date the edition took effect." },
unknown_param: { kind: 'info', summary: 'The call passed a parameter the tool does not declare; it was ignored.' },
record_types_undeclared: { kind: 'info', summary: 'entity.record_types names a page type that neither the schema pack declares nor any page uses, so no record of that type is listed.' },
references_unavailable: { kind: 'degraded', summary: 'The reference count and records on entity rows did not finish (deadline or read failure); rows marked references_unavailable are unread, not empty.' },
diff --git a/src/core/exit-codes.ts b/src/core/exit-codes.ts
index 0d113dab1a..d295053c69 100644
--- a/src/core/exit-codes.ts
+++ b/src/core/exit-codes.ts
@@ -8,6 +8,7 @@
* 11 resumable budget stop · 13 harness wired, verification pending ·
* 12 no results (a lookup matched nothing; opt-in, GBRAIN_FAIL_ON_EMPTY=1) ·
* 14 harness wired, shared-skills/token cleanup pending ·
+ * 15 no edition in force on the as_of date · 16 host upgrade required ·
* 69 serve exited unhealthy · 75 migration
* lock held · 124 timeout · 130 interrupted. `test/exit-codes.test.ts` enumerates every literal
* exit 3 in src/ so a new one cannot reuse it.
@@ -81,3 +82,17 @@ export const HARNESS_CLEANUP_PENDING_EXIT_CODE = 14;
* (`serve_unhealthy_exit`). EX_UNAVAILABLE: a supervisor restarts it.
*/
export const SERVE_UNHEALTHY_EXIT_CODE = 69;
+
+/**
+ * GBRA-217: `gbrain get --as-of <date>` answered, but no edition was in force on that date (`valid_time.status` is
+ * `not_in_force`, `not_yet_in_force` or `before_recorded_history`). stdout carries the status and why, never a document,
+ * so a script cannot mistake expired or future text for the page in force. Distinct from 0 (an edition is in force) and
+ * from 1, which means the read failed.
+ */
+export const VALID_TIME_NOT_IN_FORCE_EXIT_CODE = 15;
+
+/**
+ * GBRA-217 (`host_upgrade_required`): the brain host is older than this client and answered a different question (an
+ * `as_of` read came back as the current page). Nothing was printed; upgrade the host.
+ */
+export const HOST_UPGRADE_REQUIRED_EXIT_CODE = 16;
diff --git a/src/core/operation-manifest.generated.ts b/src/core/operation-manifest.generated.ts
index abb2c1a536..353e698b9c 100644
--- a/src/core/operation-manifest.generated.ts
+++ b/src/core/operation-manifest.generated.ts
@@ -401,6 +401,10 @@ export const OPERATION_MANIFEST: OperationMeta[] = [
"type": "string",
"fullSurfaceOnly": true,
"description": "Recorded time: the page as this brain had recorded it at this ISO 8601 instant (2026-10-01T12:00:00Z), from the belief ledger. Not as_of, which is valid time (a date)."
+ },
+ "as_of": {
+ "type": "string",
+ "description": "YYYY-MM-DD: edition in force then. No valid_time in reply: current page."
}
},
"scope": "read",
@@ -477,6 +481,11 @@ export const OPERATION_MANIFEST: OperationMeta[] = [
"type": "number",
"description": "Commit wait ms (0-30000, default 5000)."
},
+ "reason": {
+ "type": "string",
+ "description": "Why this change, one line (max 500 chars); kept in page history.",
+ "fullSurfaceOnly": true
+ },
"source_kind": {
"type": "string",
"description": "Server-set remotely.",
@@ -903,6 +912,11 @@ export const OPERATION_MANIFEST: OperationMeta[] = [
"request_id": {
"type": "string",
"description": "Reuse only to retry."
+ },
+ "reason": {
+ "type": "string",
+ "description": "Why this change, one line (max 500 chars); kept in page history.",
+ "fullSurfaceOnly": true
}
},
"mutating": true,
@@ -1005,6 +1019,11 @@ export const OPERATION_MANIFEST: OperationMeta[] = [
"drop_timeline": {
"type": "boolean",
"description": "Content without a Timeline section deletes its dated entries."
+ },
+ "reason": {
+ "type": "string",
+ "description": "Why this change, one line (max 500 chars); kept in page history.",
+ "fullSurfaceOnly": true
}
}
}
@@ -2527,7 +2546,7 @@ export const OPERATION_MANIFEST: OperationMeta[] = [
"outputRedaction": {
"exempt": "full page version snapshots by slug; a page read governed by visibility like get_page (CEO-17)"
},
- "description": "Page version history, newest snapshot first: metadata only (id, snapshot_at, title, type, tags, frontmatter) for the newest 20 versions by default. Pass include_body: true for each version's compiled_truth and timeline, and a larger limit (at most 100 over MCP) for older versions. Trusted local and admin callers also get written_by and archived_by (who wrote each snapshot and whose write archived it). revert_version takes the id field.",
+ "description": "Page version history, newest snapshot first: metadata only (id, snapshot_at, title, type, tags, frontmatter) for the newest 20 versions by default. Pass include_body: true for each version's compiled_truth and timeline, and a larger limit (at most 100 over MCP) for older versions. Trusted local and admin callers also get written_by and archived_by (who wrote each snapshot and whose write archived it). replaced_because is the reason given for the write that replaced the snapshot (null when none was given). revert_version takes the id field.",
"params": {
"slug": {
"type": "string",
@@ -2598,6 +2617,11 @@ export const OPERATION_MANIFEST: OperationMeta[] = [
"type": "number",
"required": true,
"description": "Numeric version id to revert to, as returned by get_versions. Not a version NUMBER offset — pass the id field."
+ },
+ "reason": {
+ "type": "string",
+ "description": "Why this change, one line (max 500 chars); kept in page history.",
+ "fullSurfaceOnly": true
}
},
"mutating": true,
diff --git a/src/core/ops/pages.ts b/src/core/ops/pages.ts
index 58b88dfc12..6c73c6e72f 100644
--- a/src/core/ops/pages.ts
+++ b/src/core/ops/pages.ts
@@ -22,6 +22,8 @@ import { assertFullReadFits, bodyBytes, fetchWindowResult, GET_PAGE_BODY_PARAMS,
import { isSegmentedPage } from '../page-body/page-shape.ts';
import { MIN_TRUST_PARAM } from '../eligibility/policy.ts';
import { getPageKnownAsOf, KNOWN_AS_OF_PARAM } from './known-as-of.ts';
+import { AS_OF_PARAM, getPageAsOf } from './valid-time-read.ts';
+import { currentValidTime } from '../valid-time.ts';
import { stampRowTrust } from '../eligibility/stamp.ts';
import { isAutoLinkEnabled } from '../link-extraction.ts';
import { sanitizeRemoteBody } from '../remote-body.ts';
@@ -106,8 +108,10 @@ const get_page: Operation = {
include_quarantined: { type: 'boolean', description: 'Admin: quarantined body.', fullSurfaceOnly: true },
min_trust: MIN_TRUST_PARAM,
known_as_of: KNOWN_AS_OF_PARAM,
+ as_of: AS_OF_PARAM,
},
handler: async (ctx, p) => {
+ if (p.as_of !== undefined) return getPageAsOf(ctx, p);
if (p.known_as_of !== undefined) return getPageKnownAsOf(ctx, p);
const slug = p.slug as string;
const fuzzy = (p.fuzzy as boolean) || false;
@@ -228,13 +232,15 @@ const get_page: Operation = {
const quarantined = readQuarantined(ctx, page, p.include_quarantined === true); // #6259
const fenceHeld = (await (await import('../generations/fence.ts')).fenceHoldEntries(ctx.engine, [page.source_id], { slug: page.slug }).catch(() => [])).map(({ source_id: _s, slug: _g, ...hold }) => hold); const fileHeld = { ...(held ? { file_held: fileHeldField(held, isUntrustedReader) } : {}), ...(fenceHeld.length ? { fence_held: fenceHeld } : {}) };
const segmented = isSegmentedPage(page);
+ // GBRA-217 (B7): a current page not in force today says so; a page with no valid_from / valid_until reads as before.
+ const validTime = currentValidTime(page.frontmatter as Record<string, unknown> | null);
const pin = authorizedReadPin(ctx, page, snapshot!.bodyGeneration, p.min_trust, () => pageNotFoundError(ctx, slug, { includeDeleted, sourceIdParam }));
const whole = bodyRequest.mode === 'full'
|| (bodyRequest.mode === 'auto' && !segmented && bodyBytes(visibleBody) <= await inlineBodyBytes(ctx));
if (!whole) {
const partial = await readPartialBody(ctx, { page, visibleBody, revision: snapshot!.revision, tags, quarantined, trust: readable.trust, pin,
extras: { ...(quarantined ? { quarantined } : {}), ...(timelineEntries ? { timeline_entries: timelineEntries } : {}), ...fileHeld,
- ...(resolved_slug ? { resolved_slug } : {}), ...(content_flag ? { content_flag } : {}) } }, bodyRequest);
+ ...(resolved_slug ? { resolved_slug } : {}), ...(content_flag ? { content_flag } : {}), ...(validTime ? { valid_time: validTime } : {}) } }, bodyRequest);
return lineGrammar ? { ...partial, line_grammar: lineGrammar } : partial;
}
if (segmented) throw await segmentedFullReadError(ctx, page, bodyRequest, { ...pin, revision: snapshot!.revision });
@@ -244,7 +250,8 @@ const get_page: Operation = {
...fileHeld,
});
if (ctx.remote !== false) await assertFullReadFits(ctx, visibleBody, projected, bodyRequest);
- return lineGrammar ? { ...projected, line_grammar: lineGrammar } : projected;
+ const withValidTime = validTime ? { ...projected, valid_time: validTime } : projected;
+ return lineGrammar ? { ...withValidTime, line_grammar: lineGrammar } : withValidTime;
},
scope: 'read', mutating: false,
cliHints: { name: 'get', positional: ['slug'] },
diff --git a/src/core/ops/valid-time-read.ts b/src/core/ops/valid-time-read.ts
new file mode 100644
index 0000000000..8c70fc5d24
--- /dev/null
+++ b/src/core/ops/valid-time-read.ts
@@ -0,0 +1,350 @@
+/**
+ * GBRA-217 `get_page {as_of}`: the edition of one page in force on a date (valid time), from the frontmatter
+ * `valid_from` / `valid_until` of the current page and its retained versions.
+ *
+ * One statement picks over every row of the resolved page identity, before any visibility check: the greatest
+ * `valid_from` on or before the date, the most recently recorded on a tie; with the counts, the gap facts and the
+ * ambiguity window the verdict needs (src/core/valid-time.ts). A chosen edition the caller may not see answers as a
+ * missing page, never with an older visible edition. Only `in_force` carries text at the top level; any other status
+ * puts the edition under `last_in_force` or `earliest_known`. A large edition is read in windows whose cursor pins
+ * that edition (`v:<version id>`, or the current page's revision, found again among the versions if the page moved
+ * on); an edition that has gone answers `history: incomplete` with no text.
+ */
+import type { OperationContext, ParamDef } from './contract.ts';
+import { opError } from './contract.ts';
+import { hostFix, opTransport, readFix } from './op-fix.ts';
+import { renderAction, type Action } from '../agent-output.ts';
+import { assertExplicitSourceLive, federatedSearchScope, pageNotFoundError, parseSourceIdParam, validatePageSlug } from './context.ts';
+import { inlineBodyBytes } from './get-page-body.ts';
+import { pageTrustForRead } from './get-page-projection.ts';
+import { isCalendarDate } from '../link-validity.ts';
+import { replacedBecauseSql } from '../engine-sql/pages.ts';
+import { privateLinkOriginFilterFragment, privatePagesFilterFragment, privateSnapshotFilterFragment, resolveExcludePrivatePages } from '../search/private-visibility.ts';
+import { sanitizeRemoteBody } from '../remote-body.ts';
+import { serializePageToMarkdown } from '../markdown.ts';
+import { pageDocument } from '../page-window/document.ts';
+import { DEFAULT_WINDOW_BYTES, MAX_WINDOW_BYTES, decodeCursor, encodeCursor, totalLines, windowFrom, type WindowSlice } from '../page-window/window.ts';
+import { openSegmentedBody } from '../page-body/read-range.ts';
+import { segmentedReadDocument } from '../page-window/segmented.ts';
+import { PAGE_INLINE_MAX_BYTES } from '../page-size-policy.ts';
+import { LARGE_PAGE_VERSIONS_KEPT } from '../page-body/limits.ts';
+import { validDateSql, validTimeVerdict, type ValidTimeVerdict, type ValidTimeWhy } from '../valid-time.ts';
+import type { BrainEngine } from '../engine.ts';
+import type { Page } from '../types.ts';
+
+export const AS_OF_PARAM: ParamDef = { type: 'string', description: 'YYYY-MM-DD: edition in force then. No valid_time in reply: current page.' };
+
+/** get_page parameters an as_of read does not serve: an edit view, a fuzzy match, another clock or another body cut. */
+const AS_OF_UNSUPPORTED = ['fuzzy', 'include_deleted', 'include_timeline_entries', 'grammar_diagnostics', 'include_quarantined',
+ 'lines', 'bytes', 'around_chunk_id', 'context_lines', 'view', 'outline_from', 'section', 'grep', 'context'] as const;
+const INSTANT = /^[0-9]{4}-[0-9]{2}-[0-9]{2}[T ][0-9]{2}:[0-9]{2}/;
+/** Sorts after every page_versions id (a SERIAL int): the current page's place in recorded order. */
+const CURRENT_ORD = 2147483648;
+const AMENDMENTS_CAP = 20;
+
+interface Identity { id: number; source_id: string; slug: string; source_path: string | null; local_path: string | null; world: boolean }
+interface PickRow {
+ version_id: number | null; ord: number; replaced_at: string | null; valid_from: string; valid_until: string | null; visible: boolean;
+ reason: string | null; successor_pruned: boolean; segmented: boolean; recorded_since: string | null; introduced_because: string | null; chosen: boolean;
+}
+interface PickResult { row: PickRow | null; competing: number[]; undated: number; largeVersions: number; segmentedVersions: number; anyFiled: boolean; gapAt: string | null; createdAt: string | null }
+
+const iso = (v: unknown): string | null => v == null ? null : new Date(v as string).toISOString();
+
+/** The as_of date: a calendar date; an instant is the other clock (`known_as_of`), refused `clock_mismatch`. */
+function parseAsOf(ctx: OperationContext, value: unknown): string {
+ if (isCalendarDate(value)) return value;
+ if (typeof value === 'string' && INSTANT.test(value.trim())) {
+ throw opError('clock_mismatch', `as_of takes a calendar date (YYYY-MM-DD), not the instant ${value.trim().slice(0, 40)}.`,
+ 'as_of is valid time: the date an edition was in force. For what the brain had recorded at an instant, pass known_as_of instead; for valid time, pass the date alone (2026-07-01).',
+ { reason: 'instant_for_date' });
+ }
+ throw opError('invalid_params', 'get_page: as_of must be a calendar date YYYY-MM-DD.', 'Pass a date such as 2026-07-01.',
+ { fix: readFix('Reads the edition in force on that date.', { mcp: { tool: 'get_page', arguments: { slug: 'policies/policy-4a-example', as_of: '2026-07-01' } } }) });
+}
+
+function refuseCombinations(ctx: OperationContext, p: Record<string, unknown>): void {
+ const slug = String(p.slug);
+ if (p.known_as_of !== undefined) {
+ throw opError('invalid_params', 'get_page: as_of (valid time) and known_as_of (recorded time) answer different questions; pass one.',
+ 'Use as_of for the edition in force on a date, or known_as_of for the page as the brain had recorded it at an instant.',
+ { fix: readFix('Reads the edition in force on that date.', { mcp: { tool: 'get_page', arguments: { slug, as_of: p.as_of } } }) });
+ }
+ if (p.include_content === true || p.content_only === true) {
+ throw opError('invalid_params', 'get_page: as_of does not combine with include_content or content_only.',
+ 'An as_of read returns an older edition; writing it back with put_page would silently revert the page. To edit, read the current page with include_content, then edit it; to quote the old edition, read it with as_of alone.',
+ { fix: readFix('Reads the current page with its revision, ready to edit.', { mcp: { tool: 'get_page', arguments: { slug, include_content: true } } }) });
+ }
+ const extra = AS_OF_UNSUPPORTED.filter(k => p[k] !== undefined && p[k] !== false);
+ if (extra.length || (p.body !== undefined && p.body !== 'auto' && p.body !== 'full')) {
+ throw opError('invalid_params', `get_page: as_of does not combine with ${extra.length ? extra.join(', ') : `body: ${String(p.body)}`}.`,
+ 'Read the edition with as_of alone (plus source_id, min_trust, or the cursor and max_bytes of its next call).');
+ }
+}
+
+/** The one page the read is about: a slug in more than one granted source refuses and asks for source_id. */
+async function resolveIdentity(tx: BrainEngine, ctx: OperationContext, slug: string, scope: { sourceId?: string; sourceIds?: string[] }, excludePrivate: boolean, asOf: string): Promise<Identity> {
+ const rows = await tx.executeRaw<Identity>(`SELECT p.id, p.source_id, p.slug, p.source_path, s.local_path, ${privatePagesFilterFragment('p')} AS world
+ FROM pages p JOIN sources s ON s.id = p.source_id
+ WHERE p.slug = $1 AND p.deleted_at IS NULL AND ($2::text IS NULL OR p.source_id = $2) AND ($3::text[] IS NULL OR p.source_id = ANY($3::text[]))
+ ${excludePrivate ? `AND ${privatePagesFilterFragment('p')}` : ''}
+ ORDER BY p.source_id LIMIT 6`, [slug, scope.sourceId ?? null, scope.sourceIds ?? null]);
+ if (rows.length > 1) {
+ const sources = rows.map(r => r.source_id);
+ throw opError('invalid_params', `get_page: ${slug} exists in several sources (${sources.join(', ')}); an as_of read follows one page's history.`,
+ 'Pass source_id to name the page.', { fix: readFix(`Reads the page in source ${sources[0]}.`, { mcp: { tool: 'get_page', arguments: { slug, source_id: sources[0], as_of: asOf } } }) });
+ }
+ if (!rows[0]) throw pageNotFoundError(ctx, slug, { includeDeleted: false, sourceIdParam: scope.sourceId });
+ return { ...rows[0], id: Number(rows[0].id), world: rows[0].world === true };
+}
+
+const bodyKey = (a: string) => `CASE WHEN ${a}.body_storage = 'segmented' THEN 's:' || COALESCE(${a}.content_hash, '')
+ ELSE md5(COALESCE(${a}.compiled_truth, '') || chr(1) || COALESCE(${a}.timeline, '')) END`;
+
+/**
+ * The pick: one statement over the current page and its retained versions. With `pinOrd` it measures that row instead
+ * (a cursor's edition). The ambiguity window is the rows recorded after the pick with an earlier valid_from, and the
+ * pick's recorded neighbours that keep its body under another valid_from.
+ */
+async function pick(tx: BrainEngine, pageId: number, asOf: string, excludePrivate: boolean, pinOrd: number | null): Promise<PickResult> {
+ const vd = (a: string, key: string) => validDateSql(`${a}.frontmatter->>'${key}'`);
+ const [r] = await tx.executeRaw<Record<string, unknown>>(`WITH rows AS (
+ SELECT pv.id AS version_id, pv.id::bigint AS ord, pv.snapshot_at AS replaced_at, ${vd('pv', 'valid_from')} AS valid_from, ${vd('pv', 'valid_until')} AS valid_until,
+ ${bodyKey('pv')} AS body_key, ${privateSnapshotFilterFragment('pv')} AS visible, ${replacedBecauseSql('pv', excludePrivate)} AS reason,
+ COALESCE(pv.successor_pruned, false) AS successor_pruned, COALESCE(pv.body_storage = 'segmented', false) AS segmented,
+ (pv.body_storage IS DISTINCT FROM 'segmented' AND octet_length(COALESCE(pv.compiled_truth, '')) + octet_length(COALESCE(pv.timeline, '')) > $3) AS large,
+ pv.source_path IS NOT NULL AS filed
+ FROM page_versions pv WHERE pv.page_id = $1
+ UNION ALL
+ SELECT NULL, ${CURRENT_ORD}::bigint, NULL, ${vd('p', 'valid_from')}, ${vd('p', 'valid_until')}, ${bodyKey('p')}, ${privatePagesFilterFragment('p')}, NULL,
+ false, COALESCE(p.body_storage = 'segmented', false), false, p.source_path IS NOT NULL
+ FROM pages p WHERE p.id = $1),
+ seq AS (
+ SELECT r.*, lag(r.replaced_at) OVER w AS recorded_since, lag(r.reason) OVER w AS introduced_because,
+ lag(r.ord) OVER w AS prev_ord, lead(r.ord) OVER w AS next_ord
+ FROM rows r WINDOW w AS (ORDER BY r.ord)),
+ pick AS (
+ SELECT s.*, (s.valid_from <= $2::text) AS chosen FROM seq s
+ WHERE s.valid_from IS NOT NULL AND ($4::bigint IS NULL OR s.ord = $4::bigint)
+ ORDER BY (s.valid_from <= $2::text) DESC, CASE WHEN s.valid_from <= $2::text THEN s.valid_from END DESC,
+ CASE WHEN s.valid_from > $2::text THEN s.valid_from END ASC, s.ord DESC
+ LIMIT 1)
+ SELECT k.version_id, k.ord, k.replaced_at, k.valid_from, k.valid_until, k.visible, k.reason, k.successor_pruned, k.segmented,
+ k.recorded_since, k.introduced_because, k.chosen,
+ (SELECT array_agg(c.ord ORDER BY c.ord) FROM (SELECT s.ord FROM seq s
+ WHERE s.valid_from IS NOT NULL AND s.ord <> k.ord AND (
+ (s.ord > k.ord AND s.valid_from < k.valid_from)
+ OR (s.ord IN (k.prev_ord, k.next_ord) AND s.body_key = (SELECT b.body_key FROM seq b WHERE b.ord = k.ord) AND s.valid_from <> k.valid_from))
+ ORDER BY s.ord LIMIT 5) c) AS competing,
+ (SELECT count(*) FROM seq WHERE valid_from IS NULL) AS undated,
+ (SELECT count(*) FROM seq WHERE version_id IS NOT NULL AND large) AS large_versions,
+ (SELECT count(*) FROM seq WHERE version_id IS NOT NULL AND segmented) AS segmented_versions,
+ (SELECT bool_or(filed) FROM seq) AS any_filed,
+ p.version_history_gap_at AS gap_at, p.created_at
+ FROM pages p LEFT JOIN pick k ON true WHERE p.id = $1`, [pageId, asOf, PAGE_INLINE_MAX_BYTES, pinOrd]);
+ const row: PickRow | null = r && r.ord != null ? {
+ version_id: r.version_id == null ? null : Number(r.version_id), ord: Number(r.ord), replaced_at: iso(r.replaced_at), valid_from: String(r.valid_from),
+ valid_until: r.valid_until == null ? null : String(r.valid_until), visible: r.visible === true, reason: (r.reason as string | null) ?? null,
+ successor_pruned: r.successor_pruned === true, segmented: r.segmented === true, recorded_since: iso(r.recorded_since),
+ introduced_because: (r.introduced_because as string | null) ?? null, chosen: r.chosen === true,
+ } : null;
+ return { row, competing: ((r?.competing as unknown[] | null) ?? []).map(Number), undated: Number(r?.undated ?? 0),
+ largeVersions: Number(r?.large_versions ?? 0), segmentedVersions: Number(r?.segmented_versions ?? 0), anyFiled: r?.any_filed === true,
+ gapAt: iso(r?.gap_at), createdAt: iso(r?.created_at) };
+}
+
+function verdictOf(asOf: string, picked: PickResult): ValidTimeVerdict {
+ const row = picked.row;
+ return validTimeVerdict({
+ asOf, undatedVersions: picked.undated, gapAt: picked.gapAt, gbrainWritten: !picked.anyFiled,
+ couldHaveBeenPruned: picked.largeVersions >= LARGE_PAGE_VERSIONS_KEPT || picked.segmentedVersions > 0,
+ ambiguous: picked.competing.length > 0,
+ edition: row ? { chosen: row.chosen, isCurrent: row.version_id === null, validFrom: row.valid_from, validUntil: row.valid_until,
+ successorPruned: row.successor_pruned, recordedSince: row.recorded_since, replacedAt: row.replaced_at } : null,
+ });
+}
+
+/** Amendment records (`amends` links to the page) dated after the edition took effect and on or before the date: as_of does not fold them in. */
+async function amendmentsNotApplied(tx: BrainEngine, pageId: number, editionFrom: string, asOf: string, excludePrivate: boolean, scope: { sourceId?: string; sourceIds?: string[] }) {
+ const sources = scope.sourceIds ?? (scope.sourceId ? [scope.sourceId] : null);
+ const rows = await tx.executeRaw<{ slug: string; source_id: string; since: string | null }>(`SELECT f.slug, f.source_id, min(to_char(r.first_start, 'YYYY-MM-DD')) AS since
+ FROM links l JOIN pages f ON f.id = l.from_page_id AND f.deleted_at IS NULL${excludePrivate ? ` AND ${privatePagesFilterFragment('f')}` : ''}
+ LEFT JOIN link_relationships r ON r.from_page_id = l.from_page_id AND r.to_page_id = l.to_page_id AND r.link_type = l.link_type AND r.scope = $4
+ WHERE l.to_page_id = $1 AND l.link_type = 'amends'${excludePrivate ? ` AND ${privateLinkOriginFilterFragment('l')}` : ''}
+ AND ($5::text[] IS NULL OR f.source_id = ANY($5::text[]))
+ AND (r.first_start IS NULL OR (r.first_start > $2::date AND r.first_start <= $3::date))
+ GROUP BY f.slug, f.source_id ORDER BY f.slug LIMIT ${AMENDMENTS_CAP}`, [pageId, editionFrom, asOf, excludePrivate ? 'world' : 'all', sources]).catch(() => []);
+ return rows.map(r => ({ slug: r.slug, source_id: r.source_id, since: r.since ?? null }));
+}
+
+/** The serialized frontmatter edit that sets valid_from to the `<DATE>` placeholder: the existing line, or a new first key. */
+function validFromEdit(page: Page, tags: string[]): { old_text: string; new_text: string } | null {
+ const head = serializePageToMarkdown({ ...page, compiled_truth: '', timeline: '' }, tags);
+ const close = head.indexOf('\n---', 4);
+ const fm = head.slice(0, close < 0 ? head.length : close + 1);
+ const line = fm.split('\n').find(l => l.startsWith('valid_from:'));
+ if (line) return { old_text: `${line}\n`, new_text: "valid_from: '<DATE>'\n" };
+ const first = fm.split('\n')[1];
+ return head.startsWith('---\n') && first ? { old_text: `---\n${first}\n`, new_text: `---\nvalid_from: '<DATE>'\n${first}\n` } : null;
+}
+
+/** ask_user for the date an edition took effect, then the templated edit_page that records it as valid_from. */
+function askDateFix(identity: Identity, page: Page, tags: string[], revision: string, question: string, why: string): Action {
+ const edit = validFromEdit(page, tags);
+ return {
+ ask_user: true, consent: [], actor: 'user', why, user_message: question, requires_exclusive: false,
+ ...(edit ? { then: { mcp: { tool: 'edit_page', arguments: { slug: identity.slug, source_id: identity.source_id, expected_revision: revision, edits: [edit],
+ reason: 'Record the date this edition took effect.' } },
+ inputs: [{ name: 'DATE', how: 'The date the user named, as YYYY-MM-DD (kept quoted in the frontmatter).' }],
+ consent: [], actor: 'agent', why: 'Sets valid_from on the current page, so as_of reads pick it on that date.', requires_exclusive: false } } : {}),
+ };
+}
+
+/**
+ * Where the missing editions can be found: a world-visible file in a source with a Git checkout has them in the file's
+ * history (run locally; over MCP the user or host operator runs it); otherwise only a retained copy the user holds.
+ */
+function recoveryFix(ctx: OperationContext, identity: Identity, asOf: string, why: ValidTimeWhy): Action {
+ const gitWhy = `gbrain does not hold every edition of ${identity.slug} around ${asOf} (${why}); the file's Git history does. Read the editions there and their valid_from lines.`;
+ if (identity.source_path && identity.world && identity.local_path) {
+ if (ctx.remote === false && identity.local_path) {
+ return { argv: ['git', '-C', identity.local_path, 'log', '--follow', '-p', '--', identity.source_path], consent: [], actor: 'agent', why: gitWhy, requires_exclusive: false };
+ }
+ return { ...hostFix(ctx, ['git', 'log', '--follow', '-p', '--', identity.source_path], gitWhy,
+ { user_message: `gbrain no longer holds every edition of ${identity.slug} around ${asOf}. In the Git checkout of source ${identity.source_id}, run the command shown and share the editions it prints.` }),
+ ...(ctx.remote === false ? {} : { actor: 'user' as const }) };
+ }
+ return { ask_user: true, consent: [], actor: 'user', requires_exclusive: false,
+ why: `gbrain does not hold every edition of ${identity.slug} around ${asOf} (${why}), and the page has no file whose history could fill the gap. Do not retry this read unchanged: the answer will not change.`,
+ user_message: `gbrain does not hold every edition of ${identity.slug} around ${asOf}. Do you have a retained copy or a backup of the page from then?` };
+}
+
+interface Edition { versionId: number | null; title: string; type: string; tags: string[]; frontmatter: Record<string, unknown>; compiled_truth: string; timeline: string; revision: string; segmented: boolean; generation?: number }
+
+async function loadEdition(tx: BrainEngine, identity: Identity, row: PickRow): Promise<{ edition: Edition; current: { page: Page; tags: string[]; revision: string } } | null> {
+ const snap = await tx.readPageSnapshot(identity.slug, { sourceId: identity.source_id });
+ if (!snap) return null;
+ const current = { page: snap.page, tags: snap.tags, revision: snap.revision };
+ if (row.version_id === null) {
+ const p = snap.page;
+ return { current, edition: { versionId: null, title: p.title, type: p.type, tags: snap.tags, frontmatter: (p.frontmatter ?? {}) as Record<string, unknown>,
+ compiled_truth: p.compiled_truth ?? '', timeline: p.timeline ?? '', revision: snap.revision, segmented: row.segmented, generation: snap.bodyGeneration } };
+ }
+ const [v] = await tx.executeRaw<Record<string, unknown>>(`SELECT id, title, type, tags, frontmatter, compiled_truth, timeline, knowledge_revision::text AS revision,
+ body_storage, body_generation FROM page_versions WHERE id = $1 AND page_id = $2`, [row.version_id, identity.id]);
+ if (!v) return null;
+ const tags = Array.isArray(v.tags) ? v.tags.map(String) : typeof v.tags === 'string' ? JSON.parse(v.tags) as string[] : [];
+ const fm = (typeof v.frontmatter === 'string' ? JSON.parse(v.frontmatter) : v.frontmatter ?? {}) as Record<string, unknown>;
+ return { current, edition: { versionId: Number(v.id), title: String(v.title ?? identity.slug), type: String(v.type ?? ''), tags, frontmatter: fm,
+ compiled_truth: String(v.compiled_truth ?? ''), timeline: String(v.timeline ?? ''), revision: String(v.revision ?? ''),
+ segmented: v.body_storage === 'segmented', ...(v.body_generation != null ? { generation: Number(v.body_generation) } : {}) } };
+}
+
+/** The edition as the caller may read it: whole, or one window (with the next call pinned to it) when it is large or segmented. */
+async function editionView(ctx: OperationContext, identity: Identity, e: Edition, asOf: string, offset: number | null, maxBytes: number): Promise<Record<string, unknown> | 'gone'> {
+ const clean = (s: string) => ctx.remote === false ? s : sanitizeRemoteBody(s, { includeWithdrawn: true, keepMaterializedMarkers: true });
+ const meta = { ...(e.versionId === null ? { revision: e.revision } : { version_id: e.versionId }), title: e.title, type: e.type, tags: e.tags, frontmatter: e.frontmatter };
+ const truth = e.segmented ? '' : clean(e.compiled_truth), timeline = e.segmented ? '' : clean(e.timeline);
+ const bytes = Buffer.byteLength(truth, 'utf8') + Buffer.byteLength(timeline, 'utf8');
+ if (!e.segmented && offset === null && (ctx.remote === false || bytes <= await inlineBodyBytes(ctx))) return { ...meta, compiled_truth: truth, timeline };
+ let total: number, slice: WindowSlice, lines: number | undefined;
+ if (e.segmented) {
+ try {
+ const body = await openSegmentedBody(ctx.engine, { pageId: identity.id, ...(e.generation !== undefined ? { generation: e.generation } : {}) });
+ const seg = await segmentedReadDocument(ctx.engine, body);
+ total = seg.total;
+ slice = await seg.from(offset ?? 0, maxBytes);
+ } catch { return 'gone'; }
+ } else {
+ const doc = pageDocument({ compiled_truth: truth, timeline });
+ total = doc.bytes.length; lines = totalLines(doc.bytes);
+ slice = windowFrom(doc.bytes, offset ?? 0, maxBytes);
+ }
+ const out: Record<string, unknown> = { ...meta, body: 'window', size: { total_bytes: total, ...(lines !== undefined ? { total_lines: lines } : {}) },
+ window: slice, truncated: slice.byte_start > 0 || slice.byte_end < total };
+ if (slice.byte_end < total) {
+ const cursor = encodeCursor({ page_id: identity.id, revision: e.versionId === null ? e.revision : `v:${e.versionId}`, view: 'read', offset: slice.byte_end, max_bytes: maxBytes });
+ out.next_cursor = cursor;
+ out.next = { tool: 'get_page', arguments: { slug: identity.slug, source_id: identity.source_id, as_of: asOf, cursor } };
+ }
+ return out;
+}
+
+/** A cursor's pinned edition as a recorded-order position: its version, or the current page while it is still at the cursor's revision. */
+async function pinnedOrd(tx: BrainEngine, ctx: OperationContext, identity: Identity, raw: unknown): Promise<{ ord: number | null; offset: number; maxBytes: number }> {
+ const c = typeof raw === 'string' ? decodeCursor(raw) : null;
+ if (!c || c.page_id !== identity.id || c.view !== 'read') {
+ throw opError('invalid_params', `get_page: cursor is not an as_of window cursor for page ${identity.slug}.`, 'Pass the next_cursor of the previous as_of read, with the same slug, source_id and as_of.');
+ }
+ if (c.revision.startsWith('v:')) return { ord: Number(c.revision.slice(2)), offset: c.offset, maxBytes: c.max_bytes };
+ const [row] = await tx.executeRaw<{ current: boolean; version_id: number | null }>(`SELECT (p.knowledge_revision::text = $2) AS current,
+ (SELECT max(v.id) FROM page_versions v WHERE v.page_id = p.id AND v.knowledge_revision::text = $2) AS version_id FROM pages p WHERE p.id = $1`, [identity.id, c.revision]);
+ const ord = row?.current === true ? CURRENT_ORD : row?.version_id != null ? Number(row.version_id) : -1;
+ return { ord, offset: c.offset, maxBytes: c.max_bytes };
+}
+
+/** `get_page {as_of}`: the edition in force on the date, with the valid_time block that says how sure the answer is. */
+export async function getPageAsOf(ctx: OperationContext, p: Record<string, unknown>): Promise<Record<string, unknown>> {
+ refuseCombinations(ctx, p);
+ const asOf = parseAsOf(ctx, p.as_of);
+ const slug = String(p.slug);
+ validatePageSlug(slug);
+ const sourceIdParam = parseSourceIdParam(p.source_id, 'get_page', { allowAll: true });
+ const scope = federatedSearchScope(ctx, sourceIdParam);
+ await assertExplicitSourceLive(ctx, sourceIdParam);
+ const excludePrivate = await resolveExcludePrivatePages(ctx.engine, ctx.remote);
+ const read = await ctx.engine.transaction(async tx => {
+ await tx.executeRaw('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ');
+ const identity = await resolveIdentity(tx, ctx, slug, scope, excludePrivate, asOf);
+ const pin = p.cursor !== undefined ? await pinnedOrd(tx, ctx, identity, p.cursor) : null;
+ let picked = await pick(tx, identity.id, asOf, excludePrivate, pin?.ord ?? null);
+ const pinGone = pin !== null && !picked.row;
+ if (pinGone) picked = await pick(tx, identity.id, asOf, excludePrivate, null);
+ const loaded = picked.row ? await loadEdition(tx, identity, picked.row) : null;
+ const amendments = picked.row?.chosen ? await amendmentsNotApplied(tx, identity.id, picked.row.valid_from, asOf, excludePrivate, scope) : [];
+ return { identity, pin, picked, pinGone, loaded, amendments };
+ });
+ const { identity, pin, picked, loaded, amendments } = read;
+ const row = picked.row;
+ const missing = () => pageNotFoundError(ctx, slug, { includeDeleted: false, sourceIdParam });
+ if (!(await pageTrustForRead(ctx, { id: identity.id }, p.min_trust))) throw missing();
+ if (!row) {
+ const snap = await ctx.engine.readPageSnapshot(identity.slug, { sourceId: identity.source_id });
+ if (!snap) throw missing();
+ throw opError('valid_time_undeclared', `${identity.slug} declares no valid_from in any retained version, so no edition can be placed on ${asOf}.`,
+ 'Ask the user when this text took effect and record it as valid_from; never invent a date. For what the brain had recorded at a time, read with known_as_of instead.',
+ { fix: askDateFix(identity, snap.page, snap.tags, snap.revision, `When did the current text of ${identity.slug} take effect? (a date, YYYY-MM-DD)`,
+ 'An as_of read needs a valid_from date on the page; only the user knows when this text took effect.') });
+ }
+ if (excludePrivate && !row.visible) throw missing();
+ if (!loaded) throw missing();
+ const verdict = verdictOf(asOf, picked);
+ let { history, uncertain, why } = verdict;
+ let view: Record<string, unknown> | 'gone' | null = null;
+ const requested = typeof p.max_bytes === 'number' && Number.isSafeInteger(p.max_bytes) && p.max_bytes > 0 ? p.max_bytes : pin?.maxBytes ?? DEFAULT_WINDOW_BYTES;
+ if (!read.pinGone) view = await editionView(ctx, identity, loaded.edition, asOf, pin ? pin.offset : null, ctx.remote === false ? requested : Math.min(requested, MAX_WINDOW_BYTES));
+ if (read.pinGone || view === 'gone') { history = 'incomplete'; uncertain = true; why = 'edition_pruned'; view = null; }
+ const reason = (s: string | null) => s === null ? null : ctx.remote === false ? s : sanitizeRemoteBody(s);
+ const chosen = row.chosen;
+ const validTime = {
+ as_of: asOf, status: verdict.status,
+ chosen_version_id: chosen ? row.version_id : null, chosen_is_current: chosen && row.version_id === null,
+ valid_from: chosen ? row.valid_from : null, valid_until: chosen ? row.valid_until : null,
+ introduced_because: chosen ? reason(row.introduced_because) : null, replaced_because: chosen ? reason(row.reason) : null,
+ history, uncertain, why, undated_versions: picked.undated, amendments_not_applied: amendments,
+ recorded_since: chosen ? row.recorded_since ?? (picked.gapAt === null ? picked.createdAt : null) : null,
+ ...(why === 'ambiguous_edition_dates' ? { competing_version_ids: picked.competing.map(o => o === CURRENT_ORD ? null : o) } : {}),
+ ...(!chosen ? { earliest_known_valid_from: row.valid_from } : {}),
+ };
+ let fix: Action | undefined;
+ if (why === 'ambiguous_edition_dates') {
+ fix = askDateFix(identity, loaded.current.page, loaded.current.tags, loaded.current.revision,
+ `Which date did this edition of ${identity.slug} take effect? Its recorded dates disagree (versions ${validTime.competing_version_ids?.map(v => v ?? 'current').join(', ')}).`,
+ 'A date correction, a renewal, a backfill and a withdrawn scheduled edition look alike in the page history; only the user can say which happened.');
+ } else if (why !== null && why !== 'undated_editions') fix = recoveryFix(ctx, identity, asOf, why);
+ const render = { transport: opTransport(ctx), isCallable: () => ctx.remote !== false, preapproved: () => false };
+ const base = { slug: identity.slug, source_id: identity.source_id, valid_time: validTime, ...(fix ? { fix: renderAction(fix, render) } : {}) };
+ if (!view) return base;
+ if (verdict.status === 'in_force') return { ...view, ...base };
+ return { ...base, [chosen ? 'last_in_force' : 'earliest_known']: { ...view, valid_from: row.valid_from, valid_until: row.valid_until } };
+}
diff --git a/src/core/page-state/version-types.ts b/src/core/page-state/version-types.ts
index 504be9cb73..5dcf779131 100644
--- a/src/core/page-state/version-types.ts
+++ b/src/core/page-state/version-types.ts
@@ -24,6 +24,9 @@ export interface PageVersion {
* read without the reason projection.
*/
replaced_because?: string | null;
+ /** GBRA-217: the version's frontmatter valid_from / valid_until as YYYY-MM-DD (src/core/valid-time.ts), null when absent or unreadable. */
+ valid_from?: string | null;
+ valid_until?: string | null;
id: number;
page_id: number;
compiled_truth: string;
diff --git a/src/core/persistence/params.ts b/src/core/persistence/params.ts
index 95a792d18a..54ea690e6c 100644
--- a/src/core/persistence/params.ts
+++ b/src/core/persistence/params.ts
@@ -38,6 +38,8 @@ import { WRITE_REQUEST_STATES, WRITE_HEALTH_REASONS, WRITE_HEALTH_ASSESSMENTS, W
export const REASON_PARAM: ParamDef = {
type: 'string',
description: 'Why this change, one line (max 500 chars); kept in page history.',
+ // GBRA-217 decision 9: the starter list cannot fit both `reason` and get_page `as_of`; as_of stays, reason is full-surface only.
+ fullSurfaceOnly: true,
};
export const WRITE_REQUEST_PARAM: ParamDef = {
diff --git a/src/core/persistence/valid-time-advisory.ts b/src/core/persistence/valid-time-advisory.ts
new file mode 100644
index 0000000000..02bd7d7f66
--- /dev/null
+++ b/src/core/persistence/valid-time-advisory.ts
@@ -0,0 +1,34 @@
+/**
+ * GBRA-217 (B1/B6): a page write's valid-time advisory. After the publication applies, the page before and after are
+ * compared (`validTimeWriteAdvisory`): a `valid_from` that is not a date warns `valid_from_unparsed`; a body change
+ * under an unchanged `valid_from` is reported as a correction of that edition; a date-only change asks whether it is a
+ * correction or a renewal. The advisory rides the write outcome as `valid_time`; nothing else changes. Same on a
+ * repo-less brain: it reads only the database rows the write's own transaction produced.
+ */
+import type { WriteRequest } from './model.ts';
+import type { PreparedMutation } from './coordinator.ts';
+import { validTimeWriteAdvisory } from '../valid-time.ts';
+
+const ADVISED = ['put_page', 'capture', 'revert_version', 'edit_page'];
+
+type BodyRow = { frontmatter: unknown; compiled_truth: string | null; timeline: string | null; body_storage?: string | null; content_hash?: string | null };
+/** What a body comparison sees: the stored text, or a segmented page's content hash (its text is not on the row). */
+const bodyKey = (p: BodyRow) => p.body_storage === 'segmented' ? `s:${p.content_hash ?? ''}` : `t:${p.compiled_truth ?? ''}\u0001${p.timeline ?? ''}`;
+const asObject = (v: unknown) => (typeof v === 'string' ? JSON.parse(v) : v ?? {}) as Record<string, unknown>;
+
+export function withValidTimeAdvisory(row: WriteRequest, prepared: PreparedMutation): PreparedMutation {
+ if (!ADVISED.includes(row.operation)) return prepared;
+ const apply = prepared.apply.bind(prepared);
+ prepared.apply = async (tx, preimage) => {
+ const outcome = await apply(tx, preimage);
+ if (prepared.noop) return outcome;
+ const [after] = await tx.executeRaw<BodyRow>(`SELECT frontmatter, compiled_truth, timeline, body_storage, content_hash FROM pages
+ WHERE source_id = $1 AND slug = $2 AND deleted_at IS NULL`, [row.source_id, row.slug]);
+ if (!after) return outcome;
+ const before = preimage && !preimage.page.deleted_at
+ ? { frontmatter: asObject(preimage.page.frontmatter), body: bodyKey(preimage.page as BodyRow) } : null;
+ const advisory = validTimeWriteAdvisory(before, { frontmatter: asObject(after.frontmatter), body: bodyKey(after) });
+ return advisory ? { ...outcome, valid_time: advisory } : outcome;
+ };
+ return prepared;
+}
diff --git a/src/core/valid-time.ts b/src/core/valid-time.ts
new file mode 100644
index 0000000000..bb1449cb0f
--- /dev/null
+++ b/src/core/valid-time.ts
@@ -0,0 +1,186 @@
+/**
+ * GBRA-217 valid time: which edition of a page was in force on a date, from the frontmatter `valid_from` /
+ * `valid_until` each retained version carries. Intervals are half-open, `[valid_from, valid_until)`, as links are
+ * (link-validity.ts).
+ *
+ * One date normaliser serves TypeScript (`validDate`) and the SQL pick (`validDateSql`): a calendar date
+ * `YYYY-MM-DD`, a YAML Date, or a midnight-UTC ISO timestamp (the form an unquoted YAML date is stored as). Anything
+ * else (a partial date, a time of day, another zone) makes that version undated, never guessed.
+ *
+ * `validTimeVerdict` holds the status rules of a read, as a pure function over what the pick statement measured.
+ */
+import { utcToday } from './link-validity.ts';
+import { opError } from './ops/contract.ts';
+
+/** Statuses of a valid-time answer. Only `in_force` carries the edition's text at the top level. */
+export type ValidTimeStatus = 'in_force' | 'not_in_force' | 'not_yet_in_force' | 'before_recorded_history';
+/** Whether gbrain still holds every edition the answer depends on. */
+export type ValidTimeHistory = 'retained' | 'incomplete' | 'unknown';
+/** Why an answer is uncertain; null when it is not. */
+export type ValidTimeWhy = 'history_pruned' | 'history_gap' | 'history_unknown' | 'before_recorded_history'
+ | 'edition_pruned' | 'ambiguous_edition_dates' | 'undated_editions';
+
+/** The accepted forms; the same pattern runs in TypeScript and in Postgres (ARE), the date is the first group. */
+const DATE_FORM = '^([0-9]{4}-[0-9]{2}-[0-9]{2})(?:T00:00:00(?:[.]0+)?(?:Z|[+]00:00))?$';
+const DATE_RE = new RegExp(DATE_FORM);
+
+/** The calendar date a frontmatter value declares, or null when it is not one of the accepted forms. */
+export function validDate(value: unknown): string | null {
+ if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : validDate(value.toISOString());
+ if (typeof value !== 'string') return null;
+ const m = DATE_RE.exec(value);
+ if (!m) return null;
+ const date = m[1]!;
+ const [year, month, day] = [Number(date.slice(0, 4)), Number(date.slice(5, 7)), Number(date.slice(8, 10))];
+ if (year < 1000 || month < 1 || month > 12 || day < 1) return null;
+ return day <= new Date(Date.UTC(year, month, 0)).getUTCDate() ? date : null;
+}
+
+/**
+ * SQL twin of `validDate` over a text expression (`frontmatter->>'valid_from'`): the date as `YYYY-MM-DD` text, or
+ * NULL. Nested CASE so a bad month never reaches make_date; it never raises on any input.
+ */
+export function validDateSql(textExpr: string): string {
+ const d = `substring(${textExpr} from '${DATE_FORM}')`;
+ const y = `substr(${d}, 1, 4)::int`, m = `substr(${d}, 6, 2)::int`, day = `substr(${d}, 9, 2)::int`;
+ return `(CASE WHEN ${d} IS NULL THEN NULL
+ WHEN ${y} < 1000 OR ${m} NOT BETWEEN 1 AND 12 THEN NULL
+ WHEN ${day} BETWEEN 1 AND extract(day from make_date(${y}, ${m}, 1) + interval '1 month' - interval '1 day')::int THEN ${d}
+ END)`;
+}
+
+/** A declared but unreadable `valid_from` (the write advisory `valid_from_unparsed` names it). */
+export function unparsedValidFrom(frontmatter: Record<string, unknown> | null | undefined): boolean {
+ const v = frontmatter?.valid_from;
+ return v !== undefined && v !== null && v !== '' && validDate(v) === null;
+}
+
+/** What the pick statement measured about the chosen edition, or the earliest dated one when none is in force. */
+export interface PickedEdition {
+ /** True when this edition has the greatest valid_from on or before the date (it is the rule's pick). */
+ chosen: boolean;
+ isCurrent: boolean;
+ validFrom: string;
+ validUntil: string | null;
+ /** The retained version recorded after this one was pruned. */
+ successorPruned: boolean;
+ /** When this edition became current (the previous retained version's snapshot time), ISO; null for the first. */
+ recordedSince: string | null;
+ /** When a later edition replaced it (its own snapshot time), ISO; null for the current page. */
+ replacedAt: string | null;
+}
+
+export interface PickFacts {
+ asOf: string;
+ edition: PickedEdition | null;
+ undatedVersions: number;
+ /** pages.version_history_gap_at, ISO. */
+ gapAt: string | null;
+ /** No edition has a file behind it: gbrain wrote the page's first recorded version, so nothing predates it. */
+ gbrainWritten: boolean;
+ /** No gap is marked, but the page has enough large or segmented versions that a prune may have run before the marker existed. */
+ couldHaveBeenPruned: boolean;
+ /** Versions around the pick have an ambiguous shape (adjacent same body with another date, or recorded later with an earlier date). */
+ ambiguous: boolean;
+}
+
+export interface ValidTimeVerdict {
+ status: ValidTimeStatus;
+ history: ValidTimeHistory;
+ uncertain: boolean;
+ why: ValidTimeWhy | null;
+}
+
+/**
+ * Decisions 5 and 6 of the valid-time plan: the status, whether the history the answer rests on is retained, and the
+ * one reason it is uncertain. A gap makes the answer uncertain only when it falls inside the chosen edition's recorded
+ * span (or the date precedes every retained edition); dates the retained editions cover after a gap stay certain.
+ */
+export function validTimeVerdict(f: PickFacts): ValidTimeVerdict {
+ const e = f.edition?.chosen ? f.edition : null;
+ const unknown = f.couldHaveBeenPruned && f.gapAt === null;
+ let status: ValidTimeStatus;
+ if (e) status = e.validUntil !== null && e.validUntil <= f.asOf ? 'not_in_force' : 'in_force';
+ else status = f.gbrainWritten && f.gapAt === null && !unknown ? 'not_yet_in_force' : 'before_recorded_history';
+ const gap = f.gapAt === null ? null : Date.parse(f.gapAt);
+ const gapInSpan = e !== null && gap !== null && (e.recordedSince === null || Date.parse(e.recordedSince) < gap)
+ && (e.replacedAt === null || Date.parse(e.replacedAt) >= gap);
+ let why: ValidTimeWhy | null = null;
+ let history: ValidTimeHistory = 'retained';
+ if (unknown) { history = 'unknown'; why = 'history_unknown'; }
+ else if (e?.successorPruned) { history = 'incomplete'; why = 'history_pruned'; }
+ else if (gapInSpan) { history = 'incomplete'; why = 'history_gap'; }
+ else if (!e && gap !== null) { history = 'incomplete'; why = 'history_gap'; }
+ else if (!e && !f.gbrainWritten) { history = 'incomplete'; why = 'before_recorded_history'; }
+ if (why === null && f.ambiguous) why = 'ambiguous_edition_dates';
+ if (why === null && !e && f.undatedVersions > 0) why = 'undated_editions';
+ return { status, history, uncertain: why !== null, why };
+}
+
+/**
+ * B7: a plain read of a current page that is not in force today carries its status (additive). Null for a page with
+ * no readable `valid_from` / `valid_until`, or one in force today, so its read is unchanged.
+ */
+export function currentValidTime(frontmatter: Record<string, unknown> | null | undefined, today: string = utcToday()):
+ { status: 'not_in_force' | 'not_yet_in_force'; as_of: string; valid_from: string | null; valid_until: string | null } | null {
+ const from = validDate(frontmatter?.valid_from), until = validDate(frontmatter?.valid_until);
+ const status = from !== null && from > today ? 'not_yet_in_force' : until !== null && until <= today ? 'not_in_force' : null;
+ return status ? { status, as_of: today, valid_from: from, valid_until: until } : null;
+}
+
+/**
+ * The first release whose get_page answers `as_of` (echoing `valid_time.as_of`). Stamped with the release at ship time;
+ * the client names it in `host_upgrade_required`.
+ */
+export const VALID_TIME_MIN_HOST_VERSION = '0.60.475.0';
+
+/**
+ * B4 version skew: an `as_of` read's reply must echo `valid_time.as_of`. An older host ignores the parameter and
+ * answers the plain read (the current page), so a reply without the echo fails closed: nothing historical is printed.
+ */
+export function assertValidTimeEcho(params: Record<string, unknown>, result: unknown, versions: { client: string; host: string | null }): void {
+ if (params.as_of === undefined) return;
+ const echoed = (result as { valid_time?: { as_of?: unknown } } | null)?.valid_time?.as_of;
+ if (echoed === params.as_of) return;
+ const host = versions.host ?? 'unknown';
+ throw opError('host_upgrade_required',
+ `The brain host (gbrain ${host}) answered get_page without valid time, so its reply is the current page, not the edition in force on ${String(params.as_of)}. Nothing was printed.`,
+ `Upgrade gbrain on the brain host to ${VALID_TIME_MIN_HOST_VERSION} or later (gbrain upgrade), or ask its operator to, then run the same read again.`,
+ { detail: JSON.stringify({ client_version: versions.client, host_version: host, min_host_version: VALID_TIME_MIN_HOST_VERSION }),
+ fix: { argv: ['gbrain', 'upgrade'], consent: [], actor: 'host_admin', requires_exclusive: false,
+ why: 'The host predates get_page as_of; an upgraded host answers the date read with valid_time.',
+ user_message: `This brain's host runs an older gbrain that cannot read a page by date. Please run gbrain upgrade on the brain host (it needs ${VALID_TIME_MIN_HOST_VERSION} or later), or ask whoever runs it.` } });
+}
+
+/** A write's valid-time advisory: what the write result tells the writer about the edition dates it kept or changed. */
+export interface ValidTimeAdvisory {
+ code: 'valid_from_unparsed' | 'valid_time_correction' | 'valid_time_date_only';
+ message: string;
+ valid_from: string | null;
+ previous_valid_from?: string;
+}
+
+/**
+ * B1/B6: the advisory for one page write, from the page before and after. A body change under an unchanged
+ * `valid_from` is read as a correction of that edition; a date-only change is a question, because as_of cannot tell a
+ * corrected date from a renewal of unchanged text and flags it. Null when nothing applies.
+ */
+export function validTimeWriteAdvisory(before: { frontmatter: Record<string, unknown> | null; body: string } | null,
+ after: { frontmatter: Record<string, unknown> | null; body: string }): ValidTimeAdvisory | null {
+ if (unparsedValidFrom(after.frontmatter)) {
+ return { code: 'valid_from_unparsed', valid_from: null,
+ message: "valid_from is not a calendar date (YYYY-MM-DD), so this version is undated and as_of reads will not pick it. Write it quoted, for example valid_from: '2026-07-01'." };
+ }
+ if (!before) return null;
+ const was = validDate(before.frontmatter?.valid_from), now = validDate(after.frontmatter?.valid_from);
+ const bodyChanged = before.body !== after.body;
+ if (now !== null && was === now && bodyChanged) {
+ return { code: 'valid_time_correction', valid_from: now,
+ message: `Treated as a correction of the edition in force since ${now}; set valid_from if this takes effect later.` };
+ }
+ if (now !== null && was !== null && was !== now && !bodyChanged) {
+ return { code: 'valid_time_date_only', valid_from: now, previous_valid_from: was,
+ message: `Only valid_from changed (${was} to ${now}). Is this a correction of the earlier date, or a renewal of an unchanged edition? as_of reads around these dates are marked uncertain (ambiguous_edition_dates), because the two look the same.` };
+ }
+ return null;
+}
diff --git a/test/mcp-schema-budget.test.ts b/test/mcp-schema-budget.test.ts
index 6b02278c1c..4da3ced989 100644
--- a/test/mcp-schema-budget.test.ts
+++ b/test/mcp-schema-budget.test.ts
@@ -63,14 +63,15 @@ import { stdioVisibleTools } from '../src/mcp/server.ts';
import { buildMcpInstructions, GBRAIN_MCP_INSTRUCTIONS } from '../src/mcp/instructions.ts';
import { cl100kAvailable, estimateTokens } from '../src/core/chunkers/token-estimate.ts';
-const SERVED_STARTER_MAX_CHARS = 18_200;
+/** GBRA-217: +120 for get_page `as_of` on starter (decision 9: valid-time reads for delegating agents; `reason` moved to the full surface to pay part of it), measured 18,114 with publish_skills on. */
+const SERVED_STARTER_MAX_CHARS = 18_320;
/** Headroom the served starter list must keep under the ceiling (wave 16: 24,998 of 25,000 left 2 characters; 200 is what the wave reaches without touching text other threads own, raised to 300 once the entity card and query/search trims land). */
const SERVED_STARTER_MIN_HEADROOM = 200;
const SERVED_STARTER_MAX_TOKENS = 4_300;
/** The whole tools/list JSON, annotations included (25,735 measured at v0.60.46.0; traverse_graph's `hops` is full-surface-only, 25,941 measured; 26,402 once mute_notice, the dismissal for the coaching notices starter sessions receive, joined starter; 26,671 with #6007's put_page wait_ms param and write guidance, which carry the put_pages hint and the receipt poll rule starter agents need; 26,679 with delta's opaque `cursor` param, paid for by trimming delta's own descriptions, model-visible 24,985; 26,692 with recall's `question` param, paid for by trimming recall's own parameter text, model-visible 24,998; 24,996 after the #6446 merge, recall's grep text trimmed again). */
-const SERVED_STARTER_MAX_JSON_CHARS = 19_800; // GBRA-156: 19,431 measured
+const SERVED_STARTER_MAX_JSON_CHARS = 19_900; // GBRA-156: 19,431 measured; GBRA-217 get_page as_of: 19,808
/** GBRA-156: the UTF-8 bytes of the served starter tools/list result (`{"tools":[...]}`, annotations included) that harnesses re-fetch every turn. */
-const SERVED_STARTER_MAX_RESULT_BYTES = 19_800; // 26,546 before GBRA-156, 19,489 after
+const SERVED_STARTER_MAX_RESULT_BYTES = 19_900; // 26,546 before GBRA-156, 19,489 after; GBRA-217 get_page as_of: 19,866
/** 4,042 at the cost wave + 586 for the operator contract's error protocol, notice prefix and memory loop (F1); no schema guidance moved here. */
const INSTRUCTIONS_MAX_CHARS = 5_108; // #6007: +240 for the issue-required write guidance (put_pages, wait_ms); Cat 40 Hard round 4: +107 for batching lists of names (entity names, keyword OR) and sending independent calls together; d5b: +70 for the brief naming the fields compact `entity names` rows carry (the maximal rendering, record types enrolled; +39 at the default) instead of a `referenced_by` walk batch mode cannot do; F4: +63 for instruction 7's governing rule (the record whose terms are in effect on the date asked about governs; page dates are named as page dates), 74 characters longer than the "prefer the newest governing source" sentence it replaces, 11 paid by cutting "the best-ranked excerpts" to "top excerpts" in the same clause
const DESCRIPTION_HARD_CAP = 1_200;
@@ -100,11 +101,13 @@ const PARAM_DESCRIPTION_HARD_CAP = 200;
* at 1,826. Without it Haiku 4.5 routes "all the people that work on X" to
* search (28/80 at temperature 1; 1/80 with the clause); the batching sentence
* `Name lists: entity names.` stays, so the growth is paid by other tools.
+ * get_page 510 -> 610 (GBRA-217): the starter `as_of` param (the edition in force on a date, and the rule that a
+ * reply without valid_time is the current page), measured at 603.
*/
const TOOL_BUDGETS: Record<string, number> = {
add_timeline_entry: 730, cancel_job: 270, cancel_write_request: 350, capture: 710, context_pack: 500,
delete_skill: 810, delta: 580, edit_page: 1040, entity: 550, find_anomalies: 400, forget: 530, get_agent_job: 270,
- get_backlinks: 710, get_ingest_log: 280, get_page: 510, get_recent_salience: 450, get_skill: 490,
+ get_backlinks: 710, get_ingest_log: 280, get_page: 610, get_recent_salience: 450, get_skill: 490,
get_skill_asset: 530, get_write_request: 360, join_brain: 560, leave_brain: 540, list_brain_skillpack: 230,
list_link_sources: 220, list_pages: 850, list_skills: 400, list_write_requests: 370, put_page: 1090,
mute_notice: 420, put_skill: 1420, query: 1700, recall: 840, remember: 940, request_tools: 530, resolve_slugs: 410, search: 1420,
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 0ba0d1862a..ed5bb3e928 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -518,6 +518,7 @@ test/unbound-source-6536.test.ts
test/unindexed-files-convergence-7149.test.ts
test/unindexed-files.test.ts
test/v273-validate-timeouts.test.ts
+test/valid-time-gbra217.test.ts
test/vector-manifest-probe-bound.test.ts
test/visibility-fail-closed-derived-writes.test.ts
test/visibility-repair-scale.test.ts
diff --git a/test/valid-time-gbra217.test.ts b/test/valid-time-gbra217.test.ts
new file mode 100644
index 0000000000..2798c3bf29
--- /dev/null
+++ b/test/valid-time-gbra217.test.ts
@@ -0,0 +1,400 @@
+/**
+ * GBRA-217 PR B: get_page {as_of} reads a page by valid time, from the frontmatter valid_from / valid_until of the
+ * current page and its retained versions.
+ *
+ * 1. Protects: the selection rule (greatest valid_from on or before the date, latest recorded on a tie, half-open
+ * valid_until), the ambiguity flag, the honest statuses when history is missing (before_recorded_history, a prune
+ * gap, an unmarked upgraded page), privacy (a private chosen edition reads as a missing page, never an older world
+ * one; a private-time reason never leaks), the refusals, the shared date normaliser, the pinned windows, the plain
+ * read's additive status, get_versions' parsed dates and the write advisories.
+ * 2. Fails when: any of those picks another edition, drops the uncertain flag, puts expired or future text at the top
+ * level, shows a hidden reason, or a window cursor follows the page instead of its edition.
+ * 3. Real handlers (put_page, get_page, get_versions) on a keyless repo-less brain: PGLite always, Postgres when
+ * DATABASE_URL is set (test/postgres-unit-arms.txt). Seeding writes SQL only where the case is history gbrain no
+ * longer writes (an unmarked pre-upgrade page) or volume (500 versions).
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { PostgresEngine } from '../src/core/postgres-engine.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { operationsByName, OperationError, type OperationContext } from '../src/core/operations.ts';
+import { resetGateway } from '../src/core/ai/gateway.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { createPageVersion } from '../src/core/page-state/versions.ts';
+import { assertValidTimeEcho, currentValidTime, validDate, validDateSql, validTimeVerdict, validTimeWriteAdvisory, VALID_TIME_MIN_HOST_VERSION } from '../src/core/valid-time.ts';
+import { exitCodeForCode } from '../src/core/error-catalogue.ts';
+import { asOfExitCode, formatGetPage, validTimeLine } from '../src/cli/page-render.ts';
+import { utcToday } from '../src/core/link-validity.ts';
+import { testBackends, requirePostgresTestDatabase } from './helpers/test-backends.ts';
+
+type R = Record<string, any>;
+const outcomeOf = (r: R) => (r.outcome ?? r) as R;
+const page = (body: string, fm: string[] = []) => ['---', 'title: Policy', 'type: note', ...fm, '---', '', body, ''].join('\n');
+const refusal = (p: Promise<unknown>) => p.then(() => null, (e: unknown) => e as OperationError);
+let n = 0;
+const fresh = (name: string) => 'policies/' + name + '-' + (++n) + '-' + Math.random().toString(36).slice(2, 8);
+
+describe('valid-time normaliser and verdict (pure)', () => {
+ test('accepted forms and undated forms', () => {
+ expect(validDate('2026-01-01')).toBe('2026-01-01');
+ expect(validDate('2026-01-01T00:00:00.000Z')).toBe('2026-01-01');
+ expect(validDate('2026-01-01T00:00:00Z')).toBe('2026-01-01');
+ expect(validDate('2026-01-01T00:00:00+00:00')).toBe('2026-01-01');
+ expect(validDate(new Date(Date.UTC(2026, 0, 1)))).toBe('2026-01-01');
+ for (const bad of ['2026-01', '2026', '2026-02-30', '2026-13-01', '2026-01-01T10:00:00Z', '2026-01-01T00:00:00-05:00', ' 2026-01-01', '0999-01-01', 2026, null, new Date(Date.UTC(2026, 0, 1, 5))]) {
+ expect(validDate(bad)).toBeNull();
+ }
+ });
+
+ test('a gap marks the answer only inside the chosen edition span, or before every retained edition', () => {
+ const base = { asOf: '2026-08-01', undatedVersions: 0, gbrainWritten: true, couldHaveBeenPruned: false, ambiguous: false };
+ const edition = { chosen: true, isCurrent: false, validFrom: '2026-07-01', validUntil: null, successorPruned: false, recordedSince: '2026-01-01T00:00:00Z', replacedAt: '2026-03-01T00:00:00Z' };
+ expect(validTimeVerdict({ ...base, gapAt: '2026-02-01T00:00:00Z', edition })).toMatchObject({ status: 'in_force', history: 'incomplete', why: 'history_gap', uncertain: true });
+ expect(validTimeVerdict({ ...base, gapAt: '2026-05-01T00:00:00Z', edition })).toMatchObject({ history: 'retained', uncertain: false, why: null });
+ expect(validTimeVerdict({ ...base, gapAt: null, edition: { ...edition, successorPruned: true } })).toMatchObject({ history: 'incomplete', why: 'history_pruned' });
+ expect(validTimeVerdict({ ...base, gapAt: '2026-05-01T00:00:00Z', edition: { ...edition, chosen: false } }))
+ .toMatchObject({ status: 'before_recorded_history', history: 'incomplete', why: 'history_gap' });
+ expect(validTimeVerdict({ ...base, gapAt: null, edition: { ...edition, chosen: false } })).toMatchObject({ status: 'not_yet_in_force', history: 'retained', uncertain: false });
+ expect(validTimeVerdict({ ...base, gapAt: null, couldHaveBeenPruned: true, edition })).toMatchObject({ history: 'unknown', why: 'history_unknown', uncertain: true });
+ });
+
+ test('write advisories: correction, date-only question, unparsed date, nothing for an undated page', () => {
+ const fm = (d?: string) => (d ? { valid_from: d } : {});
+ expect(validTimeWriteAdvisory({ frontmatter: fm('2026-01-01'), body: 'a' }, { frontmatter: fm('2026-01-01'), body: 'b' })?.code).toBe('valid_time_correction');
+ const q = validTimeWriteAdvisory({ frontmatter: fm('2026-01-01'), body: 'a' }, { frontmatter: fm('2026-03-01'), body: 'a' });
+ expect(q?.code).toBe('valid_time_date_only');
+ expect(q?.message).toContain('correction of the earlier date, or a renewal');
+ expect(validTimeWriteAdvisory(null, { frontmatter: { valid_from: '2026-01' }, body: 'a' })?.code).toBe('valid_from_unparsed');
+ expect(validTimeWriteAdvisory({ frontmatter: {}, body: 'a' }, { frontmatter: {}, body: 'b' })).toBeNull();
+ });
+
+ test('B4: a reply without the valid_time echo fails closed with host_upgrade_required (exit 16)', () => {
+ const plain = { slug: 'policies/policy-4a-example', compiled_truth: 'Current text.' };
+ const e = (() => { try { assertValidTimeEcho({ as_of: '2026-07-01' }, plain, { client: '9.9.9.9', host: '0.60.400.0' }); return null; } catch (x) { return x as OperationError; } })();
+ expect(e).toBeInstanceOf(OperationError);
+ expect(e!.code).toBe('host_upgrade_required');
+ expect(JSON.parse(String(e!.detail))).toEqual({ client_version: '9.9.9.9', host_version: '0.60.400.0', min_host_version: VALID_TIME_MIN_HOST_VERSION });
+ expect(e!.fix?.argv).toEqual(['gbrain', 'upgrade']);
+ expect(exitCodeForCode('host_upgrade_required')).toBe(16);
+ expect(() => assertValidTimeEcho({ as_of: '2026-07-01' }, { valid_time: { as_of: '2026-07-01' } }, { client: 'x', host: null })).not.toThrow();
+ expect(() => assertValidTimeEcho({}, plain, { client: 'x', host: null })).not.toThrow();
+ });
+
+ test('B2b: CLI rendering puts the header on stderr, no document under another status, exit 15', () => {
+ const writes: string[] = [];
+ const orig = process.stderr.write.bind(process.stderr);
+ (process.stderr as { write: unknown }).write = (s: string) => { writes.push(String(s)); return true; };
+ try {
+ const expired = { slug: 's', valid_time: { as_of: '2027-02-01', status: 'not_in_force', chosen_version_id: null, chosen_is_current: true, valid_from: '2026-07-01', valid_until: '2027-01-01', history: 'retained', uncertain: false, why: null },
+ last_in_force: { compiled_truth: 'Expired text.' } };
+ expect(formatGetPage(expired)).toBe('status: not_in_force\nwhy: none\n');
+ expect(asOfExitCode(expired)).toBe(15);
+ const inForce = { slug: 's', title: 'Policy', type: 'note', frontmatter: {}, compiled_truth: 'Text in force.', timeline: '', valid_time: { ...expired.valid_time, as_of: '2026-08-01', status: 'in_force' } };
+ expect(formatGetPage(inForce)).toContain('Text in force.');
+ expect(asOfExitCode(inForce)).toBe(0);
+ const plain = { slug: 's', title: 'Policy', type: 'note', frontmatter: {}, compiled_truth: 'Future text.', timeline: '', valid_time: { status: 'not_yet_in_force', as_of: '2026-10-27', valid_from: '2027-01-01', valid_until: null } };
+ expect(formatGetPage(plain)).toContain('Future text.');
+ expect(asOfExitCode(plain)).toBe(0);
+ } finally { (process.stderr as { write: unknown }).write = orig; }
+ expect(writes.join('')).toContain('[gbrain] valid_time as_of 2027-02-01: not_in_force; edition current page (valid_from 2026-07-01, valid_until 2027-01-01); history retained.');
+ expect(writes.join('')).toContain('[gbrain] valid_time: not_yet_in_force as of 2026-10-27 (valid_from 2027-01-01, valid_until -).');
+ expect(validTimeLine({ as_of: 'd', status: 'in_force', chosen_version_id: 7, history: 'incomplete', uncertain: true, why: 'history_gap', valid_from: '2026-01-01' })).toContain('uncertain: history_gap');
+ });
+});
+
+for (const backend of testBackends()) {
+ describe(backend + ': get_page as_of (repo-less brain)', () => {
+ let engine: BrainEngine;
+ beforeAll(async () => {
+ if (backend === 'postgres') {
+ const pg = new PostgresEngine();
+ await pg.connect({ database_url: requirePostgresTestDatabase() });
+ engine = pg;
+ } else {
+ const lite = new PGLiteEngine();
+ await lite.connect({});
+ engine = lite;
+ }
+ await engine.initSchema();
+ await engine.executeRaw("DELETE FROM config WHERE key = 'mcp.inline_body_bytes'");
+ }, 180_000);
+ afterAll(async () => { await engine.disconnect(); resetGateway(); });
+
+ const ctx = (remote = false): OperationContext => ({ engine, config: { engine: backend } as never, logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote, sourceId: 'default' } as OperationContext);
+ const call = (name: string, params: R, remote = false) => operationsByName[name]!.handler(ctx(remote), params) as Promise<R>;
+ const read = (slug: string, as_of: string, remote = false, extra: R = {}) => call('get_page', { slug, as_of, ...extra }, remote);
+ async function put(slug: string, body: string, fm: string[] = [], reason?: string): Promise<R> {
+ const cur = await call('get_page', { slug, body: 'none' }).catch(() => null);
+ return outcomeOf(await call('put_page', { slug, content: page(body, fm), ...(cur ? { expected_revision: cur.revision } : {}), ...(reason ? { reason } : {}), wait_ms: 30_000 }));
+ }
+ const versionIds = async (slug: string) => ((await call('get_versions', { slug })) as unknown as R[]).map(v => Number(v.id)).reverse();
+
+ test('B-T1: editions, a same-date fix and the half-open boundary', async () => {
+ const slug = fresh('sel');
+ await put(slug, 'Refunds within 14 days.', ["valid_from: '2026-01-01'"]);
+ await put(slug, 'Refunds within 30 days.', ["valid_from: '2026-07-01'", "valid_until: '2027-01-01'"]);
+ await put(slug, 'Refunds within 30 days, receipts required.', ["valid_from: '2026-07-01'", "valid_until: '2027-01-01'"]);
+ const [v1] = await versionIds(slug);
+
+ const before = await read(slug, '2025-12-31');
+ expect(before.valid_time).toMatchObject({ as_of: '2025-12-31', status: 'not_yet_in_force', history: 'retained', uncertain: false, chosen_version_id: null, earliest_known_valid_from: '2026-01-01' });
+ expect(before.compiled_truth).toBeUndefined();
+ expect(before.earliest_known.compiled_truth).toContain('14 days');
+
+ for (const d of ['2026-01-01', '2026-06-30']) {
+ const r = await read(slug, d);
+ expect(r.valid_time).toMatchObject({ status: 'in_force', chosen_version_id: v1, chosen_is_current: false, valid_from: '2026-01-01', uncertain: false, history: 'retained' });
+ expect(r.compiled_truth).toContain('14 days');
+ }
+ for (const d of ['2026-07-01', '2026-12-31']) {
+ const r = await read(slug, d);
+ expect(r.valid_time).toMatchObject({ status: 'in_force', chosen_is_current: true, valid_from: '2026-07-01', valid_until: '2027-01-01', uncertain: false, why: null });
+ expect(r.compiled_truth).toContain('receipts required');
+ }
+ const after = await read(slug, '2027-01-01');
+ expect(after.valid_time).toMatchObject({ status: 'not_in_force', chosen_is_current: true, valid_until: '2027-01-01' });
+ expect(after.compiled_truth).toBeUndefined();
+ expect(after.last_in_force.compiled_truth).toContain('receipts required');
+ });
+
+ test('B-T1: a date-only change and a same-body renewal are flagged ambiguous_edition_dates', async () => {
+ const slug = fresh('dateonly');
+ await put(slug, 'Same text.', ["valid_from: '2026-01-01'"]);
+ const advisory = await put(slug, 'Same text.', ["valid_from: '2026-03-01'"]);
+ expect(advisory.valid_time).toMatchObject({ code: 'valid_time_date_only', valid_from: '2026-03-01', previous_valid_from: '2026-01-01' });
+ const early = await read(slug, '2026-02-01');
+ expect(early.valid_time).toMatchObject({ status: 'in_force', chosen_is_current: false, uncertain: true, why: 'ambiguous_edition_dates', competing_version_ids: [null] });
+ expect(early.fix).toMatchObject({ next: 'ask_user' });
+ expect(early.fix.user_message).toContain('Which date did this edition');
+ expect(early.fix.then.mcp.tool).toBe('edit_page');
+ expect(JSON.stringify(early.fix.then.mcp.arguments.edits)).toContain("valid_from: '<DATE>'");
+ const late = await read(slug, '2026-04-01');
+ expect(late.valid_time).toMatchObject({ chosen_is_current: true, uncertain: true, why: 'ambiguous_edition_dates' });
+
+ const renewal = fresh('renewal');
+ await put(renewal, 'Annual terms.', ["valid_from: '2025-01-01'", "valid_until: '2026-01-01'"]);
+ await put(renewal, 'Annual terms.', ["valid_from: '2026-01-01'", "valid_until: '2027-01-01'"]);
+ expect((await read(renewal, '2026-06-01')).valid_time).toMatchObject({ status: 'in_force', chosen_is_current: true, why: 'ambiguous_edition_dates' });
+ });
+
+ test('B-T1: a withdrawn scheduled edition and a backfill recorded last stay the rule pick, flagged', async () => {
+ const withdrawn = fresh('withdrawn');
+ await put(withdrawn, 'Edition A.', ["valid_from: '2026-01-01'"]);
+ await put(withdrawn, 'Edition B, scheduled.', ["valid_from: '2026-09-01'"]);
+ await put(withdrawn, 'Edition A.', ["valid_from: '2026-01-01'"]);
+ const [, vB] = await versionIds(withdrawn);
+ const oct = await read(withdrawn, '2026-10-01');
+ expect(oct.valid_time).toMatchObject({ status: 'in_force', chosen_version_id: vB, uncertain: true, why: 'ambiguous_edition_dates', competing_version_ids: [null] });
+ expect(oct.compiled_truth).toContain('scheduled');
+ const may = await read(withdrawn, '2026-05-01');
+ expect(may.valid_time).toMatchObject({ chosen_is_current: true, uncertain: false });
+
+ const backfill = fresh('backfill');
+ await put(backfill, 'Edition 2026a.', ["valid_from: '2026-01-01'"]);
+ await put(backfill, 'Edition 2026b.', ["valid_from: '2026-07-01'"]);
+ await put(backfill, 'Edition 2025.', ["valid_from: '2025-01-01'"]);
+ const [, v2026b] = await versionIds(backfill);
+ expect((await read(backfill, '2025-06-01')).valid_time).toMatchObject({ chosen_is_current: true, uncertain: false });
+ expect((await read(backfill, '2026-08-01')).valid_time).toMatchObject({ chosen_version_id: v2026b, why: 'ambiguous_edition_dates' });
+ });
+
+ test('B-T1 privacy: a private chosen edition reads as a missing page; a private-time reason never shows', async () => {
+ const slug = fresh('privacy');
+ await put(slug, 'World edition one.', ["valid_from: '2026-01-01'"]);
+ await put(slug, 'Private edition.', ["valid_from: '2026-06-01'", 'visibility: private'], 'reason-r2-private-time');
+ await put(slug, 'World edition two.', ["valid_from: '2026-09-01'"], 'reason-r3-back-to-world');
+ const hidden = await refusal(read(slug, '2026-07-01', true));
+ expect(hidden?.code).toBe('page_not_found');
+ const local = await read(slug, '2026-07-01');
+ expect(local.compiled_truth).toContain('Private edition.');
+ const early = await read(slug, '2026-03-01', true);
+ expect(early.compiled_truth).toContain('World edition one.');
+ expect(early.valid_time.replaced_because).toBeNull();
+ expect((await read(slug, '2026-03-01')).valid_time.replaced_because).toBe('reason-r2-private-time');
+ const late = await read(slug, '2026-10-01', true);
+ expect(late.valid_time.introduced_because).toBe('reason-r3-back-to-world');
+ for (const d of ['2025-01-01', '2026-03-01', '2026-10-01']) expect(JSON.stringify(await read(slug, d, true))).not.toContain('reason-r2');
+ });
+
+ test('B-T2: an imported page with no gbrain-written first version reads before_recorded_history with a recovery', async () => {
+ const slug = fresh('imported');
+ await importFromContent(engine, slug, page('Imported edition.', ["valid_from: '2026-03-01'"]), { sourcePath: slug + '.md', noEmbed: true });
+ const r = await read(slug, '2026-01-01');
+ expect(r.valid_time).toMatchObject({ status: 'before_recorded_history', history: 'incomplete', uncertain: true, why: 'before_recorded_history', earliest_known_valid_from: '2026-03-01' });
+ expect(r.compiled_truth).toBeUndefined();
+ expect(r.fix).toMatchObject({ next: 'ask_user' });
+ await engine.executeRaw("UPDATE sources SET local_path = '/srv/brain-example' WHERE id = 'default'");
+ try {
+ expect((await read(slug, '2026-01-01')).fix.argv).toEqual(['git', '-C', '/srv/brain-example', 'log', '--follow', '-p', '--', slug + '.md']);
+ const remote = await read(slug, '2026-01-01', true);
+ expect(remote.fix).toMatchObject({ next: 'tell_user_to_run', argv: ['git', 'log', '--follow', '-p', '--', slug + '.md'] });
+ expect(JSON.stringify(remote)).not.toContain('/srv/brain-example');
+ } finally { await engine.executeRaw("UPDATE sources SET local_path = NULL WHERE id = 'default'"); }
+ });
+
+ test('B-T2/B-T7b: a pruned page and an unmarked upgraded page are uncertain; the recovery asks for a backup, never git', async () => {
+ const pruned = fresh('pruned');
+ await put(pruned, 'Small edition.', ["valid_from: '2026-01-01'"]);
+ const big = 'x'.repeat(1024 * 1024 + 10);
+ for (let i = 0; i < 7; i++) {
+ await engine.executeRaw("UPDATE pages SET compiled_truth = $2, frontmatter = jsonb_set(frontmatter, '{valid_from}', to_jsonb($3::text)) WHERE slug = $1", [pruned, big + i, '2026-0' + (i + 2) + '-01']);
+ await createPageVersion(engine, pruned, 'default');
+ }
+ const [{ gap }] = await engine.executeRaw<{ gap: unknown }>('SELECT version_history_gap_at AS gap FROM pages WHERE slug = $1', [pruned]);
+ expect(gap).not.toBeNull();
+ const r = await read(pruned, '2026-01-15');
+ expect(r.valid_time).toMatchObject({ status: 'before_recorded_history', history: 'incomplete', uncertain: true, why: 'history_gap' });
+ expect(r.fix).toMatchObject({ next: 'ask_user' });
+ expect(r.fix.user_message).toContain('retained copy or a backup');
+ expect(r.fix.argv).toBeUndefined();
+ expect(r.compiled_truth).toBeUndefined();
+
+ const unmarked = fresh('unmarked');
+ await put(unmarked, 'Edition.', ["valid_from: '2026-01-01'"]);
+ const [{ id }] = await engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE slug = $1', [unmarked]);
+ for (let i = 0; i < 5; i++) {
+ await engine.executeRaw("INSERT INTO page_versions (page_id, compiled_truth, frontmatter, timeline, title, type, tags) VALUES ($1, $2, '{}'::jsonb, '', 'Policy', 'note', '[]'::jsonb)", [id, big + i]);
+ }
+ const u = await read(unmarked, '2026-05-01');
+ expect(u.valid_time).toMatchObject({ status: 'in_force', history: 'unknown', uncertain: true, why: 'history_unknown', undated_versions: 5 });
+ expect(u.fix).toMatchObject({ next: 'ask_user' });
+ }, 120_000);
+
+ test('B-T3: refusals', async () => {
+ const slug = fresh('refuse');
+ await put(slug, 'Text.', ["valid_from: '2026-01-01'"]);
+ const instant = await refusal(read(slug, '2026-07-01T00:00:00Z'));
+ expect(instant?.toJSON()).toMatchObject({ code: 'clock_mismatch', reason: 'instant_for_date' });
+ expect((await refusal(read(slug, '2026-07')))?.code).toBe('invalid_params');
+ const both = await refusal(read(slug, '2026-07-01', false, { known_as_of: '2026-07-01T00:00:00Z' }));
+ expect(both?.toJSON()).toMatchObject({ error: 'invalid_params' });
+ expect(both?.fix?.mcp?.arguments).toEqual({ slug, as_of: '2026-07-01' });
+ const content = await refusal(read(slug, '2026-07-01', false, { include_content: true }));
+ expect(content?.code).toBe('invalid_params');
+ expect(content?.suggestion).toContain('silently revert');
+ expect((await refusal(read(slug, '2026-07-01', false, { content_only: true })))?.code).toBe('invalid_params');
+
+ const shared = fresh('shared');
+ await engine.executeRaw("INSERT INTO sources (id, name, config) VALUES ('vt-second', 'vt-second', '{\"federated\": true}'::jsonb) ON CONFLICT (id) DO NOTHING");
+ await put(shared, 'Default copy.', ["valid_from: '2026-01-01'"]);
+ await importFromContent(engine, shared, page('Second copy.', ["valid_from: '2026-01-01'"]), { sourceId: 'vt-second', noEmbed: true });
+ const ambiguous = await refusal(call('get_page', { slug: shared, as_of: '2026-07-01', source_id: '__all__' }));
+ expect(ambiguous?.code).toBe('invalid_params');
+ expect(ambiguous?.message).toContain('several sources');
+ expect(ambiguous?.fix?.mcp?.arguments).toMatchObject({ slug: shared, as_of: '2026-07-01' });
+ expect((await call('get_page', { slug: shared, as_of: '2026-07-01', source_id: 'vt-second' })).compiled_truth).toContain('Second copy.');
+
+ const undated = fresh('undated');
+ await put(undated, 'No dates here.');
+ const u = await refusal(read(undated, '2026-07-01'));
+ expect(u?.code).toBe('valid_time_undeclared');
+ expect(u?.fix).toMatchObject({ ask_user: true });
+ expect(u?.fix?.user_message).toContain('When did');
+ expect(u?.fix?.then?.mcp?.tool).toBe('edit_page');
+ expect(u?.suggestion).toContain('known_as_of');
+ });
+
+ test('B-T4: unquoted, quoted and partial dates through real imports; the SQL normaliser matches TypeScript', async () => {
+ const slug = fresh('forms');
+ await put(slug, 'Unquoted.', ['valid_from: 2026-01-01']);
+ await put(slug, 'Quoted.', ["valid_from: '2026-02-01'"]);
+ const partial = await put(slug, 'Partial.', ['valid_from: 2026-03']);
+ expect(partial.valid_time).toMatchObject({ code: 'valid_from_unparsed' });
+ const rows = (await call('get_versions', { slug })) as unknown as R[];
+ expect(rows.map(r => r.valid_from)).toEqual(['2026-02-01', '2026-01-01']);
+ const r = await read(slug, '2026-04-01');
+ expect(r.valid_time).toMatchObject({ valid_from: '2026-02-01', undated_versions: 1 });
+ expect(r.compiled_truth).toContain('Quoted.');
+ expect((await read(slug, '2026-01-15')).compiled_truth).toContain('Unquoted.');
+ const inputs = ['2026-01-01', '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00Z', '2026-01-01T00:00:00+00:00', '2026-02-29', '2028-02-29', '2026-02-30', '2026-13-01', '2026-00-10', '2026-01', '2026', '0999-01-01', '2026-01-01T09:00:00Z', 'soon', ''];
+ for (const input of inputs) {
+ const [row] = await engine.executeRaw<{ d: string | null }>('SELECT ' + validDateSql('$1::text') + ' AS d', [input]);
+ expect([input, row!.d ?? null]).toEqual([input, validDate(input)]);
+ }
+ });
+
+ test('B-T6: windows of a large chosen version stay pinned to it across next cursors, and a gone edition says so', async () => {
+ await engine.executeRaw("INSERT INTO config (key, value) VALUES ('mcp.inline_body_bytes', '2000') ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value");
+ try {
+ const slug = fresh('windows');
+ const old = Array.from({ length: 400 }, (_, i) => 'Old edition line ' + i + '.').join('\n');
+ await put(slug, old, ["valid_from: '2026-01-01'"]);
+ await put(slug, 'New edition.', ["valid_from: '2026-07-01'"]);
+ const [v1] = await versionIds(slug);
+ let r = await read(slug, '2026-03-01', true, { max_bytes: 1500 });
+ expect(r.valid_time).toMatchObject({ status: 'in_force', chosen_version_id: v1 });
+ expect(r.compiled_truth).toBeUndefined();
+ expect(r.body).toBe('window');
+ let text = r.window.text;
+ let hops = 0;
+ while (r.next) {
+ expect(r.next.arguments).toMatchObject({ slug, source_id: 'default', as_of: '2026-03-01' });
+ if (hops === 1) await put(slug, 'A third edition written mid-read.', ["valid_from: '2026-02-01'"]);
+ r = await call('get_page', r.next.arguments, true);
+ expect(r.version_id).toBe(v1);
+ text += r.window.text;
+ hops++;
+ }
+ expect(hops).toBeGreaterThan(2);
+ expect(text).toBe(old);
+ expect((await read(slug, '2026-03-01', true)).compiled_truth).toContain('third edition');
+
+ const first = await read(slug, '2026-01-15', true, { max_bytes: 1500 });
+ expect(first.version_id).toBe(v1);
+ await engine.executeRaw('DELETE FROM page_versions WHERE id = $1', [first.version_id]);
+ const gone = await call('get_page', first.next.arguments, true);
+ expect(gone.valid_time).toMatchObject({ history: 'incomplete', uncertain: true, why: 'edition_pruned' });
+ expect(gone.window).toBeUndefined();
+ expect(gone.compiled_truth).toBeUndefined();
+ } finally { await engine.executeRaw("DELETE FROM config WHERE key = 'mcp.inline_body_bytes'"); }
+ });
+
+ test('B-T7/B6/B5: plain read status, an unchanged plain read, get_versions dates and the correction advisory', async () => {
+ const future = fresh('future');
+ await put(future, 'Takes effect later.', ["valid_from: '2099-01-01'"]);
+ const r = await call('get_page', { slug: future });
+ expect(r.valid_time).toEqual({ status: 'not_yet_in_force', as_of: utcToday(), valid_from: '2099-01-01', valid_until: null });
+ expect(r.compiled_truth).toContain('Takes effect later.');
+ expect((await call('get_page', { slug: future, body: 'none' }, true)).valid_time.status).toBe('not_yet_in_force');
+ const plain = fresh('plain');
+ await put(plain, 'No dates.');
+ const plainRead = await call('get_page', { slug: plain });
+ expect('valid_time' in plainRead).toBe(false);
+ expect(currentValidTime({})).toBeNull();
+
+ const corrected = fresh('corrected');
+ expect((await put(corrected, 'Draft.', ["valid_from: '2026-01-01'", "valid_until: '2026-06-01'"])).valid_time).toBeUndefined();
+ expect((await put(corrected, 'Draft, fixed typo.', ["valid_from: '2026-01-01'", "valid_until: '2026-06-01'"])).valid_time)
+ .toMatchObject({ code: 'valid_time_correction', valid_from: '2026-01-01' });
+ const versions = (await call('get_versions', { slug: corrected })) as unknown as R[];
+ expect(versions[0]).toMatchObject({ valid_from: '2026-01-01', valid_until: '2026-06-01' });
+ expect((await call('get_page', { slug: corrected })).valid_time).toMatchObject({ status: 'not_in_force', valid_until: '2026-06-01' });
+ });
+
+ test('B-T8: 500 versions: the pick is one statement and stays within its budget', async () => {
+ const slug = fresh('many');
+ await put(slug, 'Edition 0.', ["valid_from: '2000-01-01'"]);
+ const [{ id }] = await engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE slug = $1', [slug]);
+ await engine.executeRaw("INSERT INTO page_versions (page_id, compiled_truth, frontmatter, timeline, title, type, tags) SELECT $1, 'Edition ' || g, jsonb_build_object('valid_from', to_char(date '2000-01-01' + g * 7, 'YYYY-MM-DD')), '', 'Policy', 'note', '[]'::jsonb FROM generate_series(1, 500) g", [id]);
+ const seen: string[] = [];
+ const transaction = engine.transaction.bind(engine);
+ (engine as { transaction: unknown }).transaction = (fn: (tx: BrainEngine) => Promise<unknown>) => transaction(async tx => {
+ const exec = tx.executeRaw.bind(tx);
+ (tx as { executeRaw: unknown }).executeRaw = (sql: string, params?: unknown[]) => { seen.push(sql); return exec(sql, params as never); };
+ return fn(tx);
+ });
+ let r: R, ms: number;
+ try {
+ await read(slug, '2005-06-01');
+ seen.length = 0;
+ const t0 = performance.now();
+ r = await read(slug, '2005-06-01');
+ ms = performance.now() - t0;
+ } finally { (engine as { transaction: unknown }).transaction = transaction; }
+ expect(seen.filter(s => s.includes('WITH rows AS'))).toHaveLength(1);
+ const days = Math.floor((Date.UTC(2005, 5, 1) - Date.UTC(2000, 0, 1)) / 86_400_000 / 7) * 7;
+ expect(r.valid_time).toMatchObject({ status: 'in_force', valid_from: new Date(Date.UTC(2000, 0, 1) + days * 86_400_000).toISOString().slice(0, 10) });
+ expect(ms).toBeLessThan(2_000);
+ }, 60_000);
+ });
+}