Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(persistence): reconcile canonical file and database drift (#5361)
Garry Tanb272cf234640
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex a6c037ca68..9864a41a19 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.52.1.0",+ "version": "0.52.2.0","description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.","author": {"name": "Garry Tan",diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonindex 84d35941d8..fb345bd598 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.52.1.0",+ "version": "0.52.2.0","description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.","author": {"name": "Garry Tan",diff --git a/.github/workflows/persistence-validation.yml b/.github/workflows/persistence-validation.ymlindex d0ede5b4b8..b6fc6c46d3 100644--- a/.github/workflows/persistence-validation.yml+++ b/.github/workflows/persistence-validation.yml@@ -119,6 +119,19 @@ jobs:test/persistence-recovery-capacity.test.ts \test/audit/pool-recovery-audit.test.ts \test/persistence-recovery-fairness.test.ts+ - name: Require canonical reconciliation through direct and pooled PostgreSQL+ timeout-minutes: 5+ env:+ DATABASE_URL: postgres://gbrain_test:[email protected]:5432/gbrain_test+ GBRAIN_TEST_ALLOW_DATABASE_URL: '1'+ GBRAIN_PGBOUNCER_URL: postgres://gbrain_test:[email protected]:55433/gbrain_test+ GBRAIN_PGBOUNCER_DIRECT_URL: postgres://gbrain_test:[email protected]:5432/gbrain_test+ GBRAIN_CI_REQUIRE_PGBOUNCER: '1'+ run: >-+ bun --no-env-file test --timeout=120000+ test/persistence-reconcile.test.ts+ test/e2e/reconcile-pgbouncer.test.ts+ test/e2e/extract-atoms-page-state.test.ts- if: always()uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02with:@@ -158,6 +171,25 @@ jobs:run: >-bun --no-env-file scripts/persistence/validate.ts --engine=${{ matrix.engine }}--manifest=.context/persistence-manifest.json+ - name: Require all reconciliation crash boundaries before and after activation+ timeout-minutes: 12+ env:+ DATABASE_URL: postgres://gbrain_test:[email protected]:5432/gbrain_test+ GBRAIN_TEST_ALLOW_DATABASE_URL: '1'+ GBRAIN_TEST_RECONCILE_CRASH_MANIFEST_DIR: .context/reconcile-crashes+ run: |+ if [ '${{ matrix.engine }}' = 'postgres' ]; then+ bun --no-env-file test --timeout=180000 test/e2e/reconcile-crash.test.ts test/e2e/reconcile-crash-unactivated.test.ts+ else+ env -u DATABASE_URL -u GBRAIN_DATABASE_URL bun --no-env-file test --timeout=180000 test/reconcile-crash.slow.test.ts+ fi+ - name: Upload reconciliation crash manifests+ if: always()+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02+ with:+ name: reconciliation-${{ matrix.engine }}-bun-${{ matrix.bun }}+ path: .context/reconcile-crashes/*.json+ if-no-files-found: error- name: Upload executed-case and latency manifestif: always()uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.mdindex 3a845c4345..dcc0cfa2cf 100644--- a/BOOTSTRAP_FOR_AGENTS.md+++ b/BOOTSTRAP_FOR_AGENTS.md@@ -1,4 +1,4 @@-<!-- gbrain-runbook-stamp: 0.52.1.0 -->+<!-- gbrain-runbook-stamp: 0.52.2.0 --><!-- This stamp must equal the VERSION file at every release; CI enforces it(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it tothe installed binary and warns on skew. -->diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d06d04b897..890d4f987f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,85 @@All notable changes to GBrain will be documented in this file.+## [0.52.2.0] - 2026-09-22++**Repair a memory page without guessing which copy to overwrite.** GBrain keeps+your notes in files and in its database. When those copies disagree, saving a new+memory can stop even though the file looks unchanged in Git. You can now compare+one exact page, preserve both originals, choose between conflicting fields, and+save the reviewed result through the existing safe writer. Information found on+only one side is kept rather than quietly discarded.++The repair checks again before saving. If another writer changed the page, file,+or owner while you were reviewing it, GBrain stops and asks for a fresh preview.+Interrupted saves recover through the same durable request, and retrying a+completed request does not apply it twice. After repair, retry your original+memory request separately and read back what was actually saved.++Background atom scanning now keeps its progress outside your note's metadata, so+a scan no longer creates a new disagreement just by recording that it finished.+Failed saves and syncs identify their page, specific reason, and durable request+instead of leaving you with a misleading permission error or an unnamed failed+file. Unsupported managed atom extraction stops before spending on a model.++**Say to your agent:** *"Preview this page's file/database disagreement, preserve+both originals, and show me the conflicts before repairing it. Then retry my+memory request and verify the fact, visibility, and provenance."*++### How to use it++```bash+gbrain sources reconcile workspace people/example --brain host --preview --json+gbrain sources reconcile workspace --brain host --audit --limit 25 --json+gbrain sources reconcile --help+```++Use `--out <new-private-file>` to keep an actionable preview, resolve conflicting+fields with explicit decisions, then apply the reviewed artifact with a retained+request UUID. The complete flow is in `docs/guides/concurrent-writes.md`.++| Situation | What happens now |+|---|---|+| Each copy has different additional metadata | Both sets of fields survive. |+| The same field has conflicting values | You choose explicitly; timestamps do not pick a winner. |+| A preview became stale | Apply refuses without overwriting either copy. |+| A save was interrupted | Retry its original UUID; inspect the durable receipt. |++### Things to watch++Repair requires an existing valid owner and trusted local CLI registration. It+works before or after managed activation but never claims, transfers, activates,+or changes source checkpoints. Private backups consume bounded local storage and+remain until explicitly removed. Forgotten active facts can still exist in that+history. This does not migrate every legacy maintenance writer to managed mode.++## To take advantage of v0.52.2.0++`gbrain upgrade` should apply migration 163 automatically. If it did not, run+`gbrain apply-migrations --yes`, then restart upgraded resident writers and+maintenance workers. Follow `skills/migrations/v0.52.2.0.md`; use a read-only audit+and an exact-page preview before any repair. No automatic bulk merge, ownership+change, activation, or paid enrichment is required.++### Itemized changes++- Add trusted-local `sources reconcile` preview, decision resolution, guarded+ apply, bounded audit, and retained-backup inspection/removal. Existing+ overwrite guards and frozen memory-verb error codes remain intact.+- Reuse the persistence journal and coordinator for revision/raw-byte/owner/policy+ checks, same-ID replay, durable preimages, and interrupted-publication recovery.+- Migration 163 adds source-incarnation/page/hash-keyed atom processing state with+ conservative legacy backfill. Canonical pages are not rewritten by migration.+ Partial atom publication still remains retryable until all provenance is saved.+- Preserve identical generated safety assessments across repeated imports, while+ keeping safety fields and policy checks in canonical comparisons.+- Report managed sync failures from their authoritative receipts, including+ resident-owner JSON, even when the local failure ledger is missing or unwritable.+ The ledger call-site fix is adapted from #5314. Contributed by @Masashi-Ono0611.+- Add real-engine reconciliation, scoped-authority, concurrent-replay, privacy,+ retained-backup, bounded-audit, real-owner CLI, and process-kill regression tests.++## [0.52.1.0] - 2026-09-22**A search result opens the page it found, and routine repair stays routine.**diff --git a/VERSION b/VERSIONindex a288738cfe..edbba8c1a4 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-0.52.1.0+0.52.2.0diff --git a/docs/TESTING.md b/docs/TESTING.mdindex 7dd087c825..e5a2c580fb 100644--- a/docs/TESTING.md+++ b/docs/TESTING.md@@ -12,6 +12,26 @@ is `scripts/bench-reindex-markdown.ts`.On-demand reference (see CLAUDE.md Reference map). Current behavior + invariantsonly.+### Canonical reconciliation++`test/persistence-reconcile-merge.test.ts` pins loss-preserving field choices.+`test/persistence-reconcile.test.ts` runs the guarded repair and replay contracts+on PGLite and, with an explicit safe `DATABASE_URL`, isolated PostgreSQL databases.+It covers stale preconditions, current/original grants, private facts, retained+backups, ordinary mutations after repair, and competing publications.+`test/reconcile-owner-journey.serial.test.ts` drives real CLI requests through+HTTP and stdio PGLite owners before and after activation, restarts the owner, and+independently reads the newly remembered private fact and provenance.++`test/reconcile-crash.slow.test.ts` and `test/e2e/reconcile-crash*.test.ts` kill real+processes at all eight publication boundaries with activation off/on. PostgreSQL+uses one file per activation state to stay within the unchanged per-file cap. Optional+`GBRAIN_TEST_RECONCILE_CRASH_MANIFEST_DIR` retains executed-case evidence.+`test/e2e/reconcile-pgbouncer.test.ts` requires the transaction-mode pooler when+`GBRAIN_CI_REQUIRE_PGBOUNCER=1` and proves repair followed by a new private memory+write. The durable-persistence workflow runs these contracts on both supported+Bun versions and uploads the crash manifests; local CI runs the slow and E2E lanes.+`test/docs-navigation.test.ts` checks local links and fragments in the primaryinstall/memory guides and all `docs/architecture/key-files/` references, requiresevery subsystem to be linked from `KEY_FILES.md`, and guards against blanketdiff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.mdindex d50114d945..8dbf96235b 100644--- a/docs/architecture/KEY_FILES.md+++ b/docs/architecture/KEY_FILES.md@@ -21,6 +21,7 @@ boundary and add its link here rather than raising the cap.| Subsystem | Entry range / scope ||---|---|| [Page identity and writer administration](key-files/page-identity-and-administration.md) | Opaque result IDs, current grants, state-bound ownership changes |+| [Canonical reconciliation](key-files/canonical-reconciliation.md) | Exact-page repair, private retained originals, derived atom state and receipt diagnostics || [Company-brain ingestion](key-files/company-brain.md) | Inspection, admission, receipts, derived relationships and schema; [operator guide](../guides/company-brain-ingestion.md) || [Commands (1/6)](key-files/commands-1.md) | `src/commands/agent-logs.ts` through `src/commands/db-repair.ts` || [Commands (2/6)](key-files/commands-2.md) | `src/commands/doctor.ts` through `src/commands/embed.ts` |diff --git a/docs/architecture/canonical-writers.tsv b/docs/architecture/canonical-writers.tsvindex 060ac73b03..e006a3a0d5 100644--- a/docs/architecture/canonical-writers.tsv+++ b/docs/architecture/canonical-writers.tsv@@ -33,6 +33,7 @@ src/core/company-brain/profile.ts 1 engine_guard Company-profile legacy deletessrc/core/company-brain/runtime.ts 1 projection Only source policy metadata advances under the company-source lock and brain/source row locks; the same transaction validates immutable approval and creates a receipt with source-incarnation and managed owner/topology fences, without source-file writes.src/core/cycle/drift.ts 1 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.src/core/cycle/extract-atoms.ts 3 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.+src/core/cycle/extract-atoms-page-state.ts 1 engine_guard Atom completion updates and cardinality checks share one transaction; managed canonical SQL remains fenced and scan/failure bookkeeping is stored separately.src/core/cycle/extract-facts.ts 2 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.src/core/cycle/extract-takes.ts 3 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.src/core/cycle/grade-takes.ts 1 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.diff --git a/docs/architecture/key-files/canonical-reconciliation.md b/docs/architecture/key-files/canonical-reconciliation.mdnew file mode 100644index 0000000000..9b2f2bf03e--- /dev/null+++ b/docs/architecture/key-files/canonical-reconciliation.md@@ -0,0 +1,7 @@+# Canonical reconciliation++- `src/commands/sync-diagnostics.ts` + `src/core/persistence/{sync-run,verb-errors}.ts` — bounded source/slug/path/reason diagnostics derive from immutable managed-sync receipts, including when the local failure ledger is unavailable. Direct and resident-owner JSON carry the same receipt; human memory errors lead with the specific write reason without widening frozen v1 error codes. Pending requests retain their original UUID, terminal corrections require a new UUID, and neither retry nor line-ending diagnostics bypasses raw-byte or skip guards.++- `src/core/persistence/reconcile*.ts` — trusted-local exact-page reconciliation: loss-preserving semantic preview, explicit JSON Pointer choices, pinned identity/revision/raw-file/policy checks, durable private preimages and same-ID replay through the existing coordinator. Normal overwrite protection stays unchanged. The bounded audit reports source-scoped drift without repair or checkpoint changes. `src/commands/source-reconcile.ts` provides strict CLI parsing, private artifact I/O, brain routing and resident-owner delegation; the operations stay outside public MCP. Operator flow: `docs/guides/concurrent-writes.md`. Tests cover merge choices, both engines, grants, stale previews, read-only audit, and private files.++- `src/core/cycle/extract-atoms-page-state.ts` — derived page scan/failure state keyed by source incarnation, stable page identity and content hash. Compare-and-swap stamps never update canonical frontmatter. Reviewed reconciliation can carry matching state across removal of legacy bookkeeping fields. Atom item completion still waits for all atoms and provenance links; unsupported managed extraction refuses before provider work.diff --git a/docs/architecture/key-files/core-cycle.md b/docs/architecture/key-files/core-cycle.mdindex a9f1d8482e..034fc51395 100644--- a/docs/architecture/key-files/core-cycle.md+++ b/docs/architecture/key-files/core-cycle.md@@ -13,7 +13,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/cycle/extract-atoms-drain.ts` — pure single-hold bounded drain for the silent lens-phase backlog. `runExtractAtomsDrain(deps, opts)` over injected deps (`withLock`, `runBatch`, `countRemaining`, `now`, optional `onBatch`) loops bounded batches under ONE continuous lock hold, **rediscovering eligibility each batch** (idempotent NOT-EXISTS-on-`source_hash`, so content mutated by a concurrent process simply doesn't match — no cross-window stale cursor), until the backlog is empty OR the time window elapses. Returns `{phase, status, extracted, skipped, remaining, batches, stopped}`. Backs `gbrain dream --phase extract_atoms --drain`. Takes the SAME `cycleLockIdFor(sourceId)` the routine cycle takes (a concurrent autopilot tick genuinely defers with `cycle_already_running`); NO release/reacquire-between-windows primitive. The shared wiring helper `runExtractAtomsDrainForSource(engine, {sourceId, windowSeconds, brainDir?, maxBatches?, onBatch?})` owns the lock+batch+count+defer wiring (dynamic imports of db-lock/cycle/extract-atoms keep the pure loop cheap to unit-test) and is the ONE drain path for three callers — `gbrain dream --drain` (which calls it), the `extract-atoms-drain` Minion handler, and autopilot auto-drain — so lock id / window / defer-on-busy can't drift. `sourceId: undefined` → legacy `gbrain-cycle` lock + `'default'` extraction; a real id → `gbrain-cycle:<id>`. `LockUnavailableError` propagates to the caller (each reports the busy case its own way). Pinned by `test/extract-atoms-drain.test.ts`. The summary's `last_error` always passes through `sanitizeFailureText` (secret/DSN redaction, whitespace collapse, bounded): typed failure records use the source/reason caps, and the count-only `firstError` compatibility path is sanitized to the combined bound, so a provider payload cannot ride either path into `--json` output. `formatDrainProviderFailure(result)` renders the Minion handler's `provider_failure` throw (batches/remaining + `last_error`), so the dead-lettered job's `error_text` names the cause.-- `src/core/cycle/extract-atoms.ts` — the extract_atoms lens phase: mines eligible pages into `atoms/<date>/<stem>-<hash>` pages. Eligibility is `COALESCE(frontmatter->>'atoms_scan_hash','') <> substring(content_hash from 1 for 16)`; the completion marker (`ATOMS_SCAN_HASH_KEY` in utils.ts) is EXCLUDED from `contentHash()`'s input so stamping it can't re-arm the very page it marks (and import-file.ts strips it from untrusted `remote===true` frontmatter so a remote writer can't suppress mining). Atom identity: page-derived atoms fold the source-page slug into the slug hash (8 chars, NUL-separated) so two same-date pages emitting the same title get DISTINCT slugs; the source CONTENT hash is deliberately NOT folded (a reworded source still upserts rather than duping); transcript atoms keep the legacy title-only 6-char hash. `resolvePageAtomSlug` adopts a legacy-slug atom with a compatible binding in place on re-extraction (upgrade idempotency — no migration, no duplicate), while `assertAtomImportBinding` fail-closed refuses to reuse a slug bound to a DIFFERENT source locator. Both share `isCompatibleAtomBinding(frontmatter, sourcePageSlug)` — the ONE definition of compatible: bound to THIS source page, or carrying no `source_slug`/`source_path` at all (pre-binding-era adoption, not a clobber); a `source_path`-bound legacy transcript atom or a different `source_slug` is a different origin, and a non-atom page squatting on the slug is refused. `source_quote` is verified at extraction time against the exact `truncateUtf8` prompt prefix the model saw (`locateQuote` advances by full code points): located quotes persist original characters + [start,end) offsets + `source_quote_verified`; unlocatable quotes are dropped with the atom kept. Edges write before the completion flip; per-item drain failures stay typed (bounded, sanitized, reconcilable). Transcript items carry the same failure-count/tombstone machinery as pages, in the `extract_atoms_transcript_state` table (migration `extract_atoms_transcript_state_table`; keyed `(source_id, file_path, content_hash)` with the 16-char hash prefix, so an edit is a new row and re-eligibilizes): `recordItemFailureCount` counts a transcript's malformed output toward `MAX_DETERMINISTIC_FAILURES`, a zero-yield transcript tombstones immediately (the page `atoms_scan_hash` semantics), and `tombstonedTranscriptsForHashes` is the batch read-side gate mirroring `atomsExistingForHashes` (fail-open on error). Reported as `tombstoned_transcripts` (paths), separate from the page-slug `tombstoned_for_failures`.+- `src/core/cycle/extract-atoms.ts` — the extract_atoms lens phase: mines eligible pages into `atoms/<date>/<stem>-<hash>` pages. Eligibility reads source-incarnation/page/full-hash-keyed derived scan state; scan and failure markers do not mutate canonical frontmatter. Managed extraction refuses before provider work. All atom completion flips and their cardinality check share a transaction after provenance links persist, so a partial match rolls back and stays retryable. Atom identity: page-derived atoms fold the source-page slug into the slug hash (8 chars, NUL-separated) so two same-date pages emitting the same title get DISTINCT slugs; the source CONTENT hash is deliberately NOT folded (a reworded source still upserts rather than duping); transcript atoms keep the legacy title-only 6-char hash. `resolvePageAtomSlug` adopts a legacy-slug atom with a compatible binding in place on re-extraction (upgrade idempotency — no migration, no duplicate), while `assertAtomImportBinding` fail-closed refuses to reuse a slug bound to a DIFFERENT source locator. Both share `isCompatibleAtomBinding(frontmatter, sourcePageSlug)` — the ONE definition of compatible: bound to THIS source page, or carrying no `source_slug`/`source_path` at all (pre-binding-era adoption, not a clobber); a `source_path`-bound legacy transcript atom or a different `source_slug` is a different origin, and a non-atom page squatting on the slug is refused. `source_quote` is verified at extraction time against the exact `truncateUtf8` prompt prefix the model saw (`locateQuote` advances by full code points): located quotes persist original characters + [start,end) offsets + `source_quote_verified`; unlocatable quotes are dropped with the atom kept. Edges write before the completion flip; per-item drain failures stay typed (bounded, sanitized, reconcilable). Transcript items carry the same failure-count/tombstone machinery as pages, in the `extract_atoms_transcript_state` table (migration `extract_atoms_transcript_state_table`; keyed `(source_id, file_path, content_hash)` with the 16-char hash prefix, so an edit is a new row and re-eligibilizes): `recordItemFailureCount` counts a transcript's malformed output toward `MAX_DETERMINISTIC_FAILURES`, a zero-yield transcript tombstones immediately (the same zero-yield policy as pages), and `tombstonedTranscriptsForHashes` is the batch read-side gate mirroring `atomsExistingForHashes` (fail-open on error). Reported as `tombstoned_transcripts` (paths), separate from the page-slug `tombstoned_for_failures`.- `src/core/cycle/extract-facts.ts` — extract_facts cycle phase. Fence is canonical: per-page wipe (`deleteFactsForPage`) + reinsert from `parseFactsFence` + `extractFactsFromFenceText` + `engine.insertFacts`. The reconcile is a no-op when the page's fence-owned DB rows already match the fence; drift on any dimension — content key `(claim, source)`, `row_num`, expiry/supersession state, or the `visibility` / `notability` cells — routes the page through the atomic wipe+reinsert (confidence is not compared). The per-page wipe passes `excludeSourcePrefixes: ['cli:']` so conversation facts (written by `extract-conversation-facts`, on pages with NO `## Facts` fence to recreate them from) survive the reconcile instead of being deleted-with-nothing-to-reinsert. The destructive phase never inherits a failed sync's full-brain walk: `slugs: []` (a real incremental no-op) is distinguished from `slugs: undefined` (full-walk intent) by presence, not length. `runPhaseExtractFacts` (cycle.ts) surfaces a `warn` (`net_fact_deletion`) when the reconcile deletes at least `NET_DELETION_WARN_FLOOR` (50) more facts than it reinserts — the exact signature of a conversation-facts wipe. Empty-fence guard refuses when legacy rows (`row_num IS NULL AND entity_slug IS NOT NULL`) pend backfill (status: warn, hint: `gbrain apply-migrations --yes`). A phantom-redirect pre-pass runs AFTER the legacy-row guard, BEFORE the main reconcile loop: when `opts.brainDir` is set, `runPhantomRedirectPass(engine, brainDir, sourceId, dryRun)` walks unprefixed-slug pages capped by `GBRAIN_PHANTOM_REDIRECT_LIMIT` (default 50). The pass returns `touched_canonicals` — canonical slugs whose disk fence merged with phantom rows; `runExtractFacts` UNIONs them into the main reconcile slug set so canonical's DB facts derive from the merged fence in the same cycle (handles phantom-had-only-on-disk-fence). `ExtractFactsResult` carries six phantom fields: `phantomsScanned`, `phantomsRedirected`, `phantomsAmbiguous`, `phantomsSkippedDrift`, `phantomsLockBusy`, `phantomsMorePending`. Three bubble to `CycleReport.totals` (`phantoms_redirected`, `phantoms_ambiguous`, `phantoms_skipped_drift`).diff --git a/docs/guides/concurrent-writes.md b/docs/guides/concurrent-writes.mdindex 84d4e85747..8690400cdf 100644--- a/docs/guides/concurrent-writes.md+++ b/docs/guides/concurrent-writes.md@@ -60,6 +60,132 @@ Changing the operation or arguments with the same UUID producesRelative times, generated capture slugs, and trusted owner/resolver defaultsare frozen at admission so retries cannot drift.+## Repair a file/database disagreement++**Say to your agent:** *"Preview the disagreement between this page's file and+database record. Preserve both originals, show me conflicting fields, and don't+apply the repair until I've reviewed it. Then retry my original memory request+separately and verify the fact, visibility, and provenance."*++`source_changed` can mean the file and database disagree even when Git reports a+clean checkout. `sources reconcile` is an exact-page repair, not a force-write+bypass. It works with an already-claimed active owner before or after managed+activation. It never claims, transfers, activates, changes source checkpoints,+or repairs an absent owner. Run it on the canonical host with an existing trusted+CLI write registration. Both its original and current grants must permit+`put_page` for the selected source and exact slug. A CLI can delegate to its+resident PGLite owner; ordinary+HTTP/MCP tokens and stdio credentials cannot administer reconciliation.++Select the brain, source, and exact slug explicitly. Store the preview outside the+canonical repository:++```bash+mkdir -p -m 700 ~/.gbrain/repair+gbrain sources reconcile workspace people/example --brain host \+ --preview --out ~/.gbrain/repair/example.preview.json --json+```++Without `--out`, preview returns a summary only. Preview never changes canonical+content. The private artifact includes both originals and the proposed result;+keep it out of Git, shared directories, and public reports. Output files use mode+0600 and never overwrite existing files. Inspect the artifact locally in a private+editor, or use `jq '.conflicts' ~/.gbrain/repair/example.preview.json`. This output+contains private content; do not paste it into shared logs or public reports.++Fields present on only one side are preserved. Disjoint nested fields combine;+different values require explicit choices. Absence is not a deletion, timestamps+do not decide which side wins, and arrays are whole values. Tags stay add-only.+Provenance, visibility, withdrawals, protected takes, and safety metadata retain+their existing policies rather than accepting merge overrides.++For conflicts, create a decisions file containing a JSON array:++```json+[+ { "path": "/frontmatter/profile/role", "action": "take_file" },+ { "path": "/frontmatter/obsolete_note", "action": "delete" }+]+```++Other actions are `take_database` and `set_value` (with a `value`). Paths use JSON+Pointer escaping: `~0` for `~`, `~1` for `/` inside a field name. Unknown,+duplicate, overlapping, and protected-field decisions are rejected. Render the+final policy-checked result before applying:++```bash+gbrain sources reconcile workspace people/example --brain host --preview \+ --from ~/.gbrain/repair/example.preview.json \+ --decisions ~/.gbrain/repair/decisions.json \+ --out ~/.gbrain/repair/example.resolved.json --json+```++The command prints only a summary. Inspect the actual resolved content locally+with `jq '.result' ~/.gbrain/repair/example.resolved.json` before approving it.++After reviewing a `ready` preview, generate and retain one UUID:++```bash+REQUEST_ID="$(bun -e 'console.log(crypto.randomUUID())')"+gbrain sources reconcile workspace people/example --brain host \+ --apply ~/.gbrain/repair/example.resolved.json \+ --request-id "$REQUEST_ID" --json+```++If the initial preview was already `ready`, apply that artifact instead. GBrain+rechecks the revision, raw bytes, source identity, owner epoch/binding, and safety+policy before publishing. Changed inputs require a fresh preview, not automatic+overwrite. Lost response or pending receipt: retry the same artifact and UUID.+Terminal conflict: make a corrected preview and use a new UUID. Inspect+`get_write_request` until committed; accepted is not the same as saved. That+helper requires its own operation grant. If it is not granted, replay the same+apply artifact and UUID to inspect the original request without widening grants.++Both originals are retained privately in `~/.gbrain/reconciliation-previews/`,+independently of temporary recovery records and receipt compaction. Backups use+bounded local capacity; capacity or disk failures refuse the repair before+publication. Local history does not protect against disk loss, and forgetting an+active fact does not erase historical backups.++Inspect backups for the exact page using `sources reconcile workspace+people/example --brain host --backups --json`. After reviewing retention needs+and copying any history you want to keep to another private location, remove an+exact returned reference with `--remove-backup <reference>`. Removal is explicit+and refuses nonterminal or recovering requests. It never deletes the page or+changes its immutable receipt. Backups from an interrupted pre-admission attempt+remain private and require operator inspection rather than automatic removal.++After commitment, submit the originally blocked `remember`, capture, or other+edit separately with its own new UUID. Read back the fact, visibility, and+provenance. Repair never silently replays a failed memory intent.++For bounded, read-only verification after sync:++```bash+gbrain sources reconcile workspace --brain host --audit --limit 25 --json+```++Continue with `--after` and the returned `next_after`. `complete` means the end of+the source was reached, not that it is drift-free. Results name scoped slugs and+reasons without page content. Whole-source audit requires a CLI grant without a+slug-prefix restriction. `sources writer activate --dry-run` includes a bounded+drift sample and identifies incomplete samples without authorizing repairs.++Atom scan/failure bookkeeping now lives outside canonical note metadata so+processing progress does not create new disagreements. Unsupported managed atom+extraction refuses before calling a model; this does not migrate every legacy+maintenance writer to managed publication.++### Roll back safely++Stop submitting new reconciliation requests first. Keep a compatible upgraded+owner running until all accepted requests are terminal and recovery has drained;+inspect the durable receipts before disabling the new command or reverting the+binary. Never downgrade an active reconciliation queue to a version that does+not understand its intents. Leave the additive processing-state table and private+backups in place. Do not automatically restore an old preimage over later edits,+and do not disable guards or change ownership as part of rollback.+## Receipt states and errors| State | Meaning |diff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex a512f63a51..fbaccfdf80 100644--- a/openclaw.plugin.json+++ b/openclaw.plugin.json@@ -1,7 +1,7 @@{"id": "gbrain-context-engine","name": "gbrain",- "version": "0.52.1.0",+ "version": "0.52.2.0","description": "Personal knowledge brain with Postgres + pgvector hybrid search","family": "bundle-plugin","configSchema": {diff --git a/package.json b/package.jsonindex 5762410e83..3405781361 100644--- a/package.json+++ b/package.json@@ -177,7 +177,7 @@"bun": ">=1.3.11"},"license": "MIT",- "version": "0.52.1.0",+ "version": "0.52.2.0","overrides": {"@ai-sdk/provider-utils": "4.0.33","@hono/node-server": "^2.0.5",diff --git a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json b/plugin-variants/gbrain-coding/.claude-plugin/plugin.jsonindex 117857c702..3c4746fd98 100644--- a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json+++ b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-coding",- "version": "0.52.1.0",+ "version": "0.52.2.0","description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 20 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json b/plugin-variants/gbrain-coding/.codex-plugin/plugin.jsonindex a20fc5537c..99f9e7e9e2 100644--- a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json+++ b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-coding",- "version": "0.52.1.0",+ "version": "0.52.2.0","description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 20 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-coding/README.md b/plugin-variants/gbrain-coding/README.mdindex 10e2cf4b6c..2d32819605 100644--- a/plugin-variants/gbrain-coding/README.md+++ b/plugin-variants/gbrain-coding/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.52.1.0 -->+<!-- gbrain-plugin-tree-stamp: 0.52.2.0 --># gbrain-coding (generated persona variant — do not hand-edit)Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant.diff --git a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json b/plugin-variants/gbrain-daily/.claude-plugin/plugin.jsonindex 5cecfb1e4b..2feef8237a 100644--- a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json+++ b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-daily",- "version": "0.52.1.0",+ "version": "0.52.2.0","description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 19 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json b/plugin-variants/gbrain-daily/.codex-plugin/plugin.jsonindex df6821daa7..d634161179 100644--- a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json+++ b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-daily",- "version": "0.52.1.0",+ "version": "0.52.2.0","description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 19 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-daily/README.md b/plugin-variants/gbrain-daily/README.mdindex babbf5e226..ed09ff90c6 100644--- a/plugin-variants/gbrain-daily/README.md+++ b/plugin-variants/gbrain-daily/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.52.1.0 -->+<!-- gbrain-plugin-tree-stamp: 0.52.2.0 --># gbrain-daily (generated persona variant — do not hand-edit)Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant.diff --git a/plugin/README.md b/plugin/README.mdindex e2d5ce0e31..2437c6d4b4 100644--- a/plugin/README.md+++ b/plugin/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.52.1.0 -->+<!-- gbrain-plugin-tree-stamp: 0.52.2.0 --># gbrain plugin skill tree (generated — do not hand-edit)This tree is the curated skill set for the gbrain Codex and Claude Codediff --git a/scripts/e2e-test-map.ts b/scripts/e2e-test-map.tsindex 466df9dba5..3fb6086cd0 100644--- a/scripts/e2e-test-map.ts+++ b/scripts/e2e-test-map.ts@@ -159,7 +159,10 @@ export const E2E_TEST_MAP: Record<string, string[]> = {// postgres.js bind paths + JSONB shapes + parity vs PGLite."src/core/db-lock.ts": ["test/e2e/db-lock-acquisition-token.test.ts", "test/e2e/sync-lock-overlap-postgres.test.ts"],"src/core/lease-schema.ts": ["test/e2e/db-lock-acquisition-token.test.ts"],- "src/core/persistence/**": ["test/e2e/persistence-chaos.test.ts", "test/e2e/persistence-runtime-matrix.test.ts", "test/e2e/persistence-admin-intent.test.ts"],+ "src/core/persistence/**": ["test/e2e/persistence-chaos.test.ts", "test/e2e/persistence-runtime-matrix.test.ts", "test/e2e/persistence-admin-intent.test.ts", "test/e2e/reconcile-crash.test.ts", "test/e2e/reconcile-crash-unactivated.test.ts", "test/e2e/reconcile-pgbouncer.test.ts"],+ "src/commands/source-reconcile.ts": ["test/e2e/reconcile-crash.test.ts", "test/e2e/reconcile-crash-unactivated.test.ts", "test/e2e/reconcile-pgbouncer.test.ts"],+ "src/core/cycle/extract-atoms.ts": ["test/e2e/extract-atoms-page-state.test.ts", "test/e2e/cycle.test.ts", "test/e2e/dream.test.ts", "test/e2e/multi-source-bug-class.test.ts"],+ "src/core/cycle/extract-atoms-page-state.ts": ["test/e2e/extract-atoms-page-state.test.ts", "test/e2e/reconcile-crash.test.ts", "test/e2e/reconcile-crash-unactivated.test.ts", "test/e2e/reconcile-pgbouncer.test.ts"],"src/commands/migrations/v0_13_1.ts": ["test/e2e/grandfather-projection-postgres.test.ts"],"src/core/pool-budget.ts": ["test/e2e/persistence-runtime-matrix.test.ts"],"src/core/connection-manager.ts": ["test/e2e/persistence-runtime-matrix.test.ts", "test/e2e/pgbouncer-teardown.test.ts"],diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 924bc25cd9..7311a63a79 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -30,7 +30,7 @@ src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connesrc/core/minions/handlers/subagent.ts 1918 ratchet merged: master v131 settle rework + dream-wave C5 peel + C6 accounting + C7 lease heartbeats/lost-lease aborts + C9 oneshot dispatch + adversarial fix batches; grown by #4078 subagent-loop capability fix; +6 lines (reasoning-item replay: adaptContentBlocksToChatBlocks handles 'reasoning' blocks); +3 wave G #4514: Anthropic-via-OpenRouter allowed on the subagent loop; +36 lines (code review, same PR): isPromptTooLongError walks a bounded .cause chain so it still matches post-normalizeAIError() wrapping, plus extractPromptTooLongDetail so the dead-lettered job's error carries the matched provider detail instead of the generic normalizeAIError() wrapper text; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; #5105: +13 call-site wiring to shared tool-write-identity helper across fresh and replay dispatchsrc/commands/bootstrap.ts 2115 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness); +5 for the harnessDetect test seam (bulk lives in core/bootstrap/harness.ts); +23 for the contract subcommand dispatcher glue (#4105 absorb — bulk lives in core/bootstrap/contract.ts); +codex hooks-consent gate + mcp+hooks receipt registration + uninstall arm; +42 ambient-writeback WP8: interview-time SURFACE_MULTIUSER audience apply (pre-init ordering) + applyDeclaredAudienceFromInterview; +3 #4897 harness usage clause documenting --source ID semanticssrc/core/minions/worker.ts 1546 ratchet grandfathered at merge (grew past the 1500 cap on master, #4170); grown v0.46.11.0 five-issue wave; security: durable queued authority and confined filesystem dispatch-src/commands/sources.ts 1988 ratchet grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules+src/commands/sources.ts 1993 ratchet grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules; canonical reconciliation: +5 engine-free sibling-command dispatch and help row, implementation remains in source-reconcile.tssrc/core/link-extraction.ts 1878 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class); +62 #4977: role-prior suppression in machine-list sections (rolePriorSuppressedRanges, EntityRef.index); +3 composed with #4985 (variation-selector strip) in the same wave; +4 #4995: markdown-link anchor strip + lowercase-candidate rationale comments; +6 pre-landing review: #4977 suppression on code-stripped content + truthful watermark/section-list comments; T2: source-qualified inference and atomic origin-scoped derived linkssrc/core/embedding-migration.ts 1545 ratchet new row: crossed 1500 in v0.46.25.0 fix waves (#4305 #4306 chunk-model truth helpers)src/core/github-source.ts 1560 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment)diff --git a/skills/migrations/v0.52.2.0.md b/skills/migrations/v0.52.2.0.mdnew file mode 100644index 0000000000..3554194ba8--- /dev/null+++ b/skills/migrations/v0.52.2.0.md@@ -0,0 +1,54 @@+# v0.52.2.0: exact-page reconciliation and derived atom scan state++Upgrade resident owners and maintenance workers before using the new repair+commands. Preserve all existing ownership, source roots, activation state, and+checkpoints. Never delete owner markers, disable guards, or run writer claim,+transfer, or activate as a shortcut for a content disagreement.++Reconciliation requires the existing trusted CLI registration's original and+current grants to permit `put_page` for the exact source and slug. Whole-source+audit additionally requires no slug-prefix restriction. Receipt lookup needs its+own `get_write_request` grant; replaying the original apply artifact and UUID is+the alternative without changing permissions.++1. Let `gbrain upgrade` apply schema migration 163. If schema maintenance failed,+ run `gbrain apply-migrations --yes` using the existing authorized maintenance+ role. The migration adds derived processing state and conservatively copies+ matching legacy markers; it does not rewrite canonical page content.+2. Restart upgraded resident writers and maintenance workers so older processes+ cannot keep writing legacy scan markers. Do not change providers or authorize+ paid enrichment as part of this migration.+3. On the canonical host, use `gbrain sources reconcile <source> --brain <brain>+ --audit --limit 25 --json` for bounded, read-only verification. Continue with+ the returned `next_after` cursor. A sample is not proof that the whole source+ is clean. A missing or invalid owner requires operator diagnosis, not automatic+ registration or activation.+4. For each affected page, run an exact preview using `sources reconcile <source>+ <slug> --brain <brain> --preview`. Save an actionable artifact only to a new+ private path outside canonical repositories with `--out`. Relay conflicts and+ the final resolved result to the operator before applying. Never choose file+ wins, database wins, or timestamp wins on the operator's behalf.+5. Apply only an operator-reviewed ready artifact with an explicit request UUID.+ Keep that UUID after a lost response or pending result. Changed preconditions+ require a new preview; a terminal conflict requires a new request UUID. The+ command retains both originals privately and leaves topology unchanged.+6. Submit the originally blocked memory intent as a separate new request after+ repair commits, then independently read back the fact, visibility, and+ provenance. A committed repair receipt alone does not prove that memory was+ inserted.++Private retained originals outlive temporary recovery records and receipt+compaction. Inspect them using `sources reconcile <source> <slug> --brain <brain>+--backups --json`. Remove an exact terminal backup only after explicit operator+approval with `--remove-backup <reference>`; nonterminal/recovering backups cannot+be removed. Forgetting active memory does not erase backup history.++See `docs/guides/concurrent-writes.md` for the complete command and decision-file+examples. Unsupported managed atom extraction now refuses before model calls;+this migration does not add a general managed dream/maintenance publication lane.++If rollback is necessary, stop new repair submissions and drain or recover every+accepted request using a compatible upgraded owner before reverting the binary.+Never downgrade a live reconciliation queue, remove the additive table or private+backups, or restore an old preimage over newer edits. Inspect the receipt state+instead of changing ownership or disabling writer guards.diff --git a/skills/skills.lock.json b/skills/skills.lock.jsonindex ef4e64d8e1..3c5ebc0277 100644--- a/skills/skills.lock.json+++ b/skills/skills.lock.json@@ -142,6 +142,7 @@"migrations/v0.51.7.0.md": "c34621712c4fc8597e193c7fc44b588cab8622584204a2b6f59ffd24b9d3624c","migrations/v0.51.8.0.md": "16af7c14f4ee12029b87ee2f07446a6355216ddf6109f54c2fcc0adbd558b09a","migrations/v0.52.1.0.md": "7b54ff2e4e881658020d725aa1709f10b34e118974e1899c4c46aca3712409a1",+ "migrations/v0.52.2.0.md": "07568b099264e56f909f46eb417c4a512788e893e8ae6080423ad6ae06918076","migrations/v0.7.0.md": "97c2740445a10b1c5c7123c17dbd625fa27a94095b85d27c2b278da756c4c59a","migrations/v0.8.0.md": "1919ff8b8f3680612ff888e7cfcc0d86ece5d5304ae19af4497bdf40b050561a","migrations/v0.8.1.md": "fad7341cfb5e02545fb8a23221d12ab395fc3d8db15d1d8ee8a18844aea6563a",diff --git a/src/cli.ts b/src/cli.tsindex f954cd267a..330b4ef1a7 100755--- a/src/cli.ts+++ b/src/cli.ts@@ -2095,7 +2095,7 @@ async function handleCliOnly(command: string, args: string[]) {}// Local deferred connections must not bypass the remote installation route.- if (command === 'capture' || command === 'forget' || command === 'call' || command === 'sources' && ['writer', 'add', 'remove', 'archive', 'restore', 'purge', 'set-path', 'reclone'].includes(args[0]) || command === 'takes' && ['add', 'update', 'supersede', 'resolve'].includes(args[0]) && !hasHelpFlag(args)) {+ if (command === 'capture' || command === 'forget' || command === 'call' || command === 'sources' && ['writer', 'reconcile', 'add', 'remove', 'archive', 'restore', 'purge', 'set-path', 'reclone'].includes(args[0]) || command === 'takes' && ['add', 'update', 'supersede', 'resolve'].includes(args[0]) && !hasHelpFlag(args)) {const { runDeferredPersistenceCommand } = await import('./commands/persistence-delegate.ts');await runDeferredPersistenceCommand(command, args, connectEngine);return;diff --git a/src/commands/persistence-delegate.ts b/src/commands/persistence-delegate.tsindex ee2964485e..78581be34e 100644--- a/src/commands/persistence-delegate.ts+++ b/src/commands/persistence-delegate.ts@@ -14,11 +14,11 @@ export async function reportPersistenceCliError(error: unknown, json = false,const detail = error.toJSON();if (json) await out(JSON.stringify(detail, null, 2) + '\n');console.error(error instanceof OperationError || error instanceof RemoteMcpError- ? `Error [${detail.error}]: ${detail.message}` : error.message);+ ? `Error [${'write_error' in detail && detail.write_error || detail.error}]: ${detail.message}` : error.message);if (detail.suggestion) console.error(`Fix: ${detail.suggestion}`);- if (!json && error instanceof RemoteMcpError) {- console.error(`Request: ${error.detail?.request_id ?? error.detail?.write_request?.request_id}`);- }+ const receipt = 'write_request' in detail ? detail.write_request : undefined;+ const requestId = receipt?.request_id ?? ('request_id' in detail ? detail.request_id : undefined);+ if (requestId) console.error(`Request: ${requestId}${receipt ? ` (${receipt.state})` : ''}`);setCliExitVerdict(1);return true;}@@ -56,7 +56,10 @@ export async function runDeferredPersistenceCommand(const { runTakesMutation } = await import('./takes-mutation.ts');await runTakesMutation(getEngine, args);} else if (command === 'sources') {- if (args[0] === 'writer') {+ if (args[0] === 'reconcile') {+ const { runReconcileCli } = await import('./source-reconcile.ts');+ await runReconcileCli(args.slice(1));+ } else if (args[0] === 'writer') {const { runPersistenceAdminCli } = await import('./persistence-admin.ts');await runPersistenceAdminCli('writer', args.slice(1));} else {diff --git a/src/commands/source-reconcile.ts b/src/commands/source-reconcile.tsnew file mode 100644index 0000000000..b159c45444--- /dev/null+++ b/src/commands/source-reconcile.ts@@ -0,0 +1,214 @@+import { randomUUID } from 'node:crypto';+import { closeSync, constants, fstatSync, fsyncSync, linkSync, lstatSync, openSync, readFileSync, realpathSync, unlinkSync, writeFileSync } from 'node:fs';+import { basename, dirname, join, resolve } from 'node:path';+import type { BrainEngine } from '../core/engine.ts';+import { getCliOptions } from '../core/cli-options.ts';+import { finishCliTeardown, setCliExitVerdict, writeStdoutFinal } from '../core/cli-force-exit.ts';+import { isThinClient, loadConfig, toEngineConfig } from '../core/config.ts';+import { loadMounts } from '../core/brain-registry.ts';+import { OperationError } from '../core/ops/contract.ts';+import { isValidSourceId } from '../core/source-id.ts';+import { validateSlug } from '../core/utils.ts';+import { runPersistenceAdministration } from '../core/persistence/administration.ts';+import type { PersistenceAdminOperation } from '../core/persistence/admin-contract.ts';+import { assertManagedFilesystemWrite } from '../core/persistence/filesystem-guard.ts';+import { PERSISTENCE_IPC_MAX_BYTES } from '../core/persistence/ipc.ts';+import { maybeDelegateLocalAdministration, persistenceConfigForBrain } from '../core/persistence/local-client.ts';+import { isWriteRequestId } from '../core/persistence/types.ts';+import { readLocalWriter, withVerifiedLocalRegistration } from '../core/persistence/identity.ts';+import { reportPersistenceCliError } from './persistence-delegate.ts';++export const RECONCILE_HELP = `Usage:+ gbrain sources reconcile <source> <slug> --brain <id> [--preview] [--out <new-file>] [--json]+ gbrain sources reconcile <source> <slug> --brain <id> --preview --from <preview-file>+ --decisions <decisions-file> --out <new-file> [--json]+ gbrain sources reconcile <source> <slug> --brain <id> --apply <resolved-preview-file>+ --request-id <uuid> [--json]+ gbrain sources reconcile <source> --brain <id> --audit [--limit <1-100>] [--after <slug>] [--json]+ gbrain sources reconcile <source> <slug> --brain <id> --backups [--limit <1-100>] [--after <request-uuid>] [--json]+ gbrain sources reconcile <source> <slug> --brain <id> --remove-backup <exact-reference> [--json]++Preview is the default and never changes canonical content. --out creates a new+private file outside canonical worktrees; it never replaces an existing file.+Resolve conflicts with JSON-Pointer decisions and inspect the resolved preview+before applying. Apply preserves both originals and uses the current canonical+owner without changing ownership, activation, roots, or sync checkpoints.+The caller must already have a trusted CLI registration whose original and+current grants permit put_page for this source and exact slug.+get_write_request needs its own operation grant; identical apply replay is+available without that receipt helper. Inspect the private artifact's .conflicts+and .result locally before applying; stdout contains only a summary.+Use the same request ID and arguments after a lost response or pending receipt.+After a terminal conflict, make a new preview and use a new request ID.+Retry any originally blocked memory write separately, with its own new ID.+Audit is bounded and read-only; its cursor is not a sync checkpoint.+Backups persist until explicitly removed. Removal deletes that private history,+not the page or immutable receipt, and refuses nonterminal/recovering requests.`;++export interface ReconcileCliArgs {+ operation: PersistenceAdminOperation;+ params: Record<string, unknown>;+ brain?: string;+ json: boolean;+ output?: string;+ input?: string;+ decisions?: string;+}++export function parseReconcileArgs(args: string[]): ReconcileCliArgs {+ const flags = new Map<string, string | true>();+ const positional: string[] = [];+ const boolean = new Set(['--preview', '--audit', '--backups', '--json']);+ const values = new Set(['--brain', '--out', '--from', '--decisions', '--apply', '--request-id', '--limit', '--after', '--remove-backup']);+ for (let i = 0; i < args.length; i++) {+ const token = args[i];+ if (!token.startsWith('-')) { positional.push(token); continue; }+ const equal = token.indexOf('=');+ const flag = equal < 0 ? token : token.slice(0, equal);+ if (flags.has(flag)) throw new OperationError('invalid_params', `Duplicate option ${flag}.`);+ if (boolean.has(flag)) {+ if (equal >= 0) throw new OperationError('invalid_params', `${flag} does not accept a value.`);+ flags.set(flag, true);+ continue;+ }+ if (!values.has(flag)) throw new OperationError('invalid_params', `Unknown reconciliation option: ${flag}.`);+ const value = equal >= 0 ? token.slice(equal + 1) : args[++i];+ if (!value || value.startsWith('-') || value.includes('\0')) throw new OperationError('invalid_params', `${flag} requires a value.`);+ flags.set(flag, value);+ }+ const [source, slug] = positional;+ if (!isValidSourceId(source)) throw new OperationError('invalid_params', 'Reconciliation requires one explicit source ID.');+ const audit = flags.has('--audit');+ const backups = flags.has('--backups') || flags.has('--remove-backup');+ if (positional.length !== (audit ? 1 : 2)) throw new OperationError('invalid_params', audit+ ? 'Audit requires one source and no page slug.' : 'Reconciliation requires one source and one exact page slug.');+ if (slug !== undefined) {+ try { validateSlug(slug); } catch { throw new OperationError('invalid_params', 'Invalid page slug.'); }+ if (/[?*]/.test(slug)) throw new OperationError('invalid_params', 'Reconciliation does not accept page patterns.');+ }+ const applying = flags.has('--apply');+ if (applying && ['--preview', '--from', '--decisions', '--out', '--audit', '--backups', '--remove-backup'].some(flag => flags.has(flag))) {+ throw new OperationError('invalid_params', 'Apply cannot be combined with preview, decisions, output, or audit options.');+ }+ if (!applying && flags.has('--request-id')) throw new OperationError('invalid_params', '--request-id is only valid with --apply.');+ if (applying && !isWriteRequestId(flags.get('--request-id'))) throw new OperationError('invalid_params', 'Apply requires an explicit UUID --request-id.');+ if (flags.has('--decisions') && !flags.has('--from')) throw new OperationError('invalid_params', '--decisions requires --from.');+ if (!audit && !flags.has('--backups') && (flags.has('--limit') || flags.has('--after'))) throw new OperationError('invalid_params', '--limit and --after are only valid with --audit or --backups.');+ if (audit && ['--preview', '--out', '--from', '--decisions'].some(flag => flags.has(flag))) throw new OperationError('invalid_params', 'Audit cannot create or resolve a page preview.');+ if (backups && ['--preview', '--out', '--from', '--decisions', '--apply', '--audit'].some(flag => flags.has(flag)) || flags.has('--backups') && flags.has('--remove-backup')) {+ throw new OperationError('invalid_params', 'Backup administration cannot be combined with preview, apply, audit, or another backup action.');+ }+ const brain = flags.get('--brain') as string | undefined;+ if (brain !== undefined && !isValidSourceId(brain)) throw new OperationError('invalid_params', 'Invalid brain ID.');+ const params: Record<string, unknown> = { source_id: source, ...(slug ? { slug } : {}) };+ if (backups) {+ params.action = flags.has('--backups') ? 'list' : 'remove';+ if (flags.has('--remove-backup')) params.backup_reference = flags.get('--remove-backup');+ if (flags.has('--after') && !isWriteRequestId(flags.get('--after'))) throw new OperationError('invalid_params', 'Backup pagination requires a request UUID cursor.');+ }+ if (applying) params.request_id = flags.get('--request-id');+ if (flags.has('--limit')) {+ const limit = Number(flags.get('--limit'));+ if (!Number.isInteger(limit) || limit < 1 || limit > 100) throw new OperationError('invalid_params', 'Audit limit must be an integer from 1 to 100.');+ params.limit = limit;+ }+ if (flags.has('--after')) params.after = flags.get('--after');+ return { operation: audit ? 'writer_reconcile_audit' : backups ? 'writer_reconcile_backups' : applying ? 'writer_reconcile_apply' : 'writer_reconcile_preview',+ params, brain, json: flags.has('--json'), output: flags.get('--out') as string | undefined,+ input: (flags.get('--apply') ?? flags.get('--from')) as string | undefined,+ decisions: flags.get('--decisions') as string | undefined };+}++export function readReconcileJson(path: string): unknown {+ let fd: number | undefined;+ try {+ const target = resolve(path);+ if (!lstatSync(target).isFile()) throw new OperationError('invalid_params', 'Reconciliation input must be a regular JSON file, not a symbolic link.');+ fd = openSync(target, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);+ const stat = fstatSync(fd);+ if (!stat.isFile() || stat.size > PERSISTENCE_IPC_MAX_BYTES - 65536) throw new OperationError('invalid_params', 'Reconciliation input must be a bounded regular JSON file.');+ const content = readFileSync(fd);+ if (content.byteLength > PERSISTENCE_IPC_MAX_BYTES - 65536) throw new OperationError('invalid_params', 'Reconciliation input exceeds the transport limit.');+ try { return JSON.parse(content.toString('utf8')); }+ catch { throw new OperationError('invalid_params', 'Reconciliation input is not valid JSON.'); }+ } catch (error) {+ if (error instanceof OperationError) throw error;+ throw new OperationError('invalid_params', 'Cannot read the reconciliation input as a regular JSON file.');+ } finally { if (fd !== undefined) closeSync(fd); }+}++export function writeReconcilePreview(path: string, preview: unknown): void {+ let temporary: string | undefined;+ let fd: number | undefined;+ try {+ const requested = resolve(path);+ const directory = realpathSync(dirname(requested));+ const target = join(directory, basename(requested));+ assertManagedFilesystemWrite(target);+ const content = JSON.stringify(preview, null, 2) + '\n';+ if (Buffer.byteLength(content) > PERSISTENCE_IPC_MAX_BYTES - 65536) throw new OperationError('invalid_params', 'The preview exceeds the artifact size limit.');+ temporary = join(directory, `.${basename(target)}.${randomUUID()}.tmp`);+ fd = openSync(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);+ writeFileSync(fd, content);+ fsyncSync(fd);+ closeSync(fd);+ fd = undefined;+ assertManagedFilesystemWrite(target);+ linkSync(temporary, target);+ if (process.platform !== 'win32') {+ const directoryFd = openSync(directory, constants.O_RDONLY);+ try { fsyncSync(directoryFd); } finally { closeSync(directoryFd); }+ }+ } catch (error) {+ if (error instanceof OperationError) throw error;+ throw new OperationError('storage_error', 'Cannot create the private preview file. Use an existing directory outside the canonical worktree and a new filename.');+ } finally {+ if (fd !== undefined) closeSync(fd);+ if (temporary) {+ try { unlinkSync(temporary); } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; }+ }+ }+}++export async function runReconcileCli(args: string[], connected?: BrainEngine): Promise<void> {+ if (!args.length || args.includes('--help') || args.includes('-h')) { console.log(RECONCILE_HELP); return; }+ let owned: BrainEngine | undefined;+ try {+ const parsed = parseReconcileArgs(args);+ const brain = parsed.brain ?? getCliOptions().brain;+ if (!brain) throw new OperationError('invalid_params', 'Select the brain explicitly with --brain <id> (use --brain host for the local brain).');+ const config = persistenceConfigForBrain(loadConfig(), brain, brain === 'host' ? [] : loadMounts());+ if (!config) throw new OperationError('invalid_params', 'The selected brain has no configuration.');+ if (isThinClient(config)) throw new OperationError('permission_denied', 'Reconciliation runs on the canonical host using its existing trusted CLI registration. A remote token cannot repair files.');+ if (parsed.input) parsed.params[parsed.operation === 'writer_reconcile_apply' ? 'preview' : 'from'] = readReconcileJson(parsed.input);+ if (parsed.decisions) parsed.params.decisions = readReconcileJson(parsed.decisions);+ if (parsed.output) parsed.params.output_path = resolve(parsed.output);+ const delegated = connected ? { handled: false as const } : await maybeDelegateLocalAdministration(parsed.operation, parsed.params, config,+ { timeoutMs: getCliOptions().timeoutMs ?? undefined });+ let result: Record<string, unknown>;+ if (delegated.handled) result = delegated.result as Record<string, unknown>;+ else {+ if (!connected) {+ const { createEngine } = await import('../core/engine-factory.ts');+ owned = await createEngine(toEngineConfig(config));+ await owned.connect(toEngineConfig(config));+ }+ const engine = connected ?? owned!;+ const registration = await readLocalWriter(engine, 'cli');+ result = await withVerifiedLocalRegistration(engine, registration,+ () => runPersistenceAdministration(engine, parsed.operation, parsed.params));+ }+ const { preview, ...summary } = result;+ if (parsed.output) {+ if (!preview) throw new OperationError('storage_error', 'The owner did not return the requested preview.');+ writeReconcilePreview(parsed.output, preview);+ summary.preview_file = resolve(parsed.output);+ }+ await writeStdoutFinal(JSON.stringify(summary, null, 2) + '\n');+ } catch (error) {+ if (!await reportPersistenceCliError(error, args.includes('--json'))) {+ console.error('Reconciliation could not complete. Inspect the canonical owner before retrying.');+ setCliExitVerdict(1);+ }+ } finally { if (owned) await finishCliTeardown({ engine: owned, drainTimeoutMs: 1000 }); }+}diff --git a/src/commands/sources.ts b/src/commands/sources.tsindex 3b99d7de29..8359df0b47 100644--- a/src/commands/sources.ts+++ b/src/commands/sources.ts@@ -1793,6 +1793,10 @@ async function runAudit(engine: BrainEngine, args: string[]): Promise<void> {export async function runSources(engine: BrainEngine, args: string[]): Promise<void> {const sub = args[0];const rest = args.slice(1);+ if (sub === 'reconcile') {+ const { runReconcileCli } = await import('./source-reconcile.ts');+ return runReconcileCli(rest, engine);+ }if (sub === 'inspect') {const { runCompanyBrainInspection } = await import('./company-brain-inspect.ts');return runCompanyBrainInspection(rest);@@ -1904,6 +1908,7 @@ Subcommands:with committed files; --force skips that check.list [--json] List registered sources with page counts.writer status|claim|activate|transfer Inspect, activate or transfer canonical ownership (see writer --help).+ reconcile <id> <slug> --brain <id> Preview or apply a guarded file/database repair (see reconcile --help).remove <id> [--confirm-destructive] [--dry-run]Permanently delete a source and all its data.Shows impact preview. Requires --confirm-destructivediff --git a/src/commands/sync-diagnostics.ts b/src/commands/sync-diagnostics.tsnew file mode 100644index 0000000000..5fc6173af2--- /dev/null+++ b/src/commands/sync-diagnostics.ts@@ -0,0 +1,16 @@+import type { SyncResult } from './sync.ts';++export function printManagedSyncDiagnostic(result: SyncResult, sink: NodeJS.WriteStream): boolean {+ const d = result.managedWrite;+ if (!d) return false;+ const write = (line: string) => sink.write(line + '\n');+ write(result.status === 'blocked_by_failures'+ ? `Sync BLOCKED at ${result.toCommit.slice(0, 8)}: ${result.failedFiles ?? 0} file(s) failed.`+ : 'Sync PARTIAL: an accepted write is not committed; last_commit is unchanged.');+ write(` ${d.write_error} [${d.reason}]: ${d.message}`);+ write(` Source: ${JSON.stringify(d.source_id)}; slug: ${JSON.stringify(d.slug)}; path: ${JSON.stringify(d.path)}`);+ write(` Request: ${d.write_request.request_id} (${d.write_request.state})`);+ write(` Fix: ${d.suggestion}`);+ if (d.ledger_recorded === false) write(' Local failure ledger unavailable; the durable receipt above remains authoritative.');+ return true;+}diff --git a/src/commands/sync-persistence-delegate.ts b/src/commands/sync-persistence-delegate.tsindex a8f9624c74..3fdb2ae832 100644--- a/src/commands/sync-persistence-delegate.ts+++ b/src/commands/sync-persistence-delegate.ts@@ -14,6 +14,8 @@ import { reportPersistenceCliError } from './persistence-delegate.ts';import { setCliExitVerdict, writeStdoutFinal } from '../core/cli-force-exit.ts';import type { SyncResult } from './sync.ts';import { buildSingleSyncJsonEnvelope } from '../core/sync-embed-backfill.ts';+import { printManagedSyncDiagnostic } from './sync-diagnostics.ts';+import { parseDurationSeconds } from '../core/sync-concurrency.ts';export async function parsePersistenceSyncArgs(args:string[],cwd=process.cwd()) {const options:Record<string,unknown>={};@@ -32,7 +34,10 @@ export async function parsePersistenceSyncArgs(args:string[],cwd=process.cwd())const source=resolveSourceIdEngineFree(typeof options.sourceId==='string'?options.sourceId:null,cwd);if(source==='__all__')throw new OperationError('invalid_params','Owner-delegated sync requires one explicit source.');if(source)options.sourceId=source;- return validateSyncWireParams({options,cwd,timeoutSeconds:await deriveDelegatedTimeoutSeconds(args)});+ const softTimeout=parseDurationSeconds(args.find((_,i)=>args[i-1]==='--timeout'),'--timeout');+ const hardTimeout=await deriveDelegatedTimeoutSeconds(args);+ const timeoutSeconds=softTimeout && softTimeout>0 ? hardTimeout>0 ? Math.min(softTimeout,hardTimeout) : softTimeout : hardTimeout;+ return validateSyncWireParams({options,cwd,timeoutSeconds});}/** Any resident native owner may proxy; its durable registration, not a process label, authorizes work. */export async function maybeDelegateSyncToPersistence(hostConfig:GBrainConfig|null,args:string[]):Promise<boolean> {@@ -55,14 +60,18 @@ export async function maybeDelegateSyncToPersistence(hostConfig:GBrainConfig|nulif(performance.now()>=deadline){result={...result,reason:'timeout'};break;}await new Promise(resolve=>setTimeout(resolve,result.reason==='writer_pending'?250:0));}- if(args.includes('--json'))await writeStdoutFinal(JSON.stringify(buildSingleSyncJsonEnvelope(result.source_id??params.options.sourceId??'default',result))+'\n');+ if(args.includes('--json')) {+ await writeStdoutFinal(JSON.stringify({ ...buildSingleSyncJsonEnvelope(result.source_id??params.options.sourceId??'default',result),+ ...(result.managedWrite ? { managed_write: result.managedWrite } : {}) })+'\n');+ printManagedSyncDiagnostic(result, process.stderr);+ }else {(await import('./sync.ts')).printSyncResult(result);if(!params.options.dryRun&&!params.options.noEmbed&&result.added+result.modified>0) {console.error('[sync] embeds deferred — the owner drains them using its configured provider and keys.');}}- if(result.status==='blocked_by_failures'||result.reason==='pull_failed')setCliExitVerdict(1);+ if(result.managedWrite||result.status==='blocked_by_failures'||result.reason==='pull_failed')setCliExitVerdict(1);return true;}catch(error){if(error instanceof PersistenceIpcTransportError&&error.sent)error=new OperationError('write_pending','The sync acknowledgment was lost; accepted page requests retain their IDs.','Repeat the same sync options to resume the durable cursor.');diff --git a/src/commands/sync.ts b/src/commands/sync.tsindex c536f46df4..69986a3712 100644--- a/src/commands/sync.ts+++ b/src/commands/sync.ts@@ -72,6 +72,7 @@ import { loadStorageConfig, findDbOnlyCollisions } from '../core/storage-config.// time. integrations.ts is side-effect-free at module load (pure recipe I/O// helpers), so a static import is safe here.import { getConfiguredCollectorOutputs } from './integrations.ts';+import { printManagedSyncDiagnostic } from './sync-diagnostics.ts';import { getDefaultSourcePath } from '../core/source-resolver.ts';// v0.41.32.0: stamp the durable newest-COMMIT timestamp at sync time so the// remote staleness path reads a column instead of shelling out to git.@@ -244,6 +245,7 @@ export function shouldNudgeAfterSync(status: SyncResult['status']): boolean {}export interface SyncResult {+ managedWrite?: import('../core/persistence/sync-run.ts').ManagedSyncWriteDiagnostic;status: 'up_to_date' | 'synced' | 'first_sync' | 'dry_run' | 'blocked_by_failures' | 'partial';fromCommit: string | null;toCommit: string;@@ -5227,11 +5229,11 @@ See also:const r = results[i];const src = runnableSources[i];if (r.status === 'fulfilled') {- writeHuman(` ✓ ${src.name}: ${r.value.result.status} (added=${r.value.result.added}, modified=${r.value.result.modified}, deleted=${r.value.result.deleted})`);+ if (!printManagedSyncDiagnostic(r.value.result, humanSink)) writeHuman(` ✓ ${src.name}: ${r.value.result.status} (added=${r.value.result.added}, modified=${r.value.result.modified}, deleted=${r.value.result.deleted})`);perSourceResults.push({sourceId: src.id,sourceName: src.name,- status: 'ok',+ status: r.value.result.managedWrite ? 'error' : 'ok',result: r.value.result,});} else {@@ -5254,7 +5256,7 @@ See also:perSourceResults.push({sourceId: src.id,sourceName: src.name,- status: 'ok',+ status: result.managedWrite ? 'error' : 'ok',result,});} catch (e: unknown) {@@ -5292,6 +5294,7 @@ See also:// #3068: surface the partial reason (e.g. pull_failed) so JSON// consumers can distinguish a self-healing timeout from a wedge....(r.result.reason ? { reason: r.result.reason } : {}),+ ...(r.result.managedWrite ? { managed_write: r.result.managedWrite } : {}),added: r.result.added,modified: r.result.modified,deleted: r.result.deleted,@@ -5398,20 +5401,12 @@ See also:}}- // Bug 9 — --retry-failed: before running normal sync, clear acknowledgment- // flags so the sync picks them up as fresh work. The actual re-attempt- // happens inside the regular incremental/full loop because once the commit- // pointer is behind the failures, the diff naturally revisits them.if (retryFailed) {- // v0.42.42.0 (#2139, D13C): scope the retry count to THIS source — rows- // carry source_id (#1939), so a single-source retry shouldn't report- // another source's failures.const failures = unacknowledgedSyncFailures().filter(f => f.source_id === sourceId);if (failures.length === 0) {- slog('No unacknowledged sync failures to retry.');+ slog('No local ledger entries; checking the durable sync cursor for unfinished or failed writes.');} else {slog(`Retrying ${failures.length} previously-failed file(s)...`);- // Don't acknowledge them yet — they must succeed to clear.}}@@ -5433,7 +5428,7 @@ See also:// Routed through the owned verdict channel (NOT bare `process.exitCode`,// which PGLite's Emscripten runtime clobbers mid-run — see// src/core/cli-force-exit.ts).- if (result.status === 'partial' && result.reason === 'pull_failed') {+ if (result.managedWrite || result.status === 'partial' && result.reason === 'pull_failed') {const { setCliExitVerdict } = await import('../core/cli-force-exit.ts');setCliExitVerdict(1);}@@ -5485,7 +5480,8 @@ See also:}}if (jsonOut) {- console.log(JSON.stringify(buildSingleSyncJsonEnvelope(sourceId, result, singleEmbedBackfill, singleCostGate)));+ console.log(JSON.stringify({ ...buildSingleSyncJsonEnvelope(sourceId, result, singleEmbedBackfill, singleCostGate),+ ...(result.managedWrite ? { managed_write: result.managedWrite } : {}) }));}return;}@@ -5919,6 +5915,7 @@ async function maybeExtractionNudge(engine: BrainEngine, sourceId?: string): Pro* JSON envelope pipes cleanly through `jq` (D4).*/export function printSyncResult(result: SyncResult, sink: NodeJS.WriteStream = process.stdout) {+ if (printManagedSyncDiagnostic(result, sink)) return;const write = (line: string) => sink.write(line + '\n');const writeUncommittedNote = (u: NonNullable<SyncResult['uncommitted']>) =>write(diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 8839546977..7a2c16b295 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -97,7 +97,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'remote': ['--brain', '--help', '--json', '--mcp-only', '--scopes', '--source', '--timeout'],'repair-jsonb': ['--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--progress-interval', '--progress-json', '--quiet', '--source', '--supabase', '--timeout', '--url'],'report': ['--brain', '--content', '--dir', '--help', '--json', '--source', '--title', '--type'],- 'repos': ['--abbrev-ref', '--abort', '--access', '--account', '--admin-intent', '--all', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--budget-usd-per-day', '--cached', '--calendar-id', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--count', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--detect', '--diff-filter', '--dir', '--dry-run', '--exclude', '--exclude-standard', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--file', '--fix', '--force', '--format', '--get', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--history-days', '--http', '--id', '--include', '--include-warns', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--limit', '--local', '--manifest', '--max-cost-usd', '--message', '--name', '--name-only', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-pull', '--no-verify', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--probe', '--profile', '--push-only', '--quiet', '--rebase', '--redirect-uri', '--repair', '--replace', '--repos', '--request-id', '--scope', '--scopes', '--secret', '--services', '--set', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--stale', '--status', '--surface', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--url', '--usage', '--yes'],+ 'repos': ['--abbrev-ref', '--abort', '--access', '--account', '--admin-intent', '--after', '--all', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--budget-usd-per-day', '--cached', '--calendar-id', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--count', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--detect', '--diff-filter', '--dir', '--dry-run', '--exclude', '--exclude-standard', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--file', '--fix', '--force', '--format', '--from', '--get', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--history-days', '--http', '--id', '--include', '--include-warns', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--limit', '--local', '--manifest', '--max-cost-usd', '--message', '--name', '--name-only', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-pull', '--no-verify', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--preview', '--probe', '--profile', '--push-only', '--quiet', '--rebase', '--redirect-uri', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--scope', '--scopes', '--secret', '--services', '--set', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--stale', '--status', '--surface', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--url', '--usage', '--yes'],'resolvers': ['--backend', '--brain', '--cost', '--help', '--json', '--source'],'retrieval-upgrade': ['--all', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--force-sunset-target', '--help', '--ignore-env-override', '--include-null-signature', '--json', '--no-embed', '--non-interactive', '--pace', '--pace-max-concurrency', '--priority', '--progress-interval', '--progress-json', '--quiet', '--reranker', '--retarget', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--yes'],'routing-eval': ['--brain', '--help', '--json', '--llm', '--skills-dir', '--source'],@@ -110,7 +110,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'skillpack': ['--all', '--apply-clean-hunks', '--author', '--auto', '--brain', '--dest', '--dry-run', '--env', '--exit-code', '--fast', '--fix', '--force-unlock', '--format', '--from', '--full', '--harness', '--help', '--homepage', '--json', '--license', '--list', '--minimal', '--name-only', '--no-cache', '--no-lint', '--note', '--out', '--overwrite-local', '--persona', '--pure', '--push', '--quick', '--quiet', '--refresh', '--repo', '--schema-pack', '--scope', '--short', '--since', '--skill', '--skills-dir', '--skip-doctor', '--source', '--strict', '--stub', '--supabase', '--target', '--tier', '--trust', '--url', '--verify', '--workspace', '--yes'],'skillpack-check': ['--background', '--brain', '--explain', '--fast', '--follow', '--help', '--json', '--list', '--progress-interval', '--progress-json', '--quiet', '--source', '--strict', '--timeout', '--yes'],'smoke-test': ['--brain', '--help', '--json', '--source'],- 'sources': ['--abbrev-ref', '--abort', '--access', '--account', '--admin-intent', '--all', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--budget-usd-per-day', '--cached', '--calendar-id', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--count', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--detect', '--diff-filter', '--dir', '--dry-run', '--exclude', '--exclude-standard', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--file', '--fix', '--force', '--format', '--get', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--history-days', '--http', '--id', '--include', '--include-warns', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--limit', '--local', '--manifest', '--max-cost-usd', '--message', '--name', '--name-only', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-pull', '--no-verify', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--probe', '--profile', '--push-only', '--quiet', '--rebase', '--redirect-uri', '--repair', '--replace', '--repos', '--request-id', '--scope', '--scopes', '--secret', '--services', '--set', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--stale', '--status', '--surface', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--url', '--usage', '--yes'],+ 'sources': ['--abbrev-ref', '--abort', '--access', '--account', '--admin-intent', '--after', '--all', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--budget-usd-per-day', '--cached', '--calendar-id', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--count', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--detect', '--diff-filter', '--dir', '--dry-run', '--exclude', '--exclude-standard', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--file', '--fix', '--force', '--format', '--from', '--get', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--history-days', '--http', '--id', '--include', '--include-warns', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--limit', '--local', '--manifest', '--max-cost-usd', '--message', '--name', '--name-only', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-pull', '--no-verify', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--preview', '--probe', '--profile', '--push-only', '--quiet', '--rebase', '--redirect-uri', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--scope', '--scopes', '--secret', '--services', '--set', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--stale', '--status', '--surface', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--url', '--usage', '--yes'],'status': ['--abbrev-ref', '--all', '--allow-empty', '--brain', '--break-lock', '--cached', '--concurrency', '--confirm-destructive', '--deadline-ms', '--diff-filter', '--empty', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--hard-deadline', '--help', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--others', '--parallel', '--path', '--priority', '--quiet', '--repo', '--retry-failed', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],'storage': ['--brain', '--fix', '--help', '--json', '--repo', '--restore-only', '--source', '--to'],'sweep': ['--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-delegate', '--once', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout'],diff --git a/src/core/cycle/extract-atoms-page-state.ts b/src/core/cycle/extract-atoms-page-state.tsnew file mode 100644index 0000000000..8fc00323d7--- /dev/null+++ b/src/core/cycle/extract-atoms-page-state.ts@@ -0,0 +1,134 @@+import type { SqlEngine } from '../persistence/model.ts';+import type { PageSnapshot } from '../page-state/types.ts';+import { stableJson } from '../persistence/digest.ts';+import type { BrainEngine } from '../engine.ts';++export interface AtomPageIdentity {+ pageId: number;+ sourceIncarnation: string;+ revision: string;+}++export interface AtomPageInput {+ slug: string;+ content: string;+ contentHash: string;+ identity?: AtomPageIdentity;+}++export class AtomPageStateError extends Error {+ constructor(reason: 'changed' | 'unpinned' | 'schema' | 'denied' | 'storage') {+ super({+ changed: 'atom page changed during extraction; scan state was not saved and the page remains retryable',+ unpinned: 'atom page state was not pinned before extraction; page remains retryable',+ schema: 'atom page scan state is unavailable (42P01); check schema migrations. The page remains retryable',+ denied: 'atom page scan state write was denied (42501); check database permissions. The page remains retryable',+ storage: 'atom page scan state could not be saved; check database access and schema migrations. The page remains retryable',+ }[reason]);+ this.name = 'AtomPageStateError';+ }+}++export async function readAtomPageIdentity(engine: SqlEngine, sourceId: string, item: AtomPageInput): Promise<AtomPageIdentity | undefined> {+ const [row] = await engine.executeRaw<{ id: number; incarnation: string; knowledge_revision: string }>(+ `SELECT p.id, s.incarnation, p.knowledge_revision FROM pages p JOIN sources s ON s.id=p.source_id+ WHERE p.source_id=$1 AND p.slug=$2 AND p.content_hash=$3 AND p.compiled_truth=$4 AND p.deleted_at IS NULL`,+ [sourceId, item.slug, item.contentHash, item.content]);+ return row && { pageId: row.id, sourceIncarnation: row.incarnation, revision: row.knowledge_revision };+}++export async function writeAtomPageState(+ engine: SqlEngine, sourceId: string, item: AtomPageInput, outcome: 'complete' | 'failure',+): Promise<number> {+ if (!item.identity) throw new AtomPageStateError('unpinned');+ const { pageId, sourceIncarnation, revision } = item.identity;+ const [row] = await engine.executeRaw<{ fail_count: number }>(+ `INSERT INTO extract_atoms_page_state (source_incarnation, page_id, content_hash, fail_count, tombstoned)+ SELECT s.incarnation, p.id, p.content_hash, $8::integer, $9::boolean+ FROM pages p JOIN sources s ON s.id=p.source_id+ WHERE p.id=$1 AND s.incarnation=$2::uuid AND p.source_id=$3 AND p.slug=$4+ AND p.content_hash=$5 AND p.knowledge_revision=$6::uuid AND p.compiled_truth=$7 AND p.deleted_at IS NULL+ FOR SHARE OF p, s+ ON CONFLICT (source_incarnation, page_id, content_hash) DO UPDATE+ SET fail_count=extract_atoms_page_state.fail_count + EXCLUDED.fail_count,+ tombstoned=extract_atoms_page_state.tombstoned OR EXCLUDED.tombstoned, updated_at=now()+ RETURNING fail_count`,+ [pageId, sourceIncarnation, sourceId, item.slug, item.contentHash, revision, item.content,+ outcome === 'failure' ? 1 : 0, outcome === 'complete']).catch((error: unknown) => {+ const code = error && typeof error === 'object' && 'code' in error ? error.code : undefined;+ throw new AtomPageStateError(code === '42P01' ? 'schema' : code === '42501' ? 'denied' : 'storage');+ });+ if (!row) throw new AtomPageStateError('changed');+ return Number(row.fail_count);+}++export async function completeAtomReceipts(+ engine: BrainEngine, sourceId: string, importedSlugs: string[], hash16: string, page?: AtomPageInput,+): Promise<void> {+ await engine.transaction(async tx => {+ const completed = await tx.executeRaw(+ `UPDATE pages+ SET frontmatter = frontmatter || jsonb_build_object('source_hash', $1::text)+ WHERE source_id = $2 AND type = 'atom' AND slug = ANY($3::text[]) AND deleted_at IS NULL+ ${page ? `AND EXISTS (+ SELECT 1 FROM pages origin JOIN sources s ON s.id=origin.source_id+ WHERE origin.id=$4 AND s.incarnation=$5::uuid AND origin.source_id=$2+ AND origin.content_hash=$6 AND origin.knowledge_revision=$7::uuid AND origin.deleted_at IS NULL+ FOR SHARE OF origin, s+ )` : ''}+ RETURNING slug`,+ page+ ? [hash16, sourceId, importedSlugs, page.identity?.pageId ?? null,+ page.identity?.sourceIncarnation ?? null, page.contentHash, page.identity?.revision ?? null]+ : [hash16, sourceId, importedSlugs],+ );+ if (completed.length !== new Set(importedSlugs).size) {+ throw new Error('atom completion could not be saved because the source or atom pages changed; pending atoms remain retryable');+ }+ });+}++const LEGACY_KEYS = ['atoms_scan_hash', 'atoms_fail_hash', 'atoms_fail_count'];++export function matchingLegacyAtomPageState(frontmatter: Record<string, unknown>, contentHash: string): { fail_count: number; tombstoned: boolean } | null {+ if (!/^[0-9a-f]{64}$/.test(contentHash)) return null;+ const hash = contentHash.slice(0, 16);+ const hasFailure = LEGACY_KEYS.slice(1).some(key => Object.hasOwn(frontmatter, key));+ const count = frontmatter.atoms_fail_count;+ if (hasFailure && (frontmatter.atoms_fail_hash !== hash || typeof count !== 'number'+ || !Number.isInteger(count) || count < 1 || count > 2147483647)) return null;+ if (Object.hasOwn(frontmatter, 'atoms_scan_hash') && frontmatter.atoms_scan_hash !== hash) return null;+ const tombstoned = frontmatter.atoms_scan_hash === hash;+ return tombstoned || hasFailure ? { fail_count: hasFailure ? count as number : 0, tombstoned } : null;+}++export async function transferLegacyAtomPageState(engine: SqlEngine, before: PageSnapshot, after: PageSnapshot): Promise<boolean> {+ if (before.page.id !== after.page.id || before.sourceIncarnation !== after.sourceIncarnation+ || !before.page.content_hash || !after.page.content_hash || before.page.deleted_at || after.page.deleted_at) return false;+ const canonical = (snapshot: PageSnapshot) => {+ const frontmatter = { ...snapshot.page.frontmatter };+ for (const key of LEGACY_KEYS) delete frontmatter[key];+ return { sourceId: snapshot.page.source_id, slug: snapshot.page.slug, type: snapshot.page.type,+ title: snapshot.page.title, body: snapshot.page.compiled_truth,+ timeline: snapshot.page.timeline, frontmatter, tags: [...snapshot.tags].sort(), withdrawals: snapshot.withdrawals };+ };+ if (stableJson(canonical(before)) !== stableJson(canonical(after))) return false;+ const [existing] = await engine.executeRaw<{ fail_count: number; tombstoned: boolean }>(+ `SELECT fail_count, tombstoned FROM extract_atoms_page_state+ WHERE source_incarnation=$1::uuid AND page_id=$2 AND content_hash=$3`,+ [before.sourceIncarnation, before.page.id, before.page.content_hash]);+ const state = existing ?? matchingLegacyAtomPageState(before.page.frontmatter, before.page.content_hash);+ if (!state) return false;+ const rows = await engine.executeRaw(+ `INSERT INTO extract_atoms_page_state (source_incarnation, page_id, content_hash, fail_count, tombstoned)+ SELECT s.incarnation, p.id, p.content_hash, $5::integer, $6::boolean+ FROM pages p JOIN sources s ON s.id=p.source_id+ WHERE p.id=$1 AND s.incarnation=$2::uuid AND p.content_hash=$3 AND p.knowledge_revision=$4::uuid AND p.deleted_at IS NULL+ FOR SHARE OF p, s+ ON CONFLICT (source_incarnation, page_id, content_hash) DO UPDATE+ SET fail_count=GREATEST(extract_atoms_page_state.fail_count, EXCLUDED.fail_count),+ tombstoned=extract_atoms_page_state.tombstoned OR EXCLUDED.tombstoned, updated_at=now()+ RETURNING page_id`,+ [after.page.id, after.sourceIncarnation, after.page.content_hash, after.revision, state.fail_count, state.tombstoned]);+ return rows.length > 0;+}diff --git a/src/core/cycle/extract-atoms.ts b/src/core/cycle/extract-atoms.tsindex 20cbbe218b..5752aa7dc2 100644--- a/src/core/cycle/extract-atoms.ts+++ b/src/core/cycle/extract-atoms.ts@@ -78,6 +78,8 @@ import { resolveTierDefault } from '../model-config.ts';import { isUndefinedTableError, warnOncePerProcess } from '../utils.ts';import { normalizeForGrounding } from './synthesize-verify.ts';import type { TranscriptPageIndex } from '../transcripts/discover.ts';+import { assertUnmanagedCanonicalWriter } from '../persistence/maintenance.ts';+import { AtomPageStateError, completeAtomReceipts, readAtomPageIdentity, writeAtomPageState, type AtomPageInput } from './extract-atoms-page-state.ts';const DEFAULT_BUDGET_USD = 0.3;// #4529 + #4540: per-item extractor caps, overridable via@@ -135,6 +137,12 @@ const MIN_PAGE_CHARS_FOR_EXTRACTION = 500;const RAW_SOURCE_HOLDER_EXCLUSION_SQL =`AND NOT (p.type = 'source' AND COALESCE(p.frontmatter ? 'raw', false))`;+const PAGE_SCAN_STATE_EXCLUSION_SQL = `AND NOT EXISTS (+ SELECT 1 FROM extract_atoms_page_state scan+ WHERE scan.source_incarnation=(SELECT s.incarnation FROM sources s WHERE s.id=p.source_id)+ AND scan.page_id=p.id AND scan.content_hash=p.content_hash AND scan.tombstoned+)`;+/*** Pure allowlist policy: the legacy floor UNION the pack's `extractable: true`* types, MINUS synthesis outputs. Exported for unit tests; keep I/O-free.@@ -327,12 +335,6 @@ never explain in prose.Output ONLY the JSON array, no prose.`;-interface DiscoveredPage {- slug: string;- content: string;- contentHash: string;-}-/*** v0.41.2.1 (D2) — single-SQL discovery + idempotency filter for brain* pages. Discovers extractable pages whose content_hash has no@@ -359,10 +361,12 @@ export async function discoverExtractablePages(sourceId: string,affectedSlugs?: string[],limit: number = PAGE_DISCOVERY_BUDGET,-): Promise<DiscoveredPage[]> {+): Promise<AtomPageInput[]> {const hasFilter = Array.isArray(affectedSlugs) && affectedSlugs.length > 0;const sql = `- SELECT p.slug,+ SELECT p.id, p.knowledge_revision,+ (SELECT s.incarnation FROM sources s WHERE s.id=p.source_id) AS source_incarnation,+ p.slug,p.compiled_truth,p.content_hashFROM pages p@@ -374,7 +378,7 @@ export async function discoverExtractablePages(AND COALESCE(p.frontmatter->>'dream_generated', '') <> 'true'${RAW_SOURCE_HOLDER_EXCLUSION_SQL}AND length(COALESCE(p.compiled_truth, '')) >= $3- AND COALESCE(p.frontmatter->>'atoms_scan_hash', '') <> substring(p.content_hash from 1 for 16)+ ${PAGE_SCAN_STATE_EXCLUSION_SQL}${hasFilter ? "AND p.slug = ANY($5::text[])" : ''}AND NOT EXISTS (SELECT 1@@ -397,6 +401,9 @@ export async function discoverExtractablePages(try {const rows = await engine.executeRaw<{+ id: number;+ knowledge_revision: string;+ source_incarnation: string;slug: string;compiled_truth: string;content_hash: string;@@ -405,6 +412,7 @@ export async function discoverExtractablePages(slug: r.slug,content: r.compiled_truth,contentHash: r.content_hash,+ identity: { pageId: r.id, sourceIncarnation: r.source_incarnation, revision: r.knowledge_revision },}));} catch (err) {const msg = err instanceof Error ? err.message : String(err);@@ -448,7 +456,7 @@ export async function countExtractAtomsBacklog(AND COALESCE(p.frontmatter->>'dream_generated', '') <> 'true'${RAW_SOURCE_HOLDER_EXCLUSION_SQL}AND length(COALESCE(p.compiled_truth, '')) >= $3- AND COALESCE(p.frontmatter->>'atoms_scan_hash', '') <> substring(p.content_hash from 1 for 16)+ ${PAGE_SCAN_STATE_EXCLUSION_SQL}AND NOT EXISTS (SELECT 1 FROM pages atomWHERE atom.type = 'atom' AND atom.source_id = $1@@ -463,7 +471,7 @@ export async function countExtractAtomsBacklog(AND COALESCE(p.frontmatter->>'dream_generated', '') <> 'true'${RAW_SOURCE_HOLDER_EXCLUSION_SQL}AND length(COALESCE(p.compiled_truth, '')) >= $2- AND COALESCE(p.frontmatter->>'atoms_scan_hash', '') <> substring(p.content_hash from 1 for 16)+ ${PAGE_SCAN_STATE_EXCLUSION_SQL}AND NOT EXISTS (SELECT 1 FROM pages atomWHERE atom.type = 'atom' AND atom.source_id = p.source_id@@ -635,6 +643,7 @@ export async function runPhaseExtractAtoms(): Promise<PhaseResult> {const sourceId = opts.sourceId ?? 'default';const chat = opts._chat ?? gatewayChat;+ await assertUnmanagedCanonicalWriter(engine, 'Atom extraction');// 1a. Get transcripts (test seam OR production discovery).// v0.41.2.1: config loader switched to loadConfigWithEngine() so the@@ -678,9 +687,11 @@ export async function runPhaseExtractAtoms(// 1b. Get pages (test seam OR production discovery).// _pages === undefined triggers discovery; _pages: [] suppresses it// deliberately (transcript-only regression tests).- let pages: Array<{ slug: string; content: string; contentHash: string }>;+ let pages: AtomPageInput[];if (opts._pages !== undefined) {- pages = opts._pages;+ pages = await Promise.all(opts._pages.map(async page => ({+ ...page, identity: await readAtomPageIdentity(engine, sourceId, page),+ })));} else {pages = await discoverExtractablePages(engine,@@ -700,11 +711,6 @@ export async function runPhaseExtractAtoms(// short-circuit shows a sign of life (closes Issue 2 silent-phase pain).opts.progress?.heartbeat(`checking existing atoms for ${allHashes16.length} transcripts`);const existingHashes = await atomsExistingForHashes(engine, sourceId, allHashes16);- // v146 READ SIDE. The counter written above is inert without this: transcript- // eligibility was gated ONLY by "does an atom row exist for this hash", so a- // tombstone nothing consults would leave the item in the pool forever. Pages- // need no equivalent edit — their tombstone (`atoms_scan_hash`) is already- // read by discoverExtractablePages' SQL, which this change does not touch.const tombstonedTranscriptKeys = await tombstonedTranscriptsForHashes(engine,sourceId,@@ -750,7 +756,7 @@ export async function runPhaseExtractAtoms(// forever while atoms keep getting extracted from transcripts.type WorkItem =| { kind: 'transcript'; filePath: string; content: string; contentHash: string }- | { kind: 'page'; slug: string; content: string; contentHash: string };+ | ({ kind: 'page' } & AtomPageInput);const seenHashes = new Set<string>();const transcriptItems: WorkItem[] = [];@@ -973,16 +979,8 @@ export async function runPhaseExtractAtoms(// say are "retryable, never counted" — see that regex's doc comment.let hardFailureCount = 0;- /** Stamp the zero-yield/complete tombstone (hash-keyed; edits re-eligibilize). */- async function stampAtomsScanHash(item: { slug: string; contentHash: string }): Promise<void> {- try {- await engine.executeRaw(- `UPDATE pages- SET frontmatter = frontmatter || jsonb_build_object('atoms_scan_hash', $1::text)- WHERE source_id = $2 AND slug = $3 AND deleted_at IS NULL`,- [item.contentHash.slice(0, 16), sourceId, item.slug],- );- } catch { /* fail-soft: page stays rediscoverable */ }+ async function stampAtomsScanHash(item: AtomPageInput): Promise<void> {+ await writeAtomPageState(engine, sourceId, item, 'complete');}/**@@ -1011,14 +1009,13 @@ export async function runPhaseExtractAtoms(* content edit resets the streak. Returns the new consecutive count, or* null on write failure (never blocks the phase).*- * v146: transcripts are covered too. Pages keep their frontmatter counter;- * transcripts are files with no frontmatter, so theirs lives in+ * v146: transcripts are covered too. Their state lives in* `extract_atoms_transcript_state`. Both reset on a content change for the* same reason — the page counter is hash-keyed, the transcript row IS* hash-keyed — and both feed the same MAX_DETERMINISTIC_FAILURES bound.*/async function recordItemFailureCount(- item: { kind: string; slug?: string; filePath?: string; contentHash: string },+ item: WorkItem,): Promise<number | null> {if (opts.dryRun) return null;const hash16 = item.contentHash.slice(0, 16);@@ -1047,23 +1044,12 @@ export async function runPhaseExtractAtoms(return null;}}- if (item.kind !== 'page' || !item.slug) return null;try {- const rows = await engine.executeRaw<{ cnt: number | string }>(- `UPDATE pages- SET frontmatter = frontmatter- || jsonb_build_object('atoms_fail_hash', $1::text)- || jsonb_build_object('atoms_fail_count',- CASE WHEN COALESCE(frontmatter->>'atoms_fail_hash', '') = $1::text- THEN COALESCE((frontmatter->>'atoms_fail_count')::int, 0) + 1- ELSE 1 END)- WHERE source_id = $2 AND slug = $3 AND deleted_at IS NULL- RETURNING (frontmatter->>'atoms_fail_count')::int AS cnt`,- [hash16, sourceId, item.slug],- );- const cnt = rows[0]?.cnt;- return cnt == null ? null : Number(cnt);- } catch {+ return await writeAtomPageState(engine, sourceId, item, 'failure');+ } catch (err) {+ const error = err instanceof AtomPageStateError ? err.message : new AtomPageStateError('storage').message;+ failures.push({ source: item.slug, error });+ console.error(`[extract_atoms] ${item.slug}: ${error}`);return null;}}@@ -1292,12 +1278,7 @@ export async function runPhaseExtractAtoms(// after every atom AND provenance edge persisted), then stamp the// source page. A crash between flip and stamp degrades to the legacy// atom-rows-mean-done semantics — safe, not lossy.- await engine.executeRaw(- `UPDATE pages- SET frontmatter = frontmatter || jsonb_build_object('source_hash', $1::text)- WHERE source_id = $2 AND type = 'atom' AND slug = ANY($3::text[]) AND deleted_at IS NULL`,- [hash16, sourceId, importedSlugs],- );+ await completeAtomReceipts(engine, sourceId, importedSlugs, hash16, item.kind === 'page' ? item : undefined);if (item.kind === 'page') {await stampAtomsScanHash(item);}diff --git a/src/core/import-file.ts b/src/core/import-file.tsindex a17e6508f5..9a5a988c76 100644--- a/src/core/import-file.ts+++ b/src/core/import-file.ts@@ -1,5 +1,6 @@import { assertUnmanagedCanonicalWriter } from './persistence/maintenance.ts';import { assertImportBase, sameCanonicalImport } from './page-state/import-guard.ts';+import { stabilizeSafetyAssessments } from './persistence/reconcile-safety.ts';import { readSourceFileSync } from './minions/source-filesystem.ts';import { readFileSync, statSync, lstatSync } from 'fs';import { basename, extname } from 'path';@@ -553,11 +554,9 @@ export async function importFromContent(// would not change, and tag reconciliation would silently no-op// (this function returns early on hash-match).//- // v0.42 (#1699): the content-sanity gate runs on EVERY import and stamps- // GATE-DERIVED markers (quarantine / content_flag / embed_skip) carrying a- // fresh `assessed_at` timestamp. Those markers are derived from the body,- // not source content, so they must be EXCLUDED from the hash — otherwise- // every re-sync of a flagged/quarantined page sees a changed hash and+ // v0.42 (#1699): gate-derived quarantine/content_flag/embed_skip markers+ // carry assessed_at timestamps. They describe the assessment, not source+ // content, so they must be EXCLUDED from the hash — otherwise re-sync// re-chunks + re-embeds forever (a markup-heavy page keeps chunks, so this// is real, unbounded embedding spend). Same bug class as the captured_at /// ingested_at fix above; the gate re-derives the markers deterministically@@ -571,6 +570,7 @@ export async function importFromContent(// unscoped-check/scoped-write bug class).const existingSnapshot = opts.prepare ? await engine.readPageSnapshot(slug, { sourceId: sourceId ?? 'default', includeDeleted: true }) : null;const existing = opts.prepare ? existingSnapshot?.page ?? null : await engine.getPage(slug, { sourceId: sourceId ?? 'default', includeDeleted: true });+ if (existing) stabilizeSafetyAssessments(parsed.frontmatter, existing.frontmatter);// #2044 / #4548: remote get_page/fetch intentionally strip non-'world'// facts rows before an untrusted caller ever sees them. A documenteddiff --git a/src/core/migrate.ts b/src/core/migrate.tsindex 832318b0ba..f4d4d75d63 100644--- a/src/core/migrate.ts+++ b/src/core/migrate.ts@@ -6594,6 +6594,57 @@ CREATE TRIGGER minion_queue_protocol BEFORE INSERT OR UPDATE ON minion_jobs},},{ version: 162, name: 'source_ingestion_receipts_with_policy', idempotent: true, sql: SOURCE_INGESTION_RECEIPTS_SCHEMA_SQL },+ {+ version: 163,+ name: 'derived_atom_page_scan_state',+ idempotent: true,+ sql: `+ CREATE TABLE IF NOT EXISTS extract_atoms_page_state (+ source_incarnation UUID NOT NULL REFERENCES sources(incarnation) ON DELETE CASCADE,+ page_id INTEGER NOT NULL REFERENCES pages(id) ON DELETE CASCADE,+ content_hash TEXT NOT NULL,+ fail_count INTEGER NOT NULL DEFAULT 0 CHECK (fail_count >= 0),+ tombstoned BOOLEAN NOT NULL DEFAULT false,+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ PRIMARY KEY (source_incarnation, page_id, content_hash)+ );+ CREATE INDEX IF NOT EXISTS extract_atoms_page_state_tombstoned_idx+ ON extract_atoms_page_state (source_incarnation, content_hash, page_id) WHERE tombstoned;+ CREATE INDEX IF NOT EXISTS extract_atoms_page_state_page_idx ON extract_atoms_page_state (page_id);+ CREATE OR REPLACE FUNCTION gbrain_clear_atom_page_state() RETURNS trigger LANGUAGE plpgsql AS $fn$+ BEGIN+ IF NEW.deleted_at IS DISTINCT FROM OLD.deleted_at OR NEW.source_id IS DISTINCT FROM OLD.source_id THEN+ DELETE FROM extract_atoms_page_state WHERE page_id=OLD.id;+ END IF;+ RETURN NEW;+ END $fn$;+ DROP TRIGGER IF EXISTS pages_clear_atom_scan_state ON pages;+ CREATE TRIGGER pages_clear_atom_scan_state AFTER UPDATE ON pages+ FOR EACH ROW EXECUTE FUNCTION gbrain_clear_atom_page_state();+ INSERT INTO extract_atoms_page_state (source_incarnation, page_id, content_hash, fail_count, tombstoned)+ SELECT s.incarnation, p.id, p.content_hash,+ CASE WHEN p.frontmatter ? 'atoms_fail_count' THEN (p.frontmatter->>'atoms_fail_count')::integer ELSE 0 END,+ COALESCE(p.frontmatter->>'atoms_scan_hash'=substring(p.content_hash from 1 for 16), false)+ FROM pages p JOIN sources s ON s.id=p.source_id+ WHERE p.deleted_at IS NULL AND p.content_hash ~ '^[0-9a-f]{64}$'+ AND p.frontmatter ?| ARRAY['atoms_scan_hash','atoms_fail_hash','atoms_fail_count']+ AND (NOT (p.frontmatter ? 'atoms_scan_hash') OR+ (jsonb_typeof(p.frontmatter->'atoms_scan_hash')='string'+ AND p.frontmatter->>'atoms_scan_hash'=substring(p.content_hash from 1 for 16)))+ AND (NOT (p.frontmatter ?| ARRAY['atoms_fail_hash','atoms_fail_count']) OR+ (jsonb_typeof(p.frontmatter->'atoms_fail_hash')='string'+ AND p.frontmatter->>'atoms_fail_hash'=substring(p.content_hash from 1 for 16)+ AND CASE WHEN jsonb_typeof(p.frontmatter->'atoms_fail_count')='number'+ AND p.frontmatter->>'atoms_fail_count' ~ '^[1-9][0-9]{0,9}$'+ THEN (p.frontmatter->>'atoms_fail_count')::numeric <= 2147483647 ELSE false END))+ ON CONFLICT (source_incarnation, page_id, content_hash) DO NOTHING;+ DO $rls$ BEGIN+ IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname=current_user AND rolbypassrls) THEN+ ALTER TABLE extract_atoms_page_state ENABLE ROW LEVEL SECURITY;+ END IF;+ END $rls$;+ `,+ },];export const LATEST_VERSION = MIGRATIONS.length > 0diff --git a/src/core/persistence/activation.ts b/src/core/persistence/activation.tsindex 8a04b829ca..bcebee74eb 100644--- a/src/core/persistence/activation.ts+++ b/src/core/persistence/activation.ts@@ -8,7 +8,13 @@ import { nativeLockCapability, tryAcquireNativeLock, type NativeLockHandle } froimport { managedFilesystemDatastorePath, refreshManagedFilesystemRoots } from './filesystem-guard.ts';import { assertWriterAdminState, WRITER_INSPECTION_HINT } from './admin-intent.ts';-export interface ActivationReport { enabled: boolean; activated: boolean; filesystem_sources: number; native_lock: { target: string; napi: 3 }; }+export interface ActivationReport {+ enabled: boolean;+ activated: boolean;+ filesystem_sources: number;+ native_lock: { target: string; napi: 3 };+ drift_audit?: { sources: Array<Record<string, unknown>>; complete: boolean; snapshot_only: true };+}interface SourceRoot { id: string; incarnation: string; root: string | null; }const quiescence = () => new OperationError('writer_not_quiesced', 'Managed activation requires all older writers and maintenance jobs to be stopped.',WRITER_INSPECTION_HINT);@@ -64,6 +70,20 @@ export async function activatePersistence(engine: BrainEngine, opts: { confirmQuconst hostId = opts.dryRun ? existingLocalHostId() : localHostId();const sources = await configuredSources(engine);const initial = await validatedBindings(engine, sources, hostId);+ let driftAudit: ActivationReport['drift_audit'];+ if (opts.dryRun) {+ const { auditCanonicalSource } = await import('./reconcile-audit.ts');+ const audited: Array<Record<string, unknown>> = [];+ for (const binding of initial.slice(0, 4)) {+ try { audited.push(await auditCanonicalSource(engine, binding.source_id)); }+ catch (error) {+ audited.push({ source_id: binding.source_id, complete: false,+ reason: error instanceof OperationError ? error.code : 'storage_error',+ suggestion: 'Run sources reconcile --audit on this source’s canonical owner.' });+ }+ }+ driftAudit = { sources: audited, complete: initial.length <= 4 && audited.every(report => report.complete === true), snapshot_only: true };+ }const locks: NativeLockHandle[] = [];try {// All native acquisition precedes the transaction and any database wait.@@ -93,7 +113,7 @@ export async function activatePersistence(engine: BrainEngine, opts: { confirmQuif ((await tx.executeRaw('SELECT id FROM gbrain_cycle_locks LIMIT 1')).length) throw quiescence();if ((await tx.executeRaw(`SELECT id FROM persistence_requests WHERE state IN ('queued','running','recovering') OR recovery IS NOT NULL LIMIT 1`)).length|| (await tx.executeRaw('SELECT id FROM persistence_effects WHERE recovery IS NOT NULL LIMIT 1')).length) throw quiescence();- if (opts.dryRun) return { enabled: false, activated: false, filesystem_sources: bindings.length, native_lock: native };+ if (opts.dryRun) return { enabled: false, activated: false, filesystem_sources: bindings.length, native_lock: native, drift_audit: driftAudit };await registerLocalWriter(tx, 'cli');await registerLocalWriter(tx, 'stdio');await tx.executeRaw('UPDATE persistence_brain SET enabled=true,activated_at=COALESCE(activated_at,now()) WHERE singleton=1');diff --git a/src/core/persistence/admin-contract.ts b/src/core/persistence/admin-contract.tsindex 87b185aa90..58d383afb6 100644--- a/src/core/persistence/admin-contract.ts+++ b/src/core/persistence/admin-contract.ts@@ -3,6 +3,7 @@ export const PERSISTENCE_ADMIN_OPERATIONS = ['writer_status', 'writer_sync', 'writer_reindex_code', 'writer_claim', 'writer_activate', 'writer_transfer_prepare', 'writer_transfer_accept','local_writer_list', 'local_writer_register', 'local_writer_revoke','source_lifecycle', 'source_add', 'company_brain_preview', 'company_brain_connect', 'company_brain_resume',+ 'writer_reconcile_preview', 'writer_reconcile_apply', 'writer_reconcile_audit', 'writer_reconcile_backups',] as const;export type PersistenceAdminOperation = typeof PERSISTENCE_ADMIN_OPERATIONS[number];export function isPersistenceAdminOperation(value: unknown): value is PersistenceAdminOperation {diff --git a/src/core/persistence/administration.ts b/src/core/persistence/administration.tsindex 15a7240210..39a1b2368d 100644--- a/src/core/persistence/administration.ts+++ b/src/core/persistence/administration.ts@@ -57,6 +57,10 @@ async function registrationGrant(engine: BrainEngine, params: Record<string, unkexport async function runPersistenceAdministration(engine: BrainEngine, operation: PersistenceAdminOperation,params: Record<string, unknown>): Promise<Record<string, unknown>> {+ if (operation === 'writer_reconcile_preview') return (await import('./reconcile.ts')).runReconcilePreview(engine, params);+ if (operation === 'writer_reconcile_apply') return (await import('./reconcile.ts')).runReconcileApply(engine, params);+ if (operation === 'writer_reconcile_audit') return (await import('./reconcile-audit.ts')).runReconcileAudit(engine, params);+ if (operation === 'writer_reconcile_backups') return (await import('./reconcile.ts')).runReconcileBackups(engine, params);if (operation === 'company_brain_preview' || operation === 'company_brain_connect' || operation === 'company_brain_resume') {const writer = currentVerifiedLocalWriter();if (!writer || writer.remote || writer.principal.kind !== 'local_cli') throw new OperationError('permission_denied', 'Company source administration requires an authenticated local CLI registration.');diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.tsindex cf5a2afc96..15e2aef7e5 100644--- a/src/core/persistence/page-mutations.ts+++ b/src/core/persistence/page-mutations.ts@@ -40,6 +40,9 @@ export function pageMutationSource(ctx: OperationContext, params: Record<string,}export async function submitPageMutation(ctx: OperationContext,input: { operation: string; params: Record<string, unknown>; waitMs?: number }): Promise<Record<string, unknown>> {+ if (input.operation === 'put_page' && ['kind', 'preview', 'backup_reference'].some(key => Object.hasOwn(input.params, key))) {+ throw new OperationError('invalid_params', 'Reserved persistence fields cannot be submitted through put_page. Use trusted local reconciliation administration.');+ }assertPersistenceAccepting(ctx.engine);const p: Record<string, unknown> = { ...input.params, ...parseMutationPrecondition(input.params) };const requestId = typeof p.request_id === 'string' ? p.request_id : randomUUID();diff --git a/src/core/persistence/reconcile-audit.ts b/src/core/persistence/reconcile-audit.tsnew file mode 100644index 0000000000..5eec55a4d5--- /dev/null+++ b/src/core/persistence/reconcile-audit.ts@@ -0,0 +1,98 @@+import { statSync } from 'node:fs';+import { join } from 'node:path';+import type { BrainEngine } from '../engine.ts';+import { OperationError, type OperationContext } from '../ops/contract.ts';+import { isValidSourceId } from '../source-id.ts';+import { validateSlug } from '../utils.ts';+import { resolveSourceLocalFilePath } from '../markdown.ts';+import { recordedPathFromFileUri } from '../write-through.ts';+import { isWriteTargetContained } from '../path-confine.ts';+import { submissionAuthority } from './authority.ts';+import { currentVerifiedLocalWriter, existingLocalHostId, readLocalWriter, verifyLocalWriter } from './identity.ts';+import { getWorktreeBinding } from './ownership.ts';+import { prepareFileTarget } from './page-prepare.ts';++export interface ReconcileAuditReport extends Record<string, unknown> {+ source_id: string;+ inspected: number;+ drifted: number;+ errors: number;+ findings: Array<{ slug: string; reason: string; suggestion: string }>;+ next_after: string | null;+ complete: boolean;+ snapshot_only: true;+}++export async function auditCanonicalSource(engine: BrainEngine, sourceId: string,+ options: { limit?: number; after?: string } = {}): Promise<ReconcileAuditReport> {+ const limit = options.limit ?? 25;+ if (!isValidSourceId(sourceId) || !Number.isInteger(limit) || limit < 1 || limit > 100) {+ throw new OperationError('invalid_params', 'Audit requires an explicit source and a limit from 1 to 100.');+ }+ if (options.after !== undefined) {+ if (typeof options.after !== 'string') throw new OperationError('invalid_params', 'The audit cursor must be a page slug.');+ try { validateSlug(options.after); } catch { throw new OperationError('invalid_params', 'The audit cursor must be a valid page slug.'); }+ }+ const hostId = existingLocalHostId();+ const binding = hostId ? await getWorktreeBinding(engine, sourceId, hostId) : null;+ if (!binding?.local_path || binding.owner_host_id !== hostId || binding.state !== 'active') {+ throw new OperationError('owner_unavailable', 'Read-only drift auditing must run on the active canonical owner.');+ }+ const root = join(binding.local_path, binding.relative_path);+ const rows = await engine.executeRaw<{ slug: string; bytes: number }>(`SELECT slug,+ octet_length(compiled_truth)+octet_length(COALESCE(timeline,''))+octet_length(frontmatter::text) AS bytes+ FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND page_kind='markdown' AND slug>$2+ ORDER BY slug LIMIT $3`, [sourceId, options.after ?? '', limit + 1]);+ const report: ReconcileAuditReport = { source_id: sourceId, inspected: 0, drifted: 0, errors: 0, findings: [],+ next_after: rows.length > limit ? rows[limit - 1].slug : null, complete: rows.length <= limit, snapshot_only: true };+ for (const candidate of rows.slice(0, limit)) {+ report.inspected++;+ try {+ if (Number(candidate.bytes) > 5_000_000) throw new OperationError('invalid_params', 'The page exceeds the bounded audit size.');+ const snapshot = await engine.readPageSnapshot(candidate.slug, { sourceId });+ if (!snapshot || snapshot.sourceIncarnation !== binding.source_incarnation) throw new OperationError('page_identity_changed', 'The page identity changed during the audit.');+ const capturedPath = recordedPathFromFileUri(snapshot.page.source_uri, root);+ const path = resolveSourceLocalFilePath(root, snapshot.page.source_path, candidate.slug)+ ?? (capturedPath ? join(root, capturedPath) : join(root, `${candidate.slug}.md`));+ if (!isWriteTargetContained(path, root)) throw new OperationError('source_changed', 'The canonical path is not confined.');+ let size = 0;+ try {+ const stat = statSync(path);+ if (!stat.isFile()) throw new OperationError('invalid_params', 'The canonical target is not a regular file.');+ size = stat.size;+ } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; }+ if (size > 5_000_000) throw new OperationError('invalid_params', 'The file exceeds the bounded audit size.');+ await prepareFileTarget(engine, { source_id: sourceId, worktree_id: binding.worktree_id, slug: candidate.slug }, snapshot, null, hostId!);+ } catch (error) {+ const reason = error instanceof OperationError ? error.code : 'storage_error';+ if (reason === 'source_changed') report.drifted++;+ else report.errors++;+ report.findings.push({ slug: candidate.slug, reason,+ suggestion: reason === 'source_changed'+ ? 'Preview this exact page with sources reconcile before attempting another write.'+ : 'Inspect this page on the canonical host; no repair was attempted.' });+ }+ }+ return report;+}++export async function runReconcileAudit(engine: BrainEngine, params: Record<string, unknown>): Promise<ReconcileAuditReport> {+ if (Object.keys(params).some(key => !['source_id', 'limit', 'after'].includes(key)) || !isValidSourceId(params.source_id)) {+ throw new OperationError('invalid_params', 'Audit accepts only source_id, limit, and after.');+ }+ const writer = currentVerifiedLocalWriter() ?? await verifyLocalWriter(engine, await readLocalWriter(engine, 'cli'));+ if (writer.remote || writer.principal.kind !== 'local_cli' || writer.grant.slugPrefixes !== null) {+ throw new OperationError('permission_denied', 'A whole-source audit requires the existing trusted CLI grant without a slug-prefix restriction.');+ }+ if (!writer.grant.sourceIds.includes('*') && !writer.grant.sourceIds.includes(params.source_id)) {+ throw new OperationError('permission_denied', 'The current CLI grant excludes this source.');+ }+ const [source] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation FROM sources WHERE id=$1 AND NOT archived', [params.source_id]);+ if (!source) throw new OperationError('source_changed', 'The selected source is unavailable.');+ await submissionAuthority({ engine, remote: false, sourceId: params.source_id } as OperationContext,+ 'put_page', params.source_id, source.incarnation, '__reconciliation_audit__');+ const report = await auditCanonicalSource(engine, params.source_id, { limit: params.limit as number | undefined, after: params.after as string | undefined });+ await submissionAuthority({ engine, remote: false, sourceId: params.source_id } as OperationContext,+ 'put_page', params.source_id, source.incarnation, '__reconciliation_audit__');+ return report;+}diff --git a/src/core/persistence/reconcile-backup.ts b/src/core/persistence/reconcile-backup.tsnew file mode 100644index 0000000000..7a6a6ce150--- /dev/null+++ b/src/core/persistence/reconcile-backup.ts@@ -0,0 +1,162 @@+import { constants, closeSync, existsSync, fsyncSync, linkSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, unlinkSync, writeFileSync, type Stats } from 'node:fs';+import { randomUUID } from 'node:crypto';+import { dirname, isAbsolute, join } from 'node:path';+import type { BrainEngine } from '../engine.ts';+import { configDir } from '../config.ts';+import { OperationError } from '../ops/contract.ts';+import { canonicalFilesystemPath } from './root-registry.ts';+import { containsPath } from './ownership.ts';+import { acquireNativeLock } from './native-lock.ts';+import { digest, jsonBytes, stableJson } from './digest.ts';+import { readJournalLimits } from './limits.ts';+import { capacityError, intentDigest } from './journal.ts';+import type { ReconcileArtifact } from './reconcile-state.ts';+import { isTerminal, type Principal, type WriteAuthority, type WriteRequest } from './model.ts';+import { PERSISTENCE_IPC_MAX_BYTES } from './ipc.ts';+import { authorizeStoredRequest } from './authority.ts';++const backupPattern = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}\.[a-f0-9]{64}\.json$/;+const backupReference = (brain: string, principal: Principal, requestId: string) => `${requestId}.${digest({ brain, principal, requestId })}.json`;+const backupDirectory = () => join(canonicalFilesystemPath(configDir()), 'reconciliation-previews');+const privatePermissions = (stat: Stats) => process.platform === 'win32' ||+ (stat.mode & 0o077) === 0 && (typeof process.getuid !== 'function' || stat.uid === process.getuid());++export async function assertReconcileOutputPath(engine: BrainEngine, sourceId: string, path: string): Promise<void> {+ if (!isAbsolute(path) || path.includes('\0')) throw new OperationError('invalid_params', 'The private preview output must be an absolute local path.');+ const roots = await engine.executeRaw<{ local_path: string }>(`SELECT local_path FROM sources WHERE local_path IS NOT NULL+ UNION SELECT local_path FROM persistence_host_bindings WHERE local_path IS NOT NULL`);+ const resolved = canonicalFilesystemPath(path);+ if (roots.some(row => containsPath(canonicalFilesystemPath(row.local_path), resolved))) {+ throw new OperationError('permission_denied', 'Private reconciliation artifacts must be stored outside every canonical source and worktree.');+ }+}+function privateDirectory(path: string): void {+ if (!existsSync(path)) { mkdirSync(path, { mode: 0o700, recursive: true }); flushDirectory(dirname(path)); }+ const stat = lstatSync(path);+ if (!stat.isDirectory() || stat.isSymbolicLink() || !privatePermissions(stat)) {+ throw new OperationError('permission_denied', 'The reconciliation backup directory must be private, owned, and free of symlinks.');+ }+}+function flushDirectory(path: string): void {+ let fd: number | undefined;+ try { fd = openSync(path, 'r'); fsyncSync(fd); }+ catch (error) {+ if (!(process.platform === 'win32' && ['EISDIR', 'EPERM', 'EINVAL', 'ENOTSUP'].includes((error as NodeJS.ErrnoException).code ?? ''))) throw error;+ } finally { if (fd !== undefined) closeSync(fd); }+}+export async function assertReconcileSize(engine: BrainEngine, artifact: ReconcileArtifact): Promise<void> {+ const limits = await readJournalLimits(engine);+ if (jsonBytes(artifact) + 65536 > Math.min(PERSISTENCE_IPC_MAX_BYTES, limits.principalIntentBytes, limits.brainIntentBytes, limits.worktreeRecoveryBytes, limits.brainRecoveryBytes)) {+ throw new OperationError('request_too_large', 'The complete reconciliation artifact exceeds the configured request/recovery capacity.');+ }+}+export async function retainReconcileBackup(engine: BrainEngine, artifact: ReconcileArtifact, principal: Principal, requestId: string): Promise<string> {+ const directory = backupDirectory();+ await assertReconcileOutputPath(engine, artifact.preconditions.source_id, directory);+ privateDirectory(directory);+ const lock = await acquireNativeLock(join(directory, '.capacity.lock'), { timeoutMs: 5000 });+ if (!lock) throw new OperationError('writer_lock_unavailable', 'Reconciliation backup capacity is busy.');+ try {+ privateDirectory(directory);+ const limits = await readJournalLimits(engine);+ const reference = backupReference(artifact.preconditions.brain_id, principal, requestId);+ const path = join(directory, reference);+ const value = stableJson({ format_version: 1, retention: 'pre_admission_or_terminal', principal, request_id: requestId, preview: artifact });+ if (existsSync(path)) {+ const stat = lstatSync(path);+ if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || !privatePermissions(stat) || readFileSync(path, 'utf8') !== value) {+ throw new OperationError('idempotency_conflict', 'A different or unsafe retained backup already owns this request ID.');+ }+ return reference;+ }+ let count = 0, bytes = 0;+ for (const name of readdirSync(directory)) {+ if (name === '.capacity.lock') continue;+ const stat = lstatSync(join(directory, name));+ if (!stat.isFile() || stat.isSymbolicLink()) throw new OperationError('storage_error', 'Unexpected content in the private reconciliation backup directory.');+ count++; bytes += stat.size;+ }+ if (count + 1 > limits.brainLifetimeIds || bytes + Buffer.byteLength(value) > limits.brainRecoveryBytes) throw capacityError('retained reconciliation backups');+ const temporary = join(directory, `${reference}.${randomUUID()}.tmp`);+ const fd = openSync(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);+ try { writeFileSync(fd, value); fsyncSync(fd); } finally { closeSync(fd); }+ try { linkSync(temporary, path); flushDirectory(directory); }+ finally { unlinkSync(temporary); flushDirectory(directory); }+ return reference;+ } finally { await lock.release(); }+}+export function verifyReconcileBackup(reference: string, artifact: ReconcileArtifact): void {+ if (!backupPattern.test(reference)) throw new OperationError('storage_error', 'Invalid reconciliation backup reference.');+ try {+ const directory = backupDirectory();+ privateDirectory(directory);+ const path = join(directory, reference), stat = lstatSync(path);+ if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || !privatePermissions(stat) ||+ digest(JSON.parse(readFileSync(path, 'utf8')).preview) !== digest(artifact)) throw new Error('backup changed');+ } catch {+ throw new OperationError('storage_error', 'The retained reconciliation preimages are missing or changed.');+ }+}++export async function manageReconcileBackups(engine: BrainEngine, authority: WriteAuthority, slug: string,+ params: { action: 'list' | 'remove'; backup_reference?: string; after?: string; limit?: number }): Promise<Record<string, unknown>> {+ const directory = backupDirectory();+ const principal = authority.principal;+ const [brain] = await engine.executeRaw<{ brain_id: string }>('SELECT brain_id FROM persistence_brain WHERE singleton=1');+ const limit = params.limit ?? 100;+ if (params.action === 'list') {+ const rows = await engine.executeRaw<WriteRequest>(`SELECT * FROM persistence_requests WHERE principal_kind=$1 AND principal_id=$2+ AND source_id=$3 AND slug=$4 AND ($5::uuid IS NULL OR request_id>$5::uuid)+ AND operation='put_page' ORDER BY request_id LIMIT $6`,+ [principal.kind, principal.id, authority.sourceId, slug, params.after ?? null, limit + 1]);+ const backups: Record<string, unknown>[] = [];+ for (const row of rows.slice(0, limit)) {+ await authorizeStoredRequest(engine, row);+ const reference = backupReference(brain.brain_id, principal, row.request_id);+ const path = join(directory, reference);+ if (!existsSync(path) && row.outcome?.backup_reference !== reference && row.intent?.backup_reference !== reference) continue;+ let bytes: number | null = null;+ if (existsSync(path)) {+ privateDirectory(directory);+ const stat = lstatSync(path);+ if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || !privatePermissions(stat)) throw new OperationError('storage_error', 'A retained backup is not a private ordinary file.');+ bytes = stat.size;+ }+ backups.push({ backup_reference: reference, request_id: row.request_id, state: row.state, retained: bytes !== null, bytes,+ removable: bytes !== null && isTerminal(row) && row.recovery === null });+ }+ const limits = await readJournalLimits(engine);+ return { source_id: authority.sourceId, slug, backups, next_after: rows.length > limit ? rows[limit - 1].request_id : null,+ capacity: { max_retained_bytes: limits.brainRecoveryBytes, max_retained_count: limits.brainLifetimeIds } };+ }+ const reference = params.backup_reference!;+ if (!backupPattern.test(reference)) throw new OperationError('invalid_params', 'An exact private backup reference is required.');+ const requestId = reference.slice(0, 36);+ if (reference !== backupReference(brain.brain_id, principal, requestId)) throw new OperationError('permission_denied', 'The backup reference belongs to another caller or brain.');+ await assertReconcileOutputPath(engine, authority.sourceId, directory);+ privateDirectory(directory);+ const lock = await acquireNativeLock(join(directory, '.capacity.lock'), { timeoutMs: 5000 });+ if (!lock) throw new OperationError('writer_lock_unavailable', 'Reconciliation backup capacity is busy.');+ try {+ return await engine.transaction(async tx => {+ const [row] = await tx.executeRaw<WriteRequest>(`SELECT * FROM persistence_requests WHERE principal_kind=$1 AND principal_id=$2+ AND source_id=$3 AND slug=$4 AND request_id=$5::uuid AND operation='put_page' FOR UPDATE`,+ [principal.kind, principal.id, authority.sourceId, slug, requestId]);+ if (!row) throw new OperationError('permission_denied', 'No caller-bound accepted request authorizes removal of this backup.');+ await authorizeStoredRequest(tx, row, true);+ if (!isTerminal(row) || row.recovery !== null) throw new OperationError('recovery_required', 'The backup still protects a nonterminal or recovering request.');+ const path = join(directory, reference);+ if (!existsSync(path)) return { removed: false, backup_reference: reference, request_id: row.request_id };+ privateDirectory(directory);+ const stat = lstatSync(path);+ if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || !privatePermissions(stat)) throw new OperationError('storage_error', 'The backup is not a private ordinary file.');+ const stored = JSON.parse(readFileSync(path, 'utf8')) as { preview: ReconcileArtifact; principal: Principal; request_id: string };+ if (stored.request_id !== row.request_id || digest(stored.principal) !== digest(principal) ||+ intentDigest({ operation: 'put_page', sourceId: row.source_id, slug: row.slug, callerIntent: { kind: 'canonical_reconcile', preview: stored.preview } }) !== row.digest) {+ throw new OperationError('storage_error', 'The retained backup does not match its immutable request.');+ }+ unlinkSync(path); flushDirectory(directory);+ return { removed: true, backup_reference: reference, request_id: row.request_id, bytes: stat.size };+ });+ } finally { await lock.release(); }+}diff --git a/src/core/persistence/reconcile-merge.ts b/src/core/persistence/reconcile-merge.tsnew file mode 100644index 0000000000..7a992516b8--- /dev/null+++ b/src/core/persistence/reconcile-merge.ts@@ -0,0 +1,121 @@+import type { ParsedPage } from '../import-file.ts';+import type { Page } from '../types.ts';+import { OperationError } from '../ops/contract.ts';+import { digest, stableJson } from './digest.ts';+import { RECONCILE_SAFETY_KEYS } from './reconcile-safety.ts';++export type ReconcileDecision = { path: string; action: 'take_file' | 'take_database' | 'set_value' | 'delete'; value?: unknown };+export interface ReconcileConflict { path: string; file: unknown; database: unknown; }+export const RECONCILE_SCAN_KEYS = ['atoms_scan_hash', 'atoms_fail_hash', 'atoms_fail_count'];+const protectedKeys = new Set([...RECONCILE_SCAN_KEYS, ...RECONCILE_SAFETY_KEYS, 'visibility', 'source_hash', 'source_kind',+ 'source_uri', 'source_slug', 'source_path', 'source_quote', 'source_quote_verified', 'source_quote_offset', 'quote_unverified',+ 'ingested_via', 'ingested_at', 'captured_at', 'extracted_at', 'extracted_by', 'provenance',+ 'trust', 'trust_level', 'trusted', 'trust_frontmatter_overrides', 'allowed_tools']);++export function reconcileCanonical(page: Pick<Page, 'type' | 'title' | 'compiled_truth' | 'timeline' | 'frontmatter'>, tags: string[]): ParsedPage {+ const value = { type: page.type, title: page.title, compiled_truth: page.compiled_truth, timeline: page.timeline ?? '',+ frontmatter: page.frontmatter, tags: [...new Set(tags)].sort() };+ validateReconcileJson(value, true);+ return JSON.parse(stableJson(value)) as ParsedPage;+}+function object(value: unknown): value is Record<string, unknown> { return value !== null && typeof value === 'object' && !Array.isArray(value); }+export function validateReconcileJson(value: unknown, allowDates = false): void {+ let nodes = 0;+ const visit = (item: unknown, depth: number) => {+ if (++nodes > 100_000 || depth > 64) throw new OperationError('request_too_large', 'Reconciliation JSON exceeds the structural limit.');+ if (allowDates && item instanceof Date && Number.isFinite(item.getTime())) return;+ if (item === null || typeof item === 'string' || typeof item === 'boolean' || typeof item === 'number' && Number.isFinite(item)) return;+ if (Array.isArray(item)) { for (const child of item) visit(child, depth + 1); return; }+ if (object(item) && [Object.prototype, null].includes(Object.getPrototypeOf(item))) {+ for (const child of Object.values(item)) visit(child, depth + 1);+ return;+ }+ throw new OperationError('invalid_params', 'Reconciliation values must be finite JSON data.');+ };+ visit(value, 0);+}+export function strictReconcileKeys(value: unknown, allowed: string[], required = allowed): asserts value is Record<string, unknown> {+ if (!object(value) || Object.keys(value).some(k => !allowed.includes(k)) || required.some(k => !Object.hasOwn(value, k))) {+ throw new OperationError('invalid_params', 'Unsupported or missing reconciliation fields.');+ }+}+function pointer(path: string): string[] {+ if (!path.startsWith('/') || /~(?![01])/u.test(path)) throw new OperationError('invalid_params', 'Decisions require escaped JSON Pointer paths.');+ return path.slice(1).split('/').map(k => k.replace(/~1/g, '/').replace(/~0/g, '~'));+}+function escaped(key: string): string { return key.replace(/~/g, '~0').replace(/\//g, '~1'); }+export function protectedReconcileKey(key: string): boolean {+ return protectedKeys.has(key);+}+export function reconcileDecisions(value: unknown): ReconcileDecision[] {+ if (!Array.isArray(value) || value.length > 1000) throw new OperationError('invalid_params', 'decisions must be a bounded array.');+ const decisions = value.map(item => {+ strictReconcileKeys(item, ['path', 'action', 'value'], ['path', 'action']);+ if (typeof item.path !== 'string' || !['take_file', 'take_database', 'set_value', 'delete'].includes(String(item.action)) ||+ (item.action === 'set_value') !== Object.hasOwn(item, 'value')) throw new OperationError('invalid_params', 'Invalid reconciliation decision.');+ const parts = pointer(item.path);+ if (parts[0] === 'tags' || parts[0] === 'frontmatter' && (parts.length === 1 || protectedReconcileKey(parts[1]))) {+ throw new OperationError('permission_denied', 'Reconciliation decisions cannot change protected metadata or remove tags.');+ }+ if (item.action === 'delete' && parts[0] !== 'frontmatter') throw new OperationError('invalid_params', 'Only ordinary metadata fields support explicit deletion.');+ if (item.action === 'set_value') validateReconcileJson(item.value);+ return item as unknown as ReconcileDecision;+ }).sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);+ for (let i = 0; i < decisions.length; i++) for (let j = 0; j < i; j++) {+ if (decisions[i].path === decisions[j].path || decisions[i].path.startsWith(`${decisions[j].path}/`) || decisions[j].path.startsWith(`${decisions[i].path}/`)) {+ throw new OperationError('invalid_params', 'Duplicate or overlapping reconciliation decisions.');+ }+ }+ return decisions;+}++export function mergeReconcile(file: ParsedPage, database: ParsedPage, decisions: ReconcileDecision[] = []) {+ const chosen = new Map(reconcileDecisions(decisions).map(d => [d.path, d]));+ const extractionStatus = file.frontmatter.provenance === 'auto-extracted' || database.frontmatter.provenance === 'auto-extracted';+ if (extractionStatus && [...chosen.keys()].some(path => path === '/frontmatter/status' || path.startsWith('/frontmatter/status/'))) {+ throw new OperationError('permission_denied', 'Extraction review status requires the scoped review workflow.');+ }+ const used = new Set<string>(), conflicts: ReconcileConflict[] = [], protectedPaths: string[] = [], scanPaths: string[] = [];+ const absent = Symbol('absent');+ const merge = (left: unknown | typeof absent, right: unknown | typeof absent, path: string): unknown | typeof absent => {+ const parts = path ? pointer(path) : [];+ if (parts[0] === 'frontmatter' && parts.length === 2 && (protectedReconcileKey(parts[1]) || extractionStatus && parts[1] === 'status')) {+ if (RECONCILE_SCAN_KEYS.includes(parts[1])) { scanPaths.push(path); return absent; }+ if (left !== absent && (right === absent || digest(left) !== digest(right))) protectedPaths.push(path);+ return right;+ }+ const decision = chosen.get(path);+ if (decision) {+ used.add(path);+ if (decision.action === 'delete') return absent;+ if (decision.action === 'set_value') return decision.value;+ const selected = decision.action === 'take_file' ? left : right;+ if (selected === absent) throw new OperationError('invalid_params', 'The chosen side has no value; use an explicit delete decision.');+ return selected;+ }+ if (left === absent) {+ if (object(right)) return merge({}, right, path);+ return right;+ }+ if (right === absent) {+ if (object(left)) return merge(left, {}, path);+ return left;+ }+ if (object(left) && object(right)) {+ return Object.fromEntries([...new Set([...Object.keys(left), ...Object.keys(right)])].sort().flatMap(key => {+ const value = merge(Object.hasOwn(left, key) ? left[key] : absent, Object.hasOwn(right, key) ? right[key] : absent, `${path}/${escaped(key)}`);+ return value === absent ? [] : [[key, value]];+ }));+ }+ if (digest(left) === digest(right)) return left;+ conflicts.push({ path, file: left, database: right });+ return right;+ };+ const tags = [...new Set([...file.tags, ...database.tags])].sort();+ const result = merge({ ...file, tags }, { ...database, tags }, '') as ParsedPage;+ if ([...chosen.keys()].some(path => !used.has(path))) throw new OperationError('invalid_params', 'A decision names an unknown field path.');+ if (['title', 'type', 'compiled_truth', 'timeline'].some(key => typeof result[key as keyof ParsedPage] !== 'string') || !object(result.frontmatter)) {+ throw new OperationError('invalid_params', 'Resolved content has invalid canonical field types.');+ }+ return { result, conflicts, protectedPaths, scanPaths };+}diff --git a/src/core/persistence/reconcile-prepare.ts b/src/core/persistence/reconcile-prepare.tsnew file mode 100644index 0000000000..2525734d27--- /dev/null+++ b/src/core/persistence/reconcile-prepare.ts@@ -0,0 +1,98 @@+import { basename } from 'node:path';+import { readFileSync } from 'node:fs';+import type { BrainEngine } from '../engine.ts';+import type { GBrainConfig } from '../config.ts';+import { importFromContent, type ParsedPage } from '../import-file.ts';+import { parseMarkdown, serializePageToMarkdown } from '../markdown.ts';+import { parseFactsFence, renderFactsTable, replaceOrInsertFactsFence, restoreHiddenFactRows } from '../facts-fence.ts';+import { OperationError } from '../ops/contract.ts';+import { sealPageTextProjection } from '../page-state/projections.ts';+import { sameCanonicalImport } from '../page-state/import-guard.ts';+import { transferLegacyAtomPageState } from '../cycle/extract-atoms-page-state.ts';+import type { PreparedContentImport } from './prepared-import.ts';+import type { PreparedMutation } from './coordinator.ts';+import type { WriteRequest } from './model.ts';+import { authorizeStoredRequest } from './authority.ts';+import { prepareCanonicalProjections } from './canonical-projections.ts';+import { preserveProtectedTakes } from './protected-takes.ts';+import { digest, sha256 } from './digest.ts';+import { mergeReconcile, reconcileCanonical, type ReconcileDecision } from './reconcile-merge.ts';+import { stabilizeSafetyAssessments } from './reconcile-safety.ts';+import { assertReconcilePins, readReconcileState, staleReconcile, validateReconcileArtifact, type ReconcileState } from './reconcile-state.ts';+import { verifyReconcileBackup } from './reconcile-backup.ts';++function preservePrivateFacts(incoming: string, stored: string): string {+ const next = parseFactsFence(incoming), prior = parseFactsFence(stored);+ if (next.warnings.length || prior.warnings.length) throw new OperationError('invalid_params', 'Fact fences must parse losslessly before reconciliation.');+ for (const fact of prior.facts.filter(f => f.visibility !== 'world')) {+ if (next.facts.some(f => f.claim === fact.claim && (f.visibility !== fact.visibility || f.rowNum === fact.rowNum && digest(f) !== digest(fact)))) {+ throw new OperationError('permission_denied', 'Reconciliation cannot modify protected private facts; use the scoped fact workflow.');+ }+ }+ const merged = restoreHiddenFactRows(next, prior);+ return merged ? replaceOrInsertFactsFence(incoming, renderFactsTable(merged.merged)) : incoming;+}+export async function prepareReconcileResult(engine: BrainEngine, state: ReconcileState, decisions: ReconcileDecision[]) {+ const merged = mergeReconcile(state.file, reconcileCanonical(state.snapshot.page, state.snapshot.tags), decisions);+ if (merged.conflicts.length) return { ...merged, ready: undefined };+ const result = merged.result;+ for (const key of ['compiled_truth', 'timeline'] as const) {+ result[key] = preservePrivateFacts(preserveProtectedTakes(result[key], state.snapshot.page[key] ?? ''), state.snapshot.page[key] ?? '');+ }+ const content = serializePageToMarkdown({ ...state.snapshot.page, ...result }, result.tags);+ let ready: PreparedContentImport | undefined;+ const imported = await importFromContent(engine, state.pins.slug, content, {+ sourceId: state.pins.source_id, sourcePath: state.snapshot.page.source_path ?? undefined,+ filename: basename(state.path).replace(/\.mdx?$/i, ''), noEmbed: true, remote: false, allowEmptyOverwrite: true,+ prepareFrontmatter: page => stabilizeSafetyAssessments(page.frontmatter, state.snapshot.page.frontmatter, state.pins.assessment_at),+ prepare: async prepared => { ready = prepared; return prepared.result; },+ });+ if (!ready || ready.slug !== state.pins.slug) throw new OperationError('invalid_params', imported.error ?? 'Reconciliation cannot change page identity or deduplicate to another page.');+ if (ready.observedRevision !== state.snapshot.revision) staleReconcile('revision changed during policy assessment');+ const resolved = reconcileCanonical(ready.parsedPage, [...new Set([...state.snapshot.tags, ...ready.parsedPage.tags])]);+ const project = prepareCanonicalProjections(resolved, state.pins.slug, state.pins.source_id);+ return { ...merged, result: resolved, ready, project };+}++export async function prepareReconcileMutation(engine: BrainEngine, row: WriteRequest, _config: GBrainConfig): Promise<PreparedMutation> {+ if (row.operation !== 'put_page' || row.intent?.kind !== 'canonical_reconcile' || row.authority.remote !== false || row.authority.principal.kind !== 'local_cli') {+ throw new OperationError('permission_denied', 'Canonical reconciliation requires trusted local administration.');+ }+ await authorizeStoredRequest(engine, row);+ const artifact = validateReconcileArtifact(row.intent.preview);+ const reference = row.intent.backup_reference;+ if (typeof reference !== 'string') throw new OperationError('storage_error', 'Reconciliation has no retained preimages.');+ verifyReconcileBackup(reference, artifact);+ if (artifact.status !== 'ready' || artifact.preconditions.source_id !== row.source_id || artifact.preconditions.slug !== row.slug || artifact.preconditions.page_id !== row.page_id) {+ throw new OperationError('invalid_params', 'The reconciliation artifact does not name the accepted page.');+ }+ const state = await readReconcileState(engine, row.source_id, row.slug, artifact.preconditions.assessment_at);+ assertReconcilePins(artifact.preconditions, state.pins);+ const prepared = await prepareReconcileResult(engine, state, artifact.decisions);+ if (!prepared.ready || digest(prepared.result) !== artifact.result_digest) staleReconcile('canonical policy result changed');+ const content = serializePageToMarkdown({ ...state.snapshot.page, ...prepared.result }, prepared.result.tags);+ const ready = prepared.ready;+ return {+ observedRevision: state.snapshot.revision,+ file: { path: state.path, root: state.root, content, expectedBeforeHash: state.pins.raw_file_hash },+ noop: ready.noop && sha256(content) === state.pins.raw_file_hash,+ validate: async tx => {+ await authorizeStoredRequest(tx, row, true);+ assertReconcilePins(artifact.preconditions, (await readReconcileState(tx, row.source_id, row.slug, artifact.preconditions.assessment_at)).pins);+ verifyReconcileBackup(reference, artifact);+ },+ apply: async tx => {+ await ready.apply(tx);+ if (!ready.noop) { await prepared.project!(tx); await sealPageTextProjection(tx, row.slug, row.source_id); }+ const final = await tx.readPageSnapshot(row.slug, { sourceId: row.source_id });+ const scanStateTransferred = final ? await transferLegacyAtomPageState(tx, state.snapshot, final) : false;+ const file = parseMarkdown(readFileSync(state.path, 'utf8'), row.slug);+ if (!sameCanonicalImport(final, prepared.result) || digest(reconcileCanonical(file, file.tags)) !== artifact.result_digest) {+ throw new OperationError('storage_error', 'Reconciliation canonical readback did not match the reviewed result.');+ }+ return { status: 'reconciled', source_id: row.source_id, slug: row.slug, backup_reference: reference,+ result_digest: artifact.result_digest, database_changed: !ready.noop, file_changed: sha256(content) !== state.pins.raw_file_hash,+ scan_state_transferred: scanStateTransferred };+ },+ };+}diff --git a/src/core/persistence/reconcile-safety.ts b/src/core/persistence/reconcile-safety.tsnew file mode 100644index 0000000000..8fa2f6e562--- /dev/null+++ b/src/core/persistence/reconcile-safety.ts@@ -0,0 +1,14 @@+import { digest } from './digest.ts';++export const RECONCILE_SAFETY_KEYS = ['quarantine', 'content_flag', 'embed_skip'];++export function stabilizeSafetyAssessments(frontmatter: Record<string, unknown>, previous: Record<string, unknown>, assessmentAt?: string): void {+ for (const key of RECONCILE_SAFETY_KEYS) {+ const marker = frontmatter[key];+ if (!marker || typeof marker !== 'object' || Array.isArray(marker)) continue;+ const prior = previous[key];+ const withoutStamp = (value: unknown) => value && typeof value === 'object' ? Object.fromEntries(Object.entries(value).filter(([k]) => k !== 'assessed_at')) : value;+ if (prior && digest(withoutStamp(marker)) === digest(withoutStamp(prior))) frontmatter[key] = prior;+ else if (assessmentAt) frontmatter[key] = { ...marker, assessed_at: assessmentAt };+ }+}diff --git a/src/core/persistence/reconcile-state.ts b/src/core/persistence/reconcile-state.tsnew file mode 100644index 0000000000..870f774410--- /dev/null+++ b/src/core/persistence/reconcile-state.ts@@ -0,0 +1,147 @@+import { lstatSync, readFileSync, realpathSync } from 'node:fs';+import { basename, join, relative } from 'node:path';+import { pathToFileURL } from 'node:url';+import type { BrainEngine } from '../engine.ts';+import { loadConfig, loadConfigWithEngine } from '../config.ts';+import { loadOperatorLiterals } from '../content-sanity-literals.ts';+import { parseMarkdown, resolveSourceLocalFilePath } from '../markdown.ts';+import { parseDataFrontmatter } from '../data-frontmatter.ts';+import { OperationError } from '../ops/contract.ts';+import type { PageSnapshot } from '../page-state/types.ts';+import { isWriteTargetContained } from '../path-confine.ts';+import { recordedPathFromFileUri } from '../write-through.ts';+import { localHostId } from './identity.ts';+import { getWorktreeBinding, type WorktreeBinding } from './ownership.ts';+import { digest, requireUuid, sha256, stableJson } from './digest.ts';+import { reconcileCanonical, strictReconcileKeys, validateReconcileJson, type ReconcileConflict, type ReconcileDecision } from './reconcile-merge.ts';+import type { ParsedPage } from '../import-file.ts';++export interface ReconcilePins {+ brain_id: string; source_id: string; source_incarnation: string; slug: string; page_id: number;+ worktree_id: string; binding_digest: string; owner_epoch: string; revision: string;+ raw_file_hash: string; relative_path: string; policy_digest: string; withdrawals_digest: string; assessment_at: string;+}+export interface ReconcileArtifact {+ format_version: 1; preview_id: string; preconditions: ReconcilePins;+ preimages: { file_base64: string; database: PageSnapshot; stored_page: Record<string, unknown> };+ decisions: ReconcileDecision[]; conflicts: ReconcileConflict[]; result: ParsedPage; result_digest: string;+ status: 'needs_resolution' | 'ready';+}+export interface ReconcileState {+ binding: WorktreeBinding; root: string; path: string; raw: Buffer; snapshot: PageSnapshot;+ storedPage: Record<string, unknown>; file: ParsedPage; pins: ReconcilePins;+}+export async function reconcilePolicyDigest(engine: BrainEngine, sourceId: string): Promise<string> {+ const config = await loadConfigWithEngine(engine, loadConfig());+ const [source] = await engine.executeRaw('SELECT config,contextual_retrieval_mode,trust_frontmatter_overrides FROM sources WHERE id=$1', [sourceId]);+ return digest({ version: 1, config, source, literals: loadOperatorLiterals(), disabled: process.env.GBRAIN_NO_SANITY ?? null });+}+export function staleReconcile(what: string): never {+ throw new OperationError('source_changed', `Reconciliation preview is stale: ${what}.`, 'Generate a fresh preview; submit a corrected intent with a new request ID.');+}+function recordedReconcilePath(root: string, page: { slug: string; source_path?: string | null; source_uri?: string | null }): string | null {+ const path = resolveSourceLocalFilePath(root, page.source_path, page.slug);+ if (path) return path;+ const recorded = recordedPathFromFileUri(page.source_uri, root);+ return recorded ? join(root, recorded) : null;+}+export async function readReconcileState(engine: BrainEngine, sourceId: string, slug: string, assessmentAt = new Date().toISOString()): Promise<ReconcileState> {+ const binding = await getWorktreeBinding(engine, sourceId);+ if (!binding?.local_path || binding.owner_host_id !== localHostId() || binding.state !== 'active') {+ throw new OperationError('owner_unavailable', 'Reconciliation requires the existing active owner on this host.', 'Run repair on the current owner; repair never claims or activates a source.');+ }+ const [brain] = await engine.executeRaw<{ brain_id: string }>('SELECT brain_id FROM persistence_brain WHERE singleton=1');+ const snapshot = await engine.readPageSnapshot(slug, { sourceId, includeDeleted: true });+ if (!snapshot || snapshot.page.deleted_at) throw new OperationError('page_not_found', 'Reconciliation requires an existing live page; use the separate restore workflow for deleted pages.');+ if (binding.source_incarnation !== snapshot.sourceIncarnation) staleReconcile('source binding incarnation');+ const [storedPage] = await engine.executeRaw<Record<string, unknown>>(`SELECT id,source_id,slug,type,title,compiled_truth,timeline,frontmatter,+ content_hash,source_path,source_kind,source_uri,ingested_via,ingested_at,knowledge_revision,deleted_at FROM pages WHERE id=$1 AND source_id=$2`, [snapshot.page.id, sourceId]);+ const root = realpathSync(join(binding.local_path, binding.relative_path));+ const recorded = recordedPathFromFileUri(snapshot.page.source_uri, root);+ const path = recordedReconcilePath(root, snapshot.page);+ if (!path || !isWriteTargetContained(path, root)) throw new OperationError('source_changed', 'The page has no unambiguous confined recorded Markdown origin.');+ let size: number;+ try {+ const info = lstatSync(path);+ if (!info.isFile() || info.isSymbolicLink() || info.nlink !== 1) throw new Error('not an ordinary file');+ size = info.size;+ } catch { throw new OperationError('source_changed', 'The recorded canonical file is missing or is not an ordinary file; repair does not restore files.'); }+ const { readJournalLimits } = await import('./limits.ts');+ const limits = await readJournalLimits(engine);+ if (size > Math.min(limits.principalIntentBytes, limits.brainIntentBytes, limits.worktreeRecoveryBytes)) {+ throw new OperationError('request_too_large', 'The canonical file exceeds reconciliation capacity.');+ }+ const fileName = basename(path), uriName = pathToFileURL(path).pathname.split('/').pop()!;+ const candidates = await engine.executeRaw<{ slug: string; source_path: string | null; source_uri: string | null }>(+ `SELECT slug,source_path,source_uri FROM pages WHERE source_id=$1 AND id<>$2 AND (+ regexp_replace(CASE WHEN $7::boolean THEN replace(btrim(source_path),chr(92),'/') ELSE btrim(source_path) END,'^.*/','')=$3+ OR source_uri LIKE 'file:%' AND (right(source_uri,length($4::text))=$4 OR right(source_uri,length($5::text))=$5)+ OR source_uri=$6) ORDER BY id LIMIT 101`,+ [sourceId, snapshot.page.id, fileName, `/${fileName}`, `/${uriName}`, recorded ? snapshot.page.source_uri : null, process.platform === 'win32']);+ if (candidates.length > 100) throw new OperationError('source_changed', 'Too many candidate page origins to verify this exact file safely.',+ 'Review the recorded source paths before retrying this exact-page reconciliation.');+ const canonicalPath = realpathSync(path);+ for (const candidate of candidates) {+ const candidatePath = recordedReconcilePath(root, candidate);+ if (!candidatePath || !isWriteTargetContained(candidatePath, root)) continue;+ let canonicalCandidate: string;+ try { canonicalCandidate = realpathSync(candidatePath); }+ catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue;+ throw new OperationError('source_changed', 'A candidate canonical file origin could not be verified.');+ }+ if (canonicalCandidate === canonicalPath) throw new OperationError('source_changed', 'Several pages claim the recorded canonical file.');+ }+ const raw = readFileSync(path), text = raw.toString('utf8');+ if (!Buffer.from(text).equals(raw)) throw new OperationError('invalid_params', 'The canonical file must contain valid UTF-8.');+ try { parseDataFrontmatter(text); }+ catch { throw new OperationError('invalid_params', 'Canonical file metadata cannot be parsed losslessly; repair its syntax before previewing.'); }+ const parsed = parseMarkdown(text, slug, { validate: true, expectedSlug: slug });+ const errors = parsed.errors?.filter(e => !['MISSING_OPEN', 'MISSING_CLOSE', 'EMPTY_FRONTMATTER'].includes(e.code)) ?? [];+ if (errors.length || parsed.errors?.some(e => e.code === 'MISSING_CLOSE') || parsed.slug !== slug) {+ throw new OperationError('invalid_params', 'Canonical file metadata cannot be parsed losslessly; repair its syntax before previewing.');+ }+ const pins: ReconcilePins = { brain_id: brain.brain_id, source_id: sourceId, source_incarnation: snapshot.sourceIncarnation, slug,+ page_id: snapshot.page.id, worktree_id: binding.worktree_id, binding_digest: digest({ binding, root, path: canonicalPath }), owner_epoch: String(binding.owner_epoch),+ revision: snapshot.revision, raw_file_hash: sha256(raw), relative_path: relative(root, path),+ policy_digest: await reconcilePolicyDigest(engine, sourceId), withdrawals_digest: digest(snapshot.withdrawals), assessment_at: assessmentAt };+ return { binding, root, path, raw, snapshot, storedPage, file: reconcileCanonical(parsed, parsed.tags), pins };+}+export function assertReconcilePins(expected: ReconcilePins, actual: ReconcilePins): void {+ for (const key of Object.keys(expected) as Array<keyof ReconcilePins>) if (expected[key] !== actual[key]) staleReconcile(key);+}+export function validateReconcileArtifact(value: unknown): ReconcileArtifact {+ validateReconcileJson(value);+ strictReconcileKeys(value, ['format_version', 'preview_id', 'preconditions', 'preimages', 'decisions', 'conflicts', 'result', 'result_digest', 'status']);+ strictReconcileKeys(value.preconditions, ['brain_id', 'source_id', 'source_incarnation', 'slug', 'page_id', 'worktree_id', 'binding_digest',+ 'owner_epoch', 'revision', 'raw_file_hash', 'relative_path', 'policy_digest', 'withdrawals_digest', 'assessment_at']);+ strictReconcileKeys(value.preimages, ['file_base64', 'database', 'stored_page']);+ strictReconcileKeys(value.preimages.database, ['page', 'tags', 'revision', 'sourceIncarnation', 'withdrawals']);+ strictReconcileKeys(value.preimages.database.page, ['id', 'slug', 'source_id', 'type', 'title', 'compiled_truth', 'timeline', 'frontmatter',+ 'content_hash', 'source_path', 'knowledge_revision', 'text_projection_revision', 'emotional_weight', 'created_at', 'updated_at', 'updated_at_iso',+ 'deleted_at', 'effective_date', 'effective_date_source', 'import_filename', 'salience_touched_at', 'source_kind', 'source_uri', 'ingested_via',+ 'ingested_at', 'contextual_retrieval_mode', 'corpus_generation'], ['id', 'slug', 'source_id', 'type', 'title', 'compiled_truth', 'timeline', 'frontmatter']);+ strictReconcileKeys(value.preimages.stored_page, ['id', 'source_id', 'slug', 'type', 'title', 'compiled_truth', 'timeline', 'frontmatter',+ 'content_hash', 'source_path', 'source_kind', 'source_uri', 'ingested_via', 'ingested_at', 'knowledge_revision', 'deleted_at']);+ strictReconcileKeys(value.result, ['type', 'title', 'compiled_truth', 'timeline', 'frontmatter', 'tags']);+ const result = value.result;+ if (value.format_version !== 1 || typeof value.preview_id !== 'string' || !['ready', 'needs_resolution'].includes(String(value.status)) ||+ !Array.isArray(value.conflicts) || !Array.isArray(value.decisions) || !Array.isArray(value.preimages.database.tags) ||+ !Array.isArray(value.preimages.database.withdrawals) || !Array.isArray(value.result.tags) || value.result.tags.some(v => typeof v !== 'string') ||+ ['type', 'title', 'compiled_truth', 'timeline'].some(key => typeof result[key] !== 'string') ||+ value.result.frontmatter === null || typeof value.result.frontmatter !== 'object' || Array.isArray(value.result.frontmatter) ||+ typeof value.preimages.file_base64 !== 'string' ||+ digest(value.result) !== value.result_digest || typeof value.preconditions.assessment_at !== 'string' ||+ !Number.isFinite(Date.parse(value.preconditions.assessment_at)) || !Number.isSafeInteger(value.preconditions.page_id) ||+ Object.entries(value.preconditions).some(([key, v]) => key !== 'page_id' && typeof v !== 'string')) {+ throw new OperationError('invalid_params', 'Malformed or modified reconciliation artifact.');+ }+ for (const key of ['brain_id', 'source_incarnation', 'worktree_id', 'revision']) requireUuid(value.preconditions[key] as string);+ requireUuid(value.preview_id as string);+ for (const key of ['binding_digest', 'raw_file_hash', 'policy_digest', 'withdrawals_digest']) {+ if (!/^[a-f0-9]{64}$/.test(value.preconditions[key] as string)) throw new OperationError('invalid_params', 'Invalid reconciliation fingerprint.');+ }+ for (const conflict of value.conflicts as unknown[]) strictReconcileKeys(conflict, ['path', 'file', 'database']);+ for (const withdrawal of value.preimages.database.withdrawals as unknown[]) strictReconcileKeys(withdrawal, ['visibility', 'fact_hash', 'withdrawn_at']);+ return JSON.parse(stableJson(value)) as ReconcileArtifact;+}diff --git a/src/core/persistence/reconcile.ts b/src/core/persistence/reconcile.tsnew file mode 100644index 0000000000..753fefb9f7--- /dev/null+++ b/src/core/persistence/reconcile.ts@@ -0,0 +1,147 @@+import { randomUUID } from 'node:crypto';+import type { BrainEngine } from '../engine.ts';+import { loadConfig, loadConfigWithEngine, type GBrainConfig } from '../config.ts';+import { OperationError, type OperationContext } from '../ops/contract.ts';+import { validatePageSlug, slugUnderBoundPrefixes } from '../ops/context.ts';+import { isValidSourceId } from '../source-id.ts';+import { submissionAuthority, authorizeStoredRequest } from './authority.ts';+import { currentVerifiedLocalWriter } from './identity.ts';+import { admitWrite, assertPageRequestIdentity, assertReplayIntent, getWriteRequest, intentDigest } from './journal.ts';+import { assertPersistenceAccepting, waitForWrite, writeResponse } from './service.ts';+import { digest, requireUuid, sha256, stableJson } from './digest.ts';+import { reconcileCanonical, reconcileDecisions, strictReconcileKeys } from './reconcile-merge.ts';+import { assertReconcilePins, readReconcileState, staleReconcile, validateReconcileArtifact, type ReconcileArtifact, type ReconcileState } from './reconcile-state.ts';+import { prepareReconcileResult } from './reconcile-prepare.ts';+import { assertReconcileOutputPath, assertReconcileSize, manageReconcileBackups, retainReconcileBackup } from './reconcile-backup.ts';+import type { LocalGrant } from './identity.ts';+import { isTerminal } from './model.ts';+import { serializePageToMarkdown } from '../markdown.ts';++export { assertReconcileOutputPath } from './reconcile-backup.ts';+export type { ReconcileArtifact } from './reconcile-state.ts';++async function authorize(engine: BrainEngine, sourceId: unknown, slug: unknown) {+ const verified = currentVerifiedLocalWriter();+ if (!verified || verified.remote || verified.principal.kind !== 'local_cli') throw new OperationError('permission_denied', 'Reconciliation requires a verified trusted local CLI caller.');+ if (typeof sourceId !== 'string' || !isValidSourceId(sourceId) || typeof slug !== 'string' || !slug) throw new OperationError('invalid_params', 'One explicit source ID and page slug are required.');+ validatePageSlug(slug);+ if (/[?*]/.test(slug)) throw new OperationError('invalid_params', 'Reconciliation requires an exact page slug, not a pattern.');+ const permitted = (grant: LocalGrant) => (grant.sourceIds.includes('*') || grant.sourceIds.includes(sourceId)) &&+ grant.scopes.includes('write') && (grant.operations === null || grant.operations.includes('put_page')) &&+ (grant.slugPrefixes === null || slugUnderBoundPrefixes(grant.slugPrefixes, slug));+ if (!permitted(verified.grant)) throw new OperationError('permission_denied', 'Reconciliation exceeds the original CLI grant.');+ const [writer] = await engine.executeRaw<{ grant_ceiling: LocalGrant; revoked_at: unknown; lane: string }>(+ 'SELECT grant_ceiling,revoked_at,lane FROM persistence_local_writers WHERE id=$1::uuid', [verified.principal.id]);+ if (!writer || writer.revoked_at !== null || writer.lane !== 'cli' || !permitted(writer.grant_ceiling)) {+ throw new OperationError('permission_denied', 'Reconciliation exceeds the current CLI grant.');+ }+ const [source] = await engine.executeRaw<{ incarnation: string; archived: boolean }>('SELECT incarnation,archived FROM sources WHERE id=$1', [sourceId]);+ if (!source || source.archived) throw new OperationError('source_changed', 'The explicit source is missing or archived.');+ const authority = await submissionAuthority({ engine, remote: false, sourceId } as OperationContext, 'put_page', sourceId, source.incarnation, slug);+ return { sourceId, slug, authority };+}+function assertPreimages(artifact: ReconcileArtifact, state: ReconcileState): void {+ assertReconcilePins(artifact.preconditions, state.pins);+ const canonical = (snapshot: typeof state.snapshot) => ({ page: reconcileCanonical(snapshot.page, snapshot.tags), revision: snapshot.revision,+ sourceIncarnation: snapshot.sourceIncarnation, withdrawals: snapshot.withdrawals,+ provenance: Object.fromEntries(['id', 'slug', 'source_id', 'source_path', 'source_kind', 'source_uri', 'ingested_via', 'ingested_at',+ 'knowledge_revision', 'deleted_at'].map(key => [key, snapshot.page[key as keyof typeof snapshot.page]])) });+ if (artifact.preimages.file_base64 !== state.raw.toString('base64') || digest(canonical(artifact.preimages.database)) !== digest(canonical(state.snapshot)) ||+ digest(artifact.preimages.stored_page) !== digest(state.storedPage)) staleReconcile('preimages changed or were edited');+}+async function config(engine: BrainEngine): Promise<GBrainConfig> {+ return await loadConfigWithEngine(engine, loadConfig()) ?? { engine: engine.kind } as GBrainConfig;+}+export async function runReconcilePreview(engine: BrainEngine, params: Record<string, unknown>): Promise<Record<string, unknown> & { preview: ReconcileArtifact }> {+ strictReconcileKeys(params, ['source_id', 'slug', 'from', 'decisions', 'output_path'], ['source_id', 'slug']);+ const { sourceId, slug } = await authorize(engine, params.source_id, params.slug);+ if (params.output_path !== undefined) {+ if (typeof params.output_path !== 'string') throw new OperationError('invalid_params', 'output_path must be an absolute private file path.');+ await assertReconcileOutputPath(engine, sourceId, params.output_path);+ }+ const from = params.from === undefined ? undefined : validateReconcileArtifact(params.from);+ if (params.decisions !== undefined && !from) throw new OperationError('invalid_params', 'Decisions require the previous private preview artifact.');+ if (from && (from.preconditions.source_id !== sourceId || from.preconditions.slug !== slug)) throw new OperationError('invalid_params', 'The previous preview names a different page.');+ const state = await readReconcileState(engine, sourceId, slug, from?.preconditions.assessment_at);+ if (from) assertPreimages(from, state);+ const decisions = reconcileDecisions(params.decisions ?? from?.decisions ?? []);+ const prepared = await prepareReconcileResult(engine, state, decisions);+ const preview: ReconcileArtifact = { format_version: 1, preview_id: from?.preview_id ?? randomUUID(), preconditions: state.pins,+ preimages: JSON.parse(stableJson({ file_base64: state.raw.toString('base64'), database: state.snapshot, stored_page: state.storedPage })),+ decisions, conflicts: prepared.conflicts, result: prepared.result, result_digest: digest(prepared.result),+ status: prepared.conflicts.length ? 'needs_resolution' : 'ready' };+ await assertReconcileSize(engine, preview);+ return { source_id: sourceId, slug, preview_id: preview.preview_id, status: preview.status,+ conflict_paths: prepared.conflicts.map(c => c.path), protected_paths: prepared.protectedPaths,+ migrated_scan_paths: prepared.scanPaths, relative_path: state.pins.relative_path,+ line_endings: state.raw.includes(Buffer.from('\r\n')) ? 'crlf' : 'lf',+ formatting_only: digest(state.file) === digest(reconcileCanonical(state.snapshot.page, state.snapshot.tags)) &&+ sha256(serializePageToMarkdown(state.snapshot.page, state.snapshot.tags)) !== state.pins.raw_file_hash,+ result_digest: preview.result_digest, preview };+}+export async function runReconcileApply(engine: BrainEngine, params: Record<string, unknown>): Promise<Record<string, unknown>> {+ strictReconcileKeys(params, ['source_id', 'slug', 'preview', 'request_id']);+ const { sourceId, slug, authority } = await authorize(engine, params.source_id, params.slug);+ const artifact = validateReconcileArtifact(params.preview);+ artifact.decisions = reconcileDecisions(artifact.decisions);+ const requestId = requireUuid(params.request_id as string);+ if (artifact.preconditions.source_id !== sourceId || artifact.preconditions.slug !== slug || artifact.status !== 'ready' || artifact.conflicts.length) {+ throw new OperationError('invalid_params', 'Apply requires a ready preview for this exact source and page.');+ }+ const callerIntent = { kind: 'canonical_reconcile', preview: artifact };+ const expectedDigest = intentDigest({ operation: 'put_page', sourceId, slug, callerIntent });+ await assertPageRequestIdentity(engine, authority.principal, requestId);+ const replay = async () => {+ const prior = await getWriteRequest(engine, authority.principal, requestId);+ if (!prior) return null;+ assertReplayIntent(prior, expectedDigest);+ await authorizeStoredRequest(engine, prior);+ return writeResponse(isTerminal(prior) ? prior : await waitForWrite(engine, prior, await config(engine)));+ };+ const prior = await replay();+ if (prior) return prior;+ try {+ assertPersistenceAccepting(engine);+ await assertReconcileSize(engine, artifact);+ const state = await readReconcileState(engine, sourceId, slug, artifact.preconditions.assessment_at);+ assertPreimages(artifact, state);+ const prepared = await prepareReconcileResult(engine, state, artifact.decisions);+ if (!prepared.ready || digest(prepared.result) !== artifact.result_digest) staleReconcile('resolved content or canonical policy changed');+ const preparedReplay = await replay();+ if (preparedReplay) return preparedReplay;+ const reference = await retainReconcileBackup(engine, artifact, authority.principal, requestId);+ const retainedReplay = await replay();+ if (retainedReplay) return retainedReplay;+ const current = await readReconcileState(engine, sourceId, slug, artifact.preconditions.assessment_at);+ assertPreimages(artifact, current);+ const row = await admitWrite(engine, { principal: authority.principal, operation: 'put_page', sourceId,+ sourceIncarnation: state.pins.source_incarnation, slug, pageId: state.pins.page_id, worktreeId: state.pins.worktree_id,+ topologyGeneration: state.binding.topology_generation, requestId, authority, callerIntent,+ intent: { ...callerIntent, backup_reference: reference } });+ return writeResponse(await waitForWrite(engine, row, await config(engine)));+ } catch (error) {+ const racedReplay = await replay();+ if (racedReplay) return racedReplay;+ if (error instanceof OperationError) throw error;+ throw new OperationError('storage_error', 'Reconciliation could not preserve or publish its private artifacts.', 'Inspect private storage capacity and permissions before retrying the same request ID.');+ }+}++export async function runReconcileBackups(engine: BrainEngine, params: Record<string, unknown>): Promise<Record<string, unknown>> {+ strictReconcileKeys(params, ['source_id', 'slug', 'action', 'backup_reference', 'after', 'limit'], ['source_id', 'slug', 'action']);+ const { slug, authority } = await authorize(engine, params.source_id, params.slug);+ if (!['list', 'remove'].includes(String(params.action)) || params.action === 'remove' &&+ (typeof params.backup_reference !== 'string' || params.after !== undefined || params.limit !== undefined) ||+ params.action === 'list' && params.backup_reference !== undefined || params.limit !== undefined &&+ (!Number.isSafeInteger(params.limit) || Number(params.limit) < 1 || Number(params.limit) > 100)) {+ throw new OperationError('invalid_params', 'Invalid exact-page backup administration parameters.');+ }+ try {+ return await manageReconcileBackups(engine, authority, slug, { action: params.action as 'list' | 'remove',+ backup_reference: params.backup_reference as string | undefined, after: params.after === undefined ? undefined : requireUuid(params.after as string),+ limit: params.limit as number | undefined });+ } catch (error) {+ if (error instanceof OperationError) throw error;+ throw new OperationError('storage_error', 'Private reconciliation backup administration failed.', 'Inspect the private backup directory permissions and capacity.');+ }+}diff --git a/src/core/persistence/service.ts b/src/core/persistence/service.tsindex 43ac75fe54..3b6516526f 100644--- a/src/core/persistence/service.ts+++ b/src/core/persistence/service.ts@@ -22,6 +22,7 @@ export function startPersistenceConsumer(engine: BrainEngine, config: GBrainConfconst consumer = new PersistenceConsumer(engine, config, async (e, row, cfg) => {const registered = preparers.get(row.operation);if (registered) return registered(e, row, cfg);+ if (row.operation === 'put_page' && row.intent?.kind === 'canonical_reconcile') return (await import('./reconcile-prepare.ts')).prepareReconcileMutation(e, row, cfg);if (row.operation === 'submit_job' && row.intent?.kind === 'code_projection_reindex') return (await import('./projection-reindex.ts')).prepareCodeReindex(e, row);if (row.operation === 'submit_job' && String(row.intent?.kind).startsWith('managed_sync_')) return (await import('./sync-prepare.ts')).prepareManagedSyncMutation(e, row, cfg);if (row.operation === 'remember') return (await import('./memory-mutations.ts')).prepareMemoryMutation(e, row, cfg);diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.tsindex de02d8bd47..a023d53593 100644--- a/src/core/persistence/sync-run.ts+++ b/src/core/persistence/sync-run.ts@@ -4,15 +4,32 @@ import type { SyncOpts, SyncResult } from '../../commands/sync.ts';import { loadConfig } from '../config.ts';import { OperationError } from '../ops/contract.ts';import { currentJobSignal } from '../minions/submission-authority.ts';-import { digest } from './digest.ts';-import { getWriteRequest, admitWrite } from './journal.ts';+import { digest, sha256 } from './digest.ts';+import { getWriteRequest, admitWrite, receiptFor } from './journal.ts';import { assertPersistenceAccepting, foregroundWriteCompletions, startPersistenceConsumer, waitForWrite } from './service.ts';-import { discoverManagedSync, resolveManagedSyncContext, readSyncContent, syncRawHash, type SyncDiscovery } from './sync-discovery.ts';+import { discoverManagedSync, resolveManagedSyncContext, readSyncContent, readSyncFile, syncRawHash, type SyncDiscovery } from './sync-discovery.ts';import { managedSyncAuthority, validateSyncAuthority, validateManagedSyncOptions, type SyncAuthority } from './sync-authority.ts';import type { SyncIntent } from './sync-prepare.ts';import { currentCompanyBrainSync, getCompanyBrainProfile, readCompanyBrainPlan } from '../company-brain/profile.ts';import { readCommittedBlob } from '../company-brain/revision.ts';import { refreshProjectionStatistics } from '../search/projection-statistics.ts';+import { recordFailures, clearFailures } from '../sync-failure-ledger.ts';+import { writeFailureDiagnostic } from './verb-errors.ts';+import { isTerminalWriteState, publicWriteReceipt, type WriteReceipt } from './types.ts';+import type { WriteRequest } from './model.ts';++export interface ManagedSyncWriteDiagnostic {+ source_id: string;+ slug: string;+ path: string | null;+ write_error: string;+ reason: string;+ message: string;+ suggestion: string;+ write_request: WriteReceipt;+ line_endings?: 'crlf_lf_only';+ ledger_recorded?: boolean;+}interface Pending { requestId: string; slug: string; pageId: number | null; intent: SyncIntent; }interface Cursor extends SyncDiscovery { runId: string; index: number; authority: SyncAuthority; pending?: Pending; done?: boolean; companyReceiptId?: string;@@ -54,6 +71,31 @@ function result(cursor: Cursor, status: SyncResult['status'], reason?: SyncResuldeleted: cursor.counts.deleted, renamed: 0, chunksCreated: cursor.counts.chunks, embedded: 0, pagesAffected: [],filesImported: cursor.index, bankedFiles: cursor.index, ...(cursor.uncommitted ? { uncommitted: cursor.uncommitted } : {}), ...(reason ? { reason } : {}) };}+function writeDiagnostic(cursor: Cursor, pending: Pending, row: WriteRequest): ManagedSyncWriteDiagnostic {+ const terminal = isTerminalWriteState(row.state);+ const code = terminal ? row.error_code ?? (row.state === 'cancelled' ? 'cancelled' : 'storage_error') : 'write_pending';+ const blockedReason = ['writer_busy', 'writer_pool_capacity', 'owner_unavailable', 'recovery_required', 'writer_lock_unavailable',+ 'database_contention', 'consumer_stopping', 'revision_changed_repreparing'].includes(row.blocked_reason ?? '') ? row.blocked_reason! : 'write_pending';+ const detail = terminal ? writeFailureDiagnostic(code, row.error_message) : {+ reason: blockedReason, message: 'The write is accepted but not committed; the sync checkpoint has not advanced.',+ suggestion: 'Re-run the same sync options to resume this request. Do not submit a replacement request or skip the pending write.',+ };+ const diagnostic: ManagedSyncWriteDiagnostic = { source_id: cursor.sourceId, slug: pending.slug,+ path: pending.intent.path, write_error: code, ...detail, write_request: publicWriteReceipt(receiptFor(row)) };+ if (terminal) diagnostic.suggestion += ' After repair, run gbrain sync with the same source/options and --retry-failed to start a new request. Without --retry-failed, the frozen terminal request returns the same outcome. --skip-failed cannot bypass a managed write.';+ if (diagnostic.reason === 'pinned_git_worktree_conflict' && pending.intent.path && pending.intent.content !== null) {+ try {+ const bytes = readSyncFile(cursor.root, pending.intent.path);+ if (bytes && sha256(bytes) === pending.intent.rawHash && sha256(bytes) !== sha256(pending.intent.content)+ && bytes.equals(Buffer.from(bytes.toString('utf8')))+ && bytes.toString('utf8').replace(/\r\n/g, '\n') === pending.intent.content.replace(/\r\n/g, '\n')) {+ diagnostic.line_endings = 'crlf_lf_only';+ diagnostic.message += ' The frozen working-tree and Git versions differ only by CRLF/LF line endings; exact byte protection still applies.';+ }+ } catch {}+ }+ return diagnostic;+}async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string): Promise<Pending> {const entry = cursor.entries[cursor.index];let slug = '__managed_sync_checkpoint__', pageId: number | null = null, revision: string | null = null;@@ -169,11 +211,19 @@ export async function performManagedSync(engine: BrainEngine, opts: SyncOpts, slprincipal: cursor.authority.writer.principal, authority: cursor.authority.writer, callerIntent: pending.intent, intent: pending.intent });await validateSyncAuthority(engine, cursor.authority, pending.slug);const done = await waitForWrite(engine, row, config, 5000);- if (!['committed','failed','conflict','cancelled'].includes(done.state)) return result(cursor, 'partial', 'writer_pending');+ if (!isTerminalWriteState(done.state)) return { ...result(cursor, 'partial', 'writer_pending'), managedWrite: writeDiagnostic(cursor, pending, done) };if (done.state !== 'committed') {+ const diagnostic = writeDiagnostic(cursor, pending, done);+ try {+ recordFailures(cursor.sourceId, [{ path: pending.intent.path ?? '<checkpoint>',+ error: `${diagnostic.write_error}: ${diagnostic.message} Request: ${done.request_id}` }], cursor.target);+ diagnostic.ledger_recorded = true;+ } catch { diagnostic.ledger_recorded = false; }return { ...result(cursor, 'blocked_by_failures'), failedFiles: 1,- failureCodes: [{ code: done.error_code ?? 'storage_error', count: 1 }] };+ failureCodes: [{ code: diagnostic.write_error, count: 1 }], managedWrite: diagnostic };}+ try { clearFailures(cursor.sourceId, [pending.intent.path ?? '<checkpoint>']); }+ catch { console.warn('[sync-failures] Could not clear the local ledger; the durable write receipt is committed.'); }if (pending.intent.kind === 'managed_sync_checkpoint') {cursor = (await readCursor(engine, key))!;if (!cursor?.done) throw new OperationError('storage_error', 'Committed sync checkpoint lost its cursor.');diff --git a/src/core/persistence/verb-errors.ts b/src/core/persistence/verb-errors.tsindex 61e8f36c12..4f5bb0f2f7 100644--- a/src/core/persistence/verb-errors.ts+++ b/src/core/persistence/verb-errors.ts@@ -1,23 +1,71 @@import { verbError, OperationError } from '../ops/contract.ts';import { isTerminalWriteState, isWriteErrorCode, type WriteErrorCode, type WriteReceipt } from './types.ts';+export function writeFailureDiagnostic(code: string, message?: string | null): { reason: string; message: string; suggestion: string } {+ if (code === 'source_changed') {+ if (message === 'The canonical file contains an uncoordinated local edit.') return {+ reason: 'file_database_drift', message: 'The canonical file and database disagree. Neither copy was overwritten.',+ suggestion: 'On the source host, run gbrain sources reconcile <source> <slug> --brain <brain> --preview. Review and apply the resolved preview before retrying the original write with a new request_id. This is data repair, not an ownership or permission change.',+ };+ if (['Newer working-tree bytes and the current page disagree with this pinned Git import.',+ 'Newer code file bytes disagree with the pinned import.', 'Canonical sanitization cannot overwrite newer working-tree bytes.'].includes(message ?? '')) return {+ reason: 'pinned_git_worktree_conflict', message: 'The pinned Git content conflicts with working-tree bytes; sync did not overwrite them.',+ suggestion: 'Inspect the exact working-tree bytes and pinned Git version, including CRLF/LF differences. Preserve local edits; do not normalize or discard them automatically. If the file and database disagree, preview gbrain sources reconcile <source> <slug> --brain <brain> --preview on the source host.',+ };+ if (['The imported file changed after sync admission.', 'The canonical file changed after preparation.',+ 'The canonical file changed during preparation.'].includes(message ?? '')) return {+ reason: 'raw_file_changed', message: 'The source file bytes changed after this request was accepted.',+ suggestion: 'Review the changed file before starting a corrected attempt. Exact byte checks remain required even when Git reports a clean file.',+ };+ if (message === 'The canonical file was removed outside coordinated publication.') return {+ reason: 'canonical_file_missing', message: 'The canonical file is missing; the database page was not overwritten.',+ suggestion: 'Review the deletion and recover the intended canonical file or import the intended deletion before retrying. Reconciliation does not restore missing files.',+ };+ if (message === 'An unindexed file already occupies the canonical page path.') return {+ reason: 'canonical_path_occupied', message: 'An unindexed file already occupies this page path; it was not overwritten.',+ suggestion: 'Review and import the existing file before retrying the intended page write.',+ };+ if (['The canonical file target is outside its registered source.', 'The registered source root was replaced by a symlink.',+ 'Sync file escaped its registered root.', 'Sync cannot publish through a symlink.', 'Sync target is not a regular file.'].includes(message ?? '')) return {+ reason: 'unsafe_file_target', message: 'The file target no longer meets the registered source confinement checks.',+ suggestion: 'Inspect the registered source and file type on its owner. Do not bypass confinement checks or replace ownership to force publication.',+ };+ if (message === 'The unfinished sync cursor belongs to an older source binding.' || message === 'The original sync source was replaced.') return {+ reason: 'source_binding_changed', message: 'The source binding changed after this sync was accepted.',+ suggestion: 'Inspect the current source binding on its existing owner. Do not claim, transfer, or activate a source as a data-repair shortcut.',+ };+ return { reason: 'source_changed', message: 'A canonical source input or binding changed; the write was refused.',+ suggestion: 'Inspect the source on its existing owner. For file/database drift, preview gbrain sources reconcile <source> <slug> --brain <brain> --preview. Do not change ownership or permissions to bypass this guard.' };+ }+ if (code === 'owner_unavailable') return { reason: code, message: 'The accepted source owner is unavailable or changed.',+ suggestion: 'Check the existing owner and its availability. Do not claim, transfer, or activate a source to repair content.' };+ if (code === 'permission_denied' || code === 'scope_denied') return { reason: code, message: 'The caller is not authorized for this write.',+ suggestion: 'Check the current caller grant for this source and operation. Content reconciliation does not grant permissions.' };+ if (code === 'revision_conflict' || code === 'page_identity_changed') return { reason: code, message: 'The accepted page identity or revision no longer matches.',+ suggestion: 'Read the current page and review the intended change before submitting a corrected write.' };+ return { reason: isWriteErrorCode(code) ? code : 'storage_error', message: 'The write did not commit. Inspect its durable request on the source host.',+ suggestion: 'Resolve the reported write failure before starting a corrected attempt.' };+}+/** Apply the frozen contract at the verb boundary for CLI and every transport. */export async function runMemoryWrite<T>(run: () => Promise<T>): Promise<T> {try { return await run(); } catch (error) {if (!(error instanceof OperationError)) throw error;- if (error.writeRequest) throw frozenVerbWriteError(error.writeRequest, error.writeError);if (error.protocolVersion === 1 && ['invalid_params','provenance_required','not_found','scope_denied','unavailable','budget_unsatisfiable','internal'].includes(error.code)) throw error;+ if (error.writeRequest) throw frozenVerbWriteError(error.writeRequest, error.writeError, error.message);const code = ['permission_denied','scope_denied','source_changed','writer_registration_required'].includes(error.code)? 'scope_denied' : ['revision_required','revision_conflict','idempotency_conflict','invalid_params','page_identity_changed'].includes(error.code)? 'invalid_params' : 'unavailable';- const frozen = verbError(code,error.message,error.suggestion ?? 'Inspect writer status before retrying.');+ const diagnostic = error.code === 'source_changed' ? writeFailureDiagnostic(error.code, error.message) : null;+ const frozen = verbError(code,diagnostic?.message ?? error.message,diagnostic?.suggestion ?? error.suggestion ?? 'Inspect writer status before retrying.');+ if (diagnostic) frozen.detail = diagnostic.reason;if (isWriteErrorCode(error.code)) frozen.writeError=error.code;throw frozen;}}/** Queue states are additive detail; frozen MEMORY_VERBS v1 error codes never widen. */-export function frozenVerbWriteError(receipt: WriteReceipt, reason?: WriteErrorCode): OperationError {+export function frozenVerbWriteError(receipt: WriteReceipt, reason?: WriteErrorCode, message?: string): OperationError {const pending = !isTerminalWriteState(receipt.state);const writeError = reason ?? (pending ? 'write_pending': receipt.state === 'conflict' ? 'revision_conflict'@@ -25,16 +73,16 @@ export function frozenVerbWriteError(receipt: WriteReceipt, reason?: WriteErrorCconst code = ['source_changed','permission_denied','scope_denied','writer_registration_required'].includes(writeError) ? 'scope_denied': ['revision_required', 'revision_conflict', 'idempotency_conflict','invalid_params','page_identity_changed'].includes(writeError)? 'invalid_params' : 'unavailable';+ const diagnostic = writeFailureDiagnostic(writeError, message);const suggestion = pending? `Retry the same verb with the same arguments and request_id ${receipt.request_id}${receipt.retry_after_ms === null ? ' after checking writer availability' : ` after ${receipt.retry_after_ms} ms`}. Do not submit a new request_id for this write.`- : receipt.state === 'conflict'- ? 'Read the current state and submit any corrected write with a new request_id. Reusing this request_id returns the same conflict.'- : receipt.state === 'cancelled'+ : receipt.state === 'cancelled'? 'This request was cancelled. Submit a new request_id only if you want to make a new write.'- : 'Resolve the reported write failure before submitting a new request_id. Reusing this request_id returns the same outcome.';+ : `${diagnostic.suggestion} Submit any corrected write with a new request_id. Reusing this request_id returns the same ${receipt.state === 'conflict' ? 'conflict' : 'outcome'}.`;const error = verbError(code,- pending ? 'The write is accepted and awaiting completion.' : `The write ended with state ${receipt.state}.`,+ pending ? 'The write is accepted and awaiting completion; it is not committed.' : diagnostic.message,suggestion);+ if (!pending) error.detail = diagnostic.reason;error.writeError = writeError;error.writeRequest = receipt;return error;diff --git a/src/core/pglite-schema.ts b/src/core/pglite-schema.tsindex b07de56aa7..cf5e7a933b 100644--- a/src/core/pglite-schema.ts+++ b/src/core/pglite-schema.ts@@ -1266,6 +1266,19 @@ ${PAGE_PROJECTION_SCHEMA_SQL}${PERSISTENCE_TOPOLOGY_SCHEMA_SQL}${SOURCE_INGESTION_RECEIPTS_SCHEMA_SQL}+CREATE TABLE IF NOT EXISTS extract_atoms_page_state (+ source_incarnation UUID NOT NULL REFERENCES sources(incarnation) ON DELETE CASCADE,+ page_id INTEGER NOT NULL REFERENCES pages(id) ON DELETE CASCADE,+ content_hash TEXT NOT NULL,+ fail_count INTEGER NOT NULL DEFAULT 0 CHECK (fail_count >= 0),+ tombstoned BOOLEAN NOT NULL DEFAULT false,+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ PRIMARY KEY (source_incarnation, page_id, content_hash)+);+CREATE INDEX IF NOT EXISTS extract_atoms_page_state_tombstoned_idx+ ON extract_atoms_page_state (source_incarnation, content_hash, page_id) WHERE tombstoned;+CREATE INDEX IF NOT EXISTS extract_atoms_page_state_page_idx ON extract_atoms_page_state (page_id);+`;/**diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.tsindex 73e40653fc..67cdb37970 100644--- a/src/core/schema-embedded.generated.ts+++ b/src/core/schema-embedded.generated.ts@@ -1679,6 +1679,18 @@ END \$\$;-- Canonical page state (migration 150).ALTER TABLE sources ADD COLUMN IF NOT EXISTS incarnation UUID NOT NULL DEFAULT gen_random_uuid();CREATE UNIQUE INDEX IF NOT EXISTS sources_incarnation_key ON sources(incarnation);+CREATE TABLE IF NOT EXISTS extract_atoms_page_state (+ source_incarnation UUID NOT NULL REFERENCES sources(incarnation) ON DELETE CASCADE,+ page_id INTEGER NOT NULL REFERENCES pages(id) ON DELETE CASCADE,+ content_hash TEXT NOT NULL,+ fail_count INTEGER NOT NULL DEFAULT 0 CHECK (fail_count >= 0),+ tombstoned BOOLEAN NOT NULL DEFAULT false,+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ PRIMARY KEY (source_incarnation, page_id, content_hash)+);+CREATE INDEX IF NOT EXISTS extract_atoms_page_state_tombstoned_idx+ ON extract_atoms_page_state (source_incarnation, content_hash, page_id) WHERE tombstoned;+CREATE INDEX IF NOT EXISTS extract_atoms_page_state_page_idx ON extract_atoms_page_state (page_id);ALTER TABLE pages ADD COLUMN IF NOT EXISTS knowledge_revision UUID NOT NULL DEFAULT gen_random_uuid();ALTER TABLE pages ADD COLUMN IF NOT EXISTS text_projection_revision UUID;ALTER TABLE page_versions ADD COLUMN IF NOT EXISTS knowledge_revision UUID;diff --git a/src/schema.sql b/src/schema.sqlindex a3408056b6..5e0375deda 100644--- a/src/schema.sql+++ b/src/schema.sql@@ -1675,6 +1675,18 @@ END $$;-- Canonical page state (migration 150).ALTER TABLE sources ADD COLUMN IF NOT EXISTS incarnation UUID NOT NULL DEFAULT gen_random_uuid();CREATE UNIQUE INDEX IF NOT EXISTS sources_incarnation_key ON sources(incarnation);+CREATE TABLE IF NOT EXISTS extract_atoms_page_state (+ source_incarnation UUID NOT NULL REFERENCES sources(incarnation) ON DELETE CASCADE,+ page_id INTEGER NOT NULL REFERENCES pages(id) ON DELETE CASCADE,+ content_hash TEXT NOT NULL,+ fail_count INTEGER NOT NULL DEFAULT 0 CHECK (fail_count >= 0),+ tombstoned BOOLEAN NOT NULL DEFAULT false,+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ PRIMARY KEY (source_incarnation, page_id, content_hash)+);+CREATE INDEX IF NOT EXISTS extract_atoms_page_state_tombstoned_idx+ ON extract_atoms_page_state (source_incarnation, content_hash, page_id) WHERE tombstoned;+CREATE INDEX IF NOT EXISTS extract_atoms_page_state_page_idx ON extract_atoms_page_state (page_id);ALTER TABLE pages ADD COLUMN IF NOT EXISTS knowledge_revision UUID NOT NULL DEFAULT gen_random_uuid();ALTER TABLE pages ADD COLUMN IF NOT EXISTS text_projection_revision UUID;ALTER TABLE page_versions ADD COLUMN IF NOT EXISTS knowledge_revision UUID;diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.mdindex f20a37e635..8e5d833548 100644--- a/templates/bootstrap/template-repo/README.md+++ b/templates/bootstrap/template-repo/README.md@@ -1,6 +1,6 @@# gbrain agent workspace — template-<!-- gbrain-template-stamp: 0.52.1.0 -->+<!-- gbrain-template-stamp: 0.52.2.0 -->This repository is the **"Use this template"** distribution artifact for a[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the samediff --git a/test/cycle/extract-atoms-work-interleave.test.ts b/test/cycle/extract-atoms-work-interleave.test.tsindex 8192b4c577..dea4e2f80b 100644--- a/test/cycle/extract-atoms-work-interleave.test.ts+++ b/test/cycle/extract-atoms-work-interleave.test.ts@@ -27,7 +27,8 @@import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';import { PGLiteEngine } from '../../src/core/pglite-engine.ts';-import { runPhaseExtractAtoms, countExtractAtomsBacklog } from '../../src/core/cycle/extract-atoms.ts';+import { countExtractAtomsBacklog } from '../../src/core/cycle/extract-atoms.ts';+import { runPhaseWithStoredPageFixtures as runPhaseExtractAtoms } from '../helpers/extract-atoms-page-fixtures.ts';import { BudgetExhausted } from '../../src/core/budget/budget-tracker.ts';import { resetPgliteState } from '../helpers/reset-pglite.ts';import type { ChatResult, ChatOpts } from '../../src/core/ai/gateway.ts';diff --git a/test/e2e/extract-atoms-page-state.test.ts b/test/e2e/extract-atoms-page-state.test.tsnew file mode 100644index 0000000000..9a4b6767c9--- /dev/null+++ b/test/e2e/extract-atoms-page-state.test.ts@@ -0,0 +1,157 @@+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { hasDatabase, setupDB, teardownDB } from './helpers.ts';+import type { PostgresEngine } from '../../src/core/postgres-engine.ts';+import { countExtractAtomsBacklog, discoverExtractablePages, runPhaseExtractAtoms } from '../../src/core/cycle/extract-atoms.ts';+import { readAtomPageIdentity, transferLegacyAtomPageState, writeAtomPageState } from '../../src/core/cycle/extract-atoms-page-state.ts';+import { MIGRATIONS } from '../../src/core/migrate.ts';+import type { ChatResult } from '../../src/core/ai/gateway.ts';++const describeDb = hasDatabase() ? describe : describe.skip;+describeDb('Postgres derived atom page state', () => {+ let engine: PostgresEngine;+ const slug = 'meetings/atom-state-example';+ const body = 'Synthetic evidence with sufficient source detail for extraction. '.repeat(20);+ const chat = async (): Promise<ChatResult> => ({ text: '[]', blocks: [{ type: 'text', text: '[]' }], stopReason: 'end',+ usage: { input_tokens: 1, output_tokens: 1, cache_read_tokens: 0, cache_creation_tokens: 0 },+ model: 'anthropic:claude-haiku-4-5', providerId: 'anthropic' });+ beforeAll(async () => { engine = await setupDB(); }, 60000);+ afterAll(async () => { await teardownDB(); });+ beforeEach(async () => {+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw('TRUNCATE pages CASCADE');+ await engine.executeRaw("DELETE FROM sources WHERE id='atom-state-example'");+ await engine.putPage(slug, { title: 'Synthetic example', type: 'meeting', compiled_truth: body, timeline: '', frontmatter: { preserve: { nested: true } } });+ });+ const snapshot = async () => (await engine.readPageSnapshot(slug, { sourceId: 'default' }))!;++ test('zero-yield scan is indexed derived state, never canonical page mutation', async () => {+ const before = await snapshot();+ expect((await runPhaseExtractAtoms(engine, { _transcripts: [], _chat: chat })).status).toBe('ok');+ expect(await snapshot()).toEqual(before);+ expect(await discoverExtractablePages(engine, 'default')).toEqual([]);+ expect(await countExtractAtomsBacklog(engine)).toBe(0);+ expect(await engine.executeRaw('SELECT fail_count,tombstoned FROM extract_atoms_page_state'))+ .toEqual([{ fail_count: 0, tombstoned: true }]);+ const indexes = await engine.executeRaw<{ indexname: string }>("SELECT indexname FROM pg_indexes WHERE tablename='extract_atoms_page_state'");+ expect(indexes.map(row => row.indexname)).toContain('extract_atoms_page_state_tombstoned_idx');+ });++ test('CAS rejects stale content and page/source replacement', async () => {+ const before = await snapshot();+ const item = { slug, content: body, contentHash: before.page.content_hash! };+ const identity = await readAtomPageIdentity(engine, 'default', item);+ await engine.putPage(slug, { ...before.page, content_hash: undefined, compiled_truth: body + 'Edited.' });+ await expect(writeAtomPageState(engine, 'default', { ...item, identity }, 'complete')).rejects.toThrow('page changed');+ await engine.executeRaw('DELETE FROM pages WHERE slug=$1', [slug]);+ await engine.putPage(slug, { ...before.page });+ await expect(writeAtomPageState(engine, 'default', { ...item, identity }, 'complete')).rejects.toThrow('page changed');+ expect(await countExtractAtomsBacklog(engine, 'default')).toBe(1);+ await engine.executeRaw("INSERT INTO sources(id,name) VALUES ('atom-state-example','Example')");+ await engine.putPage(slug, { ...before.page }, { sourceId: 'atom-state-example' });+ const sourceIdentity = await readAtomPageIdentity(engine, 'atom-state-example', item);+ await engine.executeRaw("DELETE FROM sources WHERE id='atom-state-example'");+ await engine.executeRaw("INSERT INTO sources(id,name) VALUES ('atom-state-example','Replacement')");+ await engine.putPage(slug, { ...before.page }, { sourceId: 'atom-state-example' });+ await expect(writeAtomPageState(engine, 'atom-state-example', { ...item, identity: sourceIdentity }, 'complete')).rejects.toThrow('page changed');+ });++ test('a state write waiting behind a concurrent edit rechecks its CAS after the lock', async () => {+ const before = await snapshot();+ const item = { slug, content: body, contentHash: before.page.content_hash! };+ const identity = await readAtomPageIdentity(engine, 'default', item);+ let edited!: () => void, release!: () => void;+ const editReady = new Promise<void>(resolve => { edited = resolve; });+ const continueEdit = new Promise<void>(resolve => { release = resolve; });+ const writer = engine.transaction(async tx => {+ await tx.executeRaw('UPDATE pages SET compiled_truth=$1, content_hash=$2 WHERE slug=$3', [body + 'Changed.', 'e'.repeat(64), slug]);+ edited();+ await continueEdit;+ });+ await editReady;+ const stamp = writeAtomPageState(engine, 'default', { ...item, identity }, 'complete').then(() => null, error => error);+ let observedLock = false;+ try {+ for (let attempt = 0; attempt < 100; attempt++) {+ const [row] = await engine.executeRaw<{ waiting: boolean }>(`SELECT EXISTS (+ SELECT 1 FROM pg_stat_activity WHERE datname=current_database() AND wait_event_type='Lock'+ AND query LIKE '%INSERT INTO extract_atoms_page_state%') AS waiting`);+ if (row.waiting) { observedLock = true; break; }+ await Bun.sleep(10);+ }+ } finally { release(); }+ await writer;+ expect(observedLock).toBe(true);+ expect((await stamp)?.message).toContain('page changed');+ expect(await engine.executeRaw('SELECT * FROM extract_atoms_page_state')).toEqual([]);+ });++ test('migration backfills matching valid markers only and never rewrites canonical pages', async () => {+ const hash = 'c'.repeat(64), scan = hash.slice(0, 16);+ await engine.executeRaw(`UPDATE pages SET content_hash=$1,+ frontmatter=frontmatter || jsonb_build_object('atoms_scan_hash',$2::text,'atoms_fail_hash',$2::text,'atoms_fail_count',3)+ WHERE slug=$3`, [hash, scan, slug]);+ await engine.putPage('meetings/stale-marker', { type: 'meeting', title: 'Stale marker', compiled_truth: body,+ content_hash: hash, frontmatter: { atoms_scan_hash: 'd'.repeat(16) } });+ await engine.putPage('meetings/invalid-marker', { type: 'meeting', title: 'Invalid marker', compiled_truth: body,+ content_hash: hash, frontmatter: { atoms_fail_hash: scan, atoms_fail_count: '3' } });+ const before = await engine.executeRaw('SELECT * FROM pages ORDER BY id');+ const migration = MIGRATIONS.find(m => m.name === 'derived_atom_page_scan_state')!;+ await engine.runMigration(migration.version, migration.sql);+ await engine.runMigration(migration.version, migration.sql);+ expect(await engine.executeRaw('SELECT * FROM pages ORDER BY id')).toEqual(before);+ expect(await engine.executeRaw('SELECT fail_count,tombstoned FROM extract_atoms_page_state'))+ .toEqual([{ fail_count: 3, tombstoned: true }]);+ expect(await countExtractAtomsBacklog(engine, 'default')).toBe(2);+ const prior = await snapshot();+ await engine.putPage(slug, { ...prior.page, content_hash: undefined, frontmatter: { preserve: { nested: true } } });+ const next = await snapshot();+ expect(next.page.content_hash).not.toBe(prior.page.content_hash);+ expect(await transferLegacyAtomPageState(engine, prior, next)).toBe(true);+ expect(await countExtractAtomsBacklog(engine, 'default')).toBe(2);+ });++ test('managed refusal precedes all provider calls', async () => {+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ let calls = 0;+ await expect(runPhaseExtractAtoms(engine, { _transcripts: [], _chat: async () => { calls++; return chat(); } }))+ .rejects.toThrow('Atom extraction cannot mutate a managed brain');+ expect(calls).toBe(0);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ });++ test.each(['atom', 'links', 'deleted-before-completion'])('partial %s writes retain pending receipts until every atom and edge persists', async failure => {+ const put = engine.putPage, addLinks = engine.addLinksBatch;+ let writes = 0;+ engine.putPage = async function (...args) {+ if (failure === 'atom' && args[1].type === 'atom' && ++writes === 2) throw new Error('synthetic atom failure');+ return put.apply(this, args);+ };+ engine.addLinksBatch = async function (...args) {+ if (failure === 'links') throw new Error('synthetic link failure');+ const result = await addLinks.apply(this, args);+ if (failure === 'deleted-before-completion') {+ await this.executeRaw("DELETE FROM pages WHERE source_id='default' AND slug=$1", [args[0][0].to_slug]);+ }+ return result;+ };+ const atomChat = async (): Promise<ChatResult> => ({ ...await chat(), text: JSON.stringify([+ { title: 'First parity insight', atom_type: 'insight', body: 'Synthetic first evidence.' },+ { title: 'Second parity insight', atom_type: 'insight', body: 'Synthetic second evidence.' },+ ]) });+ try {+ const result = await runPhaseExtractAtoms(engine, { _transcripts: [], _chat: atomChat });+ expect(result.status).toBe('warn');+ if (failure === 'deleted-before-completion') {+ expect(JSON.stringify(result.details.failures)).toContain('pending atoms remain retryable');+ }+ } finally { engine.putPage = put; engine.addLinksBatch = addLinks; }+ const pending = await engine.executeRaw<{ hash: string }>("SELECT frontmatter->>'source_hash' AS hash FROM pages WHERE type='atom'");+ expect(pending).toHaveLength(failure === 'links' ? 2 : 1);+ expect(pending.every(row => row.hash.startsWith('pending:'))).toBe(true);+ expect(await engine.executeRaw('SELECT 1 FROM extract_atoms_page_state WHERE tombstoned')).toEqual([]);+ expect(await countExtractAtomsBacklog(engine, 'default')).toBe(1);+ expect((await runPhaseExtractAtoms(engine, { _transcripts: [], _chat: atomChat })).status).toBe('ok');+ expect(await countExtractAtomsBacklog(engine, 'default')).toBe(0);+ expect((await engine.getLinks(slug)).filter(link => link.link_source === 'atom-provenance')).toHaveLength(2);+ });+});diff --git a/test/e2e/reconcile-crash-unactivated.test.ts b/test/e2e/reconcile-crash-unactivated.test.tsnew file mode 100644index 0000000000..45ce3e9451--- /dev/null+++ b/test/e2e/reconcile-crash-unactivated.test.ts@@ -0,0 +1,15 @@+import { expect, test } from 'bun:test';+import { CRASH_BOUNDARIES, runReconcileCrashCase } from '../fixtures/reconcile-crash-worker.ts';++const databaseUrl = process.env.DATABASE_URL;+const enabled = false;+for (const boundary of CRASH_BOUNDARIES) {+ test.skipIf(!databaseUrl)(`Postgres reconciliation survives SIGKILL/${boundary}, activation=${enabled}`, async () => {+ const result = await runReconcileCrashCase({ kind: 'postgres', boundary, enabled, databaseUrl });+ expect(result).toMatchObject({ status: 'passed', boundary, enabled, killed_signal: 'SIGKILL',+ committed_requests: 1, added_versions: 1, normal_apply_replay: true, originals_retained: true,+ receipt_unchanged: true, recovery_cleared: true, staging_cleaned: true, topology_unchanged: true, counters_conserved: true });+ if (boundary === 'staging_flushed') expect(result.flushed_before_rename_verified).toBe(true);+ if (boundary === 'after_response') expect(result.response_read_before_kill).toBe(true);+ }, 180_000);+}diff --git a/test/e2e/reconcile-crash.test.ts b/test/e2e/reconcile-crash.test.tsnew file mode 100644index 0000000000..7e0e7f85dc--- /dev/null+++ b/test/e2e/reconcile-crash.test.ts@@ -0,0 +1,15 @@+import { expect, test } from 'bun:test';+import { CRASH_BOUNDARIES, runReconcileCrashCase } from '../fixtures/reconcile-crash-worker.ts';++const databaseUrl = process.env.DATABASE_URL;+const enabled = true;+for (const boundary of CRASH_BOUNDARIES) {+ test.skipIf(!databaseUrl)(`Postgres reconciliation survives SIGKILL/${boundary}, activation=${enabled}`, async () => {+ const result = await runReconcileCrashCase({ kind: 'postgres', boundary, enabled, databaseUrl });+ expect(result).toMatchObject({ status: 'passed', boundary, enabled, killed_signal: 'SIGKILL',+ committed_requests: 1, added_versions: 1, normal_apply_replay: true, originals_retained: true,+ receipt_unchanged: true, recovery_cleared: true, staging_cleaned: true, topology_unchanged: true, counters_conserved: true });+ if (boundary === 'staging_flushed') expect(result.flushed_before_rename_verified).toBe(true);+ if (boundary === 'after_response') expect(result.response_read_before_kill).toBe(true);+ }, 180_000);+}diff --git a/test/e2e/reconcile-pgbouncer.test.ts b/test/e2e/reconcile-pgbouncer.test.tsnew file mode 100644index 0000000000..0aecaa7b9f--- /dev/null+++ b/test/e2e/reconcile-pgbouncer.test.ts@@ -0,0 +1,106 @@+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import postgres from 'postgres';+import { PostgresEngine } from '../../src/core/postgres-engine.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import { parseMarkdown, serializePageToMarkdown } from '../../src/core/markdown.ts';+import { parseFactsFence } from '../../src/core/facts-fence.ts';+import { operationsByName } from '../../src/core/operations.ts';+import type { OperationContext } from '../../src/core/ops/contract.ts';+import { claimWorktree } from '../../src/core/persistence/ownership.ts';+import { registerLocalWriter, withVerifiedLocalRegistration } from '../../src/core/persistence/identity.ts';+import { runReconcileApply, runReconcilePreview } from '../../src/core/persistence/reconcile.ts';+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';+import { withEnv } from '../helpers/with-env.ts';++const pooled = process.env.GBRAIN_PGBOUNCER_URL;+const direct = process.env.GBRAIN_PGBOUNCER_DIRECT_URL;+const available = Boolean(pooled && direct);+if (process.env.GBRAIN_CI_REQUIRE_PGBOUNCER === '1' && !available) throw new Error('Reconciliation requires the configured CI PgBouncer fixture.');+let home: string;+let database: string;+let admin: ReturnType<typeof postgres> | undefined;+let engine: PostgresEngine | undefined;++beforeAll(async () => {+ if (!available) return;+ assertSafeE2eDatabaseUrl(direct!);+ home = mkdtempSync(join(tmpdir(), 'gbrain-reconcile-pooled-'));+ database = `gbrain_test_reconcile_pool_${randomUUID().replaceAll('-', '')}`;+ admin = postgres(direct!, { max: 1, prepare: false });+ await admin.unsafe(`CREATE DATABASE ${database}`);+ const url = new URL(pooled!);+ url.pathname = `/${database}`;+ engine = new PostgresEngine();+ await withEnv({ GBRAIN_HOME: home }, async () => {+ await engine!.connect({ database_url: url.toString(), poolSize: 4 });+ await engine!.initSchema();+ });+}, 120_000);++afterAll(async () => {+ if (engine) {+ await withEnv({ GBRAIN_HOME: home }, async () => { await disposePersistenceConsumer(engine!); await engine!.disconnect(); });+ }+ if (admin) {+ try { if (database) await admin.unsafe(`DROP DATABASE IF EXISTS ${database} WITH (FORCE)`); }+ finally { await admin.end(); }+ }+ if (home) rmSync(home, { recursive: true, force: true });+});++for (const enabled of [false, true]) {+ test.skipIf(!available)(`transaction-pooled repair restores a private memory write with activation=${enabled}`, async () => {+ await withEnv({ GBRAIN_HOME: home, OPENAI_API_KEY: undefined, ANTHROPIC_API_KEY: undefined }, async () => {+ const db = engine!;+ await disposePersistenceConsumer(db);+ await db.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ const source = `pool-${randomUUID().slice(0, 8)}`;+ const root = join(home, source), slug = 'people/example';+ mkdirSync(join(root, 'people'), { recursive: true });+ await db.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [source, root]);+ await importFromContent(db, slug, '---\ntitle: Example\ntype: person\ndatabase_field: kept\n---\nSynthetic biography.\n',+ { sourceId: source, sourcePath: 'people/example.md', noEmbed: true, remote: false });+ const before = (await db.readPageSnapshot(slug, { sourceId: source }))!;+ const file = join(root, 'people/example.md');+ writeFileSync(file, serializePageToMarkdown({ ...before.page, frontmatter: { file_field: 'kept' } }, before.tags));+ const binding = await claimWorktree(db, source, root);+ const registration = await registerLocalWriter(db, 'cli');+ await db.executeRaw('UPDATE persistence_brain SET enabled=$1 WHERE singleton=1', [enabled]);+ await withVerifiedLocalRegistration(db, registration, async () => {+ const ctx: OperationContext = { engine: db, remote: false, sourceId: source, config: { engine: 'postgres' }, dryRun: false,+ logger: { info() {}, warn() {}, error() {} } };+ const fact = 'Prefers the synthetic morning review.', provenance = 'Synthetic operator conversation';+ const blockedId = randomUUID(), repairId = randomUUID(), memoryId = randomUUID();+ await expect(operationsByName.remember!.handler(ctx, { fact, provenance, entity: slug, visibility: 'private', request_id: blockedId }))+ .rejects.toMatchObject({ code: 'scope_denied', writeError: 'source_changed' });+ const { preview } = await runReconcilePreview(db, { source_id: source, slug });+ expect(preview.status).toBe('ready');+ const applied = await runReconcileApply(db, { source_id: source, slug, preview, request_id: repairId });+ expect(applied.state).toBe('committed');+ const saved = await operationsByName.remember!.handler(ctx, { fact, provenance, entity: slug, visibility: 'private', request_id: memoryId }) as Record<string, unknown>;+ expect(saved).toMatchObject({ status: 'inserted', state: 'committed', request_id: memoryId });+ const current = (await db.readPageSnapshot(slug, { sourceId: source }))!;+ expect(current.page.frontmatter).toMatchObject({ database_field: 'kept', file_field: 'kept' });+ expect(parseFactsFence(current.page.compiled_truth).facts).toEqual(expect.arrayContaining([+ expect.objectContaining({ claim: fact, visibility: 'private', source: provenance }),+ ]));+ expect(parseMarkdown(readFileSync(file, 'utf8'), slug).compiled_truth).toBe(current.page.compiled_truth);+ expect(await db.executeRaw('SELECT fact,visibility,source FROM facts WHERE id=$1 AND source_id=$2', [Number(saved.id), source]))+ .toEqual([{ fact, visibility: 'private', source: provenance }]);+ expect(await runReconcileApply(db, { source_id: source, slug, preview, request_id: repairId })).toEqual(applied);+ expect((await db.readPageSnapshot(slug, { sourceId: source }))?.revision).toBe(current.revision);+ expect(await db.executeRaw('SELECT owner_epoch::text AS epoch FROM persistence_worktrees WHERE id=$1::uuid', [binding.worktree_id]))+ .toEqual([{ epoch: String(binding.owner_epoch) }]);+ expect(await db.executeRaw('SELECT last_commit,last_sync_at FROM sources WHERE id=$1', [source]))+ .toEqual([{ last_commit: null, last_sync_at: null }]);+ expect(await db.executeRaw('SELECT enabled FROM persistence_brain WHERE singleton=1')).toEqual([{ enabled }]);+ });+ await disposePersistenceConsumer(db);+ });+ }, 120_000);+}diff --git a/test/extract-atoms-empty-array-rule.test.ts b/test/extract-atoms-empty-array-rule.test.tsindex c5f3ffaa0e..dc98950bcc 100644--- a/test/extract-atoms-empty-array-rule.test.ts+++ b/test/extract-atoms-empty-array-rule.test.ts@@ -16,7 +16,8 @@import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';import { PGLiteEngine } from '../src/core/pglite-engine.ts';-import { runPhaseExtractAtoms, parseAtomsOutcome } from '../src/core/cycle/extract-atoms.ts';+import { parseAtomsOutcome } from '../src/core/cycle/extract-atoms.ts';+import { runPhaseWithStoredPageFixtures as runPhaseExtractAtoms } from './helpers/extract-atoms-page-fixtures.ts';import { resetPgliteState } from './helpers/reset-pglite.ts';import type { ChatResult, ChatOpts } from '../src/core/ai/gateway.ts';diff --git a/test/extract-atoms-failure-classes.test.ts b/test/extract-atoms-failure-classes.test.tsindex 1a83715ce8..a26ffb65d2 100644--- a/test/extract-atoms-failure-classes.test.ts+++ b/test/extract-atoms-failure-classes.test.ts@@ -16,11 +16,11 @@import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import {- runPhaseExtractAtoms,discoverExtractablePages,parseAtomsOutcome,MAX_DETERMINISTIC_FAILURES,} from '../src/core/cycle/extract-atoms.ts';+import { runPhaseWithStoredPageFixtures as runPhaseExtractAtoms } from './helpers/extract-atoms-page-fixtures.ts';import { resetPgliteState } from './helpers/reset-pglite.ts';import type { ChatResult, ChatOpts } from '../src/core/ai/gateway.ts';@@ -74,6 +74,14 @@ async function frontmatterOf(slug: string): Promise<Record<string, unknown>> {return typeof fm === 'string' ? JSON.parse(fm) : fm;}+async function stateOf(slug: string) {+ const [row] = await engine.executeRaw<{ fail_count: number; content_hash: string; tombstoned: boolean }>(+ `SELECT scan.* FROM extract_atoms_page_state scan JOIN pages p ON p.id=scan.page_id+ JOIN sources s ON s.id=p.source_id AND s.incarnation=scan.source_incarnation+ WHERE p.source_id='default' AND p.slug=$1 AND scan.content_hash=p.content_hash`, [slug]);+ return row;+}+describe('parseAtomsOutcome — typed parse (gbrain#4148)', () => {test('malformed shapes are ok:false, never an empty success', () => {expect(parseAtomsOutcome('sorry, I cannot help with that')).toEqual({ ok: false, reason: 'no JSON array in response' });@@ -128,8 +136,11 @@ describe('runPhaseExtractAtoms — failure classes (gbrain#4148)', () => {expect(result.details.pages_processed).toBe(0);const fm = await frontmatterOf('note/m1');expect(fm.atoms_scan_hash).toBeUndefined(); // the pre-fix bug: this was stamped- expect(Number(fm.atoms_fail_count)).toBe(1);- expect(fm.atoms_fail_hash).toBe(HASH_A);+ expect(fm.atoms_fail_count).toBeUndefined();+ expect(fm.atoms_fail_hash).toBeUndefined();+ expect((await stateOf('note/m1'))?.fail_count).toBe(1);+ expect((await stateOf('note/m1'))?.content_hash).toBe(HASH_A);+ expect((await stateOf('note/m1'))?.tombstoned).toBe(false);});test(`tombstones only after ${MAX_DETERMINISTIC_FAILURES} consecutive same-content malformed failures`, async () => {@@ -144,14 +155,18 @@ describe('runPhaseExtractAtoms — failure classes (gbrain#4148)', () => {const r = await runPhaseExtractAtoms(engine, opts);expect(r.details.tombstoned_for_failures).toEqual([]);const fm = await frontmatterOf('note/m2');- expect(Number(fm.atoms_fail_count)).toBe(i);+ expect((await stateOf('note/m2'))?.fail_count).toBe(i);+ expect((await stateOf('note/m2'))?.tombstoned).toBe(false);+ expect(fm.atoms_fail_count).toBeUndefined();expect(fm.atoms_scan_hash).toBeUndefined();}const final = await runPhaseExtractAtoms(engine, opts);expect(final.details.tombstoned_for_failures).toEqual(['note/m2']);const fm = await frontmatterOf('note/m2');- expect(Number(fm.atoms_fail_count)).toBe(MAX_DETERMINISTIC_FAILURES);- expect(fm.atoms_scan_hash).toBe(HASH_A); // backlog floor clears+ expect((await stateOf('note/m2'))?.fail_count).toBe(MAX_DETERMINISTIC_FAILURES);+ expect((await stateOf('note/m2'))?.content_hash).toBe(HASH_A);+ expect((await stateOf('note/m2'))?.tombstoned).toBe(true);+ expect(fm.atoms_scan_hash).toBeUndefined();});test('a content edit resets the failure streak (count is hash-keyed)', async () => {@@ -164,11 +179,13 @@ describe('runPhaseExtractAtoms — failure classes (gbrain#4148)', () => {});await runPhaseExtractAtoms(engine, mk(HASH_A));await runPhaseExtractAtoms(engine, mk(HASH_A));- expect(Number((await frontmatterOf('note/m3')).atoms_fail_count)).toBe(2);+ expect((await stateOf('note/m3'))?.fail_count).toBe(2);await runPhaseExtractAtoms(engine, mk('b'.repeat(16))); // edited contentconst fm = await frontmatterOf('note/m3');- expect(Number(fm.atoms_fail_count)).toBe(1);- expect(fm.atoms_fail_hash).toBe('b'.repeat(16));+ expect((await stateOf('note/m3'))?.fail_count).toBe(1);+ expect((await stateOf('note/m3'))?.content_hash).toBe('b'.repeat(16));+ expect(fm.atoms_fail_count).toBeUndefined();+ expect(fm.atoms_fail_hash).toBeUndefined();});test('transient provider errors are retryable: no count, no tombstone', async () => {@@ -184,6 +201,7 @@ describe('runPhaseExtractAtoms — failure classes (gbrain#4148)', () => {const fm = await frontmatterOf('note/t1');expect(fm.atoms_fail_count).toBeUndefined();expect(fm.atoms_scan_hash).toBeUndefined();+ expect(await stateOf('note/t1')).toBeUndefined();});});@@ -220,6 +238,7 @@ describe('runPhaseExtractAtoms — global-error halt (#3044)', () => {const fm = await frontmatterOf(slug);expect(fm.atoms_fail_count).toBeUndefined();expect(fm.atoms_scan_hash).toBeUndefined();+ expect(await stateOf(slug)).toBeUndefined();}});@@ -242,6 +261,7 @@ describe('runPhaseExtractAtoms — global-error halt (#3044)', () => {expect(failures[2].error).toContain('3 consecutive rate_limit errors');for (const slug of ['note/r1', 'note/r2', 'note/r3', 'note/r4']) {expect((await frontmatterOf(slug)).atoms_fail_count).toBeUndefined();+ expect(await stateOf(slug)).toBeUndefined();}});@@ -377,7 +397,9 @@ describe('runPhaseExtractAtoms — completion receipt (gbrain#4148)', () => {const afm = typeof atoms[0].frontmatter === 'string' ? JSON.parse(atoms[0].frontmatter) : atoms[0].frontmatter;expect(afm.source_hash).toBe(HASH_A); // flipped, not pending:expect(String(afm.source_hash)).not.toContain('pending');- expect((await frontmatterOf('note/ok1')).atoms_scan_hash).toBe(HASH_A);+ expect((await stateOf('note/ok1'))?.content_hash).toBe(HASH_A);+ expect((await stateOf('note/ok1'))?.tombstoned).toBe(true);+ expect((await frontmatterOf('note/ok1')).atoms_scan_hash).toBeUndefined();});test('a pending (partial-persist) atom row does NOT mark the source page done for discovery', async () => {diff --git a/test/extract-atoms-page-discovery.test.ts b/test/extract-atoms-page-discovery.test.tsindex 0a144c65c9..55738b2ec1 100644--- a/test/extract-atoms-page-discovery.test.ts+++ b/test/extract-atoms-page-discovery.test.ts@@ -18,9 +18,9 @@ import { tmpdir } from 'node:os';import { join } from 'node:path';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import {- runPhaseExtractAtoms,discoverExtractablePages,} from '../src/core/cycle/extract-atoms.ts';+import { runPhaseWithStoredPageFixtures as runPhaseExtractAtoms } from './helpers/extract-atoms-page-fixtures.ts';import { resetPgliteState } from './helpers/reset-pglite.ts';import type { ChatOpts, ChatResult } from '../src/core/ai/gateway.ts';@@ -547,12 +547,12 @@ describe('#2144: zero-yield tombstone', () => {expect(result.details?.pages_processed).toBe(1);expect(result.details?.atoms_extracted).toBe(0);- // Stamp landed: atoms_scan_hash = first 16 chars of the page's content_hash.const rows = await engine.executeRaw<{ scan: string; ch: string }>(- `SELECT frontmatter->>'atoms_scan_hash' AS scan, content_hash AS ch- FROM pages WHERE slug = 'article/zero-yield'`,+ `SELECT scan.content_hash AS scan, p.content_hash AS ch+ FROM pages p JOIN extract_atoms_page_state scan ON scan.page_id=p.id+ WHERE p.slug = 'article/zero-yield' AND scan.tombstoned`,);- expect(rows[0].scan).toBe(rows[0].ch.slice(0, 16));+ expect(rows[0].scan).toBe(rows[0].ch);// No longer rediscovered.const discovered = await discoverExtractablePages(engine, 'default');@@ -578,7 +578,8 @@ describe('#2144: zero-yield tombstone', () => {const failingChat = async (_o: ChatOpts): Promise<ChatResult> => { throw new Error('rate limit'); };await runPhaseExtractAtoms(engine, { _transcripts: [], _chat: failingChat as never });const rows = await engine.executeRaw<{ scan: string | null }>(- `SELECT frontmatter->>'atoms_scan_hash' AS scan FROM pages WHERE slug = 'article/transient-failure'`,+ `SELECT scan.content_hash AS scan FROM pages p LEFT JOIN extract_atoms_page_state scan ON scan.page_id=p.id+ WHERE p.slug = 'article/transient-failure'`,);expect(rows[0].scan).toBeNull();const discovered = await discoverExtractablePages(engine, 'default');@@ -643,7 +644,7 @@ describe('local extract-atoms config knobs — invalid-value fallbacks', () => {sql: string,params?: unknown[],) {- if (sql.includes('atoms_scan_hash') && sql.includes('LIMIT $4')) {+ if (sql.includes('extract_atoms_page_state') && sql.includes('LIMIT $4')) {limitParam = Number((params ?? [])[3]);}return realExecute.call(this, sql as never, params as never);diff --git a/test/extract-atoms-page-state.test.ts b/test/extract-atoms-page-state.test.tsnew file mode 100644index 0000000000..69c326859a--- /dev/null+++ b/test/extract-atoms-page-state.test.ts@@ -0,0 +1,252 @@+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 { discoverExtractablePages, countExtractAtomsBacklog, runPhaseExtractAtoms } from '../src/core/cycle/extract-atoms.ts';+import { matchingLegacyAtomPageState, transferLegacyAtomPageState } from '../src/core/cycle/extract-atoms-page-state.ts';+import { MIGRATIONS } from '../src/core/migrate.ts';+import type { ChatResult } from '../src/core/ai/gateway.ts';++let engine: PGLiteEngine;+beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 60000);+afterAll(async () => { await engine.disconnect(); });+beforeEach(async () => { await resetPgliteState(engine); });++const body = 'Evidence about a synthetic example and its repeatable outcomes. '.repeat(20);+const slug = 'meetings/example';+const response = (text: string): ChatResult => ({ text, blocks: [{ type: 'text', text }], stopReason: 'end',+ usage: { input_tokens: 10, output_tokens: 10, cache_read_tokens: 0, cache_creation_tokens: 0 },+ model: 'anthropic:claude-haiku-4-5', providerId: 'anthropic' });+const atoms = JSON.stringify([+ { title: 'First synthetic atom', atom_type: 'insight', body: 'First evidence.' },+ { title: 'Second synthetic atom', atom_type: 'insight', body: 'Second evidence.' },+]);+async function seed(sourceId = 'default') {+ await engine.putPage(slug, { type: 'meeting', title: 'Example', compiled_truth: body, timeline: '', frontmatter: { custom: { keep: true } } }, { sourceId });+}+async function rows() {+ return engine.executeRaw<{ page_id: number; content_hash: string; fail_count: number; tombstoned: boolean }>('SELECT * FROM extract_atoms_page_state');+}+async function snapshot() {+ return (await engine.readPageSnapshot(slug, { sourceId: 'default' }))!;+}+async function scan(text: string) {+ return runPhaseExtractAtoms(engine, { _transcripts: [], _chat: async () => response(text) });+}++describe('derived atom page state', () => {+ test('zero-yield bookkeeping never changes canonical frontmatter, revision, hash, or versions', async () => {+ await seed();+ const before = await snapshot();+ const versions = await engine.executeRaw('SELECT * FROM page_versions');+ expect((await scan('[]')).status).toBe('ok');+ expect(await snapshot()).toEqual(before);+ expect(await engine.executeRaw('SELECT * FROM page_versions')).toEqual(versions);+ expect(await rows()).toEqual([expect.objectContaining({ page_id: before.page.id, content_hash: before.page.content_hash, fail_count: 0, tombstoned: true })]);+ expect(await discoverExtractablePages(engine, 'default')).toEqual([]);+ expect(await countExtractAtomsBacklog(engine, 'default')).toBe(0);+ expect(await countExtractAtomsBacklog(engine)).toBe(0);+ });++ test('malformed output counts to three without canonical mutation; transient failures do not count', async () => {+ await seed();+ const before = await snapshot();+ await runPhaseExtractAtoms(engine, { _transcripts: [], _chat: async () => { throw new Error('503 timeout'); } });+ expect(await rows()).toEqual([]);+ for (let count = 1; count <= 3; count++) {+ const result = await scan('not an array');+ expect(result.status).toBe('warn');+ expect(await rows()).toEqual([expect.objectContaining({ fail_count: count, tombstoned: count === 3 })]);+ expect(await snapshot()).toEqual(before);+ expect(await countExtractAtomsBacklog(engine, 'default')).toBe(count === 3 ? 0 : 1);+ }+ });++ test('edited, soft-deleted, and physically recreated pages never inherit a tombstone', async () => {+ await seed();+ await scan('[]');+ await engine.putPage(slug, { ...(await snapshot()).page, content_hash: undefined, compiled_truth: body + 'Edited.' }, { sourceId: 'default' });+ expect(await countExtractAtomsBacklog(engine, 'default')).toBe(1);+ await scan('[]');+ await engine.executeRaw('UPDATE pages SET deleted_at=now() WHERE slug=$1', [slug]);+ expect(await rows()).toEqual([]);+ await engine.executeRaw('UPDATE pages SET deleted_at=NULL WHERE slug=$1', [slug]);+ expect(await countExtractAtomsBacklog(engine, 'default')).toBe(1);+ await scan('[]');+ const oldId = (await snapshot()).page.id;+ await engine.executeRaw('DELETE FROM pages WHERE slug=$1', [slug]);+ await seed();+ expect((await snapshot()).page.id).not.toBe(oldId);+ expect(await countExtractAtomsBacklog(engine, 'default')).toBe(1);+ });++ test('source recreation and same-slug pages in another source never inherit state', async () => {+ await engine.executeRaw("INSERT INTO sources(id,name) VALUES ('example','Example')");+ await seed('example');+ await runPhaseExtractAtoms(engine, { sourceId: 'example', _transcripts: [], _chat: async () => response('[]') });+ await seed();+ expect(await countExtractAtomsBacklog(engine, 'default')).toBe(1);+ await engine.executeRaw("DELETE FROM sources WHERE id='example'");+ await engine.executeRaw("INSERT INTO sources(id,name) VALUES ('example','Example')");+ await seed('example');+ expect(await countExtractAtomsBacklog(engine, 'example')).toBe(1);+ });++ test.each(['[]', atoms])('a page edited during the provider call cannot complete stale extraction: %s', async text => {+ await seed();+ const result = await runPhaseExtractAtoms(engine, { _transcripts: [], _chat: async () => {+ await engine.putPage(slug, { ...(await snapshot()).page, content_hash: undefined, compiled_truth: body + 'Concurrent edit.' }, { sourceId: 'default' });+ return response(text);+ } });+ expect(result.status).toBe('warn');+ expect(JSON.stringify(result.details.failures)).toContain('changed');+ expect(await rows()).toEqual([]);+ expect(await countExtractAtomsBacklog(engine, 'default')).toBe(1);+ const receipts = await engine.executeRaw<{ hash: string }>("SELECT frontmatter->>'source_hash' AS hash FROM pages WHERE type='atom'");+ expect(receipts.every(row => row.hash.startsWith('pending:'))).toBe(true);+ });++ test.each(['[]', atoms])('a page recreated during the provider call cannot complete stale extraction: %s', async text => {+ await seed();+ const result = await runPhaseExtractAtoms(engine, { _transcripts: [], _chat: async () => {+ await engine.executeRaw('DELETE FROM pages WHERE slug=$1', [slug]);+ await seed();+ return response(text);+ } });+ expect(result.status).toBe('warn');+ expect(await rows()).toEqual([]);+ expect(await countExtractAtomsBacklog(engine, 'default')).toBe(1);+ const receipts = await engine.executeRaw<{ hash: string }>("SELECT frontmatter->>'source_hash' AS hash FROM pages WHERE type='atom'");+ expect(receipts.every(row => row.hash.startsWith('pending:'))).toBe(true);+ });++ test.each([+ ['42501', 'check database permissions'],+ ['42P01', 'check schema migrations'],+ ['private-code-sentinel', 'check database access'],+ ])('state write failures stay visible without private error payloads: %s', async (code, guidance) => {+ await seed();+ const execute = engine.executeRaw;+ const messages: string[] = [];+ const log = console.error;+ console.error = (...args: unknown[]) => { messages.push(args.map(String).join(' ')); };+ engine.executeRaw = (async (sql: string, params?: unknown[]) => {+ if (sql.includes('INSERT INTO extract_atoms_page_state')) throw Object.assign(new Error('private-payload-sentinel SQL parameter dump'), { code });+ return execute.call(engine, sql, params);+ }) as typeof execute;+ try {+ const result = await scan('[]');+ expect(result.status).toBe('warn');+ expect(JSON.stringify(result.details.failures)).toContain(guidance);+ expect(JSON.stringify(result.details.failures)).toContain('remains retryable');+ expect(JSON.stringify(result.details.failures)).not.toContain('private-payload-sentinel');+ expect(JSON.stringify(result.details.failures)).not.toContain('private-code-sentinel');+ expect(messages.join('\n')).not.toContain('private-payload-sentinel');+ expect(messages.join('\n')).not.toContain('private-code-sentinel');+ expect(messages.join('\n')).toContain(guidance);+ } finally { engine.executeRaw = execute; console.error = log; }+ expect(await countExtractAtomsBacklog(engine, 'default')).toBe(1);+ });++ test('managed atom extraction refuses before any provider call, including dry runs', async () => {+ await seed();+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ let calls = 0;+ for (const dryRun of [false, true]) {+ await expect(runPhaseExtractAtoms(engine, { dryRun, _transcripts: [], _chat: async () => {+ calls++; return response(atoms);+ } })).rejects.toThrow('Atom extraction cannot mutate a managed brain');+ }+ expect(calls).toBe(0);+ expect(await rows()).toEqual([]);+ });++ test.each(['atom', 'links', 'deleted-before-completion'])('partial %s publication never finalizes source_hash or scan state', async failure => {+ await seed();+ const put = engine.putPage, links = engine.addLinksBatch;+ let writes = 0;+ engine.putPage = (async function (this: PGLiteEngine, ...args: Parameters<typeof put>) {+ if (failure === 'atom' && args[1].type === 'atom' && ++writes === 2) throw new Error('synthetic second atom failure');+ return put.apply(this, args);+ }) as typeof put;+ engine.addLinksBatch = async (...args) => {+ if (failure === 'links') throw new Error('synthetic provenance failure');+ const result = await links.apply(engine, args);+ if (failure === 'deleted-before-completion') {+ await engine.executeRaw("DELETE FROM pages WHERE source_id='default' AND slug=$1", [args[0][0].to_slug]);+ }+ return result;+ };+ try {+ const result = await scan(atoms);+ expect(result.status).toBe('warn');+ if (failure === 'deleted-before-completion') {+ expect(JSON.stringify(result.details.failures)).toContain('pending atoms remain retryable');+ }+ }+ finally { engine.putPage = put; engine.addLinksBatch = links; }+ const pending = await engine.executeRaw<{ hash: string }>("SELECT frontmatter->>'source_hash' AS hash FROM pages WHERE type='atom'");+ expect(pending).toHaveLength(failure === 'links' ? 2 : 1);+ expect(pending.every(row => row.hash.startsWith('pending:'))).toBe(true);+ expect((await rows()).every(row => !row.tombstoned)).toBe(true);+ expect(await countExtractAtomsBacklog(engine, 'default')).toBe(1);+ expect((await scan(atoms)).status).toBe('ok');+ const complete = await engine.executeRaw<{ hash: string }>("SELECT frontmatter->>'source_hash' AS hash FROM pages WHERE type='atom'");+ expect(complete).toHaveLength(2);+ expect(complete.every(row => row.hash === (pending[0].hash.slice('pending:'.length)))).toBe(true);+ expect((await engine.getLinks(slug)).filter(link => link.link_source === 'atom-provenance')).toHaveLength(2);+ expect(await countExtractAtomsBacklog(engine, 'default')).toBe(0);+ });+});++describe('legacy atom state migration and reviewed cleanup', () => {+ test('migration copies only well-formed matching markers, preserving canonical data and revision', async () => {+ const hash = 'a'.repeat(64), stale = 'b'.repeat(16);+ const markers = [+ { atoms_scan_hash: hash.slice(0, 16) },+ { atoms_fail_hash: hash.slice(0, 16), atoms_fail_count: 2 },+ { atoms_scan_hash: stale },+ { atoms_fail_hash: hash.slice(0, 16), atoms_fail_count: '2' },+ { atoms_fail_hash: hash.slice(0, 16), atoms_fail_count: 1.5 },+ { atoms_scan_hash: hash.slice(0, 16), atoms_fail_hash: stale, atoms_fail_count: 3 },+ { atoms_scan_hash: hash.slice(0, 16), atoms_fail_count: 3 },+ { atoms_scan_hash: null },+ { atoms_fail_hash: hash.slice(0, 16), atoms_fail_count: 2147483648 },+ ];+ for (let i = 0; i < markers.length; i++) {+ await engine.putPage(`meetings/legacy-${i}`, { type: 'meeting', title: 'Legacy example', compiled_truth: body, frontmatter: markers[i] });+ }+ await engine.executeRaw('UPDATE pages SET content_hash=$1', [hash]);+ const before = await engine.executeRaw('SELECT * FROM pages ORDER BY id');+ const migration = MIGRATIONS.find(m => m.name === 'derived_atom_page_scan_state')!;+ await engine.runMigration(migration.version, migration.sql);+ await engine.runMigration(migration.version, migration.sql);+ expect(await engine.executeRaw('SELECT * FROM pages ORDER BY id')).toEqual(before);+ expect(await rows()).toHaveLength(2);+ expect((await rows()).map(row => [row.fail_count, row.tombstoned]).sort()).toEqual([[0, true], [2, false]]);+ for (let i = 0; i < markers.length; i++) expect(matchingLegacyAtomPageState(markers[i], hash) !== null).toBe(i < 2);+ });++ test('reviewed cleanup carries state to a changed hash only for identical canonical input', async () => {+ await seed();+ const hash = 'd'.repeat(64);+ await engine.executeRaw(`UPDATE pages SET frontmatter=frontmatter || jsonb_build_object(+ 'atoms_scan_hash',$1::text,'atoms_fail_hash',$1::text,'atoms_fail_count',3), content_hash=$3 WHERE slug=$2`, [hash.slice(0, 16), slug, hash]);+ const before = await snapshot();+ const clean = { ...before.page.frontmatter };+ delete clean.atoms_scan_hash; delete clean.atoms_fail_hash; delete clean.atoms_fail_count;+ await engine.putPage(slug, { ...before.page, content_hash: undefined, frontmatter: clean });+ const after = await snapshot();+ expect(after.page.content_hash).not.toBe(before.page.content_hash);+ expect(await transferLegacyAtomPageState(engine, before, after)).toBe(true);+ expect(await countExtractAtomsBacklog(engine, 'default')).toBe(0);+ await engine.executeRaw('DELETE FROM extract_atoms_page_state');+ await engine.putPage(slug, { ...after.page, content_hash: undefined, compiled_truth: body + 'Real edit.' });+ expect(await transferLegacyAtomPageState(engine, before, await snapshot())).toBe(false);+ expect(await countExtractAtomsBacklog(engine, 'default')).toBe(1);+ expect(await transferLegacyAtomPageState(engine, before, after)).toBe(false);+ });+});diff --git a/test/extract-atoms-provenance-links.test.ts b/test/extract-atoms-provenance-links.test.tsindex c11f41b913..6ff89d56dc 100644--- a/test/extract-atoms-provenance-links.test.ts+++ b/test/extract-atoms-provenance-links.test.ts@@ -24,7 +24,7 @@import { describe, test, expect, beforeAll, afterAll } from 'bun:test';import { createHash } from 'crypto';import { PGLiteEngine } from '../src/core/pglite-engine.ts';-import { runPhaseExtractAtoms } from '../src/core/cycle/extract-atoms.ts';+import { runPhaseWithStoredPageFixtures as runPhaseExtractAtoms } from './helpers/extract-atoms-page-fixtures.ts';import type { ChatResult, ChatOpts } from '../src/core/ai/gateway.ts';let engine: PGLiteEngine;diff --git a/test/fixtures/reconcile-crash-worker.ts b/test/fixtures/reconcile-crash-worker.tsnew file mode 100644index 0000000000..15e6d51c98--- /dev/null+++ b/test/fixtures/reconcile-crash-worker.ts@@ -0,0 +1,372 @@+import assert from 'node:assert/strict';+import { randomUUID } from 'node:crypto';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync, writeSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';+import postgres from 'postgres';+import { CRASH_BOUNDARIES, childEnvironment } from '../../scripts/persistence/validate.ts';+import { assertConservation } from '../../scripts/persistence/harness.ts';+import { configDir, type GBrainConfig } from '../../src/core/config.ts';+import type { BrainEngine } from '../../src/core/engine.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import { parseMarkdown, serializePageToMarkdown } from '../../src/core/markdown.ts';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { PostgresEngine } from '../../src/core/postgres-engine.ts';+import { publishMutation } from '../../src/core/persistence/coordinator.ts';+import { digest, sha256, stableJson } from '../../src/core/persistence/digest.ts';+import { localHostId, readLocalWriter, registerLocalWriter, withVerifiedLocalRegistration } from '../../src/core/persistence/identity.ts';+import { claimNextWrite, getWriteRequest, receiptFor } from '../../src/core/persistence/journal.ts';+import { acquireWorktree, claimWorktree, getWorktreeBinding } from '../../src/core/persistence/ownership.ts';+import { prepareReconcileMutation } from '../../src/core/persistence/reconcile-prepare.ts';+import { reconcileCanonical } from '../../src/core/persistence/reconcile-merge.ts';+import { runReconcileApply, runReconcilePreview, type ReconcileArtifact } from '../../src/core/persistence/reconcile.ts';+import { disposePersistenceConsumer, startPersistenceConsumer } from '../../src/core/persistence/service.ts';+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';++export { CRASH_BOUNDARIES };+type Boundary = typeof CRASH_BOUNDARIES[number];+interface CaseOptions { kind: 'pglite' | 'postgres'; boundary: Boundary; enabled: boolean; databaseUrl?: string; }+interface WorkerConfig extends CaseOptions { root: string; dataDir: string; requestId: string; }+interface WorkerEvent { event: string; boundary?: Boundary; request_id?: string; row_id?: string; url?: string; result?: Record<string, unknown>; message?: string; }+interface ReplayFixture {+ params: { source_id: string; slug: string; preview: ReconcileArtifact; request_id: string };+ rowId: string; backupReference: string; backupHash: string; versions: number; binding: unknown; source: unknown;+}+const sourceId = 'reconcile-crash-test';+const slug = 'notes/example';+const emit = (event: WorkerEvent) => process.stdout.write(`${JSON.stringify(event)}\n`);+const hold = () => { setInterval(() => {}, 1000); return new Promise<never>(() => {}); };++function stopSynchronously(event: WorkerEvent): never {+ const bytes = Buffer.from(`${JSON.stringify(event)}\n`);+ let offset = 0;+ while (offset < bytes.length) {+ const written = writeSync(1, bytes, offset, bytes.length - offset);+ assert(written > 0);+ offset += written;+ }+ const blocked = new Int32Array(new SharedArrayBuffer(4));+ for (;;) Atomics.wait(blocked, 0, 0);+}++function engineConfig(config: WorkerConfig): GBrainConfig {+ return config.kind === 'pglite' ? { engine: 'pglite', database_path: config.dataDir }+ : { engine: 'postgres', database_url: config.databaseUrl };+}++async function openEngine(config: WorkerConfig, initialize: boolean): Promise<BrainEngine> {+ const engine = config.kind === 'pglite' ? new PGLiteEngine() : new PostgresEngine();+ if (config.kind === 'postgres') assertSafeE2eDatabaseUrl(config.databaseUrl!);+ await engine.connect(config.kind === 'pglite' ? { database_path: config.dataDir } : { database_url: config.databaseUrl!, poolSize: 4 });+ if (initialize) await engine.initSchema();+ return engine;+}++async function versionCount(engine: BrainEngine): Promise<number> {+ const [row] = await engine.executeRaw<{ count: string }>(`SELECT COUNT(*)::text AS count FROM page_versions v+ JOIN pages p ON p.id=v.page_id WHERE p.source_id=$1 AND p.slug=$2`, [sourceId, slug]);+ return Number(row.count);+}++async function sourceState(engine: BrainEngine): Promise<unknown> {+ const [row] = await engine.executeRaw('SELECT incarnation,last_commit,last_sync_at,config FROM sources WHERE id=$1', [sourceId]);+ return JSON.parse(stableJson(row));+}++async function crash(config: WorkerConfig): Promise<never> {+ const engine = await openEngine(config, true);+ const root = join(config.root, 'source');+ mkdirSync(join(root, 'notes'), { recursive: true });+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);+ await importFromContent(engine, slug, '---\ntype: note\ntitle: Example\ncustom_database: retained\nprofile:\n role: example-role\n---\nA durable synthetic observation.\n',+ { sourceId, sourcePath: 'notes/example.md', noEmbed: true });+ const snapshot = await engine.readPageSnapshot(slug, { sourceId });+ assert(snapshot);+ const file = join(root, `${slug}.md`);+ writeFileSync(file, serializePageToMarkdown({ ...snapshot.page,+ frontmatter: { custom_file: 'retained', profile: { location: 'example-place' } } }, snapshot.tags));+ const binding = await claimWorktree(engine, sourceId, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=$1 WHERE singleton=1', [config.enabled]);+ const registration = await registerLocalWriter(engine, 'cli');+ return withVerifiedLocalRegistration(engine, registration, async () => {+ const { preview } = await runReconcilePreview(engine, { source_id: sourceId, slug });+ assert.equal(preview.status, 'ready');+ assert.deepEqual(preview.result.frontmatter.profile, { location: 'example-place', role: 'example-role' });+ const params = { source_id: sourceId, slug, preview, request_id: config.requestId };+ const holder = await acquireWorktree(binding);+ assert(holder, 'fixture must hold the actual native worktree lock before admission');+ try {+ await assert.rejects(runReconcileApply(engine, params), (error: unknown) => {+ const pending = error as { code?: string; writeRequest?: { request_id: string; state: string } };+ assert.equal(pending.code, 'write_pending');+ assert.equal(pending.writeRequest?.request_id, config.requestId);+ assert(['queued', 'running'].includes(pending.writeRequest!.state));+ return true;+ });+ await disposePersistenceConsumer(engine);+ assert.equal((await engine.readPageSnapshot(slug, { sourceId }))!.revision, snapshot.revision);+ assert.equal(readFileSync(file).toString('base64'), preview.preimages.file_base64);+ } finally { await holder.release(); }+ const row = await getWriteRequest(engine, { kind: 'local_cli', id: registration.id }, config.requestId);+ assert(row);+ assert.equal(row.state, 'queued');+ assert.equal(row.recovery, null);+ const backupReference = String(row.intent!.backup_reference);+ const fixture: ReplayFixture = { params, rowId: row.id, backupReference,+ backupHash: sha256(readFileSync(join(configDir(), 'reconciliation-previews', backupReference))),+ versions: await versionCount(engine), binding, source: await sourceState(engine) };+ writeFileSync(join(config.root, 'replay.json'), stableJson(fixture), { mode: 0o600 });+ const event: WorkerEvent = { event: 'boundary', boundary: config.boundary, row_id: row.id, request_id: config.requestId };+ const stop = async () => { emit(event); await hold(); };+ if (config.boundary === 'admitted') { await stop(); throw new Error('unreachable'); }+ const claimed = await claimNextWrite(engine, localHostId());+ assert.equal(claimed?.id, row.id);+ const prepared = await prepareReconcileMutation(engine, claimed!, engineConfig(config));+ const committed = await publishMutation(engine, claimed!, prepared, localHostId(), {+ boundary: async boundary => { if (boundary === config.boundary) await stop(); },+ stagingFlushed: () => { if (config.boundary === 'staging_flushed') stopSynchronously(event); },+ });+ if (config.boundary === 'after_response') {+ assert.equal(committed.state, 'committed');+ const receipt = await runReconcileApply(engine, params);+ const server = Bun.serve({ hostname: '127.0.0.1', port: 0, fetch: () => Response.json(receipt) });+ emit({ ...event, event: 'response_ready', url: server.url.toString() });+ await hold();+ }+ throw new Error(`Boundary ${config.boundary} was not reached: ${committed.state}/${committed.error_code}`);+ });+}++async function recover(config: WorkerConfig): Promise<Record<string, unknown>> {+ const engine = await openEngine(config, false);+ try {+ const fixture: ReplayFixture = JSON.parse(readFileSync(join(config.root, 'replay.json'), 'utf8'));+ const { params } = fixture;+ const registration = await readLocalWriter(engine, 'cli');+ return await withVerifiedLocalRegistration(engine, registration, async () => {+ const row = await getWriteRequest(engine, { kind: 'local_cli', id: registration.id }, config.requestId);+ assert(row, 'acknowledged reconciliation request must survive SIGKILL');+ assert.equal(row.id, fixture.rowId);+ assert.equal(row.intent?.kind, 'canonical_reconcile');+ const file = join(config.root, 'source', `${slug}.md`);+ const original = Buffer.from(params.preview.preimages.file_base64, 'base64');+ const reviewed = serializePageToMarkdown({ ...params.preview.preimages.database.page, ...params.preview.result }, params.preview.result.tags);+ const committedBoundary = ['after_commit', 'after_response'].includes(config.boundary);+ const publishedBoundary = committedBoundary || ['after_publication', 'before_commit'].includes(config.boundary);+ assert.equal(readFileSync(file, 'utf8'), publishedBoundary ? reviewed : original.toString('utf8'));+ const initialSnapshot = (await engine.readPageSnapshot(slug, { sourceId }))!;+ assert(initialSnapshot);+ assert.equal(row.state, committedBoundary ? 'committed' : config.boundary === 'admitted' ? 'queued' : 'running');+ assert.deepEqual(reconcileCanonical(initialSnapshot.page, initialSnapshot.tags), committedBoundary ? params.preview.result+ : reconcileCanonical(params.preview.preimages.database.page, params.preview.preimages.database.tags));+ if (!committedBoundary) assert.equal(initialSnapshot.revision, params.preview.preimages.database.revision);+ const stage = row.recovery?.staging?.publication;+ if (config.boundary === 'staging_flushed') {+ assert(stage, 'flushed staging path must have a durable recovery record');+ assert.equal(readFileSync(stage.path, 'utf8'), reviewed);+ assert.deepEqual(readFileSync(file), original, 'stagingFlushed must stop synchronously before rename');+ }+ if (config.boundary === 'admitted' || config.boundary === 'after_response') assert.equal(row.recovery, null);+ else assert(row.recovery, 'interrupted publication must retain its recovery record');+ await assertConservation(engine);+ startPersistenceConsumer(engine, engineConfig(config));+ let receipt: Record<string, unknown> | undefined;+ const deadline = Date.now() + 30_000;+ while (!receipt && Date.now() < deadline) {+ try { receipt = await runReconcileApply(engine, params); }+ catch (error) { if ((error as { code?: string }).code !== 'write_pending') throw error; }+ }+ assert(receipt, 'same-ID normal apply must complete after restart');+ assert.equal(receipt.state, 'committed');+ assert.equal(receipt.request_id, config.requestId);+ assert.equal((receipt.persistence as Record<string, unknown>).mode, 'filesystem');+ assert.equal((receipt.persistence as Record<string, unknown>).file_written, true);+ assert.equal((receipt.outcome as Record<string, unknown>).result_digest, params.preview.result_digest);+ assert.equal((receipt.outcome as Record<string, unknown>).backup_reference, fixture.backupReference);+ assert.equal((receipt.outcome as Record<string, unknown>).database_changed, true);+ assert.equal((receipt.outcome as Record<string, unknown>).file_changed, true);+ if (committedBoundary) assert.deepEqual(receipt.write_request, receiptFor(row));+ if (config.boundary === 'after_response') {+ assert.deepEqual(receipt, JSON.parse(readFileSync(join(config.root, 'received.json'), 'utf8')));+ }+ const cleanupDeadline = Date.now() + 5000;+ while (Date.now() < cleanupDeadline) {+ const unresolved = await engine.executeRaw('SELECT 1 FROM persistence_requests WHERE recovery IS NOT NULL');+ if (!unresolved.length) break;+ await Bun.sleep(25);+ }+ await disposePersistenceConsumer(engine);+ const final = (await engine.readPageSnapshot(slug, { sourceId }))!;+ assert.deepEqual(reconcileCanonical(final.page, final.tags), params.preview.result);+ assert.equal(final.revision, receipt.revision);+ assert.notEqual(final.revision, params.preview.preimages.database.revision);+ assert.equal(await versionCount(engine), fixture.versions + 1, 'exactly one canonical version must be committed');+ assert.equal(readFileSync(file, 'utf8'), reviewed);+ const parsed = parseMarkdown(readFileSync(file, 'utf8'), slug);+ assert.deepEqual(reconcileCanonical(parsed, parsed.tags), params.preview.result);+ const fileStat = statSync(file);+ assert.deepEqual(await runReconcileApply(engine, params), receipt, 'same-ID replay must preserve the complete receipt');+ assert.equal((await engine.readPageSnapshot(slug, { sourceId }))!.revision, final.revision);+ assert.equal(await versionCount(engine), fixture.versions + 1);+ assert.equal(statSync(file).mtimeMs, fileStat.mtimeMs, 'replay must not republish the canonical file');+ const requests = await engine.executeRaw<{ id: string; state: string; recovery: unknown; recovery_bytes: string }>('SELECT id,state,recovery,recovery_bytes FROM persistence_requests');+ assert.equal(requests.length, 1);+ assert.equal(requests[0].id, fixture.rowId);+ assert.equal(requests[0].state, 'committed');+ assert.equal(requests[0].recovery, null);+ assert.equal(Number(requests[0].recovery_bytes), 0);+ assert.equal((await engine.executeRaw('SELECT 1 FROM persistence_effects WHERE recovery IS NOT NULL')).length, 0);+ if (stage) assert.equal(existsSync(stage.path), false);+ assert.deepEqual(readdirSync(join(config.root, 'source', 'notes')).sort(), ['example.md']);+ const backups = join(configDir(), 'reconciliation-previews');+ assert.deepEqual(readdirSync(backups).filter(name => name !== '.capacity.lock'), [fixture.backupReference]);+ const backup = join(backups, fixture.backupReference);+ assert.equal(sha256(readFileSync(backup)), fixture.backupHash);+ assert.equal(statSync(backup).mode & 0o777, 0o600);+ assert.equal(statSync(backups).mode & 0o777, 0o700);+ assert.deepEqual(JSON.parse(readFileSync(backup, 'utf8')).preview.preimages, params.preview.preimages);+ assert.deepEqual(JSON.parse(stableJson(await getWorktreeBinding(engine, sourceId))), fixture.binding);+ assert.deepEqual(await sourceState(engine), fixture.source);+ assert.equal((await engine.executeRaw<{ enabled: boolean }>('SELECT enabled FROM persistence_brain WHERE singleton=1'))[0].enabled, config.enabled);+ await assertConservation(engine);+ return { boundary: config.boundary, enabled: config.enabled, initial_state: row.state, request_id: config.requestId,+ row_id: fixture.rowId, terminal_state: 'committed', committed_requests: 1, added_versions: 1,+ result_digest: digest(reconcileCanonical(final.page, final.tags)), originals_retained: true,+ normal_apply_replay: true, receipt_unchanged: true, recovery_cleared: true, staging_cleaned: true,+ topology_unchanged: true, counters_conserved: true,+ ...(config.boundary === 'staging_flushed' ? { flushed_before_rename_verified: true } : {}) };+ });+ } finally { await disposePersistenceConsumer(engine); await engine.disconnect(); }+}++function spawnWorker(configPath: string, home: string, mode: 'crash' | 'recover') {+ const child = Bun.spawn([process.execPath, '--no-env-file', resolve(import.meta.path), mode, configPath],+ { cwd: home, env: childEnvironment(home), stdin: 'ignore', stdout: 'pipe', stderr: 'inherit' });+ const events: WorkerEvent[] = [];+ const waiters = new Set<() => void>();+ let ended = false;+ const reading = (async () => {+ const decoder = new TextDecoder();+ let pending = '';+ for await (const chunk of child.stdout) {+ pending += decoder.decode(chunk, { stream: true });+ for (;;) {+ const newline = pending.indexOf('\n');+ if (newline < 0) break;+ const line = pending.slice(0, newline);+ pending = pending.slice(newline + 1);+ try { const event = JSON.parse(line); if (typeof event.event === 'string') events.push(event); } catch {}+ for (const wake of waiters) wake();+ }+ }+ ended = true;+ for (const wake of waiters) wake();+ })();+ return {+ child,+ async event(name: string): Promise<WorkerEvent> {+ const deadline = Date.now() + 90_000;+ for (;;) {+ const found = events.find(event => event.event === name);+ if (found) return found;+ const failure = events.find(event => event.event === 'failure');+ assert(!failure, `${mode}: ${failure?.message}`);+ assert(!ended, `${mode} exited before ${name}`);+ assert(Date.now() < deadline, `${mode} timed out before ${name}`);+ await new Promise<void>(done => {+ const timer = setTimeout(wake, 500);+ function wake() { clearTimeout(timer); waiters.delete(wake); done(); }+ waiters.add(wake);+ });+ }+ },+ async kill() { if (child.exitCode === null) child.kill('SIGKILL'); await child.exited; await reading; },+ };+}++export async function runReconcileCrashCase(options: CaseOptions): Promise<Record<string, unknown>> {+ const root = mkdtempSync(join(tmpdir(), 'gbrain-reconcile-crash-'));+ const home = join(root, 'home');+ mkdirSync(home, { mode: 0o700 });+ const children: ReturnType<typeof spawnWorker>[] = [];+ let admin: ReturnType<typeof postgres> | undefined;+ let database: string | undefined;+ const manifest: Record<string, unknown> = { engine: options.kind, boundary: options.boundary, enabled: options.enabled,+ runtime: `bun-${Bun.version}`, platform: process.platform, status: 'running' };+ try {+ let databaseUrl: string | undefined;+ if (options.kind === 'postgres') {+ assert(options.databaseUrl, 'Postgres crash coverage requires an explicit test DATABASE_URL');+ assertSafeE2eDatabaseUrl(options.databaseUrl);+ admin = postgres(options.databaseUrl, { max: 1, prepare: false, onnotice() {} });+ const name = `gbrain_test_reconcile_crash_${randomUUID().replaceAll('-', '')}`;+ await admin.unsafe(`CREATE DATABASE ${name}`);+ database = name;+ const url = new URL(options.databaseUrl);+ url.pathname = `/${database}`;+ databaseUrl = url.toString();+ }+ const config: WorkerConfig = { ...options, databaseUrl, root, dataDir: join(root, 'data'), requestId: randomUUID() };+ const configPath = join(root, 'config.json');+ writeFileSync(configPath, JSON.stringify(config), { mode: 0o600 });+ const killed = spawnWorker(configPath, home, 'crash');+ children.push(killed);+ const reached = await killed.event(options.boundary === 'after_response' ? 'response_ready' : 'boundary');+ assert.equal(reached.boundary, options.boundary);+ assert.equal(reached.request_id, config.requestId);+ if (options.boundary === 'after_response') {+ const response = await fetch(reached.url!, { signal: AbortSignal.timeout(5000) });+ assert(response.ok);+ const receipt = await response.json() as Record<string, unknown>;+ assert.equal(receipt.request_id, config.requestId);+ assert.equal(receipt.state, 'committed');+ assert.equal((receipt.persistence as Record<string, unknown>).mode, 'filesystem');+ assert.equal((receipt.persistence as Record<string, unknown>).file_written, true);+ writeFileSync(join(root, 'received.json'), JSON.stringify(receipt), { mode: 0o600 });+ manifest.response_read_before_kill = true;+ }+ assert.equal(killed.child.exitCode, null, 'boundary must be a live blocked process, not a thrown exception');+ await killed.kill();+ assert.equal(killed.child.signalCode, 'SIGKILL');+ const restarted = spawnWorker(configPath, home, 'recover');+ children.push(restarted);+ const recovered = await restarted.event('done');+ assert.equal(await restarted.child.exited, 0);+ assert.equal(recovered.result?.row_id, reached.row_id);+ Object.assign(manifest, recovered.result, { status: 'passed', killed_signal: killed.child.signalCode });+ return manifest;+ } catch (error) {+ manifest.status = 'failed';+ throw error;+ } finally {+ try { await Promise.all(children.map(child => child.kill())); }+ finally {+ try { if (database && admin) await admin.unsafe(`DROP DATABASE ${database} WITH (FORCE)`); }+ finally {+ await admin?.end({ timeout: 1 });+ rmSync(root, { recursive: true, force: true });+ const directory = process.env.GBRAIN_TEST_RECONCILE_CRASH_MANIFEST_DIR;+ if (directory) {+ mkdirSync(directory, { recursive: true });+ writeFileSync(join(directory, `${options.kind}-${options.enabled ? 'enabled' : 'claimed'}-${options.boundary}.json`), `${JSON.stringify(manifest, null, 2)}\n`);+ }+ }+ }+ }+}++if (import.meta.main) {+ const [mode, configPath] = process.argv.slice(2);+ const config: WorkerConfig = JSON.parse(readFileSync(configPath, 'utf8'));+ try {+ assert(CRASH_BOUNDARIES.includes(config.boundary));+ assert.equal(process.env.HOME, join(config.root, 'home'));+ assert.equal(process.env.GBRAIN_HOME, process.env.HOME);+ if (mode === 'crash') await crash(config);+ else { assert.equal(mode, 'recover'); emit({ event: 'done', result: await recover(config) }); }+ } catch (error) {+ const message = error instanceof Error ? error.message : 'Unknown worker failure';+ emit({ event: 'failure', message: config.databaseUrl ? message.replaceAll(config.databaseUrl, '[test database]') : message });+ process.exit(1);+ }+}diff --git a/test/helpers/extract-atoms-page-fixtures.ts b/test/helpers/extract-atoms-page-fixtures.tsnew file mode 100644index 0000000000..79c3bce92e--- /dev/null+++ b/test/helpers/extract-atoms-page-fixtures.ts@@ -0,0 +1,13 @@+import type { BrainEngine } from '../../src/core/engine.ts';+import { runPhaseExtractAtoms, type ExtractAtomsOpts } from '../../src/core/cycle/extract-atoms.ts';++export async function runPhaseWithStoredPageFixtures(engine: BrainEngine, opts: ExtractAtomsOpts = {}) {+ const sourceId = opts.sourceId ?? 'default';+ for (const page of opts._pages ?? []) {+ const stored = await engine.getPage(page.slug, { sourceId })+ ?? await engine.putPage(page.slug, { type: 'note', title: page.slug, compiled_truth: page.content, timeline: '' }, { sourceId });+ await engine.executeRaw(`UPDATE pages SET compiled_truth=$1, content_hash=$2, slug=$4 WHERE source_id=$3 AND id=$5`,+ [page.content, page.contentHash, sourceId, page.slug, stored.id]);+ }+ return runPhaseExtractAtoms(engine, opts);+}diff --git a/test/persistence-managed-sync.test.ts b/test/persistence-managed-sync.test.tsindex a8f943bae0..6927f2952a 100644--- a/test/persistence-managed-sync.test.ts+++ b/test/persistence-managed-sync.test.ts@@ -7,7 +7,7 @@ import { execFileSync } from 'node:child_process';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';import type { BrainEngine } from '../src/core/engine.ts';-import { getWorktreeBinding, claimWorktree } from '../src/core/persistence/ownership.ts';+import { getWorktreeBinding, claimWorktree, acquireWorktree } from '../src/core/persistence/ownership.ts';import { admitWrite, claimNextWrite, getWriteRequest } from '../src/core/persistence/journal.ts';import { localHostId } from '../src/core/persistence/identity.ts';import { managedSyncAuthority } from '../src/core/persistence/sync-authority.ts';@@ -21,6 +21,7 @@ import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';import { withEnv } from './helpers/with-env.ts';import { prepareRemoteJob, withSubmissionAuthority } from '../src/core/minions/submission-authority.ts';import type { OperationContext } from '../src/core/ops/contract.ts';+import { loadSyncFailures, syncFailuresPath } from '../src/core/sync-failure-ledger.ts';const home = mkdtempSync(join(tmpdir(), 'gbrain-managed-sync-'));const engines: BrainEngine[] = [];@@ -249,6 +250,86 @@ test('raw bytes changing after preparation conflict without publishing and the s}}),120_000);+test.each([false, true])('managed terminal receipts survive a missing ledger and corrected retry uses a new ID (CRLF=%s)', async crlf =>+ withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {+ for (const engine of engines) {+ const f = await fixture(engine, { 'notes/example.md': 'An original observation about the example system.\n' });+ await performManagedSync(engine, { sourceId: f.id, noPull: true });+ const pinned = 'A newly committed observation about the example system.\n';+ const path = join(f.root, 'notes/example.md');+ writeFileSync(path, pinned);+ const target = commit(f.root);+ const working = crlf ? pinned.replace(/\n/g, '\r\n') : 'A private uncommitted observation that must not appear in diagnostics.\n';+ writeFileSync(path, working);+ const opts = { sourceId: f.id, noPull: true };+ const blocked = await performManagedSync(engine, opts);+ expect(blocked).toMatchObject({ status: 'blocked_by_failures', failedFiles: 1, filesImported: 0,+ managedWrite: { source_id: f.id, slug: 'notes/example', path: 'notes/example.md', write_error: 'source_changed',+ reason: 'pinned_git_worktree_conflict', ledger_recorded: true, write_request: { state: 'conflict', retry_after_ms: null } } });+ expect(blocked.managedWrite?.line_endings).toBe(crlf ? 'crlf_lf_only' : undefined);+ expect(JSON.stringify(blocked)).not.toContain(working.trim());+ expect(JSON.stringify(blocked)).not.toContain(f.root);+ expect(readFileSync(path, 'utf8')).toBe(working);+ const id = blocked.managedWrite!.write_request.request_id;+ const recorded = loadSyncFailures().filter(row => row.source_id === f.id);+ expect(recorded).toHaveLength(1);+ expect(recorded[0].path).toBe('notes/example.md');+ expect(recorded[0].error).toContain(id);+ expect(recorded[0].error).toContain('source_changed');+ expect((await engine.executeRaw<{ last_commit: string }>('SELECT last_commit FROM sources WHERE id=$1', [f.id]))[0].last_commit).toBe(f.head);+ writeFileSync(path, pinned);+ rmSync(syncFailuresPath(), { force: true });+ const replay = await performManagedSync(engine, opts);+ expect(replay.managedWrite?.write_request).toEqual(blocked.managedWrite!.write_request);+ expect(replay.status).toBe('blocked_by_failures');+ expect(loadSyncFailures().find(row => row.source_id === f.id)?.error).toContain(id);+ await withEnv({ GBRAIN_SYNC_FAILURES_DIR: path }, async () => {+ const unavailable = await performManagedSync(engine, opts);+ expect(unavailable).toMatchObject({ status: 'blocked_by_failures', managedWrite: { ledger_recorded: false,+ write_request: { request_id: id, state: 'conflict' } } });+ });+ await expect(performManagedSync(engine, { ...opts, skipFailed: true })).rejects.toMatchObject({ code: 'writer_coordinator_required' });+ const corrected = await performManagedSync(engine, { ...opts, retryFailed: true });+ expect(corrected.status).toBe('synced');+ expect(loadSyncFailures().filter(row => row.source_id === f.id)).toHaveLength(0);+ const requests = await engine.executeRaw<{ request_id: string; state: string }>('SELECT request_id,state FROM persistence_requests WHERE source_id=$1 ORDER BY sequence', [f.id]);+ expect(requests.filter(row => row.request_id === id)).toEqual([{ request_id: id, state: 'conflict' }]);+ expect(requests.at(-1)?.state).toBe('committed');+ expect(requests.at(-1)?.request_id).not.toBe(id);+ expect((await engine.executeRaw<{ last_commit: string }>('SELECT last_commit FROM sources WHERE id=$1', [f.id]))[0].last_commit).toBe(target);+ }+ }), 120_000);++test('pending durable sync retries keep the same request ID and do not claim committed imports', async () =>+ withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {+ for (const engine of engines) {+ await disposePersistenceConsumer(engine);+ const f = await fixture(engine, { 'pending.md': 'An observation waiting for publication.\n' });+ const lock = await acquireWorktree((await getWorktreeBinding(engine, f.id))!);+ expect(lock).not.toBeNull();+ try {+ const opts = { sourceId: f.id, noPull: true };+ const pending = await performManagedSync(engine, opts);+ expect(pending).toMatchObject({ status: 'partial', reason: 'writer_pending', filesImported: 0, added: 0,+ managedWrite: { source_id: f.id, slug: 'pending', path: 'pending.md', write_error: 'write_pending' } });+ const id = pending.managedWrite!.write_request.request_id;+ expect(pending.managedWrite!.write_request.state).not.toBe('committed');+ expect(await engine.executeRaw('SELECT id FROM pages WHERE source_id=$1', [f.id])).toHaveLength(0);+ expect((await engine.executeRaw<{ last_commit: string | null }>('SELECT last_commit FROM sources WHERE id=$1', [f.id]))[0].last_commit).toBeNull();+ const retry = await performManagedSync(engine, { ...opts, retryFailed: true });+ expect(retry).toMatchObject({ status: 'partial', reason: 'writer_pending', filesImported: 0,+ managedWrite: { write_request: { request_id: id } } });+ expect(await engine.executeRaw('SELECT id FROM persistence_requests WHERE source_id=$1', [f.id])).toHaveLength(1);+ expect(loadSyncFailures().filter(row => row.source_id === f.id)).toHaveLength(0);+ await lock!.release();+ const resumed = await performManagedSync(engine, opts);+ expect(resumed).toMatchObject({ status: 'first_sync', added: 1 });+ expect(await engine.executeRaw('SELECT state FROM persistence_requests WHERE source_id=$1 AND request_id=$2::uuid', [f.id, id]))+ .toEqual([{ state: 'committed' }]);+ } finally { await lock?.release(); await disposePersistenceConsumer(engine); }+ }+ }), 120_000);+test('continuous foreground arrivals cannot starve a bounded sync batch', async () => withEnv({GBRAIN_HOME:home},async()=>{const { registerMutationPreparer, startPersistenceConsumer, foregroundWriteCompletions } = await import('../src/core/persistence/service.ts');registerMutationPreparer('test_sync_foreground',async()=>{diff --git a/test/persistence-reconcile-merge.test.ts b/test/persistence-reconcile-merge.test.tsnew file mode 100644index 0000000000..556269099f--- /dev/null+++ b/test/persistence-reconcile-merge.test.ts@@ -0,0 +1,64 @@+import { expect, test } from 'bun:test';+import { mergeReconcile, reconcileDecisions } from '../src/core/persistence/reconcile-merge.ts';+import type { ParsedPage } from '../src/core/import-file.ts';++const page = (frontmatter: Record<string, unknown> = {}): ParsedPage => ({ type: 'note', title: 'Example',+ compiled_truth: 'A useful example observation.', timeline: '', frontmatter, tags: [] });++test('preserves unknown nested one-sided fields and add-only tags', () => {+ const file = { ...page({ profile: { location: 'example-place' }, custom_file: [1, 2] }), tags: ['file-tag'] };+ const database = { ...page({ profile: { role: 'example-role' }, custom_database: null }), tags: ['database-tag'] };+ expect(mergeReconcile(file, database)).toMatchObject({ conflicts: [], result: {+ frontmatter: { profile: { location: 'example-place', role: 'example-role' }, custom_file: [1, 2], custom_database: null },+ tags: ['database-tag', 'file-tag'] } });+});++test('requires exact escaped pointer decisions for scalar, type and array conflicts', () => {+ const file = page({ 'a/b': { '~key': 1 }, list: ['file'], mixed: {} });+ const database = page({ 'a/b': { '~key': 2 }, list: ['database'], mixed: 'scalar' });+ const before = mergeReconcile(file, database);+ expect(before.conflicts.map(c => c.path)).toEqual(['/frontmatter/a~1b/~0key', '/frontmatter/list', '/frontmatter/mixed']);+ const resolved = mergeReconcile(file, database, [+ { path: '/frontmatter/a~1b/~0key', action: 'take_file' },+ { path: '/frontmatter/list', action: 'set_value', value: ['explicit'] },+ { path: '/frontmatter/mixed', action: 'delete' },+ ]);+ expect(resolved.conflicts).toEqual([]);+ expect(resolved.result.frontmatter).toEqual({ 'a/b': { '~key': 1 }, list: ['explicit'] });+});++test('deletion is explicit even for one-sided metadata and no timestamps win', () => {+ const file = page({ obsolete: true, updated_at: '2030-01-01' });+ const database = page({ updated_at: '2020-01-01' });+ expect(mergeReconcile(file, database).conflicts).toHaveLength(1);+ expect(mergeReconcile(file, database).result.frontmatter.obsolete).toBe(true);+ expect(mergeReconcile(file, database, [{ path: '/frontmatter/obsolete', action: 'delete' }]).result.frontmatter.obsolete).toBeUndefined();+});++test('preserves trusted metadata, classifies exact scan keys and rejects protected decisions', () => {+ const file = page({ visibility: 'world', source_hash: 'forged', atoms_scan_hash: 'old', atoms_custom: 'keep', quarantine: false });+ const database = page({ visibility: 'private', source_hash: 'trusted', quarantine: { reason: 'junk_pattern' } });+ const merged = mergeReconcile(file, database);+ expect(merged.result.frontmatter).toEqual({ visibility: 'private', source_hash: 'trusted', atoms_custom: 'keep', quarantine: { reason: 'junk_pattern' } });+ expect(merged.scanPaths).toEqual(['/frontmatter/atoms_scan_hash']);+ expect(() => mergeReconcile(file, database, [{ path: '/frontmatter/visibility', action: 'take_file' }])).toThrow('protected');+ expect(() => reconcileDecisions([{ path: '/frontmatter', action: 'set_value', value: {} }])).toThrow('protected');+});++test('unknown metadata with sensitive-looking prefixes is preserved without granting trusted provenance', () => {+ const fields = { source_custom_label: 'keep', provenance_notes: { ordinary: true }, withdrawal_notes: 'keep', safety_review: 'keep',+ permission_context: 'keep', trust_custom: 'keep', ingested_custom: 'keep', atoms_scan_custom: 'keep' };+ const merged = mergeReconcile(page({ ...fields, source_quote_offset: [1, 2] }), page());+ expect(merged.result.frontmatter).toEqual(fields);+ expect(merged.protectedPaths).toEqual(['/frontmatter/source_quote_offset']);+ expect(mergeReconcile(page({ status: 'ordinary-status' }), page()).result.frontmatter.status).toBe('ordinary-status');+ expect(mergeReconcile(page({ status: 'verified' }), page({ provenance: 'auto-extracted', status: 'unverified' })).result.frontmatter.status).toBe('unverified');+});++test('rejects unknown, duplicate, overlapping and malformed decisions', () => {+ expect(() => mergeReconcile(page(), page(), [{ path: '/frontmatter/missing', action: 'delete' }])).toThrow('unknown');+ expect(() => reconcileDecisions([{ path: '/frontmatter/x', action: 'delete' }, { path: '/frontmatter/x/y', action: 'delete' }])).toThrow('overlapping');+ expect(() => reconcileDecisions([{ path: '/bad~2path', action: 'delete' }])).toThrow('Pointer');+ expect(() => reconcileDecisions([{ path: '/frontmatter/x', action: 'delete', value: true }])).toThrow('Invalid');+ expect(() => reconcileDecisions([{ path: '/tags', action: 'set_value', value: [] }])).toThrow('protected');+});diff --git a/test/persistence-reconcile.test.ts b/test/persistence-reconcile.test.tsnew file mode 100644index 0000000000..dd9ff49c5e--- /dev/null+++ b/test/persistence-reconcile.test.ts@@ -0,0 +1,646 @@+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { pathToFileURL } from 'node:url';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { configDir } from '../src/core/config.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { parseMarkdown, serializePageToMarkdown } from '../src/core/markdown.ts';+import { acceptWriterTransfer, acquireWorktree, claimWorktree, getWorktreeBinding, prepareWriterTransfer } from '../src/core/persistence/ownership.ts';+import { registerLocalWriter, withVerifiedLocalRegistration, type LocalRegistration } from '../src/core/persistence/identity.ts';+import { runReconcileApply, runReconcileBackups, runReconcilePreview, assertReconcileOutputPath } from '../src/core/persistence/reconcile.ts';+import { prepareFileTarget } from '../src/core/persistence/page-prepare.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { admitWrite, claimNextWrite, compactWriteReceipts, getWriteRequest } from '../src/core/persistence/journal.ts';+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { submissionAuthority } from '../src/core/persistence/authority.ts';+import { retainReconcileBackup } from '../src/core/persistence/reconcile-backup.ts';+import { prepareReconcileMutation } from '../src/core/persistence/reconcile-prepare.ts';+import { publishMutation } from '../src/core/persistence/coordinator.ts';+import { localHostId } from '../src/core/persistence/identity.ts';+import { parseFactsFence, upsertFactRow } from '../src/core/facts-fence.ts';+import { sha256 } from '../src/core/persistence/digest.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';+import { operationsByName } from '../src/core/operations.ts';+import { reconcileCanonical } from '../src/core/persistence/reconcile-merge.ts';+import { dispatchToolCall } from '../src/mcp/dispatch.ts';+import { withEnv } from './helpers/with-env.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';++const home = mkdtempSync(join(tmpdir(), 'gbrain-reconcile-'));+const engines: BrainEngine[] = [];+let closePostgres: (() => Promise<void>) | undefined;+beforeAll(async () => {+ const engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); engines.push(engine);+ if (process.env.DATABASE_URL) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL); engines.push(pg.engine); closePostgres = pg.close; }+}, 120_000);+afterAll(async () => {+ await withEnv({ GBRAIN_HOME: home }, async () => {+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }+ });+ await closePostgres?.(); rmSync(home, { recursive: true, force: true });+});+async function fixture(engine: BrainEngine, enabled = false, body = 'A useful durable example observation.') {+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ const id = `reconcile-${randomUUID().slice(0, 12)}`, root = join(home, id), slug = 'notes/example';+ mkdirSync(join(root, 'notes'), { recursive: true });+ await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,\'{}\')', [id, root]);+ const content = `---\ntype: note\ntitle: Example\ncustom_database: kept\nprofile:\n role: example-role\n---\n${body}\n`;+ await importFromContent(engine, slug, content, { sourceId: id, sourcePath: 'notes/example.md', noEmbed: true });+ const snapshot = (await engine.readPageSnapshot(slug, { sourceId: id }))!;+ const file = join(root, 'notes/example.md');+ writeFileSync(file, serializePageToMarkdown({ ...snapshot.page, frontmatter: { profile: { location: 'example-place' }, custom_file: 'kept' } }, snapshot.tags));+ const binding = await claimWorktree(engine, id, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=$1 WHERE singleton=1', [enabled]);+ const registration = await registerLocalWriter(engine, 'cli');+ return { id, root, slug, file, binding, registration, snapshot };+}+const local = <T>(engine: BrainEngine, registration: LocalRegistration, fn: () => Promise<T>) => withVerifiedLocalRegistration(engine, registration, fn);+const isolated = (fn: (engine: BrainEngine) => Promise<void>) => withEnv({ GBRAIN_HOME: home, OPENAI_API_KEY: undefined, ANTHROPIC_API_KEY: undefined }, async () => {+ for (const engine of engines) await fn(engine);+});+async function preparedRepair(engine: BrainEngine, f: Awaited<ReturnType<typeof fixture>>) {+ const { preview } = await runReconcilePreview(engine, { source_id: f.id, slug: f.slug });+ const authority = await submissionAuthority({ engine, remote: false } as OperationContext, 'put_page', f.id, preview.preconditions.source_incarnation, f.slug);+ const requestId = randomUUID(), reference = await retainReconcileBackup(engine, preview, authority.principal, requestId);+ const callerIntent = { kind: 'canonical_reconcile', preview };+ await admitWrite(engine, { principal: authority.principal, operation: 'put_page', sourceId: f.id, sourceIncarnation: preview.preconditions.source_incarnation,+ slug: f.slug, pageId: f.snapshot.page.id, worktreeId: f.binding.worktree_id, topologyGeneration: f.binding.topology_generation,+ requestId, authority, callerIntent, intent: { ...callerIntent, backup_reference: reference } });+ const row = (await claimNextWrite(engine, localHostId()))!;+ expect(row.request_id).toBe(requestId);+ const prepared = await prepareReconcileMutation(engine, row, { engine: engine.kind });+ return { preview, authority, reference, row, prepared, params: { source_id: f.id, slug: f.slug, preview, request_id: requestId } };+}++test('repairs claimed enabled and disabled sources without topology changes and retains both preimages', async () => isolated(async engine => {+ for (const enabled of [false, true]) {+ const f = await fixture(engine, enabled), before = readFileSync(f.file);+ await expect(prepareFileTarget(engine, { source_id: f.id, slug: f.slug, worktree_id: f.binding.worktree_id }, f.snapshot, 'next')).rejects.toMatchObject({ code: 'source_changed' });+ const [sourceBefore] = await engine.executeRaw('SELECT incarnation,last_commit,last_sync_at,config FROM sources WHERE id=$1', [f.id]);+ await local(engine, f.registration, async () => {+ const preview = await runReconcilePreview(engine, { source_id: f.id, slug: f.slug });+ expect(preview.status).toBe('ready');+ expect(preview.preview.result.frontmatter).toMatchObject({ custom_database: 'kept', custom_file: 'kept', profile: { role: 'example-role', location: 'example-place' } });+ expect(readFileSync(f.file)).toEqual(before);+ expect((await engine.readPageSnapshot(f.slug, { sourceId: f.id }))?.revision).toBe(f.snapshot.revision);+ const receipt = await runReconcileApply(engine, { source_id: f.id, slug: f.slug, preview: preview.preview, request_id: randomUUID() });+ expect(receipt.state).toBe('committed');+ expect(receipt.outcome).toMatchObject({ status: 'reconciled', database_changed: true, file_changed: true });+ const outcome = receipt.outcome as { backup_reference: string };+ const backup = join(configDir(), 'reconciliation-previews', outcome.backup_reference);+ if (process.platform !== 'win32') {+ expect(statSync(backup).mode & 0o777).toBe(0o600);+ expect(statSync(join(configDir(), 'reconciliation-previews')).mode & 0o777).toBe(0o700);+ }+ expect(JSON.parse(readFileSync(backup, 'utf8')).preview.preimages.file_base64).toBe(before.toString('base64'));+ const current = (await engine.readPageSnapshot(f.slug, { sourceId: f.id }))!;+ expect(current.page.frontmatter).toEqual(preview.preview.result.frontmatter);+ expect(parseMarkdown(readFileSync(f.file, 'utf8'), f.slug).frontmatter).toEqual(current.page.frontmatter);+ await expect(prepareFileTarget(engine, { source_id: f.id, slug: f.slug, worktree_id: f.binding.worktree_id }, current, 'next')).resolves.toBeDefined();+ });+ expect(await getWorktreeBinding(engine, f.id)).toEqual(f.binding);+ expect((await engine.executeRaw('SELECT incarnation,last_commit,last_sync_at,config FROM sources WHERE id=$1', [f.id]))[0]).toEqual(sourceBefore);+ expect((await engine.executeRaw<{ enabled: boolean }>('SELECT enabled FROM persistence_brain WHERE singleton=1'))[0].enabled).toBe(enabled);+ }+}), 120_000);++test('same-ID replay precedes raw CAS, survives compaction and never allocates another backup', async () => isolated(async engine => {+ const f = await fixture(engine);+ await local(engine, f.registration, async () => {+ const { preview } = await runReconcilePreview(engine, { source_id: f.id, slug: f.slug });+ const params = { source_id: f.id, slug: f.slug, preview, request_id: randomUUID() };+ const receipt = await runReconcileApply(engine, params);+ const files = readdirSync(join(configDir(), 'reconciliation-previews'));+ writeFileSync(f.file, 'A later independent edit.\n');+ expect((await runReconcileApply(engine, params)).revision).toBe(receipt.revision);+ await disposePersistenceConsumer(engine);+ await engine.executeRaw("UPDATE persistence_effects SET state='committed' WHERE request_id=(SELECT id FROM persistence_requests WHERE request_id=$1::uuid)", [params.request_id]);+ await engine.executeRaw("UPDATE persistence_requests SET completed_at=now()-interval '60 days' WHERE request_id=$1::uuid", [params.request_id]);+ await compactWriteReceipts(engine);+ expect(await runReconcileApply(engine, params)).toMatchObject({ state: 'committed', compacted: true, revision: receipt.revision });+ expect(readdirSync(join(configDir(), 'reconciliation-previews'))).toEqual(files);+ await expect(runReconcileApply(engine, { ...params, preview: { ...preview, preview_id: randomUUID() } })).rejects.toMatchObject({ code: 'idempotency_conflict' });+ });+}), 120_000);++test('raw-byte, policy, withdrawal and owner epoch changes refuse new admission', async () => isolated(async engine => {+ for (const mutation of ['raw', 'policy', 'withdrawal', 'owner']) {+ const f = await fixture(engine);+ await local(engine, f.registration, async () => {+ const { preview } = await runReconcilePreview(engine, { source_id: f.id, slug: f.slug });+ if (mutation === 'raw') writeFileSync(f.file, readFileSync(f.file, 'utf8').replace(/\n/g, '\r\n'));+ if (mutation === 'policy') await engine.setConfig('content_sanity.bytes_warn', String(200000 + Math.floor(Math.random() * 100)));+ if (mutation === 'withdrawal') await engine.executeRaw("INSERT INTO fact_withdrawals(source_id,visibility,fact_hash) VALUES($1,'world',$2)", [f.id, 'a'.repeat(64)]);+ if (mutation === 'owner') await engine.executeRaw('UPDATE persistence_worktrees SET owner_epoch=owner_epoch+1 WHERE id=$1::uuid', [f.binding.worktree_id]);+ await expect(runReconcileApply(engine, { source_id: f.id, slug: f.slug, preview, request_id: randomUUID() })).rejects.toMatchObject({ code: 'source_changed' });+ expect(await engine.executeRaw('SELECT id FROM persistence_requests WHERE source_id=$1', [f.id])).toHaveLength(0);+ });+ }+}), 120_000);++test('file-only drift publishes instead of a global no-op and preserves the DB revision', async () => isolated(async engine => {+ const f = await fixture(engine);+ writeFileSync(f.file, serializePageToMarkdown({ ...f.snapshot.page, frontmatter: {} }, []));+ await local(engine, f.registration, async () => {+ const { preview } = await runReconcilePreview(engine, { source_id: f.id, slug: f.slug });+ const result = await runReconcileApply(engine, { source_id: f.id, slug: f.slug, preview, request_id: randomUUID() });+ expect(result.outcome).toMatchObject({ database_changed: false, file_changed: true });+ expect(result.revision).toBe(f.snapshot.revision);+ expect(parseMarkdown(readFileSync(f.file, 'utf8'), f.slug).frontmatter.custom_database).toBe('kept');+ });+}), 120_000);++test('original and current grants are enforced before reading either preimage', async () => isolated(async engine => {+ const f = await fixture(engine);+ await expect(runReconcilePreview(engine, { source_id: f.id, slug: f.slug })).rejects.toMatchObject({ code: 'permission_denied' });+ const narrow = await registerLocalWriter(engine, 'stdio');+ await expect(local(engine, narrow, () => runReconcilePreview(engine, { source_id: f.id, slug: f.slug }))).rejects.toMatchObject({ code: 'permission_denied' });+ const originalRead = engine.readPageSnapshot;+ let reads = 0;+ engine.readPageSnapshot = async (...args) => { reads++; return originalRead.apply(engine, args); };+ try {+ await local(engine, f.registration, async () => {+ await engine.executeRaw("UPDATE persistence_local_writers SET grant_ceiling=$2::text::jsonb WHERE id=$1::uuid", [f.registration.id,+ JSON.stringify({ sourceIds: ['*'], scopes: ['write'], operations: ['put_page'], slugPrefixes: ['other/'] })]);+ await expect(runReconcilePreview(engine, { source_id: f.id, slug: f.slug })).rejects.toMatchObject({ code: 'permission_denied' });+ expect(reads).toBe(0);+ });+ } finally {+ engine.readPageSnapshot = originalRead;+ await engine.executeRaw("UPDATE persistence_local_writers SET grant_ceiling=$2::text::jsonb WHERE id=$1::uuid", [f.registration.id,+ JSON.stringify({ sourceIds: ['*'], scopes: ['read', 'write'], operations: null, slugPrefixes: null })]);+ }+ await expect(assertReconcileOutputPath(engine, f.id, join(f.root, 'private.json'))).rejects.toMatchObject({ code: 'permission_denied' });+}), 120_000);++test('conflicting bodies require reviewed decisions and modified artifacts cannot apply', async () => isolated(async engine => {+ const f = await fixture(engine);+ writeFileSync(f.file, readFileSync(f.file, 'utf8').replace('A useful durable example observation.', 'A different carefully reviewed observation.'));+ await local(engine, f.registration, async () => {+ const initial = await runReconcilePreview(engine, { source_id: f.id, slug: f.slug });+ expect(initial.status).toBe('needs_resolution');+ expect(initial.conflict_paths).toEqual(['/compiled_truth']);+ const { preview } = await runReconcilePreview(engine, { source_id: f.id, slug: f.slug, from: initial.preview,+ decisions: [{ path: '/compiled_truth', action: 'take_file' }, { path: '/frontmatter/custom_database', action: 'delete' }] });+ expect(preview.status).toBe('ready');+ expect(preview.result.compiled_truth).toBe('A different carefully reviewed observation.');+ await expect(runReconcileApply(engine, { source_id: f.id, slug: f.slug, preview: { ...preview, unexpected: true }, request_id: randomUUID() })).rejects.toMatchObject({ code: 'invalid_params' });+ expect((await runReconcileApply(engine, { source_id: f.id, slug: f.slug, preview, request_id: randomUUID() })).state).toBe('committed');+ });+}), 120_000);++test('unchanged safety assessments reuse canonical stamps without fresh revision churn', async () => isolated(async engine => {+ const f = await fixture(engine, true, 'Just a moment...\n\nChecking your browser before accessing this website.\nVerify you are human.');+ await local(engine, f.registration, async () => {+ const { preview } = await runReconcilePreview(engine, { source_id: f.id, slug: f.slug });+ expect(preview.result.frontmatter.quarantine).toBeDefined();+ const first = await runReconcileApply(engine, { source_id: f.id, slug: f.slug, preview, request_id: randomUUID() });+ const second = await runReconcilePreview(engine, { source_id: f.id, slug: f.slug });+ expect(second.preview.result).toEqual(preview.result);+ const repeated = await runReconcileApply(engine, { source_id: f.id, slug: f.slug, preview: second.preview, request_id: randomUUID() });+ expect(repeated.revision).toBe(first.revision);+ expect(repeated.outcome).toMatchObject({ database_changed: false, file_changed: false });+ let importNoop = false;+ await importFromContent(engine, f.slug, readFileSync(f.file, 'utf8'), { sourceId: f.id, sourcePath: 'notes/example.md', noEmbed: true,+ prepare: async value => { importNoop = value.noop; expect(value.parsedPage.frontmatter).toEqual(preview.result.frontmatter); return value.result; } });+ expect(importNoop).toBe(true);+ });+}), 120_000);++test('private and withdrawn timeline facts survive file choices without resurrection', async () => isolated(async engine => {+ const privateBody = upsertFactRow('Private biography.', { claim: 'Prefers a private example venue', kind: 'fact', visibility: 'private', confidence: 1, notability: 'medium' }).body;+ const timeline = upsertFactRow('## Timeline\n', { claim: 'Previously preferred the old example venue', kind: 'fact', visibility: 'world', confidence: 1, notability: 'medium' }).body.replace('| 1 |', '| 2 |');+ const f = await fixture(engine, false, `${privateBody}\n<!-- timeline -->\n${timeline}`);+ await engine.executeRaw("INSERT INTO fact_withdrawals(source_id,visibility,fact_hash) VALUES($1,'world',$2)",+ [f.id, sha256('previously preferred the old example venue')]);+ writeFileSync(f.file, serializePageToMarkdown({ ...f.snapshot.page, compiled_truth: 'A revised public biography.' }, []));+ await local(engine, f.registration, async () => {+ const initial = await runReconcilePreview(engine, { source_id: f.id, slug: f.slug });+ const decisions = initial.preview.conflicts.map(c => ({ path: c.path, action: 'take_file' }));+ const resolved = await runReconcilePreview(engine, { source_id: f.id, slug: f.slug, from: initial.preview, decisions });+ expect(parseFactsFence(resolved.preview.result.compiled_truth).facts[0].visibility).toBe('private');+ const retired = parseFactsFence(resolved.preview.result.timeline).facts[0];+ expect(retired.validUntil).toBeDefined();+ expect((await runReconcileApply(engine, { source_id: f.id, slug: f.slug, preview: resolved.preview, request_id: randomUUID() })).state).toBe('committed');+ const current = (await engine.readPageSnapshot(f.slug, { sourceId: f.id }))!;+ expect(parseFactsFence(current.page.compiled_truth).facts[0].visibility).toBe('private');+ expect(parseFactsFence(current.page.timeline).facts[0].validUntil).toBe(retired.validUntil);+ });+}), 120_000);++test('matching legacy scan state migrates only during canonical publication', async () => isolated(async engine => {+ const f = await fixture(engine);+ const marker = f.snapshot.page.content_hash!.slice(0, 16);+ await withCoordinatedWrite(engine, [f.id], () => engine.executeRaw("UPDATE pages SET frontmatter=frontmatter || $3::text::jsonb WHERE source_id=$1 AND slug=$2",+ [f.id, f.slug, JSON.stringify({ atoms_scan_hash: marker, atoms_custom: 'preserve' })]));+ const before = (await engine.readPageSnapshot(f.slug, { sourceId: f.id }))!;+ writeFileSync(f.file, serializePageToMarkdown(before.page, before.tags));+ await local(engine, f.registration, async () => {+ const { preview } = await runReconcilePreview(engine, { source_id: f.id, slug: f.slug });+ expect(preview.result.frontmatter.atoms_scan_hash).toBeUndefined();+ expect(preview.result.frontmatter.atoms_custom).toBe('preserve');+ expect(await engine.executeRaw('SELECT * FROM extract_atoms_page_state WHERE page_id=$1', [before.page.id])).toHaveLength(0);+ const result = await runReconcileApply(engine, { source_id: f.id, slug: f.slug, preview, request_id: randomUUID() });+ expect(result.outcome).toMatchObject({ scan_state_transferred: true });+ expect(await engine.executeRaw('SELECT tombstoned FROM extract_atoms_page_state WHERE page_id=$1', [before.page.id])).toEqual([{ tombstoned: true }]);+ });+}), 120_000);++test('capacity refusal is bounded, preserves originals, and admits no request', async () => isolated(async engine => {+ const f = await fixture(engine), raw = readFileSync(f.file);+ await local(engine, f.registration, async () => {+ await engine.setConfig('persistence.limits.brain_lifetime_ids', '0');+ try {+ const { preview } = await runReconcilePreview(engine, { source_id: f.id, slug: f.slug });+ await expect(runReconcileApply(engine, { source_id: f.id, slug: f.slug, preview, request_id: randomUUID() })).rejects.toMatchObject({ code: 'queue_capacity' });+ expect(readFileSync(f.file)).toEqual(raw);+ expect(await engine.executeRaw('SELECT id FROM persistence_requests WHERE source_id=$1', [f.id])).toHaveLength(0);+ } finally { await engine.executeRaw("DELETE FROM config WHERE key='persistence.limits.brain_lifetime_ids'"); }+ });+}), 120_000);++test('queued intent resumes with a fresh consumer and retains its accepted request identity', async () => isolated(async engine => {+ for (const enabled of [false, true]) {+ const f = await fixture(engine, enabled);+ await local(engine, f.registration, async () => {+ const { preview } = await runReconcilePreview(engine, { source_id: f.id, slug: f.slug });+ const ctx = { engine, remote: false, sourceId: f.id } as OperationContext;+ const authority = await submissionAuthority(ctx, 'put_page', f.id, preview.preconditions.source_incarnation, f.slug);+ const requestId = randomUUID();+ const reference = await retainReconcileBackup(engine, preview, authority.principal, requestId);+ const callerIntent = { kind: 'canonical_reconcile', preview };+ await admitWrite(engine, { principal: authority.principal, operation: 'put_page', sourceId: f.id,+ sourceIncarnation: preview.preconditions.source_incarnation, slug: f.slug, pageId: f.snapshot.page.id,+ worktreeId: f.binding.worktree_id, topologyGeneration: f.binding.topology_generation, requestId, authority, callerIntent,+ intent: { ...callerIntent, backup_reference: reference } });+ await expect(runReconcileBackups(engine, { source_id: f.id, slug: f.slug, action: 'remove', backup_reference: reference })).rejects.toMatchObject({ code: 'recovery_required' });+ await disposePersistenceConsumer(engine);+ const result = await runReconcileApply(engine, { source_id: f.id, slug: f.slug, preview, request_id: requestId });+ expect(result).toMatchObject({ state: 'committed', request_id: requestId });+ expect(await engine.executeRaw('SELECT id FROM persistence_requests WHERE source_id=$1', [f.id])).toHaveLength(1);+ expect(JSON.parse(readFileSync(join(configDir(), 'reconciliation-previews', reference), 'utf8')).preview.result_digest).toBe(preview.result_digest);+ await disposePersistenceConsumer(engine);+ const listing = await runReconcileBackups(engine, { source_id: f.id, slug: f.slug, action: 'list' });+ expect(listing.backups).toMatchObject([{ backup_reference: reference, retained: true, removable: true }]);+ expect(await runReconcileBackups(engine, { source_id: f.id, slug: f.slug, action: 'remove', backup_reference: reference })).toMatchObject({ removed: true });+ expect((await runReconcileApply(engine, { source_id: f.id, slug: f.slug, preview, request_id: requestId })).revision).toBe(result.revision);+ });+ }+}), 120_000);++test('publication rechecks grants after preparation without touching the canonical file', async () => isolated(async engine => {+ const f = await fixture(engine), raw = readFileSync(f.file);+ await local(engine, f.registration, async () => {+ const { preview } = await runReconcilePreview(engine, { source_id: f.id, slug: f.slug });+ const authority = await submissionAuthority({ engine, remote: false } as OperationContext, 'put_page', f.id, preview.preconditions.source_incarnation, f.slug);+ const requestId = randomUUID(), reference = await retainReconcileBackup(engine, preview, authority.principal, requestId);+ const callerIntent = { kind: 'canonical_reconcile', preview };+ await admitWrite(engine, { principal: authority.principal, operation: 'put_page', sourceId: f.id, sourceIncarnation: preview.preconditions.source_incarnation,+ slug: f.slug, pageId: f.snapshot.page.id, worktreeId: f.binding.worktree_id, topologyGeneration: f.binding.topology_generation,+ requestId, authority, callerIntent, intent: { ...callerIntent, backup_reference: reference } });+ const row = (await claimNextWrite(engine, localHostId()))!;+ const prepared = await prepareReconcileMutation(engine, row, { engine: engine.kind });+ await engine.executeRaw("UPDATE persistence_local_writers SET grant_ceiling=$2::text::jsonb WHERE id=$1::uuid", [f.registration.id,+ JSON.stringify({ sourceIds: ['*'], scopes: ['read'], operations: null, slugPrefixes: null })]);+ try {+ const result = await publishMutation(engine, row, prepared);+ expect(result.state).not.toBe('committed');+ expect((await getWriteRequest(engine, authority.principal, requestId))?.error_code).toBe('permission_denied');+ expect(readFileSync(f.file)).toEqual(raw);+ } finally {+ await engine.executeRaw("UPDATE persistence_local_writers SET grant_ceiling=$2::text::jsonb WHERE id=$1::uuid", [f.registration.id,+ JSON.stringify({ sourceIds: ['*'], scopes: ['read', 'write'], operations: null, slugPrefixes: null })]);+ }+ });+}), 120_000);++test('concurrent same-ID callers replay a winner committed between lookup and live CAS', async () => isolated(async engine => {+ for (const pauseLookup of [1, 3]) {+ const f = await fixture(engine);+ await local(engine, f.registration, async () => {+ const { preview } = await runReconcilePreview(engine, { source_id: f.id, slug: f.slug });+ const params = { source_id: f.id, slug: f.slug, preview, request_id: randomUUID() };+ const executeRaw = engine.executeRaw;+ let release!: () => void, paused!: () => void, reads = 0;+ const held = new Promise<void>(resolve => { release = resolve; });+ const reached = new Promise<void>(resolve => { paused = resolve; });+ engine.executeRaw = async function(this: BrainEngine, sql: string, values?: unknown[]) {+ const result = await executeRaw.call(this, sql, values);+ if (sql.includes('SELECT * FROM persistence_requests WHERE principal_kind=') && values?.[2] === params.request_id && ++reads === pauseLookup) {+ paused(); await held;+ }+ return result;+ } as BrainEngine['executeRaw'];+ try {+ const delayed = runReconcileApply(engine, params);+ await reached;+ const winner = await runReconcileApply(engine, params);+ expect(winner.state).toBe('committed');+ release();+ expect(await delayed).toMatchObject({ state: 'committed', request_id: params.request_id, revision: winner.revision });+ expect(await engine.executeRaw('SELECT id FROM persistence_requests WHERE source_id=$1', [f.id])).toHaveLength(1);+ await expect(runReconcileApply(engine, { ...params, request_id: randomUUID() })).rejects.toMatchObject({ code: 'source_changed' });+ } finally { release(); engine.executeRaw = executeRaw; }+ });+ }+}), 120_000);++test('valid empty metadata is ordinary input while malformed metadata and missing files are refused', async () => isolated(async engine => {+ const f = await fixture(engine);+ await local(engine, f.registration, async () => {+ writeFileSync(f.file, '---\n{}\n---\nA useful durable example observation.\n');+ expect((await runReconcilePreview(engine, { source_id: f.id, slug: f.slug })).preview.result.frontmatter.custom_database).toBe('kept');+ for (const invalid of ['---\n[1, 2]\n---\nBody.', '---\nkey: [broken\n---\nBody.', '---\nkey: value\nBody.']) {+ writeFileSync(f.file, invalid);+ await expect(runReconcilePreview(engine, { source_id: f.id, slug: f.slug })).rejects.toMatchObject({ code: 'invalid_params' });+ }+ rmSync(f.file);+ await expect(runReconcilePreview(engine, { source_id: f.id, slug: f.slug })).rejects.toMatchObject({ code: 'source_changed' });+ });+}), 120_000);++test('a repaired page supports normal capture, put, delete and restore with revision-bound readback', async () => isolated(async engine => {+ for (const enabled of [false, true]) {+ const f = await fixture(engine, enabled);+ await local(engine, f.registration, async () => {+ const { preview } = await runReconcilePreview(engine, { source_id: f.id, slug: f.slug });+ expect((await runReconcileApply(engine, { source_id: f.id, slug: f.slug, preview, request_id: randomUUID() })).state).toBe('committed');+ const ctx: OperationContext = { engine, remote: false, sourceId: f.id, config: { engine: engine.kind }, dryRun: false,+ logger: { info() {}, warn() {}, error() {} } };+ for (const operation of ['capture', 'put_page']) {+ const before = (await engine.readPageSnapshot(f.slug, { sourceId: f.id }))!;+ const content = serializePageToMarkdown({ ...before.page, compiled_truth: `${before.page.compiled_truth}\n\nA new ${operation} observation.` }, before.tags);+ const receipt = await operationsByName[operation]!.handler(ctx, { source_id: f.id, slug: f.slug, content,+ expected_revision: before.revision, request_id: randomUUID() }) as Record<string, unknown>;+ expect(receipt.state).toBe('committed');+ const after = (await engine.readPageSnapshot(f.slug, { sourceId: f.id }))!;+ const file = parseMarkdown(readFileSync(f.file, 'utf8'), f.slug);+ expect(reconcileCanonical(file, file.tags)).toEqual(reconcileCanonical(after.page, after.tags));+ expect(after.page.compiled_truth).toContain(`A new ${operation} observation.`);+ expect(after.page.frontmatter.custom_file).toBe('kept');+ }+ const before = (await engine.readPageSnapshot(f.slug, { sourceId: f.id }))!;+ const deleted = await operationsByName.delete_page!.handler(ctx, { source_id: f.id, slug: f.slug,+ expected_revision: before.revision, request_id: randomUUID() }) as Record<string, unknown>;+ expect(deleted.state).toBe('committed');+ expect(existsSync(f.file)).toBe(false);+ expect(await engine.readPageSnapshot(f.slug, { sourceId: f.id })).toBeNull();+ const tombstone = (await engine.readPageSnapshot(f.slug, { sourceId: f.id, includeDeleted: true }))!;+ const restored = await operationsByName.restore_page!.handler(ctx, { source_id: f.id, slug: f.slug,+ expected_revision: tombstone.revision, request_id: randomUUID() }) as Record<string, unknown>;+ expect(restored.state).toBe('committed');+ const after = (await engine.readPageSnapshot(f.slug, { sourceId: f.id }))!;+ const file = parseMarkdown(readFileSync(f.file, 'utf8'), f.slug);+ expect(reconcileCanonical(file, file.tags)).toEqual(reconcileCanonical(after.page, after.tags));+ expect(after.page.compiled_truth).toBe(before.page.compiled_truth);+ expect(after.page.source_kind).toBe(before.page.source_kind);+ expect(after.page.ingested_via).toBe(before.page.ingested_via);+ });+ }+}), 120_000);++test('source substitution, changed canonical revisions and recreated pages never consume an old preview', async () => isolated(async engine => {+ for (const mutation of ['source', 'revision', 'identity']) {+ const f = await fixture(engine), raw = readFileSync(f.file);+ await local(engine, f.registration, async () => {+ const { preview } = await runReconcilePreview(engine, { source_id: f.id, slug: f.slug });+ let sourceId = f.id;+ if (mutation === 'source') sourceId = (await fixture(engine)).id;+ else await withCoordinatedWrite(engine, [f.id], async () => {+ if (mutation === 'identity') await engine.deletePage(f.slug, { sourceId: f.id });+ await engine.putPage(f.slug, { type: 'note', title: 'Example', compiled_truth: 'A later database observation.', frontmatter: {} }, { sourceId: f.id });+ });+ await expect(runReconcileApply(engine, { source_id: sourceId, slug: f.slug, preview, request_id: randomUUID() })).rejects.toMatchObject({+ code: mutation === 'source' ? 'invalid_params' : 'source_changed' });+ expect(readFileSync(f.file)).toEqual(raw);+ expect(await engine.executeRaw('SELECT id FROM persistence_requests WHERE source_id=$1', [f.id])).toHaveLength(0);+ });+ }+}), 120_000);++test('derived page telemetry does not stale canonical preimages and CRLF-only differences are explicit', async () => isolated(async engine => {+ const f = await fixture(engine);+ writeFileSync(f.file, serializePageToMarkdown(f.snapshot.page, f.snapshot.tags).replace(/\n/g, '\r\n'));+ await local(engine, f.registration, async () => {+ const result = await runReconcilePreview(engine, { source_id: f.id, slug: f.slug });+ expect(result).toMatchObject({ status: 'ready', line_endings: 'crlf', formatting_only: true });+ await engine.executeRaw('UPDATE pages SET emotional_weight=0.3 WHERE id=$1', [f.snapshot.page.id]);+ expect((await runReconcileApply(engine, { source_id: f.id, slug: f.slug, preview: result.preview, request_id: randomUUID() })).state).toBe('committed');+ expect(readFileSync(f.file, 'utf8')).not.toContain('\r\n');+ expect((await engine.readPageSnapshot(f.slug, { sourceId: f.id }))?.revision).toBe(f.snapshot.revision);+ });+}), 120_000);++test('unadmitted private backups cannot be removed through receipt administration', async () => isolated(async engine => {+ const f = await fixture(engine);+ await local(engine, f.registration, async () => {+ const { preview } = await runReconcilePreview(engine, { source_id: f.id, slug: f.slug });+ const authority = await submissionAuthority({ engine, remote: false } as OperationContext, 'put_page', f.id, preview.preconditions.source_incarnation, f.slug);+ const reference = await retainReconcileBackup(engine, preview, authority.principal, randomUUID());+ await expect(runReconcileBackups(engine, { source_id: f.id, slug: f.slug, action: 'remove', backup_reference: reference })).rejects.toMatchObject({ code: 'permission_denied' });+ expect(existsSync(join(configDir(), 'reconciliation-previews', reference))).toBe(true);+ });+}), 120_000);++test('public warn-mode put_page rejects reserved reconciliation fields for local and remote callers before admission', async () => isolated(async engine => {+ const f = await fixture(engine);+ await engine.setConfig('mcp.strict_params', 'warn');+ const stdio = await registerLocalWriter(engine, 'stdio');+ for (const remote of [false, true]) for (const extra of [{ kind: 'canonical_reconcile' }, { preview: {} }, { backup_reference: 'private-backup' }]) {+ const result = await local(engine, remote ? stdio : f.registration, () => dispatchToolCall(engine, 'put_page', {+ source_id: f.id, slug: f.slug, content: 'A public caller observation.', expected_revision: f.snapshot.revision,+ request_id: randomUUID(), ...extra,+ }, { remote, sourceId: f.id, config: { engine: engine.kind }, auth: { token: 'fixture', clientId: 'fixture-client', scopes: ['read', 'write'], sourceId: f.id },+ logger: { info() {}, warn() {}, error() {} } }));+ expect(result.isError).toBe(true);+ expect(JSON.parse((result.content[0] as { text: string }).text)).toMatchObject({ error: 'invalid_params' });+ expect((result.content[0] as { text: string }).text).toContain('Reserved persistence fields');+ }+ expect(await engine.executeRaw('SELECT id FROM persistence_requests WHERE source_id=$1', [f.id])).toHaveLength(0);+}), 120_000);++test('a real ownership transfer to a matching successor invalidates an unadmitted preview without changing canonical content', async () => isolated(async engine => {+ for (const enabled of [false, true]) {+ const f = await fixture(engine, enabled), before = readFileSync(f.file);+ await local(engine, f.registration, async () => {+ const { preview } = await runReconcilePreview(engine, { source_id: f.id, slug: f.slug });+ const successor = join(home, `${f.id}-successor`), successorHost = randomUUID();+ cpSync(f.root, successor, { recursive: true });+ const transfer = await prepareWriterTransfer(engine, f.id);+ await acceptWriterTransfer(engine, f.id, successor, transfer.owner_epoch, transfer.manifest.digest, successorHost);+ const binding = (await getWorktreeBinding(engine, f.id, successorHost))!;+ expect(binding.owner_host_id).toBe(successorHost);+ expect(binding.local_path).toBe(successor);+ expect(Number(binding.owner_epoch)).toBe(Number(f.binding.owner_epoch) + 1);+ await expect(runReconcileApply(engine, { source_id: f.id, slug: f.slug, preview, request_id: randomUUID() })).rejects.toMatchObject({ code: 'owner_unavailable' });+ expect(readFileSync(f.file)).toEqual(before);+ expect(readFileSync(join(successor, 'notes/example.md'))).toEqual(before);+ expect(await engine.readPageSnapshot(f.slug, { sourceId: f.id })).toEqual(f.snapshot);+ expect(await engine.executeRaw('SELECT id FROM persistence_requests WHERE source_id=$1', [f.id])).toHaveLength(0);+ expect((await engine.executeRaw<{ enabled: boolean }>('SELECT enabled FROM persistence_brain WHERE singleton=1'))[0].enabled).toBe(enabled);+ });+ }+}), 120_000);++test('a publication holding the native root excludes real transfer until commit and preserves replay after transfer', async () => isolated(async engine => {+ for (const enabled of [false, true]) {+ const f = await fixture(engine, enabled), before = readFileSync(f.file);+ await local(engine, f.registration, async () => {+ const repair = await preparedRepair(engine, f);+ let release!: () => void, reached!: () => void;+ const held = new Promise<void>(resolve => { release = resolve; });+ const preparedBoundary = new Promise<void>(resolve => { reached = resolve; });+ const publication = publishMutation(engine, repair.row, repair.prepared, localHostId(), {+ boundary: async name => { if (name === 'prepared') { reached(); await held; } },+ });+ try {+ await preparedBoundary;+ const competingLock = await acquireWorktree(f.binding);+ if (competingLock) await competingLock.release();+ expect(competingLock).toBeNull();+ await expect(prepareWriterTransfer(engine, f.id)).rejects.toMatchObject({ code: 'write_pending' });+ const pending = (await getWriteRequest(engine, repair.authority.principal, repair.row.request_id))!;+ expect(pending.state).toBe('running');+ expect(pending.recovery).not.toBeNull();+ expect((await getWorktreeBinding(engine, f.id))?.state).toBe('active');+ expect(readFileSync(f.file)).toEqual(before);+ expect(await engine.readPageSnapshot(f.slug, { sourceId: f.id })).toEqual(f.snapshot);+ } finally { release(); await publication; }+ const committed = await publication;+ expect(committed.state).toBe('committed');+ const receipt = await runReconcileApply(engine, repair.params);+ const canonical = (await engine.readPageSnapshot(f.slug, { sourceId: f.id }))!;+ const repairedBytes = readFileSync(f.file);+ expect(reconcileCanonical(canonical.page, canonical.tags)).toEqual(repair.preview.result);+ const successor = join(home, `${f.id}-successor`), successorHost = randomUUID();+ cpSync(f.root, successor, { recursive: true });+ const transfer = await prepareWriterTransfer(engine, f.id);+ await acceptWriterTransfer(engine, f.id, successor, transfer.owner_epoch, transfer.manifest.digest, successorHost);+ expect((await getWorktreeBinding(engine, f.id, successorHost))?.owner_host_id).toBe(successorHost);+ expect(await runReconcileApply(engine, repair.params)).toEqual(receipt);+ expect(readFileSync(f.file)).toEqual(repairedBytes);+ expect(readFileSync(join(successor, 'notes/example.md'))).toEqual(repairedBytes);+ expect(await engine.readPageSnapshot(f.slug, { sourceId: f.id })).toEqual(canonical);+ expect(await engine.executeRaw('SELECT id FROM persistence_requests WHERE source_id=$1', [f.id])).toHaveLength(1);+ expect((await engine.executeRaw<{ enabled: boolean }>('SELECT enabled FROM persistence_brain WHERE singleton=1'))[0].enabled).toBe(enabled);+ });+ }+}), 120_000);++test('file and database edits after reconciliation preparation abort publication without overwriting the competing state', async () => isolated(async engine => {+ for (const enabled of [false, true]) for (const mutation of ['file', 'database']) {+ const f = await fixture(engine, enabled), originalBytes = readFileSync(f.file);+ await local(engine, f.registration, async () => {+ const repair = await preparedRepair(engine, f);+ const competingBytes = Buffer.from(`${originalBytes.toString('utf8')}\nA competing local file observation.\n`);+ if (mutation === 'file') writeFileSync(f.file, competingBytes);+ else await engine.transaction(tx => withCoordinatedWrite(tx, [f.id], () => tx.putPage(f.slug, {+ type: f.snapshot.page.type, title: f.snapshot.page.title, compiled_truth: 'A competing database observation.',+ timeline: f.snapshot.page.timeline, frontmatter: f.snapshot.page.frontmatter,+ }, { sourceId: f.id, expectedRevision: f.snapshot.revision })));+ const competingSnapshot = (await engine.readPageSnapshot(f.slug, { sourceId: f.id }))!;+ const result = await publishMutation(engine, repair.row, repair.prepared);+ expect(result.state).toBe('conflict');+ expect(result.error_code).toBe(mutation === 'file' ? 'source_changed' : 'revision_conflict');+ expect(readFileSync(f.file)).toEqual(mutation === 'file' ? competingBytes : originalBytes);+ expect(await engine.readPageSnapshot(f.slug, { sourceId: f.id })).toEqual(competingSnapshot);+ expect(competingSnapshot.revision === f.snapshot.revision).toBe(mutation === 'file');+ const receipt = (await getWriteRequest(engine, repair.authority.principal, repair.row.request_id))!;+ expect(receipt.recovery).toBeNull();+ expect(receipt.publication_started).toBe(false);+ expect(JSON.parse(readFileSync(join(configDir(), 'reconciliation-previews', repair.reference), 'utf8')).preview.preimages.file_base64).toBe(originalBytes.toString('base64'));+ });+ }+}), 120_000);++test('historical basename origins in separate slug directories remain distinct canonical files', async () => isolated(async engine => {+ for (const enabled of [false, true]) {+ const f = await fixture(engine, enabled), otherSlug = 'other/example', otherFile = join(f.root, 'other/example.md');+ mkdirSync(join(f.root, 'other'), { recursive: true });+ await engine.transaction(tx => withCoordinatedWrite(tx, [f.id], async () => {+ await tx.executeRaw('UPDATE pages SET source_path=$3 WHERE source_id=$1 AND slug=$2', [f.id, f.slug, 'example.md']);+ await tx.putPage(otherSlug, { type: 'note', title: 'Other example', compiled_truth: 'An independent historical basename page.',+ frontmatter: { independent: true }, source_path: 'example.md' }, { sourceId: f.id });+ }));+ const other = (await engine.readPageSnapshot(otherSlug, { sourceId: f.id }))!;+ writeFileSync(otherFile, serializePageToMarkdown(other.page, other.tags));+ const otherBytes = readFileSync(otherFile);+ await local(engine, f.registration, async () => {+ const result = await runReconcilePreview(engine, { source_id: f.id, slug: f.slug });+ expect(result).toMatchObject({ status: 'ready', relative_path: 'notes/example.md' });+ expect((await runReconcileApply(engine, { source_id: f.id, slug: f.slug, preview: result.preview, request_id: randomUUID() })).state).toBe('committed');+ expect(readFileSync(otherFile)).toEqual(otherBytes);+ const after = (await engine.readPageSnapshot(otherSlug, { sourceId: f.id }))!;+ expect(after.revision).toBe(other.revision);+ expect(reconcileCanonical(after.page, after.tags)).toEqual(reconcileCanonical(other.page, other.tags));+ expect(after.page.source_path).toBe(other.page.source_path);+ });+ }+}), 120_000);++test('shared provenance URI does not override distinct explicit canonical paths', async () => isolated(async engine => {+ for (const enabled of [false, true]) {+ const f = await fixture(engine, enabled), otherSlug = 'other/provenance', otherFile = join(f.root, 'other/provenance.md');+ const sharedUri = pathToFileURL(f.file).href;+ mkdirSync(join(f.root, 'other'), { recursive: true });+ await engine.transaction(tx => withCoordinatedWrite(tx, [f.id], async () => {+ await tx.executeRaw('UPDATE pages SET source_uri=$3 WHERE source_id=$1 AND slug=$2', [f.id, f.slug, sharedUri]);+ await tx.putPage(otherSlug, { type: 'note', title: 'Independent provenance', compiled_truth: 'A distinct file sharing ingestion provenance.',+ frontmatter: {}, source_path: 'other/provenance.md', source_uri: sharedUri }, { sourceId: f.id });+ }));+ const other = (await engine.readPageSnapshot(otherSlug, { sourceId: f.id }))!;+ writeFileSync(otherFile, serializePageToMarkdown(other.page, other.tags));+ const otherBytes = readFileSync(otherFile);+ await local(engine, f.registration, async () => {+ const { preview } = await runReconcilePreview(engine, { source_id: f.id, slug: f.slug });+ expect(preview.status).toBe('ready');+ expect((await runReconcileApply(engine, { source_id: f.id, slug: f.slug, preview, request_id: randomUUID() })).state).toBe('committed');+ expect(readFileSync(otherFile)).toEqual(otherBytes);+ const after = (await engine.readPageSnapshot(otherSlug, { sourceId: f.id }))!;+ expect(after.revision).toBe(other.revision);+ expect(reconcileCanonical(after.page, after.tags)).toEqual(reconcileCanonical(other.page, other.tags));+ expect(after.page.source_path).toBe(other.page.source_path);+ expect(after.page.source_uri).toBe(sharedUri);+ });+ }+}), 120_000);++test('genuine shared-file origins through explicit paths or URI fallback still refuse reconciliation', async () => isolated(async engine => {+ for (const enabled of [false, true]) for (const origin of ['path', 'dot-path', 'repeated-separators', 'uri']) {+ const f = await fixture(engine, enabled), raw = readFileSync(f.file), uri = pathToFileURL(f.file).href;+ await engine.transaction(tx => withCoordinatedWrite(tx, [f.id], async () => {+ const sourcePath = origin === 'uri' ? null : origin === 'dot-path' ? './notes/example.md'+ : origin === 'repeated-separators' ? 'notes//example.md' : 'notes/example.md';+ await tx.putPage('other/collision', { type: 'note', title: 'Collision', compiled_truth: 'Another page claiming the same file.',+ frontmatter: {}, source_path: sourcePath, source_uri: origin === 'uri' ? uri : null }, { sourceId: f.id });+ }));+ const snapshot = await engine.readPageSnapshot(f.slug, { sourceId: f.id });+ await local(engine, f.registration, async () => {+ await expect(runReconcilePreview(engine, { source_id: f.id, slug: f.slug })).rejects.toMatchObject({+ code: 'source_changed', message: 'Several pages claim the recorded canonical file.' });+ expect(readFileSync(f.file)).toEqual(raw);+ expect(await engine.readPageSnapshot(f.slug, { sourceId: f.id })).toEqual(snapshot);+ expect(await engine.executeRaw('SELECT id FROM persistence_requests WHERE source_id=$1', [f.id])).toHaveLength(0);+ });+ }+}), 120_000);++test('candidate-origin fanout stops at a bounded verification limit rather than scanning the source', async () => isolated(async engine => {+ const f = await fixture(engine), uri = pathToFileURL(f.file).href;+ await engine.transaction(tx => withCoordinatedWrite(tx, [f.id], async () => {+ await tx.executeRaw('UPDATE pages SET source_uri=$3 WHERE source_id=$1 AND slug=$2', [f.id, f.slug, uri]);+ await tx.executeRaw(`INSERT INTO pages(source_id,slug,type,title,compiled_truth,frontmatter,source_path,source_uri)+ SELECT $1,'other/candidate-'||n,'note','Independent origin','Independent candidate '||n,'{}'::jsonb,'other/candidate-'||n||'.md',$2+ FROM generate_series(1,101) n`, [f.id, uri]);+ }));+ await local(engine, f.registration, async () => {+ await expect(runReconcilePreview(engine, { source_id: f.id, slug: f.slug })).rejects.toMatchObject({+ code: 'source_changed', message: 'Too many candidate page origins to verify this exact file safely.' });+ expect(await engine.executeRaw('SELECT id FROM persistence_requests WHERE source_id=$1', [f.id])).toHaveLength(0);+ });+}), 120_000);diff --git a/test/persistence-sync-receipt-diagnostics.test.ts b/test/persistence-sync-receipt-diagnostics.test.tsnew file mode 100644index 0000000000..16e17df1dd--- /dev/null+++ b/test/persistence-sync-receipt-diagnostics.test.ts@@ -0,0 +1,104 @@+import { afterEach, expect, spyOn, test } from 'bun:test';+import { OperationError } from '../src/core/ops/contract.ts';+import { frozenVerbWriteError, runMemoryWrite, writeFailureDiagnostic } from '../src/core/persistence/verb-errors.ts';+import type { WriteReceipt } from '../src/core/persistence/types.ts';+import { reportPersistenceCliError, runDeferredPersistenceCommand } from '../src/commands/persistence-delegate.ts';+import { _resetCliExitVerdictForTests } from '../src/core/cli-force-exit.ts';+import { printSyncResult, type SyncResult } from '../src/commands/sync.ts';+import { ERROR_SCHEMA } from '../src/core/verbs.ts';+import { validateAgainstSchema } from '../src/core/verbs/conformance.ts';++const requestId = '20000000-0000-4000-8000-000000000001';+const receipt: WriteReceipt = { request_id: requestId, state: 'conflict', retry_after_ms: null };+const driftMessage = 'The canonical file contains an uncoordinated local edit.';+afterEach(() => { _resetCliExitVerdictForTests(); process.exitCode = 0; });++test('deferred reconciliation help does not acquire an engine', async () => {+ const log = spyOn(console, 'log').mockImplementation(() => {});+ try {+ await runDeferredPersistenceCommand('sources', ['reconcile', '--help'], async () => { throw new Error('Help must not connect.'); });+ expect(log.mock.calls.flat().join('\n')).toContain('sources reconcile');+ } finally { log.mockRestore(); }+});++test('file/database drift preserves v1 vocabulary and names reviewed repair without privilege escalation', async () => {+ const cause = new OperationError('source_changed', driftMessage);+ cause.writeError = 'source_changed';+ cause.writeRequest = receipt;+ let error: OperationError | undefined;+ try { await runMemoryWrite(async () => { throw cause; }); } catch (caught) { error = caught as OperationError; }+ const body = error!.toJSON();+ expect(body).toMatchObject({ error: 'scope_denied', protocol_version: 1, write_error: 'source_changed',+ detail: 'file_database_drift', write_request: receipt });+ expect(body.message).toContain('file and database disagree');+ expect(body.suggestion).toContain('gbrain sources reconcile');+ expect(body.suggestion).toContain('--preview');+ expect(body.suggestion).toContain('new request_id');+ expect(body.suggestion).not.toMatch(/sources writer (claim|activate|transfer)/);+ expect(validateAgainstSchema(body, ERROR_SCHEMA)).toEqual([]);+ await expect(runMemoryWrite(async () => { throw error; })).rejects.toBe(error);+});++test('pre-admission drift uses the same diagnosis without inventing a receipt', async () => {+ let error: OperationError | undefined;+ try { await runMemoryWrite(async () => { throw new OperationError('source_changed', driftMessage); }); }+ catch (caught) { error = caught as OperationError; }+ expect(error!.toJSON()).toMatchObject({ error: 'scope_denied', write_error: 'source_changed', detail: 'file_database_drift' });+ expect(error!.toJSON()).not.toHaveProperty('write_request');+});++test('human output leads with source_changed, JSON stays frozen and clean, both retain the request ID', async () => {+ const error = frozenVerbWriteError(receipt, 'source_changed', driftMessage);+ const stderr = spyOn(console, 'error').mockImplementation(() => {});+ let stdout = '';+ try {+ expect(await reportPersistenceCliError(error, true, async text => { stdout += text; })).toBe(true);+ expect(JSON.parse(stdout)).toMatchObject({ error: 'scope_denied', write_error: 'source_changed', write_request: receipt });+ const lines = stderr.mock.calls.map(args => args.join(' '));+ expect(lines[0]).toStartWith('Error [source_changed]:');+ expect(lines.join('\n')).toContain(`Request: ${requestId} (conflict)`);+ expect(stdout).not.toContain('Error [');+ } finally { stderr.mockRestore(); }+});++test.each(['queued', 'running', 'recovering'] as const)('%s cannot look committed or suggest a replacement request', state => {+ const body = frozenVerbWriteError({ ...receipt, state, retry_after_ms: 1000 }, 'write_pending').toJSON();+ expect(body.message).toContain('not committed');+ expect(body.suggestion).toContain(`same arguments and request_id ${requestId}`);+ expect(body.suggestion).toContain('Do not submit a new request_id');+ expect(body.write_request).not.toHaveProperty('revision');+});++test('unrecognized errors cannot echo private content, absolute paths, or credentials', () => {+ const privateMessage = '/private/source/example.md contains secret private fixture content with credential=redacted';+ for (const code of ['source_changed', 'storage_error', 'invalid_params', 'unknown_error']) {+ const detail = writeFailureDiagnostic(code, privateMessage);+ expect(JSON.stringify(detail)).not.toContain(privateMessage);+ expect(JSON.stringify(detail)).not.toContain('/private');+ expect(JSON.stringify(detail)).not.toContain('credential');+ }+ expect(writeFailureDiagnostic('source_changed', 'Newer working-tree bytes and the current page disagree with this pinned Git import.').reason)+ .toBe('pinned_git_worktree_conflict');+ expect(writeFailureDiagnostic('owner_unavailable').reason).toBe('owner_unavailable');+ expect(writeFailureDiagnostic('permission_denied').reason).toBe('permission_denied');+});++test.each(['blocked_by_failures', 'partial'] as const)('managed %s rendering uses the receipt instead of generic parse/skip advice', status => {+ const pending = status === 'partial';+ const result: SyncResult = { status, fromCommit: null, toCommit: '0123456789', added: 0, modified: 0, deleted: 0,+ renamed: 0, chunksCreated: 0, embedded: 0, pagesAffected: [], failedFiles: pending ? 0 : 1,+ managedWrite: { source_id: 'example-source', path: 'notes/example.md', slug: 'notes/example',+ write_error: pending ? 'write_pending' : 'source_changed', reason: pending ? 'write_pending' : 'file_database_drift',+ message: pending ? 'The accepted write is not committed.' : 'The file and database disagree.',+ suggestion: pending ? 'Resume this request.' : 'Review gbrain sources reconcile before retrying.',+ write_request: pending ? { ...receipt, state: 'queued', retry_after_ms: 1000 } : receipt, ledger_recorded: false } };+ let output = '';+ printSyncResult(result, { write: (text: string) => { output += text; return true; } } as NodeJS.WriteStream);+ expect(output).toContain('example-source');+ expect(output).toContain('notes/example.md');+ expect(output).toContain(requestId);+ expect(output).toContain('remains authoritative');+ expect(output).not.toContain('frontmatter validate');+ expect(output).not.toContain('sync --skip-failed');+ if (pending) { expect(output).toContain('not committed'); expect(output).not.toContain('First sync complete'); }+});diff --git a/test/persistence-sync-stdio-owner.serial.test.ts b/test/persistence-sync-stdio-owner.serial.test.tsindex 4bb160faeb..47fc826310 100644--- a/test/persistence-sync-stdio-owner.serial.test.ts+++ b/test/persistence-sync-stdio-owner.serial.test.ts@@ -4,7 +4,7 @@ import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync } from 'nodimport { tmpdir } from 'node:os';import { join } from 'node:path';import { PGLiteEngine } from '../src/core/pglite-engine.ts';-import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { claimWorktree, acquireWorktree, type WorktreeBinding } from '../src/core/persistence/ownership.ts';import { registerLocalWriter } from '../src/core/persistence/identity.ts';import { inspectLockHolder } from '../src/core/pglite-lock.ts';import { persistenceSocketPathForConfig, requestPersistenceCapabilities, requestPersistenceAdministration } from '../src/core/persistence/ipc.ts';@@ -18,8 +18,9 @@ const home=mkdtempSync(join(tmpdir(),'gbrain-stdio-sync-'));const root=join(home,'repo'), databasePath=join(home,'db');const config={engine:'pglite' as const,database_path:databasePath};const env={...process.env,GBRAIN_HOME:home,DATABASE_URL:undefined,GBRAIN_DATABASE_URL:undefined,GBRAIN_BRAIN_ID:'host',- GBRAIN_SOURCE:'workspace',GBRAIN_NO_BANNER:'1',GBRAIN_BACKUP_CHECK:'0',GBRAIN_SWEEP:'0',GBRAIN_SKIP_STARTUP_HOOKS:'1'};+ GBRAIN_SOURCE:'workspace',GBRAIN_NO_BANNER:'1',GBRAIN_BACKUP_CHECK:'0',GBRAIN_SWEEP:'0',GBRAIN_SKIP_STARTUP_HOOKS:'1',GBRAIN_SYNC_FAILURES_DIR:home};let setup:PGLiteEngine;+let sourceBinding:WorktreeBinding;let owner:ReturnType<typeof Bun.spawn>|undefined;let stdout='',stderr='';const readers:Promise<void>[]=[];@@ -53,7 +54,7 @@ beforeAll(async()=>{const code = 'export function residentExample() { return 4; }\n';writeFileSync(join(root,'example.ts'),code);await importCodeFile(setup,'example.ts',code,{sourceId:'workspace',noEmbed:true});- await claimWorktree(setup,'workspace',root);await registerLocalWriter(setup,'cli');await registerLocalWriter(setup,'stdio');+ sourceBinding=await claimWorktree(setup,'workspace',root);await registerLocalWriter(setup,'cli');await registerLocalWriter(setup,'stdio');await setup.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');await setup.disconnect();});owner=Bun.spawn([process.execPath,join(import.meta.dir,'fixtures/persistence-stdio-owner.ts')],{cwd:home,env,stdin:'pipe',stdout:'pipe',stderr:'pipe'});@@ -81,10 +82,82 @@ test('actual CLI sync and page reads delegate to a real non-serve stdio owner beexpect(inspectLockHolder(databasePath).pid).toBe(owner!.pid);},90000);+test('resident-owner failure JSON retains safe scoped diagnostics and the frozen receipt without a local ledger',async()=>{+ const path=join(root,'a.md');+ const pinned=execFileSync('git',['-C',root,'show','HEAD:a.md'],{encoding:'utf8'});+ const current=await cli(['call','get_page',JSON.stringify({slug:'a',source_id:'workspace'})]);+ expect(current.code).toBe(0);+ const updated=await cli(['call','put_page',JSON.stringify({slug:'a',source_id:'workspace',+ expected_revision:JSON.parse(current.out).revision,content:'A newer coordinated database observation.\n'})]);+ expect(updated.code).toBe(0);+ expect(JSON.parse(updated.out).state).toBe('committed');+ writeFileSync(path,'PRIVATE_RESIDENT_DIAGNOSTIC_CONTENT_CANARY\n');+ const args=['sync','--source','workspace','--full','--no-pull','--no-embed','--exclude','excluded.md','--exclude','example.ts','--json','--no-hard-deadline'];+ const blocked=await cli(args);+ expect(blocked.code).toBe(1);+ const body=JSON.parse(blocked.out);+ expect(body).toMatchObject({sync_status:'blocked_by_failures',managed_write:{source_id:'workspace',slug:'a',path:'a.md',+ write_error:'source_changed',reason:'pinned_git_worktree_conflict',write_request:{state:'conflict',retry_after_ms:null}}});+ const id=body.managed_write.write_request.request_id;+ expect(id).toMatch(/^[0-9a-f-]{36}$/);+ expect(blocked.err).toContain(id);+ expect(blocked.err).toContain('source_changed');+ expect(blocked.out+blocked.err).not.toContain('PRIVATE_RESIDENT_DIAGNOSTIC_CONTENT_CANARY');+ expect(blocked.out+blocked.err).not.toContain(root);+ writeFileSync(path,pinned);+ rmSync(join(home,'sync-failures.jsonl'),{force:true});+ const replay=await cli(args);+ expect(replay.code).toBe(1);+ expect(JSON.parse(replay.out).managed_write.write_request).toEqual(body.managed_write.write_request);+ const corrected=await cli([...args,'--retry-failed']);+ expect(corrected.code).toBe(0);+ expect(JSON.parse(corrected.out).sync_status).toBe('synced');+ const original=await cli(['call','get_write_request',JSON.stringify({request_id:id})]);+ expect(original.code).toBe(0);+ expect(JSON.parse(original.out)).toMatchObject({request_id:id,state:'conflict'});+ expect(inspectLockHolder(databasePath).pid).toBe(owner!.pid);+},90000);++test('resident-owner pending timeout exits nonzero and resumes the same durable request after lock release',async()=>{+ const path=join(root,'a.md');+ const content='A resident source observation waiting for the held worktree lock.\n';+ writeFileSync(path,content);+ const lock=await acquireWorktree(sourceBinding);+ expect(lock).not.toBeNull();+ let id:string;+ const args=['sync','--source','workspace','--full','--working-tree','--no-pull','--no-embed','--exclude','excluded.md','--exclude','example.ts','--json','--no-hard-deadline'];+ try {+ const pending=await cli([...args,'--timeout','1']);+ expect(pending.code).toBe(1);+ const body=JSON.parse(pending.out);+ expect(body).toMatchObject({sync_status:'partial',reason:'timeout',added:0,modified:0,+ managed_write:{source_id:'workspace',slug:'a',path:'a.md',write_error:'write_pending'}});+ id=body.managed_write.write_request.request_id;+ expect(body.managed_write.write_request.state).not.toBe('committed');+ expect(body.managed_write.write_request).not.toHaveProperty('revision');+ expect(pending.err).toContain(id);+ expect(pending.err).toContain('not committed');+ const before=await cli(['call','get_page',JSON.stringify({slug:'a',source_id:'workspace'})]);+ expect(before.code).toBe(0);+ expect(JSON.parse(before.out).compiled_truth).not.toContain('held worktree lock');+ } finally {await lock?.release();}+ const resumed=await cli(args);+ expect(resumed.code).toBe(0);+ expect(JSON.parse(resumed.out).sync_status).toBe('synced');+ const receipt=await cli(['call','get_write_request',JSON.stringify({request_id:id!})]);+ expect(receipt.code).toBe(0);+ expect(JSON.parse(receipt.out)).toMatchObject({request_id:id!,state:'committed'});+ expect(inspectLockHolder(databasePath).pid).toBe(owner!.pid);+},90000);+test('strict sync parsing retains filtering options and rejects runtime authority fields',async()=>{await withEnv(env,async()=>{expect((await parsePersistenceSyncArgs(['--source','workspace','--no-pull','--working-tree','--exclude','draft/**','--include-hidden','.notes/**','--no-hard-deadline'],home)).options).toMatchObject({sourceId:'workspace',noPull:true,workingTree:true,exclude:['draft/**'],includeHidden:['.notes/**']});+ expect((await parsePersistenceSyncArgs(['--timeout','2','--no-hard-deadline'],home)).timeoutSeconds).toBe(2);+ expect((await parsePersistenceSyncArgs(['--timeout','2','--hard-deadline','30'],home)).timeoutSeconds).toBe(2);+ expect((await parsePersistenceSyncArgs(['--timeout','30','--hard-deadline','2'],home)).timeoutSeconds).toBe(2);+ expect((await parsePersistenceSyncArgs(['--no-hard-deadline'],home)).timeoutSeconds).toBe(0);await expect(parsePersistenceSyncArgs(['--skipLock','--no-hard-deadline'],home)).rejects.toMatchObject({code:'invalid_params'});});});diff --git a/test/reconcile-audit.test.ts b/test/reconcile-audit.test.tsnew file mode 100644index 0000000000..c8dd8022e3--- /dev/null+++ b/test/reconcile-audit.test.ts@@ -0,0 +1,149 @@+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { parseMarkdown } from '../src/core/markdown.ts';+import { activatePersistence } from '../src/core/persistence/activation.ts';+import { registerLocalWriter, revokeLocalWriter } from '../src/core/persistence/identity.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { auditCanonicalSource, runReconcileAudit } from '../src/core/persistence/reconcile-audit.ts';+import { withEnv } from './helpers/with-env.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';++let engine: PGLiteEngine;+let version: string;+beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ version = (await engine.getConfig('version'))!;+}, 120_000);+afterAll(async () => { await engine.disconnect(); });++async function fixture(run: (root: string, source: string) => Promise<void>) {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-reconcile-audit-'));+ const root = join(home, 'canonical');+ mkdirSync(root);+ try {+ await withEnv({ GBRAIN_HOME: home, GBRAIN_SOURCE: undefined }, async () => {+ await resetPgliteState(engine);+ await engine.setConfig('version', version);+ const source = `audit-${randomUUID().slice(0, 8)}`;+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [source, root]);+ const content = '---\ntitle: Example\ntype: note\n---\nA synthetic observation.\n';+ for (const slug of ['a', 'b', 'c']) {+ const parsed = parseMarkdown(content, slug);+ await engine.putPage(slug, { ...parsed, source_path: `${slug}.md`, frontmatter: slug === 'b'+ ? { ...parsed.frontmatter, atoms_scan_hash: '0123456789abcdef', private_marker: 'fixture-value-not-in-output' } : parsed.frontmatter }, { sourceId: source });+ if (slug !== 'c') writeFileSync(join(root, `${slug}.md`), content);+ }+ await claimWorktree(engine, source, root);+ await registerLocalWriter(engine, 'cli');+ await run(root, source);+ });+ } finally { rmSync(home, { recursive: true, force: true }); }+}++test('bounded audit detects metadata drift and missing files without changing canonical state', () => fixture(async (root, source) => {+ const snapshot = await engine.readPageSnapshot('b', { sourceId: source });+ const bytes = readFileSync(join(root, 'b.md'), 'utf8');+ const before = await engine.executeRaw('SELECT last_commit,last_sync_at,incarnation FROM sources WHERE id=$1', [source]);+ const report = await runReconcileAudit(engine, { source_id: source });+ expect(report).toMatchObject({ source_id: source, inspected: 3, drifted: 2, errors: 0, complete: true, next_after: null, snapshot_only: true });+ expect(report.findings.map(row => row.slug)).toEqual(['b', 'c']);+ expect(JSON.stringify(report)).not.toContain('fixture-value-not-in-output');+ expect(JSON.stringify(report)).not.toContain(root);+ expect(await engine.readPageSnapshot('b', { sourceId: source })).toEqual(snapshot);+ expect(readFileSync(join(root, 'b.md'), 'utf8')).toBe(bytes);+ expect(await engine.executeRaw('SELECT last_commit,last_sync_at,incarnation FROM sources WHERE id=$1', [source])).toEqual(before);+ expect(await engine.executeRaw('SELECT request_id FROM persistence_requests')).toEqual([]);+}), 60_000);++test('audit cursor is bounded, explicit and not a source checkpoint', () => fixture(async (_root, source) => {+ const first = await runReconcileAudit(engine, { source_id: source, limit: 1 });+ expect(first).toMatchObject({ inspected: 1, drifted: 0, next_after: 'a', complete: false });+ const second = await runReconcileAudit(engine, { source_id: source, limit: 1, after: first.next_after });+ expect(second).toMatchObject({ inspected: 1, drifted: 1, next_after: 'b', complete: false });+ const third = await runReconcileAudit(engine, { source_id: source, limit: 1, after: second.next_after });+ expect(third).toMatchObject({ inspected: 1, drifted: 1, next_after: null, complete: true });+ await expect(runReconcileAudit(engine, { source_id: source, limit: 101 })).rejects.toMatchObject({ code: 'invalid_params' });+ await expect(runReconcileAudit(engine, { source_id: source, after: '../escape' })).rejects.toMatchObject({ code: 'invalid_params' });+}), 60_000);++test('activation dry-run reports drift without enabling or changing the source', () => fixture(async (_root, source) => {+ const report = await activatePersistence(engine, { confirmQuiesced: true, dryRun: true });+ expect(report).toMatchObject({ enabled: false, activated: false, drift_audit: { complete: true, snapshot_only: true } });+ expect(report.drift_audit?.sources).toEqual([expect.objectContaining({ source_id: source, drifted: 2 })]);+ expect(await engine.executeRaw('SELECT enabled FROM persistence_brain WHERE singleton=1')).toEqual([{ enabled: false }]);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ expect(await runReconcileAudit(engine, { source_id: source })).toMatchObject({ drifted: 2, errors: 0 });+}), 60_000);++test('audit refuses source and operation grant restrictions before disclosing a page', () => fixture(async (_root, source) => {+ await registerLocalWriter(engine, 'cli', { sourceIds: [source], scopes: ['read', 'write'], operations: ['get_page'], slugPrefixes: null }, true);+ await expect(runReconcileAudit(engine, { source_id: source })).rejects.toMatchObject({ code: 'permission_denied' });+ await registerLocalWriter(engine, 'cli', { sourceIds: [source], scopes: ['read', 'write'], operations: ['put_page'], slugPrefixes: ['a'] }, true);+ await expect(runReconcileAudit(engine, { source_id: source })).rejects.toMatchObject({ code: 'permission_denied' });+ await registerLocalWriter(engine, 'cli', { sourceIds: ['default'], scopes: ['read', 'write'], operations: ['put_page'], slugPrefixes: null }, true);+ await expect(runReconcileAudit(engine, { source_id: source })).rejects.toMatchObject({ code: 'permission_denied' });+}), 60_000);++test('revocation during audit prevents returning the result', () => fixture(async (_root, source) => {+ const registration = await registerLocalWriter(engine, 'cli');+ let revoked = false;+ const proxy = new Proxy(engine, { get(target, property) {+ if (property === 'readPageSnapshot') return async (...args: Parameters<BrainEngine['readPageSnapshot']>) => {+ const snapshot = await target.readPageSnapshot(...args);+ if (!revoked) { revoked = true; await revokeLocalWriter(engine, registration.id); }+ return snapshot;+ };+ const value = Reflect.get(target, property);+ return typeof value === 'function' ? value.bind(target) : value;+ } }) as BrainEngine;+ await expect(runReconcileAudit(proxy, { source_id: source })).rejects.toMatchObject({ code: 'permission_denied' });+}), 60_000);++test('audit never claims an owner for an unbound source', () => fixture(async (_root, source) => {+ await expect(auditCanonicalSource(engine, 'default')).rejects.toMatchObject({ code: 'owner_unavailable' });+ expect(await engine.executeRaw('SELECT source_id FROM persistence_source_bindings ORDER BY source_id')).toEqual([{ source_id: source }]);+}), 60_000);++test('audit without an existing host identity refuses without creating private state', () => fixture(async (_root, source) => {+ const otherHome = mkdtempSync(join(tmpdir(), 'gbrain-reconcile-read-only-'));+ try {+ await withEnv({ GBRAIN_HOME: otherHome }, async () => {+ await expect(auditCanonicalSource(engine, source)).rejects.toMatchObject({ code: 'owner_unavailable' });+ expect(existsSync(join(otherHome, '.gbrain'))).toBe(false);+ });+ } finally { rmSync(otherHome, { recursive: true, force: true }); }+}), 60_000);++test('large sources remain bounded to one requested audit page without canonical churn', () => fixture(async (root, source) => {+ for (const count of [1600, 6400]) {+ await engine.executeRaw(`INSERT INTO pages(source_id,slug,type,title,compiled_truth,timeline,frontmatter,content_hash,source_path)+ SELECT $1,'scale-'||lpad(n::text,5,'0'),'note','Example','A synthetic scale observation.','','{}'::jsonb,+ 'synthetic-scale-hash','scale-'||lpad(n::text,5,'0')||'.md'+ FROM generate_series(1,$2::integer) AS n ON CONFLICT(source_id,slug) DO NOTHING`, [source, count]);+ for (let index = 1; index <= 25; index++) {+ writeFileSync(join(root, `scale-${String(index).padStart(5, '0')}.md`), '---\ntitle: Example\ntype: note\n---\nA synthetic scale observation.\n');+ }+ let reads = 0;+ const proxy = new Proxy(engine, { get(target, property) {+ if (property === 'readPageSnapshot') return async (...args: Parameters<BrainEngine['readPageSnapshot']>) => {+ reads++;+ return target.readPageSnapshot(...args);+ };+ const value = Reflect.get(target, property);+ return typeof value === 'function' ? value.bind(target) : value;+ } }) as BrainEngine;+ const before = await engine.executeRaw('SELECT slug,knowledge_revision FROM pages WHERE source_id=$1 ORDER BY slug', [source]);+ const report = await runReconcileAudit(proxy, { source_id: source, limit: 25, after: 'c' });+ expect(report).toMatchObject({ inspected: 25, drifted: 0, errors: 0, next_after: 'scale-00025', complete: false });+ expect(reads).toBe(25);+ expect(await engine.executeRaw('SELECT slug,knowledge_revision FROM pages WHERE source_id=$1 ORDER BY slug', [source])).toEqual(before);+ expect(await engine.executeRaw('SELECT request_id FROM persistence_requests')).toEqual([]);+ }+}), 60_000);diff --git a/test/reconcile-cli.test.ts b/test/reconcile-cli.test.tsnew file mode 100644index 0000000000..f34bb85500--- /dev/null+++ b/test/reconcile-cli.test.ts@@ -0,0 +1,96 @@+import { afterEach, describe, expect, test } from 'bun:test';+import { mkdtempSync, readFileSync, readdirSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { parseReconcileArgs, readReconcileJson, writeReconcilePreview } from '../src/commands/source-reconcile.ts';++const directories: string[] = [];+function directory() {+ const path = mkdtempSync(join(tmpdir(), 'gbrain-reconcile-cli-'));+ directories.push(path);+ return path;+}+afterEach(() => { for (const path of directories.splice(0)) rmSync(path, { recursive: true, force: true }); });++describe('exact reconciliation CLI', () => {+ test('defaults to preview with explicit identities and keeps artifact paths off the wire', () => {+ expect(parseReconcileArgs(['workspace', 'people/example', '--brain', 'host', '--out', 'preview.json', '--json'])).toEqual({+ operation: 'writer_reconcile_preview', params: { source_id: 'workspace', slug: 'people/example' }, brain: 'host',+ output: 'preview.json', input: undefined, decisions: undefined, json: true,+ });+ expect(parseReconcileArgs(['workspace', 'people/example', '--preview', '--from=old.json', '--decisions=choices.json', '--out=new.json']))+ .toMatchObject({ operation: 'writer_reconcile_preview', input: 'old.json', decisions: 'choices.json', output: 'new.json' });+ });++ test('apply requires an explicit replay ID and cannot add preview decisions', () => {+ const requestId = '20000000-0000-4000-8000-000000000001';+ expect(parseReconcileArgs(['workspace', 'people/example', '--apply', 'ready.json', '--request-id', requestId]))+ .toMatchObject({ operation: 'writer_reconcile_apply', params: { source_id: 'workspace', slug: 'people/example', request_id: requestId }, input: 'ready.json' });+ for (const extra of [[], ['--request-id', 'invalid'], ['--request-id', requestId, '--out', 'other.json'],+ ['--request-id', requestId, '--preview'], ['--request-id', requestId, '--decisions', 'choices.json']]) {+ expect(() => parseReconcileArgs(['workspace', 'people/example', '--apply', 'ready.json', ...extra])).toThrow();+ }+ });++ test('rejects ambiguous identities, duplicate or unsupported flags and invalid modes', () => {+ for (const args of [[], ['workspace'], ['workspace', 'people/*'], ['workspace', '../example'], ['workspace', 'a', 'b'],+ ['workspace', 'a', '--force'], ['workspace', 'a', '--preview=false'], ['workspace', 'a', '--out'],+ ['workspace', 'a', '--out', 'one', '--out', 'two'], ['workspace', 'a', '--decisions', 'choices.json'],+ ['workspace', 'a', '--request-id', '20000000-0000-4000-8000-000000000001'],+ ['workspace', 'a', '--limit', '10'], ['workspace', '--audit', '--out', 'private.json']]) {+ expect(() => parseReconcileArgs(args)).toThrow();+ }+ });++ test('read-only audit requires one source with a bounded cursor', () => {+ expect(parseReconcileArgs(['workspace', '--audit', '--limit', '10', '--after', 'people/example']))+ .toMatchObject({ operation: 'writer_reconcile_audit', params: { source_id: 'workspace', limit: 10, after: 'people/example' } });+ for (const limit of ['0', '101', '1.5', 'NaN']) expect(() => parseReconcileArgs(['workspace', '--audit', '--limit', limit])).toThrow();+ expect(() => parseReconcileArgs(['workspace', 'a', '--audit'])).toThrow();+ });++ test('backup cleanup is explicit, exact-page and separate from every repair mode', () => {+ expect(parseReconcileArgs(['workspace', 'people/example', '--backups', '--limit', '2']))+ .toMatchObject({ operation: 'writer_reconcile_backups', params: { source_id: 'workspace', slug: 'people/example', action: 'list', limit: 2 } });+ expect(parseReconcileArgs(['workspace', 'people/example', '--remove-backup', 'exact-reference']))+ .toMatchObject({ operation: 'writer_reconcile_backups', params: { source_id: 'workspace', slug: 'people/example', action: 'remove', backup_reference: 'exact-reference' } });+ for (const extra of [['--preview'], ['--out', 'file.json'], ['--remove-backup', 'reference'], ['--after', 'not-a-uuid'], ['--audit']]) {+ expect(() => parseReconcileArgs(['workspace', 'people/example', '--backups', ...extra])).toThrow();+ }+ expect(() => parseReconcileArgs(['workspace', 'people/example', '--remove-backup', 'reference', '--limit', '2'])).toThrow();+ });+});++describe('private reconciliation artifact files', () => {+ test('writes complete JSON privately and refuses to replace existing output', () => {+ const dir = directory();+ const path = join(dir, 'preview.json');+ const preview = { format_version: 1, preimages: { file: 'synthetic original' } };+ writeReconcilePreview(path, preview);+ expect(readReconcileJson(path)).toEqual(preview);+ if (process.platform !== 'win32') expect(statSync(path).mode & 0o777).toBe(0o600);+ expect(() => writeReconcilePreview(path, { changed: true })).toThrow();+ expect(JSON.parse(readFileSync(path, 'utf8'))).toEqual(preview);+ expect(readdirSync(dir)).toEqual(['preview.json']);+ });++ test('rejects symbolic links, directories and malformed JSON without leaking content', () => {+ const dir = directory();+ const input = join(dir, 'input.json');+ writeFileSync(input, '{ synthetic-private-marker invalid');+ expect(() => readReconcileJson(input)).toThrow('not valid JSON');+ try { readReconcileJson(input); } catch (error) { expect(String(error)).not.toContain('synthetic-private-marker'); }+ symlinkSync(input, join(dir, 'alias.json'));+ expect(() => readReconcileJson(join(dir, 'alias.json'))).toThrow('regular JSON file');+ expect(() => readReconcileJson(dir)).toThrow();+ expect(() => writeReconcilePreview(join(dir, 'alias.json'), {})).toThrow();+ expect(readFileSync(input, 'utf8')).toContain('synthetic-private-marker');+ });++ test('refuses artifacts inside a claimed canonical worktree without creating a file', () => {+ const dir = directory();+ writeFileSync(join(dir, '.gbrain-owner.json'), JSON.stringify({ version: 1, managed: true }));+ expect(() => writeReconcilePreview(join(dir, 'preview.json'), {})).toThrow();+ expect(readdirSync(dir)).toEqual(['.gbrain-owner.json']);+ });+});diff --git a/test/reconcile-crash.slow.test.ts b/test/reconcile-crash.slow.test.tsnew file mode 100644index 0000000000..fed783aa89--- /dev/null+++ b/test/reconcile-crash.slow.test.ts@@ -0,0 +1,13 @@+import { expect, test } from 'bun:test';+import { CRASH_BOUNDARIES, runReconcileCrashCase } from './fixtures/reconcile-crash-worker.ts';++for (const enabled of [false, true]) for (const boundary of CRASH_BOUNDARIES) {+ test(`disk PGLite reconciliation survives SIGKILL/${boundary}, activation=${enabled}`, async () => {+ const result = await runReconcileCrashCase({ kind: 'pglite', boundary, enabled });+ expect(result).toMatchObject({ status: 'passed', boundary, enabled, killed_signal: 'SIGKILL',+ committed_requests: 1, added_versions: 1, normal_apply_replay: true, originals_retained: true,+ receipt_unchanged: true, recovery_cleared: true, staging_cleaned: true, topology_unchanged: true, counters_conserved: true });+ if (boundary === 'staging_flushed') expect(result.flushed_before_rename_verified).toBe(true);+ if (boundary === 'after_response') expect(result.response_read_before_kill).toBe(true);+ }, 180_000);+}diff --git a/test/reconcile-owner-journey.serial.test.ts b/test/reconcile-owner-journey.serial.test.tsnew file mode 100644index 0000000000..897746a6ad--- /dev/null+++ b/test/reconcile-owner-journey.serial.test.ts@@ -0,0 +1,282 @@+import { expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { parseMarkdown, serializePageToMarkdown } from '../src/core/markdown.ts';+import { parseFactsFence } from '../src/core/facts-fence.ts';+import { inspectLockHolder } from '../src/core/pglite-lock.ts';+import { claimWorktree, getWorktreeBinding } from '../src/core/persistence/ownership.ts';+import { registerLocalWriter } from '../src/core/persistence/identity.ts';+import { acquireNativeLock, type NativeLockHandle } from '../src/core/persistence/native-lock.ts';+import { persistenceSocketPathForConfig, requestPersistenceCapabilities } from '../src/core/persistence/ipc.ts';+import { runCli, type CliResult } from './helpers/cli-spawn.ts';+import { keylessBrainEnv, PROVIDER_ENV_KEYS } from './helpers/provider-env.ts';+import { withEnv } from './helpers/with-env.ts';+import { waitFor } from './helpers/wait-for.ts';++const slug = 'people/example';+const sourceId = 'workspace';+const body = 'A synthetic biography whose original bytes must stay out of the CLI summary.';+const fact = 'Prefers the example meeting room on Tuesdays';+const provenance = 'Synthetic operator conversation, reconciliation journey';++async function topology(engine: PGLiteEngine) {+ return {+ brain: await engine.executeRaw('SELECT brain_id,enabled FROM persistence_brain'),+ binding: await getWorktreeBinding(engine, sourceId),+ sources: await engine.executeRaw('SELECT id,incarnation,local_path,last_commit,last_sync_at,config FROM sources ORDER BY id'),+ checkpoints: await engine.executeRaw('SELECT * FROM op_checkpoints ORDER BY op,fingerprint'),+ checkpointPaths: await engine.executeRaw('SELECT * FROM op_checkpoint_paths ORDER BY op,fingerprint,path'),+ writers: await engine.executeRaw('SELECT id,lane,grant_ceiling,revoked_at FROM persistence_local_writers ORDER BY id'),+ };+}++function success(result: CliResult): Record<string, any> {+ if (result.exitCode !== 0) throw new Error(`CLI exited ${result.exitCode}\n${result.stderr}\n${result.stdout}`);+ return JSON.parse(result.stdout);+}++function privateSummary(result: CliResult) {+ expect(result.stdout).not.toContain(body);+ expect(result.stdout).not.toContain('database-only-private-value');+ expect(result.stdout).not.toContain('file-only-private-value');+ expect(result.stdout).not.toContain('file_base64');+ expect(result.stdout).not.toContain('preimages');+ expect(result.stdout).not.toContain('compiled_truth');+}++for (const transport of ['stdio', 'http'] as const) {+ for (const enabled of [false, true]) {+ test(`${transport} resident owner: preview, resolve, pending/restart/replay, and independent remember readback with activation ${enabled ? 'on' : 'off'}`, async () => {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-reconcile-owner-'));+ const root = join(home, 'workspace');+ const file = join(root, 'people/example.md');+ const config = { engine: 'pglite' as const, database_path: join(home, 'db') };+ const env = keylessBrainEnv(process.env, home, {+ DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined, GBRAIN_DIRECT_DATABASE_URL: undefined,+ GBRAIN_REMOTE_CLIENT_SECRET: undefined, GBRAIN_BRAIN_ID: 'host', GBRAIN_SOURCE: sourceId,+ GBRAIN_HOOKS: undefined, GBRAIN_SWEEP: '0', GBRAIN_BACKUP_CHECK: '0', GBRAIN_NO_BANNER: '1',+ GBRAIN_SKIP_STARTUP_HOOKS: '1', GBRAIN_SERVE_BOOT_TIMEOUT_SECONDS: '120',+ });+ const isolatedEnv: Record<string, string | undefined> = { ...env,+ ...Object.fromEntries([...PROVIDER_ENV_KEYS, 'DATABASE_URL', 'GBRAIN_DATABASE_URL', 'GBRAIN_DIRECT_DATABASE_URL',+ 'GBRAIN_REMOTE_CLIENT_SECRET', 'GBRAIN_HOOKS'].map(key => [key, undefined])) };+ let owner: ReturnType<typeof Bun.spawn> | undefined;+ let ownerStdout = '', ownerStderr = '';+ let readers: Promise<void>[] = [];+ const held: { lock: NativeLockHandle | null } = { lock: null };+ const engine = new PGLiteEngine();+ const cli = (args: string[]) => runCli(args, { home, cwd: home, env: isolatedEnv, timeoutMs: 60_000 });+ const call = (operation: string, params: Record<string, unknown>) => cli([+ '--brain', 'host', 'call', '--source', sourceId, operation, JSON.stringify({ source_id: sourceId, ...params }),+ ]);+ const reconcile = (args: string[]) => cli(['sources', 'reconcile', sourceId, slug, '--brain', 'host', '--json', ...args]);+ async function drain(stream: ReadableStream<Uint8Array>, append: (value: string) => void) {+ const reader = stream.getReader(), decoder = new TextDecoder();+ try {+ for (;;) {+ const { done, value } = await reader.read();+ if (done) return;+ append(decoder.decode(value, { stream: true }));+ }+ } finally { reader.releaseLock(); }+ }+ async function stop() {+ if (owner?.exitCode === null) {+ owner.kill('SIGTERM');+ const timer = setTimeout(() => owner?.kill('SIGKILL'), 15_000);+ try { await owner.exited; } finally { clearTimeout(timer); }+ }+ await Promise.allSettled(readers);+ }+ async function start() {+ ownerStdout = ''; ownerStderr = '';+ const reservation = transport === 'http' ? Bun.serve({ hostname: '127.0.0.1', port: 0, fetch: () => new Response() }) : undefined;+ const port = reservation?.port;+ await reservation?.stop(true);+ const args = transport === 'stdio'+ ? [join(import.meta.dir, 'fixtures/persistence-stdio-owner.ts')]+ : [join(import.meta.dir, '../src/cli.ts'), 'serve', '--http', '--bind', '127.0.0.1', '--port', String(port)];+ owner = Bun.spawn([process.execPath, '--no-env-file', ...args], {+ cwd: home, env, stdin: 'pipe', stdout: 'pipe', stderr: 'pipe',+ });+ readers = [drain(owner.stdout as ReadableStream<Uint8Array>, text => { ownerStdout += text; }),+ drain(owner.stderr as ReadableStream<Uint8Array>, text => { ownerStderr += text; })];+ await waitFor(async () => {+ if (owner!.exitCode !== null) throw new Error(`Owner exited before readiness: ${ownerStderr}`);+ try {+ await requestPersistenceCapabilities(persistenceSocketPathForConfig(config)!, 500);+ return transport === 'stdio' || (await fetch(`http://127.0.0.1:${port}/health`, { signal: AbortSignal.timeout(1000) })).ok;+ } catch { return false; }+ }, { timeoutMs: 90_000, intervalMs: 50, label: `${transport} owner ready` });+ if (transport === 'stdio') {+ (owner.stdin as { write: (value: string) => unknown }).write(JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'initialize',+ params: { protocolVersion: '2024-11-05', capabilities: {}, clientInfo: { name: 'reconcile-example-test', version: '1' } } }) + '\n');+ await waitFor(() => ownerStdout.split('\n').some(line => {+ try { return JSON.parse(line).id === 1; } catch { return false; }+ }), { timeoutMs: 15_000, label: 'stdio initialize response' });+ }+ expect(inspectLockHolder(config.database_path).pid).toBe(owner.pid);+ }++ try {+ await withEnv(isolatedEnv, async () => {+ mkdirSync(join(home, '.gbrain'), { recursive: true });+ mkdirSync(join(root, 'people'), { recursive: true });+ writeFileSync(join(home, '.gbrain/config.json'), JSON.stringify(config));+ await engine.connect(config); await engine.initSchema();+ await engine.setConfig('search.mcp_keyword_only', 'true');+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,last_commit,last_sync_at,config) VALUES($1,$1,$2,'example-checkpoint',now(),'{\"fixture\":true}')", [sourceId, root]);+ await engine.executeRaw("INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES('reconcile-owner-example','fixture','[\"already-completed\"]')");+ await engine.executeRaw("INSERT INTO op_checkpoint_paths(op,fingerprint,path) VALUES('reconcile-owner-example','fixture','already-completed.md')");+ await importFromContent(engine, slug, `---\ntype: person\ntitle: Example\nprofile:\n role: database-role\n database_field: database-only-private-value\ncustom_database: retained\nobsolete_note: remove-after-review\n---\n${body}\n`,+ { sourceId, sourcePath: 'people/example.md', noEmbed: true });+ await importFromContent(engine, slug, '---\ntype: person\ntitle: Other Example\n---\nAn unrelated source must remain unchanged.\n',+ { sourceId: 'default', sourcePath: 'people/example.md', noEmbed: true });+ const original = (await engine.readPageSnapshot(slug, { sourceId }))!;+ const otherSource = (await engine.readPageSnapshot(slug, { sourceId: 'default' }))!;+ await engine.executeRaw("UPDATE pages SET frontmatter=frontmatter || $3::text::jsonb WHERE source_id=$1 AND slug=$2",+ [sourceId, slug, JSON.stringify({ atoms_scan_hash: original.page.content_hash!.slice(0, 16) })]);+ const databaseBefore = (await engine.readPageSnapshot(slug, { sourceId }))!;+ writeFileSync(file, serializePageToMarkdown({ ...original.page, frontmatter: {+ profile: { role: 'file-role', file_field: 'file-only-private-value' }, custom_file: 'retained',+ } }, original.tags));+ const originalBytes = readFileSync(file);+ const binding = await claimWorktree(engine, sourceId, root);+ await registerLocalWriter(engine, 'cli'); await registerLocalWriter(engine, 'stdio');+ await engine.executeRaw('UPDATE persistence_brain SET enabled=$1 WHERE singleton=1', [enabled]);+ const beforeTopology = await topology(engine);+ await engine.disconnect();+ await start();++ const blockedId = randomUUID();+ const memoryParams = { fact, provenance, entity: slug, visibility: 'private' };+ const blocked = await call('remember', { ...memoryParams, request_id: blockedId });+ expect(blocked.exitCode).toBe(1);+ const blockedError = JSON.parse(blocked.stdout);+ expect(blockedError).toMatchObject({ error: 'scope_denied', write_error: 'source_changed', write_request: { request_id: blockedId } });+ expect(readFileSync(file)).toEqual(originalBytes);++ const previewPath = join(home, 'preview.json');+ const previewResult = await reconcile(['--preview', '--out', previewPath]);+ expect(success(previewResult)).toMatchObject({ source_id: sourceId, slug, status: 'needs_resolution',+ conflict_paths: ['/frontmatter/profile/role'], relative_path: 'people/example.md' });+ privateSummary(previewResult);+ expect(statSync(previewPath).mode & 0o777).toBe(0o600);+ const preview = JSON.parse(readFileSync(previewPath, 'utf8'));+ expect(preview.preimages.file_base64).toBe(originalBytes.toString('base64'));+ expect(readFileSync(file)).toEqual(originalBytes);+ expect(success(await call('get_page', { slug })).revision).toBe(databaseBefore.revision);++ const decisionsPath = join(home, 'decisions.json'), resolvedPath = join(home, 'resolved.json');+ writeFileSync(decisionsPath, JSON.stringify([+ { path: '/frontmatter/profile/role', action: 'take_file' },+ { path: '/frontmatter/obsolete_note', action: 'delete' },+ ]));+ const resolvedResult = await reconcile(['--preview', '--from', previewPath, '--decisions', decisionsPath, '--out', resolvedPath]);+ expect(success(resolvedResult)).toMatchObject({ source_id: sourceId, slug, status: 'ready', conflict_paths: [] });+ privateSummary(resolvedResult);+ const resolved = JSON.parse(readFileSync(resolvedPath, 'utf8'));+ expect(resolved.result.frontmatter).toMatchObject({ custom_database: 'retained', custom_file: 'retained',+ profile: { role: 'file-role', database_field: 'database-only-private-value', file_field: 'file-only-private-value' } });+ expect(resolved.result.frontmatter.obsolete_note).toBeUndefined();+ expect(resolved.result.frontmatter.atoms_scan_hash).toBeUndefined();++ const reconcileId = randomUUID();+ const applyArgs = ['--apply', resolvedPath, '--request-id', reconcileId];+ held.lock = await acquireNativeLock(binding.coordination_path!, { timeoutMs: 1000 });+ expect(held.lock).not.toBeNull();+ const pending = await reconcile(applyArgs);+ expect(pending.exitCode).toBe(1);+ expect(JSON.parse(pending.stdout)).toMatchObject({ error: 'write_pending', write_request: { request_id: reconcileId } });+ expect(JSON.parse(pending.stdout).write_request.state).not.toBe('committed');+ privateSummary(pending);+ expect(readFileSync(file)).toEqual(originalBytes);+ const pendingReceipt = success(await call('get_write_request', { request_id: reconcileId }));+ expect(pendingReceipt.request_id).toBe(reconcileId);+ expect(pendingReceipt.state).not.toBe('committed');+ const pendingReplay = await reconcile(applyArgs);+ expect(pendingReplay.exitCode).toBe(1);+ expect(JSON.parse(pendingReplay.stdout)).toMatchObject({ error: 'write_pending', write_request: {+ request_id: reconcileId, created_at: pendingReceipt.created_at,+ } });+ expect(readFileSync(file)).toEqual(originalBytes);+ await stop();+ await held.lock!.release(); held.lock = null;+ await start();++ const appliedResult = await reconcile(applyArgs), applied = success(appliedResult);+ expect(applied).toMatchObject({ request_id: reconcileId, state: 'committed', outcome: { status: 'reconciled',+ database_changed: true, file_changed: true, scan_state_transferred: false } });+ privateSummary(appliedResult);+ const page = success(await call('get_page', { slug }));+ expect(page.source_id).toBe(sourceId);+ expect(page.frontmatter).toEqual(resolved.result.frontmatter);+ expect(parseMarkdown(readFileSync(file, 'utf8'), slug).frontmatter).toEqual(page.frontmatter);+ const backupDir = join(home, '.gbrain/reconciliation-previews');+ const backupPath = join(backupDir, applied.outcome.backup_reference);+ const backupBytes = readFileSync(backupPath);+ const backup = JSON.parse(backupBytes.toString());+ expect(backup.preview.preimages.file_base64).toBe(originalBytes.toString('base64'));+ expect(backup.preview.preimages.database.page.frontmatter).toEqual(databaseBefore.page.frontmatter);+ expect(statSync(backupPath).mode & 0o777).toBe(0o600);+ expect(statSync(backupDir).mode & 0o777).toBe(0o700);+ const backupFiles = readdirSync(backupDir);+ expect(backupFiles.filter(name => name.endsWith('.json'))).toEqual([applied.outcome.backup_reference]);++ const memoryId = randomUUID();+ expect(new Set([blockedId, reconcileId, memoryId]).size).toBe(3);+ const remembered = success(await call('remember', { ...memoryParams, request_id: memoryId }));+ expect(remembered).toMatchObject({ status: 'inserted', state: 'committed', request_id: memoryId,+ entity_slug: slug, protocol_version: 1 });+ const readback = success(await call('get_page', { slug }));+ expect(readback.source_id).toBe(sourceId);+ expect(parseFactsFence(readback.compiled_truth).facts).toEqual(expect.arrayContaining([+ expect.objectContaining({ claim: fact, visibility: 'private', source: provenance }),+ ]));+ const rememberedBytes = readFileSync(file);+ expect(parseMarkdown(rememberedBytes.toString(), slug).compiled_truth).toBe(readback.compiled_truth);+ const replay = success(await reconcile(applyArgs));+ expect(replay).toEqual(applied);+ expect(readFileSync(file)).toEqual(rememberedBytes);+ expect(readFileSync(backupPath)).toEqual(backupBytes);+ expect(readdirSync(backupDir)).toEqual(backupFiles);+ expect(success(await call('get_write_request', { request_id: reconcileId }))).toMatchObject({+ request_id: reconcileId, state: 'committed', outcome: applied.outcome,+ });+ expect(inspectLockHolder(config.database_path).pid).toBe(owner!.pid);+ await stop();++ await engine.connect(config);+ expect(await topology(engine)).toEqual(beforeTopology);+ expect(await engine.readPageSnapshot(slug, { sourceId: 'default' })).toEqual(otherSource);+ const durable = (await engine.readPageSnapshot(slug, { sourceId }))!;+ const parsedFile = parseMarkdown(readFileSync(file, 'utf8'), slug);+ expect(durable.page.frontmatter).toEqual(resolved.result.frontmatter);+ expect(parsedFile.frontmatter).toEqual(durable.page.frontmatter);+ expect(parsedFile.compiled_truth).toBe(durable.page.compiled_truth);+ expect(await engine.executeRaw('SELECT fact,source_id,source,visibility,entity_slug,source_markdown_slug FROM facts WHERE id=$1', [Number(remembered.id)]))+ .toEqual([{ fact, source_id: sourceId, source: provenance, visibility: 'private', entity_slug: slug, source_markdown_slug: slug }]);+ expect(await engine.executeRaw('SELECT id FROM facts WHERE source_id=$1 AND fact=$2', [sourceId, fact])).toHaveLength(1);+ expect(await engine.executeRaw('SELECT request_id,state,error_code FROM persistence_requests WHERE request_id=$1::uuid', [blockedId]))+ .toEqual([{ request_id: blockedId, state: blockedError.write_request.state, error_code: 'source_changed' }]);+ expect(await engine.executeRaw('SELECT request_id,operation,source_id,slug,state FROM persistence_requests WHERE request_id IN ($1::uuid,$2::uuid) ORDER BY operation',+ [reconcileId, memoryId])).toEqual([+ { request_id: reconcileId, operation: 'put_page', source_id: sourceId, slug, state: 'committed' },+ { request_id: memoryId, operation: 'remember', source_id: sourceId, slug, state: 'committed' },+ ]);+ expect(await engine.executeRaw('SELECT tombstoned FROM extract_atoms_page_state WHERE page_id=$1', [durable.page.id])).toEqual([]);+ await engine.disconnect();+ });+ } finally {+ await held.lock?.release();+ await stop();+ await engine.disconnect();+ rmSync(home, { recursive: true, force: true });+ }+ }, 240_000);+ }+}diff --git a/test/sync-json-stdout-clean.test.ts b/test/sync-json-stdout-clean.test.tsindex 8651da9ab5..6d9bedb2b9 100644--- a/test/sync-json-stdout-clean.test.ts+++ b/test/sync-json-stdout-clean.test.ts@@ -17,6 +17,9 @@ import { join } from 'node:path';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';import { withEnv } from './helpers/with-env.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';let engine: PGLiteEngine;let repoPath: string;@@ -50,7 +53,7 @@ afterAll(async () => {});/** runSync with stdout and stderr split-captured (console.* AND the raw streams). */-async function run(args: string[]): Promise<{ stdout: string[]; stderr: string[] }> {+async function run(args: string[], expectedExit?: number): Promise<{ stdout: string[]; stderr: string[] }> {const { runSync } = await import('../src/commands/sync.ts');const stdout: string[] = [];const stderr: string[] = [];@@ -60,16 +63,19 @@ async function run(args: string[]): Promise<{ stdout: string[]; stderr: string[]const origOut = process.stdout.write.bind(process.stdout);const origErrWrite = process.stderr.write.bind(process.stderr);const origExit = process.exit;+ let exitCode: number | undefined;console.log = (...a: unknown[]) => { stdout.push(a.map(str).join(' ') + '\n'); };console.error = (...a: unknown[]) => { stderr.push(a.map(str).join(' ') + '\n'); };process.stdout.write = ((c: unknown) => { stdout.push(String(c)); return true; }) as typeof process.stdout.write;process.stderr.write = ((c: unknown) => { stderr.push(String(c)); return true; }) as typeof process.stderr.write;- process.exit = ((code?: number) => { throw new Error(`__exit__${code}`); }) as typeof process.exit;+ process.exit = ((code?: number) => { exitCode = code; throw new Error(`__exit__${code}`); }) as typeof process.exit;try {await withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home, GBRAIN_SOURCE: undefined, GBRAIN_ALLOW_DEFAULT_WRITE: undefined },() => runSync(engine, args),);+ } catch (error) {+ if (expectedExit === undefined || exitCode !== expectedExit || !(error instanceof Error) || error.message !== `__exit__${expectedExit}`) throw error;} finally {process.exit = origExit;console.log = origLog;@@ -77,6 +83,7 @@ async function run(args: string[]): Promise<{ stdout: string[]; stderr: string[]process.stdout.write = origOut;process.stderr.write = origErrWrite;}+ if (expectedExit !== undefined) expect(exitCode).toBe(expectedExit);return { stdout, stderr };}@@ -135,7 +142,8 @@ describe('#4888: sync --json keeps stdout pure JSON', () => {rmSync(join(home, 'sync-failures.jsonl'), { force: true });const { stdout, stderr } = await run(['--retry-failed', '--dry-run', '--no-pull', '--no-embed', '--json']);for (const l of lines(stdout)) expect(() => JSON.parse(l)).not.toThrow();- expect(stderr.join('')).toContain('No unacknowledged sync failures to retry.');+ expect(stderr.join('')).toContain('No local ledger entries; checking the durable sync cursor');+ expect(stderr.join('')).not.toContain('No unacknowledged sync failures to retry.');}, 60_000);test('--retry-failed --json with a pending failure: the "Retrying N" line is stderr, stdout parses', async () => {@@ -183,6 +191,42 @@ describe('#4888: sync --json keeps stdout pure JSON', () => {expect(out).toHaveLength(1);expect(typeof JSON.parse(out[0]).job_id).toBe('number');}, 60_000);++ test('managed failures keep one clean JSON receipt with scoped diagnostics even without a ledger', async () => {+ await run(['--no-pull', '--no-embed']);+ await withEnv({ GBRAIN_HOME: home }, () => claimWorktree(engine, 'default', repoPath));+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ try {+ writeFileSync(join(repoPath, 'topics/foo.md'), FOO('A new committed source observation.'));+ execSync('git add -A && git commit -q -m diagnostic-fixture', { cwd: repoPath, stdio: 'pipe' });+ writeFileSync(join(repoPath, 'topics/foo.md'), FOO('PRIVATE_DIAGNOSTIC_CONTENT_CANARY'));+ rmSync(join(home, 'sync-failures.jsonl'), { force: true });+ const { stdout, stderr } = await run(['--retry-failed', '--no-pull', '--no-embed', '--json']);+ const out = lines(stdout);+ expect(out).toHaveLength(1);+ const body = JSON.parse(out[0]);+ expect(body).toMatchObject({ sync_status: 'blocked_by_failures', managed_write: {+ source_id: 'default', slug: 'topics/foo', path: 'topics/foo.md', write_error: 'source_changed',+ reason: 'pinned_git_worktree_conflict', write_request: { state: 'conflict' },+ } });+ expect(body.managed_write.write_request.request_id).toMatch(/^[0-9a-f-]{36}$/);+ expect(stderr.join('')).toContain(body.managed_write.write_request.request_id);+ expect(stderr.join('')).toContain('No local ledger entries; checking the durable sync cursor');+ expect(stderr.join('')).not.toContain('No unacknowledged sync failures');+ expect([...stdout, ...stderr].join('')).not.toContain('PRIVATE_DIAGNOSTIC_CONTENT_CANARY');+ expect(out[0]).not.toContain(repoPath);+ expect(currentExitCode()).toBe(1);+ const all = await run(['--all', '--serial', '--no-pull', '--no-embed', '--json'], 1);+ const aggregate = JSON.parse(all.stdout.join(''));+ expect(aggregate).toMatchObject({ ok_count: 0, error_count: 1, sources: [{ source_id: 'default', status: 'error',+ managed_write: { write_request: { request_id: body.managed_write.write_request.request_id } } }] });+ expect(all.stderr.join('')).toContain(body.managed_write.write_request.request_id);+ } finally {+ _resetCliExitVerdictForTests(); process.exitCode = 0;+ await withEnv({ GBRAIN_HOME: home }, () => disposePersistenceConsumer(engine));+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ }+ }, 60_000);});/** One open ledger row for the default source (the shape sync-failure-ledger writes). */