Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(fence-repair): durable fence_repair receipts and fence commit subjects (#6188)

garrytan7950be5e0a5f
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.md
index d82622755a..af6c069e91 100644
--- a/docs/architecture/key-files/core-persistence.md
+++ b/docs/architecture/key-files/core-persistence.md
@@ -45,13 +45,13 @@ Connector ingestion, item holds and checkpoint validation continue in [Core Pers
- `src/core/persistence/page-edit.ts` — `edit_page` (#5616): splits the canonical serialization into editable text and protected takes/facts segments whose remote view matches get_page's sanitized `content` byte for byte; `applyPageEdits` applies ordered exact-once replacements inside editable text only (typed `edit_no_match`/`edit_ambiguous_match`/`edit_protected_span`/`edit_invalid`), so canonical fences never move; `editDiff` caps the caller-view diff at 8 KB. Called at submission (`page-mutations.ts`, before admission) and again on the locked snapshot in `page-prepare.ts`, which gives edit_page put_page's revision-bound `editing` timeline semantics. Pinned by `test/edit-page.test.ts`.
- `src/core/persistence/suffixed-slug.ts` — `.md`/`.mdx`-suffixed slugs (#4807). `preparePageAdmission` refuses a new put_page/put_pages slug ending in `.md`/`.mdx` before any journal row (`invalid_params`, why, suggestion naming the bare slug, read-only `get_page` fix and verify); a live page with that exact (source_id, slug) still updates and the put_page response carries `slug_advisory` (put under the bare slug, then delete_page). `suffixedSlugDryRun` serves put_page dry runs; `suffixedFrontmatterSlugHold` holds a file import whose frontmatter `slug:` identity ends in `.md` as `frontmatter_slug_conflict`. `validateSlug` and path-derived import slugs are unchanged. Test: `test/ingestion/put-page-write-through.test.ts`.
-- `src/core/persistence/{effect-schema,effect-model,effect-journal,effect-recovery,effect-git,effects}.ts` — bounded postcommit outbox (migration 155). Canonical publication atomically queues Git and embedding work; withdrawals queue three versioned, bounded exact-page manifests with durable slug cursors. `effect-targets.ts` converts legacy source scans with complete bounded discovery keyed on the request's own forgotten fact (falling back to the whole source ledger only when that fact row is gone) while retaining each cursor; ambiguous or over-capacity legacy intent stays pending. Older workers must be quiesced before rollout. Independent mirror recovery reserves capacity before file effects, finishes forward without changing revision or receipt, and blocks only its worktree until reconciled. Git holds the native root lock, disables hooks, uses literal pathspecs and target-only commits, and pushes without pull/rebase. A claimed single-file Git effect brings up to 99 more ready single-file Git effects of its worktree (`claimCoalescedGitEffects`, same readiness, recovery and withdrawal-mirror ordering predicates, `SKIP LOCKED`); the runner validates each path under the worktree lock, makes one `commit --only` per group (`commitGitTargets`: one `ls-files`, `status`, `add` and `diff` for the group; untracked absent or ignored targets take the per-target refusal path) and pushes each root once at the end of the pass (`pushGitRoot`). A group shorter than 100 yields to publications still queued or running for its worktree (`retryEffect` with `publication_pending`, 250 ms apart) for at most 20 claims, so a serial producer publishes ahead and its Git work lands as one group; the v0.13.1 grandfather step admits a 50-page window (`admitCanonicalGrandfather`) before waiting for it. A path failure fails only its effect; a push failure leaves the group queued with `git_push_unavailable`, and the next pass finds nothing to commit and pushes once (#5530; tests: `persistence-git-coalescing-5530.slow.test.ts` + Postgres wrapper). A Git effect for a declared db_only page completes as skipped (`reason: db_only`), keeping its gitignored cache file out of Git. A Git or withdrawal target parks after five consecutive execution failures (`data.target_failures` for `data.failing_target`, reset when the target advances or a different target fails; shutdown cancellation, contention, dependency waits (including recovery-capacity waits) and transient database failures do not count): a scan records it in `data.parked` and moves on, a single-target effect or a failure outside any target parks the whole effect, and an effect with parked targets finishes as `failed`/`targets_parked`, never committed. A mirror or Git scan never parks on a sync-skip metafile page (`RESOLVER.md` carries the managed durability block by design) or on a file whose bytes hold an uncoordinated local edit (`file_database_drift`): the mirror materializes the withdrawal in the database without touching the file, both scans record the page in `data.skipped` (at most 100) and advance, so the request's Git and embedding effects are no longer gated behind a parked mirror (#5396). Migration 170 indexes parked effects for the `parked_effects` doctor check. `retryParkedEffects` (the `retry-effects` admin path) previews parked targets or authorizes one more attempt per target (`data.retry_slugs`, visited before the cursor); tests: `persistence-effect-parking.test.ts`. Old targets resolve under the same hash/confinement checks without changing frozen data; ambiguous absent spellings refuse after scoped staged/unstaged deletion checks. Embedding runs outside transactions/OS locks and installs with projection CAS. Receipt helpers return only public effect state/reason/push. Consumer shutdown aborts providers and awaits workers; receipt compaction is bounded. Tests: `persistence-effects.test.ts`, `persistence-git-publication.test.ts`, `persistence-publication-native.serial.test.ts`. Embedding completion checks active column/vector, embedded stamp, text hash, model and page signature; partial work sends only stale chunks and preserves valid siblings. A partial synopsis rebuild completes before title demotion. Provider timeouts use the gateway budget, five durable page claims/backoff, execution-token CAS after provider work and atomic vector/stamp/effect completion. Keyless work skips cleanly. `retry-effects` is an explicit one-shot failed-effect allowance; current vectors reconcile provider-free without changing canonical receipts. A git refusal on an index lock (git's own message names the lock, so linked worktrees resolve) is `git_index_locked` contention (retried, not counted toward parking) while the lock is younger than 10 minutes, and `git_index_stale` (counted, naming the lock) when older or future-dated; the lock is never removed, because no timestamp proves its holder is gone.
+- `src/core/persistence/{effect-schema,effect-model,effect-journal,effect-recovery,effect-git,effects}.ts` — bounded postcommit outbox (migration 155). Canonical publication atomically queues Git and embedding work; withdrawals queue three versioned, bounded exact-page manifests with durable slug cursors. `effect-targets.ts` converts legacy source scans with complete bounded discovery keyed on the request's own forgotten fact (falling back to the whole source ledger only when that fact row is gone) while retaining each cursor; ambiguous or over-capacity legacy intent stays pending. Older workers must be quiesced before rollout. Independent mirror recovery reserves capacity before file effects, finishes forward without changing revision or receipt, and blocks only its worktree until reconciled. Git holds the native root lock, disables hooks, uses literal pathspecs and target-only commits, and pushes without pull/rebase. A claimed single-file Git effect brings up to 99 more ready single-file Git effects of its worktree (`claimCoalescedGitEffects`, same readiness, recovery and withdrawal-mirror ordering predicates, `SKIP LOCKED`); the runner validates each path under the worktree lock, makes one `commit --only` per group (`commitGitTargets`: one `ls-files`, `status`, `add` and `diff` for the group; untracked absent or ignored targets take the per-target refusal path) and pushes each root once at the end of the pass (`pushGitRoot`). A page file target's optional `commit` note (`GitCommitNote`, set only by trusted local preparers: a fence repair's `fenceRepairCommit`) is queued as `commit_subject`/`commit_line` in the Git effect's data and passed by the runner to `commitGitTargets`/`publishGitEffect`: a noted path committing alone takes its subject; a group keeps `gbrain: persist N canonical memory updates` and lists the noted paths' lines in the body, in path order; control characters are stripped, and targets without a note commit exactly as before (`test/fence-repair-receipts.test.ts`). A group shorter than 100 yields to publications still queued or running for its worktree (`retryEffect` with `publication_pending`, 250 ms apart) for at most 20 claims, so a serial producer publishes ahead and its Git work lands as one group; the v0.13.1 grandfather step admits a 50-page window (`admitCanonicalGrandfather`) before waiting for it. A path failure fails only its effect; a push failure leaves the group queued with `git_push_unavailable`, and the next pass finds nothing to commit and pushes once (#5530; tests: `persistence-git-coalescing-5530.slow.test.ts` + Postgres wrapper). A Git effect for a declared db_only page completes as skipped (`reason: db_only`), keeping its gitignored cache file out of Git. A Git or withdrawal target parks after five consecutive execution failures (`data.target_failures` for `data.failing_target`, reset when the target advances or a different target fails; shutdown cancellation, contention, dependency waits (including recovery-capacity waits) and transient database failures do not count): a scan records it in `data.parked` and moves on, a single-target effect or a failure outside any target parks the whole effect, and an effect with parked targets finishes as `failed`/`targets_parked`, never committed. A mirror or Git scan never parks on a sync-skip metafile page (`RESOLVER.md` carries the managed durability block by design) or on a file whose bytes hold an uncoordinated local edit (`file_database_drift`): the mirror materializes the withdrawal in the database without touching the file, both scans record the page in `data.skipped` (at most 100) and advance, so the request's Git and embedding effects are no longer gated behind a parked mirror (#5396). Migration 170 indexes parked effects for the `parked_effects` doctor check. `retryParkedEffects` (the `retry-effects` admin path) previews parked targets or authorizes one more attempt per target (`data.retry_slugs`, visited before the cursor); tests: `persistence-effect-parking.test.ts`. Old targets resolve under the same hash/confinement checks without changing frozen data; ambiguous absent spellings refuse after scoped staged/unstaged deletion checks. Embedding runs outside transactions/OS locks and installs with projection CAS. Receipt helpers return only public effect state/reason/push. Consumer shutdown aborts providers and awaits workers; receipt compaction is bounded. Tests: `persistence-effects.test.ts`, `persistence-git-publication.test.ts`, `persistence-publication-native.serial.test.ts`. Embedding completion checks active column/vector, embedded stamp, text hash, model and page signature; partial work sends only stale chunks and preserves valid siblings. A partial synopsis rebuild completes before title demotion. Provider timeouts use the gateway budget, five durable page claims/backoff, execution-token CAS after provider work and atomic vector/stamp/effect completion. Keyless work skips cleanly. `retry-effects` is an explicit one-shot failed-effect allowance; current vectors reconcile provider-free without changing canonical receipts. A git refusal on an index lock (git's own message names the lock, so linked worktrees resolve) is `git_index_locked` contention (retried, not counted toward parking) while the lock is younger than 10 minutes, and `git_index_stale` (counted, naming the lock) when older or future-dated; the lock is never removed, because no timestamp proves its holder is gone.
- `src/core/persistence/native-file-target.ts` — shared preparation/Git execution spelling resolution. Native directory-entry inode/device identity proves aliases; no global case folding or separator rewrite. Missing suffixes retain exact spelling, descendant symlinks and ambiguous aliases refuse, and physical root identity is rechecked. Exact POSIX case-distinct names and literal backslashes remain distinct. #5032: `isWindowsColonTarget(rel)` and `colonSlugWindowsRefusal(slug, sourceId)` name the one Windows-only refusal (`colon_slug_windows_write_through`: `:` names an NTFS alternate data stream); `submitPageMutation` raises it before admission when this host publishes the file, `prepareFileTarget` at publication, and managed (`fileRefusals`) and unmanaged (`failedFiles`) sync skip each such path by name (`test/colon-slug-windows-5032.test.ts`).
- `src/core/persistence/{ipc,local-client}.ts` — dedicated local persistence socket and engine-free CLI delegation. The narrow protocol carries a durable brain UUID, existing local writer registration, client source/cwd, and one request UUID; the production provider verifies current authority and dispatches through operations. Max frame 32 MiB (five-million-byte content even with JSON escaping), eight connections/in-flight dispatches, incomplete-frame timeout 15s. Lost responses preserve the original request ID with unknown submission state and never automatically replay or open another engine. Brain/mount routing precedes lock inspection. A lock holder that is not a serve and answers no owner socket (a concurrent CLI call) is not a resident owner: `maybeDelegateLocalOperation` returns unhandled and the engine path waits for the PGLite lock instead of answering `owner_unavailable`; a serve holder or an answering socket keeps every failure final. Owner-side `resolveSourceId(..., { skipLocalSignals: true })` prevents serve env/dotfiles from overriding client routing. For an op that owns a `source` param (`opOwnsSource`, `src/core/ops/contract.ts`), `params.source` stays on the wire as the op's own value (provenance) and routing comes from the ambient tiers, as on the direct and thin-client CLI routes (`test/cli-op-owned-source.test.ts`). The production provider dispatches the trusted `local_cli` principal's allow-listed skill-administration ops with the `'stdio'` locality marker, so the four `localOnly` ones (`get_skill_retention`, `prune_skill_revisions`, `retain_skill_revision`, `import_skill_proposal`) work while a serve owns the brain, as does `takes_remove` for the `local_cli` principal (its write scope still checked; `gbrain takes remove` defers its engine like the other takes verbs); other local calls keep no marker (`test/persistence-local-only-ops.test.ts`). `bindResolveIpcForServe` accepts the provider as its third argument and closes the dedicated listener with hook IPC. `residentPersistenceConfig` resolves a resident serve's brain the same way (`--brain`, `GBRAIN_BRAIN_ID`, `.gbrain-mount`, mount path), so the owner socket and the provider's consumer config follow a mounted brain instead of the host config (#5237); hook IPC stays keyed off the host config. Tests: `test/persistence-ipc.test.ts`, `test/persistence-local-client.test.ts`, `test/resolve-ipc-binding.test.ts`, `test/serve-mounted-owner.test.ts`. A credential-free, read-only `projection_status` request (like `capabilities`) returns the resident's projection backlog counts (`PersistenceProjectionStatus`, no identifiers) so doctor's `text_projection_readiness` can report it while the resident holds a PGLite datastore (#5401, `test/projection-resident-doctor.test.ts`).
-- `src/core/persistence/{schema,model,journal,authority,identity,ownership,coordinator,consumer,service,page-mutations,page-prepare,source-storage,control,context,digest,prepared-import}.ts` — dedicated durable mutation admission and permanent principal-scoped replay IDs, atomic quota reservations, registered canonical worktree ownership, native lock publication, conditional file recovery, and coherent receipt completion. Recovery presence blocks its whole worktree even when the receipt is terminal; admission and publication both enforce the fence. A file write is not claimed while a queued or running withdrawal mirror targets its page (any page, for an untargeted mirror), so the mirror cannot rewrite the file under an accepted request; when file bytes differ from preparation and the page revision also moved, publication reprepares (`revision_conflict`) instead of refusing as `raw_file_changed`, which stays the outcome for changed bytes at an unchanged revision (`test/withdrawal-followup-writes.test.ts`). Migration 159 adds a partial worktree/sequence recovery index so permanent receipt retention does not turn the fence into a history scan. Canonical file preparation honors a recorded source path or contained absolute capture file URI within the registered owner root (relative or host-only `file://` URIs are absent); symlink confinement and coherent snapshot checks still apply. A slug under a `storage.db_only` dir declared in `gbrain.yml` (matched case-insensitively, derive-phase defaults excluded) publishes database-only when a live page's file is absent (the case that otherwise refuses as an uncoordinated removal), with receipt `write_through.skipped: db_only`; new pages, tombstones, missing-file-tolerant callers and present cache files keep the full file treatment and never read `gbrain.yml`. `gbrain.yml` is read from the source root, like doctor, export and backup, not the git root `manageGitignore` uses, which differs for a monorepo-subdir source. `source-storage.ts` caches the parsed file per version and logs an invalid one (unreadable, overlapping tiers, db_only declared in syntax that resolves nothing) once; that missing-file refusal then reports `storage_error`, and the Git effect treats the page as not db_only. The drift guard applies the import rule for a file without an explicit `type:` (the stored type stands) and compares titles trimmed, as the parser reads them; a real drift refuses with `detail: file_database_drift` and a filled `sources reconcile` command; when sync holds the page's file (`sync-holds.ts`), the drift and occupied-path refusals name the hold instead (location-free message from `verb-errors.ts` `heldFileMessage`, mapped back by `heldFileDiagnostic` in receipts and `service.ts`) and its repair, and the page stays read-only for put_page until the file is repaired. The first write that binds an origin in a Git-subdirectory source with no slug-root pin pins the inferred mode in its publication transaction (a concurrent different pin refuses with `revision_conflict`), so later pages cannot flip the inference. A new page captured from a file inside the source (`capture_path`, resolved from the trusted CLI `local_file` in `page-mutations`, only when sync would give that file the capture slug under the source's slug-root mode) publishes to that file when its bytes are exactly the captured input; otherwise capture records `source_uri: cli-file`, never a host path. `acquireWorktree(binding, waitMs, signal, engine)` re-stamps a device-only physical-root change under the native lock (see `physical-root.ts`); without an engine, or when birth time is zero, it refuses with `detail: physical_root_device_changed` and the filled self-transfer commands. Version snapshots retain nullable `is_deleted`: new snapshots restore recorded deletion state atomically with content, tags, files and receipts; legacy NULL preserves current deletion state. Canonical no-op detection compares deletion state as well as content. Page replacement preconditions are checked before no-op detection; providers prepare outside publication transactions; recovery never restores unexpected bytes. Local registrations retain immutable CLI/stdio trust lanes and hashed credentials; accepted authority is intersected with current grants. `limits.ts` reads every `persistence.limits.*` cap and `persistence.receipt_retention_days` (default 30) from the database config table (`JOURNAL_CONFIG_KEYS`, registered for `gbrain config set`; malformed values are rejected at set time). Cumulative defaults (250,000 lifetime IDs and 1.5 GiB receipt bytes per principal, 8 GiB brain receipt bytes) cover 600 admissions a day for a year; each admission reserves at least 16 KiB and a compacted receipt keeps about 4 KiB. A cumulative `queue_capacity` refusal names its key in `detail` and suggests a `gbrain config set` value covering one more year at the recent admission rate (`oneYearCapacity`). Compaction filters out receipts with unfinished effects before its batch limit. `test/persistence-journal.test.ts` exercises real PGLite and optional guarded Postgres admission, cancellation, compaction, conflict and publication recovery; `test/persistence-capacity.test.ts` covers retention, the compaction filter, capacity hints and default sizing. `service.ts` also dispatches operation `decide_proposal` (S9 proposal accept/undo) to `facts/proposal-supersede.ts`. GOOGLE PUBLISH MODE: a page target is a `PageMutationFile` (`MutationFile` plus optional `publishMode`). The Google callers set `publishMode: 0o600` at prepare time from the stored connector (`prepareConnectorMutation` in `connector-sync.ts` when `p.connector === 'google'`, and `prepareGoogleReceiptPatch`); it is never part of the submitted intent, so request ids are unchanged. `publishFile` then creates missing directories with `mkdirPrivate(dirname(path), root)` (0700) instead of `mkdirSync` and opens the stage with `mode ?? publishMode` through `AtomicWriteOpts.mode`, so a rewrite of a legacy 0644 page lands 0600. Restoration keeps restoring the journaled before-mode and opens its stage with it (the post-flush chmod stays), so a restored private page is never staged wider than its mode.
+- `src/core/persistence/{schema,model,journal,authority,identity,ownership,coordinator,consumer,service,page-mutations,page-prepare,source-storage,control,context,digest,prepared-import}.ts` — dedicated durable mutation admission and permanent principal-scoped replay IDs, atomic quota reservations, registered canonical worktree ownership, native lock publication, conditional file recovery, and coherent receipt completion. Recovery presence blocks its whole worktree even when the receipt is terminal; admission and publication both enforce the fence. A file write is not claimed while a queued or running withdrawal mirror targets its page (any page, for an untargeted mirror), so the mirror cannot rewrite the file under an accepted request; when file bytes differ from preparation and the page revision also moved, publication reprepares (`revision_conflict`) instead of refusing as `raw_file_changed`, which stays the outcome for changed bytes at an unchanged revision (`test/withdrawal-followup-writes.test.ts`). Migration 159 adds a partial worktree/sequence recovery index so permanent receipt retention does not turn the fence into a history scan. Canonical file preparation honors a recorded source path or contained absolute capture file URI within the registered owner root (relative or host-only `file://` URIs are absent); symlink confinement and coherent snapshot checks still apply. A slug under a `storage.db_only` dir declared in `gbrain.yml` (matched case-insensitively, derive-phase defaults excluded) publishes database-only when a live page's file is absent (the case that otherwise refuses as an uncoordinated removal), with receipt `write_through.skipped: db_only`; new pages, tombstones, missing-file-tolerant callers and present cache files keep the full file treatment and never read `gbrain.yml`. `gbrain.yml` is read from the source root, like doctor, export and backup, not the git root `manageGitignore` uses, which differs for a monorepo-subdir source. `source-storage.ts` caches the parsed file per version and logs an invalid one (unreadable, overlapping tiers, db_only declared in syntax that resolves nothing) once; that missing-file refusal then reports `storage_error`, and the Git effect treats the page as not db_only. The drift guard applies the import rule for a file without an explicit `type:` (the stored type stands) and compares titles trimmed, as the parser reads them; a real drift refuses with `detail: file_database_drift` and a filled `sources reconcile` command; when sync holds the page's file (`sync-holds.ts`), the drift and occupied-path refusals name the hold instead (location-free message from `verb-errors.ts` `heldFileMessage`, mapped back by `heldFileDiagnostic` in receipts and `service.ts`) and its repair, and the page stays read-only for put_page until the file is repaired. The first write that binds an origin in a Git-subdirectory source with no slug-root pin pins the inferred mode in its publication transaction (a concurrent different pin refuses with `revision_conflict`), so later pages cannot flip the inference. A new page captured from a file inside the source (`capture_path`, resolved from the trusted CLI `local_file` in `page-mutations`, only when sync would give that file the capture slug under the source's slug-root mode) publishes to that file when its bytes are exactly the captured input; otherwise capture records `source_uri: cli-file`, never a host path. `acquireWorktree(binding, waitMs, signal, engine)` re-stamps a device-only physical-root change under the native lock (see `physical-root.ts`); without an engine, or when birth time is zero, it refuses with `detail: physical_root_device_changed` and the filled self-transfer commands. Version snapshots retain nullable `is_deleted`: new snapshots restore recorded deletion state atomically with content, tags, files and receipts; legacy NULL preserves current deletion state. Canonical no-op detection compares deletion state as well as content. Page replacement preconditions are checked before no-op detection; providers prepare outside publication transactions; recovery never restores unexpected bytes. Local registrations retain immutable CLI/stdio trust lanes and hashed credentials; accepted authority is intersected with current grants. `limits.ts` reads every `persistence.limits.*` cap and `persistence.receipt_retention_days` (default 30) from the database config table (`JOURNAL_CONFIG_KEYS`, registered for `gbrain config set`; malformed values are rejected at set time). Cumulative defaults (250,000 lifetime IDs and 1.5 GiB receipt bytes per principal, 8 GiB brain receipt bytes) cover 600 admissions a day for a year; each admission reserves at least 16 KiB and a compacted receipt keeps about 4 KiB. A cumulative `queue_capacity` refusal names its key in `detail` and suggests a `gbrain config set` value covering one more year at the recent admission rate (`oneYearCapacity`). Compaction filters out receipts with unfinished effects before its batch limit. `test/persistence-journal.test.ts` exercises real PGLite and optional guarded Postgres admission, cancellation, compaction, conflict and publication recovery; `test/persistence-capacity.test.ts` covers retention, the compaction filter, capacity hints and default sizing. `service.ts` also dispatches operation `decide_proposal` (S9 proposal accept/undo) to `facts/proposal-supersede.ts`. FENCE REPAIR RECEIPT: `fence_repair` is a reserved `put_page` param; `preparePageAdmission` refuses it (`invalid_params`) on every operation unless the call is a trusted local (`ctx.remote === false`) `put_page` whose value `parseFenceRepairReceipt` accepts; `page-prepare.ts` re-parses it from the stored intent, returns it in the outcome as `fence_repair` and gives the page's file target the `fenceRepairCommit` note for its source-relative path. GOOGLE PUBLISH MODE: a page target is a `PageMutationFile` (`MutationFile` plus optional `publishMode` and `commit`). The Google callers set `publishMode: 0o600` at prepare time from the stored connector (`prepareConnectorMutation` in `connector-sync.ts` when `p.connector === 'google'`, and `prepareGoogleReceiptPatch`); it is never part of the submitted intent, so request ids are unchanged. `publishFile` then creates missing directories with `mkdirPrivate(dirname(path), root)` (0700) instead of `mkdirSync` and opens the stage with `mode ?? publishMode` through `AtomicWriteOpts.mode`, so a rewrite of a legacy 0644 page lands 0600. Restoration keeps restoring the journaled before-mode and opens its stage with it (the post-flush chmod stays), so a restored private page is never staged wider than its mode.
- `src/core/persistence/protocol.ts` — the persistence protocol declaration and the global row-lock order: the `persistence_brain` row, then worktree rows (id order), then source rows (id order), then `persistence_counters`, request rows and page keys. The request and effect protocol triggers (`shared-skills/persistence-schema.ts`) read the brain row FOR SHARE, and worktree claims, topology changes (`lockTopologyRows`, then `settleTopologyRequests` locks the `brain` counter) and activation hold it FOR UPDATE before their worktrees, sources and counters. So `declarePersistenceProtocol` and `declareDurablePersistence` take the brain row FOR SHARE in the same statement as their settings (after `lock_timeout`, a missing row still declares), and every journal transaction declares before any other row lock: admission, publication, recovery, completion, cancellation (`control.ts`), `forget` (`memory-mutations.ts`), connector retry approval, embedding effect retry and settlement, and withdrawal-target upgrades (`effect-targets.ts`). A transaction that needs the brain row FOR UPDATE takes it first and declares after it (`skill-activation.ts`). Before this order, an ordinary write that locked its source and counters before the trigger's brain read inverted against a concurrent claim or topology change and ended in a 1 s `lock_timeout` (or a deadlock), a retry, and writes left pending. Tests: `test/e2e/persistence-publish-lock-order-postgres.test.ts` (paused topology change and a claim/topology race, direct and through PgBouncer), the crash robot's `brain_before_rows` rule (`scripts/persistence/lock-order.ts`, `test/persistence-crash-robot.test.ts`).
- `src/core/persistence/unbound-source.ts` — #5254 policy for a Postgres page write to a filesystem source (`local_path`, or `sync.repo_path` for `default`) with default write-through and no worktree binding. `submitPageMutation` refuses `owner_unavailable` with `detail: unbound_source`, a `docs` pointer to `write-refusals.md#unbound-sources-on-postgres`, and a hint naming the filled `sources writer status`/`writer claim ... --admin-intent writer_claim --expected-state <admin_state>` bind command (host path only for trusted local callers) and, for `put_page` to a page without `source_path`, `gbrain config set persistence.unbound_write database_only`. That key (`refuse` default, validated by `config set`; any other stored value refuses) lets such a `put_page` admit with `databaseOnlyReason: 'unbound_source'`. Publication rechecks inside its transaction, after `authorizeStoredRequest` share-locks the source row, that the source is still unbound and the page still has no `source_path` (else `owner_unavailable`/`unbound_source`, hint rebuilt from the persisted message by `writeResponse`), then stamps `pages.database_only_reason='unbound_source'` (migration 177). After binding, `prepareFileTarget` keeps a stamped page with no file database-only (receipt `write_through.skipped: unbound_source` with a warning) and managed sync refuses to import a file at its path (`source_changed`, diagnostic reason `unbound_source`). PGLite keeps auto-claiming. Tests: `test/e2e/unbound-source-postgres.test.ts`, `test/persistence-unbound-source.test.ts`.
diff --git a/docs/architecture/key-files/google-and-loops-continued.md b/docs/architecture/key-files/google-and-loops-continued.md
index f565e22d28..0a46b8a1f7 100644
--- a/docs/architecture/key-files/google-and-loops-continued.md
+++ b/docs/architecture/key-files/google-and-loops-continued.md
@@ -22,7 +22,7 @@
- **`src/core/persistence/sync-lanes.ts`** + **`worktree-lease.ts`** — #5984 lanes. The drain opens a lane policy for its worktree (`openLanes`, keyed by a per-drain run id that lane groups carry as `intent.lane`; `closeLaneRun` at drain end stops new lane claims and waits up to 90 s for the lane tasks still running, counted from the head's claim by `laneTask`; the drain then cancels its run's still-queued rows whose predecessor ended without committing, `cancelOrphanedLaneRows` in sync-window.ts, so a blocked drain never reports while one of its groups is still publishing, aborting or released). While it is open, this process's consumer claims the next admitted lane group head out of FIFO order (`claimNextLaneHead` in journal.ts: every earlier request claimed, any unfinished one a running request of the same run) up to the effective lane count (`laneRoots`), and runs it as a lane (`executeClaimedGroup` with `lane`). Lane publications share the worktree's native lock in this process (`acquireWorktreeShared` / `worktree-lease.ts`; one lane acquires the lock while lanes arriving meanwhile wait and join, and a lease stays registered until its lock is released); every exclusive `acquireWorktree` first yields the lease (marks it draining and wounded, waits up to its budget), and a lease drains for new claims after `LEASE_TURN_MS` of continuous holding. Lane transactions begin in manifest order (`awaitLaneBegin`) and commit in manifest order (`awaitLaneTurn`, inside the transaction before the counters: the predecessor `intent.after` must be committed; a failed one cancels the group, a requeued or unadmitted one releases it, a wounded lease or 60 s rolls it back). Publication validation accepts a lane group whose predecessor is still queued or running (`windowPredecessorAllows`). `laneFallback` in group-publish.ts cancels, releases or falls back to the single path, and a lock or statement timeout steps the lane count down (`stepDownLanes`). Lane settings (`--lanes`/`--no-lanes` > `GBRAIN_SYNC_LANES` > `sync.lanes` > 6, clamped to the pool's long-hold capacity minus 3) resolve in `resolveBulkSettings` (sync-group.ts); with lanes the drain keeps twice the lane count of groups admitted ahead (`admitAhead`).
- **`src/core/persistence/sync-run.ts`** + **`sync-authority.ts`** — one immutable request at a time, bounded fairness and pinned-target resumption. A completed discovery that finds nothing to do (`up_to_date`) stamps only `sources.last_sync_at`, inside `withCoordinatedWrite` and guarded by source id and incarnation, so a quiet managed source stays fresh in doctor and a run that outlived a re-added source stamps nothing; dry runs and partial runs do not stamp. Cursors and requests freeze `noEmbed`, `noExtract` and `noSchemaPack`. A resume adopts the stored options for every option the caller did not set explicitly (`SyncOpts.explicitProcessing`: CLI flags, wire flags, job params; autopilot and the cycle set none); an explicit conflict refuses with `detail: cursor_processing_options_conflict`, the stored options and the exact resume command. Callers that omit `explicitProcessing` stay strict. Explicit idle ordinary-source retry creates fresh discovery/admission and retains terminal receipts, also when the run has a recorded failure and its pending write already committed before the cursor advanced; company consent retry retains its approved manifest/run. Active work blocks replacement. Claimed/inactive sync, including connector/company dispatch, remains refused: existing leases and native locks do not fence already-running engine-only legacy writers. No automatic activation or new transition protocol. `freezeEntry` checks a rename's source page (id, revision, origin) as well as its target slug, and a committed rename counts in `renamed`. #5522: a new-file entry (`pageId: null`) whose origin another cursor of the source has since imported is re-frozen against that page when it is live, holds exactly that origin at the entry's slug in the cursor's incarnation, and the sync preparer finds its content unchanged; otherwise the origin refusal stands, and the manifest is never rewritten. #5751: the working-tree screen passes the kernel waivers for working-tree entries and counts them into `legacySkips` (printed by `sync-diagnostics.ts` with `gbrain repair contextual-mode`). A terminal `checkpoint_validation_timeout` receipt gets its hint from `checkpoint-validation.ts`. Content holds (#5988, `sync-screen.ts`): `freezeEntry` screens each import (company-profile cursors and `sync.holds=fail` excepted); a refused file becomes a hold written in the same transaction as the cursor step (`saveCursor`'s `inTx`), with no request admitted, and an over-bound pinned blob is held by size before it is read. A cursor whose pending request failed with a content refusal (`isContentRefusal`, old message shapes included) converts in place with its stored options: held, or re-frozen once per distinct bytes (`converted`), so a refusal the screen misses stays blocked without minting receipts. #6188: a failed fence refusal (`fenceReceiptLocation`: the durable `error_detail.fence`, the message, or an older release's message) holds the same bytes even when the screen admits them (`prepareTimeFenceHold`, reason `prepare_time`); a compacted `invalid_params` / `take_row_collision` receipt converts only when the re-screen holds. A page request of the run that fails with a fence refusal is held in the same invocation at the terminal-failure branch (single path and a bulk group's failed member) after the source's other requests settle within the run's wait budget, else the run returns `partial`; it is converted once, gets no failure-ledger row and is logged as a conversion. `sync.holds=fail` and company-profile cursors keep blocking with the typed refusal. Results carry this run's holds, the outstanding total, escalation, `converted_from_failed` and `recovered_frontmatter` (`buildHoldReport`); dry runs list `would_hold` / `screen_skipped`. After the checkpoint commits (and unless `noExtract`), the owner derives links for the source's stale pages through `links-maintenance.ts`, so a PGLite-delegated sync and a Postgres sync take the same path; the result carries `links`, and an extraction failure leaves pages stale without failing the committed sync.
- **`src/core/persistence/sync-holds.ts`** + **`sync-screen.ts`** + **`sync-blobs.ts`** — Git holds (#5988). One `op_checkpoints` row per held file (`sync-hold`, fingerprint `source:incarnation:path`) plus a per-source `sync-hold-summary` row (`count`, and `stale`: holds whose page exists); `writeGitHold` / `clearGitHold` lock the summary row and are conditional on the writing run's discovery time (`observed_at`), so an older run never replaces or clears a newer hold. Managed and legacy sync write the same rows; `readGitSourceHolds` (current incarnation only) feeds `retry-held` and legacy sync, and `readGitHoldListing` (count from the summary row, rows limited per source in SQL) feeds `sources status`, never `readAllSourceHolds`. `recordSyncConversion` logs each blocked request a managed run converted in place (`sync-conversions`, newest 20 per source, in the transaction that saves the converted cursor); `sources status` shows the newest 5. `gitHoldItem` gives every surface code, reason, key, line, location-only message, `fix` Action and `docs` anchor. #6188 `invalid_fence` holds carry `meta.fence` (reason, fence, section, rows, columns, line) and `fence_version`; the summary row counts them (`fences`), and `holdRepairSteps` is the one router (D6) every surface prints: fence holds read the page, edit the named fence and sync with `--no-pull`, other holds preview `gbrain repair frontmatter`, a mixed source names both. `holdRescreenDue` is the one re-screen predicate managed discovery and legacy sync share (retry request, database-dependent codes, an older frontmatter reader or fence screen). Policy keys: `sync.holds` (`hold`/`fail`), `sync.hold_cap` (detail shown, default 500), `sync.hold_escalate_count` (50), `sync.hold_escalate_pct` (5, from 40 screened imports), `sync.parser_regression` (`stop`/`hold`). `screenFrozenImport` admits a fence Tier 1 fixes (`fences.normalize`, read once per run only when needed; the dry run lists it in `would_normalize`), turns a refusal into a hold, or throws `sync_parser_regression` only when `sync-import-provenance` proves a validating gbrain imported the same bytes. `sync-blobs.ts` reads blob ids/sizes with chunked `ls-tree -l` and contents with `cat-file --batch`. `held-reads.ts` is the read side: `get_page.file_held`, `stale` on search/query hits and the `held_files` retrieval meta and notice, from one lookup by page id (`op_checkpoints_sync_hold_page_idx`, migration v200) and one summary read per call, cached per request; remote callers get codes and counts, never paths, and a fix addressed to the brain host operator. Tests: `test/sync-holds-store.test.ts`, `test/persistence-sync-holds.test.ts`, `test/sync-all-hold-notes.test.ts`, `test/held-read-signals.test.ts`. #5493: with multimodal embedding on, managed discovery admits image imports (deletions reconcile their pages; company plans still refuse) and `freezeEntry` holds each image import as `managed_image_sync_unsupported` (`managedImageHold`, also in the dry-run screen) before any content read or admission, whatever `sync.holds` says: the rest of the source imports and the checkpoint advances, while the image stays recorded as incomplete coverage keyed by its pinned blob (or working bytes), so a later sync re-screens it when it changes, leaves the source (or multimodal is turned off) or `sources retry-held` asks. The summary row also counts `images`; those holds are listed everywhere a hold is but never count toward `holds_escalated` or doctor `git_held_files` escalation.
-- **`src/core/persistence/file-repair.ts`** — `managed_file_repair` (#5988), the owner-internal `put_page` kind `gbrain repair frontmatter --apply` submits (accepted only from the trusted local CLI with `managedFileImport`; MCP is refused by the reserved-field gate, remote authority by the preparer). The preparer confines the path (`isWriteTargetContained` plus a component-wise `lstat` walk, no symlinks), requires the file's sha256 to equal the previewed `beforeHash` (`changed_since_preview` otherwise), recomputes `prepareRepairPublication` (the `screenSyncImport` + `importFromContent` preparation a managed sync import gets) and refuses a different result digest or a canonical overlay. It publishes the exact bytes as `file` (`expectedBeforeHash` = previewed hash; no `file_database_drift` check), applies the import (a held new file creates its page, a `renameFrom` moves the page with `updateSlug`), clears the Git hold and records `sync-import-provenance` in the same transaction; the file write queues the Git target effect. Tests: `test/repair-frontmatter.test.ts`.
+- **`src/core/persistence/file-repair.ts`** — `managed_file_repair` (#5988), the owner-internal `put_page` kind `gbrain repair frontmatter --apply` submits (accepted only from the trusted local CLI with `managedFileImport`; MCP is refused by the reserved-field gate, remote authority by the preparer). The preparer confines the path (`isWriteTargetContained` plus a component-wise `lstat` walk, no symlinks), requires the file's sha256 to equal the previewed `beforeHash` (`changed_since_preview` otherwise), recomputes `prepareRepairPublication` (the `screenSyncImport` + `importFromContent` preparation a managed sync import gets) and refuses a different result digest or a canonical overlay. It publishes the exact bytes as `file` (`expectedBeforeHash` = previewed hash; no `file_database_drift` check), applies the import (a held new file creates its page, a `renameFrom` moves the page with `updateSlug`), clears the Git hold and records `sync-import-provenance` in the same transaction; the file write queues the Git target effect. A fence repair (`gbrain repair fences`) passes its `FenceRepairReceipt` as `fenceRepair`: submission and the preparer refuse (`invalid_params`, nothing written) a receipt `parseFenceRepairReceipt` rejects or whose `before_sha256`/`after_sha256` are not the previewed and written bytes; the outcome carries it as `fence_repair`, the file target carries the commit note from `fenceRepairCommit` (`effect-model.ts`), and every refusal and fix names `gbrain repair fences --source <id>` instead of `gbrain repair frontmatter` (`FileRepairKind`, also taken by `confinedRepairTarget` and `managedRepairRoot`). Tests: `test/repair-frontmatter.test.ts`, `test/fence-repair-receipts.test.ts`.
- **`src/core/persistence/sync-prepare.ts`** — guarded raw fingerprint/revision, source root and active coordinator checks before preparation and at locked publication. Old imports/checkpoints without durable processing consent refuse under their original IDs; old deletions require their immutable origin manifest and a still-matching page origin. `noEmbed` suppresses the effect itself; `noSchemaPack` bypasses pack loading; optional extraction stays disabled, but mandatory provider-free canonical projections remain. A filename-derived slug mismatch is accepted on every platform only when the page's stored canonical path is this file and the parsed slug is that page's slug; a different declared slug still refuses. CRLF equivalence never weakens raw CAS. No uncoordinated filesystem writes. The checkpoint validates receipts through `checkpoint-validation.ts` and, for a run whose entries another cursor imported (`overtaken`, #5522), also commits when that cursor already checkpointed the same target. Markdown imports pass `screenSyncImport` (the already-published working-tree exemption, then `screenImportContent` with the expected slug and recorded-origin exemption), the same screen the freeze-time hold screen runs, so a file is held exactly when publication would refuse it. Each import, deletion and no-op apply clears the path's Git hold (`holdObservedAt`), the checkpoint clears `releasedHolds` and ignores `supersededRequests` (failed content refusals the run converted in place), and every Markdown import records `sync-import-provenance` (raw sha256, blob, gbrain version, quoting recoveries) and reports `recovered_frontmatter` / `comment_value` in its outcome. Tests: `persistence-sync-origin-native.serial.test.ts`, `persistence-sync-options.serial.test.ts`, `persistence-sync-company.serial.test.ts`. A same-slug `renameFrom` accepts the page's recorded old origin. A different-slug rename prepares against the page where it stands, locks the old slug as an additional page key, and at publication moves the page with `updateSlug` (same id, inbound links and history, `old -> new` in `slug_aliases`, withdrawn claims follow), re-infers an implicit type from the new path, then re-prepares and applies the file content at the new slug, so the move never writes back to the file. Tests: `persistence-managed-lifecycle.test.ts`.
- **`src/core/persistence/links-maintenance.ts`** — `extractManagedStaleLinks` (then the mention pass unless `mentions: false`, which sync passes) derives links for pages whose extraction watermark is stale with `prepareAutomaticLinks` (put_page's replace contract; other producers' edges stay) and adds the coordinator's unrecorded canonical timeline tuples (insert-only) and each page's watermark in the same `withCoordinatedWrite` transaction, bound to the revision it read; an edited page or unresolved attendance stays stale. A page skipped for unresolved attendance is marked attendance-blocked at that revision (`pages.links_attendance_blocked_revision` / `_at`, written by `markPagesAttendanceBlocked` in `engine-sql/pages.ts` only while the revision still matches, cleared by `markPagesExtractedBatch` with the watermark); it is still reconsidered every run, and the `links_extraction_lag` doctor check counts it apart from lag while the marker equals the page's current revision. It is the one managed extraction path: managed sync, `extractStaleFromDB` on a managed brain, and the owner delegation all run it. `runManagedStaleExtraction` backs `gbrain extract --stale` on managed brains, locally or through the `writer_extract_stale` administration operation inside a PGLite owner (`src/commands/extract-stale-delegate.ts`, trusted CLI registration only). `links-preparation.ts` retargets a link written against a renamed page's old slug to the live canonical page through `slug_aliases`, as `get_page` does. Tests: `persistence-managed-lifecycle.test.ts`, `persistence-sync-stdio-owner.serial.test.ts`.
- **`src/core/persistence/sync-authority.ts`** — trusted CLI or original remote generic job authority; rejects stdio bulk privilege promotion and runtime option expansion, intersects original grants with current principal/source policy.
diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.ts
index cf7bd9ac16..bdee7fb9ad 100644
--- a/src/core/persistence/coordinator.ts
+++ b/src/core/persistence/coordinator.ts
@@ -23,6 +23,7 @@ import { withFilesystemPublication } from './filesystem-guard.ts';
import { mayReprepare } from './semantic.ts';
import { tryAcquirePublicationCapacity } from './pool-capacity.ts';
import { queuePublicationEffects } from './effect-journal.ts';
+import type { GitCommitNote } from './effect-model.ts';
import { authorizePageVisibility } from './page-visibility.ts';
import { withNoRepoWriteThroughWarning } from '../write-through.ts';
import { assertUnboundPublication, classifyUnboundPage, unboundWriteWarning } from './unbound-source.ts';
@@ -62,8 +63,11 @@ interface PreparedMutationBase {
postimage?: PageSnapshot | null;
validate?(tx: BrainEngine): Promise<void>;
}
-/** A page file target; `publishMode` (Google pages) is the exact mode it publishes with, and its created directories get 0700. */
-export type PageMutationFile = MutationFile & { publishMode?: number };
+/**
+ * A page file target; `publishMode` (Google pages) is the exact mode it publishes with, and its created directories get 0700.
+ * `commit` (trusted local preparers only) rides the Git effect into the commit message.
+ */
+export type PageMutationFile = MutationFile & { publishMode?: number; commit?: GitCommitNote };
export type PreparedMutation = PreparedMutationBase & (
| { target?: 'page'; file?: PageMutationFile; files?: never }
| { target: 'skill_bundle'; file?: never; files: MutationFile[]; validate(tx: BrainEngine): Promise<void> }
diff --git a/src/core/persistence/effect-git.ts b/src/core/persistence/effect-git.ts
index 373d559947..b33aa9e1f2 100644
--- a/src/core/persistence/effect-git.ts
+++ b/src/core/persistence/effect-git.ts
@@ -3,6 +3,7 @@ import { basename, dirname, join, relative, resolve as resolvePath, sep } from '
import { execFileBounded, isDurabilityHardenedAsync } from '../brain-repo-durability.ts';
import { OperationError, opError } from '../ops/contract.ts';
import { readFix } from '../ops/op-fix.ts';
+import type { GitCommitNote } from './effect-model.ts';
import { persistenceHome } from './identity.ts';
import { nativeFileTarget } from './native-file-target.ts';
@@ -124,13 +125,21 @@ function withHooks<T>(run: (hooks: string) => Promise<T>): Promise<T> {
return run(hooks).finally(() => rmSync(hooks, { recursive: true, force: true }));
}
+const commitText = (text: string) => text.replace(/[\u0000-\u001f\u007f]/g, '');
+
/**
* #5530: commit a group of single-file targets with one `commit --only`. The
* caller owns the native worktree lock and has probed durability. Each
* target's outcome (or its own error) is keyed by its requested relative
* path; a failing target never enters the commit. Nothing is pushed.
+ *
+ * `notes` (keyed by requested path) carry a preparer's commit metadata: a
+ * path that commits alone with a note uses its subject; a group keeps the
+ * generic subject and lists the noted paths' lines in the body, in path
+ * order. Control characters are stripped from both.
*/
-export async function commitGitTargets(root: string, relativePaths: string[], signal?: AbortSignal): Promise<Map<string, GitOutcome | OperationError>> {
+export async function commitGitTargets(root: string, relativePaths: string[], signal?: AbortSignal,
+ notes?: ReadonlyMap<string, GitCommitNote>): Promise<Map<string, GitOutcome | OperationError>> {
const results = new Map<string, GitOutcome | OperationError>();
await withHooks(async hooks => {
// One ls-files, one status, one add and one diff for the group; targets
@@ -178,8 +187,12 @@ export async function commitGitTargets(root: string, relativePaths: string[], si
// --only keeps unrelated staged paths out of this commit. After a lost
// database acknowledgment the same HEAD/file state is an exact no-op.
const commitPaths = [...new Set(changed.map(c => c.path))];
- const message = commitPaths.length === 1 ? 'gbrain: persist canonical memory update' : `gbrain: persist ${commitPaths.length} canonical memory updates`;
- const result = await git(root, hooks, ['commit', '--only', '-m', message, '--', ...commitPaths], signal);
+ const noted = new Map<string, GitCommitNote>();
+ for (const c of changed) { const note = notes?.get(c.requested); if (note && !noted.has(c.path)) noted.set(c.path, note); }
+ const subject = commitPaths.length > 1 ? `gbrain: persist ${commitPaths.length} canonical memory updates`
+ : commitText(noted.get(commitPaths[0]!)?.subject ?? '') || 'gbrain: persist canonical memory update';
+ const body = commitPaths.length > 1 ? [...new Set([...noted.keys()].sort().map(path => commitText(noted.get(path)!.line)).filter(Boolean))] : [];
+ const result = await git(root, hooks, ['commit', '--only', '-m', subject, ...(body.length ? ['-m', body.join('\n')] : []), '--', ...commitPaths], signal);
const outcome = result.code === 0 ? { git: 'committed' } : gitFailure('Cannot commit the canonical Git target.',
`git commit failed for ${commitPaths.length} file(s); a missing Git identity (user.name, user.email) in that checkout is one cause to check.`);
for (const c of changed) results.set(c.requested, outcome);
@@ -209,9 +222,9 @@ export async function pushGitRoot(root: string, signal?: AbortSignal): Promise<{
* the worktree.
*/
export async function publishGitEffect(root: string, relativePath: string, signal?: AbortSignal,
- hardened?: boolean): Promise<Record<string, unknown>> {
+ hardened?: boolean, note?: GitCommitNote): Promise<Record<string, unknown>> {
if (!(hardened ?? await isDurabilityHardenedAsync(root))) return { git: 'skipped', reason: 'durability_not_enabled', push: 'skipped' };
- const outcome = (await commitGitTargets(root, [relativePath], signal)).get(relativePath)!;
+ const outcome = (await commitGitTargets(root, [relativePath], signal, note ? new Map([[relativePath, note]]) : undefined)).get(relativePath)!;
if (outcome instanceof OperationError) throw outcome;
if (outcome.reason === 'target_absent') return outcome;
const pushed = await pushGitRoot(root, signal);
diff --git a/src/core/persistence/effect-journal.ts b/src/core/persistence/effect-journal.ts
index 3b6c8cb537..d2808a89d4 100644
--- a/src/core/persistence/effect-journal.ts
+++ b/src/core/persistence/effect-journal.ts
@@ -39,8 +39,10 @@ export async function queuePublicationEffects(tx: BrainEngine, row: EffectReques
if (!binding?.local_path) throw opError('owner_unavailable', 'Cannot record the canonical Git target without its owner binding.',
`Worktree ${row.worktree_id} of source ${row.source_id} has no host binding for its owner, so request ${row.id} could not record its Git target. Read the request's receipt; the owner host's binding is restored by its claim or transfer.`,
row.principal_kind === 'local_cli' ? { fix: readFix(`Reads request ${row.id}'s durable receipt, read-only.`, { argv: ['gbrain', 'write-request', '--', row.id] }) } : {});
+ const commit = prepared.file.commit;
queue('git', { relative_path: relative(binding.local_path, prepared.file.path).split(sep).join('/'),
- expected_hash: prepared.file.content === null ? null : sha256(prepared.file.content) });
+ expected_hash: prepared.file.content === null ? null : sha256(prepared.file.content),
+ ...(commit ? { commit_subject: commit.subject, commit_line: commit.line } : {}) });
if (outcome.persistence && typeof outcome.persistence === 'object') Object.assign(outcome.persistence, { git_state: 'queued' });
}
if (snapshot && !snapshot.page.deleted_at) {
diff --git a/src/core/persistence/effect-model.ts b/src/core/persistence/effect-model.ts
index 2c855c9185..29d454ca63 100644
--- a/src/core/persistence/effect-model.ts
+++ b/src/core/persistence/effect-model.ts
@@ -1,5 +1,6 @@
import type { WriteRequest } from './model.ts';
import type { WithdrawalTarget } from '../facts/withdrawal-discovery.ts';
+import { fenceRepairCommitSubject } from '../fence-repair/receipt.ts';
export type EffectKind = 'git' | 'embedding' | 'withdrawal-mirror' | 'facts-backstop' | 'links';
/** Brain config key gating the remote mention-links effect; unset is on, false/0/no/off turns it off. */
@@ -8,6 +9,16 @@ export const REMOTE_AUTO_LINKS_KEY = 'mcp.remote_auto_links';
export const REMOTE_MENTION_LINK_SOURCE = 'mcp-remote-mention';
/** Operations whose remote publications queue a `links` effect. */
export const REMOTE_MENTION_OPERATIONS: readonly string[] = ['put_page', 'capture', 'edit_page'];
+/**
+ * Commit metadata a trusted local preparer attaches to a page file target
+ * (a fence repair): the subject when the file commits alone, and its body
+ * line when it commits with other files. Location only, never page text.
+ */
+export interface GitCommitNote { subject: string; line: string }
+/** A fence-repaired file's note: `fenceRepairCommitSubject` alone, `<path> (<classes>)` as its line in a batched commit. */
+export function fenceRepairCommit(path: string, classes: readonly string[]): GitCommitNote {
+ return { subject: fenceRepairCommitSubject(path, classes), line: `${path.replace(/[\u0000-\u001f\u007f]/g, '?')} (${classes.join(', ')})` };
+}
export interface ParkedTarget { slug?: string; error_code: string }
export interface SkippedTarget { slug: string; reason: 'metafile' | 'file_database_drift' }
/** A Git or withdrawal target parks after this many consecutive execution failures. */
@@ -37,6 +48,9 @@ export interface PersistenceEffect {
source_incarnation: string;
worktree_id: string | null;
data: { version?: 2; targets?: WithdrawalTarget[]; slug?: string; page_id?: number; relative_path?: string; expected_hash?: string | null; after_slug?: string; source_id?: string; source_scan?: boolean; visibility?: 'private' | 'world'; embedding_attempt_base?: number; embedding_retry_base?: number;
+ /** A single-file Git target's GitCommitNote, when its preparer gave one. */
+ commit_subject?: string;
+ commit_line?: string;
/** Consecutive execution failures of the current Git or withdrawal target. */
target_failures?: number;
/** The target `target_failures` belongs to; a different target starts from zero. */
diff --git a/src/core/persistence/effects.ts b/src/core/persistence/effects.ts
index 2db352d2e4..cb98bf8298 100644
--- a/src/core/persistence/effects.ts
+++ b/src/core/persistence/effects.ts
@@ -34,7 +34,7 @@ import { commitGitTargets, publishGitEffect, pushGitRoot } from './effect-git.ts
import { isDurabilityHardenedAsync } from '../brain-repo-durability.ts';
import { dispatchFactsBackstopEffect } from './effect-facts.ts';
import { runLinksEffect } from './effect-links.ts';
-import { PARK_AFTER_FAILURES, type EffectRecovery, type PersistenceEffect, type SkippedTarget } from './effect-model.ts';
+import { PARK_AFTER_FAILURES, type EffectRecovery, type GitCommitNote, type PersistenceEffect, type SkippedTarget } from './effect-model.ts';
import { SYNC_SKIP_FILES } from '../sync.ts';
import { recoveryStagingFile } from './staging.ts';
import { selectEffectRecoveries } from './effect-recovery-scan.ts';
@@ -208,6 +208,12 @@ async function singleFileGitTarget(engine: BrainEngine, effect: PersistenceEffec
return relative(binding.local_path, path).split(sep).join('/');
}
+/** The commit metadata a single-file Git effect's preparer recorded, if any. */
+function gitCommitNote(effect: PersistenceEffect): GitCommitNote | undefined {
+ const { commit_subject: subject, commit_line: line } = effect.data;
+ return typeof subject === 'string' && typeof line === 'string' ? { subject, line } : undefined;
+}
+
async function gitPage(engine: BrainEngine, effect: PersistenceEffect, binding: WorktreeBinding | null, opts: EffectWorkerOptions,
attempt: EffectAttempt, hardened: boolean | undefined): Promise<void> {
if (!binding?.local_path) { await completeEffect(engine, effect, { git: 'skipped', reason: 'no_repo_configured' }); return; }
@@ -216,7 +222,7 @@ async function gitPage(engine: BrainEngine, effect: PersistenceEffect, binding:
const root = binding.local_path;
if (!targetedWithdrawalEffect(effect) && !effect.data.source_scan) {
const target = await singleFileGitTarget(engine, effect, { ...binding, local_path: root }, attempt);
- if (target !== null) await completeEffect(engine, effect, await publishGitEffect(root, target, opts.signal, hardened));
+ if (target !== null) await completeEffect(engine, effect, await publishGitEffect(root, target, opts.signal, hardened, gitCommitNote(effect)));
return;
}
// Only a page walk reads snapshots; a single-file effect completes by its recorded hash.
@@ -578,7 +584,8 @@ export async function runPersistenceEffects(engine: BrainEngine, config: GBrainC
if (path !== null) targets.push({ effect, path, attempt });
} catch (error) { await recordFailure(engine, effect, error, opts.signal, attempt.target); }
}
- const outcomes = targets.length ? await commitGitTargets(binding.local_path, targets.map(t => t.path), opts.signal) : new Map();
+ const notes = new Map(targets.flatMap(({ effect, path }) => { const note = gitCommitNote(effect); return note ? [[path, note] as const] : []; }));
+ const outcomes = targets.length ? await commitGitTargets(binding.local_path, targets.map(t => t.path), opts.signal, notes) : new Map();
const pending = unpushed.get(binding.local_path) ?? { binding, items: [] };
for (const { effect, path, attempt } of targets) {
const outcome = outcomes.get(path)!;
diff --git a/src/core/persistence/file-repair.ts b/src/core/persistence/file-repair.ts
index 25fb2b3e37..c4c150fbee 100644
--- a/src/core/persistence/file-repair.ts
+++ b/src/core/persistence/file-repair.ts
@@ -19,6 +19,13 @@
* canonical overlay (retained tags, a withdrawal, sanitization) is refused,
* never written with the overlay bypassed.
*
+ * A fence repair (`gbrain repair fences`) carries its `FenceRepairReceipt` in
+ * the intent (`fenceRepair`): the preparer refuses a malformed receipt or one
+ * whose before/after sha256 are not the previewed and the written bytes, the
+ * receipt rides the publication outcome as `fence_repair`, the file's Git
+ * commit takes `fenceRepairCommitSubject`, and every refusal routes to
+ * `gbrain repair fences` instead of `gbrain repair frontmatter`.
+ *
* Trusted local CLI only: admission refuses remote and delegated callers, the
* `put_page` reserved-field gate refuses the kind from MCP, and the preparer
* refuses any request whose authority is remote. Every path is confined to
@@ -43,6 +50,7 @@ import { assertPageRevision, type PageSnapshot } from '../page-state/types.ts';
import { sealPageTextProjection } from '../page-state/projections.ts';
import { currentSubmissionAuthority } from '../minions/submission-authority.ts';
import { VERSION } from '../../version.ts';
+import { parseFenceRepairReceipt, type FenceRepairReceipt } from '../fence-repair/receipt.ts';
import { prepareCanonicalProjections } from './canonical-projections.ts';
import { digest, sha256 } from './digest.ts';
import { currentVerifiedLocalWriter, localHostId } from './identity.ts';
@@ -53,6 +61,7 @@ import { screenSyncImport } from './sync-prepare.ts';
import type { SyncRename } from './sync-discovery.ts';
import type { PreparedContentImport } from './prepared-import.ts';
import type { PreparedMutation } from './coordinator.ts';
+import { fenceRepairCommit } from './effect-model.ts';
import type { WriteRequest } from './model.ts';
export interface ManagedFileRepairIntent extends Record<string, unknown> {
@@ -73,17 +82,40 @@ export interface ManagedFileRepairIntent extends Record<string, unknown> {
/** A held renamed file: the page it moves, bound to the revision the preview read. */
renameFrom?: SyncRename;
noEmbed: boolean;
+ /** A fence repair's receipt (location and hashes only). */
+ fenceRepair?: FenceRepairReceipt;
}
+/** The repair command a refusal names (D6 router): a fence repair's, or the frontmatter repair's. */
+export type FileRepairKind = 'frontmatter' | 'fences';
+
const ownerStatusFix = (sourceId: string): Action => readFix(`Shows source ${sourceId}'s canonical owner and its state, read-only.`,
{ argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'] });
-const previewFix = (sourceId: string): Action => ({ argv: ['gbrain', 'repair', 'frontmatter', '--source', sourceId], consent: [], actor: 'agent',
- requires_exclusive: false, why: `Previews the frontmatter repair of source ${sourceId} again from the files as they are now; nothing is written.` });
+const previewFix = (sourceId: string, kind: FileRepairKind): Action => ({ argv: ['gbrain', 'repair', kind, '--source', sourceId], consent: [], actor: 'agent',
+ requires_exclusive: false, why: `Previews the ${kind === 'fences' ? 'fence' : 'frontmatter'} repair of source ${sourceId} again from the files as they are now; nothing is written.` });
-function changedSincePreview(sourceId: string, path: string, why: string) {
+function changedSincePreview(sourceId: string, path: string, why: string, kind: FileRepairKind) {
return opError('changed_since_preview', `${path} changed since its repair was previewed: ${why}.`,
- `Nothing was written for ${path}. Preview again with gbrain repair frontmatter --source ${sourceId}, review the new proposal, and approve its new hash.`,
- { fix: previewFix(sourceId) });
+ `Nothing was written for ${path}. Preview again with gbrain repair ${kind} --source ${sourceId}, review the new proposal, and approve its new hash.`,
+ { fix: previewFix(sourceId, kind) });
+}
+
+/**
+ * The well-formed fence repair receipt of a repair request, or undefined for
+ * a frontmatter repair. Refuses (`invalid_params`, nothing written) a
+ * malformed receipt or one whose hashes are not the previewed bytes
+ * (`beforeHash`) and the bytes it writes (`content`).
+ */
+function checkedFenceRepair(input: { fenceRepair?: unknown; beforeHash: string; content: string; path: string }, sourceId: string): FenceRepairReceipt | undefined {
+ if (input.fenceRepair === undefined) return undefined;
+ const refuse = (why: string): never => { throw opError('invalid_params', `The fence repair receipt for ${input.path} ${why}, so nothing was written.`,
+ `gbrain repair fences builds this receipt from the bytes it previewed and writes; this one does not describe them. Preview again with gbrain repair fences --source ${sourceId} and apply its new plan; if the apply refuses the same way, tell the user and include gbrain doctor --json.`,
+ { fix: previewFix(sourceId, 'fences') }); };
+ const receipt = parseFenceRepairReceipt(input.fenceRepair);
+ if (!receipt) return refuse('is malformed');
+ if (receipt.before_sha256 !== input.beforeHash) return refuse('does not name the previewed file bytes');
+ if (receipt.after_sha256 !== sha256(Buffer.from(input.content, 'utf8'))) return refuse('does not name the repaired file bytes');
+ return receipt;
}
/**
@@ -91,9 +123,9 @@ function changedSincePreview(sourceId: string, path: string, why: string) {
* or climbing path, a target outside the root, and any symlink on the way
* (each component below the root is `lstat`ed); the target must be a file.
*/
-export function confinedRepairTarget(root: string, path: string, sourceId: string): string {
+export function confinedRepairTarget(root: string, path: string, sourceId: string, kind: FileRepairKind = 'frontmatter'): string {
const refuse = (why: string): never => { throw opError('source_changed', `The repair target ${JSON.stringify(path)} ${why}, so nothing was written.`,
- `gbrain repair frontmatter writes only regular files inside source ${sourceId}'s root, never through a symlink. Replace the link with the real file (or leave it out), then preview again.`,
+ `gbrain repair ${kind} writes only regular files inside source ${sourceId}'s root, never through a symlink. Replace the link with the real file (or leave it out), then preview again.`,
{ fix: ownerStatusFix(sourceId) }); };
if (!path || path.includes('\0') || isAbsolute(path) || path.split(/[\\/]/).some(part => part === '..' || part === '')) refuse('is not a confined source-relative path');
const target = resolve(root, path);
@@ -181,11 +213,11 @@ function assertTrustedRepairCaller(ctx: Pick<OperationContext, 'remote'>): void
}
/** The active local owner's canonical root of a source, or a refusal naming writer status. */
-export async function managedRepairRoot(engine: BrainEngine, sourceId: string): Promise<{ root: string; ownerEpoch: string }> {
+export async function managedRepairRoot(engine: BrainEngine, sourceId: string, kind: FileRepairKind = 'frontmatter'): Promise<{ root: string; ownerEpoch: string }> {
const binding = await getWorktreeBinding(engine, sourceId);
if (!binding?.local_path || binding.owner_host_id !== localHostId() || binding.state !== 'active') {
throw opError('owner_unavailable', 'A managed file repair must run on the active canonical owner of its source.',
- `This host is not the active owner of source ${sourceId}, so nothing was written. Run gbrain repair frontmatter on the owner host that writer status names, or wait until its owner is active.`,
+ `This host is not the active owner of source ${sourceId}, so nothing was written. Run gbrain repair ${kind} on the owner host that writer status names, or wait until its owner is active.`,
{ fix: ownerStatusFix(sourceId) });
}
return { root: join(binding.local_path, binding.relative_path), ownerEpoch: String(binding.owner_epoch) };
@@ -199,13 +231,17 @@ export async function managedRepairRoot(engine: BrainEngine, sourceId: string):
export interface ManagedFileRepairInput {
sourceId: string; requestId: string; slug: string; path: string; sourcePath: string; content: string;
beforeHash: string; resultDigest: string; expected_revision?: string; renameFrom?: SyncRename; noEmbed: boolean;
+ /** Set by `gbrain repair fences`: the write's receipt, and its refusals route there. */
+ fenceRepair?: FenceRepairReceipt;
}
export async function submitManagedFileRepair(ctx: OperationContext, input: ManagedFileRepairInput): Promise<Record<string, unknown>> {
assertTrustedRepairCaller(ctx);
- const { root, ownerEpoch } = await managedRepairRoot(ctx.engine, input.sourceId);
- const target = confinedRepairTarget(root, input.path, input.sourceId);
- if (fileSha256(target) !== input.beforeHash) throw changedSincePreview(input.sourceId, input.path, 'the file bytes differ from the previewed hash');
+ const kind: FileRepairKind = input.fenceRepair !== undefined ? 'fences' : 'frontmatter';
+ checkedFenceRepair(input, input.sourceId);
+ const { root, ownerEpoch } = await managedRepairRoot(ctx.engine, input.sourceId, kind);
+ const target = confinedRepairTarget(root, input.path, input.sourceId, kind);
+ if (fileSha256(target) !== input.beforeHash) throw changedSincePreview(input.sourceId, input.path, 'the file bytes differ from the previewed hash', kind);
const { sourceId, requestId, expected_revision, ...rest } = input;
const params: Record<string, unknown> = { ...rest, kind: 'managed_file_repair', ownerEpoch, source_id: sourceId, request_id: requestId,
...(expected_revision ? { expected_revision } : {}) };
@@ -214,13 +250,15 @@ export async function submitManagedFileRepair(ctx: OperationContext, input: Mana
export async function prepareManagedFileRepairMutation(engine: BrainEngine, row: WriteRequest, _config: GBrainConfig): Promise<PreparedMutation> {
const p = row.intent as ManagedFileRepairIntent | null;
+ const kind: FileRepairKind = p?.fenceRepair !== undefined ? 'fences' : 'frontmatter';
if (row.authority.remote || row.principal_kind !== 'local_cli') throw trustedCliRequired('A managed file repair requires a trusted local CLI writer.');
if (!p || p.kind !== 'managed_file_repair' || typeof p.content !== 'string' || typeof p.path !== 'string' || typeof p.sourcePath !== 'string'
|| typeof p.beforeHash !== 'string' || typeof p.resultDigest !== 'string') {
throw opError('invalid_params', 'The durable file repair intent is incomplete.',
- `Repair request ${row.request_id} in source ${row.source_id} has no complete intent, so it published nothing. Preview the repair again: gbrain repair frontmatter --source ${row.source_id}.`,
- { fix: previewFix(row.source_id) });
+ `Repair request ${row.request_id} in source ${row.source_id} has no complete intent, so it published nothing. Preview the repair again: gbrain repair ${kind} --source ${row.source_id}.`,
+ { fix: previewFix(row.source_id, kind) });
}
+ const fenceRepair = checkedFenceRepair(p, row.source_id);
const binding = await getWorktreeBinding(engine, row.source_id);
if (!row.worktree_id || !binding?.local_path || String(binding.owner_epoch) !== p.ownerEpoch) throw opError('owner_unavailable', 'A managed file repair requires its accepted canonical owner.',
`Source ${row.source_id}'s canonical owner changed or went away after repair request ${row.request_id} was accepted, so it published nothing. Check the owner, then preview the repair again on the host that owns the source.`,
@@ -229,8 +267,8 @@ export async function prepareManagedFileRepairMutation(engine: BrainEngine, row:
const bytes = Buffer.from(p.content, 'utf8');
const fileChanges = sha256(bytes) !== p.beforeHash;
const checkFile = () => {
- const target = confinedRepairTarget(root, p.path, row.source_id);
- if (fileSha256(target) !== p.beforeHash) throw changedSincePreview(row.source_id, p.path, 'the file bytes differ from the previewed hash');
+ const target = confinedRepairTarget(root, p.path, row.source_id, kind);
+ if (fileSha256(target) !== p.beforeHash) throw changedSincePreview(row.source_id, p.path, 'the file bytes differ from the previewed hash', kind);
return target;
};
const target = checkFile();
@@ -240,14 +278,14 @@ export async function prepareManagedFileRepairMutation(engine: BrainEngine, row:
if ((snapshot?.page.id ?? null) !== row.page_id || (snapshot?.page.source_path != null && snapshot.page.source_path !== p.sourcePath)) {
throw opError('page_identity_changed', 'The repaired path no longer names the previewed page.',
`Page ${row.slug} in source ${row.source_id} was replaced, removed, or now maps to a different file than ${p.sourcePath}, so repair request ${row.request_id} published nothing. Preview the repair again.`,
- { fix: previewFix(row.source_id) });
+ { fix: previewFix(row.source_id, kind) });
}
const moved = p.renameFrom && p.renameFrom.slug !== row.slug ? p.renameFrom : undefined;
const assertRenameSource = async (tx: BrainEngine) => {
if (!moved) return null;
const previous = await tx.readPageSnapshot(moved.slug, { ...source, includeDeleted: true });
if (previous?.page.id !== moved.pageId || previous.revision !== moved.revision || previous.page.deleted_at != null) {
- throw changedSincePreview(row.source_id, p.path, `page ${moved.slug}, which it was renamed from, changed or was deleted`);
+ throw changedSincePreview(row.source_id, p.path, `page ${moved.slug}, which it was renamed from, changed or was deleted`, kind);
}
return previous;
};
@@ -255,16 +293,16 @@ export async function prepareManagedFileRepairMutation(engine: BrainEngine, row:
const screenConfig = await repairScreenConfig(engine, row.source_id);
const publication = await prepareRepairPublication(engine, { sourceId: row.source_id, slug: row.slug, sourcePath: p.sourcePath, path: p.path, root,
content: p.content, snapshot, base, ...screenConfig });
- if (publication.status === 'refused') throw changedSincePreview(row.source_id, p.path, `the repaired content now refuses to import (${publication.refusal.code})`);
- if (publication.status === 'overlay') throw changedSincePreview(row.source_id, p.path, 'importing it would now store a canonical overlay instead of the file as written');
- if (publication.digest !== p.resultDigest) throw changedSincePreview(row.source_id, p.path, 'the page it would publish differs from the previewed result');
+ if (publication.status === 'refused') throw changedSincePreview(row.source_id, p.path, `the repaired content now refuses to import (${publication.refusal.code})`, kind);
+ if (publication.status === 'overlay') throw changedSincePreview(row.source_id, p.path, 'importing it would now store a canonical overlay instead of the file as written', kind);
+ if (publication.digest !== p.resultDigest) throw changedSincePreview(row.source_id, p.path, 'the page it would publish differs from the previewed result', kind);
const ready = publication.ready;
const project = await prepareCanonicalProjections(engine, ready.parsedPage, row.slug, row.source_id, base, 'file');
const importContent = p.content.replace(/^\uFEFF/, '');
const importOptions = { ...source, noEmbed: true, remote: false, activePack: screenConfig.activePack, filename: basename(p.sourcePath).replace(/\.mdx?$/i, ''), sourcePath: p.sourcePath, allowEmptyOverwrite: true };
return { observedRevision: snapshot?.revision ?? null, noop: ready.noop && !fileChanges && !moved, contentUnchanged: ready.noop && !fileChanges && !moved,
deferEmbedding: p.noEmbed, ...(moved ? { additionalPageKeys: [{ sourceId: row.source_id, slug: moved.slug }] } : {}),
- ...(fileChanges ? { file: { root, path: target, content: bytes, expectedBeforeHash: p.beforeHash } } : {}),
+ ...(fileChanges ? { file: { root, path: target, content: bytes, expectedBeforeHash: p.beforeHash, ...(fenceRepair ? { commit: fenceRepairCommit(p.path, fenceRepair.classes) } : {}) } } : {}),
validate: async tx => {
const current = await getWorktreeBinding(tx, row.source_id);
if (!current || current.worktree_id !== row.worktree_id || String(current.owner_epoch) !== p.ownerEpoch) throw opError('owner_unavailable', 'The repair owner changed.',
@@ -277,11 +315,11 @@ export async function prepareManagedFileRepairMutation(engine: BrainEngine, row:
apply: async tx => {
let applied = ready;
if (moved) {
- if (await tx.updateSlug(moved.slug, row.slug, source) !== 1) throw changedSincePreview(row.source_id, p.path, `page ${moved.slug} could not move to ${row.slug}`);
+ if (await tx.updateSlug(moved.slug, row.slug, source) !== 1) throw changedSincePreview(row.source_id, p.path, `page ${moved.slug} could not move to ${row.slug}`, kind);
if (publication.renamedType) await tx.executeRaw('UPDATE pages SET type=$3 WHERE source_id=$1 AND slug=$2', [row.source_id, row.slug, publication.renamedType]);
let movedImport: PreparedContentImport | undefined;
await importFromContent(tx, row.slug, importContent, { ...importOptions, prepare: async value => { movedImport = value; return value.result; } });
- if (!movedImport || movedImport.slug !== row.slug) throw changedSincePreview(row.source_id, p.path, `page ${moved.slug} could not be prepared at ${row.slug}`);
+ if (!movedImport || movedImport.slug !== row.slug) throw changedSincePreview(row.source_id, p.path, `page ${moved.slug} could not be prepared at ${row.slug}`, kind);
await movedImport.validate(tx);
applied = movedImport;
}
@@ -293,6 +331,7 @@ export async function prepareManagedFileRepairMutation(engine: BrainEngine, row:
if (page) await recordSyncImportProvenance(tx, { source_id: row.source_id, incarnation: row.source_incarnation, page_id: Number(page.id), origin: p.sourcePath,
raw_sha256: sha256(importContent), gbrain_version: VERSION });
return { status: moved ? 'renamed' : applied.noop ? 'skipped' : snapshot ? 'updated' : 'created', slug: row.slug, source_id: row.source_id,
- chunks: applied.result.chunks, imported_file: true, file_repaired: fileChanges, hold_cleared: holdCleared, ...(moved ? { renamed_from: moved.slug } : {}) };
+ chunks: applied.result.chunks, imported_file: true, file_repaired: fileChanges, hold_cleared: holdCleared, ...(moved ? { renamed_from: moved.slug } : {}),
+ ...(fenceRepair ? { fence_repair: fenceRepair } : {}) };
} };
}
diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.ts
index 8a16eaf9a0..a0dfdfcd55 100644
--- a/src/core/persistence/page-mutations.ts
+++ b/src/core/persistence/page-mutations.ts
@@ -1,5 +1,6 @@
import { randomUUID } from 'node:crypto';
import { fenceNormalizedNotice, type FencesNormalized } from '../fence-repair/report.ts';
+import { parseFenceRepairReceipt } from '../fence-repair/receipt.ts';
import { realpathSync } from 'node:fs';
import { isAbsolute, join, relative, resolve, sep } from 'node:path';
import type { OperationContext } from '../ops/contract.ts';
@@ -178,6 +179,11 @@ export async function preparePageAdmission(ctx: OperationContext,
'Drop kind, preview and backup_reference from put_page; reconciling a canonical file runs through gbrain sources reconcile on the brain host.');
}
}
+ // #6188: a fence repair's receipt is recorded only by the trusted local fence repair, never by a caller.
+ if (Object.hasOwn(input.params, 'fence_repair') && (input.operation !== 'put_page' || ctx.remote !== false || !parseFenceRepairReceipt(input.params.fence_repair))) {
+ throw new OperationError('invalid_params', 'fence_repair is reserved for the trusted fence repair.',
+ 'Drop fence_repair and submit the page without it; gbrain repair fences records its own receipt on the brain host. To fix a malformed facts or takes fence, correct it in content (or write facts with remember and takes with takes_add); a held file is repaired by the brain host operator with gbrain repair fences, so ask the user to run it.');
+ }
const { page_batch: _forged, ...params } = input.params;
const p: Record<string, unknown> = { ...params, ...parseMutationPrecondition(params) };
if (input.batch) p.page_batch = { id: input.batch.id, index: input.batch.index, size: input.batch.size };
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index 902d396cdd..36e64bfcae 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -48,6 +48,8 @@ import { applyPageEdits, editDiff, parsePageEdits } from './page-edit.ts';
import { carryCoreMarking, prepareCoreGuard } from './core-guard.ts';
import { fenceWhere } from '../fence-repair/refusal.ts';
import { pageFencesNormalized } from '../fence-repair/report.ts';
+import { parseFenceRepairReceipt } from '../fence-repair/receipt.ts';
+import { fenceRepairCommit } from './effect-model.ts';
const PURGE_RESIDUALS = 'Brain-repo git history, synced working-tree copies, exports, compiled context files and slug-keyed derived rows (takes, open loops, file records) may still hold the content — rotate the credential and rewrite or regenerate those copies.';
@@ -286,6 +288,9 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequest
recoverable_until: 'now + 72h via restore_page (remove immediately instead: gbrain delete <slug> --purge, local CLI only)' };
} };
}
+ // #6188: a trusted local fence repair's receipt (admission refuses it from every other caller) rides the outcome and the file's commit.
+ const fenceRepair = row.operation === 'put_page' && !row.authority.remote ? parseFenceRepairReceipt(p.fence_repair) : null;
+ const fenceRepairOutcome = fenceRepair ? { fence_repair: fenceRepair } : {};
// #5616: edits apply to the caller's view of the locked snapshot (revision checked above).
const edited = row.operation === 'edit_page' ? editLockedPage(row, snapshot) : undefined;
let content = edited?.content ?? preparedIntent?.content ?? p.content as string;
@@ -351,7 +356,7 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequest
const file=await prepareFileTarget(engine,row,snapshot,targetDeleted ? null : serializePageToMarkdown(snapshot.page,snapshot.tags),undefined,{ activePack, remote: row.authority.remote });
return {observedRevision,noop:true,file,...await pageDatabaseOnlyPublication(engine,row,file),
apply:async()=>({...pageNoopAdvisories(row),status:'skipped',slug:row.slug,source_id:row.source_id,noop:true,chunks:0,chunk_skip_reason:'write_skipped',
- ...(row.operation==='capture'?{channel:'capture',content_hash:p.capture_hash}:{})})};
+ ...(row.operation==='capture'?{channel:'capture',content_hash:p.capture_hash}:{}),...fenceRepairOutcome})};
}
}
let prepared: PreparedContentImport | undefined;
@@ -419,7 +424,8 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequest
const shownFixes = (ready.result.fences_normalized ?? []).filter(fix => !row.authority.remote || fix.fence !== 'takes');
const fencesNormalized = shownFixes.length ? { fences_normalized: pageFencesNormalized({ sourceId: row.source_id, slug: row.slug, fixes: shownFixes,
writer: row.principal_kind, path: snapshot?.page.source_path ?? null, remote: row.authority.remote }) } : {};
- const file = await prepareFileTarget(engine, row, snapshot, targetDeleted ? null : rendered, undefined, { capture, allowMissing: options.allowMissingFile, activePack, remote: row.authority.remote });
+ const target = await prepareFileTarget(engine, row, snapshot, targetDeleted ? null : rendered, undefined, { capture, allowMissing: options.allowMissingFile, activePack, remote: row.authority.remote });
+ const file = target && fenceRepair ? { ...target, commit: fenceRepairCommit(relative(target.root, target.path).split(sep).join('/'), fenceRepair.classes) } : target;
const mintMode = file && !snapshot?.page.source_path ? await scannerSlugRootMode(engine, row.source_id, file.root) : undefined;
const sourcePath = file && mintMode ? scannerSourcePath(file.root, file.path, mintMode) : undefined;
// An inferred mode is pinned with the first origin it mints, so later pages cannot flip the inference (#5610).
@@ -465,7 +471,7 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequest
...(ready.result.chunks === 0 ? {chunk_skip_reason: noop ? 'write_skipped'
: isEmbedSkipped(ready.parsedPage.frontmatter) || isQuarantined(ready.parsedPage.frontmatter) ? 'embed_skip' : 'empty_body'} : {}),
...(row.operation === 'capture' ? { channel: 'capture', content_hash: p.capture_hash } : {}),
- ...(edited ? editDiff(row.slug, edited.before, edited.after) : {}), ...fencesNormalized };
+ ...(edited ? editDiff(row.slug, edited.before, edited.after) : {}), ...fencesNormalized, ...fenceRepairOutcome };
} };
}
diff --git a/test/fence-repair-receipts.test.ts b/test/fence-repair-receipts.test.ts
new file mode 100644
index 0000000000..04bfaea80b
--- /dev/null
+++ b/test/fence-repair-receipts.test.ts
@@ -0,0 +1,302 @@
+/**
+ * #6188 fence repair receipts and commit messages.
+ *
+ * Protects: the durable `fence_repair` receipt a fence repair's write records
+ * (`managed_file_repair` with `fenceRepair`, or a trusted local `put_page`
+ * with `fence_repair`), its Git commit subject `gbrain: repair fence in
+ * <path> (<classes>)` and, in a batched commit, one `<path> (<classes>)` body
+ * line per repaired path; refusals of a fence repair routed to `gbrain repair
+ * fences` (D6); `fence_repair` refused from every remote caller; location-only
+ * privacy of receipts and commit messages.
+ * Fails when: the commit note is dropped anywhere between the preparer and
+ * `git commit` (file target, Git effect data, effect worker, commitGitTargets),
+ * a malformed or mismatched receipt is written, an MCP caller can set
+ * `fence_repair`, a fence repair's refusal names the frontmatter repair, or a
+ * commit without metadata changes its message.
+ * Why new: no test covered Git commit messages or a repair receipt;
+ * test/repair-frontmatter.test.ts covers `managed_file_repair` without one.
+ * Seams: none; real PGLite (and a Postgres arm) managed brains and real Git checkouts.
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { randomUUID } from 'node:crypto';
+import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { OperationError, type OperationContext } from '../src/core/ops/contract.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { sha256 } from '../src/core/persistence/digest.ts';
+import { localHostId } from '../src/core/persistence/identity.ts';
+import { runPersistenceEffects } from '../src/core/persistence/effects.ts';
+import { commitGitTargets } from '../src/core/persistence/effect-git.ts';
+import { declarePersistenceProtocol } from '../src/core/persistence/protocol.ts';
+import { readGitSourceHolds } from '../src/core/persistence/sync-holds.ts';
+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { confinedRepairTarget, managedRepairRoot, prepareRepairPublication, repairScreenConfig, submitManagedFileRepair } from '../src/core/persistence/file-repair.ts';
+import type { FenceRepairReceipt } from '../src/core/fence-repair/receipt.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const backends = testBackends();
+const home = mkdtempSync(join(tmpdir(), 'gbrain-fence-receipts-'));
+const engines: BrainEngine[] = [];
+let closePostgres: (() => Promise<void>) | undefined;
+const env = { GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined };
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
+/** The last commit's message without a trailing trailer paragraph: a host's git may append one (a co-author line); gbrain writes none. */
+const lastMessage = (root: string) => git(root, 'log', '-1', '--format=%B').trimEnd().replace(/\n\n(?:[A-Za-z-]+: [^\n]*\n?)+$/, '');
+const commits = (root: string) => Number(git(root, 'rev-list', '--count', 'HEAD').trim());
+
+const FB = '<!--- gbrain:facts:begin -->', FE = '<!--- gbrain:facts:end -->';
+const FH = '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |\n|---|---|---|---|---|---|---|---|---|---|';
+/** Privacy sentinel: a claim that must never reach a receipt, an effect row or a commit message. */
+const CLAIM = 'Sentinelclaimrq7 renews yearly';
+const row = (n: number, claim: string) => `| ${n} | ${claim} | fact | 1.0 | private | medium | 2026-01-01 | | call | |`;
+const page = (title: string, body: string) => `---\ntitle: ${title}\n---\nA synthetic note.\n\n${body}`;
+/** A facts fence without a header row: managed sync holds it for a model repair. */
+const headerless = (title: string) => page(title, `${FB}\n${row(1, CLAIM)}\n${row(2, 'Another synthetic fact')}\n${FE}\n`);
+const repaired = (title: string) => page(title, `${FB}\n${FH}\n${row(1, CLAIM)}\n${row(2, 'Another synthetic fact')}\n${FE}\n`);
+const receiptFor = (before: string, after: string, classes = ['no_header']): FenceRepairReceipt => ({ actor: 'fence-repair', tier: 'llm', classes,
+ rows: [1, 2], columns: ['#', 'claim'], model: 'example:fence-model', before_sha256: sha256(before), after_sha256: sha256(after), cost_usd: 0.002 });
+
+beforeAll(async () => {
+ if (backends.includes('pglite')) { const engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); engines.push(engine); }
+ if (backends.includes('postgres')) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engines.push(pg.engine); closePostgres = pg.close; }
+}, 120_000);
+
+afterAll(async () => {
+ await withEnv(env, async () => { for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); } });
+ await closePostgres?.(); rmSync(home, { recursive: true, force: true });
+});
+
+const quiet = { info() {}, warn() {}, error() {} };
+const localCtx = (engine: BrainEngine, sourceId: string, remote = false) =>
+ ({ engine, config: { engine: engine.kind }, logger: quiet, dryRun: false, remote, sourceId }) as unknown as OperationContext;
+
+/** A managed source over a durability-hardened checkout holding `files`, synced once. */
+async function managed(engine: BrainEngine, files: Record<string, string>) {
+ const id = `fr-${randomUUID().replace(/-/g, '').slice(0, 20)}`, root = join(home, id);
+ mkdirSync(root, { recursive: true }); git(root, 'init', '-q');
+ git(root, 'config', 'user.name', 'Example'); git(root, 'config', 'user.email', '[email protected]');
+ writeFileSync(join(root, '.git', 'hooks', 'post-commit'), '#!/bin/sh\n# gbrain brain-durability post-commit hook (v0.42.44+)\n'); chmodSync(join(root, '.git', 'hooks', 'post-commit'), 0o755);
+ for (const [path, content] of Object.entries(files)) { mkdirSync(join(root, path, '..'), { recursive: true }); writeFileSync(join(root, path), content); }
+ git(root, 'add', '-A'); git(root, 'commit', '-qm', 'fixture');
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [id, root]);
+ await claimWorktree(engine, id, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ await performManagedSync(engine, { sourceId: id, noPull: true, noEmbed: true, noExtract: true });
+ const read = (path: string) => readFileSync(join(root, path), 'utf8');
+ /** What the repair preview would bind: the publication digest of `content` at `path`. */
+ const digestOf = async (path: string, content: string) => {
+ const slug = path.replace(/\.md$/, '');
+ const snapshot = await engine.readPageSnapshot(slug, { sourceId: id, includeDeleted: true });
+ const publication = await prepareRepairPublication(engine, { sourceId: id, slug, sourcePath: path, path, root, content, snapshot, base: snapshot, ...await repairScreenConfig(engine, id) });
+ if (publication.status !== 'ready') throw new Error(`fixture publication is ${publication.status}`);
+ return { slug, resultDigest: publication.digest, revision: snapshot?.revision };
+ };
+ return { id, root, read, digestOf };
+}
+
+/** Runs queued effects here (and waits for the consumer's) until no Git effect of the source is open. */
+async function gitEffectsSettled(engine: BrainEngine, sourceId: string) {
+ for (let i = 0; i < 100; i++) {
+ await runPersistenceEffects(engine, { engine: engine.kind }, { hostId: localHostId(), limit: 10 });
+ const open = await engine.executeRaw("SELECT 1 FROM persistence_effects WHERE source_id=$1 AND kind='git' AND state<>'committed'", [sourceId]);
+ if (!open.length) return;
+ await Bun.sleep(100);
+ }
+ throw new Error('git effects did not settle');
+}
+
+const durableOutcome = async (engine: BrainEngine, requestId: string) =>
+ (await engine.executeRaw<{ outcome: Record<string, unknown> | null }>('SELECT outcome FROM persistence_requests WHERE request_id=$1::uuid', [requestId]))[0]?.outcome ?? null;
+const gitEffectData = async (engine: BrainEngine, requestId: string) =>
+ (await engine.executeRaw<{ data: Record<string, unknown> }>(`SELECT e.data FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id
+ WHERE r.request_id=$1::uuid AND e.kind='git'`, [requestId]))[0]?.data;
+
+async function each(run: (engine: BrainEngine) => Promise<void>) {
+ await withEnv(env, async () => {
+ for (const engine of engines) {
+ try { await run(engine); } finally { await disposePersistenceConsumer(engine); }
+ }
+ });
+}
+
+async function refusal(run: () => Promise<unknown>): Promise<OperationError> {
+ try { await run(); } catch (error) { if (error instanceof OperationError) return error; throw error; }
+ throw new Error('expected a refusal');
+}
+
+test('commitGitTargets: a noted path committing alone takes its subject; a group keeps the generic subject and lists noted lines in path order', () => withEnv(env, async () => {
+ const root = mkdtempSync(join(home, 'commit-notes-'));
+ git(root, 'init', '-q'); git(root, 'config', 'user.name', 'Example'); git(root, 'config', 'user.email', '[email protected]');
+ const write = (path: string, content: string) => { mkdirSync(join(root, path, '..'), { recursive: true }); writeFileSync(join(root, path), content); };
+ for (const path of ['a.md', 'notes/b.md', 'notes/c.md', 'z.md']) write(path, 'seed\n');
+ git(root, 'add', '-A'); git(root, 'commit', '-qm', 'seed');
+ const note = (path: string, classes: string) => ({ subject: `gbrain: repair fence in ${path} (${classes})`, line: `${path} (${classes})` });
+
+ write('notes/b.md', 'repaired\n');
+ expect((await commitGitTargets(root, ['notes/b.md'], undefined, new Map([['notes/b.md', note('notes/b.md', 'close_fence, header_alias')]]))).get('notes/b.md')).toEqual({ git: 'committed' });
+ expect(lastMessage(root)).toBe('gbrain: repair fence in notes/b.md (close_fence, header_alias)');
+
+ for (const path of ['z.md', 'notes/c.md', 'a.md']) write(path, 'batched\n');
+ const batch = await commitGitTargets(root, ['z.md', 'notes/c.md', 'a.md'], undefined,
+ new Map([['z.md', note('z.md', 'row_renumbered')], ['a.md', note('a.md', 'no_header')]]));
+ expect([...batch.values()]).toEqual([{ git: 'committed' }, { git: 'committed' }, { git: 'committed' }]);
+ expect(lastMessage(root)).toBe('gbrain: persist 3 canonical memory updates\n\na.md (no_header)\nz.md (row_renumbered)');
+
+ // A preparer's text never adds lines or trailers: control characters are stripped.
+ write('a.md', 'again\n');
+ await commitGitTargets(root, ['a.md'], undefined, new Map([['a.md', { subject: 'gbrain: repair fence in a.md (close_fence)\n\nSigned-off-by: x', line: 'unused' }]]));
+ expect(lastMessage(root)).toBe('gbrain: repair fence in a.md (close_fence)Signed-off-by: x');
+
+ // Without notes, single and grouped commits keep their messages byte for byte.
+ write('a.md', 'plain\n');
+ await commitGitTargets(root, ['a.md']);
+ expect(lastMessage(root)).toBe('gbrain: persist canonical memory update');
+ write('a.md', 'plain again\n'); write('z.md', 'plain again\n');
+ await commitGitTargets(root, ['a.md', 'z.md'], undefined, new Map());
+ expect(lastMessage(root)).toBe('gbrain: persist 2 canonical memory updates');
+}), 60_000);
+
+test('a managed_file_repair with a fence receipt commits under the fence subject and its durable receipt carries fence_repair, location only', () => each(async engine => {
+ const s = await managed(engine, { 'notes/alpha.md': headerless('Alpha') });
+ const hold = ((await readGitSourceHolds(engine, { sourceIds: [s.id] }))[0]?.holds ?? []).find(h => h.path === 'notes/alpha.md');
+ expect(hold?.code).toBe('invalid_fence');
+ const before = s.read('notes/alpha.md'), after = repaired('Alpha');
+ const { slug, resultDigest } = await s.digestOf('notes/alpha.md', after);
+ const receipt = receiptFor(before, after);
+ const requestId = randomUUID();
+ const outcome = await submitManagedFileRepair(localCtx(engine, s.id), { sourceId: s.id, requestId, slug, path: 'notes/alpha.md', sourcePath: 'notes/alpha.md',
+ content: after, beforeHash: sha256(before), resultDigest, noEmbed: true, fenceRepair: receipt });
+ expect(outcome).toMatchObject({ state: 'committed', file_repaired: true, hold_cleared: true, fence_repair: receipt });
+ expect((await durableOutcome(engine, requestId))?.fence_repair).toEqual(receipt);
+ expect(s.read('notes/alpha.md')).toBe(after);
+ const data = await gitEffectData(engine, requestId);
+ expect(data).toMatchObject({ commit_subject: 'gbrain: repair fence in notes/alpha.md (no_header)', commit_line: 'notes/alpha.md (no_header)' });
+
+ await gitEffectsSettled(engine, s.id);
+ expect(lastMessage(s.root)).toBe('gbrain: repair fence in notes/alpha.md (no_header)');
+ expect(git(s.root, 'status', '--porcelain', '--', 'notes/alpha.md')).toBe('');
+ for (const text of [JSON.stringify(outcome), JSON.stringify(await durableOutcome(engine, requestId)), JSON.stringify(data), git(s.root, 'log', '--format=%B')]) {
+ expect(text).not.toContain('Sentinelclaimrq7');
+ }
+}), 180_000);
+
+test('without a receipt the repair keeps the generic subject and names the frontmatter repair; with one, refusals name gbrain repair fences', () => each(async engine => {
+ const s = await managed(engine, { 'notes/plain.md': page('Plain', 'First version.\n') });
+ const before = s.read('notes/plain.md'), after = page('Plain', 'Second version.\n');
+ const { slug, resultDigest, revision } = await s.digestOf('notes/plain.md', after);
+ const input = { sourceId: s.id, slug, path: 'notes/plain.md', sourcePath: 'notes/plain.md', content: after, resultDigest, expected_revision: revision, noEmbed: true };
+
+ const stale = 'b'.repeat(64);
+ const frontmatter = await refusal(() => submitManagedFileRepair(localCtx(engine, s.id), { ...input, requestId: randomUUID(), beforeHash: stale }));
+ expect(frontmatter.code).toBe('changed_since_preview');
+ expect(frontmatter.suggestion).toContain(`gbrain repair frontmatter --source ${s.id}`);
+ expect(frontmatter.fix?.argv).toEqual(['gbrain', 'repair', 'frontmatter', '--source', s.id]);
+ const fences = await refusal(() => submitManagedFileRepair(localCtx(engine, s.id), { ...input, requestId: randomUUID(), beforeHash: stale,
+ fenceRepair: { ...receiptFor(before, after, ['close_fence']), before_sha256: stale } }));
+ expect(fences.code).toBe('changed_since_preview');
+ expect(fences.suggestion).toContain(`gbrain repair fences --source ${s.id}`);
+ expect(fences.fix?.argv).toEqual(['gbrain', 'repair', 'fences', '--source', s.id]);
+ expect(JSON.stringify({ message: fences.message, suggestion: fences.suggestion, fix: fences.fix })).not.toContain('frontmatter');
+ let confined: unknown;
+ try { confinedRepairTarget(s.root, '../outside.md', s.id, 'fences'); } catch (error) { confined = error; }
+ expect((confined as OperationError).suggestion).toContain('gbrain repair fences writes only regular files');
+
+ const requestId = randomUUID();
+ const outcome = await submitManagedFileRepair(localCtx(engine, s.id), { ...input, requestId, beforeHash: sha256(before) });
+ expect(outcome).toMatchObject({ state: 'committed', file_repaired: true });
+ expect(outcome).not.toHaveProperty('fence_repair');
+ expect(await gitEffectData(engine, requestId)).not.toHaveProperty('commit_subject');
+ await gitEffectsSettled(engine, s.id);
+ expect(lastMessage(s.root)).toBe('gbrain: persist canonical memory update');
+}), 180_000);
+
+test('a malformed or mismatched fence receipt is refused before admission and by the preparer; nothing is written', () => each(async engine => {
+ const s = await managed(engine, { 'notes/gamma.md': page('Gamma', 'First version.\n') });
+ const before = s.read('notes/gamma.md'), after = page('Gamma', 'Second version.\n');
+ const { slug, resultDigest, revision } = await s.digestOf('notes/gamma.md', after);
+ const input = { sourceId: s.id, slug, path: 'notes/gamma.md', sourcePath: 'notes/gamma.md', content: after, beforeHash: sha256(before), resultDigest, expected_revision: revision, noEmbed: true };
+ const receipt = receiptFor(before, after, ['close_fence']);
+ const requests = async (requestId: string) => (await engine.executeRaw('SELECT 1 FROM persistence_requests WHERE request_id=$1::uuid', [requestId])).length;
+
+ for (const [bad, why] of [[{ ...receipt, actor: 'someone-else' }, 'is malformed'], [{ ...receipt, classes: ['Close fence'] }, 'is malformed'],
+ [{ ...receipt, before_sha256: 'c'.repeat(64) }, 'previewed file bytes'], [{ ...receipt, after_sha256: 'd'.repeat(64) }, 'repaired file bytes']] as const) {
+ const requestId = randomUUID();
+ const error = await refusal(() => submitManagedFileRepair(localCtx(engine, s.id), { ...input, requestId, fenceRepair: bad as unknown as FenceRepairReceipt }));
+ expect(error.code).toBe('invalid_params');
+ expect(error.message).toContain(why);
+ expect(error.fix?.argv).toEqual(['gbrain', 'repair', 'fences', '--source', s.id]);
+ expect(await requests(requestId)).toBe(0);
+ }
+
+ // The preparer checks the stored intent itself (a replay, or a caller that skipped the submit checks).
+ const { ownerEpoch } = await managedRepairRoot(engine, s.id);
+ const requestId = randomUUID();
+ const stored = await refusal(() => submitPageMutation(localCtx(engine, s.id), { operation: 'put_page', waitMs: 30_000, managedFileImport: true, params: {
+ kind: 'managed_file_repair', slug, source_id: s.id, request_id: requestId, path: 'notes/gamma.md', sourcePath: 'notes/gamma.md', content: after,
+ beforeHash: sha256(before), resultDigest, ownerEpoch, expected_revision: revision, noEmbed: true, fenceRepair: { ...receipt, after_sha256: 'e'.repeat(64) } } }));
+ expect(stored.code).toBe('invalid_params');
+ expect(stored.message).toContain('repaired file bytes');
+ expect(s.read('notes/gamma.md')).toBe(before);
+ expect((await engine.getPage(slug, { sourceId: s.id }))?.compiled_truth).toContain('First version.');
+}), 180_000);
+
+test('put_page fence_repair is refused from remote callers and malformed values; a trusted local put_page records it and commits under the fence subject', () => each(async engine => {
+ const s = await managed(engine, { 'notes/beta.md': page('Beta', 'First version.\n') });
+ const snapshot = (await engine.readPageSnapshot('notes/beta', { sourceId: s.id }))!;
+ const content = repaired('Beta');
+ const receipt = receiptFor(s.read('notes/beta.md'), content, ['close_fence']);
+ const params = { slug: 'notes/beta', source_id: s.id, content, expected_revision: snapshot.revision, fence_repair: receipt };
+
+ const remote = await refusal(() => submitPageMutation(localCtx(engine, s.id, true), { operation: 'put_page', params: { ...params, request_id: randomUUID() } }));
+ expect(remote).toMatchObject({ code: 'invalid_params', message: 'fence_repair is reserved for the trusted fence repair.' });
+ const malformed = await refusal(() => submitPageMutation(localCtx(engine, s.id), { operation: 'put_page', params: { ...params, request_id: randomUUID(), fence_repair: { ...receipt, tier: 'manual' } } }));
+ expect(malformed.code).toBe('invalid_params');
+ const otherVerb = await refusal(() => submitPageMutation(localCtx(engine, s.id), { operation: 'capture', params: { content: 'A synthetic capture.', source_id: s.id, fence_repair: receipt } }));
+ expect(otherVerb.code).toBe('invalid_params');
+ expect(s.read('notes/beta.md')).toBe(page('Beta', 'First version.\n'));
+
+ const requestId = randomUUID();
+ const response = await submitPageMutation(localCtx(engine, s.id), { operation: 'put_page', params: { ...params, request_id: requestId } });
+ expect(response).toMatchObject({ state: 'committed', fence_repair: receipt });
+ expect((await durableOutcome(engine, requestId))?.fence_repair).toEqual(receipt);
+ await gitEffectsSettled(engine, s.id);
+ expect(lastMessage(s.root)).toBe('gbrain: repair fence in notes/beta.md (close_fence)');
+ for (const text of [JSON.stringify(response), JSON.stringify(await gitEffectData(engine, requestId)), git(s.root, 'log', '--format=%B')]) {
+ expect(text).not.toContain('Sentinelclaimrq7');
+ }
+}), 180_000);
+
+test('fence repairs that commit in one Git group list one path and its classes per body line; an ordinary write in the group adds none', () => each(async engine => {
+ const s = await managed(engine, { 'notes/one.md': page('One', 'First.\n'), 'notes/two.md': page('Two', 'First.\n'), 'notes/three.md': page('Three', 'First.\n') });
+ const effectSql = (sql: string) => engine.transaction(async tx => { await declarePersistenceProtocol(tx); await tx.executeRaw(sql); });
+ const startCommits = commits(s.root);
+ // Hold every new effect back so the three writes reach the runner as one group.
+ await engine.executeRaw("ALTER TABLE persistence_effects ALTER COLUMN next_attempt_at SET DEFAULT (now()+interval '1 hour')");
+ try {
+ for (const [path, classes] of [['notes/two.md', ['row_renumbered']], ['notes/one.md', ['close_fence', 'header_alias']]] as const) {
+ const before = s.read(path), after = page(path === 'notes/one.md' ? 'One' : 'Two', 'Repaired.\n');
+ const { slug, resultDigest, revision } = await s.digestOf(path, after);
+ await submitManagedFileRepair(localCtx(engine, s.id), { sourceId: s.id, requestId: randomUUID(), slug, path, sourcePath: path, content: after,
+ beforeHash: sha256(before), resultDigest, expected_revision: revision, noEmbed: true, fenceRepair: receiptFor(before, after, [...classes]) });
+ }
+ const three = (await engine.readPageSnapshot('notes/three', { sourceId: s.id }))!;
+ await submitPageMutation(localCtx(engine, s.id), { operation: 'put_page', params: { slug: 'notes/three', source_id: s.id, request_id: randomUUID(),
+ content: page('Three', 'Second.\n'), expected_revision: three.revision } });
+ } finally {
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('ALTER TABLE persistence_effects ALTER COLUMN next_attempt_at SET DEFAULT now()');
+ }
+ await effectSql(`UPDATE persistence_effects SET next_attempt_at=now() WHERE kind='git' AND state='queued' AND source_id='${s.id}'`);
+ await gitEffectsSettled(engine, s.id);
+ expect(commits(s.root)).toBe(startCommits + 1);
+ expect(lastMessage(s.root)).toBe('gbrain: persist 3 canonical memory updates\n\nnotes/one.md (close_fence, header_alias)\nnotes/two.md (row_renumbered)');
+}), 180_000);
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 960bf7929e..52f2a2209f 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -24,6 +24,7 @@ test/doctor-frontmatter-holds.test.ts
test/embedding-completion-atomic.serial.test.ts
test/engine-sql-facts-keyset.test.ts
test/extract-endpoint-revision.serial.test.ts
+test/fence-repair-receipts.test.ts
test/graduation-copy.test.ts
test/graduation-digest.test.ts
test/graduation-drain.test.ts