Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
GBRA-217: verify fixes (key-files page, module ceilings, guard and dynamic-SQL allowlists, skill link, regenerated trees)
garrytanf33d980f64d5
diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.mdindex 69a1ff129d..905d06734b 100644--- a/docs/architecture/KEY_FILES.md+++ b/docs/architecture/KEY_FILES.md@@ -25,7 +25,7 @@ link it here rather than raising the cap.|---|---|| [Page identity and writer administration](key-files/page-identity-and-administration.md) | Opaque result IDs, current grants, state-bound ownership changes || [Canonical reconciliation](key-files/canonical-reconciliation.md) | Exact-page repair, retained originals, [derived generations](key-files/generations.md), sync discovery and the origin rule (`sync-origin.ts`, `file-claims.ts`) |-| [Company-brain ingestion](key-files/company-brain.md) | Inspection, admission, receipts, derived relationships and schema; [operator guide](../guides/company-brain-ingestion.md) |+| [Company-brain ingestion](key-files/company-brain.md) | Inspection, admission, receipts, derived relationships and schema || [Agent operator contract](key-files/agent-contract.md) | `agent-output.ts`, error registry + docs, notice ledger, `isCallable`, `--json` guard, contract scanner || [Commands (1/6)](key-files/commands-1.md) | `src/commands/agent-logs.ts` through `src/commands/db-repair.ts` || [Commands (2/6)](key-files/commands-2.md) | `src/commands/doctor.ts` and `src/commands/doctor/` |@@ -47,7 +47,7 @@ link it here rather than raising the cap.| [Core Minions (2/2)](key-files/core-minions-2.md) | `src/core/minions/queue.ts` through `src/core/minions/worker.ts` || [Core Persistence](key-files/core-persistence.md) | `src/core/persistence/` journal, coordinator, effects, managed sync || [Core Persistence (continued)](key-files/core-persistence-continued.md) | worktree-refresh*, connectors, holds, receipts; [fence repair](key-files/core-fence-repair.md) |-| [Persistence capacity](key-files/core-persistence-capacity.md) | write caps, true-up |+| [Persistence capacity](key-files/core-persistence-capacity.md) | write caps, true-up; [page history](key-files/page-history.md) || [Core Persistence (seams)](key-files/core-persistence-request-indexes.md) | `checkpoint-validation`, `fault-points`, `native-file-target`, `admission-retry`, `unbound-source` || [Core Persistence (managed facts)](key-files/core-persistence-facts.md) | `facts-maintenance.ts`, `facts-prepare.ts`, `derived-facts.ts`, `same-page-shadow.ts` || [Core Persistence (engine graduation)](key-files/core-persistence-graduation.md) | `engine-graduation*.ts`, `graduation-*.ts`, `commands/migrate-graduation.ts` |diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.mdindex dd2419dfa7..25a49499c3 100644--- a/docs/architecture/key-files/core-persistence.md+++ b/docs/architecture/key-files/core-persistence.md@@ -12,7 +12,6 @@ Managed facts extraction (withdrawn-candidate skip and recovery, conversation fa- `src/core/persistence/activation.ts` — private CLI `sources writer activate --confirm-quiesced` boundary. Verifies native capability and filesystem bindings, takes root locks before DB waits and rechecks topology under transaction guards. Live/young/foreign legacy leases refuse regardless of expiry; only explicitly requested `--cleanup-dead-local-locks` removes exact dead same-host holders under the lease lock. Dry-run deletes nothing. Never silently claims a source. Tests: `test/persistence-activation.test.ts`, `test/persistence-onboarding.test.ts`. Unbound Google/GitHub API sources may activate as reviewed `connector_database` without fabricating a Git root, while bound sources still need physical-root checks. Activation increments `persistence_brain.mode_epoch` (migration 183), which the writer admin-state hash includes. A non-connector source whose recorded `local_path` no longer exists or is relative (unclaimed, or claimed by this host) refuses `source_changed` with detail `source_path_missing`, naming the source, the path and the `sources set-path` / `sources remove` exits (the claimed checkout filled in), in `--dry-run` too (#5206, `test/activation-missing-source-path.test.ts`). The report's `warnings[]` (dry run and real run) carries one `git_durability_not_enabled` entry per filesystem source the effect runner's policy (`gitDurabilityPolicy`) would leave non-durable, with `enable_command`, a read-only `git-durability --enable --dry-run` fix and the note that enabling re-queues skipped Git effects; `persistence-admin.ts` also prints them to stderr without `--json`, and activation proceeds (#5182, `test/writer-activate-durability-warnings-5182.test.ts`).- `src/core/persistence/git-durability-policy.ts` + `git-durability-administration.ts` — whether the persistence owner commits and pushes page writes through its Git effect is a per-host-binding setting (#5182): `persistence_host_bindings.git_durability` (`enabled` | `disabled` | NULL, migration v234, column SQL kept out of the replayed schema blob as `PERSISTENCE_GIT_DURABILITY_COLUMN_SQL`). `gitDurabilityPolicy(binding, root)` is tri-state and fail-closed: a recorded value wins, NULL falls back to the legacy post-commit-hook probe, a probe error fails the effect instead of skipping it; `effects.ts` takes its per-root verdict from it. `gitDurabilityState` renders `on`/`off`/`unknown` for `writer status` and `writer activate`'s `git_durability` listing. `planGitDurabilityCatchUp`/`requeueGitDurabilityCatchUp` re-queue the Git effects completed `durability_not_enabled` while the setting was off by resetting the existing rows, never inserting under `UNIQUE(request_id, kind)`. The verb `writer_git_durability` (`gbrain sources writer git-durability <source> --enable|--disable [--pat-file <path>] [--dry-run]`, administration-gated like the other writer verbs) runs a read-only `git push --dry-run` probe before enabling (codes `git_branch_unborn`, `git_checkout_required`, `git_detached_head`), wires the repo-scoped credential under `gbrain.durability.managedcredential` from a 0600 `--pat-file` (`pat_file_unreadable` otherwise) and retries the worktree's parked pushes (codes in `GIT_PUSH_CODES`; `retry-effects <source> --parked-pushes` does the same without a credential). `sources push` (`managedPushRefusal` in `workspace-push.ts`), `bootstrap verify`'s `checkPushProbe` and the skill-pack writer guard name this route on a managed worktree (#5606). Pinned by `test/persistence-admin-git-durability.test.ts`, `test/managed-push-remedy.serial.test.ts`.-- `src/core/persistence/change-reason.ts` — GBRA-217 page-write reasons ([page history](../../guides/page-history.md#reasons)). `admitChangeReason` canonicalises a `reason` (one line, at most 500 code points) and refuses `change_reason_rejected` (`reason_too_long`, `reason_contains_secret` via `scanTextSpans`) before admission, so no journal row ever holds a refused reason; `page-mutations.ts` runs it before `callerIntent`, so the canonical reason joins replay identity, and `page-batch.ts` runs it per item (all or nothing). `withChangeReason` wraps a page preparer in `service.ts`: its apply stamps `page_versions.change_reason` on the snapshots that transaction created for the page, and, for a world-visible page whose file is published, appends `gbrain-reason: <path>: <text>` to `prepared.file.commit` (a `GitCommitNote` with `trailers[]`), which both the door (`commitThroughDoor`) and the effect commit (`commitMessage`, one trailer line each, `commitMessageArgs` switching to `-F` over 8 KiB) read after apply. The outcome's `reason_recorded.git` is `committed` (strict), `queued`, `private`, `not_file_backed`, `no_repository` (repo-less) or `none`; `settledReasonRecorded` turns `queued` into `superseded` with a `reason_not_committed` notice on the receipt when the Git effect was superseded. Read side: `replacedBecauseSql` in `engine-sql/pages.ts` (remote readers see a reason only when the successor snapshot is world-visible and not `successor_pruned`, which the prunes in `page-state/versions.ts` set). Tests: `test/page-change-reason-gbra217.test.ts`, `test/page-change-reason-git-gbra217.test.ts`, `test/page-change-reason-mcp-gbra217.test.ts`.- `src/core/persistence/effect-git.ts` (`pushGitRoot`) + `git-push-holds.ts` — a Git effect's push tries a plain push first; a non-fast-forward rejection runs this executable's `gbrain git commit-push --push-only --keep-checkout` as a child (never on the owner's event loop, never a `gbrain` from PATH), which merges the moved remote in memory and pushes without moving the checkout or running its pre-push hook, so `sources refresh` stays the only importer. A true conflict holds the effect `integrate_conflict` with the user's `--keep-checkout --resolve` choice. `readGitPushHolds` counts, per source, Git effects retrying or parked on a push code with the conflict state and one fix; read by doctor `parked_effects` and `sync status` `git_push_holds` (`next` falls back to a parked or conflicted hold's fix). Pinned by `test/pathological/h2-git-effect-moved-remote.test.ts`.- `src/core/persistence/deactivation.ts` — private CLI `sources writer deactivate` (#5455/#5628), brain-wide and trusted-local. `deactivationBlockers` lists the admin lock, queued/running/recovering requests, recovering topology changes, queued, running or recovering effects (the predicate activation uses; each exit says what clears it, and a failing links or facts-backstop effect settles after five attempts), held connector items (managed holds that classic mode would not read) and live `gbrain_cycle_locks` leases, each with its CLI exit; `failedEffectHistory` lists terminally failed effects as history (`failed_effects` on the dry run and the applied report, never blockers), each with its code and the exit that retries it: retry-effects for parked targets and failed Git, withdrawal, links and facts-backstop effects, `repair embedding-effects` for a failed embedding effect, none for `embedding_zero_norm` or an effect whose source was archived, replaced or removed (`test/pathological/a15-deactivate-exits.test.ts` runs every printed exit and checks it clears its entry); `physicalRootBlockers(engine, mode)` (#5914 [R9a]) adds `physical_root` for this host's owned checkouts, probed as the mode's real run will: strict `assertPhysicalRoot` for managed, `assertPhysicalRootReservation` for the classic pre-activation release, so each preview lists exactly what its real operation refuses on; `--dry-run` returns them plus the worktrees that would retire, the kept shared-skill settings and, when clean, `apply_command` bound to the admin state read before the preview. `deactivatePersistence` takes the local native worktree locks, then in one transaction locks `persistence_brain FOR UPDATE`, checks the expected admin state and the admin lock, locks worktrees then sources `FOR UPDATE` (admission's order), rechecks the blockers, sets `enabled=false`, increments `mode_epoch`, retires every worktree, deletes source and host bindings and records a committed `writer_deactivate` topology change (brain id, retired epoch, retired worktree ids and roots, source roots). `cleanupRetiredManagedMarkers` runs on CLI connect, after deactivate and from `writer status`: it removes this brain's registry records, `.gbrain-managed` / Git `gbrain-managed.json`, `.gbrain-owner.json` and reservations only when their `mode_epoch` is a retired one below the current epoch, or, without an epoch, their worktree id (or, for markers without one, their root outside any active binding) is recorded as retired; unknown or newer epochs are kept and reported `pending`, each file is re-read before unlinking and other brains' files are never touched. `root-registry.ts` writes `mode_epoch` into new registry records and managed markers. Tests: `test/persistence-deactivate.test.ts` (PGLite and Postgres), `test/e2e/persistence-deactivate-race.test.ts`. See [persistence stalls](persistence-stalls.md).diff --git a/docs/architecture/key-files/page-history.md b/docs/architecture/key-files/page-history.mdnew file mode 100644index 0000000000..6c7dcb200d--- /dev/null+++ b/docs/architecture/key-files/page-history.md@@ -0,0 +1,7 @@+# Key files: Core Persistence (page history)++[Subsystem index](../KEY_FILES.md) · [Core Persistence](core-persistence.md). Read only the entries relevant to your change.+Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.+Page-write reasons: admission, the snapshot column, the Git trailer and the remote read projection.++- `src/core/persistence/change-reason.ts` — GBRA-217 page-write reasons ([page history](../../guides/page-history.md#reasons)). `admitChangeReason` canonicalises a `reason` (one line, at most 500 code points) and refuses `change_reason_rejected` (`reason_too_long`, `reason_contains_secret` via `scanTextSpans`) before admission, so no journal row ever holds a refused reason; `page-mutations.ts` runs it before `callerIntent`, so the canonical reason joins replay identity, and `page-batch.ts` runs it per item (all or nothing). `withChangeReason` wraps a page preparer in `service.ts`: its apply stamps `page_versions.change_reason` on the snapshots that transaction created for the page, and, for a world-visible page whose file is published, appends `gbrain-reason: <path>: <text>` to `prepared.file.commit` (a `GitCommitNote` with `trailers[]`), which both the door (`commitThroughDoor`) and the effect commit (`commitMessage`, one trailer line each, `commitMessageArgs` switching to `-F` over 8 KiB) read after apply. The outcome's `reason_recorded.git` is `committed` (strict), `queued`, `private`, `not_file_backed`, `no_repository` (repo-less) or `none`; `settledReasonRecorded` turns `queued` into `superseded` with a `reason_not_committed` notice on the receipt when the Git effect was superseded. Read side: `replacedBecauseSql` in `engine-sql/pages.ts` (remote readers see a reason only when the successor snapshot is world-visible and not `successor_pruned`, which the prunes in `page-state/versions.ts` set). Tests: `test/page-change-reason-gbra217.test.ts`, `test/page-change-reason-git-gbra217.test.ts`, `test/page-change-reason-mcp-gbra217.test.ts`.diff --git a/plugin-variants/gbrain-coding/skills/conventions/brain-first.md b/plugin-variants/gbrain-coding/skills/conventions/brain-first.mdindex c6348669cf..ba59538beb 100644--- a/plugin-variants/gbrain-coding/skills/conventions/brain-first.md+++ b/plugin-variants/gbrain-coding/skills/conventions/brain-first.md@@ -192,3 +192,12 @@ until the canonical form lands. Silent typos would be the worst outcomeWhen in doubt: declare `brain_first: exempt` explicitly OR add thecanonical Convention callout near the top of the skill body. Both arezero-friction one-line operations.++## Recording why a page changed++When you edit a policy, contract, plan or any document page, pass `reason` on+`put_page` or `edit_page` with one line on why, in the user's words where you+have them ("Client asked for the 30-day window."). Edit the existing page with+its `expected_revision`; don't create a second page for a new edition.+`get_versions` shows each version's `replaced_because`. Never put a credential+in a reason: it can be pushed in a Git commit message, and gbrain refuses it.diff --git a/plugin-variants/gbrain-daily/skills/conventions/brain-first.md b/plugin-variants/gbrain-daily/skills/conventions/brain-first.mdindex c6348669cf..ba59538beb 100644--- a/plugin-variants/gbrain-daily/skills/conventions/brain-first.md+++ b/plugin-variants/gbrain-daily/skills/conventions/brain-first.md@@ -192,3 +192,12 @@ until the canonical form lands. Silent typos would be the worst outcomeWhen in doubt: declare `brain_first: exempt` explicitly OR add thecanonical Convention callout near the top of the skill body. Both arezero-friction one-line operations.++## Recording why a page changed++When you edit a policy, contract, plan or any document page, pass `reason` on+`put_page` or `edit_page` with one line on why, in the user's words where you+have them ("Client asked for the 30-day window."). Edit the existing page with+its `expected_revision`; don't create a second page for a new edition.+`get_versions` shows each version's `replaced_because`. Never put a credential+in a reason: it can be pushed in a Git commit message, and gbrain refuses it.diff --git a/plugin/skills/conventions/brain-first.md b/plugin/skills/conventions/brain-first.mdindex c6348669cf..ba59538beb 100644--- a/plugin/skills/conventions/brain-first.md+++ b/plugin/skills/conventions/brain-first.md@@ -192,3 +192,12 @@ until the canonical form lands. Silent typos would be the worst outcomeWhen in doubt: declare `brain_first: exempt` explicitly OR add thecanonical Convention callout near the top of the skill body. Both arezero-friction one-line operations.++## Recording why a page changed++When you edit a policy, contract, plan or any document page, pass `reason` on+`put_page` or `edit_page` with one line on why, in the user's words where you+have them ("Client asked for the 30-day window."). Edit the existing page with+its `expected_revision`; don't create a second page for a new edition.+`get_versions` shows each version's `replaced_because`. Never put a credential+in a reason: it can be pushed in a Git commit message, and gbrain refuses it.diff --git a/scripts/check-core-guard-coverage.mjs b/scripts/check-core-guard-coverage.mjsindex 672ff1a33b..2c29ed7e7e 100644--- a/scripts/check-core-guard-coverage.mjs+++ b/scripts/check-core-guard-coverage.mjs@@ -34,6 +34,7 @@ const EXEMPT = {'src/core/persistence/connector-sync.ts': 'connector-owned pages; core marking is owner-written frontmatter the connector never sets','src/core/persistence/connector-google-receipts.ts': 'connector receipt rows, not page text','src/core/persistence/projection-reindex.ts': 'rebuilds derived projections; page text is unchanged',+ 'src/core/persistence/change-reason.ts': 'wraps the PreparedMutation preparePageMutation returned (service.ts) in place: the core guard, exclusiveSources and every other field are the guarded object\'s own','src/core/persistence/noop-kernel.ts': 'decides that nothing would change; publishes nothing','src/core/generations/repair.ts': 'the managed restore of a database-only generation (chronicle event pages, never core pages) revives and retires derived items through the adapter inside the coordinated request','src/core/generations/managed.ts': 'the generation activation flips the derived ledger; it writes no page text (its member page writes go through preparePageMutation)',diff --git a/scripts/check-engine-sql-dynamic.ts b/scripts/check-engine-sql-dynamic.tsindex 6aa1743180..05f94b03cc 100644--- a/scripts/check-engine-sql-dynamic.ts+++ b/scripts/check-engine-sql-dynamic.ts@@ -55,6 +55,7 @@ const VETTED_BUILDERS: Record<string, string> = {pageReadFilter: 'src/core/search/read-policy-sql.ts: binds scope values as params, splices only the caller alias',buildRecencyComponentSql: 'src/core/search/sql-ranking.ts: inlines LIKE literals + numeric coefficients from the decay map, as master (planner behavior)',privatePagesFilterFragment: 'src/core/search/private-visibility.ts: constant visibility predicate over a caller alias',+ replacedBecauseSql: 'src/core/engine-sql/pages.ts: constant GBRA-217 reason projection over a caller alias; the boolean picks one of two constant texts',quarantineFilterFragment: 'src/core/quarantine.ts: constant quarantine predicate over a caller alias',currentCodeEdgeFilter: 'src/core/code-intel/read-scope.ts: constant current-edge predicate over a caller alias',buildCJKKeywordSql: 'src/core/search/cjk-keyword-sql.ts: binds the query as params; shared by both engines',diff --git a/skills/conventions/brain-first.md b/skills/conventions/brain-first.mdindex 40ed4ad76c..ba59538beb 100644--- a/skills/conventions/brain-first.md+++ b/skills/conventions/brain-first.md@@ -201,4 +201,3 @@ have them ("Client asked for the 30-day window."). Edit the existing page withits `expected_revision`; don't create a second page for a new edition.`get_versions` shows each version's `replaced_because`. Never put a credentialin a reason: it can be pushed in a Git commit message, and gbrain refuses it.-Details: [page history](../../docs/guides/page-history.md#reasons).diff --git a/skills/skills.lock.json b/skills/skills.lock.jsonindex d6f73e4d80..1323c5646a 100644--- a/skills/skills.lock.json+++ b/skills/skills.lock.json@@ -45,7 +45,7 @@"context-audit/SKILL.md": "6d786629d40544ddaab4f4e6e333569d270bcb8b581589dc16fb9f8bcb4f6207","context-audit/routing-eval.jsonl": "fb1832e24cc1b04163a74c5cde72bca53050a66246ca902e1a5f40303f52b5ab","conventions/agent-operator-protocol.md": "b42b19223aa9dffbe783ce7c5c681d762377c740f3c609cbc555b9a60a035235",- "conventions/brain-first.md": "e0e4d7c4b760213325dffd286baf934720816a0b6aac5338538a0463e8fe77d2",+ "conventions/brain-first.md": "e57e47c57167b4053c3cddca13360b9b96a3676394f7ad240cfcf93b433803a3","conventions/brain-routing.md": "392998d9a109b330c9225af4ca5c8798b0ff02eba4d441c93fdb7c263687d0c6","conventions/calibration.md": "500dc26bd7c8400f50dc4c16fd83f1a588f3e7e68c59050a21fd8a0f69e4d198","conventions/cron-via-minions.md": "badb1cd6cd825d6f1ac0b6b28cc47e5d80facc783a3e59a14146ae901ee0f933",diff --git a/src/cli/main.ts b/src/cli/main.tsindex 5923b7bc18..33b7321614 100755--- a/src/cli/main.ts+++ b/src/cli/main.ts@@ -1773,8 +1773,7 @@ export function formatResult(const truth = v.compiled_truth ?? v.title ?? '';const head = truth.slice(0, VERSION_TRUTH_PREVIEW_CHARS);const elided = truth.length > VERSION_TRUTH_PREVIEW_CHARS ? '...' : '';- const reason = typeof v.replaced_because === 'string' ? `\n changed because: ${v.replaced_because}` : '';- return `#${v.id} ${v.snapshot_at?.toString().slice(0, 19) || '?'} ${head}${elided}${reason}`;+ return `#${v.id} ${v.snapshot_at?.toString().slice(0, 19) || '?'} ${head}${elided}${typeof v.replaced_because === 'string' ? `\n changed because: ${v.replaced_because}` : ''}`;}).join('\n') + '\n';}// MEMORY_VERBS v1 [F-E]: human-readable by default; trailing `--json`diff --git a/src/core/ops/pages.ts b/src/core/ops/pages.tsindex 58b88dfc12..e095cd694e 100644--- a/src/core/ops/pages.ts+++ b/src/core/ops/pages.ts@@ -341,8 +341,7 @@ const put_page: Operation = {allow_empty: { type: 'boolean', required: false, description: 'Allow an empty page.', fullSurfaceOnly: true },allow_shrink: { type: 'boolean', required: false, description: 'Allow content under half a >256 KB page. To add text use append_page, not a re-put; a page over one request goes by begin_page_upload.', fullSurfaceOnly: true },drop_timeline: { type: 'boolean', required: false, description: 'No Timeline in content: delete its entries.', fullSurfaceOnly: true },- wait_ms: WRITE_WAIT_PARAM,- reason: REASON_PARAM,+ wait_ms: WRITE_WAIT_PARAM, reason: REASON_PARAM,// v0.39.3.0 provenance write-through (WARN-8 + A1 + CV6). Optional fields// for trusted local callers (capture CLI, autopilot, dream cycle). Remote// MCP callers (ctx.remote !== false) have their values OVERRIDDEN with