Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
GBRA-217: reason trailers reach Git, receipts report superseded reasons, history CLI, docs and goldens
garrytanf9150bc50c17
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 76800a8a01..84c202edf5 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,25 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [Unreleased]++**A page write can say why it was made, and page history shows it.**++`put_page`, `edit_page`, `revert_version` and each `put_pages` item take an optional `reason` (one line, at most 500 characters; `--reason` on the CLI). It is stored on the version the write replaced, and `get_versions` returns it as `replaced_because`, so the newest version explains the text you read now; `gbrain history` prints it as `changed because: …`. When the page's file reaches Git, the commit carries it as a trailer naming the file, `gbrain-reason: <path>: <text>`, beside any `gbrain-repair:` trailer. A brain with no Git repository gets the same history from the database. Every write result reports where the reason went in `reason_recorded`.++### What changed++| Situation | Before | Now |+|---|---|---|+| A write passes `reason` | refused as an unknown parameter | stored with the replaced version and, for a world-visible file, in the commit |+| A reason over 500 characters, or one that looks like a credential | n/a | refused before admission: `change_reason_rejected` (`reason_too_long`, `reason_contains_secret`), and no journal row keeps it |+| A remote caller reads `get_versions` | no reasons | `replaced_because` when the version and the one that replaced it are both world-visible and the replacement was not pruned |+| A private page's write has a reason | n/a | the reason stays out of every commit message |+| A write without a reason | | the same commit message and history as before |+| A newer write to the same file commits first (non-strict source) | n/a | the receipt says `git: superseded` with a `reason_not_committed` notice; the reason stays in history |++Guide: [page history](docs/guides/page-history.md).+## [0.60.474.0] - 2026-10-27**A database role that can't read the writer state is now refused instead of let through.**diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.mdindex 25a49499c3..dd2419dfa7 100644--- a/docs/architecture/key-files/core-persistence.md+++ b/docs/architecture/key-files/core-persistence.md@@ -12,6 +12,7 @@ Managed facts extraction (withdrawn-candidate skip and recovery, conversation fa- `src/core/persistence/activation.ts` — private CLI `sources writer activate --confirm-quiesced` boundary. Verifies native capability and filesystem bindings, takes root locks before DB waits and rechecks topology under transaction guards. Live/young/foreign legacy leases refuse regardless of expiry; only explicitly requested `--cleanup-dead-local-locks` removes exact dead same-host holders under the lease lock. Dry-run deletes nothing. Never silently claims a source. Tests: `test/persistence-activation.test.ts`, `test/persistence-onboarding.test.ts`. Unbound Google/GitHub API sources may activate as reviewed `connector_database` without fabricating a Git root, while bound sources still need physical-root checks. Activation increments `persistence_brain.mode_epoch` (migration 183), which the writer admin-state hash includes. A non-connector source whose recorded `local_path` no longer exists or is relative (unclaimed, or claimed by this host) refuses `source_changed` with detail `source_path_missing`, naming the source, the path and the `sources set-path` / `sources remove` exits (the claimed checkout filled in), in `--dry-run` too (#5206, `test/activation-missing-source-path.test.ts`). The report's `warnings[]` (dry run and real run) carries one `git_durability_not_enabled` entry per filesystem source the effect runner's policy (`gitDurabilityPolicy`) would leave non-durable, with `enable_command`, a read-only `git-durability --enable --dry-run` fix and the note that enabling re-queues skipped Git effects; `persistence-admin.ts` also prints them to stderr without `--json`, and activation proceeds (#5182, `test/writer-activate-durability-warnings-5182.test.ts`).- `src/core/persistence/git-durability-policy.ts` + `git-durability-administration.ts` — whether the persistence owner commits and pushes page writes through its Git effect is a per-host-binding setting (#5182): `persistence_host_bindings.git_durability` (`enabled` | `disabled` | NULL, migration v234, column SQL kept out of the replayed schema blob as `PERSISTENCE_GIT_DURABILITY_COLUMN_SQL`). `gitDurabilityPolicy(binding, root)` is tri-state and fail-closed: a recorded value wins, NULL falls back to the legacy post-commit-hook probe, a probe error fails the effect instead of skipping it; `effects.ts` takes its per-root verdict from it. `gitDurabilityState` renders `on`/`off`/`unknown` for `writer status` and `writer activate`'s `git_durability` listing. `planGitDurabilityCatchUp`/`requeueGitDurabilityCatchUp` re-queue the Git effects completed `durability_not_enabled` while the setting was off by resetting the existing rows, never inserting under `UNIQUE(request_id, kind)`. The verb `writer_git_durability` (`gbrain sources writer git-durability <source> --enable|--disable [--pat-file <path>] [--dry-run]`, administration-gated like the other writer verbs) runs a read-only `git push --dry-run` probe before enabling (codes `git_branch_unborn`, `git_checkout_required`, `git_detached_head`), wires the repo-scoped credential under `gbrain.durability.managedcredential` from a 0600 `--pat-file` (`pat_file_unreadable` otherwise) and retries the worktree's parked pushes (codes in `GIT_PUSH_CODES`; `retry-effects <source> --parked-pushes` does the same without a credential). `sources push` (`managedPushRefusal` in `workspace-push.ts`), `bootstrap verify`'s `checkPushProbe` and the skill-pack writer guard name this route on a managed worktree (#5606). Pinned by `test/persistence-admin-git-durability.test.ts`, `test/managed-push-remedy.serial.test.ts`.+- `src/core/persistence/change-reason.ts` — GBRA-217 page-write reasons ([page history](../../guides/page-history.md#reasons)). `admitChangeReason` canonicalises a `reason` (one line, at most 500 code points) and refuses `change_reason_rejected` (`reason_too_long`, `reason_contains_secret` via `scanTextSpans`) before admission, so no journal row ever holds a refused reason; `page-mutations.ts` runs it before `callerIntent`, so the canonical reason joins replay identity, and `page-batch.ts` runs it per item (all or nothing). `withChangeReason` wraps a page preparer in `service.ts`: its apply stamps `page_versions.change_reason` on the snapshots that transaction created for the page, and, for a world-visible page whose file is published, appends `gbrain-reason: <path>: <text>` to `prepared.file.commit` (a `GitCommitNote` with `trailers[]`), which both the door (`commitThroughDoor`) and the effect commit (`commitMessage`, one trailer line each, `commitMessageArgs` switching to `-F` over 8 KiB) read after apply. The outcome's `reason_recorded.git` is `committed` (strict), `queued`, `private`, `not_file_backed`, `no_repository` (repo-less) or `none`; `settledReasonRecorded` turns `queued` into `superseded` with a `reason_not_committed` notice on the receipt when the Git effect was superseded. Read side: `replacedBecauseSql` in `engine-sql/pages.ts` (remote readers see a reason only when the successor snapshot is world-visible and not `successor_pruned`, which the prunes in `page-state/versions.ts` set). Tests: `test/page-change-reason-gbra217.test.ts`, `test/page-change-reason-git-gbra217.test.ts`, `test/page-change-reason-mcp-gbra217.test.ts`.- `src/core/persistence/effect-git.ts` (`pushGitRoot`) + `git-push-holds.ts` — a Git effect's push tries a plain push first; a non-fast-forward rejection runs this executable's `gbrain git commit-push --push-only --keep-checkout` as a child (never on the owner's event loop, never a `gbrain` from PATH), which merges the moved remote in memory and pushes without moving the checkout or running its pre-push hook, so `sources refresh` stays the only importer. A true conflict holds the effect `integrate_conflict` with the user's `--keep-checkout --resolve` choice. `readGitPushHolds` counts, per source, Git effects retrying or parked on a push code with the conflict state and one fix; read by doctor `parked_effects` and `sync status` `git_push_holds` (`next` falls back to a parked or conflicted hold's fix). Pinned by `test/pathological/h2-git-effect-moved-remote.test.ts`.- `src/core/persistence/deactivation.ts` — private CLI `sources writer deactivate` (#5455/#5628), brain-wide and trusted-local. `deactivationBlockers` lists the admin lock, queued/running/recovering requests, recovering topology changes, queued, running or recovering effects (the predicate activation uses; each exit says what clears it, and a failing links or facts-backstop effect settles after five attempts), held connector items (managed holds that classic mode would not read) and live `gbrain_cycle_locks` leases, each with its CLI exit; `failedEffectHistory` lists terminally failed effects as history (`failed_effects` on the dry run and the applied report, never blockers), each with its code and the exit that retries it: retry-effects for parked targets and failed Git, withdrawal, links and facts-backstop effects, `repair embedding-effects` for a failed embedding effect, none for `embedding_zero_norm` or an effect whose source was archived, replaced or removed (`test/pathological/a15-deactivate-exits.test.ts` runs every printed exit and checks it clears its entry); `physicalRootBlockers(engine, mode)` (#5914 [R9a]) adds `physical_root` for this host's owned checkouts, probed as the mode's real run will: strict `assertPhysicalRoot` for managed, `assertPhysicalRootReservation` for the classic pre-activation release, so each preview lists exactly what its real operation refuses on; `--dry-run` returns them plus the worktrees that would retire, the kept shared-skill settings and, when clean, `apply_command` bound to the admin state read before the preview. `deactivatePersistence` takes the local native worktree locks, then in one transaction locks `persistence_brain FOR UPDATE`, checks the expected admin state and the admin lock, locks worktrees then sources `FOR UPDATE` (admission's order), rechecks the blockers, sets `enabled=false`, increments `mode_epoch`, retires every worktree, deletes source and host bindings and records a committed `writer_deactivate` topology change (brain id, retired epoch, retired worktree ids and roots, source roots). `cleanupRetiredManagedMarkers` runs on CLI connect, after deactivate and from `writer status`: it removes this brain's registry records, `.gbrain-managed` / Git `gbrain-managed.json`, `.gbrain-owner.json` and reservations only when their `mode_epoch` is a retired one below the current epoch, or, without an epoch, their worktree id (or, for markers without one, their root outside any active binding) is recorded as retired; unknown or newer epochs are kept and reported `pending`, each file is re-read before unlinking and other brains' files are never touched. `root-registry.ts` writes `mode_epoch` into new registry records and managed markers. Tests: `test/persistence-deactivate.test.ts` (PGLite and Postgres), `test/e2e/persistence-deactivate-race.test.ts`. See [persistence stalls](persistence-stalls.md).diff --git a/docs/architecture/system-of-record.md b/docs/architecture/system-of-record.mdindex 38e41c1918..972bd8630c 100644--- a/docs/architecture/system-of-record.md+++ b/docs/architecture/system-of-record.md@@ -144,6 +144,19 @@ Keep an appropriate database backup before any destructive recovery, and donot delete historical unmatched facts or generate empty pages to make themappear file-backed.+### Change reasons++A page write's optional reason (GBRA-217, [page history](../guides/page-history.md#reasons))+follows the same rule as content. On a page whose file reaches Git it is+written into the commit as a path-mapped trailer+(`gbrain-reason: <path>: <text>`): on a git-canonical source the commit lands+before the database row, on other sources the row lands first and the Git+effect commits after it. `page_versions.change_reason` mirrors it, stamped by+the same write. Private, database-only and withheld pages, and repo-less+brains, keep the reason in the database only, as they do their content.+Existing rows are never re-stamped, and snapshot rows are not rebuilt from+`git log`.+## Write attributionGBrain records write attribution: who wrote each page revision, page version,diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 6eafb98264..1b2a32a57c 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -15,6 +15,7 @@ Under contract v1 an `error` value never changes. Where a surface sends a legacy| `error` (frozen) | `code` (canonical) | Meaning ||---|---|---|+| `invalid_params` | `change_reason_rejected` | The write's reason was refused before anything was admitted: it is longer than 500 characters, or it looks like it holds a secret. || `invalid_params` | `fact_withdrawn` | `remember`, or an owner `gbrain trust release` that writes a held fact into its entity page's `## Facts` table (a managed brain), refused a claim that was explicitly forgotten for this subject (wire `invalid_params`, message prefix `fact_withdrawn:`); nothing was saved, and a refused release leaves the fact held. || `permission_denied` | `insufficient_scope` | The connection lacks the OAuth scope the operation requires. || `invalid_params` | `invalid_fence` | A facts or takes fence in the page cannot be imported without dropping or guessing rows, so the page (or the file) was not written. |@@ -509,6 +510,18 @@ More: [docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover](../../|---|---|---|---|---|---|---|| Shared skill storage is not ready on this brain. | A temporary condition (a lock, a pending write, a rate limit); the same request can succeed later. | Wait briefly, then retry the same request (writes: reuse the same request_id). | agent | `repeat the read that failed` | 1 | yes |+### change_reason_rejected++<a id="change_reason_rejected"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| The write's reason was refused before anything was admitted: it is longer than 500 characters, or it looks like it holds a secret. | A reason is kept in page history and, on a page that reaches Git, in the commit message, which a push makes permanent; it is checked before the write is journaled so no copy of a refused reason is stored anywhere. | Shorten the reason, or remove the secret from it, and send the write again. | agent | `repeat the read that failed` | 1 | no |++Reasons: `reason_too_long`, `reason_contains_secret`.++More: [docs/guides/page-history.md#reasons](../../docs/guides/page-history.md#reasons)+### changed_since_preview<a id="changed_since_preview"></a>diff --git a/docs/guides/memory-boundaries.md b/docs/guides/memory-boundaries.mdindex f7bbe88078..cfe6e81c81 100644--- a/docs/guides/memory-boundaries.md+++ b/docs/guides/memory-boundaries.md@@ -406,6 +406,11 @@ and [isolated local backup guide](in-agent-setup.md#6-back-up-the-complete-local<a id="purge"></a>## Expire versus purge+A write's [reason](page-history.md#reasons) is stored with the page's history+and, when the page's file reaches Git, in the commit message. A purge removes+the database copies it covers, but a commit already pushed keeps its message+text, just as it keeps the file's earlier contents.+`forget` **expires**: the fact stops being recalled, cannot be saved again inthe same source and visibility, and its row is struck in the page's Markdown.The text stays in the row, the file, page history and backups.diff --git a/docs/guides/page-history.md b/docs/guides/page-history.mdnew file mode 100644index 0000000000..a241738575--- /dev/null+++ b/docs/guides/page-history.md@@ -0,0 +1,129 @@+# Page history: why a page changed++**Say to your agent:** *"Update the refund policy to a 30-day window, and record that the client asked for it."*++Every page write in gbrain keeps the text it replaced as a version. A write can+also carry a short human reason, so the history says why the text changed, not+only that it did. This guide covers how to give a reason, where it is stored,+who can read it, and what happens on a brain with no Git repository.++## Reasons++Pass `reason` on `put_page`, `edit_page`, `revert_version` or on any item of+`put_pages`:++```json+{ "slug": "policies/refunds", "expected_revision": "…", "content": "…",+ "reason": "Client asked for the 30-day window." }+```++The parameter is listed on the full MCP tool surface. The starter surface leaves+it out of the tool schemas to keep them small, but still accepts it, so an agent+on the starter surface can pass it too. On the CLI the same parameter is `--reason`, for example+`gbrain put policies/refunds --reason "Client asked for the 30-day window." < refunds.md`.++A reason is one line of at most 500 characters. Tabs and line breaks become+spaces, other control characters are removed, and an empty reason counts as+none. It is checked before the write is accepted, so a refused reason leaves no+copy anywhere:++- longer than 500 characters: `change_reason_rejected` with reason+ `reason_too_long` (the wire `error` is `invalid_params`), naming the length+ and the limit;+- it looks like it holds a credential: `change_reason_rejected` with reason+ `reason_contains_secret`, naming the detector and the character position,+ never the value.++Shorten the reason or remove the secret, then send the write again. The reason+is part of the request's identity: replaying a `request_id` with the same+reason replays the write, and replaying it with a different reason is a+conflict. In `put_pages`, one refused reason refuses the whole batch and names+the item; two copies of a page with the same reason are written once, and two+copies with different reasons are refused.++### Where the reason is stored++A version is the page as it was before a write. So the reason is stored on the+version that write archived, and `get_versions` shows it on that version as+`replaced_because`. The newest version's `replaced_because` explains the text+you read now. `gbrain history <slug>` prints it as `changed because: …` under+each version.++A page's first write archives nothing, so its reason has no version to sit on.+Every write result says where its reason went in `reason_recorded`:++| Field | Meaning |+|---|---|+| `reason` | The reason as stored, after the cleanup above. |+| `version` | `true` when a version carries it. |+| `version_why` | Why no version carries it: `page_created` (first write) or `no_change` (the write changed nothing). |+| `git` | Where Git stands, below. |++`git` is one of:++- `committed`: on a git-canonical source the commit landed with the write.+- `queued`: the file's commit is queued and will carry the reason.+- `superseded`: a newer write to the same file committed first (shown on the+ receipt, `get_write_request`, with a `reason_not_committed` notice). The+ reason stays in gbrain's history but is in no commit. Nothing needs fixing,+ and retrying the write would be wrong.+- `private`: the page is private, so its reason stays out of every commit+ message, group commits for other pages included.+- `not_file_backed`: the page has no file (database-only), so the reason is in+ gbrain's history only.+- `no_repository`: the brain has no Git repository (below).+- `none`: the write changed nothing.++### In Git++When the page's file reaches Git, its commit carries the reason as a trailer+naming the file:++```+gbrain-reason: policies/refunds.md: Client asked for the 30-day window.+```++There is one trailer per file, in the same trailer block as any+`gbrain-repair:` trailer, so `git interpret-trailers --parse` lists them all.+A write without a reason commits exactly the message it did before. A commit+you make yourself can give a reason the same way:++```bash+git commit --trailer "gbrain-reason: policies/refunds.md: Client asked for the 30-day window."+```++A pushed commit message cannot be changed, so treat a reason like any other+text you push. There is no operation to add a reason to a past write.++### Repo-less brains++A brain without a Git repository, such as the default keyless install, gets the+same feature. The database is the record there: the reason is stored on the+version by the same write, `get_versions` shows it the same way, and+`reason_recorded.git` is `no_repository`. Nothing is refused because there is no+repository. If you connect a repository later, the reasons already stored stay+where they are; old versions are not rewritten into commits.++### Who can read a reason++A trusted local caller sees every stored reason. A remote caller (an MCP client)+sees a version's reason only when both that version and the version that+replaced it are world-visible. The reason for turning a page private, or for+any change made while it was private, is therefore never shown remotely. When+the replacing version was later pruned (large pages keep a few versions), its+visibility can no longer be checked and the reason is withheld from remote+callers. Remote reasons go through the same text sanitizer as version bodies.++## Choosing how to record a change++A reason explains an edit to one document. Pick the shape that matches what+happened:++| What happened | Do this |+|---|---|+| The same document changed (a new edition, a correction) | Edit the page in place with `expected_revision` and a `reason`. |+| A separate document amends part of it | Write the amendment as its own page with an `amends` link (`since` the date it applies). |+| A different document replaces it entirely | Keep both pages and add a `supersedes` link from the new one. |++Do not create a second page for a new edition of the same document: the+history of one page, with reasons, is what readers and agents follow.diff --git a/llms.txt b/llms.txtindex f2f8a208d7..7dbf40db9f 100644--- a/llms.txt+++ b/llms.txt@@ -11,6 +11,7 @@ Repo: https://github.com/garrytan/gbrain- [Muse personal agent](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/muse.md): Verify durable storage first; connect Muse to your published brain (`gbrain mcp expose --funnel` + thin CLI) or add local explicit memory with provenance alongside Muse's native memory; distinguish Muse Code and unverified native MCP.- [Inside an existing agent](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/in-agent-setup.md): Isolated setup, absolute launcher, receipts, keyless maintenance, complete private backup and safe restoration.- [Memory boundaries](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/memory-boundaries.md): Durable shared preferences versus harness state; remote graph maintenance, provider text disclosure, authorization and full-backup limits.+- [Page history](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/page-history.md): Why a page changed: an optional reason on page writes, replaced_because in get_versions, the gbrain-reason commit trailer, remote visibility and repo-less brains.- [Brain versus session memory](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/brain-vs-memory.md): Route durable facts and preferences to shared memory, configuration to the harness, and temporary work to session state.- [Connect a hosted brain](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/hosted-harness-access.md): Getting the HTTPS endpoint (`gbrain mcp expose`, admin token file), host-side grants, private credential handoff, harness installation, profile repair, delegation limits and honest verification.- [Harness adapter reference](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/harness-adapters.md): Registry-generated transport, authentication lifetime and configuration facts.diff --git a/scripts/llms-config.ts b/scripts/llms-config.tsindex e0118e417e..2105925d3f 100644--- a/scripts/llms-config.ts+++ b/scripts/llms-config.ts@@ -43,6 +43,7 @@ export const SECTIONS: DocSection[] = [{ title: "Muse personal agent", path: "docs/guides/muse.md", description: "Verify durable storage first; connect Muse to your published brain (`gbrain mcp expose --funnel` + thin CLI) or add local explicit memory with provenance alongside Muse's native memory; distinguish Muse Code and unverified native MCP." },{ title: "Inside an existing agent", path: "docs/guides/in-agent-setup.md", description: "Isolated setup, absolute launcher, receipts, keyless maintenance, complete private backup and safe restoration." },{ title: "Memory boundaries", path: "docs/guides/memory-boundaries.md", description: "Durable shared preferences versus harness state; remote graph maintenance, provider text disclosure, authorization and full-backup limits.", includeInFull: false },+ { title: "Page history", path: "docs/guides/page-history.md", description: "Why a page changed: an optional reason on page writes, replaced_because in get_versions, the gbrain-reason commit trailer, remote visibility and repo-less brains.", includeInFull: false },{ title: "Brain versus session memory", path: "docs/guides/brain-vs-memory.md", description: "Route durable facts and preferences to shared memory, configuration to the harness, and temporary work to session state.", includeInFull: false },{ title: "Connect a hosted brain", path: "docs/guides/hosted-harness-access.md", description: "Getting the HTTPS endpoint (`gbrain mcp expose`, admin token file), host-side grants, private credential handoff, harness installation, profile repair, delegation limits and honest verification." },{ title: "Harness adapter reference", path: "docs/guides/harness-adapters.md", description: "Registry-generated transport, authentication lifetime and configuration facts.", includeInFull: false },diff --git a/skills/conventions/brain-first.md b/skills/conventions/brain-first.mdindex c6348669cf..40ed4ad76c 100644--- a/skills/conventions/brain-first.md+++ b/skills/conventions/brain-first.md@@ -192,3 +192,13 @@ until the canonical form lands. Silent typos would be the worst outcomeWhen in doubt: declare `brain_first: exempt` explicitly OR add thecanonical Convention callout near the top of the skill body. Both arezero-friction one-line operations.++## Recording why a page changed++When you edit a policy, contract, plan or any document page, pass `reason` on+`put_page` or `edit_page` with one line on why, in the user's words where you+have them ("Client asked for the 30-day window."). Edit the existing page with+its `expected_revision`; don't create a second page for a new edition.+`get_versions` shows each version's `replaced_because`. Never put a credential+in a reason: it can be pushed in a Git commit message, and gbrain refuses it.+Details: [page history](../../docs/guides/page-history.md#reasons).diff --git a/src/cli/main.ts b/src/cli/main.tsindex 9069c3803e..5923b7bc18 100755--- a/src/cli/main.ts+++ b/src/cli/main.ts@@ -1773,7 +1773,8 @@ export function formatResult(const truth = v.compiled_truth ?? v.title ?? '';const head = truth.slice(0, VERSION_TRUTH_PREVIEW_CHARS);const elided = truth.length > VERSION_TRUTH_PREVIEW_CHARS ? '...' : '';- return `#${v.id} ${v.snapshot_at?.toString().slice(0, 19) || '?'} ${head}${elided}`;+ const reason = typeof v.replaced_because === 'string' ? `\n changed because: ${v.replaced_because}` : '';+ return `#${v.id} ${v.snapshot_at?.toString().slice(0, 19) || '?'} ${head}${elided}${reason}`;}).join('\n') + '\n';}// MEMORY_VERBS v1 [F-E]: human-readable by default; trailing `--json`diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 670323c770..658df95074 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -859,6 +859,7 @@ export const NOTICE_CODES = {migrations_pending: { kind: 'safety', summary: 'Schema migrations are pending or failed to apply on this brain.' },socket_identity_mismatch: { kind: 'degraded', summary: 'The running serve\'s warm CLI socket refused this CLI call because an identity part (named, never its value) differs from the serve\'s, so the call ran on the slower cold path; doctor `cli_socket_refusals` counts these.' },sync_retry_failed_deprecated: { kind: 'coaching', summary: '`gbrain sync --retry-failed` is a deprecated alias for a plain sync, accepted for two releases: a plain sync retries a failure the previous run recorded by itself. Drop the flag.' },+ reason_not_committed: { kind: 'degraded', summary: 'A write\'s reason is in gbrain\'s page history but in no Git commit: on a non-strict source a newer write to the same file committed first, carrying only its own reason. Nothing needs fixing and retrying the write is wrong (docs/guides/page-history.md#reasons).' },sync_tail_degraded: { kind: 'degraded', summary: 'A managed sync ended synced, but its post-checkpoint tail (planner statistics, link extraction for the imported pages) failed, was cut off at its budget or did not start before the run\'s deadline; the step stays scheduled for the next sync, and the fix runs it now (`gbrain extract --stale --source-id <id>`, or doctor for the statistics).' },no_resident: { kind: 'degraded', summary: 'gbrain sync trigger recorded the request (and queued a job or nudged the serve), but no resident (gbrain serve, gbrain jobs work or the autopilot daemon) watches the source, so the recorded request waits until one starts or a sync reaches it; the fix syncs the checkout HEAD now (`gbrain sync --source <id> --no-pull`). docs/guides/on-commit-sync.md#no-resident' },no_worker: { kind: 'degraded', summary: 'A job was queued but no worker is running to execute it; it waits until a worker runs.' },diff --git a/src/core/operation-manifest.generated.ts b/src/core/operation-manifest.generated.tsindex abb2c1a536..dc699cee25 100644--- a/src/core/operation-manifest.generated.ts+++ b/src/core/operation-manifest.generated.ts@@ -477,6 +477,11 @@ export const OPERATION_MANIFEST: OperationMeta[] = ["type": "number","description": "Commit wait ms (0-30000, default 5000)."},+ "reason": {+ "type": "string",+ "description": "Why this change, one line (max 500 chars); kept in page history.",+ "fullSurfaceOnly": true+ },"source_kind": {"type": "string","description": "Server-set remotely.",@@ -903,6 +908,11 @@ export const OPERATION_MANIFEST: OperationMeta[] = ["request_id": {"type": "string","description": "Reuse only to retry."+ },+ "reason": {+ "type": "string",+ "description": "Why this change, one line (max 500 chars); kept in page history.",+ "fullSurfaceOnly": true}},"mutating": true,@@ -1005,6 +1015,11 @@ export const OPERATION_MANIFEST: OperationMeta[] = ["drop_timeline": {"type": "boolean","description": "Content without a Timeline section deletes its dated entries."+ },+ "reason": {+ "type": "string",+ "description": "Why this change, one line (max 500 chars); kept in page history.",+ "fullSurfaceOnly": true}}}@@ -2527,7 +2542,7 @@ export const OPERATION_MANIFEST: OperationMeta[] = ["outputRedaction": {"exempt": "full page version snapshots by slug; a page read governed by visibility like get_page (CEO-17)"},- "description": "Page version history, newest snapshot first: metadata only (id, snapshot_at, title, type, tags, frontmatter) for the newest 20 versions by default. Pass include_body: true for each version's compiled_truth and timeline, and a larger limit (at most 100 over MCP) for older versions. Trusted local and admin callers also get written_by and archived_by (who wrote each snapshot and whose write archived it). revert_version takes the id field.",+ "description": "Page version history, newest snapshot first: metadata only (id, snapshot_at, title, type, tags, frontmatter) for the newest 20 versions by default. Pass include_body: true for each version's compiled_truth and timeline, and a larger limit (at most 100 over MCP) for older versions. Trusted local and admin callers also get written_by and archived_by (who wrote each snapshot and whose write archived it). replaced_because is the reason given for the write that replaced the snapshot (null when none was given). revert_version takes the id field.","params": {"slug": {"type": "string",@@ -2598,6 +2613,11 @@ export const OPERATION_MANIFEST: OperationMeta[] = ["type": "number","required": true,"description": "Numeric version id to revert to, as returned by get_versions. Not a version NUMBER offset — pass the id field."+ },+ "reason": {+ "type": "string",+ "description": "Why this change, one line (max 500 chars); kept in page history.",+ "fullSurfaceOnly": true}},"mutating": true,diff --git a/src/core/ops/persistence.ts b/src/core/ops/persistence.tsindex 03309e3dee..72a4a5471a 100644--- a/src/core/ops/persistence.ts+++ b/src/core/ops/persistence.ts@@ -123,8 +123,13 @@ async function publicReceipt(ctx: OperationContext, row: WriteRequest, facts?: Wconst { cliRenderContext, renderAction } = await import('../agent-output.ts');const render = ctx.remote === false ? cliRenderContext() : { transport: 'stdio' as const, isCallable: () => false, preapproved: () => false };const { liveSearchable } = await import('../persistence/searchable.ts');+ const receipt = publicWriteReceipt(receiptFor(row, facts));+ // GBRA-217: a reason whose Git effect was superseded is reported as not committed.+ const settled = await (await import('../persistence/change-reason.ts')).settledReasonRecorded(ctx.engine, row);+ if (settled) ctx.emitNotice?.(settled.notice);return {- ...publicWriteReceipt(receiptFor(row, facts)),+ ...receipt,+ ...(settled ? { outcome: { ...receipt.outcome, reason_recorded: settled.recorded } } : {}),operation: row.operation, source_id: row.source_id, slug: row.slug,...await liveSearchable(ctx, { request_id: row.request_id, state: row.state, source_id: row.source_id, slug: row.slug, searchable: row.outcome?.searchable }),...(mismatch ? { owner_build: mismatch } : {}),diff --git a/src/core/persistence/change-reason.ts b/src/core/persistence/change-reason.tsindex 9802e81dc7..2d05e81924 100644--- a/src/core/persistence/change-reason.ts+++ b/src/core/persistence/change-reason.ts@@ -13,8 +13,9 @@ import { scanTextSpans } from '../secret-scan.ts';import { privatePagesFilterFragment } from '../search/private-visibility.ts';import type { GitCommitNote } from './effect-model.ts';import { sourceCanonicalGit } from './git-door.ts';-import type { WriteRequest } from './model.ts';+import type { SqlEngine, WriteRequest } from './model.ts';import type { PreparedMutation } from './coordinator.ts';+import type { Notice } from '../agent-output.ts';export const CHANGE_REASON_MAX = 500;export const CHANGE_REASON_OPERATIONS: readonly string[] = ['put_page', 'edit_page', 'revert_version'];@@ -95,3 +96,19 @@ export function withChangeReason(row: WriteRequest, prepared: PreparedMutation):return prepared;}++/**+ * A receipt's `reason_recorded` once its Git effect settled. A non-strict write's Git effect is superseded when a newer+ * write to the same file commits first: that commit carries only the newer write's note, so this reason is in page+ * history but in no commit. The receipt then says `git: 'superseded'` with a degraded `reason_not_committed` notice.+ * Nothing needs fixing, and retrying the write would be wrong.+ */+export async function settledReasonRecorded(engine: SqlEngine, row: Pick<WriteRequest, 'id' | 'outcome'>): Promise<{ recorded: ReasonRecorded; notice: Notice } | null> {+ const recorded = row.outcome?.reason_recorded as ReasonRecorded | undefined;+ if (recorded?.git !== 'queued') return null;+ const [git] = await engine.executeRaw<{ outcome: Record<string, unknown> | null }>(+ "SELECT outcome FROM persistence_effects WHERE request_id = $1::uuid AND kind = 'git' AND state = 'committed'", [row.id]);+ if (git?.outcome?.git !== 'superseded') return null;+ return { recorded: { ...recorded, git: 'superseded' }, notice: { code: 'reason_not_committed', kind: 'degraded',+ why: 'This write\'s reason is kept in gbrain\'s page history (get_versions replaced_because), but not in a Git commit: a newer write to the same file committed first, carrying only its own reason. Nothing needs fixing; do not retry the write.' } };+}diff --git a/src/core/persistence/params.ts b/src/core/persistence/params.tsindex 95a792d18a..e33d8dc402 100644--- a/src/core/persistence/params.ts+++ b/src/core/persistence/params.ts@@ -38,6 +38,7 @@ import { WRITE_REQUEST_STATES, WRITE_HEALTH_REASONS, WRITE_HEALTH_ASSESSMENTS, Wexport const REASON_PARAM: ParamDef = {type: 'string',description: 'Why this change, one line (max 500 chars); kept in page history.',+ fullSurfaceOnly: true,};export const WRITE_REQUEST_PARAM: ParamDef = {diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.jsonindex cce10da76a..bdb6d29b1c 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json@@ -385,6 +385,8 @@"raw_data.raw_data_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE","raw_data.raw_data_page_id_source_key": "u UNIQUE (page_id, source)","raw_data.raw_data_pkey": "p PRIMARY KEY (id)",+ "reason_purge_tombstones.reason_purge_tombstones_pkey": "p PRIMARY KEY (source_id, commit_sha, path)",+ "reason_purge_tombstones.reason_purge_tombstones_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","retrieval_event_links.retrieval_event_links_event_id_fkey": "f FOREIGN KEY (event_id) REFERENCES retrieval_events(id) ON DELETE CASCADE","retrieval_event_links.retrieval_event_links_pkey": "p PRIMARY KEY (event_id, source_id, edge_key, to_slug)","retrieval_event_pages.retrieval_event_pages_event_id_fkey": "f FOREIGN KEY (event_id) REFERENCES retrieval_events(id) ON DELETE CASCADE",@@ -939,6 +941,9 @@"raw_data": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "reason_purge_tombstones": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"retrieval_event_links": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -1455,6 +1460,7 @@"question_evidence_question_idx": "CREATE INDEX question_evidence_question_idx ON public.question_evidence USING btree (question_id, answer_revision)","raw_data_page_id_source_key": "CREATE UNIQUE INDEX raw_data_page_id_source_key ON public.raw_data USING btree (page_id, source)","raw_data_pkey": "CREATE UNIQUE INDEX raw_data_pkey ON public.raw_data USING btree (id)",+ "reason_purge_tombstones_pkey": "CREATE UNIQUE INDEX reason_purge_tombstones_pkey ON public.reason_purge_tombstones USING btree (source_id, commit_sha, path)","retrieval_event_links_pkey": "CREATE UNIQUE INDEX retrieval_event_links_pkey ON public.retrieval_event_links USING btree (event_id, source_id, edge_key, to_slug)","retrieval_event_pages_pkey": "CREATE UNIQUE INDEX retrieval_event_pages_pkey ON public.retrieval_event_pages USING btree (event_id, source_id, slug)","retrieval_events_pkey": "CREATE UNIQUE INDEX retrieval_events_pkey ON public.retrieval_events USING btree (id)",@@ -3215,7 +3221,9 @@"21 body_storage text/text NOT NULL DEFAULT 'inline'::text","22 body_generation bigint/int8 NULL","23 body_bytes bigint/int8 NULL",- "24 content_hash text/text NULL"+ "24 content_hash text/text NULL",+ "25 change_reason text/text NULL",+ "26 successor_pruned boolean/bool NULL"],"flags": "relkind=r rls=false force_rls=false"},@@ -3294,7 +3302,8 @@"51 truth_lead text/text NULL","52 timeline_lead text/text NULL","53 links_extract_failure jsonb/jsonb NULL",- "54 withheld_source_path text/text NULL"+ "54 withheld_source_path text/text NULL",+ "55 version_history_gap_at timestamp with time zone/timestamptz NULL"],"flags": "relkind=r rls=false force_rls=false"},@@ -3635,6 +3644,15 @@],"flags": "relkind=r rls=false force_rls=false"},+ "reason_purge_tombstones": {+ "columns": [+ "1 source_id text/text NOT NULL",+ "2 commit_sha text/text NOT NULL",+ "3 path text/text NOT NULL",+ "4 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ ],+ "flags": "relkind=r rls=true force_rls=false"+ },"retrieval_event_links": {"columns": ["1 event_id text/text NOT NULL",diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.jsonindex c9e850e28b..4c573b30ad 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json@@ -385,6 +385,8 @@"raw_data.raw_data_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE","raw_data.raw_data_page_id_source_key": "u UNIQUE (page_id, source)","raw_data.raw_data_pkey": "p PRIMARY KEY (id)",+ "reason_purge_tombstones.reason_purge_tombstones_pkey": "p PRIMARY KEY (source_id, commit_sha, path)",+ "reason_purge_tombstones.reason_purge_tombstones_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","retrieval_event_links.retrieval_event_links_event_id_fkey": "f FOREIGN KEY (event_id) REFERENCES retrieval_events(id) ON DELETE CASCADE","retrieval_event_links.retrieval_event_links_pkey": "p PRIMARY KEY (event_id, source_id, edge_key, to_slug)","retrieval_event_pages.retrieval_event_pages_event_id_fkey": "f FOREIGN KEY (event_id) REFERENCES retrieval_events(id) ON DELETE CASCADE",@@ -939,6 +941,9 @@"raw_data": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "reason_purge_tombstones": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"retrieval_event_links": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -1455,6 +1460,7 @@"question_evidence_question_idx": "CREATE INDEX question_evidence_question_idx ON public.question_evidence USING btree (question_id, answer_revision)","raw_data_page_id_source_key": "CREATE UNIQUE INDEX raw_data_page_id_source_key ON public.raw_data USING btree (page_id, source)","raw_data_pkey": "CREATE UNIQUE INDEX raw_data_pkey ON public.raw_data USING btree (id)",+ "reason_purge_tombstones_pkey": "CREATE UNIQUE INDEX reason_purge_tombstones_pkey ON public.reason_purge_tombstones USING btree (source_id, commit_sha, path)","retrieval_event_links_pkey": "CREATE UNIQUE INDEX retrieval_event_links_pkey ON public.retrieval_event_links USING btree (event_id, source_id, edge_key, to_slug)","retrieval_event_pages_pkey": "CREATE UNIQUE INDEX retrieval_event_pages_pkey ON public.retrieval_event_pages USING btree (event_id, source_id, slug)","retrieval_events_pkey": "CREATE UNIQUE INDEX retrieval_events_pkey ON public.retrieval_events USING btree (id)",@@ -3215,7 +3221,9 @@"21 body_storage text/text NOT NULL DEFAULT 'inline'::text","22 body_generation bigint/int8 NULL","23 body_bytes bigint/int8 NULL",- "24 content_hash text/text NULL"+ "24 content_hash text/text NULL",+ "25 change_reason text/text NULL",+ "26 successor_pruned boolean/bool NULL"],"flags": "relkind=r rls=false force_rls=false"},@@ -3294,7 +3302,8 @@"51 truth_lead text/text NULL","52 timeline_lead text/text NULL","53 links_extract_failure jsonb/jsonb NULL",- "54 withheld_source_path text/text NULL"+ "54 withheld_source_path text/text NULL",+ "55 version_history_gap_at timestamp with time zone/timestamptz NULL"],"flags": "relkind=r rls=false force_rls=false"},@@ -3635,6 +3644,15 @@],"flags": "relkind=r rls=false force_rls=false"},+ "reason_purge_tombstones": {+ "columns": [+ "1 source_id text/text NOT NULL",+ "2 commit_sha text/text NOT NULL",+ "3 path text/text NOT NULL",+ "4 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ ],+ "flags": "relkind=r rls=true force_rls=false"+ },"retrieval_event_links": {"columns": ["1 event_id text/text NOT NULL",diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.jsonindex b18a529863..0f793e5e32 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json@@ -385,6 +385,8 @@"raw_data.raw_data_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE","raw_data.raw_data_page_id_source_key": "u UNIQUE (page_id, source)","raw_data.raw_data_pkey": "p PRIMARY KEY (id)",+ "reason_purge_tombstones.reason_purge_tombstones_pkey": "p PRIMARY KEY (source_id, commit_sha, path)",+ "reason_purge_tombstones.reason_purge_tombstones_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","retrieval_event_links.retrieval_event_links_event_id_fkey": "f FOREIGN KEY (event_id) REFERENCES retrieval_events(id) ON DELETE CASCADE","retrieval_event_links.retrieval_event_links_pkey": "p PRIMARY KEY (event_id, source_id, edge_key, to_slug)","retrieval_event_pages.retrieval_event_pages_event_id_fkey": "f FOREIGN KEY (event_id) REFERENCES retrieval_events(id) ON DELETE CASCADE",@@ -939,6 +941,9 @@"raw_data": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "reason_purge_tombstones": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"retrieval_event_links": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -1451,6 +1456,7 @@"question_evidence_question_idx": "CREATE INDEX question_evidence_question_idx ON public.question_evidence USING btree (question_id, answer_revision)","raw_data_page_id_source_key": "CREATE UNIQUE INDEX raw_data_page_id_source_key ON public.raw_data USING btree (page_id, source)","raw_data_pkey": "CREATE UNIQUE INDEX raw_data_pkey ON public.raw_data USING btree (id)",+ "reason_purge_tombstones_pkey": "CREATE UNIQUE INDEX reason_purge_tombstones_pkey ON public.reason_purge_tombstones USING btree (source_id, commit_sha, path)","retrieval_event_links_pkey": "CREATE UNIQUE INDEX retrieval_event_links_pkey ON public.retrieval_event_links USING btree (event_id, source_id, edge_key, to_slug)","retrieval_event_pages_pkey": "CREATE UNIQUE INDEX retrieval_event_pages_pkey ON public.retrieval_event_pages USING btree (event_id, source_id, slug)","retrieval_events_pkey": "CREATE UNIQUE INDEX retrieval_events_pkey ON public.retrieval_events USING btree (id)",@@ -3211,7 +3217,9 @@"21 body_storage text/text NOT NULL DEFAULT 'inline'::text","22 body_generation bigint/int8 NULL","23 body_bytes bigint/int8 NULL",- "24 content_hash text/text NULL"+ "24 content_hash text/text NULL",+ "25 change_reason text/text NULL",+ "26 successor_pruned boolean/bool NULL"],"flags": "relkind=r rls=false force_rls=false"},@@ -3290,7 +3298,8 @@"51 truth_lead text/text NULL","52 timeline_lead text/text NULL","53 links_extract_failure jsonb/jsonb NULL",- "54 withheld_source_path text/text NULL"+ "54 withheld_source_path text/text NULL",+ "55 version_history_gap_at timestamp with time zone/timestamptz NULL"],"flags": "relkind=r rls=false force_rls=false"},@@ -3631,6 +3640,15 @@],"flags": "relkind=r rls=false force_rls=false"},+ "reason_purge_tombstones": {+ "columns": [+ "1 source_id text/text NOT NULL",+ "2 commit_sha text/text NOT NULL",+ "3 path text/text NOT NULL",+ "4 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ ],+ "flags": "relkind=r rls=true force_rls=false"+ },"retrieval_event_links": {"columns": ["1 event_id text/text NOT NULL",diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.jsonindex 32a61f5aac..3b8191fc87 100644--- a/test/fixtures/goldens/migrations/records.json+++ b/test/fixtures/goldens/migrations/records.json@@ -1,6 +1,6 @@{"golden": {- "count": 273,+ "count": 274,"gaps": [17,18,@@ -92,7 +92,7 @@"verifyProjectionStatistics": "0d231b04ecfbc5a4109d6fca9567bf4e8c9e9db6c3fbbb35212e026579ed6f67","withSchemaLockTimeout": "95605bd3004955e11e936c7a4aa6889319b401098abf9db18ef3e48da2c3fc59"},- "latest": 278,+ "latest": 279,"records": [{"handler": {@@ -4518,6 +4518,19 @@"transaction": "absent","verify": "absent","version": 278+ },+ {+ "handler": "absent",+ "idempotent": true,+ "name": "page_change_reasons",+ "sql": {+ "length": 798,+ "sha256": "de2c9cb2f617e8d250b9e2b7cc786ed74f1fece1232b56e8073ded60e24bd5a3"+ },+ "sqlFor": "absent",+ "transaction": "absent",+ "verify": "absent",+ "version": 279}],"versions": [@@ -4793,7 +4806,8 @@275,276,277,- 278+ 278,+ 279]},"normalizer": "migrations-record-v1"diff --git a/test/page-change-reason-gbra217.test.ts b/test/page-change-reason-gbra217.test.tsindex b97edcc7eb..db26e98ef2 100644--- a/test/page-change-reason-gbra217.test.ts+++ b/test/page-change-reason-gbra217.test.ts@@ -7,38 +7,32 @@* 2. Fails when: a reason is lost or lands on the wrong snapshot, a refused reason (too long, a secret) is stored in any* journal row, the replay identity ignores the reason, or a remote reader is shown a reason whose successor snapshot* is private or was pruned.- * 3. No new seam: the real put_page / edit_page / revert_version / put_pages / get_versions handlers over PGLite.+ * 3. No new seam: the real put_page / edit_page / revert_version / put_pages / get_versions handlers over PGLite, and over Postgres when DATABASE_URL is set (test/postgres-unit-arms.txt).*/import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';-import { PGLiteEngine } from '../src/core/pglite-engine.ts';-import { resetPgliteState } from './helpers/reset-pglite.ts';+import type { BrainEngine } from '../src/core/engine.ts';import { operationsByName, OperationError, type OperationContext } from '../src/core/operations.ts';import { canonicalChangeReason, CHANGE_REASON_MAX } from '../src/core/persistence/change-reason.ts';-import { resetGateway } from '../src/core/ai/gateway.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';-let engine: PGLiteEngine;--beforeAll(async () => {- engine = new PGLiteEngine();- await engine.connect({});- await engine.initSchema();-}, 120_000);-afterAll(async () => { await engine.disconnect(); resetGateway(); });-beforeEach(async () => { await resetPgliteState(engine); resetGateway(); });+let engine: BrainEngine;+let SLUG = '';+let run = 0;function ctx(remote = false): OperationContext {- return { engine, config: { engine: 'pglite' as const }, logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote, sourceId: 'default' } as OperationContext;+ return { engine, config: { engine: engine.kind }, logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote, sourceId: 'default' } as OperationContext;}const call = (name: string, params: Record<string, unknown>, remote = false) =>operationsByName[name]!.handler(ctx(remote), params) as Promise<Record<string, unknown>>;const page = (body: string, extra = '') => `---\ntitle: Policy\ntype: note\n${extra}---\n\n${body}\n`;-const SLUG = 'policies/policy-4a-example';const outcomeOf = (result: Record<string, unknown>) => (result.outcome ?? result) as Record<string, unknown>;-async function revision(slug = SLUG): Promise<string> {- return String((await call('get_page', { slug, include_content: true })).revision);+async function revision(slug?: string): Promise<string> {+ return String((await call('get_page', { slug: slug ?? SLUG, include_content: true })).revision);}-async function versions(remote = false, slug = SLUG): Promise<Array<Record<string, unknown>>> {- return await call('get_versions', { slug }, remote) as unknown as Array<Record<string, unknown>>;+async function versions(remote = false, slug?: string): Promise<Array<Record<string, unknown>>> {+ return await call('get_versions', { slug: slug ?? SLUG }, remote) as unknown as Array<Record<string, unknown>>;}async function journalHolds(text: string): Promise<boolean> {const rows = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM persistence_requests WHERE intent::text LIKE $1 OR outcome::text LIKE $1`, [`%${text}%`]);@@ -46,7 +40,12 @@ async function journalHolds(text: string): Promise<boolean> {return rows[0]!.n + effects[0]!.n > 0;}-describe('page change reasons on a repo-less brain', () => {+for (const backend of testBackends()) describe(`[${backend}] page change reasons on a repo-less brain`, () => {+ let close: () => Promise<void>;+ beforeAll(async () => { ({ engine, close } = await isolatedSharedSkillsEngine(backend === 'postgres' ? requirePostgresTestDatabase() : undefined)); }, 120_000);+ afterAll(async () => { await disposePersistenceConsumer(engine); await close(); });+ beforeEach(() => { SLUG = `policies/policy-4a-example-${++run}`; });+test('a reason lands on the snapshot its write archived; creation and a reasonless write are reported', async () => {const created = outcomeOf(await call('put_page', { slug: SLUG, content: page('Edition one.'), reason: 'First edition from the board.', wait_ms: 30_000 }));expect(created.reason_recorded).toEqual({ reason: 'First edition from the board.', version: false, version_why: 'page_created', git: 'no_repository' });@@ -88,9 +87,9 @@ describe('page change reasons on a repo-less brain', () => {expect((await engine.executeRaw('SELECT 1 FROM pages WHERE slug = $1', [SLUG])).length).toBe(0);const batch = await call('put_pages', { request_id: crypto.randomUUID(), pages: [- { slug: 'notes/a-example', content: page('a'), reason: 'fine' }, { slug: 'notes/b-example', content: page('b'), reason: `token ${secret}` }] }).then(() => null, e => e);- expect((batch as OperationError).message).toContain('pages[1] (notes/b-example)');- expect((await engine.executeRaw("SELECT 1 FROM pages WHERE slug LIKE 'notes/%'")).length).toBe(0);+ { slug: `notes/a-example-${run}`, content: page('a'), reason: 'fine' }, { slug: `notes/b-example-${run}`, content: page('b'), reason: `token ${secret}` }] }).then(() => null, e => e);+ expect((batch as OperationError).message).toContain(`pages[1] (notes/b-example-${run})`);+ expect((await engine.executeRaw('SELECT 1 FROM pages WHERE slug LIKE $1', [`notes/%-example-${run}`])).length).toBe(0);expect(await journalHolds(secret)).toBe(false);});@@ -103,17 +102,17 @@ describe('page change reasons on a repo-less brain', () => {});test('put_pages items carry their own reasons; equal repeats coalesce and different ones conflict', async () => {- await call('put_pages', { request_id: crypto.randomUUID(), wait_ms: 30_000, pages: [{ slug: 'notes/a-example', content: page('a1') }, { slug: 'notes/b-example', content: page('b1') }] });- const a = await revision('notes/a-example'), b = await revision('notes/b-example');+ await call('put_pages', { request_id: crypto.randomUUID(), wait_ms: 30_000, pages: [{ slug: `notes/a-example-${run}`, content: page('a1') }, { slug: `notes/b-example-${run}`, content: page('b1') }] });+ const a = await revision(`notes/a-example-${run}`), b = await revision(`notes/b-example-${run}`);const result = await call('put_pages', { request_id: crypto.randomUUID(), wait_ms: 30_000, pages: [- { slug: 'notes/a-example', content: page('a2'), expected_revision: a, reason: 'reason a' },- { slug: 'notes/b-example', content: page('b2'), expected_revision: b, reason: 'reason b' },- { slug: 'notes/b-example', content: page('b2'), expected_revision: b, reason: 'reason b' }] });+ { slug: `notes/a-example-${run}`, content: page('a2'), expected_revision: a, reason: 'reason a' },+ { slug: `notes/b-example-${run}`, content: page('b2'), expected_revision: b, reason: 'reason b' },+ { slug: `notes/b-example-${run}`, content: page('b2'), expected_revision: b, reason: 'reason b' }] });const entries = result.pages as Array<Record<string, unknown>>;expect(entries[0]!.reason_recorded).toMatchObject({ reason: 'reason a', version: true });- expect((await versions(false, 'notes/b-example'))[0]!.replaced_because).toBe('reason b');+ expect((await versions(false, `notes/b-example-${run}`))[0]!.replaced_because).toBe('reason b');const differ = await call('put_pages', { request_id: crypto.randomUUID(), wait_ms: 30_000, pages: [- { slug: 'notes/c-example', content: page('c'), reason: 'one' }, { slug: 'notes/c-example', content: page('c'), reason: 'two' }] });+ { slug: `notes/c-example-${run}`, content: page('c'), reason: 'one' }, { slug: `notes/c-example-${run}`, content: page('c'), reason: 'two' }] });expect((differ.pages as Array<Record<string, unknown>>).map(entry => entry.state)).toEqual(['refused', 'refused']);});@@ -133,6 +132,26 @@ describe('page change reasons on a repo-less brain', () => {expect((await versions(false))[0]!.replaced_because).toBe('third edition');});+ test('a real prune marks the survivor: a pruned private successor withholds the world predecessor\'s reason remotely', async () => {+ const big = 'x'.repeat(1024 ** 2 + 16);+ const write = async (body: string, visibility?: string) => {+ await engine.putPage(SLUG, { type: 'note', title: 'Policy', compiled_truth: body, frontmatter: visibility ? { visibility } : {} });+ await engine.createVersion(SLUG, { sourceId: 'default' });+ };+ await write('small world edition');+ await engine.executeRaw("UPDATE page_versions SET change_reason = 'made it private' WHERE id = (SELECT max(pv.id) FROM page_versions pv JOIN pages p ON p.id = pv.page_id WHERE p.slug = $1)", [SLUG]);+ await write(big, 'private');+ for (let i = 0; i < 5; i++) await write(big + i);+ const kept = await engine.executeRaw<{ visibility: string | null; successor_pruned: boolean | null; change_reason: string | null }>(+ `SELECT pv.frontmatter->>'visibility' AS visibility, pv.successor_pruned, pv.change_reason FROM page_versions pv JOIN pages p ON p.id = pv.page_id WHERE p.slug = $1 ORDER BY pv.id`, [SLUG]);+ expect(kept.map(row => row.visibility)).toEqual([null, null, null, null, null, null]);+ expect(kept[0]).toMatchObject({ successor_pruned: true, change_reason: 'made it private' });+ const [gap] = await engine.executeRaw<{ gap: unknown }>('SELECT version_history_gap_at AS gap FROM pages WHERE slug = $1', [SLUG]);+ expect(gap!.gap).not.toBeNull();+ expect((await versions(false)).at(-1)!.replaced_because).toBe('made it private');+ expect((await versions(true)).at(-1)!.replaced_because).toBeNull();+ }, 60_000);+test('canonicaliser bounds', () => {expect(canonicalChangeReason(' a\tb\r\nc\u0007 d ')).toBe('a b c d');expect(canonicalChangeReason(' \n ')).toBeNull();diff --git a/test/page-change-reason-git-gbra217.test.ts b/test/page-change-reason-git-gbra217.test.tsnew file mode 100644index 0000000000..e9e167277e--- /dev/null+++ b/test/page-change-reason-git-gbra217.test.ts@@ -0,0 +1,161 @@+/**+ * GBRA-217: a page write's reason reaches Git as a path-mapped trailer, `gbrain-reason: <path>: <text>`.+ *+ * 1. Protects: the door (strict) and the effect commit (non-strict) put one trailer per path, beside a repair's+ * `gbrain-repair:` trailer in the same block, so `git interpret-trailers --parse` returns every one; a write without+ * a reason commits the same message as before; a private page's reason is in no commit message, a group commit for+ * other paths included; a non-strict write whose Git effect is superseded never lends its reason to the newer+ * commit and its receipt says so (`reason_not_committed`); a message too large for the command line goes through+ * a message file.+ * 2. Fails when: a trailer is lost, merged or misattributed, the message of a reasonless write changes, a private reason+ * reaches Git, or a large group commit fails on the argument limit.+ * 3. Seams: none. Real repositories, the real door and effect commit, real engines (Postgres through+ * test/e2e/page-change-reason-git-gbra217-postgres.test.ts).+ */+import { afterEach, describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { randomUUID } from 'node:crypto';+import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join } from 'node:path';+import { operationsByName, type OperationContext } from '../src/core/operations.ts';+import { commitGitTargets, commitMessage, commitMessageArgs, COMMIT_MESSAGE_ARG_BYTES } from '../src/core/persistence/effect-git.ts';+import type { GitCommitNote } from '../src/core/persistence/effect-model.ts';+import { commitThroughDoor } from '../src/core/persistence/git-door.ts';+import { hashFile } from '../src/core/persistence/large-file.ts';+import { withReasonNote } from '../src/core/persistence/change-reason.ts';+import { gitChildEnv } from '../src/core/git-env.ts';+import type { Notice } from '../src/core/agent-output.ts';+import { durableGitRepo } from './helpers/git-publication.ts';+import { managedBrain, settleManagedGitEffects } from './helpers/managed-brain.ts';+import { strictSource } from './helpers/strict-door-audit.ts';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';++const env = gitChildEnv();+const raw = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], env });+const git = (root: string, ...args: string[]) => raw(root, ...args).trim();+/** A sandbox's git wrapper may append a co-author trailer to every `git commit` (never to commit-tree): read without it. */+const unshimmed = (message: string) => message.replace(/^Co-authored-by: .*\n/gm, '').replace(/\n+$/, '\n');+const parsed = (root: string, ref = 'HEAD') => execFileSync('git', ['-C', root, 'interpret-trailers', '--parse'], { input: raw(root, 'log', '-1', '--format=%B', ref), encoding: 'utf8', env })+ .split('\n').filter(line => line && !line.startsWith('Co-authored-by:'));+const roots: string[] = [];+function repo(files: Record<string, string>): string {+ const top = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-reason-git-')));+ roots.push(top);+ git(top, 'init', '-q', '-b', 'main');+ git(top, 'config', 'user.name', 'Example Writer'); git(top, 'config', 'user.email', '[email protected]');+ for (const [path, body] of Object.entries(files)) put(top, path, body);+ git(top, 'add', '-A'); git(top, 'commit', '-qm', 'seed');+ return top;+}+function put(root: string, path: string, body: string): void {+ mkdirSync(dirname(join(root, path)), { recursive: true });+ writeFileSync(join(root, path), body);+}+afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); });++describe('reason trailers in commit messages', () => {+ const repair: GitCommitNote = { subject: 'gbrain: repair notes/a.md', line: 'notes/a.md (invalid_fence)', trailers: ['gbrain-repair: invalid_fence deterministic high'] };+ const notes = new Map<string, GitCommitNote>([+ ['notes/a.md', withReasonNote('notes/a.md', 'Fence fixed: status: done', repair)],+ ['notes/b.md', withReasonNote('notes/b.md', 'Client asked for the 30-day window.')],+ ]);++ test('door and effect commits agree, alone and in a group; interpret-trailers returns every reason and repair trailer', async () => {+ const seed = { 'notes/a.md': 'a\n', 'notes/b.md': 'b\n', 'notes/c.md': 'c\n' };+ for (const paths of [['notes/a.md'], ['notes/b.md'], ['notes/a.md', 'notes/b.md', 'notes/c.md']]) {+ const porcelain = repo(seed), plumbing = repo(seed);+ for (const root of [porcelain, plumbing]) for (const path of paths) put(root, path, `${path}, second revision\n`);+ const noted = new Map(paths.flatMap(path => notes.has(path) ? [[path, notes.get(path)!] as const] : []));+ await commitGitTargets(porcelain, paths, undefined, noted);+ await commitThroughDoor(plumbing, paths.map(path => ({ path: join(plumbing, path), planned: hashFile(join(plumbing, path)), note: noted.get(path) })));+ expect(unshimmed(raw(plumbing, 'log', '-1', '--format=%B'))).toBe(unshimmed(raw(porcelain, 'log', '-1', '--format=%B')));+ const want = [+ ...(paths.includes('notes/a.md') ? ['gbrain-repair: invalid_fence deterministic high', 'gbrain-reason: notes/a.md: Fence fixed: status: done'] : []),+ ...(paths.includes('notes/b.md') ? ['gbrain-reason: notes/b.md: Client asked for the 30-day window.'] : []),+ ];+ for (const root of [porcelain, plumbing]) expect(parsed(root)).toEqual(want);+ }+ });++ test('a message over the argument bound goes through a message file and commits the same text', async () => {+ const paths = Array.from({ length: 30 }, (_, i) => `notes/p${String(i).padStart(2, '0')}.md`);+ const noted = new Map(paths.map(path => [path, withReasonNote(path, 'r'.repeat(480))] as const));+ const paragraphs = commitMessage(paths, noted);+ expect(Buffer.byteLength(paragraphs.join('\n\n'))).toBeGreaterThan(COMMIT_MESSAGE_ARG_BYTES);+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-reason-msg-')); roots.push(dir);+ expect(commitMessageArgs(paragraphs, dir)[0]).toBe('-F');+ expect(commitMessageArgs(['small'], dir)).toEqual(['-m', 'small']);+ const seed = Object.fromEntries(paths.map(path => [path, 'x\n']));+ const porcelain = repo(seed), plumbing = repo(seed);+ for (const root of [porcelain, plumbing]) for (const path of paths) put(root, path, 'y\n');+ await commitGitTargets(porcelain, paths, undefined, noted);+ await commitThroughDoor(plumbing, paths.map(path => ({ path: join(plumbing, path), planned: hashFile(join(plumbing, path)), note: noted.get(path) })));+ for (const root of [porcelain, plumbing]) expect(parsed(root)).toHaveLength(30);+ expect(unshimmed(raw(plumbing, 'log', '-1', '--format=%B'))).toBe(unshimmed(raw(porcelain, 'log', '-1', '--format=%B')));+ });+});++const setup = ({ root }: { root: string }) => { writeFileSync(join(root, '.gitignore'), '\n'); durableGitRepo(root, ['.gitignore']); };+const page = (body: string, extra = '') => `---\ntype: note\ntitle: Policy\n${extra}---\n\n${body}\n`;+const SLUG = 'policies/policy-4a-example';+const call = (ctx: OperationContext, name: string, params: Record<string, unknown>) => operationsByName[name]!.handler(ctx, params) as Promise<Record<string, unknown>>;+const outcomeOf = (result: Record<string, unknown>) => (result.outcome ?? result) as Record<string, unknown>;+const revision = async (ctx: OperationContext, slug = SLUG) => String((await ctx.engine.readPageSnapshot(slug, { sourceId: 'default' }))!.revision);++for (const backend of testBackends()) {+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;+ describe(`[${backend}] reasons reach Git`, () => {+ for (const strict of [false, true]) {+ test(`${strict ? 'strict' : 'non-strict'}: the commit carries the trailer, a reasonless write's message is unchanged`, () => managedBrain(async ({ engine, ctx, root }) => {+ if (strict) await strictSource(engine);+ await call(ctx, 'put_page', { slug: SLUG, content: page('Edition one.'), request_id: randomUUID() });+ await settleManagedGitEffects(engine);+ const plain = unshimmed(raw(root, 'log', '-1', '--format=%B'));+ await call(ctx, 'put_page', { slug: SLUG, content: page('Edition one, corrected.'), expected_revision: await revision(ctx), request_id: randomUUID() });+ await settleManagedGitEffects(engine);+ expect(unshimmed(raw(root, 'log', '-1', '--format=%B'))).toBe(plain);+ const result = outcomeOf(await call(ctx, 'put_page', { slug: SLUG, content: page('Edition two.'), expected_revision: await revision(ctx), request_id: randomUUID(), reason: 'Client asked for the 30-day window.' }));+ expect((result.reason_recorded as Record<string, unknown>).git).toBe(strict ? 'committed' : 'queued');+ await settleManagedGitEffects(engine);+ expect(parsed(root)).toEqual([`gbrain-reason: ${SLUG}.md: Client asked for the 30-day window.`]);+ expect(unshimmed(raw(root, 'log', '-1', '--format=%B')).split('\n')[0]).toBe(plain.split('\n')[0]);+ }, { databaseUrl, setup }), 120_000);++ test(`${strict ? 'strict' : 'non-strict'}: a private page's reason is in no commit message`, () => managedBrain(async ({ engine, ctx, root }) => {+ if (strict) await strictSource(engine);+ await call(ctx, 'put_pages', { request_id: randomUUID(), wait_ms: 30_000, pages: [+ { slug: 'notes/world-example', content: page('w1') }, { slug: 'notes/private-example', content: page('p1', 'visibility: private\n') }] });+ await settleManagedGitEffects(engine);+ await call(ctx, 'put_pages', { request_id: randomUUID(), wait_ms: 30_000, pages: [+ { slug: 'notes/world-example', content: page('w2'), expected_revision: await revision(ctx, 'notes/world-example'), reason: 'world reason' },+ { slug: 'notes/private-example', content: page('p2', 'visibility: private\n'), expected_revision: await revision(ctx, 'notes/private-example'), reason: 'private-only reason' }] });+ await settleManagedGitEffects(engine);+ await call(ctx, 'put_page', { slug: 'notes/world-example', content: page('w3', 'visibility: private\n'), expected_revision: await revision(ctx, 'notes/world-example'), request_id: randomUUID(), reason: 'turned private reason' });+ await settleManagedGitEffects(engine);+ const history = raw(root, 'log', '--all', '--format=%B');+ expect(history).toContain('gbrain-reason: notes/world-example.md: world reason');+ expect(history).not.toContain('private-only reason');+ expect(history).not.toContain('turned private reason');+ const versions = await call(ctx, 'get_versions', { slug: 'notes/private-example' }) as unknown as Array<Record<string, unknown>>;+ expect(versions[0]!.replaced_because).toBe('private-only reason');+ }, { databaseUrl, setup }), 120_000);+ }++ test('non-strict: a superseded Git effect never lends its reason to the newer commit; its receipt says so', () => managedBrain(async ({ engine, ctx, root }) => {+ await call(ctx, 'put_page', { slug: SLUG, content: page('Edition one.'), request_id: randomUUID() });+ await settleManagedGitEffects(engine);+ const first = randomUUID();+ await call(ctx, 'put_page', { slug: SLUG, content: page('Edition two.'), expected_revision: await revision(ctx), request_id: first, reason: 'first write reason' });+ await call(ctx, 'put_page', { slug: SLUG, content: page('Edition three.'), expected_revision: await revision(ctx), request_id: randomUUID() });+ await settleManagedGitEffects(engine);+ expect(raw(root, 'log', '--all', '--format=%B')).not.toContain('first write reason');+ const notices: Notice[] = [];+ const receipt = await operationsByName.get_write_request!.handler({ ...ctx, emitNotice: (n: Notice) => { notices.push(n); } } as OperationContext, { request_id: first }) as Record<string, unknown>;+ expect((receipt.outcome as Record<string, unknown>).reason_recorded).toMatchObject({ reason: 'first write reason', git: 'superseded' });+ expect(notices.map(n => n.code)).toContain('reason_not_committed');+ const versions = await call(ctx, 'get_versions', { slug: SLUG }) as unknown as Array<Record<string, unknown>>;+ expect(versions.map(v => v.replaced_because)).toEqual([null, 'first write reason']);+ }, { databaseUrl, setup }), 120_000);+ });+}diff --git a/test/page-change-reason-mcp-gbra217.test.ts b/test/page-change-reason-mcp-gbra217.test.tsnew file mode 100644index 0000000000..0e0859fce7--- /dev/null+++ b/test/page-change-reason-mcp-gbra217.test.ts@@ -0,0 +1,54 @@+/**+ * GBRA-217 A-T10: the reason flow as a remote agent drives it over MCP (remote=true, a scoped writer).+ *+ * 1. Protects: put_page with a reason, a second edition with its own reason, then get_versions, through the real MCP+ * dispatcher: the second edition's reason reads back as the newest version's replaced_because, each write result+ * carries reason_recorded, and a refused reason comes back as the typed envelope without its value.+ * 2. Fails when: the dispatcher drops or rejects `reason`, the result loses reason_recorded, or the refusal echoes the+ * reason.+ * 3. No new seam: dispatchToolCall over PGLite on a repo-less brain (no repository configured).+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdtempSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { dispatchToolCall, type ToolResult } from '../src/mcp/dispatch.ts';+import { registerLocalWriter, withVerifiedLocalRegistration } from '../src/core/persistence/identity.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { withEnv } from './helpers/with-env.ts';++let engine: PGLiteEngine;+beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 120_000);+afterAll(async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); });++const body = (result: ToolResult) => JSON.parse(result.content[0]!.text) as Record<string, any>;+const page = (text: string) => `---\ntitle: Refund policy\ntype: note\n---\n\n${text}\n`;++describe('A-T10: reasons over MCP, remote=true', () => {+ test('put_page with a reason, a second edition, then get_versions', async () => {+ await withEnv({ GBRAIN_HOME: mkdtempSync(join(tmpdir(), 'gbra217-mcp-')) }, async () => {+ const registration = await registerLocalWriter(engine, 'stdio', { sourceIds: ['*'], operations: null, scopes: ['read', 'write'], slugPrefixes: ['policies'] });+ const auth = { token: 'fixture', clientId: 'fixture-client', scopes: ['read', 'write'], sourceId: 'default', boundSlugPrefixes: ['policies'] };+ const call = (name: string, params: Record<string, unknown>) => withVerifiedLocalRegistration(engine, registration, () => dispatchToolCall(engine, name, params,+ { remote: true, config: { engine: 'pglite' }, sourceId: 'default', auth, logger: { info() {}, warn() {}, error() {} }, writeWaitMs: 30_000 }));+ const slug = 'policies/refunds-example';+ const created = await call('put_page', { slug, content: page('Refunds within 14 days.'), request_id: randomUUID(), reason: 'First edition.' });+ expect(created.isError).toBeFalsy();+ expect(JSON.stringify(body(created))).toContain('"page_created"');+ const read = body(await call('get_page', { slug, include_content: true }));+ const second = await call('put_page', { slug, content: page('Refunds within 30 days.'), expected_revision: read.revision, request_id: randomUUID(), reason: 'Client asked for the 30-day window.' });+ expect(second.isError).toBeFalsy();+ expect(JSON.stringify(body(second))).toContain('"no_repository"');+ const versions = body(await call('get_versions', { slug })) as unknown as Array<Record<string, unknown>>;+ expect(versions[0]!.replaced_because).toBe('Client asked for the 30-day window.');++ const secret = 'ghp_' + 'Z9y8X7w6V5u4T3s2R1q0P9o8N7m6L5k4J3i2';+ const refused = await call('put_page', { slug, content: page('x'), request_id: randomUUID(), reason: `new token ${secret}` });+ expect(refused.isError).toBe(true);+ expect(body(refused)).toMatchObject({ error: 'invalid_params', code: 'change_reason_rejected', reason: 'reason_contains_secret' });+ expect(refused.content[0]!.text).not.toContain(secret);+ });+ }, 120_000);+});