Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

GBRA-161 PR 1a: move the generations key-files entry to its own subsystem page (canonical-reconciliation.md at its cap after the merge)

garrytancdf10cdf59fb
diff --git a/docs/architecture/key-files/canonical-reconciliation.md b/docs/architecture/key-files/canonical-reconciliation.md
index 8820de0111..c80eafd12e 100644
--- a/docs/architecture/key-files/canonical-reconciliation.md
+++ b/docs/architecture/key-files/canonical-reconciliation.md
@@ -1,5 +1,7 @@
# Canonical reconciliation
+See [generations](generations.md).
+
- `src/commands/sync-diagnostics.ts` + `src/core/persistence/{sync-run,verb-errors}.ts` — bounded source/slug/path/reason diagnostics derive from immutable managed-sync receipts, including when the local failure ledger is unavailable. Direct and resident-owner JSON carry the same receipt; human memory errors lead with the specific write reason without widening frozen v1 error codes. Pending requests retain their original UUID, terminal corrections require a new UUID, and neither retry nor line-ending diagnostics bypasses raw-byte or skip guards.
- `src/core/persistence/reconcile*.ts` — trusted-local exact-page reconciliation: loss-preserving semantic preview, explicit JSON Pointer choices, pinned identity/revision/raw-file/policy checks, durable private preimages and same-ID replay through the existing coordinator. Normal overwrite protection stays unchanged. The bounded audit reports source-scoped drift without repair or checkpoint changes; a database-only page (`isDatabaseOnlyPage`, with no file at its slug-derived path) counts as `database_only` with no reconcile suggestion, never as drift, while a legacy row that merely lacks `source_path` is audited as usual. `src/commands/source-reconcile.ts` provides strict CLI parsing, private artifact I/O, brain routing and resident-owner delegation; the operations stay outside public MCP. Operator flow: `docs/guides/concurrent-writes.md`. Tests cover merge choices, both engines, grants, stale previews, read-only audit, and private files. A database-only page (no `source_path`, no `source_uri`; `isDatabaseOnlyPage` in `src/core/persistence/unbound-pages.ts`) is matched to the canonical file at its slug-derived path (`ReconcileState.origin: 'slug_derived'`), and apply records that path as its `source_path` (the #5254 unbound collision; `test/reconcile-unbound-collision.test.ts`). Private fact rows (#6137): `reconcile-prepare.ts` `privateFactViolation` identifies a fact row by (row number, claim), as `restoreHiddenFactRows` does. A stored non-world row carried at its identity must be unchanged; a row at no stored identity may not carry a stored private claim under another visibility, and a world row may not carry (or newly gain) a stored private row's context of 24 or more characters verbatim; sources are not compared. The `permission_denied` refusal names only the row number, with a `gbrain get` read fix. It guards verbatim copies, not reworded text. #6138: an `--auto-additive` preview classified `no_drift` asks Git (`hardened-git.ts` `hardenedPathDirty`: filter-free plumbing, never `git status`, so the checkout's clean/process filters never run; `null` when only repository config could decide) whether the canonical file differs from its last commit and returns `git_dirty`; a dirty file's `next_action` says the content agrees, the difference is only how it is written, reconcile does not commit, and names `git -C <root> diff -- <file>` (committing it is the user's decision; the managed commit path is deferred, D5). The "retry the original write" step is conditional on the preview coming from a refused write. Tests: `test/persistence-reconcile-git-dirty-6138.test.ts`. #6222/#6254: `assertSoleFileClaim` (reconcile-state.ts) refuses on any claimant `findLiveFileClaimants` (file-claims.ts) returns, naming the soft-delete exit (#6517). Its predicates (`fileClaimCandidatesQuery`) match the v219 expression indexes `pages_source_path_name_idx` and `pages_file_uri_name_idx` (built online, one statement per call). `sources reconcile` help says writes to one source publish one at a time. Tests: `test/persistence-reconcile.test.ts`, `test/e2e/pages-reconcile-name-indexes-postgres.test.ts`. #6394: `readReconcileState(..., { adoptSlugPath })` lets a live page with no recorded origin and no database-only marker reconcile against the file at its slug path (`slugDerivedOrigin`, mode-aware), never for a declared db_only slug, a never-filed derive-phase page, a page with a `source_uri` or a mirror-only page; the CLI flag is `gbrain sources reconcile … --preview --adopt-slug-path`, and apply and the consumer's prepare adopt only when the preview's stored page recorded no origin (`reconcilePreviewAdopts`), with the pinned relative path and binding digest unchanged. The drift refusal names the flag for such a page. #6712 wave: a missing canonical file refuses `source_changed` / detail `canonical_file_missing` with the route `canonicalDeletionState` picks from bounded filter-free Git plumbing (`missingFileRoute`: still committed at HEAD → commit the deletion or `gbrain repair ghost-pages`; gone from HEAD, or no Git or no commit → `gbrain repair file-drift --prefer database|file`). `readReconcileState(..., { fileGone })` instead returns an absent state for a recorded origin: empty preimage bytes, `raw_file_hash` pinned to `ABSENT_FILE_HASH` (all zeros, which no file hashes to, so a file that reappears is stale), the file side read as the page itself, and `assertSoleFileClaim` run with `absent: true` (`file-claims.ts` `absentCanonicalPath`, so a candidate recording the same missing path still claims it). `reconcileReadOptions` derives `adoptSlugPath` and `fileGone` from a stored preview for apply and the consumer's prepare, whose file target then expects no bytes (`expectedBeforeHash: null`). Test: `test/repair-file-drift-deleted-6712.test.ts`. `readDeletedDriftTarget` reads the deleted side of a held file that is present: a deleted page at the origin is `tombstone_edited` (id and revision), otherwise a `deleted` `sync-origin-deleted` marker is `purged_differs` (its value digested); a live claimant, a missing file, no deletion or bytes the marker held return `changed`.
@@ -8,9 +10,7 @@
- `src/core/persistence/publication-failure.ts` (#5974) — maps a P0001 from the managed-writer guard (which raises TABLE/SCHEMA, `managed_writer_guard:<branch>` and a JSON DETAIL) or another trigger to a bounded `error_detail` (origin, raiser, table, op, branch, relationship, stage, plus owner-only source ids and the attempt's build/host). Receipts expose only `publicFailureDetail`; `sources writer status` lists the full detail under `recent_failures`. #5929: `ownerExceptionFailure` (the coordinator `requestError` fallback) keeps an unexpected exception's class, errno and top `src/...:line` frame as `origin: owner_exception` (never an application error's message), so `withAttempt` stamps the build; #7112: a server-generated database error (a five-character SQLSTATE, a severity and a routine; never a PL/pgSQL RAISE or ASSERT or another class P0 error) also keeps `error_text` (its primary message, at most 240 characters; object names survive only in a known catalog message such as a not-null violation, or a syntax-error or does-not-exist message whose name the statement holds as an identifier; any other message loses everything from its first quote to its last, because Postgres does not escape quotes inside a value) and `statement` (the failing SQL tokenized: keywords, identifiers, parameter markers and operators, with every literal, E-string, dollar-quoted body, number and comment replaced or dropped, cut at anything unrecognized, at most 160 characters, never the parameters) and `position`, all owner-only; a trusted local `gbrain write-request <id>` returns the full `error_detail`; `publicFailureDetail` is an allow-list (origin, sqlstate, raiser, table, op, branch, relationship, reason, stage, fence), so `error_class`/`errno`/`frame`/`error_text`/`statement`/`position`, `sources` and `attempt` stay owner-only; `ownerBuildMismatch` drives the local `owner_build` receipt field (`ops/persistence.ts`) and the submit-time why/fix (`page-mutations.ts`), and `ownerExceptionLogText` the consumer log line. Wave 16 (GBRA-79, #6513 comments): an untyped refusal carries a CLOSED `reason` (`PUBLICATION_REASONS`: `attribution_unclassified_table` and `trust_unclassified_table` from the two stamp triggers' own "is not classified for table" raise, `graduation_in_progress` from the engine-graduation fence, which raises SQLSTATE 55000 and which `databaseRefusal` now recognizes, else `unknown`); the message decides nothing on its own (the same text from another raiser, or the fence's text under P0001, is `unknown`), the public message names only the enum (`Publication failed (P0001 in <raiser>: <reason>)`), and no part of the message is stored, owner-side included (#5974's rule). `publicFailureDetail` passes `reason` only as a member of the enum, whatever a stored detail holds. The projection rides the managed failure (`sync-failures.ts` `ManagedSyncFailure.write_error_detail`, recorded with the failure and re-read from the pending receipt by `readManagedSyncFailures`; `publicationDetailText` appends ` raiser= table= reason=` to `formatManagedSyncFailure`, so the ledger mirror and doctor carry it) and `gbrain sync status --json` (`last_error.write_error_detail`, `last_error.detail` = the reason, which `classifySyncFault` refines by: `graduation_in_progress` is `connection` / retry / no human in `sync-fault-class.ts`). Tests: `test/publication-failure-reason-6513.test.ts` (mapping, privacy negatives, allow-list), `test/sync-status-failure-detail-6513.test.ts` (both engines, a real operator trigger).
-- `src/core/generations/{contract,plan,publish,proofs,config,repair,ledger-scrub}.ts` + `adapters/{page,atoms,index}.ts` (GBRA-161) — the generation primitive: one ledger row per derived key generation (`derived_generations`, items and bounded preimages in `derived_generation_items`); `publishGeneration` holds a shrunk, oversize, unproven-empty, valve or segmented result and otherwise writes, completes, rechecks, retires (versioned, stamped) and activates in one transaction. `gbrain repair generations` restores or releases from previews; doctor `generation_retirements` / `generation_held`. Reference: [generations](../generations.md). Tests: `test/pathological/g1-generations.test.ts`, `test/pathological/g1-atom-generations.test.ts`.
-
-- `src/core/cycle/extract-atoms-page-state.ts` — derived page scan/failure state keyed by source incarnation, stable page identity and content hash. Compare-and-swap stamps never update canonical frontmatter. Reviewed reconciliation can carry matching state across removal of legacy bookkeeping fields. Unmanaged atom items publish and complete as one generation ([generations](../generations.md)); managed extraction uses journaled publication and a durable completion receipt after trusted local source-wide authority checks and, for filesystem publication, owner preflight.
+- `src/core/cycle/extract-atoms-page-state.ts` — derived page scan/failure state keyed by source incarnation, stable page identity and content hash. Compare-and-swap stamps never update canonical frontmatter. Reviewed reconciliation can carry matching state across removal of legacy bookkeeping fields. Unmanaged atom items complete as one generation; managed extraction uses journaled publication and a durable completion receipt after trusted local source-wide authority checks and, for filesystem publication, owner preflight.
- `src/core/persistence/grandfather.ts` — provider-free canonical publication for the grandfather compatibility flag on active managed Markdown pages. Admission retains a checkpointed request UUID, exact source/incarnation/page/revision identity and a private rollback snapshot. Publication preserves chunks/vectors and only already-valid text seals, carries matching atom scan state across the metadata hash change, and defers embeddings without queuing fact extraction. Explicit validation choices, archived sources and non-Markdown artifacts remain untouched; unpublished file edits refuse. Pages under a declared `storage.db_only` dir without a local cache file publish database-only. The committed revision is returned so the migration's verify phase can tell a later rewrite from a lost write. `admitCanonicalGrandfather` splits admission from `complete()` (wait, then settle the checkpoint exactly as the serial `grandfatherCanonicalPage` does); the migration admits a 50-page window before waiting, so the pages' Git effects coalesce (#5530). The unmanaged migration keeps its bounded SQL batches. `test/grandfather-managed.test.ts` covers both engines, replay, races and preserved artifacts; the unchanged local-install lifecycle exercises the public upgrade path.
diff --git a/docs/architecture/key-files/generations.md b/docs/architecture/key-files/generations.md
new file mode 100644
index 0000000000..ed285843b2
--- /dev/null
+++ b/docs/architecture/key-files/generations.md
@@ -0,0 +1,6 @@
+# Key files: Derived generations
+
+[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.
+Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
+
+- `src/core/generations/{contract,plan,publish,proofs,config,repair,ledger-scrub}.ts` + `adapters/{page,atoms,index}.ts` (GBRA-161) — the generation primitive: one ledger row per derived key generation (`derived_generations`, items and bounded preimages in `derived_generation_items`); `publishGeneration` holds a shrunk, oversize, unproven-empty, valve or segmented result and otherwise writes, completes, rechecks, retires (versioned, stamped) and activates in one transaction. `gbrain repair generations` restores or releases from previews; doctor `generation_retirements` / `generation_held`. Reference: [generations](../generations.md). Tests: `test/pathological/g1-generations.test.ts`, `test/pathological/g1-atom-generations.test.ts`.