Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
docs: database-canonical memory design, revision 3 (autoplan round 2)
garrytanaadde16c5371
diff --git a/docs/designs/DATABASE_CANONICAL_MEMORY.md b/docs/designs/DATABASE_CANONICAL_MEMORY.mdindex 297993f775..a8c47eb527 100644--- a/docs/designs/DATABASE_CANONICAL_MEMORY.md+++ b/docs/designs/DATABASE_CANONICAL_MEMORY.md@@ -1,7 +1,7 @@# The database as the source of truth for agent-written memoryStatus: design only, no production change. Every switch named here ships off.-Revision: 2, after the gstack /autoplan review (see "Review record").+Revision: 3, after two rounds of the gstack /autoplan review (see "Review record").Author: GBRA-176 (GBrain Minder crew). Review: see "Review record" at the end.Citation convention: repo-relative paths on master b247a4c4 (v0.60.361.0).@@ -191,7 +191,7 @@ of record for pages agents also write.| Store | Written by | How ||---|---|---|| Database (pages, versions, fence rows, tags, links, timeline) | every agent and server, connectors, dream/cycle phases, the import lane | the existing journaled write path (`put_page`, `capture`, `remember`, maintenance requests, connector checkpoints), published database-only for this source through a dedicated publication branch (below) |-| Page files in the source checkout | the source's exporter, nothing else in gbrain | an export target on the existing Git effect, batched, compare-before-replace against the export ledger |+| Page files in the source checkout | the source's exporter, nothing else in gbrain | a per-source export outbox drained in batches, each batch committed through one Git effect, compare-before-replace against the export ledger || Git commits touching page paths | the exporter | one commit per batch, then a push under the existing publish lock || Non-page files (`AGENTS.md`, scripts, notes outside the source's page roots) | the operator, as today | plain git or `gbrain git commit-push` || Edits to page files made outside gbrain | a person (or a straggling agent) in the checkout or another clone | never written to the database directly: the import lane turns each one into a revision-checked page write, or into a conflict |@@ -251,8 +251,10 @@ source's mode and a mode epoch:exactly as today (grants, slug fences, expected revision, idempotentreplay, attribution), but carry no worktree id, take no worktree lock andwrite no recovery record;-- the publication transaction enqueues an export target for the page; the- page gets no `database_only_reason`, because it is meant to be exported;+- the page gets no `database_only_reason`, because it is meant to be+ exported; the export target is not enqueued by the writer at all (see+ "Driven by the database" below), so publication requests stay worktree-free+ and a target survives the owner or its binding being unavailable;- a write from any authorized host commits while the export owner is stopped,its checkout is missing, or an export batch holds the worktree lock.@@ -266,24 +268,38 @@ branch that only a source in database mode reaches.worktree lease. Losing the lease stops it; it never takes over on a staleheartbeat. On PGLite without a resident, the one-shot command that committeda write drains its export targets before it exits.-- **An extension of the Git effect, not a new effect kind.** The Git effect- already commits page paths, parks after repeated failures and is known to- every checkout-touching consumer (worktree refresh, convergence, parking,- restore; `src/core/persistence/worktree-refresh-schema.ts:45`). Database-rendered- targets reuse that registration instead of adding a sixth kind that each- consumer would have to learn.-- **Driven by the journal.** Every committed change that affects a- database-canonical page's rendering enqueues a target: page writes, and the- fan-out mutations that touch several pages at once (a `forget` that strikes a- fact on many pages, purges, renames, visibility changes). Targets for the- same path coalesce to the newest revision. The withdrawal mirror is replaced- by export work for these sources.+- **Driven by the database, not by writers.** An AFTER trigger on `pages`+ (a change of knowledge revision, slug, visibility or `deleted_at`) and on+ fact withdrawals upserts the page into a per-source **export outbox** keyed+ by (source_id, page_id), for sources in database mode only. Every writer is+ covered without knowing about export: journaled requests, the roughly thirty+ direct coordinated writers that change rendered content without a request,+ fan-out mutations (a `forget` across many pages, purges, renames), and an+ old binary's write. The outbox coalesces repeated writes to one row per+ page, so 10,000 writes with the exporter stopped are 10,000 upserts and no+ growing effect queue; export lag reads the outbox. A sweep that compares+ ledger revisions with page revisions catches anything the trigger missed.+ For these sources no writer inserts withdrawal-mirror or per-request Git+ effects; the implementation enumerates every effect-inserting writer+ (withdrawal, purge, rename, visibility, connector checkpoints, segmented+ repair) and routes it by source mode.+- **One Git effect per batch.** The exporter turns a drained outbox batch+ into one Git effect, so it keeps the registration every checkout-touching+ consumer already knows (worktree refresh, convergence, parking, restore;+ `src/core/persistence/worktree-refresh-schema.ts:45`) without one effect row+ per write holding reservations and receipts open while the exporter is down.+ The effect carries the source's mode epoch and binding generation, so a+ transfer or a flip invalidates it rather than completing it falsely.- **Eligibility is one predicate.** A new `exportEligible(page, source)`decides what may reach a tracked path: not private or alias-private, notunder a `storage.db_only` prefix, not detached, not in an import-only mirror.- It is evaluated when a batch renders, not when the target was queued, so a- page that became private after its target was queued is never published and- its existing file is removed in that batch. No current reader provides this:+ It is evaluated when a batch renders, and the batch manifest records the+ eligibility generation it saw. Visibility changes bump that generation in+ the same transaction, and the exporter rechecks it after the commit and+ again immediately before the push; a batch whose generation moved is+ re-rendered, never pushed. So a page that becomes private after rendering,+ between commit and push, or during recovery never reaches the remote, and+ its existing file is removed in the next batch. No current reader provides this:`readExportPage` (`src/core/export-snapshot.ts:28-40`) and `gbrain export`(`src/commands/export.ts:123-150`) select any live page, which is right for atrusted local snapshot and wrong for an automatic git publication.@@ -296,13 +312,20 @@ branch that only a source in database mode reaches.content equal to the current file, the ledger adopts the file's hashes andnothing is rewritten. "Equal" is one contract used everywhere: the parsedfile equals the canonical export view of the page, after removing a defined- list of database-only stamps (the #6429 class). Segmented pages compare by+ list of database-only stamps (the #6429 class). The canonical export view is+ the overlaid view: the renderer reads through `readExportPage` and+ `readExportWithdrawals` (`src/core/export-snapshot.ts:28-39`) for inline pages+ and the segmented export reader for segmented ones, then serializes. A+ plain `serializePageToMarkdown` of the stored body would publish forgotten+ facts, because a withdrawal only bumps the revision and the row is removed at+ read time. Segmented pages compare bythe streamed SHA-256 of their exported Markdown, because their body fieldscannot be read whole (`src/core/page-body/page-shape.ts:3-7`).- **Paths are a function of slugs.** A page write whose slug cannotround-trip to a path and back is refused at write time (#7305); the ledger's- live-path key is case-folded so APFS and NTFS cannot hold two pages in one- file, and a slug reused after a soft delete gets a new ledger lifetime.+ live-path key uses the export stage's NFC-plus-case fold, so APFS and NTFS+ cannot hold two pages in one file, and a slug reused after a soft delete gets+ a new ledger lifetime.- **Durable batch manifest.** Before touching the filesystem the exporterrecords the batch: id, each path's expected prior hash, the pinned revisionand the digest of the bytes it will write, and the paths it will remove.@@ -315,18 +338,31 @@ branch that only a source in database mode reaches.budgets 2 s per MiB of index for each such step(`src/core/persistence/effect-git.ts:52`), which would put a batch near aminute.- The exporter builds the commit with plumbing (tree from HEAD plus changed- entries, `commit-tree`, `update-ref`), or uses a split index, and the soak- records commit time against index size.-- **Lock order:** worktree lock, then the checkout's commit lock (the one- `gbrain git commit-push` takes), then the publish lock. An operator committing- non-page files during a batch waits on the commit lock instead of racing it.-- **Integrating a moved remote.** A rejected push fetches, runs the import- lane over page paths the fetched commits changed (revision-checked, so a- clean outside edit becomes a database write and a two-sided one a conflict),- re-renders the batch, and pushes the result. Parked paths stay out of the- batch. It never merges page files a second time outside the import lane, and- never pulls into the worktree.+ The exporter requires `core.splitIndex` on the checkout and writes each+ changed entry into the real index (`update-index --index-info`) before the+ commit, so the index never lags HEAD: otherwise `hardenedPathDirty`+ (`src/core/hardened-git.ts:230`) would see every exported path as dirty and a+ person's plain `git commit` would revert the export. A test checks that+ `diff-index --cached HEAD` is clean after a batch. The soak records commit+ time against index size.+- **Locks.** The checkout's commit lock (the one `gbrain git commit-push`+ takes) is held only for the index, commit and fast-forward steps, and never+ while waiting for the publish lock, matching commit-push's own order. Fetch+ and import run with no Git lock held. An operator committing non-page files+ during a batch waits briefly on the commit lock instead of racing it.+- **Integrating a moved remote.** A rejected push fetches with no Git lock+ held and runs the import lane over page paths the fetched commits changed+ (revision-checked: a clean outside edit becomes a database write, a+ two-sided one a conflict). The exporter then builds the next commit with the+ fetched tip as its parent: the tip's tree, including other people's+ non-page files, plus the rendered page entries, where a page path is taken+ only when the tip's blob is the one the lane just imported or adopted.+ It pushes with the tip pinned (at most eight attempts), then fast-forwards+ the branch and worktree under the commit lock. This is how non-page commits+ from other clones reach the owner checkout, and why an imported edit never+ shows up as an `integrate_conflict` (`src/core/persistence/effect-git.ts:326`)+ on the next push. Parked paths stay out of the batch, and page files are+ never merged a second time outside the import lane.- **Never exports to a mirror.** An import-only or read-only mirror source isnever an export target (#5409, #6946).@@ -355,6 +391,8 @@ current database revision r1, and file bytes F:| r1 ≠ r0 and F ≠ h0 (both changed) | Conflict `both_changed`. The database is untouched, the path is parked, both copies are kept. || F is gone, r1 = r0 | A deletion intent: soft-delete P through the normal delete path, but only when git history shows the exported file was committed and then removed (the #7130 evidence rule). Deletions are batched per scan; a batch above the mass-delete valve becomes one `bulk_delete` conflict that needs one approval, never thousands of per-file holds. || F is gone, r1 ≠ r0 | Conflict `deleted_vs_edited`. The page stays live; the path stays parked. |+| F is gone from the worktree but still committed at HEAD | Conflict `deleted_uncommitted`; the path is parked so the exporter does not recreate it. It closes as a deletion once the removal is committed (then the row above applies), or with `--take database`. |+| F is larger than the request cap (24 MiB) | A streamed, revision-checked import when r1 = r0; otherwise conflict `too_large_for_lane`. Conflict bytes are stored inline up to 24 MiB; larger ones are kept as a SHA-256 plus a pinned private Git ref that backup notes name. || No ledger entry, no page at the slug | Create the page (create-only write). || No ledger entry, a page exists at the slug | Conflict `unexported_collision` unless F is equal to the page. || Segmented page, any two-sided change | Conflict; no partial comparison. |@@ -375,7 +413,11 @@ A conflict blocks only its own path's export:- resolution is `gbrain sources conflicts <id> resolve <conflict> --take file|database --expect <hash>`(preview-bound like every repair; `gbrain import` already names a command, sothe verb lives with the source admin verbs), or an agent's `put_page` that- carries `resolves_conflict` for that page and the expected revision.+ carries `resolves_conflict` for that page and the expected revision. The+ `put_page` route is allowed only for `both_changed`, `unexported_collision`+ and `protected_metadata`; deletion kinds resolve only through the+ preview-bound verb, so an agent write can never make the exporter recreate a+ deliberately deleted file.**Later, separately approved: a base-aware merge.** `mergeReconcile`(`src/core/persistence/reconcile-merge.ts:85-138`) is a two-way merge: equal@@ -396,11 +438,13 @@ becomes a conflict, which is the honest outcome for an agent that bypassed thewrite path. The skills an agent loads should say "write memory with`put_page` / `remember`; edit files only for content you would otherwisehand-edit". Automated committers stop committing page paths:-`gbrain git commit-push` refuses page paths of a database-canonical source for-every caller, with a code that names `put_page`. It decides from a-checkout-local marker of page roots that the exporter maintains under the-commit lock, so it needs no database connection and fails closed when the-marker is unreadable. A cron that commits every untracked file has nothing+`gbrain git commit-push` keeps refusing managed worktrees as it does today,+and a database-canonical worktree is one of them, so no new page-path marker+or loosening is needed; the refusal names `put_page` for page paths. Doctor's+`git_convergence` check learns the mode: it stops advising plain-git commits+and `--keep-checkout` pushes for a database-canonical checkout+(`src/commands/doctor/checks/git-convergence.ts:188-201`) and points at export+status instead. A cron that commits every untracked file has nothingleft to do for page files; the exporter already committed them, and the lanecatches anything it still writes.@@ -408,12 +452,26 @@ catches anything it still writes.A doctor check at conversion is not enough: production upgrades by hand andan older binary started later is the normal case. The source's mode is-enforced in the database. Converting raises a per-source protocol fence, in-the same trigger pattern as the existing brain-wide `writer_protocol_floor`-(`src/core/persistence/administration.ts:269`, `src/schema.sql:2618`), that-refuses managed-sync imports, coordinated file publication and classic import-writes for that source from any binary that does not know the mode. Unlike the-brain-wide floor it is per source and is lowered by the flip back.+enforced in the database at three points:++- **Inserts:** a per-source protocol fence on persistence request and effect+ inserts, in the trigger pattern of the brain-wide `writer_protocol_floor`+ (`src/core/persistence/administration.ts:269`, `src/schema.sql:2618`),+ refuses managed-sync imports, coordinated file publication and classic+ imports for the source from a binary that does not know the mode.+- **Canonical mutations:** the managed writer allowlist guard+ (`src/schema.sql:2326-2333`) also checks the session's protocol for sources+ in database mode, so a direct coordinated write from an old binary is+ refused, not just its requests.+- **Claims and recovery:** request and effect claims, publication and+ recovery check the source's mode epoch; work prepared before a transition is+ drained, cancelled or re-prepared, never published under the old mode.++Unlike the brain-wide floor the fence is per source and is lowered by the+flip back. The triggers read a brain-level count of database-mode sources+under the existing `FOR SHARE` and return at once when it is zero, so+brains that never use the mode pay nothing; the soak measures the cost when+it is not zero.### Freshness, status and latency@@ -429,6 +487,11 @@ brain-wide floor it is per source and is lowered by the flip back.- Writes no longer wait on a file publication on the owner host, so an ownerthat is down or slow delays only the export. Today the same outage returns`owner_unavailable` or `write_pending` to the writer.+- On PGLite with no resident, the one-shot command that committed a write+ makes one bounded, best-effort export attempt after the write is+ acknowledged; a missing remote or checkout never fails the write or holds+ the datastore, and unexported targets stay in the outbox for the next+ resident or command.- The import lane does no full-tree discovery per pass, so the O(repository)preparation and walk costs (#6858, the post-activation walk) do not apply;its own idle and catch-up costs are measured in the soak.@@ -509,11 +572,24 @@ adoption and the flip:Rollback:-- **Before step 5,** flipping back to `files` turns each adopted conflict back- into the hold it came from (adoption is a bijection, pinned by a test that- compares hold rows byte for byte), lowers the fence and restarts managed- sync; nothing on disk changed. Conflicts created after the flip by new- outside edits become ordinary holds.+- **Every flip back starts with a barrier.** The source moves to a draining+ state bound to its mode epoch: new writes still commit to the database and+ enqueue export work, but the final flip checks that the epoch and the+ outbox frontier it drained are unchanged, so a write landing after the last+ drain check is drained or re-prepared under files mode, never omitted.+- **Before step 5,** the exporter has written nothing, but agents may have+ written database-only revisions (an edit to an equal page, a new page with+ no file, a delete). Restarting managed sync would not write them out: it+ classifies an unchanged file under a newer database revision as `db_ahead`+ with no action (`src/core/persistence/sync-classify.ts:173-177`). So the+ flip enumerates every committed-but-unmaterialized revision from the outbox+ and either materializes it through one exporter batch or keeps it as an+ explicit database-ahead hold with its pending target. Then each adopted+ conflict turns back into the hold it came from (adoption is a bijection,+ pinned by a test that compares hold rows byte for byte), the fence is+ lowered and managed sync restarts. Conflicts created after the flip by new+ outside edits become ordinary holds. A test edits, creates and deletes pages+ during shadow, rolls back, and injects a write after the final drain check.- **After step 5,** the flip back is a planned conversion. It waits until theexporter has committed and pushed every eligible, unparked revision. Parkedpaths cannot be drained, so each one is listed: its conflict becomes a@@ -618,22 +694,35 @@ Adding a fourth persistence mode is only worth it if it lets the two-waymachinery stop growing for agent sources, and eventually shrink. These areexit criteria, not hopes:-- **After Phase 3a:** no new hold kind, sync guard or writer-census- `filesystem_guard` row is added to serve agent-written sources; a new- agent-source incident in the two-way classes is answered by recommending the- mode, not by another guard. Human-first sources keep getting fixes.+- **For converted, stable sources:** once a source has run in database mode+ and is green, no new hold kind, sync guard or writer-census+ `filesystem_guard` row is added to serve it; an incident there is fixed in+ the exporter or the import lane.+- **For every files-mode source, until its replacement is available and+ approved:** correctness, security and data-loss fixes keep shipping, agent+ sources included. Phase 3a does not make the existing sources convertible+ (that is Phase 3b) or usable in production (Phase 4), so "recommend the+ mode" is not an answer for them yet. The one added bar: a new hold kind for+ an agent-written source states in its PR why the mode would not have+ prevented the incident. Human-first sources keep getting fixes as today.- **After Phase 5:** with the largest agent sources converted and green for14 days, list the code that only database-canonical sources would haveneeded and that no remaining files-mode source uses (for example thekeep_db reconcile lane, the post-activation drift classifier for thosesources, the per-write Git effect path for page files), and delete what the- list proves unused. The default mode for new agent-first and hosted brains- is decided at the end of Phase 3a, not deferred to Phase 6, so brains- created during Phases 3b to 5 do not all become future conversions.-- **One model for local and hosted.** The ledger, the exporter and the- conflict table are engine-level components. A hosted brain's "mirror my- brain to a git repository I own" uses the same three pieces, so there is one- export and one conflict model, not two.+ list proves unused.+- **The default mode for new agent-first and hosted brains** is decided once+ the first production source of Phase 4 has been green for 7 days, not at+ the end of Phase 3a, when the mode has run only on the soak brain and new+ empty sources. Until then new brains keep files mode and are offered the+ mode as an opt-in when they are created.+- **One model for local and hosted.** The seam is named: rendering, the+ ledger, the batch manifest and the plumbing commit to a ref form the+ engine-level core, and plumbing works on a bare repository. Worktree+ materialization and the Git-effect registration are the local adapter. A+ hosted brain's "mirror my brain to a git repository I own" uses the core+ without the adapter, and a test exports to a bare repository with no+ worktree binding, so there is one export and one conflict model, not two.Rough size, to be refined in each phase's plan (each extra PR costs oneserial merge slot and one full gate):@@ -651,15 +740,16 @@ serial merge slot and one full gate):|---|---|---|| The database is the only copy of an edit until it is pushed | durability | verified-backup precondition and doctor check; pushed coverage and export lag in status; parked paths listed with age || A Postgres outage stops all writes for the source (files mode let a person keep editing files offline) | availability | outside edits made during an outage are imported when it ends; agents retry writes as they do on `write_pending` |-| An older binary started later writes files or imports on a converted source | correctness | the per-source protocol fence in the database refuses it; a test starts an old-protocol writer after conversion |+| An older binary started later writes files or imports on a converted source | correctness | the per-source protocol fence refuses its request and effect inserts, its direct coordinated writes and its claims; the export outbox trigger still captures any change it commits; tests start an old-protocol writer after conversion and run a bare coordinated write || Rendering is lossy or unstable, so exports churn or drop fields | correctness | one equality contract; a property test that `parse(render(page))` equals the canonical export view (empty fields, tags, metadata, timeline, overlays, malformed fences, segmented pages), then that rendering is a fixed point |-| Private or `db_only` content reaches a git remote | privacy | the new `exportEligible` predicate, evaluated at render time; tests for initial exclusion and for a page that turns private while older work is queued; tracked private files handled by big decision 7 |+| Private or `db_only` content reaches a git remote | privacy | the new `exportEligible` predicate, evaluated at render time and bound to the batch by an eligibility generation rechecked after commit and before push; the renderer reads the withdrawal overlay, so forgotten facts are never rendered; tests for initial exclusion, a page that turns private after render, between commit and push, and during recovery, and a forgotten fact on inline and segmented pages; tracked private files handled by big decision 7 || Conflict listings leak private pages or other sources' content to remote tokens | privacy | source, slug and visibility fences before listing and counting; no file bytes for remote callers; `remote=true` tests || The import lane or a crash mistakes gbrain's own write for an outside edit | correctness | durable batch manifest with compare-and-set ledger updates; crash tests at each effect fault point || Configured clean or textconv filters run during change detection | security | hardened plumbing only; a test with a configured filter driver that must never run || People keep committing page files from other clones | process | supported; each foreign commit is imported or becomes a conflict, and status names its author so the operator can move that writer to `put_page` || Conflicts pile up unresolved | operability | listed by age on the daily scoreboard; no conflict blocks anything else |-| Shadow work loads production brains | performance | shadow runs only on sources with a per-source shadow flag, from a journal cursor into a shadow table, with no effect rows; its cost is measured on the soak first |+| Shadow work loads production brains | performance | shadow runs only on sources with a per-source shadow flag, fed by the same outbox trigger Phase 3a uses, into a shadow table, with no effect rows; its cost is measured on the soak first |+| Protocol-fence triggers slow brains that never use the mode | performance | the triggers return at once when the brain has no database-mode source; the soak measures their cost when it has one |One-way doors, honestly stated:@@ -688,11 +778,11 @@ admin verb. Nothing converts on upgrade.| Phase | Ships | Exit criterion ||---|---|---|| 0 | this design, with the maintainer's decisions | approval of the direction and of the big decisions below |-| 1 | export ledger, seeded in shadow from managed sync's per-page import provenance (raw blob id and revision, `src/core/persistence/sync-holds.ts:1077-1085`) so it has a base before any export; renderer with the equality contract; `exportEligible`; shadow diff from a journal cursor for opted-in sources; the soak-brain generator if the scale soak has not delivered one | property test green on PGLite and Postgres; shadow diff on the fixture corpus plus synthetic holds shows only expected rows; shadow overhead measured |-| 2 | import lane in observe mode on opted-in managed sources: records the conflict each hold would have been and which fields a merge would have resolved; foreign-edit census | for every hold managed sync writes on the soak brain, the lane predicts the same path and a correct kind |-| 3a | database publication branch, exporter commits and pushes, protocol fence, conflict resolution, status/doctor/MCP surfaces, `git commit-push` page-path refusal; **new or empty sources only**, no adoption | on PGLite and Postgres and on the soak brain: agent writes commit with the export owner down; export lag p95 under 60 s; zero writes refused for file state; restore drill from the remote names exactly the parked and unpushed gaps. Then the default-mode decision for new agent-first brains |-| 3b | the conversion state machine (census, adopting, adopt, database, flip back) | on the production-shaped soak brain (several hundred thousand pages, years of moves and culls, thousands of synthetic holds of every kind, 65 ms injected latency, pool 25): adopt completes under live writes, freshness never freezes, zero files recreated at deleted paths, flip back restores every hold byte for byte, idle scan cost and outage catch-up within the measured envelope |-| 4 | opt-in on a test brain, then on the smallest production source, after the maintainer approves that source | 7 days: no unexpected shadow diff, conflicts only from real edits, scoreboard green |+| 1 | export ledger, seeded in shadow from managed sync's per-page import provenance (raw blob id and revision, `src/core/persistence/sync-holds.ts:1077-1085`) so it has a base before any export, with seed coverage reported per field (revision, raw hash, disk hash) per source; renderer with the equality contract and the withdrawal overlay; `exportEligible`; the export outbox trigger feeding a shadow diff for opted-in sources; the soak-brain generator if the scale soak has not delivered one | property test green on PGLite and Postgres; shadow diff on the fixture corpus plus synthetic holds shows only expected rows, including two requests that commit in reverse sequence order; shadow overhead measured |+| 2 | import lane in observe mode on opted-in managed sources: records the conflict each hold would have been and which fields a merge would have resolved; a published hold-code to conflict-kind mapping table; foreign-edit census | on a labeled fixture set, where each case carries the outcome a person would choose, the lane agrees with the label; cases where the lane is right and managed sync is not count as agreement |+| 3a | database publication branch, export outbox and exporter commits and pushes, protocol fence, conflict resolution, status/doctor/MCP surfaces, `gbrain sources canonical <id> --to database` for a provably empty source; **new or empty sources only**, no adoption | on PGLite and Postgres and on the soak brain, through the real operator verb: agent writes commit with the export owner down; export lag p95 under 60 s; zero writes refused for file state; restore drill from the remote names exactly the parked and unpushed gaps |+| 3b | the conversion state machine for non-empty sources (census, adopting, adopt, database, flip back) | on the production-shaped soak brain (several hundred thousand pages, years of moves and culls, thousands of synthetic holds of every kind, 65 ms injected latency, pool 25): adopt completes under live writes, freshness never freezes, zero files recreated at deleted paths, flip back restores every hold byte for byte, idle scan cost and outage catch-up within the measured envelope |+| 4 | opt-in on a test brain, then on the smallest production source, after the maintainer approves that source | 7 days: no unexpected shadow diff, conflicts only from real edits, scoreboard green. Then the default-mode decision for new agent-first and hosted brains || 5 | the largest sources; page-path auto-commits retired; skills updated to `put_page`-first; the retirement list in "Retirement and cost" | 14 days green on the scoreboard; no held-deletion or drift incidents || later | a base-aware three-way merge, only if Phase 2 and the census justify it, as its own design and approval | not part of this plan |@@ -727,8 +817,9 @@ but Phases 3a and 3b do.already detached pages left database-only. Flips if the census shows theyare mostly bulk or private content.6. **Automated committers: refuse page paths.** Options: allow and import, or- refuse. Pick refuse for `gbrain git commit-push` (every caller), import for- anything else that commits. The refusal names `put_page`.+ refuse. Pick refuse for `gbrain git commit-push`, which already refuses+ managed worktrees and keeps doing so, and import for anything else that+ commits. The refusal names `put_page`.7. **Private pages whose files are tracked today.** Options: keep their files(with ledger rows, never updated), or remove them from the checkout in theconversion's first export commit. Pick remove, listed in the census and@@ -740,10 +831,12 @@ but Phases 3a and 3b do.prove the mode on new, empty sources first. Pick new sources first (Phase3a before 3b): no adoption, so the exporter, ledger and lane are provenseparately from the hardest path.-9. **Exporter as a Git-effect target, not a new effect kind.** Pick the Git- effect, because every checkout-touching consumer already knows it. Flips if- batching cannot fit its target model; then a new kind ships with a test- that fails when any checkout consumer does not know it.+9. **Exporter as an outbox drained into Git effects, not a new effect kind.**+ Pick a per-source outbox filled by a database trigger, with one Git effect+ per export batch, because every checkout-touching consumer already knows+ the Git effect and the trigger removes any per-writer obligation. Flips if+ batching cannot fit the Git effect's model; then a new kind ships with a+ test that fails when any checkout consumer does not know it.## Open questions@@ -771,8 +864,8 @@ but Phases 3a and 3b do.8. **Where the exporter runs.** Inside the resident owner (recommended, as theGit effect does today) or as its own process, which isolates it from serverestarts but adds the kind of process Step 1 is removing.-9. **The default for new agent-first and hosted brains,** decided at the end- of Phase 3a.+9. **The default for new agent-first and hosted brains,** decided once the+ first production source of Phase 4 has been green for 7 days.## Implementation plan@@ -782,78 +875,136 @@ existing behavior.1. **Export ledger (Phase 1).** `export_ledger(source_id, path, path_folded, page_id, lifetime, revision, disk_sha256, blob_oid, renderer_fp, commit_sha, exported_at)`with a partial unique index on (source_id, path_folded) for live rows and on- (source_id, page_id, lifetime); renames move both keys in one transaction.+ (source_id, page_id, lifetime); `path_folded` uses the NFC-plus-case fold of+ `src/core/export-stage.ts:42`; renames move both keys in one transaction.Writers: the exporter, the import lane's hash adoption, the conversion's- adopt step, and the Phase 1 shadow seed from `SyncImportProvenance`. Next- free migration number at merge time.-2. **Renderer and equality contract (Phase 1).** Build on- `serializePageToMarkdown` (`src/core/markdown.ts`) and `reconcileCanonical` for- the comparison form, with one defined list of database-only stamps; segmented- pages by streamed SHA-256. Property test as in the risk table.+ adopt step, and the Phase 1 shadow seed from `SyncImportProvenance`. A+ seeded row carries `renderer_fp = NULL` ("imported bytes, never+ rendered"), so keep-bytes decisions use the equality contract, never the+ fingerprint; records without a revision or disk hash are not seeded and+ count as "no base" in the shadow report.+2. **Renderer and equality contract (Phase 1).** Render from the overlaid+ export view: `readExportPage` plus `readExportWithdrawals` for inline pages,+ `segmentedExportMarkdown` with `exportBodyLedger` for segmented ones+ (`src/core/export-snapshot.ts:37-90`), after `exportEligible`, and only then+ serialize; `reconcileCanonical` gives the comparison form, with one defined+ list of database-only stamps. Segmented pages compare by streamed SHA-256.+ Property test as in the risk table, plus a forgotten fact on an inline and+ a segmented page: the next committed blob lacks the row and the file still+ compares equal.3. **`exportEligible` (Phase 1).** One predicate (private, alias-private,`db_only` prefixes, `database_only_reason`, detached, mirror sources) used by- the exporter, the census and the shadow diff.-4. **Shadow diff (Phase 1).** For sources with a per-source shadow flag only:- a journal-sequence cursor feeds a shadow table of would-be batches. No- effect rows, so receipt true-up, compaction and activation are untouched.+ the exporter, the census and the shadow diff; visibility changes bump a+ per-source eligibility generation.+4. **Export outbox and shadow diff (Phase 1).** The `export_outbox(source_id,+ page_id, revision, enqueued_at)` table and its AFTER triggers on `pages`+ and fact withdrawals, active only for sources in database mode or with the+ per-source shadow flag. For shadowed sources a consumer turns outbox rows+ into a shadow table of would-be batches. Because rows are written by the+ committing transaction, out-of-order commits and request-free writes are+ seen, unlike a journal-sequence cursor. No effect rows, so receipt+ true-up, compaction and activation are untouched.5. **Import lane in observe mode (Phase 2).** Hardened plumbing only; file- watch plus poll and a stable-bytes rule; the decision table above; a- `import_conflicts` table keyed by (source_id, path) that also carries parking- and stores outside bytes; would-have-merged field counts; the foreign-edit- census.+ watch plus poll and a stable-bytes rule; the decision table above; an+ `import_conflicts` table with a partial unique index on open rows over+ (source_id, path_folded) and resolved rows kept by id, which also carries+ parking and stores outside bytes (inline up to 24 MiB, above that a SHA-256+ and a private ref); would-have-merged field counts; the hold-code to+ conflict-kind mapping; the foreign-edit census.6. **Database publication branch (Phase 3a).** Keyed on the source's mode andepoch: no worktree id, no worktree lock, no recovery record, no- `database_only_reason`; the transaction enqueues an export target. Fan-out- mutations (multi-page forget, purge, rename, visibility change) enqueue- targets for every affected page and keep old paths until the file removal is- committed.-7. **Exporter (Phase 3a).** Database-rendered targets on the Git effect;- durable batch manifest; plumbing commit; lock order worktree, commit, publish;- fetch-import-render-push on a rejected push; PGLite end-of-command drain.-8. **Protocol fence (Phase 3a).** Per-source, reversible, enforced by- triggers on persistence request and effect inserts in the- `writer_protocol_floor` pattern.-9. **Surfaces (Phase 3a).** Export lag (seconds), import lag, processed,- committed and pushed coverage, parked paths with age, conflicts by kind and- age in `gbrain sync status` and `get_brain_health`; doctor checks- `database_canonical_backup`, `export_lag`, `import_conflicts`; an MCP read op- with remote fences; `gbrain sources conflicts <id> list|show|resolve`;- `gbrain git commit-push` page-path refusal from a checkout-local marker.-10. **Conversion verb (Phase 3b).** `gbrain sources canonical <id> --to database|files`- with `--dry-run` (census), `--admin-intent source_canonical` and- `--expected-state` (fingerprint including mode and hold-set digest);- states `files` → `adopting` → `database` and back.+ `database_only_reason`, and no export work enqueued by the writer. Every+ effect-inserting writer (withdrawal, purge, rename, visibility, connector+ checkpoints, segmented repair) is routed by source mode, so a+ database-mode source gets no `withdrawal-mirror` and no per-request `git`+ effect; fan-out mutations keep old paths until the file removal is+ committed. A streamed, expected-revision import entry serves outside edits+ above the request cap.+7. **Exporter (Phase 3a).** Drains the outbox into one Git effect per batch.+ The effect is bound to the source's canonical worktree, binding generation+ and mode epoch, claimed only by the export owner; a missing owner or+ binding leaves it pending, never `skipped: no_repo_configured`+ (`src/core/persistence/effects.ts:320-322`), and an owner transfer+ re-binds it. Durable batch manifest with the eligibility generation;+ split-index commit that updates the real index; commit lock only for index,+ commit and fast-forward; fetch and import with no Git lock, then a commit+ on the fetched tip; PGLite one bounded best-effort attempt after the+ acknowledged write.+8. **Protocol fence (Phase 3a).** Per-source and reversible: triggers on+ persistence request and effect inserts in the `writer_protocol_floor`+ pattern, a protocol check in the managed writer guard for direct+ coordinated writes, and mode-epoch checks at claim, publication and+ recovery. Short-circuits when the brain has no database-mode source.+9. **Surfaces (Phase 3a).** Export lag (seconds, from the outbox), import lag,+ processed, committed and pushed coverage, parked paths with age, conflicts+ by kind and age in `gbrain sync status` and `get_brain_health`; doctor+ checks `database_canonical_backup`, `export_lag`, `import_conflicts`, and a+ mode-aware `git_convergence`; an MCP read op with remote fences;+ `gbrain sources conflicts <id> list|show|resolve`; `put_page` gains+ `resolves_conflict` (op ledger and contract goldens updated, allowed only+ for `both_changed`, `unexported_collision` and `protected_metadata`, tested+ with `remote=true`).+10. **Mode verb (empty sources in Phase 3a, conversion in Phase 3b).**+ `gbrain sources canonical <id> --to database|files` with `--dry-run`+ (census), `--admin-intent source_canonical` and `--expected-state`+ (fingerprint including mode and hold-set digest). Phase 3a accepts only a+ source that is empty by an explicit test (zero live pages, zero holds, no+ tracked files under its page roots, no prepared transfer) and raises the+ fence and the epoch; anything else is refused with a code that names+ Phase 3b. Phase 3b adds `adopting`, adopt, and the flip-back barrier.11. **Tests (each on real PGLite and Postgres; `remote=true` where it applies).**An agent write commits with the export owner down and never refuses for- file state. An outside edit with an unchanged database imports, keeping- protected keys; a visibility or trust change in the file is a conflict. A- two-sided edit records one conflict and the page stays writable. A deleted- exported file soft-deletes only with commit evidence; a never-exported- missing file does nothing. The exporter never overwrites an unimported- edit, including on a path with no ledger row. A `deleted_by_commit` hold- adopted as `deleted_vs_edited` is never recreated, across restarts. Adoption- is a bijection, including a hold written mid-adopt. An old-protocol writer- is refused after conversion. Crash at every effect fault point of a batch- finishes forward. autocrlf and LFS checkouts do not look edited. A- configured filter driver never runs. Segmented pages export and compare.- A page that turns private while a target is queued is never published.- Conflict listings respect source, slug and visibility fences. Slug reuse- after soft delete and case-only path twins get distinct lifetimes. PGLite- one-shot drain. A remote push racing a batch in two real clones.+ file state; 10,000 writes with the owner stopped leave capacity and+ receipt compaction as in a files-mode control. A non-owner's generic+ effect worker never completes an export; only the owner does, across an+ owner transfer. An outside edit with an unchanged database imports,+ keeping protected keys; a visibility or trust change in the file is a+ conflict. A two-sided edit records one conflict and the page stays+ writable. A deleted exported file soft-deletes only with commit evidence;+ an uncommitted deletion is parked and not recreated after a restart; a+ never-exported missing file does nothing. The exporter never overwrites an+ unimported edit, including on a path with no ledger row. A+ `deleted_by_commit` hold adopted as `deleted_vs_edited` is never+ recreated, across restarts. Adoption is a bijection, including a hold+ written mid-adopt. An old-protocol writer and a bare coordinated write are+ refused after conversion; forget, purge and rename leave no+ `withdrawal-mirror` or per-request `git` rows. Crash at every effect+ fault point of a batch finishes forward. After a batch+ `diff-index --cached HEAD` is clean. autocrlf and LFS checkouts do not look+ edited. A configured filter driver never runs. Segmented pages export and+ compare. A page that turns private after render, between commit and push,+ or during recovery is never published. A 30 MiB outside edit, one-sided+ and two-sided. Conflict listings respect source, slug and visibility+ fences. Slug reuse after soft delete and NFC or case-only path twins get+ distinct lifetimes. PGLite one-shot export with no remote does not fail+ the write. In two real clones, a remote commit to a page and `AGENTS.md`+ races a database write to the same page: no `integrate_conflict`, the+ remote holds the render and `AGENTS.md` reaches the owner checkout; an+ operator `commit-push` of a non-page file during a batch finishes without+ `commit_lock_busy`. Export to a bare repository with no worktree binding.12. **Scale soak.** Conversion and steady-state cells on the production-shapedsoak brain: adopt under live writes, idle scan cost as the repository grows,sustained mixed imports and writes, a hot page, catch-up after an exporter- outage, commit time against index size; gates in the rollout table.+ outage, commit and index-update time against index size, fence-trigger+ cost; gates in the rollout table.++Schema by phase, so each PR's migration can be checked when it is stamped at+merge: Phase 1 adds `export_ledger`, `export_outbox` and its triggers, the+shadow table and the per-source shadow flag; Phase 2 adds `import_conflicts`;+Phase 3a adds the source's mode, mode epoch and eligibility generation, the+batch manifest, the per-source fence and the writer-guard check; Phase 3b adds+the `adopting` state and the `adopted_by` marker on hold rows.## Review recordReviewed with gstack `/autoplan` (gstack 1.91.176.0), run`autoplan-20261022031112`, CEO and Eng phases (UI and DX out of scope), each-with a native voice (Claude Opus 5.5) and an outside voice (GPT-6.1 Sol): 52-findings (CEO 12 + 5, Eng 26 + 9; 24 High, no Critical). This revision takes-every recommendation, including the four direction changes the gate-recommends (conflicts-only import lane first, three findings; new sources-before conversions, one finding). The main corrections:+with a native voice (Claude Opus 5.5) and an outside voice (GPT-6.1 Sol).++**Round 1** (revision 1): 52 findings (CEO 12 + 5, Eng 26 + 9; 24 High, no+Critical). Revision 2 took every recommendation, including the four direction+changes the gate recommended (conflicts-only import lane first, three+findings; new sources before conversions, one finding). The main corrections:- The first draft claimed the three-way merge reused reconcile's rules; it doesnot (`mergeReconcile` is two-way). The merge is now a later, data-gated step.@@ -872,4 +1023,39 @@ before conversions, one finding). The main corrections:- A "Retirement and cost" section makes stopping two-way growth an exitcriterion; `gbrain import conflicts` became `gbrain sources conflicts`.-The gate (final plan approval) is the maintainer's to answer.+**Approval of revision 2.** The maintainer answered the round-1 gate on+2026-10-22 (UTC) with "Rec": the plan approved with every recommendation+taken, covering the reviewed plan with sha256 prefix `a4ad6b8bbc13`. The+approval is recorded in gstack's approval log for this branch.++**Round 2** (revision 2): 30 findings (CEO 7 + 2, Eng 15 + 6; 9 High, no+Critical). The reviewers found 15 of the 17 round-1 CEO findings resolved.+Revision 3 takes every recommendation:++- The renderer reads the withdrawal overlay; built on the stored body it would+ have pushed forgotten facts to the remote.+- Export work is no longer enqueued by writers: a database trigger fills a+ per-source outbox, which covers request-free coordinated writers and old+ binaries and coalesces writes while the exporter is down; one Git effect per+ batch, bound to the owner's worktree and the mode epoch, so a non-owner can+ never complete an export.+- A rejected push builds the next commit on the fetched tip, so imported+ edits and other people's non-page files merge cleanly; the commit updates+ the real index through a split index; the commit lock is no longer held+ while waiting for the publish lock.+- Batches carry an eligibility generation rechecked after commit and before+ push; the fence also covers direct coordinated writes, claims and+ recovery; a flip back drains every committed-but-unmaterialized revision+ behind an epoch barrier.+- Phase 3a ships the mode verb for provably empty sources; the shadow uses the+ outbox instead of a journal cursor; Phase 2 is gated on a labeled fixture+ set; uncommitted deletions, oversized edits and `resolves_conflict` have+ defined rules; the hosted seam is named.+- One direction change, recommended and awaiting the maintainer's answer at+ the round-2 gate: the freeze on new two-way machinery applies to converted,+ stable sources, and correctness, security and data-loss fixes continue for+ every files-mode source until its replacement is available and approved;+ the default mode for new brains is decided after Phase 4's first production+ source, not after Phase 3a.++The round-2 gate (final plan approval) is the maintainer's to answer.