Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
v0.60.5.0 fix wave 2: stop data loss, unwedge managed brains, end paid loops, fix search and connectors (#5689)
Garry Tan6e1e82628607
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 2ae810908e..c6c855c2cb 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.59.20.0",+ "version": "0.60.5.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 b12fbc6d80..a1fef08594 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.59.20.0",+ "version": "0.60.5.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/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.mdindex bbb14395c4..328bc98466 100644--- a/BOOTSTRAP_FOR_AGENTS.md+++ b/BOOTSTRAP_FOR_AGENTS.md@@ -1,4 +1,4 @@-<!-- gbrain-runbook-stamp: 0.59.20.0 -->+<!-- gbrain-runbook-stamp: 0.60.5.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 59e4781445..09228311e7 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,123 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [0.60.5.0] - 2026-09-29++**Your brain stops deleting history it can't see, managed brains stop wedging themselves, and background loops stop spending money and connections on nothing.**++This release rolls up a long list of quiet failures. The worst one: saving a page used to delete any timeline entry that lived only in the database, with no bullet in the page itself. That is fixed, those entries are now written back into their pages, and remote agents can no longer read atoms or concepts extracted from private pages.++Managed brains had several ways to get permanently stuck: a file with no `type:` line, a source inside a Git subfolder, a Mac that got a new disk number after a reboot, a sync started by hand that autopilot could not finish, a `capture --file` path, a page stored only in the database, or simply running out of write room after a few weeks. Each of those now recovers on its own or tells you the exact command to run.++Dream stops paying for the same transcripts every cycle, and after three failures in a day it stops trying a failing input until you reset it. An idle `gbrain serve` stops holding Postgres connections open, big local imports stop freezing, index rebuilds keep vectors that are still correct, and claude.ai and ChatGPT connectors can finish connecting.++**Back up first, and upgrade every writer.** Any gbrain process still on an older version keeps deleting database-only timeline history each time it republishes a page. That includes `gbrain serve`, autopilot and job workers, session hooks and every global CLI install. This release cannot restore entries that were already deleted; recovering them needs a database backup taken before the loss. A Markdown export does not include these entries.++| Situation | Before | After |+| --- | --- | --- |+| Page with database-only timeline entries is saved | Entries deleted | Entries kept and written back as marked bullets |+| Remote read of an atom from a private page | Returned | Hidden |+| File with no `type:` line, managed write | Refused forever | Written |+| Source in a Git subfolder after the first write-through | Sync failed forever | Syncs |+| Busy managed brain after a few weeks | Every write refused | Defaults last a year at 600 writes a day |+| One Git backup target keeps failing | Every later page stalled | Set aside after five failures; the rest commit |+| Synthesis model skips a transcript | Failed, re-billed next cycle | Completes |+| Dream input that died 3 times in 24 hours | Retried and paid for every cycle | Refused until reset |+| Idle `serve` behind transaction-mode PgBouncer | 7 connections held | 1 |+| PGLite import of 40 KB pages, one process | Froze at page 1,183 | 3,000 pages, WAL stayed under 269 MB |+| Rebuild of an unchanged title-mode page | Every vector erased | Every vector kept |+| ChatGPT connector sending the site root | Endless reconnect loop | Connects |++### To take advantage of v0.60.5.0++`gbrain upgrade` should do this automatically. If it didn't, or if `gbrain doctor` warns about a partial migration:++1. **Back up the database itself before upgrading:** `pg_dump` for Postgres, or a copy of the PGLite data directory made while gbrain is stopped.+2. **Upgrade every machine that writes to the brain** and restart `gbrain serve`, autopilot, job supervisors and session hooks, so no older writer keeps running.+3. **Run the orchestrator manually if schema work did not finish.** Migrations 170 to 173 add one column and three indexes.+ ```bash+ gbrain apply-migrations --yes --no-autopilot-install+ ```+4. **Your agent reads `skills/migrations/v0.60.5.0.md` the next time you interact with it.** It runs one full doctor pass, relays the new warnings and walks you through the repairs below. Show the preview before applying anything.+ ```bash+ gbrain doctor --json+ gbrain repair+ gbrain repair timeline --apply+ gbrain repair visibility --apply+ gbrain repair safe-chunks --apply+ ```+5. **Reconnect remote connectors if they misbehaved.** Remove and re-add a claude.ai connector stuck read-only; reconnect a looping ChatGPT connector.+6. **Verify the outcome:**+ ```bash+ gbrain --version+ gbrain repair --json+ gbrain dream reset-key --list+ gbrain sources writer status+ ```+7. **If any step fails or the numbers look wrong,** please file an issue:+ https://github.com/garrytan/gbrain/issues with:+ - output of `gbrain doctor`+ - contents of `~/.gbrain/upgrade-errors.jsonl` if it exists+ - which step broke++ This feedback loop is how the gbrain maintainers find fragile upgrade paths. Thank you.++Health scores may dip after upgrading because doctor now counts things it used to miss: database-only timeline entries, derived pages without an explicit visibility, and code pages below the safe-chunk index version. The repairs clear them. Do not set `search.remote_private_pages` to get derived pages back remotely; that exposes every private page.++### Itemized changes++#### Data loss and privacy++- **Page writes keep database-only history (#5567).** Every coordinated write (`put_page`, managed sync, import, reconcile, connector sync, company import) passes its prior snapshot and a writer class into canonical projection. A write deletes only timeline rows whose bullet it can see in the prior or new body; deletes and detail refreshes act only on the row id, tuple and detail pinned at preparation. Takes follow the same rule, and a new takes row that reuses the number of a database-only take refuses with the new `take_row_collision` write error instead of overwriting it.+- **Database-only history is written back.** Writers that render from the database (`put_page`, reconcile under an approved body decision, connector refresh) write bullet-less rows into the page's timeline, each preceded by `<!-- gbrain:materialized v1 <hash> -->`. A row is rendered only when rendering and re-extracting returns exactly its tuple and detail; backlink receipts and empty or delimiter-bearing sources stay in the database. Managed sync and import never rewrite your file to add bullets, and company imports stay immutable. Deleting a marked bullet with the current revision deletes its entry. Both timeline extractors skip marker lines, search text drops them, and remote `get_page` keeps them so edits round-trip.+- **Derived pages are private unless their origin is public (#5525).** Remote reads treat a missing `visibility` as private on atoms and synthesized concepts. Atom extraction stamps visibility from the origin page (private for transcripts and private pages), concept synthesis stamps the strictest visibility among its inputs, and making an origin page private later hides its atoms and concepts at read time.+- **New `gbrain repair timeline|visibility|safe-chunks [--apply] [--source] [--limit] [--json]`**, plus `gbrain repair` to preview every kind. Dry run by default, resumable, writes through revision-bound `put_page` and re-decides each item just before writing. It stops before 90% of a journal capacity cap and prints the `gbrain config set` value that lets it finish. The visibility repair never loosens a page. Thin clients refuse with "run on the brain host".+- New doctor checks `timeline_history` (bounded scan, exact or lower bound) and `derived_visibility` (exact).++#### Managed-mode wedges++- **Write guard (#5521, #5635).** A file without an explicit `type:` keeps the stored type, and titles compare trimmed. A real drift refuses with `detail: file_database_drift` and a filled `gbrain sources reconcile` command.+- **Git-subfolder sources (#5610, #5398).** New pages record `source_path` in the form of the source's slug-root mode, and the first such write pins an inferred mode. Sync accepts the older Git-root form when the rest of the path names the page, repairs it on the next import, and refuses a path that could name two files with `ambiguous_source_path`. Every reader of the stored path decodes it by mode.+- **Device renumbering after a macOS reboot (#5604).** When only the device id changed and the owner token, brain, worktree, root, inode and a non-zero birth time match, the write path re-stamps ownership under the checkout lock. Anything else refuses with `physical_root_device_changed` and filled self-transfer commands. Verified with a simulated device change, not a real Mac.+- **Sync cursor options (#5632).** The CLI, delegated sync, `sync` jobs and the dream cycle pass only the options they set; a flagless resume adopts the saved cursor's options, and a conflicting flag refuses with `cursor_processing_options_conflict` and the resume command.+- **`capture --file` (#5622, #5603).** A file inside the source is recorded by its source-relative location only when its bytes match and sync would give it the capture slug; anything else records `cli-file`, and no home-directory path is stored. Legacy relative or host-only `file://` values read as absent. An unresolvable absolute file URI refuses with the new `invalid_source_uri` error. Error code change contributed by @quqi1599 (#5554); relative and special-character file cases contributed by @javieraldape (#5670).+- **db_only pages no longer block migrations (#5538).** Pages under a declared `storage.db_only` directory publish database-only when their file is absent, pass the v0.13.1 grandfather step and skip the Git backup. Contributed by @andreineacsu (#5544).+- **Failing Git targets park (#5612).** A Git or withdrawal target that fails five times in a row is set aside; contention, dependency waits, shutdown and transient database errors never count. `gbrain sources writer retry-effects <source> --request-id <id> [--dry-run]` previews parked targets and grants one more attempt each. New doctor check `parked_effects`.+- **Managed `extract --stale` works (#5609).** Links, the page's canonical timeline rows (insert-only) and the freshness stamp publish in one revision-bound coordinated transaction per page; pages edited mid-run stay stale. The `extract.stale` recommendation is withheld when a source's schema pack cannot load.++#### Capacity and migrations++- **Write capacity lasts much longer (#5470, mitigation).** `persistence.limits.*` and the new `persistence.receipt_retention_days` (default 30) are registered config keys, and malformed values are refused at set time. Defaults rise to 250,000 lifetime IDs and 1.5 GiB receipt bytes per principal and 8 GiB per brain. Compaction skips receipts with unfinished effects before its limit. The `persistence_capacity` doctor check warns at 80%, and `queue_capacity` refusals name the key and a value sized for another year. A very write-heavy connector still needs explicit limits.+- Migration 170 adds a partial index for parked effects. Migration 171 adds nullable `content_chunks.embedding_input_hash`. Migration 172 adds a partial index of pages below the safe-chunk fence (concurrent on Postgres). Migration 173 adds a partial index on dead subagent jobs' finish time.++#### Paid loops and connectors++- **Legitimate zero-write answers complete (#5590, #5193, #5540).** An explicit oneshot skip completes the synthesis job and is banked in the ledger, so the cooldown applies. Contributed by @mariopenterman (#5592). The patterns phase opts in to completing a clean finish that ran at least one tool and wrote nothing. Contributed by @Masashi-Ono0611 (#5542). Every write failing, a dirty stop, a prose-only finish and a run whose only tools failed still dead-letter.+- **Dream stops feeding on itself (#5413, #5471).** The session-end hook skips gbrain's own `claude-cli` sessions (contributed by @furuchanchan, #5468); synthesis discovery and the sweep skip identified self-captures; discovery skips the reflections, originals, patterns and summary directories by resolved path. `--unsafe-bypass-dream-guard` turns the path rule off.+- **Paid-loop breaker.** A dream synthesize or patterns key whose submissions died `dream.breaker.max_dead_submissions` times (default 3, 0 disables) in 24 hours is refused before submission. `gbrain dream reset-key <key>` and `--list` manage it, and the `dream_paid_loop` doctor check reports looping keys. Only dead jobs count, so legitimate zero-write completions never trip it. A growing transcript gets a new key each cycle and is not caught. Released idempotency keys are now recorded correctly, and the synthesize daily cap counts released dead rows.+- **claude.ai write access (#5277).** The `/mcp` challenge suggests `read write`; grants stay capped to the registered scope. Contributed by @howardpark (#5283).+- **ChatGPT reconnect loop (#5222).** Authorize, code exchange, refresh and bearer verification share one resource derived from `--public-url`. The server origin aliases to `/mcp`; any other resource gets `invalid_target` naming the accepted URL. Legacy grants keep working.+- **Funnel (#5599).** `gbrain mcp expose --funnel` accepts the capability forms current Tailscale reports.++#### Search correctness++- **Rebuilds keep unchanged vectors (#5553).** Each vector records a hash of exactly what it was built from, written with the vector. Preserving rebuilds (queued rebuilds, the oversize heal, connector and code rebuilds) keep a vector only when the stored hash matches. On a contextual page a legacy vector without a hash is re-embedded once; non-contextual pages keep them as before. In synopsis mode a body edit clears synopsis chunks and keeps title-tier chunks.+- **Withheld pages come back (#5050, #5247).** Re-importing unchanged content below the safe-chunk fence re-seals it without a page write; coordinated imports queue a projection job. `gbrain import` and `gbrain sync --full` report re-sealed pages, chunks still needing embeddings and the estimated cost. `gbrain repair safe-chunks` costs no request IDs or receipt bytes. Doctor and remote `safe_index_pending` count every page kind and fire on partial results. On managed brains, post-upgrade prints the safe-chunk count instead of attempting a markdown reindex.+- **`recall --grep` filters before the limit (#5607).** Adapted from #5619 by @furuchanchan.++#### Runtime++- **Idle serve releases connections (#5370).** An idle tick runs one probe that mirrors every worker's selection and backs off from 250 ms to a 5 s cap; a same-process write wakes it at once. On Postgres pools of three or more, idle probes share one reserved connection and the rest close through the existing idle timeout.+- **PGLite checkpoint guard (#5449, #5284).** Before an outermost write transaction, gbrain runs a `CHECKPOINT` once WAL since the last checkpoint passes half the automatic distance. A failed probe warns once and proceeds; a failed checkpoint refuses before BEGIN with a hint to run `gbrain pglite-repair --dry-run`. Verified on a 0.8 GB harness store, not a real 3 GB store.+- **Hot memory is sent once per session (#5591).** Facts already injected earlier in the session are left out of later prompts. Contributed by @mariopenterman (#5593).++### For contributors++- `prepareCanonicalProjections` is async and takes `(engine, page, slug, sourceId, prior, writer)`; `ProjectionWriter` is `editing | preserving | file | immutable`. `compileCanonicalProjections` is the validation-only entry, and `canonicalTimelineRows` exposes the coordinator's timeline projection to `extract --stale`. New modules: `src/core/timeline-marker.ts`, `src/core/repair/*`, `src/core/embedding-input-hash.ts`, `src/core/persistence/source-storage.ts`, `src/core/cycle/dream-breaker.ts`, `scripts/pglite-checkpoint-harness/`.+- New write errors: `take_row_collision`, `invalid_source_uri`.+- New dual-engine suites: `canonical-projection-history`, `derived-page-visibility`, `timeline-materialize`, `derived-visibility-repair`, `repair-command`, `safe-chunk-reseal`, `projection-embedding-input-hash`, `recall-grep-local-cli`, `persistence-capacity`, `persistence-effect-parking`, `extract-stale-managed`, `persistence-git-subdir-origin`, `persistence-guard-digest`, `persistence-physical-root-device`, `persistence-sync-cursor-options`, `capture-file-source-path`, `oauth-resource-canonical`, `persistence-consumer-idle`, `pglite-checkpoint-guard`, `dream-breaker`, `cycle-synthesize-breaker`, with Postgres arms in `test/e2e/`.+- Intentional contract changes in existing tests: `serve-http-oauth` read-only discovery requests `read write` (the token stays `read`); `cycle-write-path-mini-eval` asserts that a declining child completes; `write-through` and `put-page-persistence` pin Git-root mode; `persistence-cli-delegation` expects `local_file`.+## [0.59.20.0] - 2026-09-29**Two commands could print a source's webhook secret, and hundreds of tests in gbrain's own suite guarded nothing: they stayed green with the code broken, or tested code the product never runs. Both are fixed.**diff --git a/VERSION b/VERSIONindex c3c002d19f..f335719623 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-0.59.20.0+0.60.5.0diff --git a/docs/TESTING.md b/docs/TESTING.mdindex fa46570017..87bb70f86f 100644--- a/docs/TESTING.md+++ b/docs/TESTING.md@@ -683,6 +683,26 @@ snapshot. The slow runner and direct BrainBench test invocation prepare thedefault profile automatically. `GBRAIN_NO_SNAPSHOT=1` clears both paths andsurvives test preloads.+### PGLite checkpoint harness (outside CI)++`scripts/pglite-checkpoint-harness/supervisor.ts` reproduces the large-store+PGLite freeze. It spawns `worker.ts`, which imports 40 KB pages through+`PGLiteEngine.transaction()` into one long-lived store. It then watches that+process from outside: CPU from `/proc`, committed pages from the worker's+progress file, and WAL and checkpoint activity from the data directory. A+worker that burns CPU with no committed page and no checkpoint progress for+`--stall-sec` is reported as wedged. A completed run also asserts that WAL+since the last redo point never exceeded the guard threshold plus the largest+single transaction. `--shared-buffers` and `--max-wal-size` scale the store+down with `ALTER SYSTEM`, so a small machine reaches the same trigger in+minutes:++```bash+bun scripts/pglite-checkpoint-harness/supervisor.ts --dir /tmp/h --fresh --pages 3000 --stall-sec 600 --timeout-sec 1800+bun scripts/pglite-checkpoint-harness/supervisor.ts --dir /tmp/h --fresh --pages 1500 \+ --shared-buffers 16MB --max-wal-size 160MB --stall-sec 120 --expect-wedge # baseline check+```+### Keeping CI partitions balancedRequired CI runs ten weighted unit workers, four serial workers with boundeddiff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.mdindex 4556f163a0..429f01be36 100644--- a/docs/architecture/KEY_FILES.md+++ b/docs/architecture/KEY_FILES.md@@ -33,13 +33,14 @@ boundary and add its link here rather than raising the cap.| [Core Cycle](key-files/core-cycle.md) | `src/core/cycle/anomaly.ts` through `src/core/cycle/triage-rescue.ts` || [Core Minions (1/2)](key-files/core-minions-1.md) | `src/core/minions/` through `src/core/minions/rss-default.ts` || [Core Minions (2/2)](key-files/core-minions-2.md) | `src/core/minions/run-child.ts` through `src/core/minions/worker.ts` |+| [Core Persistence](key-files/core-persistence.md) | `src/core/persistence/` write journal, coordinator, effects, canonical projections and managed sync || [Core Search (1/2)](key-files/core-search-1.md) | `src/core/search/` through `src/core/search/rerank.ts` || [Core Search (2/2)](key-files/core-search-2.md) | `src/core/search/return-policy.ts` through `src/core/search/vector-pool.ts` || [Core Services (1/3)](key-files/core-services-1.md) | `src/core/advisor/{types,run,render,recommended-set,history,apply,collect-*}.ts` through `src/core/context/ipc-path.ts` |-| [Core Services (2/3)](key-files/core-services-2.md) | `src/core/conversation-parser/` through `src/core/progressive-batch/` |+| [Core Services (2/3)](key-files/core-services-2.md) | `src/core/conversation-parser/` through `src/core/progressive-batch/`, except `src/core/persistence/` || [Core Services (3/3)](key-files/core-services-3.md) | `src/core/think/index.ts` through `src/core/verbs/usage-log.ts` || [Core Utilities (1/2)](key-files/core-utilities-1.md) | `src/core/archive-crawler-config.ts` through `src/core/remediation-checkpoint.ts` |-| [Core Utilities (2/2)](key-files/core-utilities-2.md) | `src/core/rerank-audit.ts` through `src/core/verbs.ts` |+| [Core Utilities (2/2)](key-files/core-utilities-2.md) | `src/core/repair/` through `src/core/verbs.ts` || [Engines (1/2)](key-files/engines-1.md) | `src/core/connection-manager.ts` through `src/core/pglite-repair.ts` || [Engines (2/2)](key-files/engines-2.md) | `src/core/pglite-resetwal.ts` through `src/core/worker-pool.ts` || [Entrypoints And Docs](key-files/entrypoints-and-docs.md) | `.agents/gbrain-launcher` through `templates/` |diff --git a/docs/architecture/RETRIEVAL.md b/docs/architecture/RETRIEVAL.mdindex edcb194612..b2e92c1ed1 100644--- a/docs/architecture/RETRIEVAL.md+++ b/docs/architecture/RETRIEVAL.md@@ -417,20 +417,30 @@ incompleteness notices to stderr. MCP carries them in `_meta.retrieval`.The upgraded resident `gbrain serve` drains queued Markdown and code rebuildswithout provider calls. Code repair can also run through the current owner:`gbrain reindex-code --force --no-embed`. Rebuilds preserve only exact,-provenance-compatible vectors; remaining NULL vectors still need an explicitly+provenance-compatible vectors: each vector records the embedding input it was+built from (`content_chunks.embedding_input_hash`: column, model, dimensions,+wrapping tier and wrapped text), and a rebuild keeps it only when the current+page would produce the same input, so an unchanged contextual page keeps its+vectors and a synopsis-mode body edit nulls every synopsis-tier chunk. Vectors+written before that record existed are kept on non-contextual pages and nulled+once on contextual ones. Remaining NULL vectors still need an explicitlyauthorized `gbrain embed --stale` run. A text-ready index is not a promise thatevery page has a vector. Diagnostics do not disclose private or foreign-sourcepending pages and never start repair themselves.Markdown chunk creation applies the strict protected-body sanitizer before-splitting text. For remote reads, all existing chunks are withheld until a-successful rebuild records the current chunker version. Public pages require-this rebuild too; trusted local chunk reads remain available. Body or chunk changes-invalidate that record until the next successful rebuild. While pages are withheld,-remote `search` / `query` report `degraded: [safe_index_pending]` (the MCP-empty-result block names it) instead of a clean miss, and `gbrain doctor` counts-the withheld pages and points at the `gbrain reindex --markdown` fix. Direct page reads-continue to use current source and visibility policy plus body sanitization.+splitting text. For remote reads, all existing chunks of every page kind are+withheld until a successful rebuild records the current chunker version. Public+pages require this rebuild too; trusted local chunk reads remain available. Body or+chunk changes invalidate that record until the next successful rebuild. Re-importing+unchanged content (`gbrain sync --full`, `gbrain import`) re-seals such a page+without a page write or journal admission. While pages are withheld, remote+`search` / `query` report `degraded: [safe_index_pending]` on empty and partial+results alike (the MCP empty-result block names it) instead of a clean or complete+answer, and `gbrain doctor` counts the withheld markdown and code pages and points+at `gbrain repair safe-chunks`, which re-seals them on any brain, managed included.+Direct page reads continue to use current source and visibility policy plus body+sanitization.Run rebuild commands from a local installation on the brain host; thin clientscannot rebuild the host's indexes.diff --git a/docs/architecture/canonical-writers.tsv b/docs/architecture/canonical-writers.tsvindex 7391878f1c..1f2250e0f3 100644--- a/docs/architecture/canonical-writers.tsv+++ b/docs/architecture/canonical-writers.tsv@@ -4,7 +4,7 @@ src/core/persistence/activation.ts 0 coordinator Trusted private administrationsrc/core/persistence/canonical-projections.ts 9 coordinator Facts, takes, timeline, chunks and aliases install within the guarded canonical publication transaction before its receipt commits.src/core/persistence/takes-prepare.ts 3 coordinator Semantic takes apply only through the journal publication callback after current revision, holder and authority validation.src/commands/extract-conversation-facts.ts 4 early_refusal Unsupported managed bulk extraction refuses before queue or provider work; legacy canonical writes retain SQL guard enforcement.-src/commands/extract.ts 6 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.+src/commands/extract.ts 7 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication. On a managed brain extract --stale inserts only the canonical timeline tuples inside withCoordinatedWrite for that page, after the revision-bound derived-link replacement locked and verified the page revision in the same transaction.src/commands/frontmatter.ts 0 filesystem_guard Batch frontmatter repair preflights every target before the first backup/write.src/commands/import.ts 1 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.src/commands/jobs.ts 1 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.@@ -77,7 +77,7 @@ src/core/page-state/schema.ts 2 schema Schema installation and forward-referencesrc/core/page-state/tags.ts 2 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.src/core/persistence/memory-mutations.ts 1 coordinator Publication is transaction-scoped under admitted authority, source/page guards and revision checks.src/core/persistence/memory-prepare.ts 3 coordinator Publication is transaction-scoped under admitted authority, source/page guards and revision checks.-src/core/persistence/page-prepare.ts 8 coordinator Publication, including versioned tombstone restoration, is transaction-scoped under admitted authority, source/page guards and revision checks; the sixth SQL site reconciles trusted first-write provenance with prepared canonical frontmatter and the seventh records canonical source_path in that same guarded transaction. Identical canonical no-ops do not heal physical metadata. The added local-CLI purge deletePage call runs in the prepared publication callback after recorded-artifact removal, under the same source/page identity, revision and durable authority guards as receipt completion; permanent journal IDs and outcomes survive the hard delete.+src/core/persistence/page-prepare.ts 9 coordinator Publication, including versioned tombstone restoration, is transaction-scoped under admitted authority, source/page guards and revision checks; the sixth SQL site reconciles trusted first-write provenance with prepared canonical frontmatter and the seventh records canonical source_path in that same guarded transaction. Identical canonical no-ops do not heal physical metadata. The added local-CLI purge deletePage call runs in the prepared publication callback after recorded-artifact removal, under the same source/page identity, revision and durable authority guards as receipt completion; permanent journal IDs and outcomes survive the hard delete. The ninth site pins an inferred slug_root_mode on sources in the same publication transaction as the first bound origin.src/core/persistence/semantic-pages.ts 1 coordinator Publication is transaction-scoped under admitted authority, source/page guards and revision checks.src/core/pglite-engine/facts.ts 14 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.src/core/pglite-engine/salience.ts 1 projection Derived indexing, retrieval telemetry, or source settings; canonical fields remain guarded by SQL triggers.diff --git a/docs/architecture/key-files/agent-bootstrap-continued.md b/docs/architecture/key-files/agent-bootstrap-continued.mdindex 5414ca9769..b194dad565 100644--- a/docs/architecture/key-files/agent-bootstrap-continued.md+++ b/docs/architecture/key-files/agent-bootstrap-continued.md@@ -3,7 +3,7 @@[Subsystem index](../KEY_FILES.md) · [Previous entries](agent-bootstrap.md).- `src/core/wsl-paths.ts` — WSL Windows-drive path translation shared by the doctor asset checks (`src/commands/doctor-asset-paths.ts`) and hook-transcript confinement (`confineTranscriptPath` above). Exports `WINDOWS_DRIVE_PATH_RE`, `translateWindowsPath(p, mountRoot)` (`C:\Users\x\file` → `<mountRoot>/c/Users/x/file`; null for non-drive input so callers keep the original untouched), `parseWslAutomountRoot(conf)` (the `/etc/wsl.conf` `[automount] root` value, default `/mnt`), and `detectWslMountRoot()` (null off-WSL). Mechanical detection + translation only — POLICY stays with callers (skip vs stat vs confine): the hook lane confines the translated path to the known Claude config tree, doctor decides skip-vs-stat. Pinned by the WSL cases in `test/claude-code-jsonl.test.ts`.-- `src/core/context/turn-context.ts` — server-side per-turn assembly: reflex pointers + volunteered pages (≤3) + hot facts (always `visibility=['world']` — the IPC path never widens what MCP would return) under a "data, not instructions" envelope, trimmed to ≤8KB (the harness caps hook output at 10,000 chars). The ambient `context_pack` and `delta` modes are world-only across every arm by default; only an explicit trusted-local `include_private` widens entity cards, changed pages, threads, and facts together. The result exposes `pointers` AND post-trim `volunteered` — exactly what the rendered text carries — so the IPC delivery point can log the feedback loop without ever counting a trimmed-out page. Reuses the hot-memory cache keyed by typed sessionId. Engine-agnostic.+- `src/core/context/turn-context.ts` — server-side per-turn assembly: reflex pointers + volunteered pages (≤3) + hot facts (always `visibility=['world']` — the IPC path never widens what MCP would return) under a "data, not instructions" envelope, trimmed to ≤8KB (the harness caps hook output at 10,000 chars). The ambient `context_pack` and `delta` modes are world-only across every arm by default; only an explicit trusted-local `include_private` widens entity cards, changed pages, threads, and facts together. The result exposes `pointers` AND post-trim `volunteered` — exactly what the rendered text carries — so the IPC delivery point can log the feedback loop without ever counting a trimmed-out page. Reuses the hot-memory cache keyed by typed sessionId. Engine-agnostic. Hot-memory facts whose rendered line (without the drifting confidence) already appears in `priorContextText` are not re-injected, the same cross-turn contract as volunteered pages (#5591).- `src/core/context/resolve-ipc.ts` (IPC v2) — discriminated-union requests (absent `kind` = legacy resolve; `turn_context` carries `protocol: 2` + a shared secret from a 0600 file in the data dir, plus an additive `channel` for feedback-loop attribution — wire channel claims are validated to the harness channels at the logging site, anything else logs as the default hook channel), handler map, named response types, per-kind timeouts/size caps, socket + parent dir permissions set before exposure, server-side source binding (cross-source requests rejected), protocol echo (a response without it = stale serve → loud degradation). Bind policy: `startResolveIpcServer` connect-probes the path first — a live owner makes it return null (that serve stays the IPC provider; a transient serve never unlinks a live socket), only a dead/absent owner's entry is unlinked (unconditionally, since Bun on win32 cannot stat the AF_UNIX socket file it leaves behind) before listen. The connection handler processes exactly ONE request per connection (trailing bytes mid-await never double-process a line or double-log a delivery); the client clamps a too-big request below the message cap by dropping the advisory `priorContextText` BEFORE any conversation turn. Delivery seams: `onDelivered` (resolve kind) and `onTurnContextDelivered` (turn_context kind) both fire ONLY after the response write succeeds — a block abandoned before the serve responded is never counted (serve's callback logs the delivered block's volunteered pages + pointers to `context_volunteer_events` under the request channel); write-accept still isn't proof of injection (the client can trim/drop after receipt), which is why the `volunteer_channels` doctor check reconciles counts against the hook heartbeat. v1 clients and servers interoperate untouched. Serve-delegated sync rides the same socket as three additive secret-gated kinds (`sync_start`/`sync_status`/`sync_abort`, wire shapes + fail-closed option validation in `src/core/context/sync-ipc.ts`): start+poll, one line per connection, O(1) handlers with no server budget race; a pre-delegation serve answers `unknown_kind:*` without the protocol echo and the client degrades to the typed stale-serve refusal.- `src/core/context/turn-context.ts` — server-side per-turn assembly: reflex pointers + volunteered pages (≤3) + hot facts (always `visibility=['world']` — the IPC path never widens what MCP would return) under a "data, not instructions" envelope, trimmed to ≤8KB (the harness caps hook output at 10,000 chars). `delta` pages carry `updated_at` from `Page.updated_at_iso` (the column's microseconds, projected by `listPages`), so `next_cursor.since` and the session `last_wake_at` (read back via `to_char` in `session-state.ts`) resume from the exact row — a millisecond-rounded cursor re-delivers same-millisecond pages on the next wake; the `delta` op keeps an already-canonical 6-digit ISO `since` verbatim instead of re-rounding it through a JS Date. The ambient `context_pack` and `delta` modes are world-only across every arm by default; only an explicit trusted-local `include_private` widens entity cards, changed pages, threads, and facts together. The result exposes `pointers` AND post-trim `volunteered` — exactly what the rendered text carries — so the IPC delivery point can log the feedback loop without ever counting a trimmed-out page. Reuses the hot-memory cache keyed by typed sessionId. Engine-agnostic.- `src/core/context/resolve-ipc.ts` (IPC v2) — discriminated-union requests (absent `kind` = legacy resolve; `turn_context` carries `protocol: 2` + a shared secret from a 0600 file in the data dir, plus an additive `channel` for feedback-loop attribution — wire channel claims are validated to the harness channels at the logging site, anything else logs as the default hook channel), handler map, named response types, per-kind timeouts/size caps, socket + parent dir permissions set before exposure, server-side source binding (cross-source requests rejected), protocol echo (a response without it = stale serve → loud degradation). The connection handler processes exactly ONE request per connection (trailing bytes mid-await never double-process a line or double-log a delivery); the client clamps a too-big request below the message cap by dropping the advisory `priorContextText` BEFORE any conversation turn. Delivery seams: `onDelivered` (resolve kind) and `onTurnContextDelivered` (turn_context kind) both fire ONLY after the response write succeeds — a block abandoned before the serve responded is never counted (serve's callback logs the delivered block's volunteered pages + pointers to `context_volunteer_events` under the request channel); write-accept still isn't proof of injection (the client can trim/drop after receipt), which is why the `volunteer_channels` doctor check reconciles counts against the hook heartbeat. v1 clients and servers interoperate untouched. Serve-delegated sync rides the same socket as three additive secret-gated kinds (`sync_start`/`sync_status`/`sync_abort`, wire shapes + fail-closed option validation in `src/core/context/sync-ipc.ts`): start+poll, one line per connection, O(1) handlers with no server budget race; a pre-delegation serve answers `unknown_kind:*` without the protocol echo and the client degrades to the typed stale-serve refusal.@@ -20,7 +20,7 @@- Read-time TTL validity (there is no sweeper): ACTIVE fact reads in BOTH engines (`listFactsByEntity/Since/BySession`, both `findCandidateDuplicates` branches, `countUnconsolidatedFacts`, `getFactsHealth` active buckets) carry `AND (valid_until IS NULL OR valid_until > now())` — `valid_until` is temporal validity, not retention; history paths (`listSupersessions`, `findTrajectory`, `--asof`) deliberately still see lapsed rows; a re-stated expired fact re-inserts fresh. Pinned by `test/facts/ttl-validity.test.ts` + engine-parity additions.- Diagnostics: `src/commands/doctor/checks/memory-writeback.ts` (`memory_writeback`, BRAIN category) — quiet-ok when off, but the OFF branch still probes receipt + canonical instruction paths and WARNS on a lingering block (off-but-still-instructing) with the converge command; plane-compare warns when the file mirror disagrees with the DB row (the Stop hook acting on the wrong truth) naming the re-sync; a read_error reports the state as UNKNOWN, never "off (default)"; resolved bundle + BOTH visibility postures + audience/reasons; instruction blocks receipt-vs-live-probe-vs-drift compare (drift fix names the `config set` + `bootstrap harness` combo — the config set re-stamps the posture mirror so the re-render converges even after an out-of-band visibility flip) + AGENTS.override.md detection — and a receipt target in state `failed` is a STANDING warn regardless of the live probe (the one physical-survival path — a smoke-rollback strip that itself threw — leaves a current-looking block directing sessions at a rolled-back endpoint, and only the receipt state knows) naming the `bootstrap harness --yes` / `--remove` converge; validity-lapsed count; 7d counters (verbs usage sidecar's additive `remember_status` [stamped in `src/mcp/dispatch.ts`, ALL-MCP-callers semantics labeled honestly] + `writeback`/`writeback-bank` heartbeat events; `turns_banked` counts flush_skip_* — banked, enqueue declined) with the local/lossy disclosure. Null-engine runs report the file mirror honestly.- Tests: `test/writeback-config.test.ts`, `test/mcp-instructions-writeback.test.ts`, `test/facts/writeback-gate.test.ts`, `test/hook-writeback-stop.serial.test.ts`, writeback-lane cases in `test/checkpoint-harvest.serial.test.ts`, `test/bootstrap-instructions-block.test.ts` + harness serial additions, `test/writeback-nudge.serial.test.ts`, `test/doctor-memory-writeback.serial.test.ts`, the hermetic 5-step `test/ambient-writeback-lifecycle.serial.test.ts`, and the NON-GATING real-codex door (`test/e2e/bootstrap-real-codex.serial.test.ts`, ambient-writeback describe).-- `src/core/sweep.ts` + `src/commands/sweep.ts` — the serve-resident maintenance sweep (the lock owner closes the persistence loop): facts-fence reconciliation (zero-LLM, reuses the cycle extractor with a slug subset), deterministic link/timeline extraction over recent workspace pages (the same cores as `gbrain extract` — remote put_page deliberately skips these, the sweep is where the graph compounds), and spend-gated corpus ingest (skipped keyless; sidecar-marked exactly-once). Bounded, fail-soft, never throws; armed at serve startup (3s, best-effort) and on 10-min idle ticks through the injectable timer seam, everything unref'd; `GBRAIN_SWEEP=0` kills it. `gbrain sweep --once` is the trusted CLI seam `bootstrap verify` uses (CLI-only, never over MCP). The link pass threads the same `link_resolution.cross_source` opt-in and configured `sources.default` the CLI extract lanes pass into `resolveCandidateSources`, so an edge into another source is created (flag on) or counted as `cross_source_link` in `skipped` (flag off) — never silently dropped, and the reconcile never deletes a cross-source edge `extract links --source db` created.+- `src/core/sweep.ts` + `src/commands/sweep.ts` — the serve-resident maintenance sweep (the lock owner closes the persistence loop): facts-fence reconciliation (zero-LLM, reuses the cycle extractor with a slug subset), deterministic link/timeline extraction over recent workspace pages (the same cores as `gbrain extract` — remote put_page deliberately skips these, the sweep is where the graph compounds), and spend-gated corpus ingest (skipped keyless; sidecar-marked exactly-once; dream outputs and claude-cli self-captures classified by `claudeCliSelfSessionIds` get a terminal `.ingested` sidecar with `skipped: dream_output` / `self_capture` and are never extracted). Bounded, fail-soft, never throws; armed at serve startup (3s, best-effort) and on 10-min idle ticks through the injectable timer seam, everything unref'd; `GBRAIN_SWEEP=0` kills it. `gbrain sweep --once` is the trusted CLI seam `bootstrap verify` uses (CLI-only, never over MCP). The link pass threads the same `link_resolution.cross_source` opt-in and configured `sources.default` the CLI extract lanes pass into `resolveCandidateSources`, so an edge into another source is created (flag on) or counted as `cross_source_link` in `skipped` (flag off) — never silently dropped, and the reconcile never deletes a cross-source edge `extract links --source db` created.- `src/core/context/sync-ipc.ts` + `src/core/serve-sync-runner.ts` + `src/commands/sync-delegate.ts` — serve-delegated sync. `sync-ipc.ts` is the LEAF wire module: the `DELEGATED_SYNC_OPTION_FIELDS` table is the single source of truth for the validator, the CLI wire-builder, and the serve-side SyncOpts builder; `validateDelegatedSyncOptions` rejects unknown keys fail-closed (repoPath/skipLock/lockId/concurrency are unreachable from the socket), requires `timeoutSeconds` (0 = the explicit `--no-hard-deadline` unbounded encoding; everything else clamps to 24h), and `toWireSyncResult` truncates `pagesAffected` to 50 + a true total under the 256KB message cap. `serve-sync-runner.ts` is the serve-side module singleton: one job at a time (correctness still rests on the `gbrain-sync:<source>` row lock inside performSync), clientToken attach (a lost-ack retry finds its own running OR retained-terminal job instead of duplicate-running), per-job deadline timer, `[serve-sync]` lifecycle stderr lines, an idempotent shared `shutdownDelegatedSync()` both serve shutdown paths await BEFORE `engine.disconnect()` (the disconnect-mode drain is allowAbort:false after `_db` is nulled, so settle writes need the live engine; a registered drainer remains as backstop), and `maybeDrainDeferredEmbeds` (delegated jobs always run noEmbed — the cost gate lives in runSync — and the serve drains stale embeds afterwards via `runEmbedCore`, keyless-safe, cleared only when a drain finds nothing left; wire `noEmbed` records that the USER declined embeds and suppresses the drain). `sync-delegate.ts` is the CLI half: read-only holder probe (`probeLivePgliteHolder`), DEFAULT-DENY argv gate (any unclassified token refuses by name — a silently dropped `--exclude` would perform the wrong sync), engine-free source tiers (`resolveSourceIdEngineFree`), 1s poll loop tolerant of event-loop-blocked serves with a PID-probe backstop, `unknown_job` → serve-restarted resume hint, Ctrl-C → `sync_abort` (second Ctrl-C exits 130), and runSync's `pull_failed` verdict mirroring. Mounts and non-PGLite configs never delegate; opt-outs `--no-delegate` / `GBRAIN_SYNC_NO_DELEGATE=1` (client) and `GBRAIN_SERVE_SYNC_IPC=0` (serve). Pinned by `test/context/sync-ipc-validation.test.ts`, `test/sync-delegate-ladder.test.ts`, `test/serve-sync-runner.serial.test.ts`, `test/context/resolve-ipc-sync-kinds.test.ts`, and `test/e2e/sync-delegation-under-serve.serial.test.ts` (gating tier1 step).- `src/core/capability.ts` — config-plane keyless/keyed detection + the honest capability report (per-provider keyless banner: OpenAI = semantic search + auto-extraction, Voyage = semantic search, Anthropic = auto-extraction) rendered by verify and the runbook. The extraction probe resolves through the SAME shared `resolveEffectiveChatModel` the gateway's reconfigure fallback uses (`GBRAIN_MODEL` > servable file pin > key-aware tier default), so a stale unservable pin degrades identically in the report and at runtime. Key/env fold comes from `mergedProviderEnv` (`src/core/ai/provider-env.ts`). Accepted limitation (documented in the module): DB-plane overrides (`models.default`, `facts.extraction_model`) are invisible to this engine-less probe; the runtime gate in `facts/extract.ts` and the engine-aware pre-enqueue gate in `facts/backstop.ts` are the backstops.- `src/core/secret-scan.ts` — pattern-based secret detection shared by `sources push`, bootstrap verify, the compiled-context sensitivity scan and the transcripts redactor. Detection is FORMAT-based, not prefix-only: vendor shapes (anthropic, openai, voyage, github, gitlab, slack, aws AKIA/ASIA, google, stripe, sendgrid, twilio, supabase sb_secret_/sbp_, npm, huggingface, gbrain), JWTs, whole-block PEM keys, plus two catch-alls appended LAST (`bearer` — prebuilt two-group layout so only the token is the value; `db_url_credentials` — the `scheme://user:pass@` span of database URLs, host/db kept). Fixed-length shapes carry a trailing negative lookahead. Per-line claimed-span dedupe is first-wins for ATTRIBUTION (order matters: `Bearer <vendor key>` keeps the vendor name, a fully covered later span is skipped) but coverage is the UNION: every unclaimed slice of a later overlapping span is claimed as a hit of the later pattern (own value, own fingerprint), so a database URL whose username is a vendor-shaped id still loses its password. The opt-in `high_entropy_assignment` rule (`ScanOpts.highEntropy`) requires a 12+ char value that contains a digit AND clears 3.5 bits/char. Own minimal allowlist + `<ws>/.gbrain-scan-allow` per-finding overrides — deliberately NOT the repo's `.gitleaks.toml` (a public-repo CI fixture policy). Deliberately NOT patterns: `sb_publishable_`, Supabase project refs (identifiers, not credentials). Never spell a literal database URL with userinfo in this file's comments (`scripts/check-pg-url-redaction.sh`). Long lines are scanned in full (no length cap — a secret on a 1 MB minified line must still redact); what keeps that linear is bounded quantifiers on every shape whose value class could otherwise run to end-of-line — `db_url_credentials` (user ≤128 stopping at `:`/`/`; password 1–256 stopping only at whitespace, `@` and the string delimiters `"`/`'`, so unescaped `/ { } < > | ^ \` and backtick passwords redact), `jwt` (prebuilt so its boundary excludes `-` as well as `_`; segments ≤4096), `high_entropy_assignment` (≤64 identifier chars after the keyword, value ≤4096), and `PEM_BLOCK_RE`'s lazy body (≤`PEM_BODY_MAX_CHARS` = 16384; a longer body degrades to the header-only match) — plus a per-pattern `precheck` substring gate on the two catch-alls (`@`; `earer`/`EARER`, since an all-caps `BEARER` scheme is accepted), a carried next-newline position in `scanPemBlocks` (sticky -1, so the header-line count is O(text) even when thousands of hits sit ahead of a newline-free multi-megabyte tail), a lazily-allocated per-line claimed-char bitmap behind the first-wins dedupe (O(value) per hit), and a windowed `buildPreview` (whole line ≤160 chars; otherwise hit−40…+80, edges snapped outward to whole spans, every claimed span in the window spliced by position, so a preview never carries a sibling secret or a fragment). `redactFindings` (= `planRedaction` + `applyRedaction`) rebuilds the text by SPAN-SPLICE in one O(text + hits) pass over the claimed spans, and fills the UNCLAIMED gaps with a bounded echo pass: the values claimed by `bearer` and `high_entropy_assignment` form an echo dictionary (value → pattern; floors `ECHO_MIN_CHARS_BEARER` = 20 / `ECHO_MIN_CHARS_ENTROPY` = 12, values ≤ `ECHO_MAX_VALUE_CHARS` = 512, the first `ECHO_MAX_UNIQUE` = 64 unique values in claim order across BOTH patterns — a value past either cap is redacted at its claim, its echoes are the accepted miss), matched by a streaming merge over the ORIGINAL text — per value, the next occurrence at or beyond the emit cursor (`indexOf` resuming at the cursor, re-sought only once the cursor passes it), leftmost-longest at each step, emitted incrementally into the unclaimed gaps — so retained state is O(values) however long the text is (occurrences are never collected into a list: a repetitive tail against 64 short claimed values meant millions of candidate objects and hundreds of MB of RSS for 64 findings, ahead of message truncation) (never an alternation RegExp — O(text × Σ|values|) on prefix-sharing values; never over emitted tokens, so a value spelling a pattern name cannot nest). Echoes add no findings. `planRedaction` feeds a caller-supplied shared map (`RedactOpts.echoValues`) and `applyRedaction` reads it at apply time, so a multi-field document scrubs an echo in one field of a value claimed in another. Every other pattern redacts exactly what `scanText` reports (a value embedded past its boundary is left as-is; vendor shapes re-match on their own). Perf pins: `test/secret-scan-perf.test.ts`. Retrieval output is another consumer of its canonical scanner; that output boundary does not sanitize internal evaluation/provider inputs.diff --git a/docs/architecture/key-files/agent-bootstrap.md b/docs/architecture/key-files/agent-bootstrap.mdindex 9b218eef40..05fbe75253 100644--- a/docs/architecture/key-files/agent-bootstrap.md+++ b/docs/architecture/key-files/agent-bootstrap.md@@ -24,7 +24,7 @@ User-facing contract: `docs/guides/bootstrap.md`. Runbook the paste block fetche- `src/core/bootstrap/atomic-write.ts` — the ONE atomic config-file writer for bootstrap host surfaces: symlink-target-resolving, mode-inheriting (`freshMode` for new files, `forceMode` for secret-bearing targets), random-suffix tmp + rename, tmp unlinked best-effort when write/chmod/rename throws (ENOSPC/EACCES never strand `.tmp-` litter), and the existsSync→realpathSync race falls back to fresh-path resolution instead of throwing raw ENOENT. hooks.ts (JSON), codex-toml.ts (TOML+EOL), and opencode-json.ts (JSONC) all swap through it; serialization and EOL policy stay caller-side.- `src/core/bootstrap/harness.ts` — `gbrain bootstrap harness`: machine-level wiring of framework-spawned Claude Code/Codex/opencode sessions to a RUNNING `gbrain serve --http`, no `agent.json`. The opencode target mirrors the codex posture: forced-wire on explicit `--harness opencode` (the JSONC writer needs no CLI), one managed `mcp.<name>` remote entry with the inline bearer header (0600) via `opencode-json.ts`, rotation across a url change recognized through the PRIOR receipt's url, failed-smoke rollback restoring the run's UNIQUE backup or removing a fresh entry — guarded by a content compare against the exact text this run wrote, so a NEWER registration that landed after the lock released is never clobbered (rollback skips with a note; the fresh mint is revoked either way), with the backup unlinked once consumed or once the smoke verifies — `--remove` classifying against the receipt url (not-ours skips with a note), and `--status` bearer recovery via `parseOpencodeEntryBearer` (url-matched). Consent block in the honesty register (reach as fact, transcript capture its own numbered item + `--no-capture`, off-ramps in the same breath; non-TTY requires `--yes`); /health probe with a loopback guard on `--url` (remote brains are `gbrain connect`'s charter; `--token` makes it a pure registrar); mint-first rotation (previous token revoked BY ID only after every target confirms + the bearer smoke passes — clients are never dead mid-swap; revoke-by-name never happens); the smoke is canary-gated: a random same-format bearer must FAIL auth before the real token is sent, so a loopback impostor is caught whichever way it answers, and ANY failed smoke rolls back symmetrically — fresh registrations removed, replaced ones restored (an unrestorable replacement fails the target honestly), the freshly-added pre-approval stripped, and the fresh mint revoked immediately so nothing live stays pointed at an unverified endpoint; the `permissions.allow` pre-approval only lands after the MCP registration itself confirms; stale prior-target cleanup runs AFTER the smoke passes, so a run that failed to establish its replacement never unwires working prior wiring; write-ahead harness receipt (targets persist as `pending` at mint time and flip per-target, so a crash leaves consumable state); registration ownership checks (`--force` to replace a foreign-url server; `--remove` skips what it no longer owns); user-XOR-project hook scopes; `GBRAIN_HOOK_LANE=harness` on hook commands so `gbrain hook` yields to a workspace bootstrap install in the cwd (Claude Code merges settings scopes — same event must not fire twice); the hook `GBRAIN_SOURCE`, the receipt `source_id`, and the token grant bind to a validated `--source` (scalar write floor), else to the source `HarnessDeps.resolveHookSource` resolves through the SAME chain the serve's resolve-IPC binding runs (`resolveSourceWithTier`: env → dotfile → local_path → `sources.default` → sole populated non-default → seed default) with that source's federated read set as the grant, so the hooks' `turn_context` claim is never `source_mismatch`; a resolution landing on `default`/`__all__` is the federated floor. Lookup failures are NOT papered over with `default`: a typo'd `--source` or stale env/dotfile throws `SOURCE_UNRESOLVED` before any mint or receipt; an explicit `--source` with an unopenable engine binds unverified with a warning; a live PGLite serve (engine cannot open) refuses with the `LIVE_SERVE` escape hatches when no token was supplied and, on the `--token` lane without `--source`, wires the hooks UNPINNED with a warning (an unpinned hook resolves through the live serve's own binding; the receipt records the federated floor `default` plus `source_pinned: false`); any other lookup failure throws `SOURCE_UNRESOLVED` naming `--source`; Postgres degradation + serve-version-skew honesty lines (`isServeOlderThanScopes` pinned to `SCOPES_MIN_SERVE_VERSION`, the first scope-aware release, so later CLI bumps never re-trigger the warning); `--status` probes the live truth with host-config token recovery (redacted; the Claude Code lane recovers a bearer ONLY from a registration whose URL matches the receipt — never another install's credential; the codex fallback reads OUR managed block at the receipt-recorded path, its `url` key not yet compared — TODOS.md; the opencode fallback IS url-compared inside `parseOpencodeEntryBearer`) and honest `verify: unavailable` degrades, with a cron-honest exit contract: 0 only when serve + token + every target verify and the rotation has converged (honest degrades count), 1 on an unreachable serve, a failed token verify, failed/pending targets, unconverged rotations, or a half-removed receipt (zero targets, minted token awaiting deferred revoke — also a doctor FAIL); no receipt prints honestly and exits 0 in plain mode, 2 under `--json`; `--json` on apply emits ONLY the final JSON document on stdout (prose → stderr); `--remove` is engine-free-first and defers the token revoke with exact instructions under a live PGLite serve. Locks on the gbrain HOME, plus the host config dir around codex/opencode writes, removals, rollbacks, and stale cleanup (stale prior-target cleanup nests the codex/opencode config-dir lock inside the held claude config-dir lock — same claude-first ordering as apply/remove, same-dir skip — so its read-modify-write can't interleave with a concurrent config-dir-locked writer); `bootstrap uninstall` holds the HOME lock across the whole teardown and runs harness removal FIRST (revoke needs the DB alive; `--delete-brain` would destroy harness.json) and treats NO_RECEIPT/HOME_GUARD/RECEIPT_MISMATCH as "no workspace install" once harness wiring is cleared. Pinned by `test/bootstrap-harness.serial.test.ts` + `test/bootstrap-harness-lifecycle.serial.test.ts`.- `src/core/token-mint.ts` — programmatic legacy-token mint/revoke for the harness lane: `mintLegacyToken` (scopes → the TEXT[] column; required `takesHolders` per-token allow-list, harness default `['world']`; optional `permissions.source_id` federation array mirroring the stdio lane's `localFederatedSourceIds` grant, element 0 = write floor; `RETURNING id`) and `revokeLegacyTokenById` (never touches same-name siblings). Exports `TOKEN_ID_RE`, the canonical token-id shape shared with the `auth revoke --id` CLI gate. Canonical `hashToken`/`generateToken` from `src/core/utils.ts`. Pinned by `test/token-mint.test.ts`.-- `src/commands/hook.ts` — engine-free `gbrain hook {session-start,user-prompt,stop,session-end,compact}` (zero engine modules in the import graph; a hook must NEVER contend for the PGLite writer lock). When `GBRAIN_HOOK_LANE=harness` (set on harness-mode hook commands), each event PARSES the cwd's workspace settings carriers — `.claude/settings.local.json` AND the committed `.claude/settings.json` — and yields silently only when a live `bootstrap-v1` hook entry wires THAT event: the workspace install wins over user-scope harness wiring so the merged settings scopes can't fire the same event twice, unwired events still run, and a repo committing marker-lookalike strings in unrelated fields can't disable the machine-wide capture lane (fail-open — a read/parse hiccup means the event runs normally). user-prompt: stdin hook JSON → transcript-path confinement → last-4-turns window + cross-turn dedupe (the transcript's `hook_additional_context` attachments — the blocks WE previously injected — ride `priorContextText`, deduplicated and capped at `PRIOR_CONTEXT_MAX_BYTES` (32KB, so the advisory payload can never blow the IPC message cap; one oversized block is skipped without evicting smaller ones), so a page is volunteered once per session, not once per mention; structured extraction only, never raw-turn substring matching) → IPC turn_context (with a feedback-loop `channel`, `--harness <claude-code|codex>`, default claude-code) → `hookSpecificOutput.additionalContext` under an 800ms self-deadline; every path fails open (exit 0, empty stdout) with a typed reason in the heartbeat. Listed in cli.ts's `STARTUP_HOOK_SKIP_COMMANDS` (per-prompt invocations must never spawn a detached check-update child; membership is pinned by a source grep — the runtime path no-ops under NODE_ENV=test). session-start: file-plane digest (allowlisted MEMORY.md sections, push staleness, prior failures) + crashed-session recovery push gated on an initialized manifest. session-end: confined full-transcript parse → redacted corpus write (session-id filename dedup, retention prune; the corpus scan runs highEntropy whenever the relay is on — the relay child derives its egress task line from the corpus text — and stays vendor-prefix-only otherwise) → parser-drift detection (`bytes>0 && turns==0` is loud) → best-effort workspace push. session-start recovery + session-end pushes run in a DETACHED child so the hook returns immediately (a synchronous inline push would block harness startup on a dirty tree); the corpus write is atomic and clears the stale ingested/in-progress sidecars so a resumed session re-ingests its appended transcript. Heartbeat JSONL is counters/reasons only by construction; `readHeartbeatTail` feeds doctor. `GBRAIN_HOOKS=0` kills all events. Session-end capture dispatches per harness through `captureSpecFor(io.harness)` (`src/core/transcripts/capture-spec.ts`): claude-code and codex each pin their OWN confinement root + parser; unknown/undefined/opencode resolve to the claude spec (golden-pinned). The codex lane confines to `codexSessionsDir()` + `codexArchivedSessionsDir()` (codex moves rollouts into the flat archived store), parses rollouts via `parseCodexHookTranscript`, and falls back to bounded id-matched discovery across both stores when the SessionEnd payload carries `transcript_path: null` or a path that no longer exists (`missing_path`; `unreadable` is reserved for EACCES/IO faults) — the fallback and prior-run relay failures are DEFERRED heartbeat reasons, applied after current-session reasons so they never mask one (first-degrade-wins). ONE gate covers the whole optional Memorable seam — `memorableGateAllowed(cfg)` in hook-heartbeat.ts: the config flag (`integrations.memorable.enabled === true`, file plane), the `GBRAIN_MEMORABLE` kill switch (any common negative spelling, trimmed; env can only ever disable), AND the gbrain-authored consent stamp (`memorable-consent.json` — see hook-heartbeat.ts). Off is the default: no tool-call collection, no receipt, no spawn. On, session-end runs the shared `redactedToolCallsJson` (span-filtered to the corpus window, highEntropy ALWAYS on — those args are the one artifact that leaves the machine) and `recordAndRelayReceipt` (receipt dedup by post-redaction content hash → CLI-side consent evidence → `resolveMemorableBin` → detached fire-and-forget `memorable record` spawn; both capture lanes trim memorable-relay.jsonl). Fail-closed egress guards: a scanner-import failure skips the receipt+relay entirely (`memorable_relay_skipped_unscanned` — parity with the openclaw lane), and a newest-mtime discovery GUESS (no session-id match) writes the local corpus but never relays (`memorable_relay_skipped_newest_guess` — the newest rollout can be a different, still-running session). A payload without session_id adopts the transcript's own id post-parse (never a shared unknown.txt corpus), and the gate answer is hoisted BEFORE the parse and collection is opt-in, so the default gate-off population never collects tool calls (`collectToolCalls: memorableAllowed`). Operator-facing doc: `docs/memorable-agents.md` (install is `npm i -g memorable-cli`; closed source, no source install, no embedding model to configure). `spawnDetachedPush` passes `env: process.env` explicitly so the detached push child inherits the parent's quarantined env view. `tryExecAsync` (the git wrapper behind `resolveBootstrapWorkspaceRoot` / `repoPhaseComplete`) also passes `env: process.env` so git sees the quarantined view, not Bun's startup snapshot; pinned by `test/hook-push-spawn-env.test.ts`.+- `src/commands/hook.ts` — engine-free `gbrain hook {session-start,user-prompt,stop,session-end,compact}` (zero engine modules in the import graph; a hook must NEVER contend for the PGLite writer lock). When `GBRAIN_HOOK_LANE=harness` (set on harness-mode hook commands), each event PARSES the cwd's workspace settings carriers — `.claude/settings.local.json` AND the committed `.claude/settings.json` — and yields silently only when a live `bootstrap-v1` hook entry wires THAT event: the workspace install wins over user-scope harness wiring so the merged settings scopes can't fire the same event twice, unwired events still run, and a repo committing marker-lookalike strings in unrelated fields can't disable the machine-wide capture lane (fail-open — a read/parse hiccup means the event runs normally). user-prompt: stdin hook JSON → transcript-path confinement → last-4-turns window + cross-turn dedupe (the transcript's `hook_additional_context` attachments — the blocks WE previously injected — ride `priorContextText`, deduplicated and capped at `PRIOR_CONTEXT_MAX_BYTES` (32KB, so the advisory payload can never blow the IPC message cap; one oversized block is skipped without evicting smaller ones), so a page is volunteered once per session, not once per mention; structured extraction only, never raw-turn substring matching) → IPC turn_context (with a feedback-loop `channel`, `--harness <claude-code|codex>`, default claude-code) → `hookSpecificOutput.additionalContext` under an 800ms self-deadline; every path fails open (exit 0, empty stdout) with a typed reason in the heartbeat. Listed in cli.ts's `STARTUP_HOOK_SKIP_COMMANDS` (per-prompt invocations must never spawn a detached check-update child; membership is pinned by a source grep — the runtime path no-ops under NODE_ENV=test). session-start: file-plane digest (allowlisted MEMORY.md sections, push staleness, prior failures) + crashed-session recovery push gated on an initialized manifest. session-end: a transcript path or payload cwd carrying the claude-cli scratch fingerprint (`isClaudeCliSelfTranscriptPath`) is gbrain's own subprocess session — heartbeat `segment: self_transcript`, no parse, no corpus write; otherwise confined full-transcript parse → redacted corpus write (session-id filename dedup, retention prune; the corpus scan runs highEntropy whenever the relay is on — the relay child derives its egress task line from the corpus text — and stays vendor-prefix-only otherwise) → parser-drift detection (`bytes>0 && turns==0` is loud) → best-effort workspace push. session-start recovery + session-end pushes run in a DETACHED child so the hook returns immediately (a synchronous inline push would block harness startup on a dirty tree); the corpus write is atomic and clears the stale ingested/in-progress sidecars so a resumed session re-ingests its appended transcript. Heartbeat JSONL is counters/reasons only by construction; `readHeartbeatTail` feeds doctor. `GBRAIN_HOOKS=0` kills all events. Session-end capture dispatches per harness through `captureSpecFor(io.harness)` (`src/core/transcripts/capture-spec.ts`): claude-code and codex each pin their OWN confinement root + parser; unknown/undefined/opencode resolve to the claude spec (golden-pinned). The codex lane confines to `codexSessionsDir()` + `codexArchivedSessionsDir()` (codex moves rollouts into the flat archived store), parses rollouts via `parseCodexHookTranscript`, and falls back to bounded id-matched discovery across both stores when the SessionEnd payload carries `transcript_path: null` or a path that no longer exists (`missing_path`; `unreadable` is reserved for EACCES/IO faults) — the fallback and prior-run relay failures are DEFERRED heartbeat reasons, applied after current-session reasons so they never mask one (first-degrade-wins). ONE gate covers the whole optional Memorable seam — `memorableGateAllowed(cfg)` in hook-heartbeat.ts: the config flag (`integrations.memorable.enabled === true`, file plane), the `GBRAIN_MEMORABLE` kill switch (any common negative spelling, trimmed; env can only ever disable), AND the gbrain-authored consent stamp (`memorable-consent.json` — see hook-heartbeat.ts). Off is the default: no tool-call collection, no receipt, no spawn. On, session-end runs the shared `redactedToolCallsJson` (span-filtered to the corpus window, highEntropy ALWAYS on — those args are the one artifact that leaves the machine) and `recordAndRelayReceipt` (receipt dedup by post-redaction content hash → CLI-side consent evidence → `resolveMemorableBin` → detached fire-and-forget `memorable record` spawn; both capture lanes trim memorable-relay.jsonl). Fail-closed egress guards: a scanner-import failure skips the receipt+relay entirely (`memorable_relay_skipped_unscanned` — parity with the openclaw lane), and a newest-mtime discovery GUESS (no session-id match) writes the local corpus but never relays (`memorable_relay_skipped_newest_guess` — the newest rollout can be a different, still-running session). A payload without session_id adopts the transcript's own id post-parse (never a shared unknown.txt corpus), and the gate answer is hoisted BEFORE the parse and collection is opt-in, so the default gate-off population never collects tool calls (`collectToolCalls: memorableAllowed`). Operator-facing doc: `docs/memorable-agents.md` (install is `npm i -g memorable-cli`; closed source, no source install, no embedding model to configure). `spawnDetachedPush` passes `env: process.env` explicitly so the detached push child inherits the parent's quarantined env view. `tryExecAsync` (the git wrapper behind `resolveBootstrapWorkspaceRoot` / `repoPhaseComplete`) also passes `env: process.env` so git sees the quarantined view, not Bun's startup snapshot; pinned by `test/hook-push-spawn-env.test.ts`.- `src/core/transcripts/claude-code-jsonl.ts` — the Claude Code transcript parser as a dated spec-target (tool_use/tool_result/thinking/image/sidechain/summary/compact-boundary shapes; placeholders for non-text content). `genuineUserTurnIndexes` separately records user-role turns containing real text blocks, because Claude stores tool-result-only entries with `role:'user'`; archival consumers keep every placeholder while prompt-only consumers select by structure. Also extracts `injectedContextBlocks` — the `hook_additional_context` attachment lines a gbrain hook previously injected (verified live against claude CLI 2.1.224; marker-filtered, so a foreign hook's blocks are excluded and another tool's output can't suppress volunteering — a same-user mislabeling guard, not an authenticity check), the user-prompt hook's cross-turn dedupe input; `confineTranscriptPath` (contained under `~/.claude/projects`, `.jsonl`, lstat-rejects symlinks, byte cap; under WSL, a Windows drive-literal `transcript_path` — Claude Code on the Windows host invoking hooks via `wsl.exe` — is translated through `src/core/wsl-paths.ts` and then held to the SAME confinement, rooted Windows-side, so translation never widens what a hook may read). Fixtures: `test/fixtures/conversation-formats/claude-code.jsonl` (synthetic, privacy-guarded) + `test/fixtures/hook-transcript.jsonl` (real captured hook round-trip). `parseTranscript` additionally returns `toolCalls`, but collection is OPT-IN (`collectToolCalls: true`; the bare parse — every per-prompt lane — collects nothing, so tool INPUTS are never retained for users who never opted in): the tool name + input args for every `tool_use` block, oldest → newest, each joined to its `tool_result` outcome by `tool_use_id` and then stripped of that id so no transcript-internal identifier reaches a consumer; every STRING in a collected input is bounded to `TOOL_CALL_VALUE_MAX_CHARS` (32k) with an explicit `…[N chars omitted]` marker (`capToolCallInput`, shared with the codex lane — one receipt-size ceiling for every harness). It is a parallel extraction, never a change to the placeholder-only archival rendering, which is load-bearing for the token-budget-constrained ambient-recall path; existing callers that ignore the field see no behavior change.- `src/core/transcripts/grok.ts` — the Grok Build (grok CLI) transcript adapter: one session directory (`~/.grok/sessions/<url-encoded-cwd>/<uuid>/chat_history.jsonl`) = one session; `GROK_HOME` relocates the root. Turn selection is STRUCTURAL (`mapGrokLine`, exported so the dated `SPEC_TARGET` mapping is pinned): user turns are `type:'user'` text blocks WITHOUT `synthetic_reason` (injected system_reminder/task_completed rows are `typed`, i.e. intentionally text-free, as are tool_result-only user arrays); assistant turns need non-empty string `content` (tool-only rows — `content` ''/null WITH `tool_calls` — are `typed`); system/reasoning/tool_result/backend_tool_call rows are `typed`; unknown row types `skip`. A recognised HUMAN-turn row whose content this parser cannot decode (user `content` missing / non-string / non-array / an array holding non-block entries; assistant non-string `content` with no `tool_calls`) is `malformed` and counted as SKIPPED, never typed, so a file made only of such rows is never `expectedEmpty` — the ingest drift signal fires (`bytesRead > 0`, sessions 0, `cleanScan=false`, watermark frozen) and `zeroSessionsReason` names the malformed row count, instead of an upstream schema change silently advancing the watermark past whole conversations. `chat_history.jsonl` carries NO per-message timestamps: session times come from the sibling `summary.json` (`created_at`/`last_active_at`; a malformed summary is ignored, an unparseable date is never fabricated) and, because grok writes `summary.json` at session END, an in-progress session or partial rsync falls back to the log file's own mtime — a real filesystem time — with `raw.timestamp_source` stamped `'summary.json'` vs `'file_mtime'` so consumers can tell them apart (without the fallback the render refusal would freeze the `--since-last` watermark for the whole grok root). Every message carries the session bounds (last message = `last_active_at`, the rest = start). Session id: summary → UUID dir name → `stableIdFromPath` (a sha256 prefix of the log path, never the bare `chat_history` basename, which would collapse every such session onto one page). Sidecars (updates.jsonl, events.jsonl, rewind_points.jsonl, summary.json, prompt_history.jsonl) are not sessions — discover.ts's grok-sidecar filter is scoped to PROVEN grok trees and the head sniff rejects claude-family keys (grok detection runs after claude-code; an oversized system head still detects through the truncated-line sniff); a percent-encoded cwd segment that fails to decode yields `cwd` undefined with the session id intact.- `src/core/transcripts/capture-spec.ts` + `codex-hook-lane.ts` — the per-harness session-end capture seam. `capture-spec.ts`: the satisfies-anchored `CAPTURE_SPECS` record ({confine, parse, discover?}) for the STDIN-DRIVEN lanes (claude-code, codex); `captureSpecFor()` resolves unknown/undefined/opencode to the claude spec (golden-pinned by `test/codex-hook-lane.test.ts`); openclaw is deliberately NOT a member (its lane is in-process, trusted-plane — see context-engine.ts). `codex-hook-lane.ts`: `confineCodexTranscriptPath` (the same S3#8 ladder as the claude root, pinned at BOTH `codexSessionsDir()` AND `codexArchivedSessionsDir()` — codex MOVES a rollout into the flat `archived_sessions` store on archive, so fencing only the live store refused a still-valid path; both CODEX_HOME-resolved since the spawner IS codex; an explicitly pinned test-seam `root` stays single-root; ENOENT/ENOTDIR on the path is `missing_path` — the rung hook.ts gates its discovery fallback on — while `unreadable` is reserved for EACCES/IO faults, so the codex session-end heartbeat reason for a nonexistent `transcript_path` after a failed discovery is `transcript_missing_path`, not `transcript_unreadable`; no WSL branch v1), `parseCodexHookTranscript` (ParsedTranscript shape over the adapter's exported `mapCodexLine`; same OPT-IN `collectToolCalls` contract as `parseTranscript`, and the same `capToolCallInput` bound on observed args; head+tail over budget so session_meta identity survives; tool calls from the OBSERVED args keys — `custom_tool_call.input` fixture-verified, `function_call.arguments` source-verified at rust-v0.147.0; tolerant JSON-string parse; NO `result` join — 0.147.0 persists no success flag on `*_output` rows; `compacted` rows become boundary positions), and `discoverNewestCodexRollout` (bounded newest-first walk over the dated live store, then a flat pass over the archived store under the SAME 4096 dirent cap — skipped once the cap trips; id-in-filename match, and an id-matched archived hit keeps `transcript_discovered` (never relabelled `_newest`, which hook.ts reads as a guess and bars from the relay); symlink-reject — the fallback for `transcript_path: null` or a moved rollout, and the seam for SIGKILL'd sessions, which never fire SessionEnd). Engine-free by construction; never imports discover.ts. Pinned by `test/codex-hook-lane.test.ts` + `test/codex-hook-lane-archived.test.ts` + the runHook-driven matrix in `test/memorable-relay.serial.test.ts`.diff --git a/docs/architecture/key-files/canonical-reconciliation.md b/docs/architecture/key-files/canonical-reconciliation.mdindex abb25c3d1b..7ed6abd1d9 100644--- a/docs/architecture/key-files/canonical-reconciliation.md+++ b/docs/architecture/key-files/canonical-reconciliation.md@@ -6,4 +6,4 @@- `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; managed extraction uses journaled publication and a durable completion receipt after trusted local source-wide authority checks and, for filesystem publication, owner preflight.-- `src/core/persistence/grandfather.ts` — provider-free canonical publication for the grandfather compatibility flag on active managed Markdown pages. Admission retains a checkpointed request UUID, exact source/incarnation/page/revision identity and a private rollback snapshot. Publication preserves chunks/vectors and only already-valid text seals, carries matching atom scan state across the metadata hash change, and defers embeddings without queuing fact extraction. Explicit validation choices, archived sources and non-Markdown artifacts remain untouched; unpublished file edits refuse. The unmanaged migration keeps its bounded SQL batches. `test/grandfather-managed.test.ts` covers both engines, replay, races and preserved artifacts; the unchanged local-install lifecycle exercises the public upgrade path.+- `src/core/persistence/grandfather.ts` — provider-free canonical publication for the grandfather compatibility flag on active managed Markdown pages. Admission retains a checkpointed request UUID, exact source/incarnation/page/revision identity and a private rollback snapshot. Publication preserves chunks/vectors and only already-valid text seals, carries matching atom scan state across the metadata hash change, and defers embeddings without queuing fact extraction. Explicit validation choices, archived sources and non-Markdown artifacts remain untouched; unpublished file edits refuse. Pages under a declared `storage.db_only` dir without a local cache file publish database-only. The committed revision is returned so the migration's verify phase can tell a later rewrite from a lost write. The unmanaged migration keeps its bounded SQL batches. `test/grandfather-managed.test.ts` covers both engines, replay, races and preserved artifacts; the unchanged local-install lifecycle exercises the public upgrade path.diff --git a/docs/architecture/key-files/commands-2.md b/docs/architecture/key-files/commands-2.mdindex 45f7f8e444..39d5049a19 100644--- a/docs/architecture/key-files/commands-2.md+++ b/docs/architecture/key-files/commands-2.md@@ -5,11 +5,13 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGELDoctor's embedding-dimension warning treats existing chunks as existing data even when every vector is missing. It directs the operator to a verified database backup and a brain-wide migration preview, followed only by explicitly approved total spending authorization; it never recommends forced reinitialization for that case. `test/doctor.test.ts` pins this recovery guidance.+- `src/commands/doctor/checks/{persistence-capacity,parked-effects}.ts` — `persistence_capacity` (OPS) warns when a principal or the brain reaches 80% of permanent request IDs or receipt bytes (via `capacityDiagnostics`) and prints one `gbrain config set <key> <value>` per brain-wide key, using the largest value any scope needs for about one more year; transient caps never warn. `parked_effects` (BRAIN) reads the partial parked-effect index, counts exactly, samples 20, and names each parked page with its `retry-effects ... --dry-run` command. Both report `exact`/`inspected`/`truncated` details; an unreadable state is warn, never clean. Tests: `test/persistence-capacity.test.ts`, `test/persistence-effect-parking.test.ts`.+- `src/commands/doctor/checks/sync-failures.ts` — reads managed durable cursor/receipt state even when its compatibility ledger is absent. An unavailable read is unknown/warn, not healthy; local findings carry diagnostics and remote findings contain only source-scoped aggregates. Legacy remediation stays separate from explicit managed retry. Tests: `test/persistence-sync-failures.serial.test.ts`, `test/doctor-report-remote.serial.test.ts`.- `src/commands/doctor.ts` — `gbrain doctor [--json] [--fast] [--fix] [--dry-run] [--index-audit] [--no-migrate]`: health checks. `checkPostgresCancellationDriver` (`postgres_cancellation_driver`) inspects a real reserved runtime owner through the shared cancellation helper: unsupported `discard()` is a typed local failure with a repair link, connection/deadline failure is a warning, and PGLite is exempt. The bounded reserve releases late arrivals and does not make general engine connect require cancellation, preserving broken-install diagnostics. `--no-migrate` keeps doctor observational: the CLI connects with `probeOnly` so a clean-or-behind schema is reported as-is instead of being auto-migrated before the checks run. The file is a façade carrying `buildChecks`/`runDoctor` and output rendering; the check-function library lives in bundles under `src/commands/doctor/checks/` plus four tail-cluster modules under `src/commands/doctor/` (see that entry), all re-exported here so the full surface is unchanged — structural guards pin its source text via `test/helpers/doctor-source.ts`, never by reading this file alone. Checks include `jsonb_integrity` + `markdown_body_completeness` (reliability), `schema_version` (fails loudly when `version=0`, routes to `gbrain apply-migrations --yes`; a version AHEAD of this client's `LATEST_VERSION` warns "upgrade this client"; and when the ledger reads current, a read-only `detectMissingColumns` diff from `src/core/schema-verify.ts` runs INSIDE the ledger-current branch — a PgBouncer-swallowed ALTER TABLE can advance `config.version` over a physically narrower table, so missing live columns downgrade the ok to a warn naming them with the `gbrain init --migrate-only` hint; diff failure is best-effort and the ledger ok stands; positional wiring pinned by `test/doctor-schema-column-diff.test.ts`), `upgrade_errors` (async `checkUpgradeErrors(engine)` over `~/.gbrain/upgrade-errors.jsonl`: the warn downgrades to an EXPLICIT status-ok line — never silence — only when the past failure is provably superseded, i.e. the running binary is at/past the failed target version AND the schema verifies current via `engine.getConfig('version')`; a missing engine or unverifiable schema keeps the warn, fail-closed, because `self-upgrade` swaps the binary before `post-upgrade` runs migrations and the binary alone can lie; pinned by `test/doctor-upgrade-errors.test.ts` + `test/doctor-upgrade-errors-stale.test.ts`), `queue_health` (Postgres-only: stalled-forever active jobs started_at > 1h, waiting-depth-per-name > threshold default 10 via `GBRAIN_QUEUE_WAITING_THRESHOLD`, and dead-lettered subagent jobs with `last_error` matching the `prompt_too_long` classifier in last 24h), `sync_failures` (`[CODE=N, ...]` breakdown for unacked-warn + acked-ok; severity comes from the shared `decideSyncFailureSeverity` in `src/core/sync-failure-ledger.ts` so the LOCAL and REMOTE/thin-client doctor surfaces can never drift — a stuck bookmark escalates to FAIL once an OPEN failure has blocked past the staleness window or ≥10 files block, while already `auto_skipped` rows stay a visible WARN), `rls_event_trigger` (healthy `evtenabled` set is `('O','A')` only; fix hint `gbrain apply-migrations --force-retry 35`), `graph_coverage` (short-circuits to ok when `SELECT COUNT(*) FROM pages WHERE type IN ('entity','person','company','organization')` returns 0; WARN hint is `gbrain extract all`), `embedding_column_registry` (probes each declared column via Postgres `format_type(atttypid, atttypmod)` to catch dim mismatch with a paste-ready `gbrain config set embedding_columns '{...}'` hint, probes HNSW index presence via `pg_indexes`, computes default-column population via `COUNT(*) FILTER (WHERE <col> IS NOT NULL) / COUNT(*)` warning below 90% except empty brains where chunk_count=0 short-circuits to ok; PGLite parity via `executeRaw`), and `skill_brain_first` (walks SKILL.md via `autoDetectSkillsDirReadOnly`, calls `analyzeSkillBrainFirst()` from `src/core/skill-brain-first.ts` per file with structured `Check.issues[]`; warn states `missing_brain_first`/`brain_first_typo`, ok states `compliant_callout`/`compliant_phase`/`compliant_position`/`exempt_frontmatter`/`no_external`; snapshot+diff audit at `~/.gbrain/audit/skill-brain-first-YYYY-Www.jsonl`). `--fix` delegates inlined cross-cutting rules to `> **Convention:** see [path](../path).` callouts via `src/core/dry-fix.ts` (and MISSING_RULE_PATTERNS for the brain-first callout); `--fix --dry-run` previews. `--index-audit` (Postgres-only, informational, no auto-drop) reports zero-scan indexes from `pg_stat_user_indexes`. Every DB check runs under a progress phase; `markdown_body_completeness` runs under a 1s heartbeat. `runDoctor` uses `autoDetectSkillsDirReadOnly` (from `src/core/repo-root.ts`; install-path fallback so `cd ~ && gbrain doctor` finds bundled skills); `--fix` carries a D6 install-path safety gate that refuses auto-repair when `detected.source === 'install_path'` (would rewrite the bundled tree). The Lane D supervisor check at `doctor.ts:1011-1043` consumes `summarizeCrashes(events)` from `src/core/minions/handlers/supervisor-audit.ts` (warn at `>=1` real crash; ok message has `clean_exits_24h=N`; warn message has `runtime=A oom=B unknown=C legacy=D` per-cause breakdown) so OOM/runtime/unknown crashes are distinguishable from clean code=0 worker drains; cross-surface parity with `gbrain jobs supervisor status` is pinned by source-grep wiring assertions requiring the breakdown substrings in BOTH `doctor.ts` and `jobs.ts`. `checkSyncFreshness` (exported, in `runDoctor` local + `doctorReportRemote` thin-client) is a staleness probe: warns at 24h, fails at 72h or never-synced; future-`last_sync_at` warns ("clock skew") instead of falling through ok; env overrides `GBRAIN_SYNC_FRESHNESS_WARN_HOURS`/`GBRAIN_SYNC_FRESHNESS_FAIL_HOURS` (invalid fall back with once-per-process stderr warn via `_resolveSyncFreshnessHours`); failure messages embed `source.id` so the printed `gbrain sync --source <id>` matches. A source holding a LIVE, non-expired per-source sync lock (`inspectLock(engine, syncLockId(source.id))` from `src/core/db-lock.ts`) is reported as actively syncing (the message names the holder pid + host) and counted in `synced_recently_count`, NOT flagged stale — the live lock is the only honest in-progress signal (checkpoint banking can't distinguish in-progress from wedged: a blocked sync banks its files but writes no anchor). A blocked/failed sync's process has exited (no lock row) and a wedged holder stops refreshing (TTL lapses), so either falls through to the stale path and is never masked; the dynamic `db-lock` import is swallowed to a no-op on a stub engine or pre-lock-table brain, so this can only ADD an in-progress verdict, never suppress a real stale one. The in-progress note is appended to whatever verdict the buckets produce and is empty when nothing is syncing, so steady-state messages stay byte-for-byte unchanged. It has a `localOnly`-gated git short-circuit (`runDoctor` passes `localOnly: true`; `doctorReportRemote` runs in the HTTP MCP server `src/commands/serve-http.ts` and keeps default `false` so that path never walks DB-supplied `local_path` via subprocess — trust boundary). The local predicate mirrors sync's "do work?" gate (HEAD == `last_commit` AND working tree clean via `requireCleanWorkingTree: 'ignore-untracked'` so a quiet repo with only untracked dirs is `unchanged` not SEVERE, AND `chunker_version === CURRENT`); the inline SELECT carries `last_commit + chunker_version + newest_content_at`. The REMOTE path computes lag via `lagFromContentMs(newest_content_at, lastSync, now)` from the stored column, NO git subprocess; LOCAL fall-through and the `< 0` clock-skew check stay on raw wall-clock. Three-bucket count math populates `Check.details = {unchanged_count, synced_recently_count, stale_count}` with the invariant `sum === sources.length`. `checkCycleFreshness` is DELIBERATELY NOT git-short-circuited or content-relativized (`last_commit == HEAD` can't answer "did the full cycle complete?"; a sync can succeed while later cycle phases fail; different axis `last_full_cycle_at`). Pinned by `test/doctor.test.ts` (incl. the IRON-RULE guard banning stale verb names, the sync_freshness boundary matrix, the D4 guard verifying git probes are NEVER called when `localOnly` is unset/false, the three-bucket invariant, and the untracked-folders / remote-never-shells-out trust-boundary cases). `pglite_data_dir` check: fs-only check that runs when a PGLite brain FAILS to connect (`!fastMode && !engine && config.engine === 'pglite'`, placed after `orphan_clones`, before the DB-checks gate): `computePgliteDataDirCheck(dataDir, diagnosis)` (exported pure fn, `computeWorkerOomLoopCheck` convention) maps the `inspectPgliteDataDir` verdict to a Check — corruption-likely/looks-healthy-but-unopenable/unsupported-layout → `fail` naming `gbrain pglite-repair --dry-run`/`--yes` or the rebuild path, live-lock/missing-dir → `warn`; all `remediation_status: 'human_only'` (Minion remediation needs the DB that is down). Escalates when ≥2 repair attempts failed inside 7 days (unclean-shutdown genesis still active → engine-switch pointer) and reports retained backup-dir inventory (orphan_clones disk-visibility class). Registered in `doctor-categories.ts` OPS_CHECK_NAMES. Pinned by `test/doctor-pglite-datadir.test.ts`. silent-failure checks: `content_hash_duplicates` (single GROUP BY over `(source_id, content_hash)` with FILTER aggregates — never N² — flagging hash groups that hold BOTH a bare and a path-prefixed slug, the wrong-import-root pattern; warn carries sample pairs + the `pages delete` → `purge-deleted --older-than 0` remediation); `undeclared_db_only_pages` (per source with a local repo: markdown pages with no backing file outside every declared + derive-phase-default db_only prefix — the one check deliberately allowed to stat the repo); `db_only_collector_collision` (configured recipe `output_paths` inside a declared db_only dir — auto-gitignore means sync AND import silently skip the collector's files; same warning fires in sync's `manageGitignore` at config-write time). All warn-level, engine-parity pinned by `test/e2e/doctor-silent-death-parity.test.ts`; units in `test/doctor-silent-death-checks.test.ts`. `graph_signals_coverage` check wired into both `runDoctor` (local) and `doctorReportRemote` (HTTP/JSON thin-client path). Reads `search.graph_signals` config first, falls back to mode default; silent `ok` when disabled. Computes inbound link coverage on the page set; warns at <10% with `gbrain extract all` fix hint; `ok` at ≥30% ("fire on most queries") and 10-29% ("fire occasionally"), each with the percentage embedded. Pinned by cases in `test/doctor.test.ts`. `subagent_provider` check (layer 3 of 3). Resolves subagent model config in runtime order (`models.subagent` > `models.default` > `models.tier.subagent` > built-in default) and warns when the selected model lacks native tool-loop capability (message names the bad value + paste-ready fix `gbrain config set models.tier.subagent anthropic:claude-sonnet-4-6`); also warns when `models.default` would sneak `subagent` into a non-Anthropic provider via tier inheritance. OK when subagent tier resolves to Anthropic. Tests in `test/doctor.test.ts`. `computeWorkerOomLoopCheck(engine)` is the single authoritative OOM-loop signal, unioning supervised `summarizeCrashes(readRecentSupervisorEvents(24)).by_cause.rss_watchdog` (cross-week read via `readRecentSupervisorEvents` so a Monday window can't lose Sunday) + bare-worker `minion_jobs error_text='aborted: watchdog'` count (Postgres-only; the same source `queue_health` subcheck 3 reads). Cap comes from the latest `rss_watchdog_loop` breaker alert's `max_rss_mb`, else `resolveDefaultMaxRssMb()` fallback. fail at breaker-tripped or oomKills≥5, warn at ≥1, null otherwise. `computePoolReapHealthCheck(engine)` is the Postgres-only `pool_reap_health` check reading `readRecentPoolRecoveries(1)` — fail when reconnect failures>0 (reconnect throwing is the actionable signal), warn at ≥10 reaps/hr (pooler thrash), null otherwise. Both registered in `buildChecks` after the `supervisor` block. The `supervisor` causeStr carries `rss=N (see worker_oom_loop)` and `queue_health`'s watchdog message cross-references `worker_oom_loop`. `DoctorReport.top_issues` + the cause-ranked render header. `worker_oom_loop` + `pool_reap_health` registered under ops in `doctor-categories.ts`. Pinned by `test/doctor-worker-oom-loop.test.ts`, `test/doctor-pool-reap-health.test.ts`. `supervisor_singleton` check, a SEPARATE check from `supervisor` (same split precedent as the niceness check) so a singleton-divergence warn can't clobber the crash/liveness precedence. Runs only when a `started` supervisor event was seen in the last 24h and a live engine is available. Reads the queue-scoped DB lock row (`gbrain_cycle_locks WHERE id = supervisorLockId(queue)`) and compares the lock holder (`holder_host:holder_pid`) against the local pidfile holder via the pure `classifySupervisorSingleton`. `mismatch` → warn (a second supervisor may be running with a different `--max-rss`; message names both holders, the effective cap from the `started` event's `max_rss_mb`, and the fix `gbrain jobs supervisor stop`); `single` → ok (names holder + cap); `no_lock` → no check emitted. Best-effort try/catch (silent skip on brains without the lock table). Registered under ops in `doctor-categories.ts` as `supervisor_singleton`. Pinned by `test/supervisor-db-lock.test.ts` + `test/doctor.test.ts`. `checkBatchRetryHealth`: `batch_retry_health` check surfacing Supavisor circuit-breaker incidents. Wired into both `runDoctor` (local) and `doctorReportRemote` (thin-client). Reads last 24h. States: `ok` (zero exhausted in 24h OR <3 from a single site), `warn` (>=3 same-site OR >=5 cross-site), `fail` (>=20 sustained breaker). Surfaces bad `GBRAIN_BULK_*` env at doctor startup. Corrupt-JSONL tolerant. Paste-ready fix hints in every warn/fail message. Also reads `readRecentDbDisconnects(24)` and appends `Disconnect-call audit: N call(s) in 24h (most recent caller: <frame>).` to ALL three message paths so connection-incident signal is greppable from one `gbrain doctor --json` call (module-import wrapped in try/catch so older brains without the audit file degrade silently). Pinned by `test/doctor-batch-retry.test.ts` (10 cases). three checks wired into `runDoctor()` and the JSON envelope, all warn-only with paste-ready fix hints. (1) `checkSourceRoutingHealth(engine)` scans up to 200 pages on federated brains and flags pages whose `source_id` doesn't match what `resolveSourceWithTier()` would have picked for their `source_path`; single-source brains short-circuit to `ok`; the 200-page cap is total across the brain so doctor stays under 5s. (2) `checkOauthConfidentialHealth(engine)` probes registered confidential clients for `/token` reachability. (3) `checkAutopilotLockScope()` (pure, no engine) compares the resolved lock path to `$GBRAIN_HOME`; warns when set but the lock lives elsewhere, with a PID-safe inspection hint (`kill -0 <pid>` before deletion). Pinned by `test/doctor-v0_37_7_checks.test.ts`. `buildChecks(engine, args, dbSource, connectError?): Promise<Check[]>` exported as a test seam; the optional `connectError` is the connect failure captured by the CLI's dead-DB fallback, which the null-engine path turns into a SYNTHESIZED classified `connection` fail entry (so `checks[name=="connection"]` exists in every failure shape — smoke-test branches on it). The `connection` check's failure path classifies via `src/core/pg-access-classify.ts` into a redacted message + `details: {reason, transient, fix_hint}` naming `gbrain db-repair` (deliberately NOT `remediation[]`/`makeRemediationStep` — that lane feeds `--remediate`, whose Minion jobs need the very DB that's down; applicator boundary: `--remediate` = brain-DATA quality with a live engine, `db-repair` = DB ACCESS engine-free). The URL-only `pgbouncerPrepareCheck` helper and the engine-free `db_repair_recurrence` check run BOTH before the connection check and in the dead-DB filesystem lane; `pglite_scale` (engine-fit, warn at ≥1000 pages on pglite) runs in the DB phase. `computeDoctorReport(checks, extras?)` accepts optional `{engine, db_url_source}` which land as additive `DoctorReport.engine` / `DoctorReport.db_url_source` JSON fields (schema_version stays 2). `runDoctor` is a thin wrapper: `buildChecks → computeDoctorReport → render + process.exit`. All 10 `process.exit` sites stay in the wrapper; the two early-return paths (no engine, connection failure) return partial check lists instead of inline exits (observable output identical). Pinned by `test/doctor-behavioral.test.ts` (13 cases: pure aggregation math over `computeDoctorReport`, orchestrator cases for `--fast` skip set + `--json` flag + no-engine partial path + snapshot of load-bearing check names) and `test/doctor-cli-smoke.serial.test.ts` (1 subprocess case spawning `bun run src/cli.ts doctor --json` against a fresh PGLite tempdir, asserting schema_version=2 envelope, status enum, non-empty checks array — the render-path coverage buildChecks-only tests miss; quarantined `.serial` because PGLite write-locks don't play with parallel runners). three checks wired into `runDoctor()` and the JSON envelope: `oversized_pages` (warns on pages exceeding `content_sanity.bytes_warn`), `scraper_junk_pages` (warns on live DB pages matching any junk pattern that escaped ingest), and `content_sanity_audit_recent` (reads the last 7 days of audit events, aggregates by pattern+source). Default scans the 1000 most-recent pages; `--content-audit` opts into a full scan. All three warn-only with paste-ready fix hints (junk → `gbrain sources audit <id>` + `git rm` source-of-truth, oversize → split or accept). two checks wired into `runDoctor()` + the JSON envelope: `quarantined_pages` (counts pages carrying the `quarantine` marker via `engine.executeRaw` JSONB `?` existence, works on PGLite + Postgres; warn-only with a `gbrain quarantine list` hint) and `flagged_pages` (counts `content_flag` pages — searchable but odd; warn-only). Both skip gracefully (status ok, "Skipped") on engines/brains where the probe errors. Pinned by `test/doctor.test.ts`. `home_dir_in_worktree`: filesystem check walking up from `gbrainPath()` toward `$HOME` looking for a `.git` directory (main repo) or `.git` file (linked worktree pointer; Conductor + git-worktrees topology). Walk terminates at `$HOME` so a `.git` above the user's home doesn't false-positive. Honors `GBRAIN_HOME` (appends `.gbrain` to the override). Warn (not fail) with worktree-root path + paste-ready fix pointing at `GBRAIN_HOME` override or moving the brain. `--remediation-plan [--json] [--target-score N]` prints what would run (stable `id`, `idempotency_key`, `severity`, `est_seconds`, `est_usd_cost`, `depends_on`); `--remediate [--yes] [--target-score N] [--max-usd N]` submits each plan step as a Minion job in dependency order, re-checking score between steps. `--target-score N` defaults to 90; refuses to start when target exceeds `maxReachableScore()` and lists what's missing. `--max-usd N` is the cron-safety guard — submission refuses when the plan's `est_total_usd_cost` exceeds the cap. JSON envelope adds a `Check.remediation` field (additive, schema_version unchanged). Pinned by tests in `test/doctor.test.ts`. 4 checks: `abandoned_threads`, `calibration_freshness`, `grade_confidence_drift` (mitigation surface; math ships later), `voice_gate_health`. Schema health is a two-check pair: `schema_version` resolves through `schemaVersionHealth` (`src/core/schema-version-health.ts`, shared with the remote doctor report; a DB AHEAD of the client warns with an upgrade-this-client hint rather than suggesting migrations), and on ledger-current brains a read-only `schema_columns` check diffs live columns against the expected schema (`detectMissingColumns`, dynamically imported inside the ledger-current branch — positional guard in `test/doctor-schema-column-diff.test.ts`) and warns naming the missing columns with the `gbrain init --migrate-only` hint.-- `src/commands/doctor/` — the doctor module directory (the meat behind the `doctor.ts` façade). `checks/` holds the check-function library in bundles grouped by concern (`core-health.ts`, `queue-jobs.ts`, `extraction-sync.ts` (its `atom_provenance_drift` check scopes drift to page-bound atoms and splits it into `source_changed` / `source_gone`; atoms with no `source_slug` — transcript-origin `source_path`-only rows, whose hash is over a file and whose page liveness cannot be resolved by slug — are reported as their own `slug_unbound` count and never enter the drift total or the WARN ratio), `graph-embedding.ts`, `search-eval.ts`, `calibration.ts`, `consolidation-cycle.ts`, `pglite-worker.ts`, `routing-federation.ts`, `verbs-reflex.ts`, `stale-mentions.ts`, `engine-fit.ts` — the last carrying `pglite_scale` + the engine-free `db_repair_recurrence` over the db-repair receipts); `schema-pack-checks.ts`, `report-remote.ts`, `bootstrap-checks.ts`, and `skill-checks.ts` are the four tail-cluster modules (schema-pack checks, the remote/thin-client doctor report, bootstrap checks, skill checks). All are re-exported by the façade. Structural guards that pin doctor source text load it through `test/helpers/doctor-source.ts`: `doctorSource()` concatenates the façade plus every `src/commands/doctor/**/*.ts` (façade first, then sorted) so a module move can never take a pinned string out of a guard's sight; `doctorFileSource(rel)` reads one named file for positional/ordering assertions; the helper also feeds the `doctor-source-helper` detector in `scripts/classify-tests.ts`. `facadeExpansion` in `scripts/generate-flag-registry.ts` keeps this directory on the doctor command's flag-scan surface.+- `src/commands/doctor/` — the doctor module directory (the meat behind the `doctor.ts` façade). `checks/` holds the check-function library in bundles grouped by concern (`core-health.ts`, `queue-jobs.ts`, `extraction-sync.ts` (its `atom_provenance_drift` check scopes drift to page-bound atoms and splits it into `source_changed` / `source_gone`; atoms with no `source_slug` — transcript-origin `source_path`-only rows, whose hash is over a file and whose page liveness cannot be resolved by slug — are reported as their own `slug_unbound` count and never enter the drift total or the WARN ratio), `graph-embedding.ts`, `search-eval.ts`, `calibration.ts`, `consolidation-cycle.ts`, `pglite-worker.ts`, `routing-federation.ts`, `verbs-reflex.ts`, `stale-mentions.ts`, `timeline-history.ts` (`timeline_history`: database-only timeline rows, bounded to 2,000 pages / 10 s with exact-or-lower-bound counts, kept non-round-trippable rows informational, repair `gbrain repair timeline`), `derived-visibility.ts` (`derived_visibility`: atoms and synthesized concepts without explicit visibility or looser than their origin, one exact aggregate, repair `gbrain repair visibility`), `engine-fit.ts` — the last carrying `pglite_scale` + the engine-free `db_repair_recurrence` over the db-repair receipts); `schema-pack-checks.ts`, `report-remote.ts`, `bootstrap-checks.ts`, and `skill-checks.ts` are the four tail-cluster modules (schema-pack checks, the remote/thin-client doctor report, bootstrap checks, skill checks). All are re-exported by the façade. Structural guards that pin doctor source text load it through `test/helpers/doctor-source.ts`: `doctorSource()` concatenates the façade plus every `src/commands/doctor/**/*.ts` (façade first, then sorted) so a module move can never take a pinned string out of a guard's sight; `doctorFileSource(rel)` reads one named file for positional/ordering assertions; the helper also feeds the `doctor-source-helper` detector in `scripts/classify-tests.ts`. `facadeExpansion` in `scripts/generate-flag-registry.ts` keeps this directory on the doctor command's flag-scan surface.- `src/commands/doctor/checks/default-source-path.ts` — the gathering wrapper on the doctor surface: reads the `default` sources row, page counts (live + file-backed), `sync.repo_path` resolution, and the leak-guard collision, then delegates the verdict to `assessDefaultSourcePath`. Only gathers the fallback-topology inputs when the pointer is actually null; returns null for the skip verdict.@@ -25,6 +27,8 @@ Doctor's embedding-dimension warning treats existing chunks as existing data eve- `src/commands/dream-retriage.ts` — `gbrain dream retriage`: re-scores the corpus via the shared `runTriagePass` (with `maxMs: 0` — operator sweeps run to completion; `--limit` slices the discovered list caller-side) and reconciles the queued private-queue backlog: synth-v2 rows verdict-gated, plus any row stranded in a provably-dead `dream-inline-*` queue regardless of key family (patterns children, legacy grammars) — doctor's orphaned_private_queue check points here, so the repair selects everything the check can flag. Liveness uses ownership correlation (mirrors the doctor check): a live `gbrain_cycle_locks` row suppresses conversion only for queues born at/after its `acquired_at`; an older crashed cycle's queue stays repairable while a new cycle runs (unknown birth/acquisition stays fail-safe possibly-live). Spend-gated: upfront estimate via `canonicalLookup` on the resolved triage model, confirmation above `SPEND_CONFIRM_USD` ($5, in `dream-retriage-constants.ts`; unpriced models gate on `UNPRICED_CONFIRM_FILES`=500) unless `--yes` (`--json` non-interactive requires `--yes` above the gate); `--max-usd` soft-stops via the pass's `shouldStop` seam (estimate-based). `--reconcile-queue` (opt-in — cancels queued work): selects waiting/delayed/paused `dream:synth-v2:%` jobs across ALL queues, parses keys with `parseSynthV2Key`, then per row, reading THE shared gate (`passesTriageGate` from `triage-rescue.ts` — threshold pass OR the verified-segment rescue; a hand-rolled `score >= threshold` here would cancel exactly the jobs the rescue admitted): matched below the gate → cancel; matched above the gate but `waiting` in a stale `dream-inline-*` queue → cancel as `converted_for_resubmit` (the backlog conversion — cancelled rows release their idempotency slot so the next cycle re-adds into a live drain); matched above the gate in a live queue → keep; matched-but-unscored → keep (never cancel on missing data); unmatched → keep unless `--cancel-unmatched`; key-source vs `data.source_id` disagreement → skip + `source_mismatch`; status re-checked immediately before each cancel (rows turned `active` are skipped; residual race matches cancelJob's best-effort contract). Legacy `dream:synth:` keys are excluded at the SQL LIKE filter — never candidates. `--source` scopes cancels (`other_source` counted); `--threshold`/`--since`/`--force`/`--dry-run` (zero judge calls, zero cancels — cached scores only, uncached files report `needs_triage`). `--audit-rejects <n>` re-judges N stride-sampled files that the gate actually REJECTED (below threshold AND not rescued — auditing a rescued file as a rejection would misreport the disagreement rate) with the SYNTHESIS model and reports that rate — the operator calibration loop. Reports carry `rescued`/`verified_segments` so a rescued file reads as accepted everywhere the command renders. Exit 0 success (even when nothing cancelled), 1 no engine/corpus, 2 usage or declined spend gate. Pinned by `test/dream-retriage.test.ts`.+- `src/commands/dream-reset-key.ts` — `gbrain dream reset-key <base-key>` persists a breaker reset for one dream key (deaths finished before it stop counting; survives restarts); `gbrain dream reset-key --list [--json]` lists tripped keys with counts and reset commands. Dispatched from `dream.ts` before cycle flag parsing. The `dream_paid_loop` doctor check (`src/commands/doctor/checks/dream-breaker.ts`) warns on keys at the limit through the same counter.+- `src/commands/dream.ts` — `gbrain dream` CLI; thin alias over `runCycle`. Flags: `--dry-run`, `--json`, `--phase <name>`, `--pull`, `--dir <path>`, `--input <file>` (ad-hoc transcript, implies `--phase synthesize`), `--date YYYY-MM-DD`, `--from <d> --to <d>` (backfill range), `--unsafe-bypass-dream-guard` (plumbed through `runCycle.synthBypassDreamGuard` → `SynthesizePhaseOpts.bypassDreamGuard` → `discoverTranscripts({bypassGuard})` / `readSingleTranscript({bypassGuard})`; loud stderr warning at synthesize-phase entry; never auto-applied for `--input`). Conflict detection: `--input` + `--date` exits 2. ISO date validation. `--dry-run` runs the scored triage pass but skips synthesis (NOT zero LLM calls). Exit 1 on status=failed. `resolveBrainDir` returns `string | null` (order: `--dir` → resolved `--source`'s `local_path` → global `sync.repo_path` → null); a checkout-less postgres/Supabase brain runs DB-only phases (incl. `resolve_symbol_edges`) and skips the 6 filesystem phases with `details.reason: 'no_brain_dir'`; `runDream` owns the only hard error (no checkout AND no engine). When `--source` resolves but has no on-disk checkout, returns null (DB-only) rather than borrowing another source's global `sync.repo_path` (would mix scopes). Pinned by `test/dream-postgres.serial.test.ts`. `--drain [--window <seconds>]` for `--phase extract_atoms`: `runDrain()` bypasses the pack-gate and runs the single-hold bounded drain from `src/core/cycle/extract-atoms-drain.ts` under the same `cycleLockIdFor(sourceId)` the routine cycle uses (concurrent autopilot tick defers with `cycle_already_running`), reporting `{extracted, skipped, remaining}`. Exits `EXIT_DRAIN_INCOMPLETE=3` while `remaining > 0`; a null backlog count (count query FAILED) is also exit 3, never a drained success; `LockUnavailableError` → `cycle_already_running` skip (also exit 3). The `extract_atoms_backlog` doctor check (`computeExtractAtomsBacklogCheck`) surfaces the silent pack-gated backlog with the exact `--drain` command; pack-gated cycle skips carry a greppable `pack_gated:true` marker. `dream retriage` dispatches on `args[0] === 'retriage'` BEFORE `parseArgs` (its flag set never collides with cycle flags; `dream retriage --help` prints subcommand help engine-free per the same IRON RULE).- `src/commands/dream.ts` — `gbrain dream` CLI; thin alias over `runCycle`. Flags: `--dry-run`, `--json`, `--phase <name>`, `--pull`, `--dir <path>`, `--input <file>` (ad-hoc transcript, implies `--phase synthesize`), `--date YYYY-MM-DD`, `--from <d> --to <d>` (backfill range), `--unsafe-bypass-dream-guard` (plumbed through `runCycle.synthBypassDreamGuard` → `SynthesizePhaseOpts.bypassDreamGuard` → `discoverTranscripts({bypassGuard})` / `readSingleTranscript({bypassGuard})`; loud stderr warning at synthesize-phase entry; never auto-applied for `--input`). Conflict detection: `--input` + `--date` exits 2. ISO date validation. `--dry-run` runs the scored triage pass but skips synthesis (NOT zero LLM calls). Exit 1 on status=failed. Source scope enters the shared 6-tier resolver whenever `--source <id>` is given OR `GBRAIN_SOURCE` is set (a null explicit falls through to tier 2: validated + `assertSourceExists`, so an invalid/unknown env value is a clean exit 1; the `__all__` sentinel is excluded and falls through to the unscoped routing, which already spans every source); an env scope naming the brain's default-like source keeps the full implicit cycle (#4700 semantics), any other keeps the `--source` freshness boundary. `resolveBrainDir` returns `string | null` (order: `--dir` → resolved source's `local_path` → global `sync.repo_path` → null); a checkout-less postgres/Supabase brain runs DB-only phases (incl. `resolve_symbol_edges`) and skips the 6 filesystem phases with `details.reason: 'no_brain_dir'`; `runDream` owns the only hard error (no checkout AND no engine). When `--source` resolves but has no on-disk checkout, returns null (DB-only) rather than borrowing another source's global `sync.repo_path` (would mix scopes). Pinned by `test/dream-postgres.serial.test.ts`. `--drain [--window <seconds>]` for `--phase extract_atoms`: `runDrain()` bypasses the pack-gate and runs the single-hold bounded drain from `src/core/cycle/extract-atoms-drain.ts` under the same `cycleLockIdFor(sourceId)` the routine cycle uses (concurrent autopilot tick defers with `cycle_already_running`), reporting `{extracted, skipped, remaining}`. Exits `EXIT_DRAIN_INCOMPLETE=3` while `remaining > 0`; a null backlog count (count query FAILED) is also exit 3, never a drained success; `LockUnavailableError` → `cycle_already_running` skip (also exit 3). The `extract_atoms_backlog` doctor check (`computeExtractAtomsBacklogCheck`) surfaces the silent pack-gated backlog with the exact `--drain` command; pack-gated cycle skips carry a greppable `pack_gated:true` marker. `dream retriage` dispatches on `args[0] === 'retriage'` BEFORE `parseArgs` (its flag set never collides with cycle flags; `dream retriage --help` prints subcommand help engine-free per the same IRON RULE).diff --git a/docs/architecture/key-files/commands-3.md b/docs/architecture/key-files/commands-3.mdindex c094b98929..e5658f7fdd 100644--- a/docs/architecture/key-files/commands-3.md+++ b/docs/architecture/key-files/commands-3.md@@ -31,7 +31,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/extract-conversation-facts.ts` + `src/core/cycle/conversation-facts-backfill.ts` — bulk fact extraction for long-form conversation pages. Walks conversation/meeting/slack/email/imessage/imessage-daily pages, splits them into time-windowed segments (30-min gap or 30-msg cap), prepends a topical/temporal header, and uses the strict `extractFactsFromTurnWithOutcome()` path so provider and output failures remain retryable instead of becoming successful empty pages. Invariants: **strict per-source core** (`runExtractConversationFactsCore({sourceId, ...})` always takes one sourceId; CLI + cycle phase each do their own multi-source iteration because `PHASE_SCOPE='source'` is taxonomy-only); **bounded two-phase enumeration** (paginated `listPages({type, sourceId, limit:10})`; per-page body cap `MAX_PAGE_BODY_BYTES=25MB`); **page-global `row_num` accumulator** (the facts unique index is `(source_id, source_markdown_slug, row_num)`); **versioned snapshot-bound outcomes** (`cli:extract-conversation-facts:terminal:v2` for complete pages and a separate `non-extractable:v2` source for recognized pages with no eligible segment); **operation checkpoints are scheduling hints only** and never suppress a replay without a matching v2 outcome; **optional `opts.budgetTracker?`** is used as-is, while an absent tracker is created with `maxCostUsd`; **body reads cover compiled truth, timeline, and configured raw-transcript sidecars**; **`facts.extraction_enabled` kill-switch** with `--override-disabled`; **`--types LIST` allowlist** (`conversation,meeting,slack,email,imessage,imessage-daily`); **`--background` via `maybeBackground`**; and **speaker-shaped-fold decline** — when the parse reports `unrecognized_headings` containing a speaker-shaped label (1-2 title-cased words, not in the doc-heading stoplist — the stoplist gates the DECLINE only, so a miss is warn-noise, never data loss) AND the parse produced fewer than two distinct speakers, the page is declined instead of extracted under wrong attribution: counted in `pages_skipped_unrecognized_speaker` (Result/CLI/cycle surfaces), warned to stderr with the folding pattern id, and deliberately NON-terminal (no durable audit row and no orphan cleanup, so a future parser/pattern fix retries the page); multi-speaker pages with folds proceed warn-only. The companion `conversation_facts_backfill` cycle phase is default-off, iterates every source, and enforces per-source plus brain-wide cost and wall-time caps. Migration v94 provides the partial facts index used by outcome lookups. `computeConversationFactsBacklogCheck` reports fresh completed, scanned-not-extractable, and unfinished counts separately, warning when more than 10 eligible pages lack a fresh v2 outcome. `sources audit` exposes `facts_backfill_estimate: {pages, est_segments, est_cost_usd, types}`. Pinned by `test/extract-conversation-facts.test.ts` and `test/doctor-conversation-facts-backlog.test.ts`. `--workers N` for LLM-bound fact extraction over conversation pages, with a per-page advisory lock via `src/core/db-lock.ts:withRefreshingLock` (lock id `extract-conversation-facts:<source>:<slug>`, TTL `PER_PAGE_LOCK_TTL_MINUTES=2` with 20s refresh via `Math.max(15s, 120s/6)`; `LockUnavailableError` triggers skip-and-continue with rate-limited log per (source, minute) + `pages_lock_skipped` counter + CLI exits 3 when non-zero AND no hard failures). `deleteOrphanFactsForPage(engine, sourceId, slug)` provides delete-orphans-first replay safety — wipes facts from a prior crashed run for this (sourceId, slug) before re-extracting, so a terminal audit row can never certify a partial insertFacts failure. `assertFactsEmbeddingDimMatchesConfig(engine)` is the startup preflight (throws `FactsEmbeddingDimMismatchError` with paste-ready ALTER hint BEFORE the first insert; cached per engine via WeakMap). Result type carries `pages_lock_skipped` + `orphan_facts_cleaned`. Additive `pages_skipped_unparsed`, `pages_skipped_type_mismatch`, `pages_skipped_insufficient_turns`, and `pages_skipped_since` explain the unchanged `pages_skipped` aggregate across core, CLI, workers, and cycle sources; durable completion remains separate. `--dry-run` stops after segmentation, with no parser-fallback, extractor, or embedding calls and no durable knowledge/checkpoint/receipt/rollup writes. The narrow `python-dict-utterance` registry format and its quoted/nested-example rejection are documented in [conversation parser patterns](../conversation-parser-patterns.md). Checkpoint state is a shared `cpMap: Map<slug, endIso>` (NOT a per-page-mutated `cpEntries: string[]`) so atomic `Map.set` survives parallel workers. Minion handler `extract-conversation-facts` in `src/commands/jobs.ts` round-trips `workers` via `job.data.workers` for `--background --workers 20`. Cycle config key `cycle.conversation_facts_backfill.workers` (default 1; opt-in concurrency under brain-wide cost + walltime caps). Pinned by `test/extract-conversation-facts-diagnostics.serial.test.ts` (pool workers, per-page lock skip + exit 3, delete-orphans-first replay, D15 preflight, `--workers` round-trip) + the existing extract-conversation-facts behavioral tests. with `src/commands/doctor.ts` durable outcome authority: page completion survives operation-checkpoint GC through versioned terminal audit rows (`cli:extract-conversation-facts:terminal:v2`), while recognized pages with no eligible segment use the separate `cli:extract-conversation-facts:non-extractable:v2` source. Each outcome is bound to the exact parsed snapshot: regular pages use `content_hash` plus the UTC effective date; raw-conversation sidecars and legacy null-hash pages use a canonical SHA-256 over every parser-relevant input. Selection checks the token before locking, refetches under the lock, and verifies it again before writing the outcome, so an edit cannot be certified by stale work. The strict extraction path treats provider, refusal, truncation, malformed/schema-invalid output, segment-write, cleanup, and terminal-write failures as unfinished work; bulk failures increment `pages_failed`, affect CLI/cycle receipts and exit status, and never advance the legacy checkpoint. Checkpoints are only a scheduling hint: a slug without a matching v2 outcome is replayed delete-first. `no_match`, errors, cancellation, and dry runs never become durable negatives. Result, CLI, cycle, and doctor surfaces keep completed, scanned-not-extractable, unfinished, failed, and lock-skipped counts separate. See [Conversation backfill durable outcomes](../../operations/conversation-backfill-outcomes.md) for the operator and maintainer contract. Pinned by `test/extract-conversation-facts.test.ts` and `test/doctor-conversation-facts-backlog.test.ts`. Managed bulk calls, including segmentation-only previews, refuse before queue or provider work; they are listed separately from the supported coordinated fact operation.-- `src/commands/extract.ts` — `gbrain extract links|timeline|all [--source fs|db] [--source-id <id>]`: batch link/timeline extraction. fs walks markdown files, db walks pages from the engine (mutation-immune snapshot iteration; use for live brains with no local checkout). The full fs/db walks buffer candidates 100 at a time and flush via `addLinksBatch` / `addTimelineEntriesBatch` (additive); `ON CONFLICT DO NOTHING` enforces uniqueness at the DB layer, `created` counter returns real rows inserted. `ExtractOpts.slugs?: string[]` enables incremental extract via `extractForSlugs()` (single combined links+timeline pass); the cycle path threads sync's `pagesAffected` through. Every per-slug extractor — `extractForSlugs` (the cycle's incremental pass) and the two sync hooks `extractLinksForSlugs` / `extractTimelineForSlugs` — resolves each requested slug through `resolveSlugRelPath`: the `buildSlugPathIndex(walkMarkdownFiles(dir))` index first, then — only on an index miss — the legacy `join(dir, slug + '.md')` existence check. The index is the primary because `pathToSlug` lowercases and slugifies, so a reconstructed path only finds files whose names are already slugs, and every other file looked deleted and was skipped in silence; the legacy fallback stays because sync ADMITS files the walker never emits (`_`-prefixed names, dot-dirs waived via `sync.include_hidden`) and those slugs still round-trip to their real path — without it such a page imports with no edges. On a slug collision the index prefers the file whose name IS the slug (else the first walked entry), so resolution never depends on directory-read order. The per-slug extractors reconcile like `put_page`: each page's own markdown-derived links are replaced through `replacePageFileLinks` (`src/core/link-reconciliation.ts`, `replaceDerivedLinks` with `preserveExisting`; other producers survive, a page with no row counts as processed with no links, and a failed replacement is reported on stderr and leaves the page stale), and `retractRemovedTimelineEntries` (`src/core/timeline-extract.ts`) deletes the exact (date, source, summary) rows the page's previous version produced that its current text no longer does. `loadSlugAliasTargets` adds renamed pages' old slugs (`slug_aliases`) to `allSlugs` so links written before a rename resolve to the current slug. Both return `ExtractForSlugsResult { created, processed }`; `processed` is the subset actually read, and the shared `slugsSafeToStamp(links, timeline)` intersection is what every caller may stamp. Stamping the full requested set marks a silently-skipped page fresh and hides it from `extract --stale` permanently. All three call sites (`src/commands/sync.ts`, `src/core/github-source.ts`, `src/core/google/google-source.ts`) stamp the intersection. `walkMarkdownFiles(brainDir)` still runs to build `allSlugs` for link resolution. `--source-id <id>` scopes extraction to one source on federated brains (resolved via `resolveSourceWithTier()` before any SQL; failures hint `gbrain sources list`). `gbrain extract --stale [--source-id <id>] [--catch-up] [--dry-run] [--json]` branch (`extractStaleFromDB`) — incremental DB-source link+timeline sweep over pages whose `pages.links_extracted_at` watermark is stale. Embedded callers (the cycle) pass `quiet: true` so the helper writes nothing to stdout, including its JSON result; standalone CLI output is unchanged. In `jsonMode` every fs path, `extractForSlugs` included, reports a dropped flush as a `{event:'batch_error'}` stderr line rather than going silent. Stale predicate (shared by both engines + the doctor check): `links_extracted_at IS NULL OR links_extracted_at < LINK_EXTRACTOR_VERSION_TS::timestamptz OR updated_at > links_extracted_at` (the `updated_at` arm catches MCP `put_page` / `sync --no-extract` edited-since-extract). Three `BrainEngine` methods (parity in postgres-engine.ts + pglite-engine.ts + bootstrap probes): `countStalePagesForExtraction(opts?)`, `listStalePagesForExtraction({batchSize, afterPageId?, sourceId?, versionTs?})` (returns page CONTENT to avoid N+1 `getPage`; `rowToStalePage` in utils.ts maps the row, `StalePageRow` in types.ts), `markPagesExtractedBatch(refs, defaultExtractedAt)` (3-array unnest `slug[],source_id[],ts[]`; each ref may carry its own `extractedAt`). `STALE_BATCH_SIZE` default 25 (`GBRAIN_EXTRACT_STALE_BATCH`; small because page bodies are unbounded — the LIMIT is the only fetch-time memory bound); `STALE_TIME_BUDGET_MS` 30min wall-clock (`--catch-up` removes the cap). Non-swallowing flush: link/timeline flush throws propagate and abort the batch; stamp LAST so a crash leaves pages unstamped and they re-extract idempotently (`addLinksBatch` ON CONFLICT DO NOTHING + timeline dedup). `extractStaleFromDB` stamps with each row's READ `updated_at` (not `now()`), so a concurrent edit during the sweep keeps the page stale and it re-extracts next run rather than marked fresh-with-old-content. Source-correct stamping at DB-extract sites via `stampExtracted` (best-effort, never throws); `extractLinksFromDB` only stamps the combined watermark when `subcommand === 'all'` (a links-only run must not hide timeline staleness). `LINK_EXTRACTOR_VERSION_TS` lives in `src/core/link-extraction.ts` (bump like `CHUNKER_VERSION` to invalidate all prior stamps). Migration v112 (`pages_links_extracted_at`) adds nullable `TIMESTAMPTZ` + composite `(source_id, links_extracted_at)` index (CONCURRENTLY + invalid-remnant pre-drop on Postgres, plain on PGLite), NO backfill so the real backlog surfaces on first `gbrain doctor`. Schema parity in schema.sql + pglite-schema.ts + schema-embedded.generated.ts + `REQUIRED_BOOTSTRAP_COVERAGE`. `src/commands/doctor.ts:checkLinksExtractionLag` (the `links_extraction_lag` check, also in `doctorReportRemote`) warn-only by default (>`GBRAIN_EXTRACTION_LAG_WARN_PCT`, default 20%; shared `EXTRACTION_LAG_WARN_PCT_DEFAULT` + `EXTRACTION_LAG_MIN_PAGES=100` + exported `_resolveEnvNumber`), hard-fails only when `GBRAIN_EXTRACTION_LAG_FAIL_PCT` is set; vacuous-skips <100 pages (no `--source`); pre-v112 brains graceful-skip via `isUndefinedColumnError`; strictly a SQL COUNT (safe on remote/thin-client). `src/commands/sync.ts` carries `--no-extract` (threaded through single-source + `--all` + `syncOneSource`), stamps `links_extracted_at` at the inline-extract call site for the slugs the extractors actually read, and `maybeExtractionNudge` prints a one-line stderr nudge after a `synced | first_sync | up_to_date` sync that leaves a backlog (`shouldNudgeAfterSync` pure predicate; `GBRAIN_SYNC_NO_EXTRACT_NUDGE` suppresses). `src/core/retry.ts` lists `'extract.stale'` in `BATCH_AUDIT_SITES`; `src/core/doctor-categories.ts` lists `links_extraction_lag` in `BRAIN_CHECK_NAMES`. Pinned by `test/extract-stale.test.ts` (incl. edited-after-stamp + crash-contract), `test/sync-inline-extract-stamps.serial.test.ts`, `test/sync-nudge-status-gate.test.ts`, `test/doctor-links-extraction-lag.test.ts`, engine-parity (Postgres↔PGLite) for the 3 methods + v112 round-trip. The stale SELECT in both engines projects a deterministic full-µs UTC string `to_char(updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS updated_at_iso` (carried on `StalePageRow.updated_at_iso`, populated by `rowToStalePage` in utils.ts with an ISO-only fallback — never `String(Date)`, which `::timestamptz` misparses); `extractStaleFromDB` stamps that exact-precision value, not a JS `Date` (which truncates to milliseconds), so on Postgres `links_extracted_at` equals the row's `updated_at` to the microsecond and `links_extraction_lag` clears — a ms-truncated stamp stays strictly below the µs `updated_at` and leaves every page perpetually stale, which `extract --stale` could never satisfy. `to_char` (not raw `::text`, which is `DateStyle`-fragile) keeps the projection deterministic. The `markPagesExtractedBatch` SQL is unchanged, so callers passing an explicit (e.g. backdated) `extractedAt` still control the stamp and the edited-since arm is exact. A deterministic PGLite case in `test/extract-stale.test.ts` injects a µs `updated_at`, runs `--stale`, and asserts the lag is 0 and stays 0.+- `src/commands/extract.ts` — `gbrain extract links|timeline|all [--source fs|db] [--source-id <id>]`: batch link/timeline extraction. fs walks markdown files, db walks pages from the engine (mutation-immune snapshot iteration; use for live brains with no local checkout). The full fs/db walks buffer candidates 100 at a time and flush via `addLinksBatch` / `addTimelineEntriesBatch` (additive); `ON CONFLICT DO NOTHING` enforces uniqueness at the DB layer, `created` counter returns real rows inserted. `ExtractOpts.slugs?: string[]` enables incremental extract via `extractForSlugs()` (single combined links+timeline pass); the cycle path threads sync's `pagesAffected` through. Every per-slug extractor — `extractForSlugs` (the cycle's incremental pass) and the two sync hooks `extractLinksForSlugs` / `extractTimelineForSlugs` — resolves each requested slug through `resolveSlugRelPath`: the `buildSlugPathIndex(walkMarkdownFiles(dir))` index first, then — only on an index miss — the legacy `join(dir, slug + '.md')` existence check. The index is the primary because `pathToSlug` lowercases and slugifies, so a reconstructed path only finds files whose names are already slugs, and every other file looked deleted and was skipped in silence; the legacy fallback stays because sync ADMITS files the walker never emits (`_`-prefixed names, dot-dirs waived via `sync.include_hidden`) and those slugs still round-trip to their real path — without it such a page imports with no edges. On a slug collision the index prefers the file whose name IS the slug (else the first walked entry), so resolution never depends on directory-read order. The per-slug extractors reconcile like `put_page`: each page's own markdown-derived links are replaced through `replacePageFileLinks` (`src/core/link-reconciliation.ts`, `replaceDerivedLinks` with `preserveExisting`; other producers survive, a page with no row counts as processed with no links, and a failed replacement is reported on stderr and leaves the page stale), and `retractRemovedTimelineEntries` (`src/core/timeline-extract.ts`) deletes the exact (date, source, summary) rows the page's previous version produced that its current text no longer does. `loadSlugAliasTargets` adds renamed pages' old slugs (`slug_aliases`) to `allSlugs` so links written before a rename resolve to the current slug. Both return `ExtractForSlugsResult { created, processed }`; `processed` is the subset actually read, and the shared `slugsSafeToStamp(links, timeline)` intersection is what every caller may stamp. Stamping the full requested set marks a silently-skipped page fresh and hides it from `extract --stale` permanently. All three call sites (`src/commands/sync.ts`, `src/core/github-source.ts`, `src/core/google/google-source.ts`) stamp the intersection. `walkMarkdownFiles(brainDir)` still runs to build `allSlugs` for link resolution. `--source-id <id>` scopes extraction to one source on federated brains (resolved via `resolveSourceWithTier()` before any SQL; failures hint `gbrain sources list`). `gbrain extract --stale [--source-id <id>] [--catch-up] [--dry-run] [--json]` branch (`extractStaleFromDB`) — incremental DB-source link+timeline sweep over pages whose `pages.links_extracted_at` watermark is stale. Embedded callers (the cycle) pass `quiet: true` so the helper writes nothing to stdout, including its JSON result; standalone CLI output is unchanged. In `jsonMode` every fs path, `extractForSlugs` included, reports a dropped flush as a `{event:'batch_error'}` stderr line rather than going silent. Stale predicate (shared by both engines + the doctor check): `links_extracted_at IS NULL OR links_extracted_at < LINK_EXTRACTOR_VERSION_TS::timestamptz OR updated_at > links_extracted_at` (the `updated_at` arm catches MCP `put_page` / `sync --no-extract` edited-since-extract). Three `BrainEngine` methods (parity in postgres-engine.ts + pglite-engine.ts + bootstrap probes): `countStalePagesForExtraction(opts?)`, `listStalePagesForExtraction({batchSize, afterPageId?, sourceId?, versionTs?})` (returns page CONTENT to avoid N+1 `getPage`; `rowToStalePage` in utils.ts maps the row, `StalePageRow` in types.ts), `markPagesExtractedBatch(refs, defaultExtractedAt)` (3-array unnest `slug[],source_id[],ts[]`; each ref may carry its own `extractedAt`). `STALE_BATCH_SIZE` default 25 (`GBRAIN_EXTRACT_STALE_BATCH`; small because page bodies are unbounded — the LIMIT is the only fetch-time memory bound); `STALE_TIME_BUDGET_MS` 30min wall-clock (`--catch-up` removes the cap). Non-swallowing flush: link/timeline flush throws propagate and abort the batch; stamp LAST so a crash leaves pages unstamped and they re-extract idempotently (`addLinksBatch` ON CONFLICT DO NOTHING + timeline dedup). `extractStaleFromDB` stamps with each row's READ `updated_at` (not `now()`), so a concurrent edit during the sweep keeps the page stale and it re-extracts next run rather than marked fresh-with-old-content. On a managed-persistence brain each page publishes its derived links, the coordinator's canonical timeline tuples (`canonicalTimelineRows`, insert-only) and its watermark in one revision-bound `withCoordinatedWrite` transaction; a page edited since the read is skipped and stays stale. Tests: `test/extract-stale-managed.test.ts`. Source-correct stamping at DB-extract sites via `stampExtracted` (best-effort, never throws); `extractLinksFromDB` only stamps the combined watermark when `subcommand === 'all'` (a links-only run must not hide timeline staleness). `LINK_EXTRACTOR_VERSION_TS` lives in `src/core/link-extraction.ts` (bump like `CHUNKER_VERSION` to invalidate all prior stamps). Migration v112 (`pages_links_extracted_at`) adds nullable `TIMESTAMPTZ` + composite `(source_id, links_extracted_at)` index (CONCURRENTLY + invalid-remnant pre-drop on Postgres, plain on PGLite), NO backfill so the real backlog surfaces on first `gbrain doctor`. Schema parity in schema.sql + pglite-schema.ts + schema-embedded.generated.ts + `REQUIRED_BOOTSTRAP_COVERAGE`. `src/commands/doctor.ts:checkLinksExtractionLag` (the `links_extraction_lag` check, also in `doctorReportRemote`) warn-only by default (>`GBRAIN_EXTRACTION_LAG_WARN_PCT`, default 20%; shared `EXTRACTION_LAG_WARN_PCT_DEFAULT` + `EXTRACTION_LAG_MIN_PAGES=100` + exported `_resolveEnvNumber`), hard-fails only when `GBRAIN_EXTRACTION_LAG_FAIL_PCT` is set; vacuous-skips <100 pages (no `--source`); pre-v112 brains graceful-skip via `isUndefinedColumnError`; strictly a SQL COUNT (safe on remote/thin-client). `src/commands/sync.ts` carries `--no-extract` (threaded through single-source + `--all` + `syncOneSource`), stamps `links_extracted_at` at the inline-extract call site for the slugs the extractors actually read, and `maybeExtractionNudge` prints a one-line stderr nudge after a `synced | first_sync | up_to_date` sync that leaves a backlog (`shouldNudgeAfterSync` pure predicate; `GBRAIN_SYNC_NO_EXTRACT_NUDGE` suppresses). `src/core/retry.ts` lists `'extract.stale'` in `BATCH_AUDIT_SITES`; `src/core/doctor-categories.ts` lists `links_extraction_lag` in `BRAIN_CHECK_NAMES`. Pinned by `test/extract-stale.test.ts` (incl. edited-after-stamp + crash-contract), `test/sync-inline-extract-stamps.serial.test.ts`, `test/sync-nudge-status-gate.test.ts`, `test/doctor-links-extraction-lag.test.ts`, engine-parity (Postgres↔PGLite) for the 3 methods + v112 round-trip. The stale SELECT in both engines projects a deterministic full-µs UTC string `to_char(updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS updated_at_iso` (carried on `StalePageRow.updated_at_iso`, populated by `rowToStalePage` in utils.ts with an ISO-only fallback — never `String(Date)`, which `::timestamptz` misparses); `extractStaleFromDB` stamps that exact-precision value, not a JS `Date` (which truncates to milliseconds), so on Postgres `links_extracted_at` equals the row's `updated_at` to the microsecond and `links_extraction_lag` clears — a ms-truncated stamp stays strictly below the µs `updated_at` and leaves every page perpetually stale, which `extract --stale` could never satisfy. `to_char` (not raw `::text`, which is `DateStyle`-fragile) keeps the projection deterministic. The `markPagesExtractedBatch` SQL is unchanged, so callers passing an explicit (e.g. backdated) `extractedAt` still control the stamp and the edited-since arm is exact. A deterministic PGLite case in `test/extract-stale.test.ts` injects a µs `updated_at`, runs `--stale`, and asserts the lag is 0 and stays 0.- Extract CLI help — `EXTRACT_HELP` in `src/commands/extract.ts` is the canonical detailed usage shared by `--help` and invalid-subcommand errors. `src/cli.ts` routes `extract --help` before engine connection so help works on unconfigured installs; the top-level TOOLS block advertises every mode-specific flag. Pinned by `test/cli-help-discoverability.test.ts`.- `src/commands/features.ts` — `gbrain features --json --auto-fix`: usage scan + feature adoption salesman.diff --git a/docs/architecture/key-files/commands-4.md b/docs/architecture/key-files/commands-4.mdindex 137cc0c764..5c0f559f79 100644--- a/docs/architecture/key-files/commands-4.md+++ b/docs/architecture/key-files/commands-4.md@@ -33,7 +33,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/pages.ts` — `gbrain purge-deleted [--older-than HOURS|Nd] [--dry-run] [--json]` operator escape hatch. Mirror of `gbrain sources purge` for the page-level lifecycle. Hard-deletes pages whose `deleted_at` is older than the cutoff; cascades to content_chunks/page_links/chunk_relations.-- `src/commands/persistence-admin.ts` + `src/core/persistence/{admin-contract,administration}.ts` — trusted local `sources writer status|claim|transfer` and `auth local-writer list|register|revoke`. Parse and resolve the brain before opening PGLite; an existing owner receives a separate private administration envelope verified against the current CLI registration. These names never enter the public MCP operation registry; stdio, hook credentials, forged trust fields and revoked CLI registrations cannot administer. Transfer requires exact manifest and owner epoch; status `--probe` acquires/releases a real native lock. Explicit credential replacement commits old revocation and new registration together before atomically publishing the private file, preserving old credentials for recovery without keeping their authority. No credential/hash appears in output. `test/persistence-administration.test.ts` covers database rollback, parallel rotations, transfer conflicts, real sockets and real CLI subprocesses. `retry-effects <source> --request-id <original-uuid> --dry-run --json` previews a failed embedding effect without work; applying the same reviewed request requires original/current authority, selected-brain config, source/page/owner CAS and one additional allowance. It never retries other effects, claims ownership or rewrites canonical receipts.+- `src/commands/persistence-admin.ts` + `src/core/persistence/{admin-contract,administration}.ts` — trusted local `sources writer status|claim|transfer` and `auth local-writer list|register|revoke`. Parse and resolve the brain before opening PGLite; an existing owner receives a separate private administration envelope verified against the current CLI registration. These names never enter the public MCP operation registry; stdio, hook credentials, forged trust fields and revoked CLI registrations cannot administer. Transfer requires exact manifest and owner epoch; status `--probe` acquires/releases a real native lock. Explicit credential replacement commits old revocation and new registration together before atomically publishing the private file, preserving old credentials for recovery without keeping their authority. No credential/hash appears in output. `test/persistence-administration.test.ts` covers database rollback, parallel rotations, transfer conflicts, real sockets and real CLI subprocesses. `retry-effects <source> --request-id <original-uuid> --dry-run --json` previews a failed embedding effect without work; applying the same reviewed request requires original/current authority, selected-brain config, source/page/owner CAS and one additional allowance. For a request with parked Git or withdrawal effects the same command previews the parked targets (`--dry-run`) or authorizes one more attempt per parked target, reporting each effect's state and whether it is terminal. It never claims ownership or rewrites canonical receipts.- `src/commands/persistence-delegate.ts` — shared CLI receipt/error rendering and lazy engine lifecycle for capture/forget/call. Shared op dispatch and CLI_ONLY dispatch both attempt persistence IPC before connecting. `runDeferredPersistenceCommand` drains/disconnects only an engine actually acquired by the fallback. Capture submits raw content and explicit event/provenance/precondition fields to the capture operation; the owner materializes default slug/time once. Forget uses the frozen verb with an opaque fact ID and stable request UUID. `scripts/generate-flag-registry.ts` excludes this pure router from recursive flag harvesting and records forget's deeper reason/request-id flags explicitly. Real subprocess coverage: `test/persistence-cli-delegation.test.ts`.@@ -47,7 +47,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/quarantine.ts` — `gbrain quarantine <list|clear|scan>` operator surface for the content-quality gate. `list [--json] [--include-flagged]` paginates `listPages` and reports quarantined (HIDDEN) pages, optionally also `content_flag` (FLAGGED, searchable) pages. `clear <slug> [--force] [--no-embed] [--json]` drops both markers and re-imports through the normal pipeline so the page re-chunks + re-embeds and becomes searchable; the gate re-runs on import so genuinely-junk pages re-quarantine (exit 1) unless `--force` sets `GBRAIN_NO_SANITY=1` for that one import. `scan [--limit N] [--apply] [--no-embed] [--json]` re-assesses already-ingested pages so junk predating the gate gets marked (unchanged content short-circuits normal sync, so it never re-assesses otherwise); dry-run uses the SAME effective `content_sanity` config thresholds `--apply` will use, idempotent (skips already-marked pages), `--apply` re-imports with `forceRechunk` to set markers + (for quarantine) drop chunks. Dispatched in `cli.ts`. Pinned by `test/quarantine-cli.test.ts`.-- `src/commands/recall.ts` — the `gbrain recall` CLI (facts-first by default; local engine or thin-client). Optional `--budget-policy facts_first|query_first` routes a one-shot read through the shared operation, forwarding fact filters and using remote recall on thin clients. Enum validation uses the shared operation definition; option order does not affect budget parsing. Only query-first with a nonblank query preserves numeric fractions until server packing; omitted/explicit facts-first keeps legacy integer parsing. The new option rejects watch/cursor/rollup/as-context combinations rather than silently ignoring them. Opt-in selector failures use stamped v1 errors; JSON mode emits structured local and remote errors on stdout with a nonzero exit, preserving remote read-error details without requiring a mutation receipt. Omitted-policy validation and fallback remain unchanged. Entity→text fallback: a bare positional without verb options is entity-first, but when the entity arm matches ZERO facts (and no `--grep`/`--supersessions`/`--session-id` narrows the read), the query retries as SQL-level fact-text grep with a stderr note. One predicate and note formatter are shared by the local path and thin-client mirror; explicit grep callers keep exact semantics. `--since` composes with entity and session in one query before LIMIT, on event time unless `--since-last-run`. Pinned by `test/facts-recall-since-composition.test.ts`, `test/recall-budget-policy-transports.test.ts`, `test/recall-budget-policy-thin-cli.test.ts`, and `test/recall-budget-policy-thin.serial.test.ts`.+- `src/commands/recall.ts` — the `gbrain recall` CLI (facts-first by default; local engine or thin-client). Optional `--budget-policy facts_first|query_first` routes a one-shot read through the shared operation, forwarding fact filters and using remote recall on thin clients. Enum validation uses the shared operation definition; option order does not affect budget parsing. Only query-first with a nonblank query preserves numeric fractions until server packing; omitted/explicit facts-first keeps legacy integer parsing. The new option rejects watch/cursor/rollup/as-context combinations rather than silently ignoring them. Opt-in selector failures use stamped v1 errors; JSON mode emits structured local and remote errors on stdout with a nonzero exit, preserving remote read-error details without requiring a mutation receipt. Omitted-policy validation and fallback remain unchanged. Entity→text fallback: a bare positional without verb options is entity-first, but when the entity arm matches ZERO facts (and no `--grep`/`--supersessions`/`--session-id` narrows the read), the query retries as SQL-level fact-text grep with a stderr note. One predicate and note formatter are shared by the local path and thin-client mirror; explicit grep callers keep exact semantics. `--since` composes with entity and session in one query before LIMIT, on event time unless `--since-last-run`. Local `--grep` is passed to every engine arm (ILIKE with escaped metacharacters, before LIMIT); only `--supersessions` keeps the client-side filter. Pinned by `test/recall-grep-local-cli.test.ts`. Pinned by `test/facts-recall-since-composition.test.ts`, `test/recall-budget-policy-transports.test.ts`, `test/recall-budget-policy-thin-cli.test.ts`, and `test/recall-budget-policy-thin.serial.test.ts`.- `src/commands/reindex-aliases.ts` — `gbrain reindex --aliases [--limit N] [--dry-run] [--json] [--source <id>]`: backfills the free-text alias layer for EXISTING pages whose frontmatter `aliases:` predate the alias table (the import-time projection covers new + changed pages). Reads each page's frontmatter `aliases:`, writes via `engine.setPageAliases`. Idempotent + convergent (setPageAliases replaces a page's alias set) so no op-checkpoint needed; walks `listAllPageRefs` (cheap cross-source enumeration), `--source` narrows. Pinned by `test/search/reindex-aliases.test.ts`.diff --git a/docs/architecture/key-files/commands-5.md b/docs/architecture/key-files/commands-5.mdindex 323fde8681..5647e4ad3c 100644--- a/docs/architecture/key-files/commands-5.md+++ b/docs/architecture/key-files/commands-5.md@@ -3,6 +3,7 @@[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.+- `src/commands/repair.ts` — `gbrain repair [<kind>] [--apply] [--source <id>] [--limit <n>] [--no-embed] [--json]` and `gbrain repair --all`. Kinds `timeline` (#5567 materialize), `visibility` (#5525 tighten-only backfill) and `safe-chunks` (#5050/#5247 projection-only re-seal of pages of every kind below the safe-chunk fence; `--no-embed` defers embedding to `embed --stale`); no kind previews every kind. Dry run unless `--apply` (no prompt; `--yes` refused). Output carries the resolved scope, affected count, a capped `source:slug` sample, residual counts, request-ID / receipt-byte / re-embedding cost and capacity, and the apply command; `--json` has the same fields. Host-only: thin clients refuse via `THIN_CLIENT_REFUSED_COMMANDS`. Logic lives in `src/core/repair/`.- `src/commands/reindex.ts` — `gbrain reindex --markdown [--type PAGE_TYPE] [--limit N] [--dry-run] [--json] [--no-embed] [--repo PATH]`. Walks markdown pages with stale `chunker_version` (plus unstamped contextual-retrieval mode when embedding is enabled) in 100-row id-keyset batches; a failed row cannot starve later batches in the same invocation. `--type` adds a bound-parameter `pages.type = $N` scope for focused backfills such as atom pages and is rejected by reindex modes that do not consume it. Current-version chunkless healing deliberately remains owned by the native, bounded `embed --stale` path. Rows with non-null `source_path` re-import via `importFromFile`; rows without fall back to `importFromContent`. Both paths pass `forceRechunk: true` to bypass `importFromContent`'s `content_hash` short-circuit — without it the chunker version bump never reaches pages whose source content hasn't changed, AND the stripFactsFence privacy strip never applies to chunks stored without it. Wired into `src/commands/upgrade.ts:runPostUpgrade` after `apply-migrations`. The DB-only fallback (no source file on disk) does NOT pass body-only `compiled_truth` to `importFromContent` (that path re-parses with EMPTY frontmatter and OVERWRITES the page's real frontmatter/title/timeline); it `getPage`+`getTags`, reconstructs FULL markdown via `serializeMarkdown(frontmatter, compiled_truth, timeline, {type, title, tags})`, and re-imports THAT so re-chunking a DB-only page preserves everything while bumping `chunker_version`. Pinned by `test/reindex-preserve-tags.test.ts` and `test/reindex.test.ts`.- `src/commands/repair-jsonb.ts` — `gbrain repair-jsonb [--dry-run] [--json]`: rewrites `jsonb_typeof='string'` rows in place across 8 affected columns (pages.frontmatter, raw_data.data, ingest_log.pages_updated, files.metadata, page_versions.frontmatter, subagent_messages.content_blocks, subagent_tool_executions.input, subagent_tool_executions.output). The subagent targets are `jsonPayloadOnly`: those columns can legitimately hold jsonb string scalars (persistToolExec binds a tool's pre-serialized string payload as-is), so their damage predicate additionally requires container-shaped content (`^\s*[\[{]`) that `pg_input_is_valid(..., 'jsonb')` (PG16+ floor, same as the IS JSON predicate `updateSourceConfig` relies on) actually parses — a plain-text value that merely starts with `[` or `{` is never flagged or corrupted. Targets whose table doesn't exist on the brain are skipped via `to_regclass` (brains without the subagent tables), and one target's failure is recorded on stderr while the run continues — earlier repairs are already committed and the v0_12_2 migration orchestrator JSON-parses stdout. `runDoctor`'s `jsonb_integrity` check counts damage with the same predicate over the same target list. Repairs double-encoded rows on Postgres; PGLite no-ops. Idempotent. Pinned by `test/repair-jsonb.test.ts` + `test/doctor.test.ts`.diff --git a/docs/architecture/key-files/core-ai.md b/docs/architecture/key-files/core-ai.mdindex e3a7e45974..5ddc094362 100644--- a/docs/architecture/key-files/core-ai.md+++ b/docs/architecture/key-files/core-ai.md@@ -23,7 +23,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/ai/providers/claude-cli-language-model.ts` (+ recipe `src/core/ai/recipes/claude-cli.ts`) — ai-sdk LanguageModel adapter that shells out to the locally-installed `claude` CLI in print mode (OAuth-subscription lane, no API key; `claude-cli:<model>` is config-portable with `anthropic:<model>`). Tool use is system-prompt-instructed JSON emission: the recipe teaches the model the `<use_tools>[{name,input}]</use_tools>` format and the adapter parses those blocks back into ai-sdk `tool-call` parts. An entry that carries its arguments flat beside `name` (no `input` wrapper, the Anthropic tool_use shape with the wrapper dropped) is accepted: every key other than `name`/`input` and the Anthropic tool_use leftovers (`type: "tool_use"`, a `toolu_*` `id`) becomes the input — any other `type`/`id` value is a real argument (e.g. `list_pages`' `type` filter) and stays — and a present `input` wins verbatim over stray sibling keys. Tool-call ids are ALWAYS gbrain-minted (`toolu_claude_cli_<uuidv7>`) — never model-authored: each doGenerate is a fresh subprocess replayed from an id-stripped transcript, so the model structurally cannot keep ids unique across turns (a model-authored id echoes the prompt's example entropy-free and collides); the prompt does not ask for an id, and a stray `id` field is deliberately ignored (nothing round-trips it — the loop pairs results in-memory within one turn). doStream not implemented; callers (gateway.toolLoop) use doGenerate. The recipe declares `chat` + `expansion` touchpoints (no embedding; the expansion list leads with the cheap haiku id and carries the same 30s `default_timeout_ms` as chat for the subprocess cold start); `gateway.expand()` routes `claude-cli` through the schemaless `viaText` path because the adapter ignores `responseFormat` (generateObject would throw NoObjectGeneratedError on the fenced-JSON text). Pinned by `test/claude-cli-recipe.test.ts` + `test/ai/claude-cli-expansion.test.ts`.-- `src/core/ai/providers/claude-cli-scratch.ts` — the claude-cli provider's per-PID scratch dirs (`claudeCliCwdDir`/`claudeCliConfigDir` off the `CLAUDE_CLI_CWD_PREFIX`/`CLAUDE_CLI_CONFIG_PREFIX` basename constants, plus `sweepDeadClaudeCliScratchDirs`), split into a dependency-light module so transcript discovery (`src/core/transcripts/discover.ts`) can call `isClaudeCliSelfTranscriptPath(path)` WITHOUT importing the provider's @ai-sdk surface. Each `claude --print` subprocess runs with cwd = a per-PID scratch dir (context isolation — no local CLAUDE.md auto-discovery), and Claude Code records a session transcript for that cwd under `~/.claude/projects/<slugified-cwd>/`; those sessions are gbrain's OWN internal LLM calls, and importing them back is a self-ingestion feedback loop (prompt scaffolding + page content re-entering as "conversations"). The prefix is lowercase `[a-z-]` only, so it survives Claude Code's cwd slugification verbatim and a substring match on the discovered path is a reliable self-exclusion fingerprint. Pinned by `test/transcripts-self-exclusion.test.ts`.+- `src/core/ai/providers/claude-cli-scratch.ts` — the claude-cli provider's per-PID scratch dirs (`claudeCliCwdDir`/`claudeCliConfigDir` off the `CLAUDE_CLI_CWD_PREFIX`/`CLAUDE_CLI_CONFIG_PREFIX` basename constants, plus `sweepDeadClaudeCliScratchDirs`), split into a dependency-light module so transcript discovery (`src/core/transcripts/discover.ts`) can call `isClaudeCliSelfTranscriptPath(path)` WITHOUT importing the provider's @ai-sdk surface. Each `claude --print` subprocess runs with cwd = a per-PID scratch dir (context isolation — no local CLAUDE.md auto-discovery), and Claude Code records a session transcript for that cwd under `~/.claude/projects/<slugified-cwd>/`; those sessions are gbrain's OWN internal LLM calls, and importing them back is a self-ingestion feedback loop (prompt scaffolding + page content re-entering as "conversations"). The prefix is lowercase `[a-z-]` only, so it survives Claude Code's cwd slugification verbatim and a substring match on the discovered path is a reliable self-exclusion fingerprint. `claudeCliSelfSessionIds(projectsRoot = claudeProjectsDir())` lists the session ids of those harness transcripts; the session-end hook named each corpus file `<session id>.txt`, so dream discovery and the sweep's corpus pass use the set to skip self-captures written before the hook refused them (best-effort: a pruned harness transcript leaves its capture unclassifiable). Pinned by `test/transcripts-self-exclusion.test.ts`.- `src/core/ai/recipes/anthropic.ts` — Anthropic recipe (chat + expansion touchpoints). Canonical id is `claude-sonnet-4-6` (no date suffix); a reverse alias `claude-sonnet-4-6-20250929 → claude-sonnet-4-6` keeps stale user configs working (rescues `facts.extraction_model` and `models.dream.synthesize`). Recipe shape pinned by `test/anthropic-model-ids.test.ts`.diff --git a/docs/architecture/key-files/core-cycle.md b/docs/architecture/key-files/core-cycle.mdindex 3c079e7487..8eaf14a8e2 100644--- a/docs/architecture/key-files/core-cycle.md+++ b/docs/architecture/key-files/core-cycle.md@@ -27,7 +27,9 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/cycle/nightly-quality-probe.ts` + `src/core/audit-quality-probe.ts` + `test/fixtures/longmemeval-nightly.jsonl` + `test/nightly-quality-probe.test.ts` — opt-in nightly cross-modal quality probe. The phase runs `gbrain eval longmemeval --by-type` against the committed 10-question placeholder fixture, pipes output through `gbrain eval cross-modal --batch --max-usd 5 --yes`, and writes one event per run to `~/.gbrain/audit/quality-probe-YYYY-Www.jsonl` (ISO-week-rotated, mirrors `audit-slug-fallback.ts`; honors `GBRAIN_AUDIT_DIR`). Default DISABLED — opt-in via `gbrain config set autopilot.nightly_quality_probe.enabled true` (prevents surprise API spend). 24h rate limit (pure `shouldRunNightly(now, recentEvents, windowMs?)`) skips with audit row `outcome: rate_limited`. Embedding-key short-circuit: longmemeval needs `gateway.embedQuery()`, so the phase exits early with `outcome: no_embedding_key` + stderr warn when no provider configured. Full DI surface via `NightlyProbeDeps` (`isEnabled`, `hasEmbeddingProvider`, `resolveMaxUsd`, `resolveRepoRoot`, `runLongMemEval`, `runCrossModalBatch`, `now`) so the unit test stubs every external effect. Cost ceiling: $5/run × 30 nights ≈ $150/month worst-case; expected ~$10.50/month. The `nightly_quality_probe_health` doctor check (`src/commands/doctor.ts`, right after `slug_fallback_audit`) reads last 7 days: SKIPPED when flag off (with enable command); OK when enabled + all PASS; WARN on any FAIL / ERROR / BUDGET_EXCEEDED with per-outcome counts. Pinned by `test/nightly-quality-probe.test.ts`.-- `src/core/cycle/patterns.ts` — Patterns phase: cross-session theme detection over reflections within `dream.patterns.lookback_days` (default 30). Names a pattern only when ≥`dream.patterns.min_evidence` (default 3) reflections support it. Reflection excerpts use the shared UTF-16-safe truncator; a raw `.slice(0, 600)` can split an emoji pair and make Postgres reject the subagent job's JSONB payload. Single Sonnet subagent; same allow-list path as synthesize (imports `loadAllowedSlugPrefixes` + `loadOutputRoot` from synthesize.ts — the reflections lookup, prompt slug templates, and allow-list all honor `dream.synthesize.output_root`, default 'wiki'). Subagent job/wait timeouts are config keys `dream.patterns.subagent_timeout_ms` / `dream.patterns.subagent_wait_timeout_ms` (defaults 30/35 min, mirroring the `dream.synthesize.*` pair). The phase status reflects the child outcome: non-`completed` outcome with zero writes → `fail` (error code `PATTERNS_CHILD_<OUTCOME>`); non-`completed` with partial writes → `warn`. Runs AFTER `extract` so the graph is fresh. The fan-out sets `require_writes: true` so an all-writes-failed child dead-letters instead of reporting completed. Budget clamping: clamped to the remaining parent-job budget via `clampSubagentBudgets` when the cycle threads `deadlineAtMs` — the clamp template synthesize.ts reuses; `MIN_PATTERNS_SUBAGENT_BUDGET_MS` gates an honest skip, and `CYCLE_DEADLINE_RESERVE_MS` is re-exported here from its base-phase.ts home. Evidence watermark: a `completed` child stamps the newest consumed reflection `updated_at` into the state row `dream.patterns.last_evidence_ts` (never `now()`; fail/warn/timeout paths don't stamp, so a dead child retries next tick), and a later run skips `no_new_evidence` while no reflection in the window is newer — autopilot's hourly global tick becomes a free skip until a reflection actually changes; an absent/unparseable stamp fails open; `--once` bypasses the gate but a completed forced run still stamps. Managed local evidence is source-incarnation-scoped and live/non-private; unchanged evidence coalesces the admitted child request instead of inventing a remote maintenance grant.+- `src/core/cycle/dream-breaker.ts` — dream paid-loop circuit breaker. `countDeadDreamSubmissions` is the one counting rule shared by synthesize, patterns, `gbrain dream reset-key` and the `dream_paid_loop` doctor check: dead `subagent` rows finished in the last 24 h (partial index `idx_minion_jobs_dead_subagent_finished`, migration 173), keyed by the live or released idempotency key with the `:c<i>of<n>` chunk suffix stripped, counted as distinct queues (one per run), ignoring deaths before the key's persisted reset (`dream.breaker.resets` config JSON, database clock). A key at `dream.breaker.max_dead_submissions` (default 3; 0 disables) is refused before synthesis submission; a failed count leaves the breaker off for that run with a warning. Completed jobs, including legitimate zero-write completions, never count. Growing transcripts change their content-hashed key and unkeyed patterns runs are not covered. Tests: `test/dream-breaker.test.ts`, `test/cycle-synthesize-breaker.test.ts`, `test/e2e/dream-breaker-postgres.test.ts`.++- `src/core/cycle/patterns.ts` — Patterns phase: cross-session theme detection over reflections within `dream.patterns.lookback_days` (default 30). Names a pattern only when ≥`dream.patterns.min_evidence` (default 3) reflections support it. Reflection excerpts use the shared UTF-16-safe truncator; a raw `.slice(0, 600)` can split an emoji pair and make Postgres reject the subagent job's JSONB payload. Single Sonnet subagent; same allow-list path as synthesize (imports `loadAllowedSlugPrefixes` + `loadOutputRoot` from synthesize.ts — the reflections lookup, prompt slug templates, and allow-list all honor `dream.synthesize.output_root`, default 'wiki'). Subagent job/wait timeouts are config keys `dream.patterns.subagent_timeout_ms` / `dream.patterns.subagent_wait_timeout_ms` (defaults 30/35 min, mirroring the `dream.synthesize.*` pair). The phase status reflects the child outcome: non-`completed` outcome with zero writes → `fail` (error code `PATTERNS_CHILD_<OUTCOME>`); non-`completed` with partial writes → `warn`. Runs AFTER `extract` so the graph is fresh. The fan-out sets `require_writes: true` so an all-writes-failed child dead-letters instead of reporting completed. Budget clamping: clamped to the remaining parent-job budget via `clampSubagentBudgets` when the cycle threads `deadlineAtMs` — the clamp template synthesize.ts reuses; `MIN_PATTERNS_SUBAGENT_BUDGET_MS` gates an honest skip, and `CYCLE_DEADLINE_RESERVE_MS` is re-exported here from its base-phase.ts home. Evidence watermark: a `completed` child stamps the newest consumed reflection `updated_at` into the state row `dream.patterns.last_evidence_ts` (never `now()`; fail/warn/timeout paths don't stamp, so a dead child retries next tick), and a later run skips `no_new_evidence` while no reflection in the window is newer — autopilot's hourly global tick becomes a free skip until a reflection actually changes; an absent/unparseable stamp fails open; `--once` bypasses the gate but a completed forced run still stamps. Managed local evidence is source-incarnation-scoped and live/non-private; unchanged evidence coalesces the admitted child request instead of inventing a remote maintenance grant. Maintenance runs (the only keyed patterns runs) consult the paid-loop breaker before submission and skip with `dream_breaker_tripped`.- `src/core/cycle/phantom-redirect.ts` — Phantom-redirect orchestrator. Exports `runPhantomRedirectPass(engine, brainDir, sourceId, dryRun): Promise<PhantomPassResult>` (per-cycle wrapper acquiring the `gbrain-sync` writer lock once for the whole pass, 30s bounded retry, walks up to `GBRAIN_PHANTOM_REDIRECT_LIMIT` unprefixed phantoms) + `tryRedirectPhantom(engine, page, sourceId, brainDir, dryRun): Promise<RedirectResult>` + `stripFenceAndFrontmatterAndLeadingH1` (pure body-shape gate helper — strips facts fence incl. preceding `## Facts` heading and the leading H1). Only fence rows migrate, so the residue gate also counts the page's timeline text, any `timeline_entries` row, and frontmatter keys beyond `title`/`type`/`tags`; any residue = not a phantom. Handler order: body-shape gate → `resolvePhantomCanonical` (bypasses exact-self-match) → `findPrefixCandidates` ambiguity check → `fenceDbDrift` bi-directional check → dry-run early exit → materialize canonical via `serializeMarkdown` if DB-only → append phantom fence rows to canonical's disk fence with `(claim, valid_from)` dedup-guard + row_num continuation → `engine.refreshPageBody` with SHA-256 content_hash recomputed via the import-file shape → `engine.migrateFactsToCanonical` (lossless) → move the phantom's fact withdrawals to the canonical subject → `engine.rewriteLinks` (DB FK rewrite; wiki-link text rewrite is a documented follow-up) → `engine.softDeletePage` + `engine.deleteFactsForPage(phantom)` + `fs.unlinkSync(phantomPath)`. `RedirectResult.canonical` populated on `'redirected'` (incl. dry-run preview) so the caller builds `touched_canonicals`. Idempotent on re-run: phantom soft-deleted → predicate fails (`deleted_at IS NULL`); migrate UPDATE matches no rows; dedup-guard prevents double-append.@@ -39,10 +41,10 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/cycle/synthesize-verify.ts` — Mechanical claim verification on every page a synthesis child wrote (zero LLM). Exports the shared grounding primitive `normalizeForGrounding` (whitespace/curly-quote/dash/ellipsis/case folding WITH an offset map back to the original string, so every replacement is a verbatim transcript slice) + `normForGrounding` (plain form, also used by `buildTriageMapBlock` and triage-rescue). `groundSource(path, content)` prepares a transcript: offset map, speaker turns (`parseSpeakerTurns`: bold `**Name** (ts):` anchors always, plain `Label:` anchors when the label is a role word or opens two or more lines), canonical numbers and dates (`numericFacts`: `$250K` = `$250,000` = `250 thousand`, `2026-03-14` = `March 14th`; the file basename counts), and speaker-mention patterns. `groundQuote` runs the ladder exact → normalized → near (word-trigram anchors, window clipped to the anchor's speaker turn, ≥0.8 token overlap, ambiguity within 0.05 falls through, trimmed to the first/last shared token, refused above 1.3x the quote length) and never accepts a match that touches a speaker label (`reason: 'crosses_speakers'`). `verifyBody` splits a body into claim units (`claimUnits`: sentences within a line, whole list items, whole table rows; no boundary inside a quote) and checks each NEW unit: every quote must ground in some source, a quote whose sentence names a transcript speaker must name the speaker of the matched turn, and every numeric/date claim (outside grounded quotes, code, wikilinks and link targets) must appear in a source. Any failure removes the whole unit from the body; `verifyDreamPage` records it in frontmatter `unverified_claims` (`text`, `reason` = `quote_not_in_source` / `quote_crosses_speakers` / `speaker_mismatch` / `number_not_in_source`, `detail`, `sources`, `detected_at`) and records every grounded quote's source path, character span and speaker in `grounding.quotes`; records from the pre-run revision carry forward, capped at 100 / 200. Frontmatter is neither chunked nor searched, so quarantined claims stay reviewable through `get_page` but out of search, recall, think and context packs. A page whose every unit failed keeps `ALL_CLAIMS_QUARANTINED_BODY`. Scope (`verifyAndRepairDreamPages(engine, refs, transcriptsByPath, { since, sinceByTranscript, checkedAt })`): sources are the transcripts of every child that wrote the page; the page epoch is the earliest `loadChildWriteEpochs` entry of its sources (child job `created_at`, so resumed or coalesced children keep their original epoch), else `since` (`readVerifyEpoch`, taken before fan-out). Pages created at or after the epoch are verified whole; older pages are verified only on units absent from their pre-epoch revision (`loadPreRunRevision`: the first `page_versions` snapshot at or after the epoch; none means the page was not overwritten → `skipped_unchanged`). Write-back goes through `importFromContent` (`noEmbed`; the phase-end embed sweep backfills) with a `beforeCommit` that re-projects timeline entries, facts, takes (`prepareCanonicalProjections`) and automatic links (`prepareAutomaticLinks`) from the verified body in the same transaction, so no derived row outlives its quarantined claim. Fail-open per page (read-back miss / write throw → `errors` + continue; abort still unwinds). Kill switch `dream.synthesize.quote_verify` (default on). Telemetry shape = `QuoteVerifyStats` in `details.synthesis.quote_verify`. Pinned by `test/cycle-synthesize-verify.test.ts`, the write-path mini-eval `test/cycle-write-path-mini-eval.test.ts`, and the three-cycle repeated-consolidation pin `test/cycle-repeated-consolidation.test.ts` (harness `test/helpers/repeated-consolidation.ts`, printable run `scripts/repeated-consolidation-experiment.ts`).-- `src/core/cycle/synthesize.ts` — Synthesize phase: conversation-transcript-to-brain pipeline, a two-stage cascade where cheap scored triage gates frontier synthesis. Reads `dream.synthesize.session_corpus_dir`, runs `runTriagePass` (exported; bounded pool `dream.triage.concurrency` default 4, wall-clock cache-MISS budget `dream.triage.max_ms` default 5 min — cache hits are free and deferred files report `deferred: true`, never cached, so the next pass continues) whose judge `judgeSignificance` emits `{score 0-1 ordinal salience, content_type, segments ≤8 verbatim quotes, entities ≤12, reasons}` (non-overlapping bands LOW 0-0.29 / MEDIUM 0.30-0.69 / HIGH 0.70-1.0; head 50%/middle 20%/tail 30% sample within `dream.triage.max_chars` default 24K via `safeSplitIndex`; out-of-[0,1] scores are `unparseable`, never clamped) cached in `dream_verdicts` with the judging `model` + `TRIAGE_VERSION` — cache validity requires BOTH to match (switching `models.dream.triage` re-judges; `max_chars`/`max_tokens` deliberately excluded from validity — `dream retriage --force` re-judges under new sampling knobs). Degenerate verdicts (`truncated`/`refusal`/`unparseable`) are never cached. THE gate is `passesTriageGate` (triage-rescue.ts): `score >= dream.triage.threshold` (default 0.5) OR the verified-segment rescue, applied at report construction inside `runTriagePass` at READ time — retuning the threshold or rescue knobs re-gates with zero re-judging; the stored `worth_processing` boolean derives from the fixed `DEFAULT_TRIAGE_THRESHOLD` constant (back-compat only, never the live dial). Passing files fan out one subagent per chunk with `max_turns` from `dream.synthesize.max_turns` (default 16) and a bounded advisory `buildTriageMapBlock` (exported; score/type/entities + chunk-filtered segments, '' for legacy/degraded verdicts so the prompt is unchanged for those) spliced into `buildSynthesisPrompt`, with `allowed_slug_prefixes` (sourced from `skills/_brain-filing-rules.json` `dream_synthesize_paths.globs`; when `dream.synthesize.output_root` is set, `loadAllowedSlugPrefixes(outputRoot)` remaps the `wiki/`-rooted globs to the configured namespace, and the same root drives the prompt slug templates; default 'wiki', validated against the slug grammar via the exported `loadOutputRoot`). The phase is source-scoped: cycle.ts threads `cycleSourceId` as `opts.sourceId` → each child's `SubagentHandlerData.source_id` → the subagent tool registry's `OperationContext.sourceId`, so put_page writes, collected refs, the summary page, and reverse-writes all target the cycle's resolved source ('default' when unscoped; reverse-writes for the cycle's own source land at `brainDir/<slug>.md`, foreign sources under `brainDir/.sources/<id>/`). Orchestrator collects slugs from `subagent_tool_executions` (NOT `pages.updated_at`) and reverse-renders DB → markdown via `serializeMarkdown`. Cooldown via `dream.synthesize.last_completion_ts`, written only when children completed and neither synthesis-budget nor triage-budget deferrals remain. Idempotency keys `dream:synth-v2:<enc source>:filename:<enc basename>:<hash16>[:c<i>of<n>]` (byte-stable, pinned by `test/dream-synthesize-chunking.serial.test.ts`; grammar parsed by exported `parseSynthV2Key`). Fan-out self-heals idempotency-coalesced rows stranded `waiting` in a FOREIGN dead `dream-inline-*` queue (cancel releases the key slot → re-add into the live run's queue) instead of burning the 35-min wait on a row no worker will ever claim. Opt-in per-source daily submission cap `dream.synthesize.max_submissions_per_source_per_day` (default 0 = off; skips whole files — never partial chunk sets; bypassed for explicit `--input/--date/--from/--to` targets; count-query failure fails OPEN with a stderr warn). `--dry-run` runs triage, skips synthesis; deferral-aware headlines append "(N not yet triaged — time budget...)" so a time-boxed cold pass never reads as mass rejection. `details.triage` (threshold/judged/cache_hits/unreliable/degraded/deferred/below_threshold + rescue_band/rescue_checked/rescue_fired + tokens_in/tokens_out/cost_usd) + `details.synthesis` (jobs/avg_turns/max_turns_config + quote_verify/spend/children_zero_pages) carry the phase telemetry. Subagent never gets fs-write access. `renderPageToMarkdown` (exported) stamps `dream_generated: true` + `dream_cycle_date` into every reverse-write's frontmatter; `writeSummaryPage` does the same on the summary index — this marker is the explicit identity surface `isDreamOutput` checks in `transcript-discovery.ts`. `stampDreamProvenance` additionally persists the same marker into the `pages.frontmatter` JSONB row (merge via `executeRawJsonb`, raw object bound to `$N::jsonb`) for every child-written page BEFORE reverse-rendering, so generated pages are DB-queryable and a later put_page write-through (which re-renders from the DB row) can't erase the stamp. `judgeSignificance`, `JudgeClient`, `runTriagePass`, `buildTriageMapBlock`, `parseSynthV2Key`, `loadSynthConfig`, `TRIAGE_VERSION`, and `DEFAULT_TRIAGE_THRESHOLD` are exported; the triage model resolves via an explicit pre-read of `models.dream.triage` (preferred; through exported `resolveAlias`) falling back to the standard `resolveModel` chain (`models.dream.synthesize_verdict` → deprecated `dream.synthesize.verdict_model` → tier `utility`). `splitTranscriptByBudget(content, contentHash, maxChars)` splits oversized transcripts at paragraph boundaries (`## Topic:` → `---` → `\n` ladder) using a deterministic offset seeded from the first 32 bits of `contentHash` so retries chunk identically; per-chunk char budget = `MODEL_CONTEXT_TOKENS[resolvedModel] × 0.9 × 3.5 chars/token` (non-Anthropic ids fall back to a 180K-token safe default + once-per-process stderr warn); operator overrides `dream.synthesize.max_prompt_tokens` (floor 100K, wins) and `dream.synthesize.max_chunks_per_transcript` (default 24); per-chunk subagent job/wait timeouts are `dream.synthesize.subagent_timeout_ms` / `dream.synthesize.subagent_wait_timeout_ms` (defaults 30/35 min). Legacy `dream:synth:` keys are never produced — `loadSuccessfulSynthesisKeys(engine, sourceId, keyPrefix)` reads the completed rows of BOTH key families once per phase, unioned with `dream_synthesis_completions` (where `MinionQueue.prune` archives completed `dream:synth%` keys before deleting their rows, so `jobs prune` never makes a synthesized transcript eligible again), so existing brains skip with `already_synthesized_legacy_single_chunk`/`_chunked` instead of re-spending the synthesis model, and a transcript whose synth-v2 children already completed skips with `already_synthesized_v2_single_chunk`/`_chunked` (`findSynthV2Completion`; a cancelled row never counts) BEFORE its link manifest is built — otherwise queue.add's idempotency fast path coalesces onto the completed children and they re-enter writtenRefs, so their old pages get quote-repaired, restamped, reverse-written and re-embedded every night. `collectChildPutPageSlugs` raw-fetches every (job_id, slug) pair (not `SELECT DISTINCT`) and rewrites bare-hash6 slugs to `<hash6>-c<idx>` for chunked children (orchestrator-side, zero Sonnet trust). Cap-hit skips write nothing new to `dream_verdicts` (the pass's cached triage verdict remains — a free cache hit on retry) and record no synthesis job, so raising the cap on next run re-attempts cleanly. Bounds INITIAL prompt size only; tool-loop turn-N accumulation is caught by terminal-error classification in `subagent.ts`. Verdict routing is gateway-routed: `makeJudgeClient(verdictModel)` (exported) mirrors `tryBuildGatewayClient` in `src/core/think/index.ts` — a construction-time provider/key probe returns `null` on a clear miss (unknown provider id via `resolveRecipe` AIConfigError, or Anthropic provider with no key via `hasAnthropicKey()`). The verdict loop wraps `judgeSignificance` in try/catch for `AIConfigError` so mid-run provider failures surface as per-transcript `worth=false, reasons=['gateway error: ...']` instead of crashing the phase. Canonical config key `models.dream.synthesize_verdict` (per `PER_TASK_KEYS` in `src/core/model-config.ts`); `JudgeClient` signature preserved verbatim for test-seam stability; CI guard `scripts/check-gateway-routed-no-direct-anthropic.sh` prevents reintroducing `new Anthropic()` here or in `think/index.ts`. At the queue.add boundary a conditional `anthropic:` prefix is applied ONLY when the resolved model has no colon AND starts with `claude-` (because `resolveModel` returns bare ids from `TIER_DEFAULTS`/`DEFAULT_ALIASES` and the subagent validator requires `provider:model` form) — avoids changing the shared constants which would ripple across every `resolveModel` caller. Pinned by `test/cycle/synthesize-gateway-adapter.test.ts`, `test/e2e/dream-synthesize-pglite.test.ts` (gateway-adapter mid-run AIConfigError catch), `test/cycle/regression-pr-wave-r1-r2-r4.test.ts`. Drain-loop lock renewal runs through exported `runDrainRenewalTick` (per-call AbortSignal + timeout + re-entrancy guard) — a hung renewLock cannot stack one checked-out slot per interval firing. Pinned by `test/cycle-drain-renewal.test.ts`. Execution mode: `dream.synthesize.mode` (default `oneshot`) threads to every child as `data.mode` alongside `oneshot_slug_suffix` (the structural suffix contract) and `require_writes: true`; `details.synthesis` adds mode/oneshot_jobs/fallback_jobs/agentic_jobs/fallback_reasons plus the drain telemetry (inline_concurrency_config/effective, drain_ms, queue-wait + runtime p50/p95, dead_jobs, degraded). Pre-retrieval LINK CANDIDATES manifest (link-manifest.ts, `dream.synthesize.link_manifest` default on) is built once per transcript from the cached triage entities/segment notes and spliced into `buildSynthesisPrompt` together with an ALLOWED WRITE PATHS block rendered from the trusted allow-list (the oneshot path never sees a tool schema, so the fence lives in the prompt; rule 2 points at the candidates first). Phase outcome gate: ALL children dead/cancelled → phase fails with SYNTH_ALL_CHILDREN_DEAD (fan-out details preserved on the failure); ANY non-completed child → the cooldown stamp is skipped so released idempotency keys retry next run; 'timeout' (parent stopped waiting) degrades but never triggers the all-dead error. Phase-end deferred-embed closure: whenever the phase wrote pages (regardless of mode — an agentic revert still sweeps debt left by earlier oneshot runs), a 120s-bounded `embedStalePages` (embed-stale.ts) embeds the NULL-embedding chunks of exactly the pages this phase wrote — never a source-wide sweep; the pre-existing stale backlog stays with the budget-tracked embed-backfill machinery — closing the gap on invocation shapes that never reach the global embed phase (`--phase synthesize`, autopilot per-source NON_GLOBAL_PHASES). Best-effort (never fails a phase that wrote its pages) and stamps the current embedding signature on fully-re-embedded pages so they stay inside the model-drift invalidation contract. The inline drain lives in `src/core/cycle/inline-drain.ts` (re-exported here for patterns.ts + `__testing`). Budget clamping: clamped to the remaining parent-job budget when `opts.deadlineAtMs` is threaded (via patterns.ts's `clampSubagentBudgets` template): the clamp re-runs against the live clock PER SUBMIT (the phase is a fan-out with claim-time-anchored child kill switches, so one phase-start clamp only bounds the first child); under the minimum child budget the phase skips honestly (`insufficient_cycle_budget`) or defers the remaining transcripts (`details.budget_deferred_transcripts`), the inline drain stops CLAIMING when the budget can't fit another child and unclaimed children are cancelled + deferred (they'd otherwise strand forever in the run's private queue), each completion wait is additionally bounded by the remaining parent budget (floored at 1s so already-terminal children still resolve), and a deferring run neither writes the 12h cooldown timestamp nor counts deferred transcripts as processed — deferral genuinely retries next cycle. THE gate is `passesTriageGate` (triage-rescue.ts) applied at report construction inside `runTriagePass`: threshold pass OR the verified-segment rescue for band scores `[dream.triage.rescue_floor (0.30), threshold)` with content_type in `dream.triage.rescue_content_types` and ≥ `dream.triage.rescue_min_segments` (default 2; 0 = off) of the judge's segments verifying as normalized transcript substrings (≥40 chars, deduped) — reports carry `rescued`/`verified_segments`, `details.triage` adds rescue_band/rescue_checked/rescue_fired + judge tokens_in/tokens_out/cost_usd (null when unpriced), and dream-retriage's reconcile/audit read the SAME predicate. TRIAGE_VERSION is 2 (peak-not-average rubric; segment selection prefers concrete facts/decisions). After slug collection and BEFORE the provenance stamp/reverse-write/embed sweep, the claim verification pass (synthesize-verify.ts, `dream.synthesize.quote_verify` default on) runs on every page the children wrote, scoped by `readVerifyEpoch` (taken before fan-out) and `loadChildWriteEpochs`; the phase is wrapped in `withChatPhase('phase:synthesize')` (children keep their own job tag — minion_jobs stays the child-spend authority) and `details.synthesis` adds `quote_verify`, `children_zero_pages` (completed children with zero put_page writes — the rule-D disposition), and `spend` (`cost_basis: 'in+out+cache_read'`; children summed from minion_jobs tokens_input/output/cache_read priced at the configured synth model, triage from the pass usage; total_usd null unless both price) `buildSynthesisPrompt` is mode-aware (`mode: 'agentic' | 'oneshot'`, passed from `config.mode` at the sole submit site): agentic children keep the search-tool and final-summary guidance; tool-less oneshot children receive neither, so the prompt never contradicts `ONESHOT_SYSTEM`'s JSON-only rule (the oneshot prompt is stored as `data.prompt` and reused verbatim by the in-job agentic fallback, whose tools stay in the schema). Pinned by `test/cycle-dream-output-root.test.ts`. Managed enabled local synthesis uses durable page admission with original authority and canonical-mirror validation; completed source-incarnation-qualified children survive restart. Quote-repair failure cannot silently certify grounded publication. Remote maintenance remains unsupported.+- `src/core/cycle/synthesize.ts` — Synthesize phase: conversation-transcript-to-brain pipeline, a two-stage cascade where cheap scored triage gates frontier synthesis. Reads `dream.synthesize.session_corpus_dir`, runs `runTriagePass` (exported; bounded pool `dream.triage.concurrency` default 4, wall-clock cache-MISS budget `dream.triage.max_ms` default 5 min — cache hits are free and deferred files report `deferred: true`, never cached, so the next pass continues) whose judge `judgeSignificance` emits `{score 0-1 ordinal salience, content_type, segments ≤8 verbatim quotes, entities ≤12, reasons}` (non-overlapping bands LOW 0-0.29 / MEDIUM 0.30-0.69 / HIGH 0.70-1.0; head 50%/middle 20%/tail 30% sample within `dream.triage.max_chars` default 24K via `safeSplitIndex`; out-of-[0,1] scores are `unparseable`, never clamped) cached in `dream_verdicts` with the judging `model` + `TRIAGE_VERSION` — cache validity requires BOTH to match (switching `models.dream.triage` re-judges; `max_chars`/`max_tokens` deliberately excluded from validity — `dream retriage --force` re-judges under new sampling knobs). Degenerate verdicts (`truncated`/`refusal`/`unparseable`) are never cached. THE gate is `passesTriageGate` (triage-rescue.ts): `score >= dream.triage.threshold` (default 0.5) OR the verified-segment rescue, applied at report construction inside `runTriagePass` at READ time — retuning the threshold or rescue knobs re-gates with zero re-judging; the stored `worth_processing` boolean derives from the fixed `DEFAULT_TRIAGE_THRESHOLD` constant (back-compat only, never the live dial). Passing files fan out one subagent per chunk with `max_turns` from `dream.synthesize.max_turns` (default 16) and a bounded advisory `buildTriageMapBlock` (exported; score/type/entities + chunk-filtered segments, '' for legacy/degraded verdicts so the prompt is unchanged for those) spliced into `buildSynthesisPrompt`, with `allowed_slug_prefixes` (sourced from `skills/_brain-filing-rules.json` `dream_synthesize_paths.globs`; when `dream.synthesize.output_root` is set, `loadAllowedSlugPrefixes(outputRoot)` remaps the `wiki/`-rooted globs to the configured namespace, and the same root drives the prompt slug templates; default 'wiki', validated against the slug grammar via the exported `loadOutputRoot`). The phase is source-scoped: cycle.ts threads `cycleSourceId` as `opts.sourceId` → each child's `SubagentHandlerData.source_id` → the subagent tool registry's `OperationContext.sourceId`, so put_page writes, collected refs, the summary page, and reverse-writes all target the cycle's resolved source ('default' when unscoped; reverse-writes for the cycle's own source land at `brainDir/<slug>.md`, foreign sources under `brainDir/.sources/<id>/`). Orchestrator collects slugs from `subagent_tool_executions` (NOT `pages.updated_at`) and reverse-renders DB → markdown via `serializeMarkdown`. Cooldown via `dream.synthesize.last_completion_ts`, written only when children completed and neither synthesis-budget nor triage-budget deferrals remain. Idempotency keys `dream:synth-v2:<enc source>:filename:<enc basename>:<hash16>[:c<i>of<n>]` (byte-stable, pinned by `test/dream-synthesize-chunking.serial.test.ts`; grammar parsed by exported `parseSynthV2Key`). Fan-out self-heals idempotency-coalesced rows stranded `waiting` in a FOREIGN dead `dream-inline-*` queue (cancel releases the key slot → re-add into the live run's queue) instead of burning the 35-min wait on a row no worker will ever claim. Opt-in per-source daily submission cap `dream.synthesize.max_submissions_per_source_per_day` (default 0 = off; skips whole files — never partial chunk sets; bypassed for explicit `--input/--date/--from/--to` targets; count-query failure fails OPEN with a stderr warn). `--dry-run` runs triage, skips synthesis; deferral-aware headlines append "(N not yet triaged — time budget...)" so a time-boxed cold pass never reads as mass rejection. `details.triage` (threshold/judged/cache_hits/unreliable/degraded/deferred/below_threshold + rescue_band/rescue_checked/rescue_fired + tokens_in/tokens_out/cost_usd) + `details.synthesis` (jobs/avg_turns/max_turns_config + quote_verify/spend/children_zero_pages) carry the phase telemetry. Subagent never gets fs-write access. `renderPageToMarkdown` (exported) stamps `dream_generated: true` + `dream_cycle_date` into every reverse-write's frontmatter; `writeSummaryPage` does the same on the summary index — this marker is the explicit identity surface `isDreamOutput` checks in `transcript-discovery.ts`. `stampDreamProvenance` additionally persists the same marker into the `pages.frontmatter` JSONB row (merge via `executeRawJsonb`, raw object bound to `$N::jsonb`) for every child-written page BEFORE reverse-rendering, so generated pages are DB-queryable and a later put_page write-through (which re-renders from the DB row) can't erase the stamp. `judgeSignificance`, `JudgeClient`, `runTriagePass`, `buildTriageMapBlock`, `parseSynthV2Key`, `loadSynthConfig`, `TRIAGE_VERSION`, and `DEFAULT_TRIAGE_THRESHOLD` are exported; the triage model resolves via an explicit pre-read of `models.dream.triage` (preferred; through exported `resolveAlias`) falling back to the standard `resolveModel` chain (`models.dream.synthesize_verdict` → deprecated `dream.synthesize.verdict_model` → tier `utility`). `splitTranscriptByBudget(content, contentHash, maxChars)` splits oversized transcripts at paragraph boundaries (`## Topic:` → `---` → `\n` ladder) using a deterministic offset seeded from the first 32 bits of `contentHash` so retries chunk identically; per-chunk char budget = `MODEL_CONTEXT_TOKENS[resolvedModel] × 0.9 × 3.5 chars/token` (non-Anthropic ids fall back to a 180K-token safe default + once-per-process stderr warn); operator overrides `dream.synthesize.max_prompt_tokens` (floor 100K, wins) and `dream.synthesize.max_chunks_per_transcript` (default 24); per-chunk subagent job/wait timeouts are `dream.synthesize.subagent_timeout_ms` / `dream.synthesize.subagent_wait_timeout_ms` (defaults 30/35 min). Legacy `dream:synth:` keys are never produced — `loadSuccessfulSynthesisKeys(engine, sourceId, keyPrefix)` reads the completed rows of BOTH key families once per phase, unioned with `dream_synthesis_completions` (where `MinionQueue.prune` archives completed `dream:synth%` keys before deleting their rows, so `jobs prune` never makes a synthesized transcript eligible again), so existing brains skip with `already_synthesized_legacy_single_chunk`/`_chunked` instead of re-spending the synthesis model, and a transcript whose synth-v2 children already completed skips with `already_synthesized_v2_single_chunk`/`_chunked` (`findSynthV2Completion`; a cancelled row never counts) BEFORE its link manifest is built — otherwise queue.add's idempotency fast path coalesces onto the completed children and they re-enter writtenRefs, so their old pages get quote-repaired, restamped, reverse-written and re-embedded every night. `collectChildPutPageSlugs` raw-fetches every (job_id, slug) pair (not `SELECT DISTINCT`) and rewrites bare-hash6 slugs to `<hash6>-c<idx>` for chunked children (orchestrator-side, zero Sonnet trust). Cap-hit skips write nothing new to `dream_verdicts` (the pass's cached triage verdict remains — a free cache hit on retry) and record no synthesis job, so raising the cap on next run re-attempts cleanly. Bounds INITIAL prompt size only; tool-loop turn-N accumulation is caught by terminal-error classification in `subagent.ts`. Verdict routing is gateway-routed: `makeJudgeClient(verdictModel)` (exported) mirrors `tryBuildGatewayClient` in `src/core/think/index.ts` — a construction-time provider/key probe returns `null` on a clear miss (unknown provider id via `resolveRecipe` AIConfigError, or Anthropic provider with no key via `hasAnthropicKey()`). The verdict loop wraps `judgeSignificance` in try/catch for `AIConfigError` so mid-run provider failures surface as per-transcript `worth=false, reasons=['gateway error: ...']` instead of crashing the phase. Canonical config key `models.dream.synthesize_verdict` (per `PER_TASK_KEYS` in `src/core/model-config.ts`); `JudgeClient` signature preserved verbatim for test-seam stability; CI guard `scripts/check-gateway-routed-no-direct-anthropic.sh` prevents reintroducing `new Anthropic()` here or in `think/index.ts`. At the queue.add boundary a conditional `anthropic:` prefix is applied ONLY when the resolved model has no colon AND starts with `claude-` (because `resolveModel` returns bare ids from `TIER_DEFAULTS`/`DEFAULT_ALIASES` and the subagent validator requires `provider:model` form) — avoids changing the shared constants which would ripple across every `resolveModel` caller. Pinned by `test/cycle/synthesize-gateway-adapter.test.ts`, `test/e2e/dream-synthesize-pglite.test.ts` (gateway-adapter mid-run AIConfigError catch), `test/cycle/regression-pr-wave-r1-r2-r4.test.ts`. Drain-loop lock renewal runs through exported `runDrainRenewalTick` (per-call AbortSignal + timeout + re-entrancy guard) — a hung renewLock cannot stack one checked-out slot per interval firing. Pinned by `test/cycle-drain-renewal.test.ts`. Execution mode: `dream.synthesize.mode` (default `oneshot`) threads to every child as `data.mode` alongside `oneshot_slug_suffix` (the structural suffix contract) and `require_writes: true`; `details.synthesis` adds mode/oneshot_jobs/fallback_jobs/agentic_jobs/fallback_reasons plus the drain telemetry (inline_concurrency_config/effective, drain_ms, queue-wait + runtime p50/p95, dead_jobs, degraded). Pre-retrieval LINK CANDIDATES manifest (link-manifest.ts, `dream.synthesize.link_manifest` default on) is built once per transcript from the cached triage entities/segment notes and spliced into `buildSynthesisPrompt` together with an ALLOWED WRITE PATHS block rendered from the trusted allow-list (the oneshot path never sees a tool schema, so the fence lives in the prompt; rule 2 points at the candidates first). Phase outcome gate: ALL children dead/cancelled → phase fails with SYNTH_ALL_CHILDREN_DEAD (fan-out details preserved on the failure); ANY non-completed child → the cooldown stamp is skipped so released idempotency keys retry next run; 'timeout' (parent stopped waiting) degrades but never triggers the all-dead error. Phase-end deferred-embed closure: whenever the phase wrote pages (regardless of mode — an agentic revert still sweeps debt left by earlier oneshot runs), a 120s-bounded `embedStalePages` (embed-stale.ts) embeds the NULL-embedding chunks of exactly the pages this phase wrote — never a source-wide sweep; the pre-existing stale backlog stays with the budget-tracked embed-backfill machinery — closing the gap on invocation shapes that never reach the global embed phase (`--phase synthesize`, autopilot per-source NON_GLOBAL_PHASES). Best-effort (never fails a phase that wrote its pages) and stamps the current embedding signature on fully-re-embedded pages so they stay inside the model-drift invalidation contract. The inline drain lives in `src/core/cycle/inline-drain.ts` (re-exported here for patterns.ts + `__testing`). Budget clamping: clamped to the remaining parent-job budget when `opts.deadlineAtMs` is threaded (via patterns.ts's `clampSubagentBudgets` template): the clamp re-runs against the live clock PER SUBMIT (the phase is a fan-out with claim-time-anchored child kill switches, so one phase-start clamp only bounds the first child); under the minimum child budget the phase skips honestly (`insufficient_cycle_budget`) or defers the remaining transcripts (`details.budget_deferred_transcripts`), the inline drain stops CLAIMING when the budget can't fit another child and unclaimed children are cancelled + deferred (they'd otherwise strand forever in the run's private queue), each completion wait is additionally bounded by the remaining parent budget (floored at 1s so already-terminal children still resolve), and a deferring run neither writes the 12h cooldown timestamp nor counts deferred transcripts as processed — deferral genuinely retries next cycle. THE gate is `passesTriageGate` (triage-rescue.ts) applied at report construction inside `runTriagePass`: threshold pass OR the verified-segment rescue for band scores `[dream.triage.rescue_floor (0.30), threshold)` with content_type in `dream.triage.rescue_content_types` and ≥ `dream.triage.rescue_min_segments` (default 2; 0 = off) of the judge's segments verifying as normalized transcript substrings (≥40 chars, deduped) — reports carry `rescued`/`verified_segments`, `details.triage` adds rescue_band/rescue_checked/rescue_fired + judge tokens_in/tokens_out/cost_usd (null when unpriced), and dream-retriage's reconcile/audit read the SAME predicate. TRIAGE_VERSION is 2 (peak-not-average rubric; segment selection prefers concrete facts/decisions). After slug collection and BEFORE the provenance stamp/reverse-write/embed sweep, the claim verification pass (synthesize-verify.ts, `dream.synthesize.quote_verify` default on) runs on every page the children wrote, scoped by `readVerifyEpoch` (taken before fan-out) and `loadChildWriteEpochs`; the phase is wrapped in `withChatPhase('phase:synthesize')` (children keep their own job tag — minion_jobs stays the child-spend authority) and `details.synthesis` adds `quote_verify`, `children_zero_pages` (completed children with zero put_page writes — the rule-D disposition), and `spend` (`cost_basis: 'in+out+cache_read'`; children summed from minion_jobs tokens_input/output/cache_read priced at the configured synth model, triage from the pass usage; total_usd null unless both price) `buildSynthesisPrompt` is mode-aware (`mode: 'agentic' | 'oneshot'`, passed from `config.mode` at the sole submit site): agentic children keep the search-tool and final-summary guidance; tool-less oneshot children receive neither, so the prompt never contradicts `ONESHOT_SYSTEM`'s JSON-only rule (the oneshot prompt is stored as `data.prompt` and reused verbatim by the in-job agentic fallback, whose tools stay in the schema). Pinned by `test/cycle-dream-output-root.test.ts`. Managed enabled local synthesis uses durable page admission with original authority and canonical-mirror validation; completed source-incarnation-qualified children survive restart. Quote-repair failure cannot silently certify grounded publication. Remote maintenance remains unsupported. Before submitting a transcript's chunk set, the phase asks the paid-loop breaker (`dream-breaker.ts`) and records a `dream_breaker_tripped` skip with the reset command instead of submitting; the opt-in daily cap counts dead rows through their released key.-- `src/core/cycle/transcript-discovery.ts` — Pure filesystem walk for synthesize. `discoverTranscripts(opts)` filters `.txt` files by date range, min_chars, and word-boundary regex `excludePatterns` (`medical` matches "medical advice" but NOT "comedical"; power users may pass full regex). `readSingleTranscript(path)` is the `gbrain dream --input <file>` ad-hoc path. Self-consumption guard: `DREAM_OUTPUT_MARKER_RE` (anchored at frontmatter open `---\n`, optional BOM + CRLF tolerance, scans first 2000 chars for `dream_generated: true` with case-insensitive value and word boundary on `true`) drives `isDreamOutput(content, bypass=false)`. Both functions skip matching files and emit a `[dream] skipped <basename>: dream_generated marker` stderr log (no silent skips). An `excludePatterns` hit is never logged per file (the matching files are sensitive by definition); instead both functions emit ONE `[dream] excluded N transcript(s) matching exclude_patterns (<label>: n, ...)` stderr line at the end of discovery, naming only the count and the configured pattern labels that fired, never a path, basename, or content. `DEFAULT_EXCLUDE_PATTERNS` is unchanged (`medical`, `therapy`). `bypassGuard?: boolean` on `DiscoverOpts` and `readSingleTranscript`'s opts disables the guard for the explicit `--unsafe-bypass-dream-guard` escape hatch only — never auto-applied for `--input`.+- `src/core/cycle/transcript-discovery.ts` — Pure filesystem walk for synthesize. `discoverTranscripts(opts)` filters `.txt` files by date range, min_chars, and word-boundary regex `excludePatterns` (`medical` matches "medical advice" but NOT "comedical"; power users may pass full regex). `readSingleTranscript(path)` is the `gbrain dream --input <file>` ad-hoc path. Self-consumption guard: `DREAM_OUTPUT_MARKER_RE` (anchored at frontmatter open `---\n`, optional BOM + CRLF tolerance, scans first 2000 chars for `dream_generated: true` with case-insensitive value and word boundary on `true`) drives `isDreamOutput(content, bypass=false)`. Both functions skip matching files and emit a `[dream] skipped <basename>: dream_generated marker` stderr log (no silent skips). An `excludePatterns` hit is never logged per file (the matching files are sensitive by definition); instead both functions emit ONE `[dream] excluded N transcript(s) matching exclude_patterns (<label>: n, ...)` stderr line at the end of discovery, naming only the count and the configured pattern labels that fired, never a path, basename, or content. `DEFAULT_EXCLUDE_PATTERNS` is unchanged (`medical`, `therapy`). `bypassGuard?: boolean` on `DiscoverOpts` and `readSingleTranscript`'s opts disables the guard for the explicit `--unsafe-bypass-dream-guard` escape hatch only — never auto-applied for `--input`. Two path-level guards run before the content read: `selfCaptureSessionIds` (from `claudeCliSelfSessionIds`) skips a `.txt` corpus file (session-end, checkpoint segment or writeback form, via `corpusFileSessionId`) captured from gbrain's own claude-cli call, and `excludeDirs` (synthesize passes the reflections, originals, patterns-output and cycle-summary directories under `brainDir`, empty under `--unsafe-bypass-dream-guard`) skips any file whose resolved path sits inside one, so an output a failed postprocess left unmarked is never re-synthesized while a transcript that merely names such a path is still discovered; each class is reported as one count-only stderr line.-- `src/core/cycle/transcript-discovery.ts` — Pure filesystem walk for synthesize. `discoverTranscripts(opts)` filters `.txt` files by date range, min_chars, and word-boundary regex `excludePatterns` (`medical` matches "medical advice" but NOT "comedical"; power users may pass full regex). `readSingleTranscript(path)` is the `gbrain dream --input <file>` ad-hoc path. Self-consumption guard: `DREAM_OUTPUT_MARKER_RE` (anchored at frontmatter open `---\n`, optional BOM + CRLF tolerance, scans first 2000 chars for `dream_generated: true` with case-insensitive value and word boundary on `true`) drives `isDreamOutput(content, bypass=false)`. Both functions skip matching files and emit a `[dream] skipped <basename>: dream_generated marker` stderr log (no silent skips). `bypassGuard?: boolean` on `DiscoverOpts` and `readSingleTranscript`'s opts disables the guard for the explicit `--unsafe-bypass-dream-guard` escape hatch only — never auto-applied for `--input`.+- `src/core/cycle/transcript-discovery.ts` — Pure filesystem walk for synthesize. `discoverTranscripts(opts)` filters `.txt` files by date range, min_chars, and word-boundary regex `excludePatterns` (`medical` matches "medical advice" but NOT "comedical"; power users may pass full regex). `readSingleTranscript(path)` is the `gbrain dream --input <file>` ad-hoc path. Self-consumption guard: `DREAM_OUTPUT_MARKER_RE` (anchored at frontmatter open `---\n`, optional BOM + CRLF tolerance, scans first 2000 chars for `dream_generated: true` with case-insensitive value and word boundary on `true`) drives `isDreamOutput(content, bypass=false)`. Both functions skip matching files and emit a `[dream] skipped <basename>: dream_generated marker` stderr log (no silent skips). `bypassGuard?: boolean` on `DiscoverOpts` and `readSingleTranscript`'s opts disables the guard for the explicit `--unsafe-bypass-dream-guard` escape hatch only — never auto-applied for `--input`. Two path-level guards run before the content read: `selfCaptureSessionIds` (from `claudeCliSelfSessionIds`) skips a `.txt` corpus file (session-end, checkpoint segment or writeback form, via `corpusFileSessionId`) captured from gbrain's own claude-cli call, and `excludeDirs` (synthesize passes the reflections, originals, patterns-output and cycle-summary directories under `brainDir`, empty under `--unsafe-bypass-dream-guard`) skips any file whose resolved path sits inside one, so an output a failed postprocess left unmarked is never re-synthesized while a transcript that merely names such a path is still discovered; each class is reported as one count-only stderr line.- `src/core/cycle/triage-rescue.ts` — THE dream triage gate (`passesTriageGate`) + the verified-segment rescue (`applyTriageRescue`). Rescue fires only for scores in `[floor, threshold)` (floor inclusive; at/above threshold is the plain gate's job) with content_type in the buried-signal allowlist (default mixed/reflection/idea/strategy/people — never routine/technical) and ≥ minSegments of the judge's own segments verifying as normalized transcript substrings (`normForGrounding`, ≥40 chars, deduped by normalized quote — repetition is not more evidence). $0 — no LLM calls; fabricated segments cannot fire it; works on cached verdicts (gate-time only). Fail-closed on every malformed shape (null score, missing/short/non-string segments), never throws. `minSegments: 0` is the kill switch (gate degenerates to the plain threshold). ONE-GATE RULE: `runTriagePass` (report construction — `worth`/`rescued`/telemetry/dry-run), the synthesize fan-out, and `dream retriage` (reconcile-queue cancels + `--audit-rejects` sampling) all read this predicate — a second hand-rolled `score >= threshold` check is how an operator sweep cancels exactly the jobs the rescue admitted. Config: `dream.triage.rescue_floor` / `rescue_min_segments` / `rescue_content_types`. Pinned by `test/cycle-triage-rescue.test.ts` + the rescue suites in `test/cycle-synthesize-triage.test.ts` / `test/dream-retriage.test.ts`.diff --git a/docs/architecture/key-files/core-minions-1.md b/docs/architecture/key-files/core-minions-1.mdindex ff603278d2..eabeaa08bc 100644--- a/docs/architecture/key-files/core-minions-1.md+++ b/docs/architecture/key-files/core-minions-1.md@@ -53,7 +53,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/minions/handlers/subagent-oneshot.ts` — oneshot synthesis runner. ONE rate-leased tool-less `gateway.chat` call (static `ONESHOT_SYSTEM` JSON contract rides the prompt-cache prefix; sub-budget min(5 min, timeout/4) → `fallback_reason: 'oneshot_timeout'`), then all-or-nothing validation BEFORE any write: JSON contract (`parseOneshotResponse`, ≤12 pages), slug grammar + `allowed_slug_prefixes` + reflections/originals task shape + the exact `oneshot_slug_suffix` (the idempotency boundary, enforced structurally), exact-match wikilink rule against existing ∪ in-batch slugs (`extractWikilinkTargets`; cold-brain relaxation: <5 pages AND no manifest accepts syntactic presence). Writes go through the SAME `brain_put_page` ToolDef the loop uses (fences/side-effects/provenance identical) with `deferEmbeds`, bracketed by standard ledger rows under invocation-scoped ids `oneshot-<inv8>-p<i>`; a post-batch `autoLinkWrittenPage` pass materializes in-batch forward wikilink edges. Ledger-first crash recovery: any prior oneshot rows → finalize from the ledger, never re-call the nondeterministic model. Transcript rows persist ONLY after success (a failed attempt is never replayable as a completed result). Every failure shape returns `{kind:'fallback', reason}` and the same job falls through to the agentic loop. Pinned by `test/minions/subagent-oneshot.test.ts` + the oneshot describes in `test/subagent-handler.test.ts` and `test/e2e/dream-synthesize-pglite.test.ts`. `ONESHOT_SYSTEM` spells out JSON string escaping (quotes, backslashes, line breaks). A parse failure whose reported output usage reaches the requested cap falls back as `length` even when the provider normalized the stop to `end`/`other`; below-cap malformed output stays `unparseable`, and valid JSON at the cap proceeds normally.-- `src/core/minions/handlers/subagent-persistence.ts` — subagent transcript + tool-execution persistence (pure peel from subagent.ts): loadPriorMessages/Tools/ToolsV2, persistMessage, persistToolExecPending/Complete/Failed (all `$N::text::jsonb` discipline), plus `finalizeWriteAccounting`: derives pages_attempted/written/failed from the job's put_page ledger rows (settled only — pending counts toward neither), merges them into every SubagentResult, and throws UnrecoverableError on require_writes jobs with no settled successful write, including zero-attempt clean finishes; `scopeToolUseIdPrefix` narrows the scan to the oneshot invocation family. Fresh `brain_put_page` rejects are normalized by `src/core/minions/tools/put-page-result.ts` before ledger settlement; accounting reclassifies rejected historical completed envelopes (including JSON strings) without changing the stored rows. Unchanged-page saves and persisted pages whose embedding failed still count as writes.+- `src/core/minions/handlers/subagent-persistence.ts` — subagent transcript + tool-execution persistence (pure peel from subagent.ts): loadPriorMessages/Tools/ToolsV2, persistMessage, persistToolExecPending/Complete/Failed (all `$N::text::jsonb` discipline), plus `finalizeWriteAccounting`: derives pages_attempted/written/failed from the job's put_page ledger rows (settled only — pending counts toward neither), merges them into every SubagentResult, and throws UnrecoverableError on require_writes jobs with no settled successful write, including zero-attempt clean finishes, unless `isLegitimateZeroWrite` accepts the zero-attempt `end_turn` finish: the oneshot explicit skip (`oneshot_skipped: true` on a `synth_mode_used: 'oneshot'` result) or, when the submitter set `allow_clean_zero_writes` (the patterns phase), a run with at least one completed tool execution in its ledger — all-attempted-failed, dirty stops, prose-only finishes and runs whose only tools failed still dead-letter (the oneshot runner banks each skip as a `oneshot-<inv8>-skip` ledger row before its transcript, so a retried job's ledger-first recovery completes as the same skip without a model call); `scopeToolUseIdPrefix` narrows the scan to the oneshot invocation family. Fresh `brain_put_page` rejects are normalized by `src/core/minions/tools/put-page-result.ts` before ledger settlement; accounting reclassifies rejected historical completed envelopes (including JSON strings) without changing the stored rows. Unchanged-page saves and persisted pages whose embedding failed still count as writes.- `src/core/minions/handlers/subagent.ts` — LLM-loop handler. Two-phase tool persistence (pending → complete/failed), replay reconciliation for mid-dispatch crashes, dual-signal abort (`ctx.signal` + `ctx.shutdownSignal`), Anthropic prompt caching on system + tool defs. `makeSubagentHandler({engine, client?, ...})` factory; `MessagesClient` is an injectable interface the real SDK implements structurally. Per-turn output cap resolves via `resolveMaxOutputTokens` (`data.max_tokens` → `agent.max_output_tokens` config → 8192 default); a `stop_reason: 'max_tokens'` final turn surfaces as `SubagentStopReason 'max_tokens'` (not a silent `end_turn`), and a max_tokens stop mid-tool-round injects a truncation note into the tool-result turn so the model re-issues the dropped call. Throws `RateLeaseUnavailableError` (renewable) when rate-lease capacity is full. Both loop paths (the direct Anthropic SDK turn loop and the gateway toolLoop's `acquireTurnPermit`) heartbeat the held lease at ttl/3 for the duration of each provider call — single-flight renewals so a stalled renewal never stacks behind a starved pool; a FALSE renewal means the lease row was pruned/stolen (the slot is already re-admitted), so the in-flight call aborts and converts to a lease-full requeue instead of running above `maxConcurrent`. Anthropic 400 `prompt is too long` responses (status 400 + body matches `/prompt is too long|prompt_too_long|context.*length/i`) classify as `UnrecoverableError` so the job goes straight to `dead` on first attempt instead of stalling three times. Catches both initial-prompt overflow and turn-N tool-loop accumulation that `synthesize.ts`'s chunker can't bound ahead of time. terminal-state short-circuit on resume. When a stored message thread already ends in `stop_reason: 'end_turn'`, the handler returns `{ ok: true }` immediately instead of issuing another `messages.create` call (re-prompting past `end_turn` would get a 400 and dead-letter an already-successful job). Pinned by `test/subagent-handler.test.ts`. Oneshot dispatch: `data.mode === 'oneshot'` on a FRESH job (zero persisted messages) routes to `runSubagentOneshot` (subagent-oneshot.ts) before either loop; a validation fallback re-enters the loops in the SAME job, stamped `synth_mode_used: 'agentic_fallback'` + `fallback_reason`. Write accounting (`finalizeWriteAccounting` in subagent-persistence.ts): every job's result carries pages_attempted/written/failed derived from the tool-execution ledger (settled rows only); `data.require_writes` jobs (dream synthesize + patterns fan-outs) require at least one settled successful page write; zero successes, including a clean prose-only finish or pending-only ledger, throw UnrecoverableError. Optional-write jobs can still complete without writing. `resolveMaxOutputTokens` takes the model: thinking-by-default models (Claude 5 by name or recipe-declared `thinking_by_default` such as DeepSeek v4, via the gateway's shared `isThinkingModel`) default to 32000 when neither per-job nor config caps are set. Gateway-path `onToolCallStart` has a uniq_subagent_tools_use_id backstop: a provider repeating a tool id across turns persists under a `#m<idx>o<ordinal>`-suffixed debug id (second violation reconciles to the existing row's gbrain_tool_use_id) instead of dead-lettering the job. Persistence helpers live in subagent-persistence.ts (pure peel; `__testing` unchanged). Tool-execution rows carry NO job-wide unique on the raw provider `tool_use_id` (migration v131 drops `uniq_subagent_tools_use_id`: providers like claude-cli legitimately re-mint the same short id every turn, and a collision would dead-letter the job); row identity is the stable `(job_id, message_idx, ordinal)` unique, and readers/settlement resolve an execution by `(message_idx, tool_use_id)`. Settle writes (complete/failed) target exactly ONE row — the call's own ordinal first, then a legacy ordinal=NULL row, never a row that already settled complete (a broader status disjunct could only capture a same-id sibling's row); pending inserts guard legacy NULL-ordinal rows via NOT EXISTS and use the stable-id `ON CONFLICT` as the zombie-worker backstop. Replay/reconcile resolve an execution by persisted ordinal first (validated against the raw id), then by `(message_idx, tool_use_id)` only when the id is unique within the turn, then the same-tool legacy positional fallback. Mixed-version window: a still-running pre-v131 `gbrain jobs work` daemon errors on tool persistence after the migration until it restarts (its two-phase writes targeted the dropped constraint)@@ -71,7 +71,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/minions/protected-names.ts` — side-effect-free constant module exporting `PROTECTED_JOB_NAMES` + `isProtectedJobName()`. Kept pure so queue core can import without loading handler modules. `PROTECTED_JOB_NAMES` includes `synthesize`, `patterns`, `consolidate`. These phases internally submit `subagent` children with `allowProtectedSubmit=true` and can spend Anthropic credits. Only trusted local callers (CLI, autopilot, `doctor --remediate`) can submit them; MCP requests are rejected by `submit_job`'s protected-name guard.-- `src/core/minions/queue.ts` — MinionQueue class (submit, claim, complete, fail, stall detection, parent-child, depth/child-cap, per-job timeouts, cascade-kill, attachments, idempotency keys, child_done inbox, removeOnComplete/Fail). `prune()` archives each completed `dream:synth%` subagent key into `dream_synthesis_completions` in the same statement that deletes the row, so pruning never re-arms paid synthesis. `add()` takes a 4th `trusted` arg (separate from `opts` to prevent spread leakage); protected names in `PROTECTED_JOB_NAMES` require `{allowProtectedSubmit: true}` and the check runs trim-normalized (whitespace-bypass safe). The same trusted arg carries `{allowPgliteInlineWorker: true}`, a narrowly scoped exception used only when `gbrain jobs submit embed-backfill --follow` starts and awaits a worker in that process. Before config, schema, policy, SQL, or transaction access, `add()` invokes the centralized embed-backfill admission gate; PGLite and unknown engine kinds refuse, while explicit Postgres preserves queued submission. `add()` plumbs `max_stalled` through with a `[1, 100]` clamp; omitted values let the schema DEFAULT (5) kick in. `handleWallClockTimeouts(lockDurationMs)` is Layer 3 kill shot for jobs where `FOR UPDATE SKIP LOCKED` stall detection and the timeout sweep both fail to evict (wedged worker holding a row lock via a pending transaction). The submission backpressure guard covers two options sharing one `pg_advisory_xact_lock` namespace keyed on `(name, queue, source)`: `maxWaiting` (rate cap, counts `waiting` only, NULL-source-as-wildcard scope) and `maxPending` (single-flight, counts `waiting` + live-lock `active` rows where `lock_until > now()`, EXACT source scope via `COALESCE(data->>'sourceId', data->>'source_id')` — an expired-lock active never suppresses, keeping the waitingClaimable wedge detectors fed). All three coalesce return paths (idempotency fast-path, cap-hit, ON CONFLICT race fallback) stamp non-persisted `coalesced: true` metadata on the returned job. Both filter on `queue` in addition to `name` so cross-queue same-name jobs don't suppress each other. `claim` and `renewLock` issue their UPDATE via `engine.executeRawDirect` (not `executeRaw`) so the lock heartbeat runs on the direct session-mode pool that the transaction pooler won't recycle mid-hold; on PGLite this is identical to `executeRaw`. The two terminal dead-letter paths (`handleWallClockTimeouts` wall-clock kill and the stall dead-letter CTE in the stall sweep) BOTH increment `attempts_made` so a long job killed there reads as an honest attempt instead of `attempts 0 / started N`; the stall path also bumps `stalled_counter`, surfaced by `gbrain jobs get` as `Attempts: M/N (started: X, stalled: S/MaxS)`. At submit, `add()` stamps a default `timeout_ms` via `defaultTimeoutMsFor(jobName)` (from `handler-timeouts.ts`) when the caller passed none, and `claim()` COALESCEs a still-NULL `timeout_ms` from `HANDLER_DEFAULT_TIMEOUT_MS` (raw-object jsonb bind) deriving `timeout_at` from the coalesced value — the durable invariant covering rows that predate submit-time stamping; an explicit `opts.timeout_ms` always wins. The lock lease follows the identical three-layer shape: `add()` stamps `opts.lock_duration_ms` (clamped [5s,1h] via the shared `clampLockDurationMs`; INSERT-only — an idempotency-key re-submit never mutates the first submitter's lease) else `defaultLockDurationMsFor(jobName)`; `claim()` derives `lock_until` from `COALESCE(lock_duration_ms, map, worker default)` and stamps the resolved lease, SQL-clamping the row/map-resolved value to [5s,1h] (the worker-default fallback passes through unclamped — operator-configured, and tests legitimately use sub-5s leases) so a bypass-written out-of-range row can't produce a pathological lease; `handleWallClockTimeouts`' null-timeout fallback uses `COALESCE(lock_duration_ms, worker default)`. `handleStalled(graceMsOverride?)` applies the stall-sweep reclaim grace (`GBRAIN_MINION_STALL_RECLAIM_GRACE_MS`, default 15s, 0 = legacy predicate, capped at 600s with a warn-once clamp so an oversized value can't disable stalled-job recovery) to all three sweep predicates — a lease that lapsed within the grace is a starved owner's head start, not a steal candidate. Guarded by `test/queue-lock-retry.test.ts` (claim never falls back to `executeRaw`), `test/postgres-execute-raw-direct.test.ts` (routing decision matrix), and `test/minions.test.ts` (attempt accounting + default-timeout stamping). `MinionQueue.add()` gates `subagent` jobs on capability, not provider: `data.model` is classified via `classifyCapabilities()` (lazy-imported from `src/core/ai/capabilities.ts` to keep queue's eager-load surface small) and rejected only when the model cannot run a tool loop (`unusable:no_tools`) or names an unknown provider; degraded verdicts pass through with a gateway cost warning. Layer 1 of the three-layer subagent capability enforcement (layers 2+3: `model-config.ts:enforceSubagentCapable` runtime fallback + `src/commands/doctor.ts` `subagent_provider` check). Pinned by `test/agent-cli.test.ts`. All three terminal reaper paths (stall dead-letter, wall-clock kill, cascade) route through the ONE private `killJobs(tx, rows, cause, message)` tail: it emits `child_done(outcome)` to each non-terminal parent's inbox and flips any `waiting-children` parent whose last open child just died back to `waiting` — so a dead-lettered child can never strand its aggregator parent. Callers lock parents FIRST via `lockParentsOrdered` (ascending-id row locks, matching `failJob`'s parent-before-child order) so the reapers and `failJob` can never deadlock on parent/child lock acquisition. An idempotent stranded-parent sweep runs once per stall tick (~30s): any `waiting-children` parent with zero non-terminal children flips back to `waiting` (single UPDATE, NOT EXISTS on an indexed FK) — self-heals every stranding class, including parents stranded before the sweep existed. Every automatic re-run path clears `started_at` (`failJob`'s delayed retry branch, the stall requeue, lease release, `promoteDelayed`, and the parent-unblock flips) so the per-attempt wall clock measures execution, not backoff/queue wait — a retried job can't be dead-lettered by the wall-clock sweep before executing a line. Pinned by `test/queue-stall-parent-unblock.test.ts` + `test/queue-started-at-retry.test.ts`. `renewLock` accepts optional `{signal}` forwarded to executeRawDirect so the renewal tick's timeout race CANCELS a hung UPDATE instead of orphaning a checked-out pool slot (best-effort — the token fence is the correctness authority; a late-landing renewal can only extend a lease nobody else claimed).+- `src/core/minions/queue.ts` — MinionQueue class (submit, claim, complete, fail, stall detection, parent-child, depth/child-cap, per-job timeouts, cascade-kill, attachments, idempotency keys, child_done inbox, removeOnComplete/Fail). `prune()` archives each completed `dream:synth%` subagent key into `dream_synthesis_completions` in the same statement that deletes the row, so pruning never re-arms paid synthesis. `add()` takes a 4th `trusted` arg (separate from `opts` to prevent spread leakage); protected names in `PROTECTED_JOB_NAMES` require `{allowProtectedSubmit: true}` and the check runs trim-normalized (whitespace-bypass safe). The same trusted arg carries `{allowPgliteInlineWorker: true}`, a narrowly scoped exception used only when `gbrain jobs submit embed-backfill --follow` starts and awaits a worker in that process. Before config, schema, policy, SQL, or transaction access, `add()` invokes the centralized embed-backfill admission gate; PGLite and unknown engine kinds refuse, while explicit Postgres preserves queued submission. `add()` plumbs `max_stalled` through with a `[1, 100]` clamp; omitted values let the schema DEFAULT (5) kick in. `handleWallClockTimeouts(lockDurationMs)` is Layer 3 kill shot for jobs where `FOR UPDATE SKIP LOCKED` stall detection and the timeout sweep both fail to evict (wedged worker holding a row lock via a pending transaction). The submission backpressure guard covers two options sharing one `pg_advisory_xact_lock` namespace keyed on `(name, queue, source)`: `maxWaiting` (rate cap, counts `waiting` only, NULL-source-as-wildcard scope) and `maxPending` (single-flight, counts `waiting` + live-lock `active` rows where `lock_until > now()`, EXACT source scope via `COALESCE(data->>'sourceId', data->>'source_id')` — an expired-lock active never suppresses, keeping the waitingClaimable wedge detectors fed). All three coalesce return paths (idempotency fast-path, cap-hit, ON CONFLICT race fallback) stamp non-persisted `coalesced: true` metadata on the returned job. Both filter on `queue` in addition to `name` so cross-queue same-name jobs don't suppress each other. `claim` and `renewLock` issue their UPDATE via `engine.executeRawDirect` (not `executeRaw`) so the lock heartbeat runs on the direct session-mode pool that the transaction pooler won't recycle mid-hold; on PGLite this is identical to `executeRaw`. The two terminal dead-letter paths (`handleWallClockTimeouts` wall-clock kill and the stall dead-letter CTE in the stall sweep) BOTH increment `attempts_made` so a long job killed there reads as an honest attempt instead of `attempts 0 / started N`; the stall path also bumps `stalled_counter`, surfaced by `gbrain jobs get` as `Attempts: M/N (started: X, stalled: S/MaxS)`. At submit, `add()` stamps a default `timeout_ms` via `defaultTimeoutMsFor(jobName)` (from `handler-timeouts.ts`) when the caller passed none, and `claim()` COALESCEs a still-NULL `timeout_ms` from `HANDLER_DEFAULT_TIMEOUT_MS` (raw-object jsonb bind) deriving `timeout_at` from the coalesced value — the durable invariant covering rows that predate submit-time stamping; an explicit `opts.timeout_ms` always wins. The lock lease follows the identical three-layer shape: `add()` stamps `opts.lock_duration_ms` (clamped [5s,1h] via the shared `clampLockDurationMs`; INSERT-only — an idempotency-key re-submit never mutates the first submitter's lease) else `defaultLockDurationMsFor(jobName)`; `claim()` derives `lock_until` from `COALESCE(lock_duration_ms, map, worker default)` and stamps the resolved lease, SQL-clamping the row/map-resolved value to [5s,1h] (the worker-default fallback passes through unclamped — operator-configured, and tests legitimately use sub-5s leases) so a bypass-written out-of-range row can't produce a pathological lease; `handleWallClockTimeouts`' null-timeout fallback uses `COALESCE(lock_duration_ms, worker default)`. `handleStalled(graceMsOverride?)` applies the stall-sweep reclaim grace (`GBRAIN_MINION_STALL_RECLAIM_GRACE_MS`, default 15s, 0 = legacy predicate, capped at 600s with a warn-once clamp so an oversized value can't disable stalled-job recovery) to all three sweep predicates — a lease that lapsed within the grace is a starved owner's head start, not a steal candidate. Guarded by `test/queue-lock-retry.test.ts` (claim never falls back to `executeRaw`), `test/postgres-execute-raw-direct.test.ts` (routing decision matrix), and `test/minions.test.ts` (attempt accounting + default-timeout stamping). `MinionQueue.add()` gates `subagent` jobs on capability, not provider: `data.model` is classified via `classifyCapabilities()` (lazy-imported from `src/core/ai/capabilities.ts` to keep queue's eager-load surface small) and rejected only when the model cannot run a tool loop (`unusable:no_tools`) or names an unknown provider; degraded verdicts pass through with a gateway cost warning. Layer 1 of the three-layer subagent capability enforcement (layers 2+3: `model-config.ts:enforceSubagentCapable` runtime fallback + `src/commands/doctor.ts` `subagent_provider` check). Pinned by `test/agent-cli.test.ts`. All three terminal reaper paths (stall dead-letter, wall-clock kill, cascade) route through the ONE private `killJobs(tx, rows, cause, message)` tail: it emits `child_done(outcome)` to each non-terminal parent's inbox and flips any `waiting-children` parent whose last open child just died back to `waiting` — so a dead-lettered child can never strand its aggregator parent. Callers lock parents FIRST via `lockParentsOrdered` (ascending-id row locks, matching `failJob`'s parent-before-child order) so the reapers and `failJob` can never deadlock on parent/child lock acquisition. An idempotent stranded-parent sweep runs once per stall tick (~30s): any `waiting-children` parent with zero non-terminal children flips back to `waiting` (single UPDATE, NOT EXISTS on an indexed FK) — self-heals every stranding class, including parents stranded before the sweep existed. Every automatic re-run path clears `started_at` (`failJob`'s delayed retry branch, the stall requeue, lease release, `promoteDelayed`, and the parent-unblock flips) so the per-attempt wall clock measures execution, not backoff/queue wait — a retried job can't be dead-lettered by the wall-clock sweep before executing a line. Pinned by `test/queue-stall-parent-unblock.test.ts` + `test/queue-started-at-retry.test.ts`. `renewLock` accepts optional `{signal}` forwarded to executeRawDirect so the renewal tick's timeout race CANCELS a hung UPDATE instead of orphaning a checked-out pool slot (best-effort — the token fence is the correctness authority; a late-landing renewal can only extend a lease nobody else claimed). Re-submitting an idempotency key held by a dead or cancelled row nulls that row's key and records it as `data.__released_idempotency_key`, so the dream paid-loop breaker and daily cap still see the death.- `src/core/minions/rate-leases.ts` — lease-based concurrency cap for outbound providers (default key `anthropic:messages`, max via `GBRAIN_ANTHROPIC_MAX_INFLIGHT`). Owner-tagged rows with `expires_at` auto-prune on acquire; `pg_advisory_xact_lock` guards check-then-insert; CASCADE on owning job deletion. `renewLeaseWithBackoff` retries 3x (250/500/1000ms). Canonical home of `RateLeaseUnavailableError` (thrown when acquire finds no slot; the worker and the inline dream drain both recognize it and requeue WITHOUT burning an attempt — lease-full is a scheduling condition, not a failure; `subagent.ts` re-exports it for compatibility) and `leaseFullBackoffMs()` (the shared 1–3s jittered lease-full requeue backoff `worker.ts` and `inline-drain.ts` both use, so the two curves cannot silently desync).diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.mdnew file mode 100644index 0000000000..f199a938f2--- /dev/null+++ b/docs/architecture/key-files/core-persistence.md@@ -0,0 +1,47 @@+# Key files: Core Persistence++[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.+Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.+The page operations that submit through this layer are in [Core Services (2/3)](core-services-2.md).++- `src/core/persistence/connector-google-receipts.ts` — the managed Google attachment-repair preparer checks account/thread/message ownership from the current canonical snapshot, changes only the owned receipt frontmatter field, and installs provider-free text projections under the existing source-before-page publication locks. Page identity/revision, current authorization, source incarnation and file recovery guards remain mandatory; body, unrelated frontmatter, tags and the withdrawal ledger are preserved. It schedules no embeddings, loop detection or fact extraction. `connector-sync.ts` admits this narrow mutation and banks its committed receipts through the existing managed connector checkpoints.++- `src/core/persistence/activation.ts` — private CLI `sources writer activate --confirm-quiesced` boundary. Verifies native capability and active filesystem bindings, takes root locks before DB waits and rechecks topology under transaction guards before enabling managed writes. Live/young/foreign legacy leases refuse regardless of expiry; only explicitly requested `--cleanup-dead-local-locks` removes exact dead same-host holders, under the lease transaction lock. Dry-run reports candidates without deletion. Registration never silently claims a source. Tests: `test/persistence-activation.test.ts`, `test/persistence-onboarding.test.ts`. Unbound Google/GitHub API sources may activate as reviewed `connector_database` without fabricating a Git root, while bound sources still require canonical physical-root checks.++- `src/core/persistence/onboarding.ts` + `legacy-locks.ts` + `physical-root-recovery.ts` — read-only source onboarding states; exact same-host dead-lock cleanup under explicit activation opt-in; and state-bound same-owner root repair using a durable manifest and token-verified temporary stamp. `physical-root.ts` `restampPhysicalRoot` handles a filesystem device id that changed while the owner token, brain, worktree, root, inode and a non-zero birth time still match (macOS can renumber `st_dev` across reboots): under the caller's outside-root native lock, one transaction verifies owner host, brain and host binding and rewrites the recorded self-transfer copies and retained topology staging identities (each only while it still names the old device); after commit the stamp and the reservation's initial device are rewritten and the event is logged, so an interruption between the two leaves a device-only change the next locked acquisition finishes. Ownership markers inside a retained topology clone stage are not re-stamped; an interrupted clone recovery that spans a device renumbering still needs source recovery. `assertPhysicalRoot` stays read-only; zero birth time or any other difference keeps the refusal. `--self-transfer` prepare/accept requires separate fresh reviewed state, preserves original reservation owner evidence and refuses uncertain records. Tests: `test/persistence-onboarding.test.ts`, `test/persistence-admin-recovery.test.ts`, `test/persistence-container-preflight.test.ts`.++- `src/core/persistence/{atom-maintenance,atom-retry,facts-maintenance,facts-prepare,prepared-maintenance}.ts` — resident dispatch for durable atom publication/completion, explicit atom retry, authorized multi-entity fact-fence/backstop append and local synthesize/patterns/consolidation. Accepted output replays provider-free after restart; page/take preparers recheck original/current grants, source incarnation and revisions. Unresolved facts remain DB-only without phantom pages. Retired takes skip; semantic fact snapshots exclude derived vector/cache fields and journal quotas reject overlarge retained intent. Managed consolidation retains the explicit chronological `valid_until` writeback from the legacy consolidation phase, scoped to the accepted source/fact IDs and revalidated semantic snapshots; contradiction probes never gain supersession authority. Remote maintenance and unapproved bulk lanes remain refused. Tests: `test/managed-extract-atoms.test.ts`, `test/managed-facts-backstop.test.ts`, `test/managed-maintenance.test.ts`.++- `src/core/persistence/canonical-projections.ts` — installs the facts, takes and timeline projections of a canonical page body inside its publication transaction. Preparation takes the caller's prior snapshot and writer class and pins the stored timeline rows and take row numbers. Writer classes: `editing` (revision-bound `put_page`, reconcile with an approved body decision), `preserving` (`put_page` without a revision, reconcile, connectors), `file` (managed sync of file edits and managed import) and `immutable` (company-brain imports). One pure decision table (`timelineRowAction`) maps each row state (`in_body`, `drifted`, `removed`, `removed_marked`, `database_only`) to `refresh_detail`, `delete`, `keep` or `materialize`: database-only rows are materialized by `editing` and `preserving` writers and kept by the others; a materialized bullet the new body drops is deleted by `editing`/`file`, rendered again by `preserving` and kept DB-side by `immutable`. `materializeTimeline` runs during preparation, before the body is imported, digested and rendered, and appends each round-trippable row after existing bullets in date-then-id order as a marked bullet (`timeline-marker.ts`); `renderMaterializedBullet` requires render-then-extract to return exactly the tuple and normalized detail, so backlink receipts, empty or delimiter-bearing sources are kept and never rendered. `pendingTimelineRows` counts materializable and kept rows for the repair and doctor. Deletes and detail refreshes match the pinned id, tuple and detail, so rows changed after preparation are untouched. A new fence row whose number belongs to a database-only take refuses with `take_row_collision`. `compileCanonicalProjections` is the validation-only entry. Tests: `test/canonical-projection-history.test.ts`, `test/timeline-materialize.test.ts` (PGLite and Postgres).++- `src/core/persistence/admission-retry.ts` — bounded retries for database-confirmed admission transaction aborts. Each retry reuses the UUID and normalized intent, rechecks guarded authority and reserves quota only on commitment. Standalone journal admission uses 100ms lock waits within the five-second retry budget to retain queue position behind short counter transactions; backoff occurs after rollback releases the connection so counter contention leaves pool capacity for reads. Ambiguous connection/commit errors are never classified as confirmed rollback. Real counter-lock, sustained-queue progress, read-capacity and after-insert rollback tests live in `test/persistence-journal.test.ts`. Withdrawal retries wrap its whole source-exclusive transaction with its existing lock policy; `admitWriteInTransaction` never backs off inside an existing unit of work. `test/persistence-withdrawal-retry.test.ts` verifies guard release, complete rollback and bounded contention.++- `src/core/persistence/connector-sync.ts` — managed Google/GitHub API ingestion uses source-scoped journaled import/deletion and `managed-connector` checkpoint CAS, not Git cursors. Unbound connectors use reviewed `connector_database` SQL-only authority; bound connectors retain canonical file publication with guarded root/hash/revision/epoch. Standalone entry, page reads and submissions authenticate the current source, local grant and canonical owner, then start the existing consumer and wait up to five seconds for retained worktree publications to settle before checking file bytes or deriving new request identity. Blocked recovery returns its retained receipt and `blocked_reason`; startup recovery precedes connector fetching, and operator edits still fail the strict file-drift check. Explicit `--retry-failed` atomically admits a new linked attempt and stores a per-base-request `managed-connector-retry` pointer, without changing the API cursor or reopening terminal receipts. Approval revalidates current and accepted authority, source/configuration/owner and idle state; concurrent approvals and pending/restarted calls reuse the already approved attempt. Receipt compaction retains the digest and authority needed for exact replay and retry. Checkpoint page-receipt lists are server-derived validation dependencies, excluded from caller identity but frozen in the first admitted intent; changed dependency lists on an unchanged sweep cannot bypass a terminal checkpoint. Durable connector cursors and retry pointers survive generic seven-day checkpoint GC, including completed sweeps needed for incremental resume. Source incarnation/configuration changes select separate cursors; obsolete state remains retained rather than automatically retiring by age. Failed pagination/identity reads cannot advance freshness or delete unconfirmed pages. Tests: `test/persistence-connectors.test.ts`, `test/persistence-connector-retry.test.ts` and `test/helpers/connector-restart.ts` cover synthetic public sync entry in fresh processes, actual SIGKILL between file publication and DB commit, blocked recovery, zero-fetch authorization refusal, aged cursor purge/resume, real storage failures, compacted retries, checkpoint dependencies, atomic approval/lost acknowledgement and concurrent paused-owner replay on PGLite and disposable Postgres.++- `src/core/persistence/consumer.ts` — resident canonical-write consumer with retained wake-ups, root-scoped retry backoff and locked-row-skipping expired-claim sweeps. A full tick fans out to every worker; when idle, each tick instead runs one work probe (a single statement mirroring the claim, recovery, expired-claim, effect, projection and topology predicates, excluding rows those workers would skip, including topology recoveries that failed to finish within the last 30 s) and the poll interval doubles from 250 ms to a 5 s cap (`idleMaxMs`), resetting on work. `wake()` runs a full tick immediately; `waitForWrite` calls it after a same-process admission commits, so cross-process writes wait at most 5 s plus one probe and no LISTEN is used. A probe failure is reported once and the next tick runs the full fan-out. On Postgres pools of three or more with no connection checked out, idle probes share one reserved connection (acquired and queried under the phase deadline; a timed-out lane returns to the pool once its query settles) so the rest of the pool drains through the 20 s `idle_timeout` (postgres.js reuses idle connections first-in-first-out); root refresh and receipt compaction run every 5 minutes while idle. Root refresh, recovery scan, sweep and capacity-marking SQL use cooperative five-second cancellation; failure never admits work under stale confinement. Cold direct initialization and queued transactions remain observed and awaited through shutdown. Recognized cancellation owned by the consumer's stop reason is not reported as a storage failure; deadline-first cancellation and unrelated storage errors remain visible. Ordinary put-page/remember preparation has a cooperative 30-second deadline; abort-ignoring work remains tracked, and late preparation cannot publish. Publication and shutdown retain the token/native-lock/recovery barriers. Trusted status exposes sampled process-local phases and attempts, not durable progress. Tests: `persistence-consumer-scheduling.test.ts`, `persistence-consumer-idle.test.ts`, `persistence-root-refresh.test.ts`, `test/e2e/persistence-phase-liveness.test.ts`, `test/e2e/persistence-idle-pool.test.ts`.++- `src/core/persistence/health.ts` — pure advisory age/reason/action policy shared by receipts and trusted diagnostics. The nested public contract is optional, validated and explicitly allowlisted; thresholds are 30/120 seconds and polls 1/5/30 seconds. The journal batches at most 100 authorized receipts into one projected root query with a 500ms caller budget, retaining one in-flight query per engine until settlement. Database-only pending lookups use a partial source-incarnation/sequence index shared by both engines. Synchronous service reads coalesce only for the same request ID, retain at most four unresolved reads per engine until settlement, and permit cancellation only by the read's initiating waiter or shutdown. No health observation changes authority or durable state. Real authenticated legacy/OAuth recovery and the synthetic three-client import live in `test/e2e/persistence-http-liveness.test.ts`.++- `src/core/persistence/effect-facts.ts` + `page-advisories.ts` — bounded writer-lint/facts-backstop outbox. Eligibility, anti-loop, selected configuration, original/current grants and source/page revision guards precede scheduling. Page publication records the effect; job insertion and completion use its stable idempotency key. Managed backstop retains the committed original page request as the facts-absorb job authority, including OAuth/stdio origin; no fabricated CLI authority or blanket managed skip. Legacy unsupported raw queue/fence paths remain refused. Tests: `test/persistence-facts-backstop.test.ts`, `test/managed-facts-backstop.test.ts`.++- `src/core/persistence/effect-recovery-scan.ts` — bounded owner-scoped recovery selection rotates through durable effect IDs even when an earlier root has no available native lock, and wraps to retry prior roots. It never changes recovery authority or releases reservations. `test/persistence-effect-recovery-fairness.test.ts` holds two real native roots, recovers a later mirror, then verifies wraparound cleanup and exact counters on both engines.++- `src/core/persistence/native-lock.ts` + `native/locks/` — lazy portable Node-API v3 kernel locks (`flock` / `LockFileEx`) with opaque handles, retained stable lock files, cancellable asynchronous waiting and fail-closed capability errors. Eight vendored prebuilds support script-disabled source installs; pinned Zig recipes and source/artifact hashes live in `scripts/native/`. Actual competing-process, crash-handoff and compiled-executable tests run across eight platform/architecture targets and Bun 1.3.11 / 1.3.13 / 1.4.2. The compiled smoke waits for child exit before cleanup; `scripts/native/compiled-smoke-cleanup.ts` bounds retries to transient Windows `EBUSY` errors, with persistent and permission failures pinned by `test/scripts/native-compiled-cleanup.test.ts`. Windows-only `windows-ipc.h` supplies opaque Global mutex claims (same-thread recursion refused, abandoned owner handoff) and exact-handle stale AF_UNIX deletion after a verified reparse tag under a retained binding claim. CNG hashing and native casing make pipe identities independent of homes and logon sessions. Build and ownership contract: `native/locks/README.md`.++- `src/core/persistence/page-input.ts` — freezes scoped subagent type normalization at durable admission, after existing-request replay. An explicit undeclared model-authored type becomes `note` with `legacy_type` retained using the then-active schema pack; a replay keeps its original normalized payload when the pack changes. Caller intent remains unchanged for idempotency checks. Raw input size is checked before normalization and malformed Markdown is left to the importer’s sanitized error contract. `test/brain-allowlist.serial.test.ts` pins changed-pack replay, raw-size refusal, and private parse-error redaction.++- `src/core/persistence/params.ts` — runtime-leaf mutation parameter and receipt schemas shared with the frozen verb registry. Its operation-contract import is type-only; runtime validators live in separate modules to avoid a registry initialization cycle. `preconditions.ts` validates UUID/revision/force syntax. `purge-params.ts` validates local-only purge shape/trust before admission and publication, keeping purge diagnostics out of generic precondition imports and unrelated command flag scans. `test/persistence-cold-import.test.ts` loads each validator/contract/registry entry in a fresh process and preserves schema and typed-error identity.++- `src/core/persistence/{effect-schema,effect-model,effect-journal,effect-recovery,effect-git,effects}.ts` — bounded postcommit outbox (migration 155). Canonical publication atomically queues Git and embedding work; withdrawals queue three versioned, bounded exact-page manifests with durable slug cursors. `effect-targets.ts` converts legacy source scans with complete bounded discovery while retaining each cursor; ambiguous or over-capacity legacy intent stays pending. Older workers must be quiesced before rollout. Independent mirror recovery reserves capacity before file effects, finishes forward without changing revision or receipt, and blocks only its worktree until reconciled. Git holds the native root lock, disables hooks, uses literal pathspecs and target-only commits, and pushes without pull/rebase. A Git effect for a declared db_only page completes as skipped (`reason: db_only`), keeping its gitignored cache file out of Git. A Git or withdrawal target parks after five consecutive execution failures (`data.target_failures` for `data.failing_target`, reset when the target advances or a different target fails; shutdown cancellation, contention, dependency waits (including recovery-capacity waits) and transient database failures do not count): a scan records it in `data.parked` and moves on, a single-target effect or a failure outside any target parks the whole effect, and an effect with parked targets finishes as `failed`/`targets_parked`, never committed. Migration 170 indexes parked effects for the `parked_effects` doctor check. `retryParkedEffects` (the `retry-effects` admin path) previews parked targets or authorizes one more attempt per target (`data.retry_slugs`, visited before the cursor); tests: `persistence-effect-parking.test.ts`. Old targets resolve under the same hash/confinement checks without changing frozen data; ambiguous absent spellings refuse after scoped staged/unstaged deletion checks. Embedding runs outside transactions/OS locks and installs with projection CAS. Receipt helpers return only public effect state/reason/push. Consumer shutdown aborts providers and awaits workers; receipt compaction is bounded. Tests: `persistence-effects.test.ts`, `persistence-git-publication.test.ts`, `persistence-publication-native.serial.test.ts`. Embedding completion checks active column/vector, embedded stamp, text hash, model and page signature; partial work sends only stale chunks and preserves valid siblings. A partial synopsis rebuild completes before title demotion. Provider timeouts use the gateway budget, five durable page claims/backoff, execution-token CAS after provider work and atomic vector/stamp/effect completion. Keyless work skips cleanly. `retry-effects` is an explicit one-shot failed-effect allowance; current vectors reconcile provider-free without changing canonical receipts.++- `src/core/persistence/native-file-target.ts` — shared preparation/Git execution spelling resolution. Native directory-entry inode/device identity proves aliases; no global case folding or separator rewrite. Missing suffixes retain exact spelling, descendant symlinks and ambiguous aliases refuse, and physical root identity is rechecked. Exact POSIX case-distinct names and literal backslashes remain distinct.++- `src/core/persistence/{ipc,local-client}.ts` — dedicated local persistence socket and engine-free CLI delegation. The narrow protocol carries a durable brain UUID, existing local writer registration, client source/cwd, and one request UUID; the production provider verifies current authority and dispatches through operations. Max frame 32 MiB (five-million-byte content even with JSON escaping), eight connections/in-flight dispatches, incomplete-frame timeout 15s. Lost responses preserve the original request ID with unknown submission state and never automatically replay or open another engine. Brain/mount routing precedes lock inspection; owner-side `resolveSourceId(..., { skipLocalSignals: true })` prevents serve env/dotfiles from overriding client routing. `bindResolveIpcForServe` accepts the provider as its third argument and closes the dedicated listener with hook IPC. Tests: `test/persistence-ipc.test.ts`, `test/persistence-local-client.test.ts`, `test/resolve-ipc-binding.test.ts`.++- `src/core/persistence/{schema,model,journal,authority,identity,ownership,coordinator,consumer,service,page-mutations,page-prepare,source-storage,control,context,digest,prepared-import}.ts` — dedicated durable mutation admission and permanent principal-scoped replay IDs, atomic quota reservations, registered canonical worktree ownership, native lock publication, conditional file recovery, and coherent receipt completion. Recovery presence blocks its whole worktree even when the receipt is terminal; admission and publication both enforce the fence. Migration 159 adds a partial worktree/sequence recovery index so permanent receipt retention does not turn the fence into a history scan. Canonical file preparation honors a recorded source path or contained absolute capture file URI within the registered owner root (relative or host-only `file://` URIs are absent); symlink confinement and coherent snapshot checks still apply. A slug under a `storage.db_only` dir declared in `gbrain.yml` (matched case-insensitively, derive-phase defaults excluded) publishes database-only when a live page's file is absent (the case that otherwise refuses as an uncoordinated removal), with receipt `write_through.skipped: db_only`; new pages, tombstones, missing-file-tolerant callers and present cache files keep the full file treatment and never read `gbrain.yml`. `gbrain.yml` is read from the source root, like doctor, export and backup, not the git root `manageGitignore` uses, which differs for a monorepo-subdir source. `source-storage.ts` caches the parsed file per version and logs an invalid one (unreadable, overlapping tiers, db_only declared in syntax that resolves nothing) once; that missing-file refusal then reports `storage_error`, and the Git effect treats the page as not db_only. The drift guard applies the import rule for a file without an explicit `type:` (the stored type stands) and compares titles trimmed, as the parser reads them; a real drift refuses with `detail: file_database_drift` and a filled `sources reconcile` command. The first write that binds an origin in a Git-subdirectory source with no slug-root pin pins the inferred mode in its publication transaction (a concurrent different pin refuses with `revision_conflict`), so later pages cannot flip the inference. A new page captured from a file inside the source (`capture_path`, resolved from the trusted CLI `local_file` in `page-mutations`, only when sync would give that file the capture slug under the source's slug-root mode) publishes to that file when its bytes are exactly the captured input; otherwise capture records `source_uri: cli-file`, never a host path. `acquireWorktree(binding, waitMs, signal, engine)` re-stamps a device-only physical-root change under the native lock (see `physical-root.ts`); without an engine, or when birth time is zero, it refuses with `detail: physical_root_device_changed` and the filled self-transfer commands. Version snapshots retain nullable `is_deleted`: new snapshots restore recorded deletion state atomically with content, tags, files and receipts; legacy NULL preserves current deletion state. Canonical no-op detection compares deletion state as well as content. Page replacement preconditions are checked before no-op detection; providers prepare outside publication transactions; recovery never restores unexpected bytes. Local registrations retain immutable CLI/stdio trust lanes and hashed credentials; accepted authority is intersected with current grants. `limits.ts` reads every `persistence.limits.*` cap and `persistence.receipt_retention_days` (default 30) from the database config table (`JOURNAL_CONFIG_KEYS`, registered for `gbrain config set`; malformed values are rejected at set time). Cumulative defaults (250,000 lifetime IDs and 1.5 GiB receipt bytes per principal, 8 GiB brain receipt bytes) cover 600 admissions a day for a year; each admission reserves at least 16 KiB and a compacted receipt keeps about 4 KiB. A cumulative `queue_capacity` refusal names its key in `detail` and suggests a `gbrain config set` value covering one more year at the recent admission rate (`oneYearCapacity`). Compaction filters out receipts with unfinished effects before its batch limit. `test/persistence-journal.test.ts` exercises real PGLite and optional guarded Postgres admission, cancellation, compaction, conflict and publication recovery; `test/persistence-capacity.test.ts` covers retention, the compaction filter, capacity hints and default sizing.++- `src/core/persistence/{semantic,semantic-pages}.ts` — revision-bound semantic tag/timeline merges through the journal. Supported merges reprepare against a newer snapshot; exact timeline replay leaves canonical bytes, revision, versions and structured rows unchanged. The public timeline handler resolves durable replay before page-existence preflight, retaining original outcomes after page purge or recreation; fresh writes preserve same-source diagnostics. `page-state/projections.ts` completes sanitized text and page search vectors together, and installs delayed embeddings with UPDATE-only revision/chunk/text/index-context checks. New vectors receive the full provider:model captured before provider execution, and a runtime model switch invalidates the prepared indexing context. Metadata updates preserve the sanitized vector. Tests: `persistence-semantic-pages.test.ts`, `page-projection-concurrency.test.ts`.++- `src/core/persistence/{source-lifecycle,managed-sources,topology-schema,topology-locks,topology-receipts,topology-clone,topology-clone-model,topology-filesystem,topology-recovery}.ts` — migration 157 coordinates source add/claim/archive/restore/remove/purge/rebind/reclone. Native root locks precede topology/source/grant/counter/request guards; a shared root advances every membership and permanently conflicts accepted old-topology requests. Withdrawal mirrors and running publication must settle first. Administrative UUIDs share the page journal's principal-scoped conflict domain and permanent capacity counters. Directory replacement reserves the configured recovery budget before provider/staging work, records a verified manifest and physical identity, and recovers only known bytes; clone failure retains the original checkout and a replayable failure receipt. Rebinding accepts a fresh candidate with exactly matching canonical content, including deletions. Old root refusal records remain. Metadata deletion retains local storage. Restart recovery rotates a bounded root scan so one conflict cannot starve other roots. Tests: `test/persistence-source-lifecycle.test.ts` on PGLite and guarded isolated Postgres.++- `src/core/persistence/{types,params,preconditions,verb-errors}.ts` — public mutation receipt states, error reasons and revision/idempotency parameter contracts. Receipt serialization explicitly selects public fields; queued content and execution credentials stay internal. `frozenVerbWriteError` uses MEMORY_VERBS v1's existing error enum with additive `write_request`/`write_error`; `committedVerbOutcome` refuses pending or failed receipts. `OperationError` and the thin MCP client preserve this metadata, including when a timeout races an already-received receipt. The registry-safe parameter/schema leaf never imports operation values. Pinned by `test/persistence-write-contracts.test.ts`, `test/mcp-client-hardening.test.ts` and a real HTTP envelope in `test/mcp-client.test.ts`.diff --git a/docs/architecture/key-files/core-search-1.md b/docs/architecture/key-files/core-search-1.mdindex 6720529b27..aef89f3d14 100644--- a/docs/architecture/key-files/core-search-1.md+++ b/docs/architecture/key-files/core-search-1.md@@ -49,7 +49,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/search/modes-report.ts` — `buildModesReport(engine)` → `SearchModesReport` (`schema_version: 2`), the read-only dashboard behind `gbrain search modes` and the `search_modes` MCP op: `active_mode` + validity, the per-knob `resolved` attribution (`attributeKnob` over `KNOB_DESCRIPTIONS`, including the five `reranker_*` knobs), the three frozen `bundles`, `config_keys`, and `reranker_readiness` — `{model, enabled, ready, required_key, key_present, self_hosted, fix}` from `rerankerReadinessForEngine` + `describeRerankerFix` (a thrown readiness check still yields a `ready: false` verdict whose `fix` says to run `gbrain doctor`; the block never vanishes silently). `redactReadinessForRemote(report)` is what the `search_modes` op returns when `ctx.remote !== false`: `required_key`, `key_present` and `fix` are dropped and `self_hosted` is forced false — which env vars exist on the host is fingerprinting data and the fix names them; `ready` stays because it is observable anyway (reranked results carry `rerank_score`). `src/commands/search.ts:formatModesText` renders the runtime `Reranker:` line (`off (resolved) — …` / `<model> (enabled) — <KEY> present` / `<model> (enabled but NOT running) — <fix>`) and a per-bundle `reranker=… topNIn=… autocut=…` line. Pinned by `test/modes-report-reranker.test.ts`. The CLI dashboard leads with command-specific expansion: `query` is on in every mode unless explicitly disabled, while `search` is off. It discloses provider prerequisites/text flow and distinguishes retained bundle configuration from effective command behavior.-- `src/core/search/private-visibility.ts` — shared page-visibility resolver and SQL predicates. Explicit local trust disables page filtering; operator env/config opt-outs retain their existing semantics and failed config reads enforce privacy. `privatePagesFilterFragment` authorizes concrete page rows; link origins and timeline projections use independent ID-based predicates. Legacy slug-set helpers are for name enumeration, never authorization of data from another row/source. `ops/context.ts:readPolicyOpts` combines canonical source precedence, resolved privacy and holder permissions. Both engines filter content/history/graph/identity/analytics before limits or aggregation; current and historical visibility are checked independently while page privacy is enforced. Semantic response caching remains disabled, so visibility-key folding alone never authorizes reuse.+- `src/core/search/private-visibility.ts` — shared page-visibility resolver and SQL predicates. Explicit local trust disables page filtering; operator env/config opt-outs retain their existing semantics and failed config reads enforce privacy. `privatePagesFilterFragment` authorizes concrete page rows and `isPrivatePage` is its row-side twin: explicit `private` hides a page, absent visibility is world for ordinary pages and private for extracted atoms (`type = 'atom'`) and synthesized concepts (`type = 'concept'` with `synthesized_by`), because their origin may be a private page or transcript. The page predicate also follows derived origins: an atom whose `source_slug` page is explicitly private, and a synthesized concept with a private input atom (or an input whose origin is private) over `concept-provenance` edges, are private whatever their own field says, so a later private flip of an origin reaches derived pages before any repair. `privateSnapshotFilterFragment` is the same rule on a row's own frontmatter for `page_versions`. `effectiveVisibility(origin)` (transcript or missing origin private, page origin per the read rule) and `strictestVisibility` are used by both `extract_atoms` paths, concept synthesis and `gbrain repair visibility`. Remote publication rechecks (`persistence/page-visibility.ts`) and the alias-inject recheck in `hybrid.ts` use the same rule. Tests: `test/private-visibility.test.ts`, `test/derived-page-visibility.test.ts` (PGLite and Postgres); link origins and timeline projections use independent ID-based predicates. Legacy slug-set helpers are for name enumeration, never authorization of data from another row/source. `ops/context.ts:readPolicyOpts` combines canonical source precedence, resolved privacy and holder permissions. Both engines filter content/history/graph/identity/analytics before limits or aggregation; current and historical visibility are checked independently while page privacy is enforced. Semantic response caching remains disabled, so visibility-key folding alone never authorizes reuse.- `src/core/search/projection-readiness.ts` — one scoped EXISTS probe for NULL/mismatched text revisions. Excludes hidden, archived, deleted and quarantined rows; returns ready, projection_pending or unknown without identifiers or counts. Shared by search metadata, doctor and code readiness.diff --git a/docs/architecture/key-files/core-search-2.md b/docs/architecture/key-files/core-search-2.mdindex d284a624e8..2dad45da35 100644--- a/docs/architecture/key-files/core-search-2.md+++ b/docs/architecture/key-files/core-search-2.md@@ -7,7 +7,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/search/return-policy.ts` (default OFF) — intent-aware adaptive return-sizing. Pure, dependency-light module that trims the final ranked candidate set to an intent-driven cap instead of returning the full top-K. `entity` intent gets a tight cap; `temporal`/`event`/`general` get a recall-preserving cap (`concept` is coerced to `general` by `hybrid.ts` before the call — concept queries want breadth). A `minKeep` failsafe (≥1) guarantees a human never gets a silent blank when candidates exist. WHY a cap, not a score-cliff detector: PrecisionMemBench instrumentation (gbrain-evals) measured the rank1→rank2 RRF gap is ~identical whether rank-1 is correct (0.602) or wrong (0.569) — mechanical decay, not a separatrix; rank-1 is right in 94% of single-answer cases, so "return a tight set" is the whole win and cliff-cutting just adds noise. Exports `AdaptiveReturnConfig`, `DEFAULT_ADAPTIVE_RETURN` (frozen: `enabled=false`, `entityMax=2`, `otherMax=6`, `minKeep=1`), `AdaptiveReturnDecision` (`{applied, intent, cap, kept, total}`), `AdaptiveReturnInput` (`boolean | Partial<AdaptiveReturnConfig> | undefined`), `adaptiveReturnFromConfig(cfg)`, `resolveAdaptiveReturn(perCall, fromConfig)` (defaults → config → per-call merge), `adaptiveReturnEnabled(...)` (cache-skip gate check), `applyAdaptiveReturn(results, intent, cfg)` (the trim). Config knobs (DB or file plane): `search.adaptive_return` (master switch), `search.adaptive_return_entity_max`, `search.adaptive_return_other_max`, `search.adaptive_return_min_keep` (each clamped ≥1). Wired into `hybridSearch` AFTER `applyReranker`, BEFORE the `limit` slice, and ONLY on the first page (`offset===0`) — paginating a confidence-gated set is incoherent, so paginated calls fall through to the fixed limit. Stamps the decision onto `HybridSearchMeta.adaptive_return` for `gbrain search --explain`. `hybridSearchCached` SKIPS the cache when the gate is on (a trimmed set must not be served to a gate-off lookup and vice versa). `SearchOpts.adaptiveReturn` + `HybridSearchMeta.adaptive_return` declared in `src/core/types.ts`. Agent-facing: the `query` op (`src/core/operations.ts`) exposes an `adaptive_return` boolean param whose description instructs the agent WHEN to set it (single-answer → on; breadth/exploration → off; pass `limit:1` for a hard single-answer cap), threaded into `hybridSearchCached` — end users never touch the config knob; their agent decides per query (same pattern as `salience`/`recency`). Pinned by `test/search/return-policy.test.ts` (mechanism) + `test/search/query-op-adaptive-return.test.ts` (agent surface: param exists + description teaches both directions + the never-empty contract).-- `src/core/search/safe-chunks.ts` — shared current-revision and remote safe-chunk predicates. `currentTextProjectionFilter` emits `(text_projection_revision = knowledge_revision) IS TRUE`, preserving NULL exclusion while allowing expression statistics to guide the planner. Visibility and revision predicates stay inside candidate selection. Body/chunk changes invalidate the safe index until a guarded rebuild.+- `src/core/search/safe-chunks.ts` — shared current-revision and remote safe-chunk predicates. `currentTextProjectionFilter` emits `(text_projection_revision = knowledge_revision) IS TRUE`, preserving NULL exclusion while allowing expression statistics to guide the planner. Visibility and revision predicates stay inside candidate selection. Body/chunk changes invalidate the safe index until a guarded rebuild. `belowSafeChunkFence` is the page-level predicate shared by the importers' unchanged-content re-seal and the drain.- `src/core/search/source-boost.ts` — Source-type boost map keyed by slug prefix. `DEFAULT_SOURCE_BOOSTS` (originals/ 1.5, concepts/ 1.3, writing/ 1.4, people/companies/deals/ 1.2, daily/ 0.8, media/x/ 0.7, <fork>/chat/ 0.5, archive/ 0.5, extracts/ 0.3) and `DEFAULT_HARD_EXCLUDES` (test/, attachments/, .raw/). `archive/` is DEMOTED (findable, ranked below curated), not hard-excluded — archive holds high-signal history users expect to retrieve; the demote is a prior at the SQL/fusion layer and the cross-encoder reranker can still promote a strongly-matching archive page. `parseSourceBoostEnv`/`parseHardExcludesEnv` parse comma-separated `prefix:factor` pairs from `GBRAIN_SOURCE_BOOST`/`GBRAIN_SEARCH_EXCLUDE`. `resolveBoostMap` and `resolveHardExcludes` merge defaults + env + caller `SearchOpts.exclude_slug_prefixes`/`include_slug_prefixes`. The surviving exclude policy is auditable via the `hidden_by_search_policy` doctor check (`src/commands/doctor.ts`, local + remote paths) which counts chunked pages withheld per active exclude prefix, reusing `resolveHardExcludes` + `buildVisibilityClause` + the exported `escapeLikePattern`.diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.mdindex b9a2ffa5a3..7ac569d09c 100644--- a/docs/architecture/key-files/core-services-2.md+++ b/docs/architecture/key-files/core-services-2.md@@ -1,7 +1,5 @@# Key files: Core Services (2/3)-- `src/core/persistence/connector-google-receipts.ts` — the managed Google attachment-repair preparer checks account/thread/message ownership from the current canonical snapshot, changes only the owned receipt frontmatter field, and installs provider-free text projections under the existing source-before-page publication locks. Page identity/revision, current authorization, source incarnation and file recovery guards remain mandatory; body, unrelated frontmatter, tags and the withdrawal ledger are preserved. It schedules no embeddings, loop detection or fact extraction. `connector-sync.ts` admits this narrow mutation and banks its committed receipts through the existing managed connector checkpoints.-[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.@@ -37,56 +35,18 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/ops/raw-data.ts` — `put_raw_data` / `get_raw_data`. `get_raw_data` follows the page soft-delete (a tombstoned page reads as `[]`, `restore_page` brings the rows back; there is no remote `include_deleted` param — `get_page include_deleted: true` verifies the tombstone) and, per #4352, a `visibility: private` page's raw data reads exactly like a missing page's for untrusted callers. Scope comes from `readPolicyOpts(ctx)`, never from MCP parameters.-- `src/core/ops/search.ts` — the search-domain op module (`search`, `query`, `search_stats`, `search_modes`, `search_tune`, `cache_stats`). `query` is the hybrid entry (`hybridSearchCached`) plus two non-hybrid legs that share ONE effective-row-contract helper, `resolveEffectiveLimit(ctx, p)`: an explicit `limit` wins, otherwise the mode-derived `searchLimit` resolved through the same trust-gated chain `hybridSearch` uses (`resolvePerCallMode` ignores a remote caller's `mode`, so a remote client cannot select the tokenmax row count); the config reads run lazily on those paths only. The legs: the image-similarity branch (`embedding_image` vector search, `test/query-image-mode-limit.serial.test.ts`) and the CRAG escalation slice — when `search.crag_escalation` is on and `shouldEscalateRetrieval` (`src/core/search/crag.ts`) says the first pass graded `weak`, was not already escalated, AND did not already run with the caller's expansion on (`callerExpanded`), the op re-runs once at `limit: max(effectiveLimit, 50)` with expansion + relational on and autocut off, keeping the better-graded run. `buildRetrievalResponseMeta(ctx, scope, …)` is the ONE producer of the `retrieval` response-meta channel (keyword-only path included): when a remote caller's result is empty and `hasUnsealedPagesInScope` finds markdown pages in scope below the safe-chunk index version (sargable `chunker_version < SAFE_FENCE_CHUNKER_VERSION` LIMIT 1 probe served by `pages_chunker_version_idx` as an Index Cond — NOT the COALESCE `safeChunksFilter` form, which the partial btree cannot serve and which walked every markdown page on a sealed brain; pinned by `test/search-safe-index-probe.test.ts`; fail-open; retains source, private, quarantine and live-page policy), it appends the `safe_index_pending` degraded stage so the MCP empty-result block names the pending `gbrain reindex --markdown` instead of a clean miss; the withholding itself is unchanged. Empty and nonempty replies also carry projection_readiness, with projection_pending/projection_status_unknown degradation when appropriate. Vector candidate incompleteness and scoped pool details survive the public CLI/MCP serialization boundary; public type filters constrain the current-projection probe. Retrieval output copies and sanitizes result/metadata after grading and capture using the canonical scanner, before snippet truncation; internal pipeline/capture remains unredacted. The CLI formatter repeats this on JSON, explain and human output.+- `src/core/ops/search.ts` — the search-domain op module (`search`, `query`, `search_stats`, `search_modes`, `search_tune`, `cache_stats`). `query` is the hybrid entry (`hybridSearchCached`) plus two non-hybrid legs that share ONE effective-row-contract helper, `resolveEffectiveLimit(ctx, p)`: an explicit `limit` wins, otherwise the mode-derived `searchLimit` resolved through the same trust-gated chain `hybridSearch` uses (`resolvePerCallMode` ignores a remote caller's `mode`, so a remote client cannot select the tokenmax row count); the config reads run lazily on those paths only. The legs: the image-similarity branch (`embedding_image` vector search, `test/query-image-mode-limit.serial.test.ts`) and the CRAG escalation slice — when `search.crag_escalation` is on and `shouldEscalateRetrieval` (`src/core/search/crag.ts`) says the first pass graded `weak`, was not already escalated, AND did not already run with the caller's expansion on (`callerExpanded`), the op re-runs once at `limit: max(effectiveLimit, 50)` with expansion + relational on and autocut off, keeping the better-graded run. `buildRetrievalResponseMeta(ctx, scope, …)` is the ONE producer of the `retrieval` response-meta channel (keyword-only path included): when a remote caller's scope holds pages of any kind below the safe-chunk index version (`hasUnsealedPagesInScope`: sargable `chunker_version < SAFE_FENCE_CHUNKER_VERSION` LIMIT 1 probe served by the unsealed-only partial `pages_safe_chunk_pending_idx` — NOT the COALESCE `safeChunksFilter` form; pinned by `test/search-safe-index-probe.test.ts`; fail-open; retains source, private, quarantine and live-page policy), it appends the `safe_index_pending` degraded stage to empty and partial results alike, so neither reads as a clean or complete answer; the drain is `gbrain repair safe-chunks`. The withholding itself is unchanged. Empty and nonempty replies also carry projection_readiness, with projection_pending/projection_status_unknown degradation when appropriate. Vector candidate incompleteness and scoped pool details survive the public CLI/MCP serialization boundary; public type filters constrain the current-projection probe. Retrieval output copies and sanitizes result/metadata after grading and capture using the canonical scanner, before snippet truncation; internal pipeline/capture remains unredacted. The CLI formatter repeats this on JSON, explain and human output.- `src/core/ops/sources.ts` — `sources_remove` is confined to the caller's WRITE authority via `assertSourceInCallerWriteScope(ctx, id)` (context.ts): an untrusted caller may hard-remove only its own write source; a federated read grant naming a source does not make it removable; any other id answers `OperationError('not_found', 'Unknown source: <id>')`, byte-identical to a nonexistent source so the error is not an existence oracle. `sources_status` keeps the read-scope helper (`assertSourceInCallerScope`), so a federated grant can still diagnose a source it cannot remove. Trusted local CLI keeps the full operator view. Over HTTP every client carries a write source (registration default `default`) and its own `oauth_clients.source_id` row FK-RESTRICTs removing that source, so hard removal is effectively an operator action (`gbrain sources remove`); a source a remote `sources_admin` caller just created via `sources_add` stays outside its authority until the operator rescopes the client. There is no `sources_archive` op — archive lives in the CLI (`gbrain sources archive`). Pinned by `test/sources-mcp.test.ts` (federated-read-only id → not_found while status still answers; write-source id → removed; unbound → any; local → any; `remote: undefined` fail-closed) and `test/e2e/sources-remote-mcp.test.ts` (real server: not_found before AND after a read-grant widen; operator CLI completes; rescoping `--source` moves the authority).- `src/core/page-state/` — Canonical page concurrency foundation shared by both engines. `schema.ts` (migration 150) adds source incarnation UUIDs, logical page revisions, text-projection revisions, and persistent guards for absent pages. `guards.ts` locks sorted sources then page identities in an existing transaction; callers lock sources before authority/request/fact rows. `snapshot.ts` reads page/tags/withdrawals in one MVCC statement and applies withdrawals using database-normalized text. `transactions.ts` makes helper transaction APIs compose through savepoints. `versions.ts` records the complete canonical snapshot; `rename-alias.ts` records `slug_aliases(old -> new)` inside both engines' `updateSlug` transaction, repoints aliases that named the old slug and drops one spelled like the new slug (`test/rename-slug-alias.test.ts`); `materialize.ts` persists only verified canonical overlay bytes without another logical revision. `types.ts` defines revision preconditions: missing revision is create-only, explicit force overwrites. Plain legacy `putPage` calls keep compatibility until their owning operation adopts the managed write protocol. `projection-schema.ts` (migration 153) invalidates unverified prior projections once and queues durable work; `projections.ts` rebuilds Markdown without a worktree/provider and installs only matching canonical revisions. Embedding installs also compare exact chunk identities/text. Source importers seal code/image projections; all read arms hide unsealed projections.-- `src/core/page-state/projections.ts` — captures canonical revision, source incarnation, page identity, the complete raw chunk inventory and resolved indexing inputs before preparing derived work. Embedding reads require a current text seal; healing/rebuild capture can explicitly include unsealed pages. Projection installation compares its originating seal, chunk identities/text/source/completion state, chunker version and indexing context (including stored corpus generation) under the page guard before replacing any row. A same-revision re-chunk may replace the snapshot it actually captured; a delayed older installation cannot discard newer chunks or vectors. Rebuild also rechecks its queued job before capture so a completed job from an old listing stays completed. Chunkless healing sanitizes complete body/timeline fences before splitting, preserving withdrawn history in direct page reads while excluding it from retrieval. Tests: `page-projection-origin.test.ts`, `page-projection-vector-preservation.test.ts` (PGLite and isolated Postgres), `embed-stale-chunkless-pages.serial.test.ts` (public healing entry). Shared `markdown-chunks.ts` and `code-chunks.ts` preserve fenced code and source-language metadata. Recovery preserves compatible legacy NULL-hash vectors without stamping provenance; non-NULL hash, model, context or chunk-identity drift still invalidates them. It replaces outgoing code edges without deleting incoming edges to retained chunks and clears backfill watermarks. Failed jobs rotate with a retained diagnostic; successful drain refreshes planner statistics.+- `src/core/page-state/projections.ts` — captures canonical revision, source incarnation, page identity, the complete raw chunk inventory and resolved indexing inputs before preparing derived work. Embedding reads require a current text seal; healing/rebuild capture can explicitly include unsealed pages. Projection installation compares its originating seal, chunk identities/text/source/completion state, chunker version and indexing context (including stored corpus generation) under the page guard before replacing any row. A same-revision re-chunk may replace the snapshot it actually captured; a delayed older installation cannot discard newer chunks or vectors. Rebuild also rechecks its queued job before capture so a completed job from an old listing stays completed. Chunkless healing sanitizes complete body/timeline fences before splitting, preserving withdrawn history in direct page reads while excluding it from retrieval. Tests: `page-projection-origin.test.ts`, `page-projection-vector-preservation.test.ts` (PGLite and isolated Postgres), `embed-stale-chunkless-pages.serial.test.ts` (public healing entry). Shared `markdown-chunks.ts` and `code-chunks.ts` preserve fenced code and source-language metadata. A preserving rebuild keeps a vector only when its `content_chunks.embedding_input_hash` (`src/core/embedding-input-hash.ts`) equals one recomputed from the current page, or, with no recorded hash, when the page is non-contextual and the legacy model/text-hash checks pass; a contextual chunk without provenance is nulled once. `installPageEmbeddings` records the hash in the vector's UPDATE (the plain re-embed tier by default, or the caller's `built` tier and corpus generation), and `stampEmbeddingInputs` does the same for full imports. `resealSafeChunks` re-seals a page below the safe-chunk fence from its unchanged body with no canonical write; `projectionBelowSafeFence` is its predicate. Tests add `projection-embedding-input-hash.test.ts` and `safe-chunk-reseal.test.ts`. It replaces outgoing code edges without deleting incoming edges to retained chunks and clears backfill watermarks. Failed jobs rotate with a retained diagnostic; successful drain refreshes planner statistics.Embedding-only publication also requires a live, unarchived source and nondeleted page under the same source/page row locks. A prepared vector cannot bypass a later archive, model change or withdrawal. `test/e2e/migration-wave-prepared-withdrawal.test.ts` exercises both publication orders and exact unchanged-vector refusal on both engines.- `src/core/page-state/version-types.ts` — complete canonical version contract with nullable legacy fields, re-exported by `types.ts` for existing callers. `page-state/versions.ts` records deletion, timeline, tags and originating revision in the page publication transaction.-- `src/core/persistence/activation.ts` — private CLI `sources writer activate --confirm-quiesced` boundary. Verifies native capability and active filesystem bindings, takes root locks before DB waits and rechecks topology under transaction guards before enabling managed writes. Live/young/foreign legacy leases refuse regardless of expiry; only explicitly requested `--cleanup-dead-local-locks` removes exact dead same-host holders, under the lease transaction lock. Dry-run reports candidates without deletion. Registration never silently claims a source. Tests: `test/persistence-activation.test.ts`, `test/persistence-onboarding.test.ts`. Unbound Google/GitHub API sources may activate as reviewed `connector_database` without fabricating a Git root, while bound sources still require canonical physical-root checks.--- `src/core/persistence/onboarding.ts` + `legacy-locks.ts` + `physical-root-recovery.ts` — read-only source onboarding states; exact same-host dead-lock cleanup under explicit activation opt-in; and state-bound same-owner root repair using a durable manifest and token-verified temporary stamp. `--self-transfer` prepare/accept requires separate fresh reviewed state, preserves original reservation owner evidence and refuses uncertain records. Tests: `test/persistence-onboarding.test.ts`, `test/persistence-admin-recovery.test.ts`, `test/persistence-container-preflight.test.ts`.--- `src/core/persistence/{atom-maintenance,atom-retry,facts-maintenance,facts-prepare,prepared-maintenance}.ts` — resident dispatch for durable atom publication/completion, explicit atom retry, authorized multi-entity fact-fence/backstop append and local synthesize/patterns/consolidation. Accepted output replays provider-free after restart; page/take preparers recheck original/current grants, source incarnation and revisions. Unresolved facts remain DB-only without phantom pages. Retired takes skip; semantic fact snapshots exclude derived vector/cache fields and journal quotas reject overlarge retained intent. Managed consolidation retains the explicit chronological `valid_until` writeback from the legacy consolidation phase, scoped to the accepted source/fact IDs and revalidated semantic snapshots; contradiction probes never gain supersession authority. Remote maintenance and unapproved bulk lanes remain refused. Tests: `test/managed-extract-atoms.test.ts`, `test/managed-facts-backstop.test.ts`, `test/managed-maintenance.test.ts`.--- `src/core/persistence/admission-retry.ts` — bounded retries for database-confirmed admission transaction aborts. Each retry reuses the UUID and normalized intent, rechecks guarded authority and reserves quota only on commitment. Standalone journal admission uses 100ms lock waits within the five-second retry budget to retain queue position behind short counter transactions; backoff occurs after rollback releases the connection so counter contention leaves pool capacity for reads. Ambiguous connection/commit errors are never classified as confirmed rollback. Real counter-lock, sustained-queue progress, read-capacity and after-insert rollback tests live in `test/persistence-journal.test.ts`. Withdrawal retries wrap its whole source-exclusive transaction with its existing lock policy; `admitWriteInTransaction` never backs off inside an existing unit of work. `test/persistence-withdrawal-retry.test.ts` verifies guard release, complete rollback and bounded contention.--- `src/core/persistence/connector-sync.ts` — managed Google/GitHub API ingestion uses source-scoped journaled import/deletion and `managed-connector` checkpoint CAS, not Git cursors. Unbound connectors use reviewed `connector_database` SQL-only authority; bound connectors retain canonical file publication with guarded root/hash/revision/epoch. Standalone entry, page reads and submissions authenticate the current source, local grant and canonical owner, then start the existing consumer and wait up to five seconds for retained worktree publications to settle before checking file bytes or deriving new request identity. Blocked recovery returns its retained receipt and `blocked_reason`; startup recovery precedes connector fetching, and operator edits still fail the strict file-drift check. Explicit `--retry-failed` atomically admits a new linked attempt and stores a per-base-request `managed-connector-retry` pointer, without changing the API cursor or reopening terminal receipts. Approval revalidates current and accepted authority, source/configuration/owner and idle state; concurrent approvals and pending/restarted calls reuse the already approved attempt. Receipt compaction retains the digest and authority needed for exact replay and retry. Checkpoint page-receipt lists are server-derived validation dependencies, excluded from caller identity but frozen in the first admitted intent; changed dependency lists on an unchanged sweep cannot bypass a terminal checkpoint. Durable connector cursors and retry pointers survive generic seven-day checkpoint GC, including completed sweeps needed for incremental resume. Source incarnation/configuration changes select separate cursors; obsolete state remains retained rather than automatically retiring by age. Failed pagination/identity reads cannot advance freshness or delete unconfirmed pages. Tests: `test/persistence-connectors.test.ts`, `test/persistence-connector-retry.test.ts` and `test/helpers/connector-restart.ts` cover synthetic public sync entry in fresh processes, actual SIGKILL between file publication and DB commit, blocked recovery, zero-fetch authorization refusal, aged cursor purge/resume, real storage failures, compacted retries, checkpoint dependencies, atomic approval/lost acknowledgement and concurrent paused-owner replay on PGLite and disposable Postgres.--- `src/core/persistence/consumer.ts` — resident canonical-write consumer with retained wake-ups, root-scoped retry backoff and locked-row-skipping expired-claim sweeps. Root refresh, recovery scan, sweep and capacity-marking SQL use cooperative five-second cancellation; failure never admits work under stale confinement. Cold direct initialization and queued transactions remain observed and awaited through shutdown. Recognized cancellation owned by the consumer's stop reason is not reported as a storage failure; deadline-first cancellation and unrelated storage errors remain visible. Ordinary put-page/remember preparation has a cooperative 30-second deadline; abort-ignoring work remains tracked, and late preparation cannot publish. Publication and shutdown retain the token/native-lock/recovery barriers. Trusted status exposes sampled process-local phases and attempts, not durable progress. Tests: `persistence-consumer-scheduling.test.ts`, `persistence-root-refresh.test.ts`, `test/e2e/persistence-phase-liveness.test.ts`.--- `src/core/persistence/health.ts` — pure advisory age/reason/action policy shared by receipts and trusted diagnostics. The nested public contract is optional, validated and explicitly allowlisted; thresholds are 30/120 seconds and polls 1/5/30 seconds. The journal batches at most 100 authorized receipts into one projected root query with a 500ms caller budget, retaining one in-flight query per engine until settlement. Database-only pending lookups use a partial source-incarnation/sequence index shared by both engines. Synchronous service reads coalesce only for the same request ID, retain at most four unresolved reads per engine until settlement, and permit cancellation only by the read's initiating waiter or shutdown. No health observation changes authority or durable state. Real authenticated legacy/OAuth recovery and the synthetic three-client import live in `test/e2e/persistence-http-liveness.test.ts`.--- `src/core/persistence/effect-facts.ts` + `page-advisories.ts` — bounded writer-lint/facts-backstop outbox. Eligibility, anti-loop, selected configuration, original/current grants and source/page revision guards precede scheduling. Page publication records the effect; job insertion and completion use its stable idempotency key. Managed backstop retains the committed original page request as the facts-absorb job authority, including OAuth/stdio origin; no fabricated CLI authority or blanket managed skip. Legacy unsupported raw queue/fence paths remain refused. Tests: `test/persistence-facts-backstop.test.ts`, `test/managed-facts-backstop.test.ts`.--- `src/core/persistence/effect-recovery-scan.ts` — bounded owner-scoped recovery selection rotates through durable effect IDs even when an earlier root has no available native lock, and wraps to retry prior roots. It never changes recovery authority or releases reservations. `test/persistence-effect-recovery-fairness.test.ts` holds two real native roots, recovers a later mirror, then verifies wraparound cleanup and exact counters on both engines.--- `src/core/persistence/native-lock.ts` + `native/locks/` — lazy portable Node-API v3 kernel locks (`flock` / `LockFileEx`) with opaque handles, retained stable lock files, cancellable asynchronous waiting and fail-closed capability errors. Eight vendored prebuilds support script-disabled source installs; pinned Zig recipes and source/artifact hashes live in `scripts/native/`. Actual competing-process, crash-handoff and compiled-executable tests run across eight platform/architecture targets and Bun 1.3.11 / 1.3.13 / 1.4.2. The compiled smoke waits for child exit before cleanup; `scripts/native/compiled-smoke-cleanup.ts` bounds retries to transient Windows `EBUSY` errors, with persistent and permission failures pinned by `test/scripts/native-compiled-cleanup.test.ts`. Windows-only `windows-ipc.h` supplies opaque Global mutex claims (same-thread recursion refused, abandoned owner handoff) and exact-handle stale AF_UNIX deletion after a verified reparse tag under a retained binding claim. CNG hashing and native casing make pipe identities independent of homes and logon sessions. Build and ownership contract: `native/locks/README.md`.--- `src/core/persistence/page-input.ts` — freezes scoped subagent type normalization at durable admission, after existing-request replay. An explicit undeclared model-authored type becomes `note` with `legacy_type` retained using the then-active schema pack; a replay keeps its original normalized payload when the pack changes. Caller intent remains unchanged for idempotency checks. Raw input size is checked before normalization and malformed Markdown is left to the importer’s sanitized error contract. `test/brain-allowlist.serial.test.ts` pins changed-pack replay, raw-size refusal, and private parse-error redaction.--- `src/core/persistence/params.ts` — runtime-leaf mutation parameter and receipt schemas shared with the frozen verb registry. Its operation-contract import is type-only; runtime validators live in separate modules to avoid a registry initialization cycle. `preconditions.ts` validates UUID/revision/force syntax. `purge-params.ts` validates local-only purge shape/trust before admission and publication, keeping purge diagnostics out of generic precondition imports and unrelated command flag scans. `test/persistence-cold-import.test.ts` loads each validator/contract/registry entry in a fresh process and preserves schema and typed-error identity.--- `src/core/persistence/{effect-schema,effect-model,effect-journal,effect-recovery,effect-git,effects}.ts` — bounded postcommit outbox (migration 155). Canonical publication atomically queues Git and embedding work; withdrawals queue three versioned, bounded exact-page manifests with durable slug cursors. `effect-targets.ts` converts legacy source scans with complete bounded discovery while retaining each cursor; ambiguous or over-capacity legacy intent stays pending. Older workers must be quiesced before rollout. Independent mirror recovery reserves capacity before file effects, finishes forward without changing revision or receipt, and blocks only its worktree until reconciled. Git holds the native root lock, disables hooks, uses literal pathspecs and target-only commits, and pushes without pull/rebase. Old targets resolve under the same hash/confinement checks without changing frozen data; ambiguous absent spellings refuse after scoped staged/unstaged deletion checks. Embedding runs outside transactions/OS locks and installs with projection CAS. Receipt helpers return only public effect state/reason/push. Consumer shutdown aborts providers and awaits workers; receipt compaction is bounded. Tests: `persistence-effects.test.ts`, `persistence-git-publication.test.ts`, `persistence-publication-native.serial.test.ts`. Embedding completion checks active column/vector, embedded stamp, text hash, model and page signature; partial work sends only stale chunks and preserves valid siblings. A partial synopsis rebuild completes before title demotion. Provider timeouts use the gateway budget, five durable page claims/backoff, execution-token CAS after provider work and atomic vector/stamp/effect completion. Keyless work skips cleanly. `retry-effects` is an explicit one-shot failed-effect allowance; current vectors reconcile provider-free without changing canonical receipts.--- `src/core/persistence/native-file-target.ts` — shared preparation/Git execution spelling resolution. Native directory-entry inode/device identity proves aliases; no global case folding or separator rewrite. Missing suffixes retain exact spelling, descendant symlinks and ambiguous aliases refuse, and physical root identity is rechecked. Exact POSIX case-distinct names and literal backslashes remain distinct.--- `src/core/persistence/{ipc,local-client}.ts` — dedicated local persistence socket and engine-free CLI delegation. The narrow protocol carries a durable brain UUID, existing local writer registration, client source/cwd, and one request UUID; the production provider verifies current authority and dispatches through operations. Max frame 32 MiB (five-million-byte content even with JSON escaping), eight connections/in-flight dispatches, incomplete-frame timeout 15s. Lost responses preserve the original request ID with unknown submission state and never automatically replay or open another engine. Brain/mount routing precedes lock inspection; owner-side `resolveSourceId(..., { skipLocalSignals: true })` prevents serve env/dotfiles from overriding client routing. `bindResolveIpcForServe` accepts the provider as its third argument and closes the dedicated listener with hook IPC. Tests: `test/persistence-ipc.test.ts`, `test/persistence-local-client.test.ts`, `test/resolve-ipc-binding.test.ts`.--- `src/core/persistence/{schema,model,journal,authority,identity,ownership,coordinator,consumer,service,page-mutations,page-prepare,control,context,digest,prepared-import}.ts` — dedicated durable mutation admission and permanent principal-scoped replay IDs, atomic quota reservations, registered canonical worktree ownership, native lock publication, conditional file recovery, and coherent receipt completion. Recovery presence blocks its whole worktree even when the receipt is terminal; admission and publication both enforce the fence. Migration 159 adds a partial worktree/sequence recovery index so permanent receipt retention does not turn the fence into a history scan. Canonical file preparation honors a recorded source path or contained capture file URI within the registered owner root; symlink confinement and coherent snapshot checks still apply. Version snapshots retain nullable `is_deleted`: new snapshots restore recorded deletion state atomically with content, tags, files and receipts; legacy NULL preserves current deletion state. Canonical no-op detection compares deletion state as well as content. Page replacement preconditions are checked before no-op detection; providers prepare outside publication transactions; recovery never restores unexpected bytes. Local registrations retain immutable CLI/stdio trust lanes and hashed credentials; accepted authority is intersected with current grants. `test/persistence-journal.test.ts` exercises real PGLite and optional guarded Postgres admission, cancellation, compaction, conflict and publication recovery.--- `src/core/persistence/{semantic,semantic-pages}.ts` — revision-bound semantic tag/timeline merges through the journal. Supported merges reprepare against a newer snapshot; exact timeline replay leaves canonical bytes, revision, versions and structured rows unchanged. The public timeline handler resolves durable replay before page-existence preflight, retaining original outcomes after page purge or recreation; fresh writes preserve same-source diagnostics. `page-state/projections.ts` completes sanitized text and page search vectors together, and installs delayed embeddings with UPDATE-only revision/chunk/text/index-context checks. New vectors receive the full provider:model captured before provider execution, and a runtime model switch invalidates the prepared indexing context. Metadata updates preserve the sanitized vector. Tests: `persistence-semantic-pages.test.ts`, `page-projection-concurrency.test.ts`.--- `src/core/persistence/{source-lifecycle,managed-sources,topology-schema,topology-locks,topology-receipts,topology-clone,topology-clone-model,topology-filesystem,topology-recovery}.ts` — migration 157 coordinates source add/claim/archive/restore/remove/purge/rebind/reclone. Native root locks precede topology/source/grant/counter/request guards; a shared root advances every membership and permanently conflicts accepted old-topology requests. Withdrawal mirrors and running publication must settle first. Administrative UUIDs share the page journal's principal-scoped conflict domain and permanent capacity counters. Directory replacement reserves the configured recovery budget before provider/staging work, records a verified manifest and physical identity, and recovers only known bytes; clone failure retains the original checkout and a replayable failure receipt. Rebinding accepts a fresh candidate with exactly matching canonical content, including deletions. Old root refusal records remain. Metadata deletion retains local storage. Restart recovery rotates a bounded root scan so one conflict cannot starve other roots. Tests: `test/persistence-source-lifecycle.test.ts` on PGLite and guarded isolated Postgres.--- `src/core/persistence/{types,params,preconditions,verb-errors}.ts` — public mutation receipt states, error reasons and revision/idempotency parameter contracts. Receipt serialization explicitly selects public fields; queued content and execution credentials stay internal. `frozenVerbWriteError` uses MEMORY_VERBS v1's existing error enum with additive `write_request`/`write_error`; `committedVerbOutcome` refuses pending or failed receipts. `OperationError` and the thin MCP client preserve this metadata, including when a timeout races an already-received receipt. The registry-safe parameter/schema leaf never imports operation values. Pinned by `test/persistence-write-contracts.test.ts`, `test/mcp-client-hardening.test.ts` and a real HTTP envelope in `test/mcp-client.test.ts`.-- `src/core/postgres-engine/` + `src/core/pglite-engine/` — narrow-deps engine module directories, mirrored in lockstep (the engine-parity discipline applies to these dirs exactly as to the façades). Each holds `facts.ts`, `takes.ts`, `code-edges.ts`, and `salience.ts`: the corresponding BrainEngine method clusters implemented as free functions over a typed deps interface (e.g. `PgliteFactsDeps`) that the engine class satisfies, so each module depends only on the narrow slice it uses. `code-edges.ts` `getCalleesOf` takes an opt-in `bareFallback` (set ONLY by the `code_callees` op + `gbrain code-callees`, never by the code_flow/code_blast BFS): a zero-row exact miss for a delimiter-free input re-keys the same UNION on `content_chunks.symbol_name` (exact, indexed, never LIKE), so the documented "bare or qualified name" contract holds for namespace/class-qualified chunks (C#/Java/Ruby/Rust, TS class methods) whose edges are emitted bare. The façade methods delegate to them via static top-level imports (the engine-live no-runtime-dynamic-import rule applies) and keep the full public surface.- `src/core/postgres-engine/forward-reference-bootstrap.ts` — `applyPostgresForwardReferenceBootstrap(conn)`: the forward-reference bootstrap for the RAW `SCHEMA_SQL` replay path (probe + patch every column/table the embedded schema blob forward-references but older brains don't have yet — single probe round-trip, idempotent, fast no-op when nothing is missing). Peeled out of `PostgresEngine` so BOTH replay entrypoints run it before the blob: `PostgresEngine.initSchema()` AND the standalone module-singleton `db.ts:initSchema()` (replaying with no bootstrap would wedge an upgrade-boundary brain on `CREATE INDEX` over a column the replayed blob forward-references). Callers MUST hold the initSchema advisory lock (key 42) on `conn` so concurrent bootstraps can't race on a transaction pooler. Mirror of `PGLiteEngine#applyForwardReferenceBootstrap` in shape — keep in sync; covered by `test/schema-bootstrap-coverage.test.ts` (PGLite A2 static check + the Postgres-blob CREATE-INDEX class-closure gate, which parses `SCHEMA_SQL` and requires every migration-added blob-indexed column to have a probe here or an explicit exemption) + `test/e2e/postgres-bootstrap.test.ts` (Postgres side, live convergence cases). Probes are column-only (nullable `ADD COLUMN`, plus `SET DEFAULT` where hardening the upgrade window needs it — `dream_verdicts.expires_at`); the owning migration stays the source of truth for backfill/constraints/indexes: on the engine path it runs right after the bootstrap under the same advisory lock, while the standalone `db.ts:initSchema` path replays the blob WITHOUT running migrations — safe because the NULL-tolerant read predicates treat pre-backfill rows as valid until the next full engine init.diff --git a/docs/architecture/key-files/core-utilities-1.md b/docs/architecture/key-files/core-utilities-1.mdindex 1acd29aa28..bcf822f404 100644--- a/docs/architecture/key-files/core-utilities-1.md+++ b/docs/architecture/key-files/core-utilities-1.md@@ -9,7 +9,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/backfill-registry.ts` — registry of idempotent data backfills. The `modality` backfill flips `modality` to `'image'` on image-asset chunks the ingest path missed; its SQL filter requires `chunk_source='image_asset'` AND `embedding_image IS NOT NULL` AND `(modality IS NULL OR modality != 'image')` — the `chunk_source` guard ensures a non-image chunk that happens to have `embedding_image` populated is never flagged. A second run finds zero rows.-- `src/core/brain-score-recommendations.ts` — pure data layer consumed by both `gbrain doctor --remediation-plan` / `--remediate` and `gbrain features`. Extraction-watermark staleness produces source-scoped `extract.stale` against database pages, including DB-only pages without a checkout; it does not imply a filesystem sync or block embedding on one. `computeRecommendations(checks, opts)` returns `Remediation[]` with stable `id`, content-hash `idempotency_key`, `severity`, `est_seconds`, `est_usd_cost`, `depends_on` (references stable ids, not check names — so plan order is reproducible). `classifyChecks(report)` triages every doctor check three-state into `remediable | human_only | blocked` (`human_only` covers RLS warnings and other human-judgment gates; `blocked` covers dependency chains where a parent check failed). `maxReachableScore(checks)` computes the ceiling for empty/under-configured brains (no entity pages → graph_coverage caps at 70; no embedding key → embedding_coverage caps at 60). Cost estimates pull from `anthropic-pricing.ts` (synthesize/patterns/consolidate) and `embedding-pricing.ts` (embed jobs). Pinned by `test/brain-score-recommendations.test.ts` (~27 cases incl. determinism, content-hash idempotency, DB-backed checkpoint provenance, three-state triage).+- `src/core/brain-score-recommendations.ts` — pure data layer consumed by both `gbrain doctor --remediation-plan` / `--remediate` and `gbrain features`. Extraction-watermark staleness produces source-scoped `extract.stale` against database pages, including DB-only pages without a checkout; it does not imply a filesystem sync or block embedding on one. `RecommendationContext.staleExtractionBlocked` (probed by `staleExtractionBlocked()` in `remediation/context.ts`, shared with autopilot) withholds `extract.stale` and classifies `links_extraction_lag` as blocked while the remediated source, or any source with stale pages in an all-source sweep, cannot load its active schema pack, so no dispatch fails every cycle. `computeRecommendations(checks, opts)` returns `Remediation[]` with stable `id`, content-hash `idempotency_key`, `severity`, `est_seconds`, `est_usd_cost`, `depends_on` (references stable ids, not check names — so plan order is reproducible). `classifyChecks(report)` triages every doctor check three-state into `remediable | human_only | blocked` (`human_only` covers RLS warnings and other human-judgment gates; `blocked` covers dependency chains where a parent check failed). `maxReachableScore(checks)` computes the ceiling for empty/under-configured brains (no entity pages → graph_coverage caps at 70; no embedding key → embedding_coverage caps at 60). Cost estimates pull from `anthropic-pricing.ts` (synthesize/patterns/consolidate) and `embedding-pricing.ts` (embed jobs). Pinned by `test/brain-score-recommendations.test.ts` (~27 cases incl. determinism, content-hash idempotency, DB-backed checkpoint provenance, three-state triage).- `src/core/cjk.ts` — Single source of truth for CJK detection. Exports `CJK_RANGES_REGEX`, `CJK_SLUG_CHARS` (character-class fragment for embedding inside other regexes), `SLUG_WORD_CHARS` + `PAGE_SLUG_SEG` (the shared slug-grammar fragments) and `SLUG_VARIATION_SELECTORS_RE` (the Mn-invisible emoji-VS16 / ideographic-IVS strip that BOTH `sync.ts:slugifySegment` and its twin `link-extraction.ts:normalizeBasename` apply, so the two grammars cannot drift on selectors), `CJK_SENTENCE_DELIMITERS` (`。!?`), `CJK_CLAUSE_DELIMITERS` (`;:,、`), `CJK_DENSITY_THRESHOLD = 0.30`, `hasCJK(s)`, `isCJKDominant(s)` (the ONE density test: CJK chars ≥ 30% of non-whitespace chars), `countCJKAwareWords(s)` (routes through `isCJKDominant` — English docs with one Japanese term stay whitespace-tokenized; Chinese-dominant docs get char-counted), and `escapeLikePattern(s)` (escapes `%`, `_`, `\\` for `ILIKE ... ESCAPE '\\'`). BMP-only ranges (Han / Hiragana / Katakana / Hangul Syllables). Consumers: `expansion.ts`, `sync.ts:slugifySegment`, `operations.ts:validatePageSlug + validateFilename`, `chunkers/recursive.ts:countWords + DELIMITERS + extractTrailingContext` (the overlap extractor branches on `isCJKDominant` so it counts the same unit `countWords` does), `pglite-engine.ts:searchKeyword + searchKeywordChunks`.diff --git a/docs/architecture/key-files/core-utilities-2.md b/docs/architecture/key-files/core-utilities-2.mdindex 9164e5d328..6f1e7d0ae9 100644--- a/docs/architecture/key-files/core-utilities-2.md+++ b/docs/architecture/key-files/core-utilities-2.md@@ -3,6 +3,7 @@[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.+- `src/core/repair/` — `gbrain repair` core. `core.ts`: `resolveRepairScope` (default every active source; prints brain and source ids), `runRepair` (dry run unless `apply`; each item is one revision-bound `put_page` with a deterministic request id (replayed while pending, a new attempt id after a terminal failure), re-decided against current state just before it is applied; a cursor in `op_checkpoints` keyed by kind + scope resumes an interrupted or `--limit` run and is cleared when a scan completes; stops before crossing 90% of the brain or principal lifetime-ID / receipt-byte caps with the `gbrain config set` value that finishes; a held writer stops with `gbrain sources writer status <source>`). `timeline.ts`: `scanTimelineHistory` (bounded id-order scan shared with the doctor) and the materialize kind. `visibility.ts`: `planVisibilityRepair`, the tighten-only atom/concept backfill (atoms from `effectiveVisibility` of their origin, concepts from the strictest input over provenance edges and atoms' `concepts:`; no-lineage concepts are counted and left alone). `safe-chunks.ts`: a `publication: 'projection'` kind (no admission, zero lifetime-ID and receipt cost, no capacity stop) that re-seals markdown and code pages below the safe-chunk fence through `resealSafeChunks`, then embeds their NULL chunks unless `--no-embed`; code pages without a recorded path and other page kinds are residuals. `safeChunkUpgradeAdvisory` is the post-upgrade line naming the drain. Tests: `test/repair-command.test.ts`, `test/derived-visibility-repair.test.ts`, `test/safe-chunk-reseal.test.ts` (PGLite and Postgres).- `src/core/rerank-audit.ts` — failure-only JSONL audit at `~/.gbrain/audit/rerank-failures-YYYY-Www.jsonl` (ISO-week rotation, mirrors `src/core/audit-slug-fallback.ts`). Exports `logRerankFailure({reason, model, query_hash, doc_count, error_summary})` + `readRecentRerankFailures(days)`. The `no_key` reason is written ONCE per process per model by the gateway itself (not per query by `applyReranker`): the provider key is absent, so calls are skipped without HTTP and results pass through unreranked; `auth` means key present but rejected. Deliberately no `logRerankSuccess`: writing once per tokenmax search is hot-path I/O churn AND success events leak query volume + timing into a local audit file. `gbrain doctor`'s `reranker_health` check (`doctor/checks/calibration.ts`) resolves enablement + model through `resolveSearchMode(loadSearchModeConfig)` — the plane search reranks with — and `rerankerReadiness` before reading the audit: readiness is evaluated against the DB-merged config plane (`loadConfigWithEngine`, so DB-plane provider keys and `provider_base_urls` self-host overrides count, exactly like the gateway the CLI configures): a brain with NO embedding provider (`isAvailable('embedding')` false on a configured gateway) is `ok` even when not ready — search runs keyword-only there and never reaches `applyReranker`, so there is nothing to fix; otherwise enabled-but-not-ready (key absent / unknown model) warns with the paste-ready fix; only audit rows for the RESOLVED model count (rows for any other model never make the live default warn or send the operator to verify the wrong key); `no_key` skip rows are informational once ready (those processes ran unreranked; a long-lived worker started before the key was added keeps skipping until restarted) and never outlive the fix as a warn; then the auth / payload / budget / transient / unknown ladders on the non-skip rows; disabled → ok (with an enable hint when the default is ready). Query text SHA-256-prefix-hashed (8 hex chars) for privacy. `GBRAIN_AUDIT_DIR` env override honored via the shared `resolveAuditDir()`.@@ -12,7 +13,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/sql-query.ts` — engine-aware tagged-template SQL adapter for OAuth/admin/auth infrastructure. `sqlQueryForEngine(engine)` returns a `SqlQuery` (`(strings, ...values) => Promise<rows[]>`) that walks the template, builds `$N` positional SQL, asserts every value is a `SqlValue` (string | number | bigint | boolean | Date | null), and routes through `engine.executeRaw(sql, params)` (Postgres via postgres.js `unsafe(sql, params)`, PGLite via `db.query(sql, params)`). Deliberately narrower than postgres.js's `sql` tag: no nested fragments, `sql.json()`, `sql.unsafe()`, `sql.begin()`, or array binding — the narrow scalar-only surface is the feature (keeps it from drifting into a partial postgres.js clone). JSONB writes go through `executeRawJsonb(engine, sql, scalarParams, jsonbParams)` which composes positional `$N::jsonb` casts and passes JS **objects** through; an object reaches the wire with the correct type oid, so executeRawJsonb is safe (verified by `test/sql-query.test.ts` on PGLite, `test/e2e/auth-permissions.test.ts:67` on Postgres). Positional binding is NOT universally immune, though: binding a `JSON.stringify(x)` **string** to a bare `$N::jsonb` via `unsafe()` double-encodes it into a jsonb string scalar on real Postgres (PGLite hides it). Fixes: pass a raw object (executeRawJsonb / `sql.json`), or cast through `$N::text::jsonb`. `scripts/check-jsonb-pattern.sh` (template grep) doesn't fire on `executeRawJsonb(...)` because it passes objects; the positional `$N::jsonb` + `JSON.stringify` form is caught by `scripts/check-jsonb-params.mjs`. Also exports `FILES_METADATA_MERGE_SQL`, the one `ON CONFLICT (storage_path)` merge fragment every files upsert (`src/commands/files.ts` x4, `src/core/ops/files.ts` `file_upload`) interpolates: it resets a non-object `files.metadata` to `{}` before the jsonb `||` merge, because `||` array-wraps a non-object left operand and would turn a legacy string-scalar row into `["{}", {...}]` that `gbrain repair-jsonb` can no longer see (pinned by `test/file-upload-fail-closed.test.ts`). Consumed by `src/commands/auth.ts`, `src/commands/serve-http.ts`, `src/core/oauth-provider.ts`, `src/commands/files.ts`, `src/mcp/http-transport.ts` so all five work uniformly against PGLite and Postgres.-- `src/core/storage-config.ts` — Storage tiering: `loadStorageConfig` reads `gbrain.yml`, normalizes deprecated keys (`git_tracked`/`supabase_only`) to canonical (`db_tracked`/`db_only`) with once-per-process deprecation warning, and runs `normalizeAndValidateStorageConfig` (auto-fixes missing trailing `/`, throws `StorageConfigError` on tier overlap). Path-segment matcher: `media/x/` does NOT match `media/xerox/foo`. Uses a dedicated parser for the `gbrain.yml` shape rather than gray-matter (broken on delimiter-less YAML). Also carries `DERIVE_PHASE_DB_ONLY_DEFAULTS` (`life/events/`, `atoms/`, `extracts/`, `dream-cycle-summaries/`) + `effectiveDbOnlyDirs` — the engine's derive-phase output prefixes treated as implicitly-declared db_only by the `undeclared_db_only_pages` doctor check but deliberately NOT merged into `loadStorageConfig` (a global merge would auto-gitignore those dirs and silently kill ingestion for brains that file-back them) — and `findDbOnlyCollisions` (pure collector-output vs db_only overlap detector shared by the `db_only_collector_collision` doctor check and sync's `manageGitignore` warning). Pinned by `test/storage-config.test.ts` + `test/doctor-silent-death-checks.test.ts`.+- `src/core/storage-config.ts` — Storage tiering: `loadStorageConfig` reads `gbrain.yml`, normalizes deprecated keys (`git_tracked`/`supabase_only`) to canonical (`db_tracked`/`db_only`) with once-per-process deprecation warning, and runs `normalizeAndValidateStorageConfig` (auto-fixes missing trailing `/`, throws `StorageConfigError` on tier overlap). Path-segment matcher: `media/x/` does NOT match `media/xerox/foo`. `isDeclaredDbOnlySlug` matches a lowercase page slug against the declared db_only dirs case-insensitively; managed persistence uses it to publish those pages database-only. `hasUnresolvedDbOnlyDeclaration` detects a db_only key line that resolved no directory (unsupported syntax such as flow-style lists; an intentionally empty `db_only: []` is an accepted false positive); the sync baseline-commit guard refuses on it, and managed persistence turns a missing-file refusal into `storage_error`. Uses a dedicated parser for the `gbrain.yml` shape rather than gray-matter (broken on delimiter-less YAML). Also carries `DERIVE_PHASE_DB_ONLY_DEFAULTS` (`life/events/`, `atoms/`, `extracts/`, `dream-cycle-summaries/`) + `effectiveDbOnlyDirs` — the engine's derive-phase output prefixes treated as implicitly-declared db_only by the `undeclared_db_only_pages` doctor check but deliberately NOT merged into `loadStorageConfig` (a global merge would auto-gitignore those dirs and silently kill ingestion for brains that file-back them) — and `findDbOnlyCollisions` (pure collector-output vs db_only overlap detector shared by the `db_only_collector_collision` doctor check and sync's `manageGitignore` warning). Pinned by `test/storage-config.test.ts` + `test/doctor-silent-death-checks.test.ts`.- `src/core/storage.ts` — Pluggable storage interface (S3, Supabase Storage, local).@@ -20,6 +21,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/surface-audit.ts` — `writeSurfaceChangeAudit(engine, audit)`: the surface-mutation audit trail. Every surface mutation (rescope CLI, `POST /admin/api/rescope-client`, `request_tools` persist) writes one typed `mcp_request_log` row — `operation='surface_change'`, params a RAW object `{actor, client_id, old, new, via}` via `executeRawJsonb` (never `JSON.stringify` into `::jsonb`). Zero new DDL; rides `idx_mcp_log_time_agent` + the retention TODO. Best-effort: a failed audit write warns to stderr, never fails the committed mutation (callers needing fail-closed semantics inspect the returned boolean). CLI-actor rows are written even though stdio ops don't otherwise log (documented exception — audit outranks the transport-logging convention). The usage reader excludes these rows from op-call stats.+- `src/core/timeline-marker.ts` — the `<!-- gbrain:materialized v1 <12-hex> -->` marker that precedes a materialized timeline bullet: `timelineKey` (the one normalization for prior-set membership, dedup, stored-row matching and marker hashes), `timelineTupleHash`, `materializedMarker`, marker-line detection and `stripMaterializedMarkers`. Both timeline extractors skip marker lines (a marker never becomes bullet or header detail) and `sanitizeRemoteBody` drops them from chunk text unless `keepMaterializedMarkers` is set (remote `get_page`/`fetch` keep them so an edit round-trips). A marker whose hash no longer matches the bullet below it marks nothing.- `src/core/transcripts.ts` — `listRecentTranscripts(engine, opts)` library reused by both the `gbrain transcripts recent` CLI and the `get_recent_transcripts` MCP op. Reads `dream.synthesize.session_corpus_dir` + `dream.synthesize.meeting_transcripts_dir` config (same as `discoverTranscripts`); walks `.txt` files within `days`; applies the `isDreamOutput` guard from `transcript-discovery.ts` (skips dream-generated files); returns `{path, date, mtime, length, summary}[]` sorted newest-first. Summary mode (default true) = first non-empty line + ~250 trailing chars; full mode caps at 100KB/file. Missing/non-existent corpus dirs return `[]`, not error. Trust gate lives in the op handler, not here: the op throws `permission_denied` for `ctx.remote === true`; this is a trusted library function used by both the gated op and the local CLI.- `src/core/types.ts` extension + `src/core/operations.ts:search` + `src/core/import-file.ts` + `src/cli.ts` + `src/core/search/telemetry.ts` — the wiring layer for the retrieval-quality stack. `SearchResult` carries `evidence`, `create_safety`, `title_match_boost`, `alias_hit` (all optional; evidence/create_safety reference the union types in `evidence.ts`). The `search` MCP op uses a cheap-hybrid path by default and accepts a per-call `mode` (conservative|balanced|tokenmax) honored ONLY for trusted/local callers (`resolvePerCallMode(ctx, ...)` — remote callers use the configured mode so a remote provider can't force tokenmax spend); every search path stamps evidence fail-soft. `importFromContent` projects frontmatter `aliases:` into `page_aliases` via `normalizeAliasList` + `engine.setPageAliases` so new + changed pages register aliases at ingest. `src/cli.ts` carries the `gbrain search diagnose` dispatch (lazy import) and reconciles the `search` CLI path with the cheap-hybrid op. `src/core/search/telemetry.ts` carries in its rollup the rank-1 base_score drift signal (sum/count + 3 coarse buckets, aggregate not per-query), surfaced via `gbrain search stats`, backed by migration v111's `search_telemetry` columns. Tests: `test/cli-search-dispatch.test.ts`, `test/search/per-call-mode.test.ts`, `test/search/telemetry-rank1.test.ts`, `test/search/title-boost-stage.test.ts`, `test/search/alias-hop.test.ts`, `test/search/evidence.test.ts`, `test/search/searchvector-maxpool.test.ts`, `test/search/pre-migration-failopen.test.ts`.diff --git a/docs/architecture/key-files/engines-1.md b/docs/architecture/key-files/engines-1.mdindex 92b92814b4..ea7fbe6f06 100644--- a/docs/architecture/key-files/engines-1.md+++ b/docs/architecture/key-files/engines-1.md@@ -31,7 +31,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/pglite-embedded-assets.ts` + `src/core/pglite-embedded-asset-paths.ts` — PGLite runtime-asset supply for every run mode (compiled binary, source checkout, bun-global install). `pglite-embedded-asset-paths.ts` is the bundler ANCHOR: five literal `with { type: 'file' }` imports of the wasm/data/extension-tarball assets via repo-relative node_modules paths (the package's `exports` map hides `./dist/*`) — keep the specifiers literal and byte-stable, an expression or indirection silently stops the bytes embedding and the compiled binary falls into the Bun-vfs ENOENT failure. `resolvePgliteAssetPaths()` in `pglite-embedded-assets.ts` is the tiered resolver: tier 1 dynamically `import()`s the anchor (the rejection under a hoisted install — bun-global upgrades dedupe `@electric-sql/pglite` to the global root, making the anchor's specifiers unresolvable — is EXPECTED and routes to tier 2, which is why the anchor is not a static import); tier 2 derives the dist dir via module resolution of `@electric-sql/pglite` (`import.meta.resolve` then `createRequire` — the SAME specifier the engine imports, so assets can never come from a different pglite copy than the loaded JS); tier 3 throws one actionable error naming everything tried, with the canonical GitHub reinstall command (never the npm-registry name, which is squatted — see the README install warning). `getEmbeddedPgliteOptions()` memoizes one build per process and hands PGLite compiled `WebAssembly.Module`s + fs-bundle Blob + materialized extension tarballs via `PGliteOptions`. Pinned by `test/pglite-embedded-assets.test.ts` + `test/pglite-hoisted-install.serial.test.ts` (real `bun add -g`-shaped hoisted layout).-- `src/core/pglite-engine.ts` — PGLite (embedded Postgres 17.5 via WASM) implementation, all BrainEngine methods. The facts/takes/code-edges/salience method clusters are implemented in narrow-deps modules under `src/core/pglite-engine/` (see the engine-module-dirs entry below); the class methods delegate to them and the façade keeps its full public surface. `listLinkSources({sourceId?, sourceIds?})` returns distinct `link_source` provenances + counts (`ORDER BY count DESC, link_source ASC NULLS LAST`; scalar + federated scoped; parity with postgres-engine.ts) powering `gbrain link-sources`. `addLinksBatch`/`addTimelineEntriesBatch`/`addTakesBatch` pass the whole batch as one JSONB document via `jsonb_to_recordset(($1::jsonb)->'rows')` (bound through `executeRawJsonb` with a `{ rows }` wrapper; rows built by the shared `src/core/batch-rows.ts` helpers, NUL-stripped), and are `batchRetry`-wrapped. `connect()` retries a failed in-memory `PGlite.create()` once, cold, only while no database is attached. The retry omits the snapshot and clears its loaded flag so `initSchema()` replays the schema. Recovery warns on stderr; exhausted recovery retains both error diagnostics. Post-open setup errors instead close the existing database, preserving close-poison and ownership rules. The doctor scratch probe is a separate disk-backed path and does not use this retry. Remaining initialization failures use the existing classifier and, for the `wasm-abort` verdict on a persistent data dir (torn WAL/checkpoint state after an unclean shutdown; it presents like a macOS WASM bug but is not one), runs in-place auto-repair via `attemptWalRepairAndRetry` (static import from `pglite-repair.ts`, per the engine-live rule; the retry create is `preservingProcessExitCode`-wrapped; success sets the public `walRepairReceipt` field + prints `buildWalRepairNotice` to stderr and returns with the lock held). The seam never throws, so every non-repaired path funnels through the single lock-release-then-throw site; repair refuses when the lock was acquired by reaping (`LockHandle.reaped` → `'possibly-live-writer'`), when disabled (`GBRAIN_PGLITE_WAL_REPAIR=off`), on layout-validation failure, or inside the post-failure cooldown. `disconnect()` awaits mandatory resident-consumer stops, closes admission on tracked query/exec/transaction handles, drains admitted statements and best-effort background work, then awaits CHECKPOINT and close before kernel release. A deadline reports `pglite_closing` while actual shutdown continues with ownership retained; a failed close poisons reconnect until process exit. The out-of-band watchdog remains available for event-loop wedges. `searchKeyword`/`searchKeywordChunks` multiply `ts_rank` by the source-factor CASE at chunk grain; `searchVector` is a two-stage CTE — inner CTE keeps `ORDER BY cc.embedding <=> vec` so HNSW stays usable, outer SELECT re-ranks by `raw_score * source_factor`, inner LIMIT scales with offset to preserve pagination. `searchTakes`/`searchTakesVector` take full `SearchOpts` and apply the standard source-scope predicates (federated `sourceIds[]` wins over scalar `sourceId`, via the joined page's `source_id`) alongside the holder allow-list — parity SQL in postgres-engine.ts; pinned by `test/e2e/think-source-isolation-pglite.test.ts`. `initSchema()` calls `applyForwardReferenceBootstrap()` BEFORE replaying SCHEMA_SQL — probes for forward-referenced state the embedded blob needs (`pages.source_id`, `links.link_source`, `links.origin_page_id`, `content_chunks.symbol_name`, `content_chunks.language`, `sources` FK target, plus `files.source_id`, `files.page_id`, `oauth_clients.source_id`, `oauth_clients.federated_read`, `sources.archived`, `sources.archived_at`, `sources.archive_expires_at`, `timeline_entries.event_page_id` — column-only, migration v121 stays the source of truth for its FK + indexes) and adds only what's missing; threads the DDL connection from `initSchema` so probes run inside the advisory-lock scope; no-op on fresh installs and current brains (this is what keeps an upgrade from wedging on a forward-referenced column). `getBrainScore` returns 100/100 with full breakdown (35/25/15/15/10) when `pageCount === 0` (vacuous truth — empty brain has no coverage problem); Pinned by `test/brain-score-breakdown.test.ts` empty-brain assertion + `test/doctor-report-remote.serial.test.ts`. `PGlite.create()` runs inside `preservingProcessExitCode`: PGLite's Emscripten runtime writes its own status into `process.exitCode` (99 at create; in-memory brains run initdb whose status lands on a later tick; the exit status at close — and assigning `undefined` cannot clear a prior value), which would otherwise silently clobber an errored op's exit 1 back to 0. The wrapper keeps the global tidy for external readers; `db.close()` stays unwrapped (its 0-write is baseline behavior test runners depend on). The CLI's exit verdict is immune either way — it lives in the gbrain-owned channel in `cli-force-exit.ts` and never reads `process.exitCode` back. Exports `classifyPgliteInitError(message): 'bunfs' | 'wasm-abort' | 'corrupt' | 'unknown'` + `buildPgliteInitErrorMessage(verdict, original, platform?, ctx?)` + `stringifyPgliteInitError(err)` + `buildWalRepairNotice(receipt)` + the `PgliteInitRepairContext` type, routing the catch-block hint by failure shape (`bunfs` matches literal `$$bunfs` OR `ENOENT[\s\S]*pglite\.data` co-occurrence, surfaces a paste-ready `bun upgrade` + Node fallback; `corrupt` — 58P01/`internal_load_library`/missing vector type, catalog corruption WAL repair can't fix — stays matched BEFORE the wasm arm and routes to `reinit-pglite`; `wasm-abort` matches the real production shapes `Aborted()`/`RuntimeError`/`unreachable` plus legacy signatures, names the corrupt-WAL root cause + the recovery ladder (`pglite-repair` → rebuild → engine switch) + what auto-repair did per `ctx` incl. the honesty-critical `failed-not-restored` arm, and links the upstream tracking issue; `unknown` is platform-gated). `stringifyPgliteInitError` also surfaces message-less Emscripten objects (`ErrnoError (errno N)`) instead of `[object Object]`. Pinned by `test/pglite-init-classifier.test.ts` + `test/pglite-wal-repair.serial.test.ts` + `test/fix-wave-structural.test.ts`. Implements `deletePages(slugs, {sourceId})` + `resolveSlugsByPaths(paths, {sourceId})` via `slug = ANY($1::text[])` array-param binding, caller-chunking primitive throwing when input exceeds `DELETE_BATCH_SIZE`, `deletePages` returns `RETURNING slug` rows so callers filter `pagesAffected` to confirmed deletes. Implements the embedding-signature stale-detection quartet — `sumStaleChunkChars({sourceId?, signature?})`, `setPageEmbeddingSignature(slug, {sourceId?, signature})`, `invalidateStaleSignatureEmbeddings({signature, sourceId?})`, widened `countStaleChunks({sourceId?, signature?})` (the `signature` opt widens via `JOIN pages p ... WHERE cc.embedding IS NULL OR (p.embedding_signature IS NOT NULL AND p.embedding_signature <> $signature)`, NULL grandfathered); parity SQL with postgres-engine.ts. PGLite-specific DDL (pgvector, pg_trgm, triggers). Engine-path helper dependencies (`retry`, ontology, recency decay) avoid dynamic `import()`; the only lazy dynamic imports are `ai/gateway.ts` in `initSchema` and `_upsertChunksOnce`, line-marked because their local catches preserve compiled-default and stored-config fallbacks that eager module evaluation would bypass. `getRawData` pushes `p.deleted_at IS NULL` into its `where[]` unless `opts.includeDeleted` — parity twin of the Postgres `alive` fragment; see the postgres-engine.ts entry.+- `src/core/pglite-engine.ts` — PGLite (embedded Postgres 17.5 via WASM) implementation, all BrainEngine methods. The facts/takes/code-edges/salience method clusters are implemented in narrow-deps modules under `src/core/pglite-engine/` (see the engine-module-dirs entry below); the class methods delegate to them and the façade keeps its full public surface. `listLinkSources({sourceId?, sourceIds?})` returns distinct `link_source` provenances + counts (`ORDER BY count DESC, link_source ASC NULLS LAST`; scalar + federated scoped; parity with postgres-engine.ts) powering `gbrain link-sources`. `addLinksBatch`/`addTimelineEntriesBatch`/`addTakesBatch` pass the whole batch as one JSONB document via `jsonb_to_recordset(($1::jsonb)->'rows')` (bound through `executeRawJsonb` with a `{ rows }` wrapper; rows built by the shared `src/core/batch-rows.ts` helpers, NUL-stripped), and are `batchRetry`-wrapped. `connect()` retries a failed in-memory `PGlite.create()` once, cold, only while no database is attached. The retry omits the snapshot and clears its loaded flag so `initSchema()` replays the schema. Recovery warns on stderr; exhausted recovery retains both error diagnostics. Post-open setup errors instead close the existing database, preserving close-poison and ownership rules. The doctor scratch probe is a separate disk-backed path and does not use this retry. Remaining initialization failures use the existing classifier and, for the `wasm-abort` verdict on a persistent data dir (torn WAL/checkpoint state after an unclean shutdown; it presents like a macOS WASM bug but is not one), runs in-place auto-repair via `attemptWalRepairAndRetry` (static import from `pglite-repair.ts`, per the engine-live rule; the retry create is `preservingProcessExitCode`-wrapped; success sets the public `walRepairReceipt` field + prints `buildWalRepairNotice` to stderr and returns with the lock held). The seam never throws, so every non-repaired path funnels through the single lock-release-then-throw site; repair refuses when the lock was acquired by reaping (`LockHandle.reaped` → `'possibly-live-writer'`), when disabled (`GBRAIN_PGLITE_WAL_REPAIR=off`), on layout-validation failure, or inside the post-failure cooldown. `disconnect()` awaits mandatory resident-consumer stops, closes admission on tracked query/exec/transaction handles, drains admitted statements and best-effort background work, then awaits CHECKPOINT and close before kernel release. A deadline reports `pglite_closing` while actual shutdown continues with ownership retained; a failed close poisons reconnect until process exit. The out-of-band watchdog remains available for event-loop wedges. `searchKeyword`/`searchKeywordChunks` multiply `ts_rank` by the source-factor CASE at chunk grain; `searchVector` is a two-stage CTE — inner CTE keeps `ORDER BY cc.embedding <=> vec` so HNSW stays usable, outer SELECT re-ranks by `raw_score * source_factor`, inner LIMIT scales with offset to preserve pagination. `searchTakes`/`searchTakesVector` take full `SearchOpts` and apply the standard source-scope predicates (federated `sourceIds[]` wins over scalar `sourceId`, via the joined page's `source_id`) alongside the holder allow-list — parity SQL in postgres-engine.ts; pinned by `test/e2e/think-source-isolation-pglite.test.ts`. `initSchema()` calls `applyForwardReferenceBootstrap()` BEFORE replaying SCHEMA_SQL — probes for forward-referenced state the embedded blob needs (`pages.source_id`, `links.link_source`, `links.origin_page_id`, `content_chunks.symbol_name`, `content_chunks.language`, `sources` FK target, plus `files.source_id`, `files.page_id`, `oauth_clients.source_id`, `oauth_clients.federated_read`, `sources.archived`, `sources.archived_at`, `sources.archive_expires_at`, `timeline_entries.event_page_id` — column-only, migration v121 stays the source of truth for its FK + indexes) and adds only what's missing; threads the DDL connection from `initSchema` so probes run inside the advisory-lock scope; no-op on fresh installs and current brains (this is what keeps an upgrade from wedging on a forward-referenced column). `getBrainScore` returns 100/100 with full breakdown (35/25/15/15/10) when `pageCount === 0` (vacuous truth — empty brain has no coverage problem); Pinned by `test/brain-score-breakdown.test.ts` empty-brain assertion + `test/doctor-report-remote.serial.test.ts`. `PGlite.create()` runs inside `preservingProcessExitCode`: PGLite's Emscripten runtime writes its own status into `process.exitCode` (99 at create; in-memory brains run initdb whose status lands on a later tick; the exit status at close — and assigning `undefined` cannot clear a prior value), which would otherwise silently clobber an errored op's exit 1 back to 0. The wrapper keeps the global tidy for external readers; `db.close()` stays unwrapped (its 0-write is baseline behavior test runners depend on). The CLI's exit verdict is immune either way — it lives in the gbrain-owned channel in `cli-force-exit.ts` and never reads `process.exitCode` back. Exports `classifyPgliteInitError(message): 'bunfs' | 'wasm-abort' | 'corrupt' | 'unknown'` + `buildPgliteInitErrorMessage(verdict, original, platform?, ctx?)` + `stringifyPgliteInitError(err)` + `buildWalRepairNotice(receipt)` + the `PgliteInitRepairContext` type, routing the catch-block hint by failure shape (`bunfs` matches literal `$$bunfs` OR `ENOENT[\s\S]*pglite\.data` co-occurrence, surfaces a paste-ready `bun upgrade` + Node fallback; `corrupt` — 58P01/`internal_load_library`/missing vector type, catalog corruption WAL repair can't fix — stays matched BEFORE the wasm arm and routes to `reinit-pglite`; `wasm-abort` matches the real production shapes `Aborted()`/`RuntimeError`/`unreachable` plus legacy signatures, names the corrupt-WAL root cause + the recovery ladder (`pglite-repair` → rebuild → engine switch) + what auto-repair did per `ctx` incl. the honesty-critical `failed-not-restored` arm, and links the upstream tracking issue; `unknown` is platform-gated). `stringifyPgliteInitError` also surfaces message-less Emscripten objects (`ErrnoError (errno N)`) instead of `[object Object]`. Pinned by `test/pglite-init-classifier.test.ts` + `test/pglite-wal-repair.serial.test.ts` + `test/fix-wave-structural.test.ts`. Implements `deletePages(slugs, {sourceId})` + `resolveSlugsByPaths(paths, {sourceId})` via `slug = ANY($1::text[])` array-param binding, caller-chunking primitive throwing when input exceeds `DELETE_BATCH_SIZE`, `deletePages` returns `RETURNING slug` rows so callers filter `pagesAffected` to confirmed deletes. Implements the embedding-signature stale-detection quartet — `sumStaleChunkChars({sourceId?, signature?})`, `setPageEmbeddingSignature(slug, {sourceId?, signature})`, `invalidateStaleSignatureEmbeddings({signature, sourceId?})`, widened `countStaleChunks({sourceId?, signature?})` (the `signature` opt widens via `JOIN pages p ... WHERE cc.embedding IS NULL OR (p.embedding_signature IS NOT NULL AND p.embedding_signature <> $signature)`, NULL grandfathered); parity SQL with postgres-engine.ts. PGLite-specific DDL (pgvector, pg_trgm, triggers). Engine-path helper dependencies (`retry`, ontology, recency decay) avoid dynamic `import()`; the only lazy dynamic imports are `ai/gateway.ts` in `initSchema` and `_upsertChunksOnce`, line-marked because their local catches preserve compiled-default and stored-config fallbacks that eager module evaluation would bypass. `getRawData` pushes `p.deleted_at IS NULL` into its `where[]` unless `opts.includeDeleted` — parity twin of the Postgres `alive` fragment; see the postgres-engine.ts entry. Outermost `transaction()` calls run `PgliteCheckpointGuard` (`src/core/pglite-engine/checkpoint-guard.ts`) before BEGIN: when WAL since the last redo point passes half the automatic-checkpoint distance (256 MB with the default 1 GB `max_wal_size`) it issues a top-level `CHECKPOINT` (each probe is queued with its own transaction, so concurrent callers see their predecessors' WAL, and the whole guarded operation is admitted once into the datastore's shutdown drain), because PGLite runs the automatic checkpoint inline inside the WAL write that crosses the trigger and that nested checkpoint spins forever (#5449/#5284). Savepoint transactions never checkpoint; the direct read-only vector-search transaction and other direct driver transactions are not guarded. A failed WAL probe proceeds with a once-per-process warning; a failed `CHECKPOINT` refuses before BEGIN with a `GBrainError` naming `gbrain pglite-repair`. Tests: `test/pglite-checkpoint-guard.test.ts`; the large-store harness `scripts/pglite-checkpoint-harness/supervisor.ts` (external supervisor, WAL-bound assertion) runs outside CI.- `src/core/pglite-lifecycle.ts` — tracks admitted datastore statements and transactions across early-null, rejects new work through captured handles, and supplies the typed closing error. A successful same-datastore reopen resumes its stopped persistence consumer only after database open and filesystem-registry success; replaced or disposed services unregister their lifecycle hooks. Pending or failed close never resets the admission barrier. Both engines expose `registerBeforeDisconnect(stop)` (returns unregister) as a mandatory resident-consumer barrier and `transactionDirect(fn)` for short control work on the existing direct route; nested calls stay in their transaction.diff --git a/docs/architecture/key-files/files-and-sync-1.md b/docs/architecture/key-files/files-and-sync-1.mdindex 577f5b2107..56a96a3b98 100644--- a/docs/architecture/key-files/files-and-sync-1.md+++ b/docs/architecture/key-files/files-and-sync-1.md@@ -25,7 +25,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/import-checkpoint.ts` — `loadCheckpoint(brainDir)`, `saveCheckpoint(brainDir, completed)`, `resumeFilter(files, completed, brainDir)`, `clearCheckpoint()`, plus the `ImportCheckpoint` type. Path-set format `{schema_version, brainDir, completed: string[]}`. Atomic write via `.tmp` + `rename()` so a mid-write crash never leaves a partial JSON. `loadCheckpoint` returns `null` on: missing file, malformed JSON, brainDir mismatch (ran against a different brain), and the old positional format (logged to stderr before discard). `resumeFilter` returns `{toProcess, skippedCount}` — pure, no I/O, deterministic. `clearCheckpoint` is no-op-on-missing for clean-exit cleanup. Honors `GBRAIN_HOME` via `gbrainPath()` so `withEnv({GBRAIN_HOME: tmpdir})` test isolation works without monkey-patching fs. Best-effort persistence — `saveCheckpoint` logs warnings on write errors but never throws.-- `src/core/import-file.ts` — importFromFile + importFromContent (chunk + embed + tags). The `beforeCommit` hook runs inside the guarded canonical transaction so a rejected file write rolls back its projections; optional legacy source-path repair uses a savepoint. Deferred importer embedding callbacks capture the committed text projection and indexing context, then install with an UPDATE-only revision/chunk/hash check. Tests: `test/import-publication-guards.test.ts`. Coordinated `prepare` imports resolve and atomically stamp the page/source/global contextual wrapping mode even with `noEmbed:true`; the durable outbox later embeds that revision. The existing paid-synopsis title fallback and mount trust gate remain in force, while embedding signatures only certify completed vectors. `test/persistence-contextual-embedding.test.ts` covers both engines, policy precedence, deferred provider execution, and a competing title replacement. `importFromContent` and `importCodeFile` stamp `pages.embedding_signature` via `setPageEmbeddingSignature(slug, {sourceId, signature: currentEmbeddingSignature()})` when the import actually embedded (not `--no-embed`) so a model/dims swap is detectable as stale; `importCodeFile` only stamps when every chunk was freshly embedded this call (`needsEmbedIndexes.length === chunks.length`), mixed reuse-by-hash pages stay unstamped (`reindex --code --force` / `embed --stale` handle those). `importFromContent`'s tag reconciliation is ADD-ONLY: it only `addTag` (idempotent, ON CONFLICT DO NOTHING). The `tags` table has no provenance column and frontmatter tags are stripped from stored `pages.frontmatter` (markdown.ts:118), so a frontmatter-origin tag can't be distinguished from a DB-enrichment tag (auto-tag / dream synthesize / signal-detector) at re-import — deletion is unsafe (would wipe enrichment under `gbrain reindex --markdown`). Accepted trade-off: removing a tag from frontmatter does not remove it from the DB on next sync (needs a `tag_source` provenance column). Pinned by `test/reindex-preserve-tags.test.ts` + `test/import-file.test.ts`. identity decisions live in `src/core/import-identity.ts` (`decideImportIdentity`, `collidingSlugOwner`; pure reads, the importer applies them). The dedup pre-check calls `engine.findDuplicatePage?.(sourceId, {hash, frontmatterId, excludeSlug})` (optional `?` so test doubles compile; the caller's own slug never matches, and a `frontmatter.id` match ranks ahead of a bare hash match). Posture: MOVE when the `frontmatter.id` matches and the other page's recorded `source_path` is gone under this import's root (`sourceRoot`, set by `importFromFile`): `updateSlug` carries the row (page id, links, facts, timeline, plus a rename alias) and the new content imports onto it, so a full sync's delete-reconcile has nothing live to remove; SKIP only when the id AND the content (`content_hash`, or title and body for a row written outside the importer) both match while the recorded file still exists (overlapping ingest roots); IMPORT with a warning when the id matches but content differs (templates, copy-paste; an edit is never frozen by the other page); WARN-ALWAYS on a bare content_hash collision; FAIL CLOSED on lookup error; bypass via `--force-rechunk`. Content-only callers (`put_page`, transcripts) never move a page. Soft-deleted pages excluded at the engine layer so tombstones don't block legitimate re-imports under new slugs. Slug collisions: when another live file (`existing.source_path`, realpath-distinct) already owns the slug, the incoming file is skipped with `skip_reason: 'slug_collision'` and a stderr warning, unless the incoming file is named exactly `<slug>.md` (the file the link extractor reads for that slug), so two spellings never overwrite each other. An embedding failure never blocks the text write: chunks commit with NULL vectors, no embedding signature is stamped, the result carries `embedding_deferred: true`, and the stale sweep embeds them later (a code file whose embed failed is not stamped either). `effective_date` for an undated page falls back to `fallbackCreatedAt` (stored fallback date, else the file's own timestamp via `fileTimes`, else now), never the latest write. Pinned by `test/import-dedup-frontmatter-id.test.ts`, `test/import-identity-move.test.ts`, `test/import-slug-collision.test.ts`, `test/import-embed-outage.test.ts` and `test/effective-date-calendar.test.ts`. `importFromContent` is the narrow waist every ingest path passes through (`gbrain import`, `gbrain sync`, `put_page` MCP, `/ingest` webhook). It runs a three-tier content-quality disposition via `assessContentSanity` from `src/core/content-sanity.ts` BEFORE chunking: (1) high-confidence junk (built-in Cloudflare/CAPTCHA interstitial patterns + operator literals) → QUARANTINE (stamps the `quarantine` frontmatter marker, writes ZERO chunks, hides the page from search) OR REJECT (throw → sync-failure) when `content_sanity.junk_disposition` is `reject`; (2) fuzzy markup-heavy (prose-vs-markup ratio above `content_sanity.max_markup_ratio`, warn-tier byte window, code pages exempt) → `content_flag:markup_heavy` marker (page stays fully searchable, marker rides search results + get_page to warn the agent); (3) oversize → `embed_skip` soft-block via `buildEmbedSkipMarker()` PLUS a `content_flag:oversized` marker, AND deletes any pre-existing chunks in the same transaction so search can't surface stale chunks. Gate-owned markers (`quarantine`, `content_flag`) are STRIPPED from untrusted (remote MCP, `ctx.remote !== false`) frontmatter so a write-scoped client can't hide pages or forge the warning channel; markers are excluded from `content_hash` so a flagged page doesn't re-embed every sync. `gbrain import` honors `errors > 0` for non-zero exit. `classifyErrorCode` in `src/core/sync.ts` recognizes the `PAGE_JUNK_PATTERN` code so sync-failures.jsonl grouping bins these. `extractEntityRefs` (canonical; matches both `[Name](../people/slug)` markdown links and Obsidian `[[people/slug|Name]]` wikilinks), `extractPageLinks`, `inferLinkType` heuristics (attended/works_at/invested_in/founded/advises/source/mentions), `parseTimelineEntries`, `isAutoLinkEnabled` config helper. Link candidates match any dir-shaped path (existence-checked at persist). Used by extract.ts, operations.ts auto-link post-hook, and backlinks.ts. Pinned by `test/import-file-content-sanity.test.ts`. `importImageFile` records `source_path` on every image page and skips an unchanged image only when its index is complete for the run: a visual vector when embedding is on, and OCR (`ocr_status: 'done'` in frontmatter, or legacy stored OCR text) when OCR is enabled, so an image first imported under `--no-embed` or an OCR skip is rebuilt on its next import (`test/import-image-retry.test.ts`). `importCodeFile` writes `source_path: relativePath` on every code page (the same repo-relative path markdown imports record) so the full-sync reconcile — which only considers `source_path IS NOT NULL` rows — can retire a deleted code file's page; `putPage` COALESCEs the column, so rows imported before this keep NULL until the file changes, `sync --force`, or `gbrain reindex-code --force`.+- `src/core/import-file.ts` — importFromFile + importFromContent (chunk + embed + tags). Unchanged markdown or code content whose page is below the safe-chunk fence is re-sealed projection-only (direct imports install it; coordinated `prepare` imports stay no-ops and queue a `safe_chunk_reseal` projection job), with no page write or admission. Freshly embedded chunks carry `embedding_input_hash` for the tier they were built under. The `beforeCommit` hook runs inside the guarded canonical transaction so a rejected file write rolls back its projections; optional legacy source-path repair uses a savepoint. Deferred importer embedding callbacks capture the committed text projection and indexing context, then install with an UPDATE-only revision/chunk/hash check. Tests: `test/import-publication-guards.test.ts`. Coordinated `prepare` imports resolve and atomically stamp the page/source/global contextual wrapping mode even with `noEmbed:true`; the durable outbox later embeds that revision. The existing paid-synopsis title fallback and mount trust gate remain in force, while embedding signatures only certify completed vectors. `test/persistence-contextual-embedding.test.ts` covers both engines, policy precedence, deferred provider execution, and a competing title replacement. `importFromContent` and `importCodeFile` stamp `pages.embedding_signature` via `setPageEmbeddingSignature(slug, {sourceId, signature: currentEmbeddingSignature()})` when the import actually embedded (not `--no-embed`) so a model/dims swap is detectable as stale; `importCodeFile` only stamps when every chunk was freshly embedded this call (`needsEmbedIndexes.length === chunks.length`), mixed reuse-by-hash pages stay unstamped (`reindex --code --force` / `embed --stale` handle those). `importFromContent`'s tag reconciliation is ADD-ONLY: it only `addTag` (idempotent, ON CONFLICT DO NOTHING). The `tags` table has no provenance column and frontmatter tags are stripped from stored `pages.frontmatter` (markdown.ts:118), so a frontmatter-origin tag can't be distinguished from a DB-enrichment tag (auto-tag / dream synthesize / signal-detector) at re-import — deletion is unsafe (would wipe enrichment under `gbrain reindex --markdown`). Accepted trade-off: removing a tag from frontmatter does not remove it from the DB on next sync (needs a `tag_source` provenance column). Pinned by `test/reindex-preserve-tags.test.ts` + `test/import-file.test.ts`. identity decisions live in `src/core/import-identity.ts` (`decideImportIdentity`, `collidingSlugOwner`; pure reads, the importer applies them). The dedup pre-check calls `engine.findDuplicatePage?.(sourceId, {hash, frontmatterId, excludeSlug})` (optional `?` so test doubles compile; the caller's own slug never matches, and a `frontmatter.id` match ranks ahead of a bare hash match). Posture: MOVE when the `frontmatter.id` matches and the other page's recorded `source_path` is gone under this import's root (`sourceRoot`, set by `importFromFile`): `updateSlug` carries the row (page id, links, facts, timeline, plus a rename alias) and the new content imports onto it, so a full sync's delete-reconcile has nothing live to remove; SKIP only when the id AND the content (`content_hash`, or title and body for a row written outside the importer) both match while the recorded file still exists (overlapping ingest roots); IMPORT with a warning when the id matches but content differs (templates, copy-paste; an edit is never frozen by the other page); WARN-ALWAYS on a bare content_hash collision; FAIL CLOSED on lookup error; bypass via `--force-rechunk`. Content-only callers (`put_page`, transcripts) never move a page. Soft-deleted pages excluded at the engine layer so tombstones don't block legitimate re-imports under new slugs. Slug collisions: when another live file (`existing.source_path`, realpath-distinct) already owns the slug, the incoming file is skipped with `skip_reason: 'slug_collision'` and a stderr warning, unless the incoming file is named exactly `<slug>.md` (the file the link extractor reads for that slug), so two spellings never overwrite each other. An embedding failure never blocks the text write: chunks commit with NULL vectors, no embedding signature is stamped, the result carries `embedding_deferred: true`, and the stale sweep embeds them later (a code file whose embed failed is not stamped either). `effective_date` for an undated page falls back to `fallbackCreatedAt` (stored fallback date, else the file's own timestamp via `fileTimes`, else now), never the latest write. Pinned by `test/import-dedup-frontmatter-id.test.ts`, `test/import-identity-move.test.ts`, `test/import-slug-collision.test.ts`, `test/import-embed-outage.test.ts` and `test/effective-date-calendar.test.ts`. `importFromContent` is the narrow waist every ingest path passes through (`gbrain import`, `gbrain sync`, `put_page` MCP, `/ingest` webhook). It runs a three-tier content-quality disposition via `assessContentSanity` from `src/core/content-sanity.ts` BEFORE chunking: (1) high-confidence junk (built-in Cloudflare/CAPTCHA interstitial patterns + operator literals) → QUARANTINE (stamps the `quarantine` frontmatter marker, writes ZERO chunks, hides the page from search) OR REJECT (throw → sync-failure) when `content_sanity.junk_disposition` is `reject`; (2) fuzzy markup-heavy (prose-vs-markup ratio above `content_sanity.max_markup_ratio`, warn-tier byte window, code pages exempt) → `content_flag:markup_heavy` marker (page stays fully searchable, marker rides search results + get_page to warn the agent); (3) oversize → `embed_skip` soft-block via `buildEmbedSkipMarker()` PLUS a `content_flag:oversized` marker, AND deletes any pre-existing chunks in the same transaction so search can't surface stale chunks. Gate-owned markers (`quarantine`, `content_flag`) are STRIPPED from untrusted (remote MCP, `ctx.remote !== false`) frontmatter so a write-scoped client can't hide pages or forge the warning channel; markers are excluded from `content_hash` so a flagged page doesn't re-embed every sync. `gbrain import` honors `errors > 0` for non-zero exit. `classifyErrorCode` in `src/core/sync.ts` recognizes the `PAGE_JUNK_PATTERN` code so sync-failures.jsonl grouping bins these. `extractEntityRefs` (canonical; matches both `[Name](../people/slug)` markdown links and Obsidian `[[people/slug|Name]]` wikilinks), `extractPageLinks`, `inferLinkType` heuristics (attended/works_at/invested_in/founded/advises/source/mentions), `parseTimelineEntries`, `isAutoLinkEnabled` config helper. Link candidates match any dir-shaped path (existence-checked at persist). Used by extract.ts, operations.ts auto-link post-hook, and backlinks.ts. Pinned by `test/import-file-content-sanity.test.ts`. `importImageFile` records `source_path` on every image page and skips an unchanged image only when its index is complete for the run: a visual vector when embedding is on, and OCR (`ocr_status: 'done'` in frontmatter, or legacy stored OCR text) when OCR is enabled, so an image first imported under `--no-embed` or an OCR skip is rebuilt on its next import (`test/import-image-retry.test.ts`). `importCodeFile` writes `source_path: relativePath` on every code page (the same repo-relative path markdown imports record) so the full-sync reconcile — which only considers `source_path IS NOT NULL` rows — can retire a deleted code file's page; `putPage` COALESCEs the column, so rows imported before this keep NULL until the file changes, `sync --force`, or `gbrain reindex-code --force`.- `src/core/link-source-check-repair.ts` — schema-drift self-heal for the `links_link_source_check` CHECK constraint (third instance of the `timeline-dedup-repair.ts` / `pages-upsert-arbiter.ts` class). Migration v114 opened `link_source` from a closed allowlist to the kebab-case gate; the migrator trusts the version ledger, so a brain stamped >= 114 whose live constraint reverted to the pre-v114 allowlist (drifted restore, manual DDL) rejects every kebab provenance write (`atom-provenance`, `concept-provenance`) while the ledger reads current. `LINK_SOURCE_KEBAB_RE` is the ONE exported copy of the regex (a drift-guard test pins it to the literal in migrate.ts v114, `schema.sql`, `pglite-schema.ts`). `checkLinkSourceCheck(engine)` probes `pg_constraint` (`pg_get_constraintdef` + `convalidated`) and classifies the drift as `absent` / `wrong_def` / `not_validated` (read-only; powers the `links_link_source_check` doctor check in `doctor/checks/core-health.ts`, whose severity follows what writes do: only `wrong_def` rejects kebab writes → fail; `absent` / `not_validated` still accept them → warn). `repairLinkSourceCheck(engine)` first COUNTs rows that fail the gate and returns `reason: 'violations'` WITHOUT any DDL when there are any (the prior constraint survives; rows are never touched; a brain with a bad row never pays for a failing ALTER at every engine open), then restores v114's definition mirroring the migration's engine split: Postgres runs DROP + `ADD ... NOT VALID` in one `engine.transaction` (atomic, no scan) and `VALIDATE CONSTRAINT` as a separate `engine.runMigration` outside it (SHARE UPDATE EXCLUSIVE, never a plain ADD's ACCESS EXCLUSIVE + full-table scan), with a `not_validated` drift getting the VALIDATE only; PGLite keeps the one-shot DROP+ADD transaction. A DDL failure re-counts violators (a row written between probe and ALTER) and rethrows when there are none. `LINK_SOURCE_GATE_MIGRATION_VERSION` (114) is the ledger gate `runMigrations` applies before calling it. Pinned by `test/link-source-check-repair.test.ts` (PGLite, incl. a recording-engine assertion that violators trigger no DDL and that a sub-114 ledger never probes) and the DATABASE_URL-gated `test/e2e/link-source-check-repair-postgres.test.ts` (two-phase DDL sequence on real Postgres).diff --git a/docs/architecture/key-files/files-and-sync-2.md b/docs/architecture/key-files/files-and-sync-2.mdindex 4793345893..3dc7bd90d2 100644--- a/docs/architecture/key-files/files-and-sync-2.md+++ b/docs/architecture/key-files/files-and-sync-2.md@@ -7,4 +7,4 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/sync.ts` — Pure sync functions (manifest parsing, filtering, slug conversion). Exported `pruneDir(name: string): boolean` is the single source of truth for descent-time directory exclusion across walkers — blocks `node_modules` (no leading dot, so a naive walker would descend into it and inflate MISSING_OPEN counts via vendor packages), `vendor`/`dist`/`build`/`venv`, dot-prefix dirs, and `*.raw` sidecars — NOT `ops/`, which is ordinary user content (the bundled daily-task-manager stores `ops/tasks` there); `isSyncable` applies it per path segment, and `walkMarkdownFiles` in `src/commands/extract.ts` + `listTextFiles` in `src/core/cycle/transcript-discovery.ts` consult it BEFORE recursing to save the IO of walking thousands of vendor files. `manageGitignore` worktree discriminator matches the gitdir path segment (`/modules/<name>` = submodule, `/worktrees/<name>` = worktree, per Git's documented layout) so Conductor worktrees (first-class repos) get `.gitignore` management for storage-tiering. The sync-failure ledger (failure store, error classifier, the shared bookmark gate, and the doctor severity rule) lives in `src/core/sync-failure-ledger.ts`; `sync.ts` re-exports `classifyErrorCode`, `summarizeFailuresByCode`, `loadSyncFailures`, `unacknowledgedSyncFailures`, `acknowledgeSyncFailures`, `recordSyncFailures`, `decideSyncFailureSeverity`, `applySyncFailureGate`, and the `SyncFailure` type for backward-compatible imports — see its entry below. `isSyncable` factored through private `classifySync(path, opts): SyncableReason | null`; exported companion `unsyncableReason(path, opts)` returns the same tagged reason or null when syncable. `SYNC_SKIP_FILES` is a named export (the four canonical metafile basenames `schema.md`, `index.md`, `log.md`, `README.md`). `SyncableReason` union: `'metafile' | 'strategy' | 'pruned-dir' | 'include-glob-miss' | 'exclude-glob-hit' | 'malformed-path'`. Malformed filenames are TWO-TIER: `hasMalformedPathSegment` (ADMISSION — control chars on any path; square brackets on `.md`/`.mdx` paths only, so code-strategy lanes keep indexing `app/[id]/page.tsx` framework layouts) vs `isPoisonedPath` (DESTRUCTION — only the injection signature `](` or control chars; sync's row-DELETING lanes gate on this so a bare-bracket markdown row already in the DB survives reconcile while its file exists). `sanitizePathForDisplay` scrubs control bytes + caps length before echoing such paths. The `commands/sync.ts` cleanup loop guards on `unsyncableReason(path)` being `'metafile'` OR `'pruned-dir'` so previously-indexed metafile pages AND deliberately put-created pages under pruned dirs survive every re-sync. Does NOT cover `manifest.deleted` (the upstream filter already strips metafiles). Pinned by `test/sync-isSyncable-shape.test.ts` (15 cases, duality contract) + `test/sync-metafile-skip.serial.test.ts` (3 PGLite cases incl. the renamed `.md → .txt` negative). `pruneDir`: `pruneDir(name, parentDir?)` extended with optional `parentDir`. When provided, additionally rejects directories containing `.git` as a FILE — the git submodule gitfile pattern (regular repos have `.git` as a DIRECTORY; submodules as a file pointing into the parent's `.git/modules/`). Sync + extract walkers thread `parentDir` so the gitfile-as-FILE check fires per descend step. Best-effort: `statSync` failures fall through and treat as a normal dir. Prevents phantom imports from a worktree-with-submodules sync walking into submodule trees. Pinned by `test/sync-walker-submodule.test.ts`. The legacy failure ledger re-export is distinct from managed cursor-keyed mirrors: repeat managed observation does not inflate attempts, success clears only the matching cursor, and managed failures cannot be acknowledged or auto-skipped.-- `src/core/write-through.ts` — shared atomic disk write-through for the canonical ingestion path. `resolvePageWriteTarget(engine, slug, sourceId, { includeDeleted? })` (active rows by default; `includeDeleted: true` resolves a tombstone's recorded `source_path` for the purge remediation retry) is the exported single source of truth for the ONE file a (source, slug) pair lives in on disk: a source with its own `local_path` writes at that tree's ROOT (never nested under `.sources/`); a source without one nests under the host repo (`sync.repo_path`, default at root, non-default under `.sources/<id>/`) unless that path is another source's own working tree (leak guard → `source_repo_belongs_to_other_source`); the page's recorded `source_path` (or a contained `file://` `source_uri`) is preferred over a slug-derived name so writes land in the file of record instead of minting a twin; and `isWriteTargetContained` rejects hostile rows escaping the tree (`path_escapes_source_root`). The ok-result also carries `sourcePathToBind` — the target expressed in the file scanner's `source_path` convention (GIT-ROOT-relative when the scan root sits inside a git repo, so a subdirectory-scoped `local_path` binds the same form delete-reconcile keys on; scan-root-relative otherwise). The resolver is shared by `writePageThrough`, the facts fence writer (`src/core/facts/fence-write.ts`), and fence forget (`src/core/facts/forget.ts`) — the fence appends to the page's file, so all writers MUST compute the identical path or the fence lands in a file sync never reads back and the next extract_facts reconcile deletes the fence-owned DB rows. `writePageThrough(engine, slug, {sourceId?, frontmatterOverrides?, logger?})` resolves the target through it, re-reads the just-written DB row (`getPage`), renders it via `serializePageToMarkdown`, and writes the `.md` so the brain has a committable artifact that round-trips through `gbrain sync`. Rendering from the row keeps the serialized content consistent at write time. The fsync-backed `atomicWriteFileSync` stages and renames the file after required source-path bookkeeping; lock/lease checks run before publication. `put_page` holds the root lock before importing and invokes write-through inside its database transaction, so ordinary filesystem rejection rolls back existing content, tags, chunks, and versions. A crash or database COMMIT failure after rename can still leave canonical Markdown ahead of the index; this is not distributed ACID or a durable queue. Never throws — returns `WriteThroughResult { written, path?, skipped?: 'disabled_by_config' | 'no_repo_configured' | 'repo_not_found' | 'source_repo_belongs_to_other_source' | 'page_not_found_after_write' | 'path_escapes_source_root' | 'case_insensitive_collision', warning?, error? }` so the caller decides messaging + exit codes. `withNoRepoWriteThroughWarning(result, sourceId)` decorates an unwritten `no_repo_configured` result with `warning` (the write landed only in the database; bind the token/server to a git-backed source or configure `local_path`/`sync.repo_path`); `put_page` applies it for untrusted callers only (`ctx.remote !== false`), so local CLI responses and the `disabled_by_config` operator opt-out stay silent. `isWriteThroughDisabled` (shared with the fence lane, ~30s per-engine cache) honors the `sync.write_through` opt-out. Trust gating (subagent sandbox, dry-run) stays at the CALLER. On a durability-hardened repo (`isDurabilityHardened` — the gbrain post-commit hook is installed, i.e. the user ran `gbrain sources harden`), a successful write is best-effort COMMITTED via `commitWriteThroughFile` (path-limited `git commit -- <file>`, never sweeps unrelated edits; the hook then background-pushes) so write-through content reaches git instead of accumulating uncommitted forever; result carries `committed?: boolean`. Unhardened repos keep write-only behavior. `deletePageThrough(engine, slug, {sourceId?, target?, logger?})` is the delete-side sink (sole caller: the `delete_page` op): resolves the same target, unlinks the `.md`, and on a hardened repo best-effort commits the removal path-limited through the same helper with subject `gbrain: delete write-through <slug>`, reporting `committed?: boolean` on `DeleteThroughResult` (absent when unhardened or when the commit did not land — the unlink still stands; a never-committed page leaves nothing to commit, so no empty commit). Pinned by `test/delete-write-through-commit.serial.test.ts`. Consumers: `put_page` op and `gbrain brainstorm/lsd --save` via `persistSavedIdea`. Pinned by `test/write-through.test.ts` + `test/write-through-commit.serial.test.ts`. The `put_page` op is that deciding caller for direct writes: a skip outside the deliberate DB-only set (`no_repo_configured`/`disabled_by_config`/`subagent_sandbox`/`dry_run`) throws `storage_error` inside the import transaction, rolling back the page revision, tags, chunks and version snapshot instead of deleting a just-created row afterward.+- `src/core/write-through.ts` — shared atomic disk write-through for the canonical ingestion path. `resolvePageWriteTarget(engine, slug, sourceId, { includeDeleted? })` (active rows by default; `includeDeleted: true` resolves a tombstone's recorded `source_path` for the purge remediation retry) is the exported single source of truth for the ONE file a (source, slug) pair lives in on disk: a source with its own `local_path` writes at that tree's ROOT (never nested under `.sources/`); a source without one nests under the host repo (`sync.repo_path`, default at root, non-default under `.sources/<id>/`) unless that path is another source's own working tree (leak guard → `source_repo_belongs_to_other_source`); the page's recorded `source_path` (or a contained absolute `file://` `source_uri`; a relative or host-only `file://` names no local file and is read as absent) is preferred over a slug-derived name so writes land in the file of record instead of minting a twin; and `isWriteTargetContained` rejects hostile rows escaping the tree (`path_escapes_source_root`). The ok-result also carries `sourcePathToBind` — the target expressed in the file scanner's `source_path` convention for the source's pinned `slug_root_mode` (or the mode its first sync would pin, via `scannerSlugRootMode`): GIT-ROOT-relative under `git-root` when the scan root sits inside a git repo, scan-root-relative under `source-root` and for non-git or git-root scan roots, so a put-born page binds the same form managed sync and delete-reconcile key on. Every recorded-path reader (write targets, takes, reconcile, audit, export restore, doctor) decodes with the same mode (`resolveSourceLocalFilePath(..., slugRootMode)`): under `source-root` the scope prefix is removed only from the legacy Git-root form whose remainder names the page slug, and basename rows resolve under the unstripped slug directory. The resolver is shared by `writePageThrough`, the facts fence writer (`src/core/facts/fence-write.ts`), and fence forget (`src/core/facts/forget.ts`) — the fence appends to the page's file, so all writers MUST compute the identical path or the fence lands in a file sync never reads back and the next extract_facts reconcile deletes the fence-owned DB rows. `writePageThrough(engine, slug, {sourceId?, frontmatterOverrides?, logger?})` resolves the target through it, re-reads the just-written DB row (`getPage`), renders it via `serializePageToMarkdown`, and writes the `.md` so the brain has a committable artifact that round-trips through `gbrain sync`. Rendering from the row keeps the serialized content consistent at write time. The fsync-backed `atomicWriteFileSync` stages and renames the file after required source-path bookkeeping; lock/lease checks run before publication. `put_page` holds the root lock before importing and invokes write-through inside its database transaction, so ordinary filesystem rejection rolls back existing content, tags, chunks, and versions. A crash or database COMMIT failure after rename can still leave canonical Markdown ahead of the index; this is not distributed ACID or a durable queue. Never throws — returns `WriteThroughResult { written, path?, skipped?: 'disabled_by_config' | 'no_repo_configured' | 'repo_not_found' | 'source_repo_belongs_to_other_source' | 'page_not_found_after_write' | 'path_escapes_source_root' | 'case_insensitive_collision', warning?, error? }` so the caller decides messaging + exit codes. `withNoRepoWriteThroughWarning(result, sourceId)` decorates an unwritten `no_repo_configured` result with `warning` (the write landed only in the database; bind the token/server to a git-backed source or configure `local_path`/`sync.repo_path`); `put_page` applies it for untrusted callers only (`ctx.remote !== false`), so local CLI responses and the `disabled_by_config` operator opt-out stay silent. `isWriteThroughDisabled` (shared with the fence lane, ~30s per-engine cache) honors the `sync.write_through` opt-out. Trust gating (subagent sandbox, dry-run) stays at the CALLER. On a durability-hardened repo (`isDurabilityHardened` — the gbrain post-commit hook is installed, i.e. the user ran `gbrain sources harden`), a successful write is best-effort COMMITTED via `commitWriteThroughFile` (path-limited `git commit -- <file>`, never sweeps unrelated edits; the hook then background-pushes) so write-through content reaches git instead of accumulating uncommitted forever; result carries `committed?: boolean`. Unhardened repos keep write-only behavior. `deletePageThrough(engine, slug, {sourceId?, target?, logger?})` is the delete-side sink (sole caller: the `delete_page` op): resolves the same target, unlinks the `.md`, and on a hardened repo best-effort commits the removal path-limited through the same helper with subject `gbrain: delete write-through <slug>`, reporting `committed?: boolean` on `DeleteThroughResult` (absent when unhardened or when the commit did not land — the unlink still stands; a never-committed page leaves nothing to commit, so no empty commit). Pinned by `test/delete-write-through-commit.serial.test.ts`. Consumers: `put_page` op and `gbrain brainstorm/lsd --save` via `persistSavedIdea`. Pinned by `test/write-through.test.ts` + `test/write-through-commit.serial.test.ts`. The `put_page` op is that deciding caller for direct writes: a skip outside the deliberate DB-only set (`no_repo_configured`/`disabled_by_config`/`subagent_sandbox`/`dry_run`) throws `storage_error` inside the import transaction, rolling back the page revision, tags, chunks and version snapshot instead of deleting a just-created row afterward.diff --git a/docs/architecture/key-files/google-and-loops-continued.md b/docs/architecture/key-files/google-and-loops-continued.mdindex 42b2fe9fc5..d637e69137 100644--- a/docs/architecture/key-files/google-and-loops-continued.md+++ b/docs/architecture/key-files/google-and-loops-continued.md@@ -5,7 +5,7 @@- `src/core/persistence/sync-failures.ts` — durable managed cursor/receipt diagnostics are the authority; JSONL is a compatibility mirror keyed by cursor and source/path. Failure observations deduplicate terminal receipts, retaining structured codes and attempts; success clears only its matching cursor. Local CLI shows request/run/pinned target details, while remote doctor returns source-scoped aggregates without paths, raw messages or receipt IDs. Missing durable state warns rather than certifying health. Failed receipts cannot be acknowledged, auto-skipped or rewritten; explicit idle ordinary-source retry creates fresh admission, while approved company manifests remain pinned. Tests: `test/persistence-sync-failures.serial.test.ts`, `test/e2e/managed-sync-failures.test.ts`.- `src/commands/mcp-expose-probe.ts` — the health / occupancy probes `mcp-expose.ts` runs, peeled out behind a narrow `ProbeDeps` (`fetch`, `tcpProbe`, `lookup`, `now`, `sleep`, `healthIntervalMs`) rather than the whole resolved-deps bag: `tryFetch(d, url, timeoutMs)` (one bounded fetch, `redirect: 'manual'`, never throws → `FetchOutcome { res, unresolved }`), `probeHealth` (`res.ok` — the `verify.*` / `--status` bar), `probeOccupied` (an accepted TCP connect OR any HTTP answer — the foreign-listener bar), `pollHealth` (wall-clock budget from `d.now()`, per-probe timeout `min(1500, remaining)`, attempt cap `ceil(budget / healthIntervalMs)` as the frozen-clock backstop, `unresolved` = the LAST probe's verdict), `unresolvedDetail(dnsName)`, `defaultTcpProbe` (one `node:net` connect, socket destroyed on every outcome) and `defaultLookup` (local RFC 6761 `.invalid` rejection, otherwise `dns.promises.lookup`). The name-resolution verdict is the reason the module exists: Bun's `fetch` rejects an unresolvable host with the SAME error as a refused connection ("Unable to connect. Is the computer able to access the url?", code `ConnectionRefused`), so a message match alone never fires in production. After a rejection `nameUnresolved` takes `new URL(url).hostname`, skips IP literals (`isIP`) and `localhost`, and otherwise awaits `d.lookup(host)` raced against the probe's `timeoutMs` (a lookup that does not answer in time proves nothing; the race keeps a late rejection handled); `isUnresolvedLookupError` classifies the lookup rejection by `code` — `ENOTFOUND`, `EAI_AGAIN`, `EAI_NONAME`, `EAI_NODATA`, `DNS_ENOTFOUND` (a resolver outage counts: the verdict is about THIS host) — or by those tokens in its message, and the fetch-message regex (`ENOTFOUND|getaddrinfo|EAI_AGAIN|failed to resolve|Unable to connect.*resolve`) is OR-ed in afterwards as the secondary hint. Tests inject a fake fetch, TCP probe and resolver (`test/mcp-expose.test.ts`; the fixture's default `lookup` resolves every name, reserved-name and label-boundary cases do not query external DNS, and the real `defaultLookup` resolves localhost).-- `src/core/tailscale.ts` — Tailscale helpers with an injected exec seam (`CommandRunner = (argv, { inherit?, timeoutMs?, stdoutToStderr? }) => Promise<CommandResult>` where `CommandResult = { status, stdout, stderr }` and `status: null` means killed at the timeout or never spawned; `defaultCommandRunner` on `Bun.spawn` — at `timeoutMs` it sends SIGTERM and, when the child has still not exited `SIGKILL_GRACE_MS` (3s) later, SIGKILL, so a child that ignores SIGTERM never hangs the caller; both timers are cleared in a `finally` — also the runner `serve-service.ts` types against; `stdoutToStderr` sends an inherited child's stdout to fd 2 so `--json` stdout stays pure): `parseTailscaleStatus` (`BackendState` — `Running`, `NeedsLogin`, `NeedsMachineAuth`, `NoState`, `Stopped`; `Self.DNSName`, `CertDomains`, and `funnelCapable`: true/false from `Self.CapMap` keys or `Self.Capabilities` entries containing `https://tailscale.com/cap/funnel`, null when both are absent), `publicUrlFromDnsName` (strip trailing dot, lowercase, `https://`), `TAILSCALE_BINARY_CANDIDATES` + `findTailscaleBinary` (`Bun.which`, then the macOS app bundle, Homebrew and `/usr/bin` paths; the candidate list doubles as `mcp-expose.ts`'s allowlist for a binary path recorded in a receipt) + `isSystemTailscaleBinary(binary, realpath = realpathSync)` (true when the path is a candidate literally or resolves to one through symlinks; an unresolvable path is false — `mcp-expose.ts` puts `sudo` in front of the binary only when this holds), `tailscaleInstallPlan(platform, hasBrew)`, `tailscaleLoginArgv(platform, user, binary)` → `{ setOperator?, up }` (Linux: `sudo <bin> set --operator=<user>` then a flagless `sudo <bin> up` — a flagged `up` trips the CLI's settings-revert check on a node with non-default prefs; macOS: `<bin> up`), `tailscaleManualLoginCommand(binary = 'tailscale')` (the Linux login the operator runs themselves when gbrain refuses to `sudo` a non-system binary — `sudo <bin> set --operator=$USER && sudo <bin> up` with the DISCOVERED path shell-quoted through `shellQuote`, because a binary outside sudo's `secure_path` is exactly that case) and `TAILSCALE_ACCEPT_DNS_COMMAND` (`tailscale set --accept-dns=true`, the MagicDNS-off remedy) — both keep their tailscale flag literals in this module so the flag-registry scan of `mcp-expose.ts` never sees them, `tailscaleServeArgv(port, { funnel })` (`serve --bg` / `funnel --bg`) + `tailscaleServeOffArgv({ funnel })` (`serve|funnel --https=443 --set-path=/ off` — `--set-path=/` scopes `off` to OUR `/` mount; without it the CLI removes every mount under `:443` and, when more than one exists, prompts interactively — with stdin ignored the prompt reads EOF and the command exits 0 having removed nothing; never `serve reset`), `parseServeStatusStrict` (the only serve-status parser, fail-closed: background `Web` handlers, `Foreground[<session>].Web` handlers marked `foreground: true`, and `TCP['443'].TCPForward` as a non-proxy root handler; an empty document / `{}` / `null` is the legitimately empty view, but non-JSON, an array or a scalar returns `null` so `mcp-expose.ts`'s `readServeView` can tell "could not read" from "nothing configured") + `findProxiedHandler(view, port)`, `classifyTailscaleError(stderr)` (Funnel rule before the HTTPS rule; the HTTPS rule matches certificate vocabulary, never a bare `https://` URL: `funnel_not_enabled` | `https_not_enabled` | `needs_operator` | `needs_login` | `daemon_not_running` | `unknown`), and the admin/KB URL constants (`TAILSCALE_ADMIN_DNS_URL`, `TAILSCALE_ADMIN_ACL_URL`, `TAILSCALE_FUNNEL_KB_URL` = `https://tailscale.com/kb/1223/funnel`, `TAILSCALE_DOWNLOAD_URL`). The parsers and argv builders are pure; the injectable `which` / `fileExists` / runner defaults touch `existsSync`, `process.env.PATH` and `process.platform`, and tests replace them. Note `tailscale status --json` exits 0 in every `BackendState` (only the human-readable form exits 1 when logged out), and `serve`/`funnel` wait interactively rather than failing when HTTPS certificates or the Funnel attribute are off — which is why `mcp-expose.ts` pre-checks before starting them.+- `src/core/tailscale.ts` — Tailscale helpers with an injected exec seam (`CommandRunner = (argv, { inherit?, timeoutMs?, stdoutToStderr? }) => Promise<CommandResult>` where `CommandResult = { status, stdout, stderr }` and `status: null` means killed at the timeout or never spawned; `defaultCommandRunner` on `Bun.spawn` — at `timeoutMs` it sends SIGTERM and, when the child has still not exited `SIGKILL_GRACE_MS` (3s) later, SIGKILL, so a child that ignores SIGTERM never hangs the caller; both timers are cleared in a `finally` — also the runner `serve-service.ts` types against; `stdoutToStderr` sends an inherited child's stdout to fd 2 so `--json` stdout stays pure): `parseTailscaleStatus` (`BackendState` — `Running`, `NeedsLogin`, `NeedsMachineAuth`, `NoState`, `Stopped`; `Self.DNSName`, `CertDomains`, and `funnelCapable`: true/false from `Self.CapMap` keys or `Self.Capabilities` entries carrying any Funnel form — `funnel` (`NodeAttrFunnel`), `https://tailscale.com/cap/funnel-ports` with or without its `?ports=` query, or the legacy `https://tailscale.com/cap/funnel` — null when both are absent), `publicUrlFromDnsName` (strip trailing dot, lowercase, `https://`), `TAILSCALE_BINARY_CANDIDATES` + `findTailscaleBinary` (`Bun.which`, then the macOS app bundle, Homebrew and `/usr/bin` paths; the candidate list doubles as `mcp-expose.ts`'s allowlist for a binary path recorded in a receipt) + `isSystemTailscaleBinary(binary, realpath = realpathSync)` (true when the path is a candidate literally or resolves to one through symlinks; an unresolvable path is false — `mcp-expose.ts` puts `sudo` in front of the binary only when this holds), `tailscaleInstallPlan(platform, hasBrew)`, `tailscaleLoginArgv(platform, user, binary)` → `{ setOperator?, up }` (Linux: `sudo <bin> set --operator=<user>` then a flagless `sudo <bin> up` — a flagged `up` trips the CLI's settings-revert check on a node with non-default prefs; macOS: `<bin> up`), `tailscaleManualLoginCommand(binary = 'tailscale')` (the Linux login the operator runs themselves when gbrain refuses to `sudo` a non-system binary — `sudo <bin> set --operator=$USER && sudo <bin> up` with the DISCOVERED path shell-quoted through `shellQuote`, because a binary outside sudo's `secure_path` is exactly that case) and `TAILSCALE_ACCEPT_DNS_COMMAND` (`tailscale set --accept-dns=true`, the MagicDNS-off remedy) — both keep their tailscale flag literals in this module so the flag-registry scan of `mcp-expose.ts` never sees them, `tailscaleServeArgv(port, { funnel })` (`serve --bg` / `funnel --bg`) + `tailscaleServeOffArgv({ funnel })` (`serve|funnel --https=443 --set-path=/ off` — `--set-path=/` scopes `off` to OUR `/` mount; without it the CLI removes every mount under `:443` and, when more than one exists, prompts interactively — with stdin ignored the prompt reads EOF and the command exits 0 having removed nothing; never `serve reset`), `parseServeStatusStrict` (the only serve-status parser, fail-closed: background `Web` handlers, `Foreground[<session>].Web` handlers marked `foreground: true`, and `TCP['443'].TCPForward` as a non-proxy root handler; an empty document / `{}` / `null` is the legitimately empty view, but non-JSON, an array or a scalar returns `null` so `mcp-expose.ts`'s `readServeView` can tell "could not read" from "nothing configured") + `findProxiedHandler(view, port)`, `classifyTailscaleError(stderr)` (Funnel rule before the HTTPS rule; the HTTPS rule matches certificate vocabulary, never a bare `https://` URL: `funnel_not_enabled` | `https_not_enabled` | `needs_operator` | `needs_login` | `daemon_not_running` | `unknown`), and the admin/KB URL constants (`TAILSCALE_ADMIN_DNS_URL`, `TAILSCALE_ADMIN_ACL_URL`, `TAILSCALE_FUNNEL_KB_URL` = `https://tailscale.com/kb/1223/funnel`, `TAILSCALE_DOWNLOAD_URL`). The parsers and argv builders are pure; the injectable `which` / `fileExists` / runner defaults touch `existsSync`, `process.env.PATH` and `process.platform`, and tests replace them. Note `tailscale status --json` exits 0 in every `BackendState` (only the human-readable form exits 1 when logged out), and `serve`/`funnel` wait interactively rather than failing when HTTPS certificates or the Funnel attribute are off — which is why `mcp-expose.ts` pre-checks before starting them.- `src/core/serve-service.ts` — the persistent-service half of `mcp expose`, everything under `gbrainPath('serve')` (`serveDir`, `adminTokenPath`, `wrapperPath`, `receiptPath`, `serveLogPath`, `serveErrPath`) so `GBRAIN_HOME` is honored. `SERVE_LAUNCHD_LABEL = 'com.gbrain.serve'`, `SERVE_SYSTEMD_UNIT = 'gbrain-serve.service'`, `detectServiceTarget(signals)` → `'macos' | 'linux-systemd' | 'none'` (a working user bus is required for systemd; cloud sandboxes and ephemeral containers fall to `none`). `renderServeWrapper` produces the 0755 launcher that sources the shell profiles and `~/.gbrain/env`, prepends the Bun dir to `PATH`, reads the admin token from its file at run time into `GBRAIN_ADMIN_BOOTSTRAP_TOKEN` (the token is never written into the wrapper, plist or unit), resolves `gbrain` the way autopilot's wrapper does (baked installer path, `type -P gbrain` fallback) and `exec`s `serve --http --port N --public-url URL [--surface] [--enable-dcr]`. `resolveServeGbrainCommand({ which, execPath, argv1, metaUrl, fileExists })` picks the baked program: a `gbrain` on PATH wins; a COMPILED binary — `import.meta.url` (or the injected `metaUrl`) under `/$bunfs/`, or an `execPath` that is not the bun runtime while `argv[1]` is absent/virtual — is `[execPath]` whatever its basename (release assets are renamed); otherwise the `[bun, <cli.ts>]` dev form only when that `cli.ts` exists on disk, else `[execPath]` rather than a path that cannot run; `renderServeLaunchdPlist` (RunAtLoad, KeepAlive, ThrottleInterval 30, logs to `serve.log` / `serve.err`, local `escapeXml`) and `renderServeSystemdUnit` (After=network-online.target, Restart=always, RestartSec=10, start-limit window; systemd specifiers escaped — `%` → `%%` in `ExecStart` and both `append:` log paths, `$` → `$$` in `ExecStart`). `ensureAdminToken` (0700 dir, 0600 file created with `wx` semantics, 64 hex chars; reuse a file matching the exported `ADMIN_TOKEN_SHAPE` = `^[A-Za-z0-9_-]{32,}$` — the same regex `serve-http.ts`'s `resolveBootstrapToken` accepts, so the file and the env var can never disagree on what a valid token is — unlink and regenerate otherwise), `installServeService` (launchd: domain-explicit `launchctl bootout gui/<uid> <plist>` — failure ignored — then `launchctl bootstrap gui/<uid> <plist>`, both through the one `launchctl(run, uid, plist, { modern, legacy })` helper whose legacy `launchctl unload` / `load` fallback is used ONLY when the modern verb exits non-zero with stderr matching `/Unknown command|unrecognized|not found/i`, never on a genuine failure or a killed call, and which reports the `verb` whose result it returns; a bootstrap that fails with stderr matching `LAUNCHCTL_SETTLE_RE` (`Input/output error`, `already in progress`, `\b5\b`, `\b37\b` — launchd still unloading the previous job) is retried up to `LAUNCHCTL_SETTLE_RETRIES` (5) times, `LAUNCHCTL_SETTLE_MS` (1s) apart through the injectable `sleep` param (default `setTimeout`; `mcp-expose.ts` passes `d.sleep`), a success after retries is a note and an exhausted retry appends "(after N settle retries)" to `error`; systemd: `daemon-reload` → `enable` → `restart` so a regenerated wrapper takes effect; `loginctl enable-linger` best effort) / `uninstallServeService` (launchd: the same `bootout gui/<uid>` with the same fallback; a bootout that exits non-zero — or is killed — with stderr NOT matching `LAUNCHCTL_NOT_LOADED_RE` (`No such process|not loaded|Could not find|not find service`) pushes `launchctl <verb> failed: <describeFailure>` into `notes`, and the exported `launchdBootoutFailed(result)` recognizes that note so `mcp-expose.ts` can say the job may still be loaded) / `serveServiceState` (`launchctl print gui/<uid>/<label>` / `systemctl --user is-active`); all three take `uid?: number` defaulting to `process.getuid?.() ?? 501`, threaded from `mcp-expose.ts`. Every supervisor subprocess carries a timeout — 60s for `launchctl bootstrap/bootout` (and the legacy `load/unload`) and `systemctl --user enable/restart/disable`, 15s for `launchctl print`, `daemon-reload`, `is-active` and `loginctl enable-linger` — and a `status: null` (killed) result counts as a failure (`error` / note) or `unknown` state; a failed call is described by `describeFailure` (its stderr, else stdout, else `exit <status>`). `readExposeReceipt` / `writeExposeReceipt` (`expose.json`, 0600, version 1, no secrets): the reader is a structural shape guard, not just `version`/`port`/`public_url` — it also requires `mode` in `tailnet|funnel`, a `service` object with a string `wrapper_path`, a `target` in `macos|linux-systemd|none`, a string `state` and string-or-null `plist_path` / `unit_path`, a `tailscale` object whose `binary` / `dns_name` are string-or-null, and string `mcp_url` / `admin_url` / `admin_token_file`; anything less is null (absent), so `--status` / `--remove` never dereference a half-written receipt. The token, receipt, wrapper, plist and unit writers refuse (clear error) when the target path is a symlink (`lstatSync`) before any supervisor call runs. Uses `shellQuote` from `src/core/mcp-registration.ts`; every filesystem/exec effect is behind injectable deps.- `src/core/harness/verify.ts` — Randomized server-side memory verification with revision-conditional cleanup and retained mutation UUIDs, with separate transport, identity, authority, read, write/readback, delegation and cleanup verdicts. Lost mutation responses are reconciled before retry; server success never certifies native-harness activation or cross-conversation behavior.@@ -15,8 +15,8 @@- `src/core/persistence/diagnostics.ts` — trusted administrator counts for owners/epochs, queued bytes/age, outbox recovery, configured quota usage and actionable capacity warnings; bigint values are transport-safe strings and diagnostics exclude intent, credentials and private paths.-- **`src/core/persistence/sync-discovery.ts`** + **`sync-origin.ts`** — managed owner-only Git discovery with source-relative exclusions and one-statement page identity/revision snapshots. Nested full discovery filters source scope before slicing paths. Windows separator aliases retain their page identity; ambiguous aliases refuse, while POSIX backslashes/case remain exact. Deletions must be absent from the pinned Git target or their explicitly selected working tree. Existing cursors reuse their accepted manifests, with unknown old deletion provenance refused rather than rewritten.-- **`src/core/persistence/sync-run.ts`** + **`sync-authority.ts`** — one immutable request at a time, bounded fairness and pinned-target resumption. Cursors and requests freeze `noEmbed`, `noExtract` and `noSchemaPack`; mismatched resumes refuse. Explicit idle ordinary-source retry creates fresh discovery/admission and retains terminal receipts; company consent retry retains its approved manifest/run. Active work blocks replacement. Claimed/inactive sync, including connector/company dispatch, remains refused: existing leases and native locks do not fence already-running engine-only legacy writers. No automatic activation or new transition protocol.+- **`src/core/persistence/sync-discovery.ts`** + **`sync-origin.ts`** — managed owner-only Git discovery with source-relative exclusions and one-statement page identity/revision snapshots. Nested full discovery filters source scope before slicing paths. Windows separator aliases retain their page identity; ambiguous aliases refuse, while POSIX backslashes/case remain exact. Under `source-root` mode a stored `<scope>/<path>` origin (the Git-root form older write-through minted from the slug, recognized because `<path>` names the page slug) is accepted as `<path>` at discovery, freeze, preparation and the page-origin query, and an import rewrites it in place; when both readings name existing files the stored origin refuses with `detail: ambiguous_source_path`. A genuine origin mismatch refuses with `detail: sync_origin_mismatch` and the filled paths. Deletions must be absent from the pinned Git target or their explicitly selected working tree. Existing cursors reuse their accepted manifests, with unknown old deletion provenance refused rather than rewritten.+- **`src/core/persistence/sync-run.ts`** + **`sync-authority.ts`** — one immutable request at a time, bounded fairness and pinned-target resumption. Cursors and requests freeze `noEmbed`, `noExtract` and `noSchemaPack`. A resume adopts the stored options for every option the caller did not set explicitly (`SyncOpts.explicitProcessing`: CLI flags, wire flags, job params; autopilot and the cycle set none); an explicit conflict refuses with `detail: cursor_processing_options_conflict`, the stored options and the exact resume command. Callers that omit `explicitProcessing` stay strict. Explicit idle ordinary-source retry creates fresh discovery/admission and retains terminal receipts; company consent retry retains its approved manifest/run. Active work blocks replacement. Claimed/inactive sync, including connector/company dispatch, remains refused: existing leases and native locks do not fence already-running engine-only legacy writers. No automatic activation or new transition protocol.- **`src/core/persistence/sync-prepare.ts`** — guarded raw fingerprint/revision, source root and active coordinator checks before preparation and at locked publication. Old imports/checkpoints without durable processing consent refuse under their original IDs; old deletions require their immutable origin manifest and a still-matching page origin. `noEmbed` suppresses the effect itself; `noSchemaPack` bypasses pack loading; optional extraction stays disabled, but mandatory provider-free canonical projections remain. CRLF equivalence never weakens raw CAS. No uncoordinated filesystem writes. Tests: `persistence-sync-origin-native.serial.test.ts`, `persistence-sync-options.serial.test.ts`, `persistence-sync-company.serial.test.ts`.- **`src/core/persistence/sync-authority.ts`** — trusted CLI or original remote generic job authority; rejects stdio bulk privilege promotion and runtime option expansion, intersects original grants with current principal/source policy.diff --git a/docs/architecture/key-files/page-identity-and-administration.md b/docs/architecture/key-files/page-identity-and-administration.mdindex 868dc88840..5fc9f7326e 100644--- a/docs/architecture/key-files/page-identity-and-administration.md+++ b/docs/architecture/key-files/page-identity-and-administration.md@@ -61,6 +61,11 @@ The grandfathering batch in `src/commands/migrations/v0_13_1.ts` changes only`frontmatter.validate`. It holds canonical page guards and row locks, recheckseligibility, and advances the text seal only for already-sealed snapshots.An unsealed page stays unsealed. This preserves keyword retrieval after a-metadata-only upgrade without bypassing revision safety. The installed-lifecycle+metadata-only upgrade without bypassing revision safety. The verify phase+checks only the pages this run grandfathered, keyed on `pages.id` and the+revision each write produced: a page a concurrent writer (such as a connector+re-import) rewrote or deleted since is reported as `rewritten_concurrently`,+and only a page still at that revision without `validate: false` fails the+phase. The installed-lifecycletest and `test/e2e/grandfather-projection-postgres.test.ts` cover the actualupgrade consequence and engine parity respectively.diff --git a/docs/architecture/key-files/providers.md b/docs/architecture/key-files/providers.mdindex 15ff8ee2f8..f3ee9125ab 100644--- a/docs/architecture/key-files/providers.md+++ b/docs/architecture/key-files/providers.md@@ -16,6 +16,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/embed-facts.ts` — explicit source-scoped NULL-fact vector repair with read-only default preview, finite nonnegative spend cap plus optional count/time bounds, row-version/incarnation/withdrawal CAS and per-attempt cost accounting. Selected-brain policy is a trusted out-of-band argument; engine DB off-switch and policy are rechecked on every provider attempt. Managed mode updates physical projection only and live PGLite delegates through private `writer_embed_facts`, not a canonical fact rewrite. Tests: `test/e2e/fact-embedding-backfill-parity.test.ts`, `test/fact-backfill-resident.test.ts`.+- `src/core/embedding-input-hash.ts` — per-chunk embedding-input provenance (#5553). `embeddingInputHash` digests the vector column, model, dimensions, wrapping tier and the exact input (chunk text; title prefix + text; or, for the unrecomputable synopsis tier, the page's corpus generation, title, `synopsisBodyHash` of the chunk set and the text). `acceptedEmbeddingInputHashes` also accepts title-tier vectors on synopsis pages; `plainEmbeddingTier` mirrors `wrapChunkTextsForStoredMode`. A body change therefore nulls every synopsis-tier chunk and nothing else unchanged. Pinned by `test/projection-embedding-input-hash.test.ts` (PGLite and Postgres).- `src/core/embed-oversize-heal.ts` — heals ALREADY-STORED chunks that exceed the active embedding model's per-input token cap (new imports respect `resolveMaxChunkTokens()`, but `--stale` re-embeds existing `chunk_text` rows chunked under looser caps, which fail every sweep forever). `healOversizedChunks` splits oversized rows in place (never truncates; char-based hard split as the pathological fallback), re-indexes contiguously, carries each piece's modality/code-symbol metadata, and leaves embeddings unset so `upsertChunks` preserves vectors for unchanged `(chunk_index, chunk_text)` pairs and NULLs the split/shifted ones; `healOversizedPageChunks` is the load-split-upsert-reload wrapper. `healedChunksToStaleRows(chunks, slug, sourceId)` remaps a post-heal chunk list back into the stale-row shape — the shared seam between `src/commands/embed.ts:embedAllStale` and `src/core/embed-stale.ts:embedStaleForSource` so the two drains cannot drift; `chunk_source` passes through UNCHANGED (coercing `fenced_code` to `compiled_truth` would make `wrapChunkTextsForStoredMode` prefix code chunks, violating the D20-T4 never-wrap convention). Pinned by `test/embed-oversize-heal.test.ts`.- `src/core/embed-retry.ts` — embed retry/backoff primitives + the title-tier restamp helper, kept in core because `src/core/import-file.ts` and `src/core/embed-stale.ts` consume these (a core→commands import would make every import-file consumer eagerly load the embed COMMAND module — one value import away from a real ESM cycle). `embedBatchWithBackoff` wraps `embedBatch` with rate-limit-aware retry: detects 429s via the wrapped error's `cause.status` (message-match fallback), also retries transient gateway 502/503/504, parses provider retry-delay hints, jitters ±30% so concurrent workers don't resynchronize, passes `maxRetries: 0` through so the AI SDK's own retry stack doesn't multiply attempts, and threads an external AbortSignal into both the sleep and the in-flight HTTP call. `restampIfDemotedToTitleTier` restamps a `per_chunk_synopsis` page's CR state to `'title'` after a plain re-embed so `contextual_retrieval_mode` keeps describing the vectors actually in the column (the reindex sweep restores the synopsis tier later). `src/commands/embed.ts` re-exports everything here (façade rule) so import sites and tests never chase the peel.diff --git a/docs/architecture/key-files/security.md b/docs/architecture/key-files/security.mdindex 0bd09582a0..358dbd96a7 100644--- a/docs/architecture/key-files/security.md+++ b/docs/architecture/key-files/security.md@@ -15,7 +15,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/guardrails.ts` — vendor-neutral content guardrail seams (`registerGuardrailProvider`, `classify`). `loadGuardrailProvidersFromEnv(env = process.env, opts?: { cwd, skipCwdCheck })` accepts ONLY an absolute path or a `~/` path for `GBRAIN_GUARDRAILS_MODULE`; cwd-relative specs (`./`, `../`, bare `.`) and bare package specifiers (`pkg`, `@scope/pkg`, `pkg/sub` — in the compiled binary Bun's module walk-up starts at the cwd, so a hostile checkout's `node_modules/<name>/` would load) throw `GuardrailLoadError` before any import, and when `env` is `process.env` (or `opts.cwd` is given) a spec that a cwd .env file assigns is refused via `cwdDotenvAssignsKey` (message composed from env-trust's `CWD_DOTENV_REMEDIATION`) unless `opts.skipCwdCheck` (preflight's cwd == config-dir case). node:path/url/os are static imports. Registration is counted by EVENTS against a pre-import baseline so import-time side-effect registration and same-id replacement are accepted (#3688 residual). Pinned by `test/guardrails.test.ts` + `test/guardrails-env-load.test.ts`.-- `src/core/oauth-grants.ts` — client-row-locked grant transactions shared by OAuth issuance, code/refresh consumption, and revocation. Preserves scope/resource ceilings and rolls back consumption with replacement writes. Pending consent requests live in a bounded in-memory store (`MAX_PENDING_TOTAL` server-wide, `MAX_PENDING_PER_CLIENT` = 10 awaiting-decision requests per `client_id`; `assertCapacity` prunes expired entries and enforces both ceilings synchronously at the start of `begin()` and again immediately before the insert, with no await in between; decided entries stay until expiry but do not count toward a client's budget) and snapshot current operation and delegation policies. `begin()` rejects revoked or deleted clients before creating a request. `src/commands/serve-http-oauth.ts` authenticates request details, enforces session-bound CSRF decisions, and adds a read-only bootstrap scope hint to scope-less Bearer challenges without changing token authority; `admin/src/pages/OAuthConsent.tsx` renders the existing admin login/approval flow without exposing protected details in the page shell.+- `src/core/oauth-grants.ts` — client-row-locked grant transactions shared by OAuth issuance, code/refresh consumption, and revocation. Preserves scope/resource ceilings and rolls back consumption with replacement writes. `canonicalOAuthResource(requested, canonical)` is the one RFC 8707 resource canonicalizer: with the provider's `resourceUrl` (serve-http passes the /mcp URL derived from the configured public URL, never `Host`), `begin()`, code exchange and refresh map the issuer origin (any trailing slash, default port or host case) to the canonical /mcp resource and refuse anything else with `invalid_target` naming the accepted URL before a request is pending or a code is consumed; stored origin-bound grants canonicalize the same way and pre-resource grants stay valid. serve-http's bearer verifier uses the same function. Pending consent requests live in a bounded in-memory store (`MAX_PENDING_TOTAL` server-wide, `MAX_PENDING_PER_CLIENT` = 10 awaiting-decision requests per `client_id`; `assertCapacity` prunes expired entries and enforces both ceilings synchronously at the start of `begin()` and again immediately before the insert, with no await in between; decided entries stay until expiry but do not count toward a client's budget) and snapshot current operation and delegation policies. `begin()` rejects revoked or deleted clients before creating a request. `src/commands/serve-http-oauth.ts` authenticates request details, enforces session-bound CSRF decisions, and adds a `read write` bootstrap scope hint to scope-less `/mcp` Bearer challenges without changing token authority (`grantScopes` caps every request to the client row's scope, so a read-only row still yields a read-only token); `admin/src/pages/OAuthConsent.tsx` renders the existing admin login/approval flow without exposing protected details in the page shell.- `src/core/oauth-provider.ts` — `GBrainOAuthProvider` implementing the MCP SDK's `OAuthServerProvider` + `OAuthRegisteredClientsStore`. Backed by raw SQL (works on both PGLite and Postgres — OAuth is infrastructure, not a BrainEngine concern). Full OAuth 2.1: `authorize` + `exchangeAuthorizationCode` with PKCE, `client_credentials`, `refresh_token` with rotation, `revokeToken`, `registerClient` (DCR validates redirect_uri is `https://` or loopback per RFC 6749 §3.1.2.1). All tokens + client secrets SHA-256 hashed before storage. Owner-approved authorization codes have a 10-minute TTL. Grant transactions lock the active client row before consuming codes or refresh tokens and creating replacements; revocation uses the same lock. Provider-side S256 PKCE validation is mandatory (`skipLocalPkceValidation=true` prevents the SDK from discarding the verifier first). Existing active-client grants remain usable. `pgArray()` escapes commas/quotes/braces so a comma-bearing redirect_uri can't smuggle a second array element. Legacy `access_tokens` fallback in `verifyAccessToken` honors the original-schema `scopes TEXT[]` column via `normalizeTokenScopes` (NULL = grandfathered `read+write+admin`, so every pre-scopes token is byte-identical; an array is filtered to known scopes and honored as-is, `[]`/all-unknown preserved as deny — a dedicated column is structurally immune to the permissions-object-replacement wipe class), and threads BOTH stored grants off the token's `permissions` JSONB: `source_id` via `parseLegacyTokenScope` and `takes_holders` via `parseTakesHoldersAllowList` (both in `src/core/legacy-token-scope.ts`, shared with the legacy HTTP transport so the two transports cannot drift; `[]` takes-holders preserved as explicit deny-all, missing/non-array → undefined → the `/mcp` dispatch site's fail-closed `['world']`; OAuth-client tokens carry no takes-holders grant pending per-client storage — TODOS.md). `sweepExpiredTokens()` runs on startup in try/catch and returns the count via `RETURNING 1` + array length. RFC hardening: `client_id` folded atomically into the `DELETE WHERE` for both auth-code exchange and refresh rotation (wrong-client paths don't burn the row); refresh-scope-subset enforced against the original grant on the row (RFC 6749 §6, so revoking a scope shrinks existing refresh tokens); `client_id` bound on `revokeToken` (RFC 7009 §2.1); `/token` `redirect_uri` validated against the `/authorize` value (RFC 6749 §4.1.3, empty-string treated as missing not wildcard); `verifyAccessToken`/`getClient` catch only `isUndefinedColumnError` from `src/core/utils.ts` (only SQLSTATE 42703 falls through to legacy; lock timeouts/network blips throw); `dcrDisabled` constructor option lets `serve-http.ts` disable `/register` without monkey-patching the router. Module-private `coerceTimestamp()` normalizes postgres-driver-as-string BIGINT columns to JS numbers at 5 read sites (`getClient` for RFC 7591 §3.2.1 numeric timestamps, `exchangeRefreshToken` + `verifyAccessToken` for the SDK's `typeof === 'number'` check); throws on NaN/Infinity (fail loud at boundary), returns undefined for SQL NULL (callers treat NULL as expired). Not promoted to `utils.ts` — generic BIGINT precision-loss risk. `registerClient` honors `token_endpoint_auth_method: "none"` (RFC 7591 §3.2.1): public PKCE clients store `client_secret_hash = NULL` and the response omits `client_secret`; confidential clients (`client_secret_post` / `client_secret_basic`) keep their one-time-reveal shape; `getClient` normalizes NULL `client_secret_hash` to JS `undefined` so the SDK's clientAuth path accepts public clients. `verifyAccessToken` JOINs `oauth_clients.source_id` (write scope, scalar) + `oauth_clients.federated_read` (read scope, TEXT[]) + `oauth_clients.bound_slug_prefixes` (write fence, TEXT[] — consumed by `enforceClientSlugFence` in `operations.ts`) onto the returned `AuthInfo`; legacy brains degrade via `isUndefinedColumnError` fallback, dropping the newest projection first. `rescopeClient(clientId, {sourceId?, federatedRead?, boundSlugPrefixes?})` is the trusted-operator rescope (CLI `gbrain auth rescope-client`, admin `POST /admin/api/rescope-client`); `boundSlugPrefixes` is tri-state — undefined leaves the binding untouched, `null` clears it, a non-empty array replaces it (explicit empty array rejected as ambiguous deny-all) — so roster churn updates the write fence in place without rotating secrets. with `src/commands/serve-http.ts`: custom `/token` middleware that runs BEFORE the MCP SDK's `clientAuth`. The SDK does plaintext compare against the request's `client_secret`; gbrain stores SHA-256 hashes only, so every confidential-client `/token` request would fail. The middleware detects confidential auth via `Authorization: Basic` header OR `client_secret_post` form body (both shapes per RFC 6749 §2.3.1), verifies via `verifyClient(client_id, presented_secret)` (SHA-256 hash compare), and falls through to the SDK for public PKCE clients (which the SDK's clientAuth still accepts via NULL-`client_secret_hash` normalization). Pinned by `test/oauth-confidential-client.test.ts` (both `client_secret_basic` and `client_secret_post`). `authorize()` only calls `grants.begin()` and redirects to `/admin/?oauth_request=<id>#oauth-consent`; codes are minted solely in `OAuthGrants.decide()` behind the admin cookie session and session-bound CSRF. `registerClient` (the unauthenticated DCR store method) computes the `grant_types` default (`authorization_code`) BEFORE the scope block, then calls `dcrScopeViolation` once and throws `InvalidClientMetadataError` (HTTP 400) on a privileged request — rejected, never silently dropped — before the unknown-scope filter runs; a registration that omits `scope` registers an empty scope (no default scope) and its consent request carries `scopes: []`. `allowClientCredentialsDcr` (`--enable-dcr-insecure`) yields anonymous READ-ONLY machine clients; that gate is evaluated BEFORE `dcrScopeViolation`, so a `client_credentials` request without the flag gets 'not permitted via dynamic client registration' rather than the misleading 'limited to `read`' ceiling message (pinned in `test/oauth-dcr-scope-ceiling.test.ts`). Downstream is already bounded: `OAuthGrants.begin()` snapshots the intersected grant, `exchangeCode` and `verifyAccessToken` re-intersect with the client's current scope. Operator paths (`registerClientManual`, CLI, admin API) do not use this store method and accept every canonical scope. Pinned in-process by `test/oauth-consent-security.test.ts` (live SDK `/register` with a foreign `redirect_uri`), against the real server by `test/e2e/serve-http-consent.test.ts`, and for the ceiling by `test/oauth-dcr-scope-ceiling.test.ts` + `test/oauth-authorize-scope-default.test.ts` (DCR client: `/authorize` `read write admin` -> code `['read','write']`, `admin` alone -> `[]`).diff --git a/docs/architecture/key-files/shared-skills.md b/docs/architecture/key-files/shared-skills.mdindex ff8a99dc8d..3d70430312 100644--- a/docs/architecture/key-files/shared-skills.md+++ b/docs/architecture/key-files/shared-skills.md@@ -1,7 +1,7 @@# Shared brain skills- `src/core/shared-skills/{model,manifest,policy,catalog,compatibility,tool-access}.ts` defines source-incarnation-qualified skill keys, bounded declared files, versioned disclosure policy, sealed catalog reads, authorized opaque views and legacy response projections. Tool/resource requirements use the same scope, snapshot, surface and publication constraints as dispatch. Existing positive publication consent remains prose-only; metadata for unapproved files is not returned.-- `src/core/shared-skills/publication.ts` prepares complete skill and shared-dependency revisions through the canonical journal. Compare-and-swap checks cover the skill, pack and every affected closure. Sealed inventory is checked against current head keys; only affected revision bodies are loaded. Generated inventory fields are rebuilt rather than duplicated in durable intents, and canonical manifests keep one compact inventory entry per line. Host adoption retains original caller intent and inventory hashes across replay; no fake page row anchors a skill revision. `knowledge-guard.ts` keeps page/sync/restore aliases from changing declared skill paths.+- `src/core/shared-skills/publication.ts` prepares complete skill and shared-dependency revisions through the canonical journal. Compare-and-swap checks cover the skill, pack and every affected closure. Sealed inventory is checked against current head keys; only affected revision bodies are loaded. Generated inventory fields are rebuilt rather than duplicated in durable intents, and canonical manifests keep one compact inventory entry per line. Host adoption retains original caller intent and inventory hashes across replay; no fake page row anchors a skill revision. `knowledge-guard.ts` keeps page/sync/restore aliases from changing declared skill paths. A relative or host-only `file://` alias names no local file and is ignored; an absolute file URI that cannot be resolved refuses with `invalid_source_uri` (not `skill_bundle_required`).- `src/core/shared-skills/{schema-all,schema,persistence-schema,membership-schema,access-schema}.ts` supplies shared schema migration/bootstrap SQL. Access DDL explicitly enables row-level security for bypass-capable owners even when the database-wide event trigger is unavailable. Protocol guards reject old consumer claims and writes before filesystem effects. `src/core/persistence/{protocol,skill-activation,bundle-files}.ts` implements explicit owner/quiescence activation and bounded whole-set recovery while preserving the existing page target and permanent receipt identity.- `src/core/shared-skills/{membership,membership-authority,membership-types,adapter}.ts` implements own-principal enrollment, source/policy-bound follow approval, issued batch acknowledgments and conflict-safe immutable local caches. Acknowledgments are self-reported delivery, never vendor-native activation. Enforced library admission rechecks freshness and requirements; native instruction routers remain advisory until separately observed.- `src/core/harness/{shared-skills,native-router}.ts` connects the enrollment protocol to target-local installation and ownership-tracked Claude Code, Codex and opencode router placement. Native registration, restart and actual task use are separate states. Removal keeps modified files and reports retained native state.diff --git a/docs/architecture/thin-client.md b/docs/architecture/thin-client.mdindex c9d7e71266..27efbe64f4 100644--- a/docs/architecture/thin-client.md+++ b/docs/architecture/thin-client.md@@ -24,10 +24,14 @@ grant authority: profiles, token scopes, operation snapshots, sources, and writefences still restrict requests. A `memory-writer` thin client gains neitheradministration nor delegation from its full surface.-OAuth bootstrap challenges advertise `scope="read"` without enforcing it as a-literal transport requirement. Existing writer, administrator, and delegated-tokens keep their granted authority. New generic connections following the-hint start read-only; writing requires an explicit authorized scope request.+OAuth bootstrap challenges advertise `scope="read write"` without enforcing it+as a literal transport requirement. Existing writer, administrator, and+delegated tokens keep their granted authority. A connection following the hint+receives only what its client row allows (`grantScopes` caps every request to+the row's `scope`), so a read-only row still yields a read-only token. The hint+lists `write` because some authorization_code clients (claude.ai custom+connectors) request exactly the hinted scope and never step up after an+`insufficient_scope` tool error, which left writer rows permanently read-only.Discovery excludes `agent`, which DCR cannot grant, while explicit DCR requestsfor delegation remain rejected.diff --git a/docs/architecture/topologies.md b/docs/architecture/topologies.mdindex 7377ab1d29..648369ff05 100644--- a/docs/architecture/topologies.md+++ b/docs/architecture/topologies.md@@ -522,6 +522,13 @@ over provider work. Losing the claim cancels that invocation; the finalinstallation still verifies its token. Caller cancellation, per-providertimeouts and budget admission remain effective without a whole-page deadline.+The same command handles parked Git and withdrawal work. A target that fails five+consecutive times is parked: its scan moves on, the effect never reports+complete, and `gbrain doctor` (`parked_effects`) names the page with the exact+command. Fix the cause, preview with `--dry-run`, then run it without+`--dry-run` to authorize one more attempt per parked target. A target that fails+again parks again; each invocation authorizes one attempt.+Direct `--brain <mount>` retry uses only the selected database's validated activecolumn and recorded model provenance for inspection and explicit queue approval.Unknown or inconsistent provenance refuses the action; the host brain's modeldiff --git a/docs/guides/concurrent-writes.md b/docs/guides/concurrent-writes.mdindex 92c9782660..1eef79776f 100644--- a/docs/guides/concurrent-writes.md+++ b/docs/guides/concurrent-writes.md@@ -611,8 +611,8 @@ Default admission limits are enforced atomically:| --- | ---: | ---: || Outstanding requests | 100 | 1,000 || Queued intent bytes | 32 MiB | 256 MiB |-| Lifetime request IDs | 100,000 | 1,000,000 |-| Terminal receipt reservation | 128 MiB | 1 GiB |+| Lifetime request IDs | 250,000 | 1,000,000 |+| Terminal receipt reservation | 1.5 GiB | 8 GiB || Recovery bytes | — | 1 GiB, also 256 MiB per worktree |Completion space is reserved at admission. Beforeimage/recovery bytes are@@ -620,4 +620,30 @@ reserved before filesystem publication. Reaching a limit refuses additionalwork; it does not discard an accepted request to make room. Terminal diagnosticcompaction has a default eligibility threshold of 30 days and preserves replay IDs, digests, terminaloutcomes, and frozen memory-verb result fields. Pending/recovering requests are-not evicted. Lifetime IDs and replay protection are not silently reset.+not evicted, and receipts with unfinished effects stay retained without+blocking compaction of later receipts. Lifetime IDs and replay protection are+not silently reset.++Each admission reserves at least 16 KiB of receipt bytes until compaction; a+compacted receipt keeps about 4 KiB. The cumulative defaults cover one+principal admitting about 600 writes a day for at least a year. Every limit and+the retention window are brain-wide database settings:++```bash+gbrain config set persistence.limits.principal_lifetime_ids 500000+gbrain config set persistence.limits.principal_terminal_bytes 3221225472+gbrain config set persistence.receipt_retention_days 7+```++**Say to your agent:** *"Doctor says my brain is near its write capacity. Raise the limit it names."*++Keys are `persistence.limits.<limit>` for `principal_outstanding`,+`brain_outstanding`, `principal_intent_bytes`, `brain_intent_bytes`,+`principal_lifetime_ids`, `brain_lifetime_ids`, `principal_terminal_bytes`,+`brain_terminal_bytes`, `brain_recovery_bytes` and `worktree_recovery_bytes`,+each a nonnegative integer. `gbrain doctor` warns (`persistence_capacity`) once+a principal or the brain uses 80% of its lifetime IDs or receipt bytes and+prints the `gbrain config set` command with a value that covers about one more+year at the current admission rate; a `queue_capacity` refusal carries the same+command. Raising a cap is a mitigation: lifetime IDs remain permanent replay+protection.diff --git a/docs/operations/spend-controls.md b/docs/operations/spend-controls.mdindex 360a934e38..33c1fb87f0 100644--- a/docs/operations/spend-controls.md+++ b/docs/operations/spend-controls.md@@ -124,6 +124,35 @@ estimate is `delta + stale backlog`, labeled as such.toward their ceiling; a run that hits its cap needs a higher cap, not a bugreport.+## Dream paid-loop breaker (`dream.breaker.max_dead_submissions`)++Dream synthesize and patterns pay a model for each transcript or reflection set+they submit. When the same input keeps failing, every cycle used to pay for it+again. The breaker stops that: once one dream key has died 3 times within 24+hours, dream refuses to submit it again until you reset it. The refusal shows up+in the cycle summary and the autopilot log with the exact reset command, and+`gbrain doctor` reports it as `dream_paid_loop`.++**Say to your agent:** *"Is dream re-billing the same transcripts?"* or+*"Reset the dream key that keeps failing once you've fixed it."*++```bash+gbrain dream reset-key --list # tripped keys, counts, reset commands+gbrain dream reset-key 'dream:synth-v2:...' # re-enable one key (persists across restarts)+gbrain config set dream.breaker.max_dead_submissions 5 # raise the limit; 0 disables+```++- A submission is one run of a key: the chunks of one transcript in one run count+ once. Only jobs that ended dead count; completed jobs, including a legitimate+ answer that wrote nothing, never do.+- The check happens before synthesis submission. Transcript triage for that run may+ already have happened, so the promise is "no synthesis submission", not "no+ model call at all".+- Not covered: a transcript that keeps growing gets a new content-hashed key each+ cycle, and patterns runs outside maintenance carry no key.+- If the count query fails, the breaker is skipped for that run with a warning, the+ same posture as the synthesize daily cap.+## Operator price overrides (`pricing.overrides`)Cost caps are fail-closed: when `--max-cost` (or a phase's default cap) is setdiff --git a/docs/storage-tiering.md b/docs/storage-tiering.mdindex 6812fa9478..9ca0452f78 100644--- a/docs/storage-tiering.md+++ b/docs/storage-tiering.md@@ -44,6 +44,7 @@ Path requirements:When storage configuration is present, `gbrain sync` automatically manages `.gitignore` entries on every successful sync:- Adds missing `db_only` directory patterns to `.gitignore`.+- A file under a `db_only` directory that git already tracked before the declaration stays tracked and shows as modified once the database updates it; untrack it with `git rm --cached <path>`.- Idempotent — re-running adds no duplicate entries.- Stable comment header so the managed block is grep-able.- Skipped on `--dry-run` (don't mutate disk in preview mode).diff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex d396e6ba01..6151d5b4a9 100644--- a/openclaw.plugin.json+++ b/openclaw.plugin.json@@ -1,7 +1,7 @@{"id": "gbrain-context-engine","name": "gbrain",- "version": "0.59.20.0",+ "version": "0.60.5.0","description": "Personal knowledge brain with Postgres + pgvector hybrid search","family": "bundle-plugin","kind": "context-engine",diff --git a/package.json b/package.jsonindex 3677e90153..4617b6bb87 100644--- a/package.json+++ b/package.json@@ -191,7 +191,7 @@"bun": ">=1.3.11"},"license": "MIT",- "version": "0.59.20.0",+ "version": "0.60.5.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 1a67fbc0a6..fec0c62f00 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.59.20.0",+ "version": "0.60.5.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 — 21 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 2c98a277b9..9f100b45c8 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.59.20.0",+ "version": "0.60.5.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 — 21 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-coding/README.md b/plugin-variants/gbrain-coding/README.mdindex 0aaeab8fc3..5defd4041b 100644--- a/plugin-variants/gbrain-coding/README.md+++ b/plugin-variants/gbrain-coding/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.59.20.0 -->+<!-- gbrain-plugin-tree-stamp: 0.60.5.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 31b9d8944b..712c89e6bb 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.59.20.0",+ "version": "0.60.5.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 — 20 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 819bf13189..b16f8ef178 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.59.20.0",+ "version": "0.60.5.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 — 20 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-daily/README.md b/plugin-variants/gbrain-daily/README.mdindex 3e074e7269..e07b1e98cb 100644--- a/plugin-variants/gbrain-daily/README.md+++ b/plugin-variants/gbrain-daily/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.59.20.0 -->+<!-- gbrain-plugin-tree-stamp: 0.60.5.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 f543e49448..ed90957039 100644--- a/plugin/README.md+++ b/plugin/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.59.20.0 -->+<!-- gbrain-plugin-tree-stamp: 0.60.5.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 0201907a54..3a39549641 100644--- a/scripts/e2e-test-map.ts+++ b/scripts/e2e-test-map.ts@@ -46,7 +46,7 @@ export const E2E_TEST_MAP: Record<string, string[]> = {"src/core/company-brain/receipt-schema.ts": ["test/e2e/company-brain-receipts.test.ts"],"src/core/minions/errors.ts": ["test/e2e/subagent-gateway-path.test.ts", "test/e2e/delegated-http-worker.test.ts", "test/e2e/subagent-crash-replay-multi-provider.test.ts"],"src/core/harness/**": ["test/e2e/harness-access.test.ts", "test/e2e/shared-skills-transports.test.ts"],- "src/core/shared-skills/**": ["test/e2e/shared-skills-transports.test.ts", "test/e2e/shared-skills-rls.test.ts", "test/e2e/persistence-skill-bundles-postgres.test.ts"],+ "src/core/shared-skills/**": ["test/e2e/shared-skills-transports.test.ts", "test/e2e/shared-skills-rls.test.ts", "test/e2e/persistence-skill-bundles-postgres.test.ts", "test/e2e/knowledge-source-uri-postgres.test.ts"],"src/mcp/skill-resources.ts": ["test/e2e/shared-skills-transports.test.ts"],"src/core/scope.ts": ["test/e2e/client-grants.test.ts", "test/e2e/shared-skills-transports.test.ts"],"src/core/grants/**": ["test/e2e/client-grants.test.ts", "test/e2e/harness-access.test.ts", "test/e2e/delegated-grants-withdrawal.test.ts", "test/e2e/delegated-http-worker.test.ts"],@@ -74,10 +74,11 @@ export const E2E_TEST_MAP: Record<string, string[]> = {// Concrete content and derived-information read policy parity."src/core/remote-body.ts": ["test/e2e/engine-content-privacy.test.ts", "test/e2e/legacy-chunk-privacy.test.ts", "test/e2e/chunk-canonical-text-privacy.test.ts"],"src/core/entity-identity.ts": ["test/e2e/engine-content-privacy.test.ts"],- "src/core/ops/**": ["test/e2e/engine-content-privacy.test.ts", "test/e2e/read-enrichment-privacy.test.ts", "test/e2e/legacy-chunk-privacy.test.ts", "test/e2e/chunk-canonical-text-privacy.test.ts", "test/e2e/put-page-persistence-postgres.test.ts", "test/e2e/deep-research-source-id.test.ts", "test/e2e/deep-research-http.test.ts"],+ "src/core/ops/**": ["test/e2e/engine-content-privacy.test.ts", "test/e2e/read-enrichment-privacy.test.ts", "test/e2e/legacy-chunk-privacy.test.ts", "test/e2e/chunk-canonical-text-privacy.test.ts", "test/e2e/put-page-persistence-postgres.test.ts", "test/e2e/deep-research-source-id.test.ts", "test/e2e/deep-research-http.test.ts", "test/e2e/derived-page-visibility.test.ts"],"src/commands/whoknows.ts": ["test/e2e/read-enrichment-privacy.test.ts"],"src/commands/orphans.ts": ["test/e2e/engine-content-privacy.test.ts"],// Source-aware ranking, hybrid search, intent classification.+ "src/core/search/private-visibility.ts": ["test/e2e/derived-page-visibility.test.ts", "test/e2e/derived-visibility-repair.test.ts"],"src/core/search/**": ["test/e2e/unsupported-embedding-identity-postgres.test.ts","test/e2e/projection-statistics-postgres.test.ts",@@ -91,7 +92,9 @@ export const E2E_TEST_MAP: Record<string, string[]> = {"test/e2e/search-exclude.test.ts","test/e2e/search-swamp.test.ts",],- "src/core/page-state/**": ["test/e2e/projection-recovery-parity.test.ts", "test/e2e/projection-readiness-currency.test.ts", ...MIGRATION_WAVE_TESTS],+ "src/core/page-state/**": ["test/e2e/projection-recovery-parity.test.ts", "test/e2e/projection-readiness-currency.test.ts", "test/e2e/projection-embedding-input-hash.test.ts", "test/e2e/safe-chunk-reseal.test.ts", ...MIGRATION_WAVE_TESTS],+ "src/core/embedding-input-hash.ts": ["test/e2e/projection-embedding-input-hash.test.ts"],+ "src/core/search/safe-chunks.ts": ["test/e2e/safe-chunk-reseal.test.ts", "test/e2e/legacy-chunk-privacy.test.ts"],"src/core/code-chunks.ts": ["test/e2e/projection-recovery-parity.test.ts"],"src/core/markdown-chunks.ts": ["test/e2e/projection-recovery-parity.test.ts"],// Tree-sitter chunkers feed code-indexing E2E.@@ -126,7 +129,9 @@ export const E2E_TEST_MAP: Record<string, string[]> = {// JSONB bind parity for the cycle writers (the #2339 class PGLite hides)."src/core/cycle/propose-takes.ts": ["test/e2e/propose-takes-jsonb-postgres.test.ts"],"src/core/cycle/calibration-profile.ts": ["test/e2e/calibration-profile-write.test.ts"],- "src/core/cycle/patterns.ts": ["test/e2e/multi-source-bug-class.test.ts"],+ "src/core/cycle/patterns.ts": ["test/e2e/multi-source-bug-class.test.ts", "test/e2e/dream-breaker-postgres.test.ts"],+ // Dream paid-loop breaker: released-key JSONB shape + counter + migration 173 on Postgres.+ "src/core/cycle/dream-breaker.ts": ["test/e2e/dream-breaker-postgres.test.ts"],"src/core/cycle/synthesize.ts": ["test/e2e/multi-source-bug-class.test.ts","test/e2e/synthesize-bigint-job-id-postgres.test.ts",@@ -156,7 +161,7 @@ export const E2E_TEST_MAP: Record<string, string[]> = {"src/core/embedding-readiness.ts": ["test/e2e/embedding-recovery-parity.test.ts"],"src/core/facts/embedding-identity.ts": ["test/e2e/embedding-recovery-parity.test.ts", "test/e2e/fact-embedding-backfill-parity.test.ts"],"src/core/stored-embedding-identity.ts": ["test/e2e/unsupported-embedding-identity-postgres.test.ts"],- "src/commands/extract.ts": ["test/e2e/multi-source-bug-class.test.ts", "test/e2e/attendance-retrieval-postgres.test.ts", "test/e2e/extract-timeline-attendance-postgres.test.ts"],+ "src/commands/extract.ts": ["test/e2e/multi-source-bug-class.test.ts", "test/e2e/attendance-retrieval-postgres.test.ts", "test/e2e/extract-timeline-attendance-postgres.test.ts", "test/e2e/w5-persistence-postgres.test.ts"],"src/commands/extract-attendance-repair.ts": ["test/e2e/attendance-repair-postgres.test.ts"],"src/commands/migrate-engine.ts": ["test/e2e/multi-source-bug-class.test.ts",@@ -191,6 +196,7 @@ export const E2E_TEST_MAP: Record<string, string[]> = {"src/core/persistence/**": ["test/e2e/persistence-http-liveness.test.ts","test/e2e/persistence-phase-liveness.test.ts",+ "test/e2e/persistence-idle-pool.test.ts","test/e2e/persistence-publication-parity.test.ts","test/e2e/persistence-sync-origin-parity.test.ts","test/e2e/persistence-sync-options-parity.test.ts",@@ -222,7 +228,17 @@ export const E2E_TEST_MAP: Record<string, string[]> = {"test/e2e/reconcile-pgbouncer.test.ts","test/e2e/persistence-skill-bundles-postgres.test.ts","test/e2e/shared-skills-transports.test.ts",+ "test/e2e/canonical-projection-history.test.ts",+ "test/e2e/derived-page-visibility.test.ts",+ "test/e2e/timeline-materialize.test.ts",+ "test/e2e/derived-visibility-repair.test.ts",+ "test/e2e/repair-command.test.ts",+ "test/e2e/w5-persistence-postgres.test.ts",],+ "src/core/brain-score-recommendations.ts": ["test/e2e/w5-persistence-postgres.test.ts"],+ "src/core/repair/**": ["test/e2e/repair-command.test.ts", "test/e2e/derived-visibility-repair.test.ts", "test/e2e/safe-chunk-reseal.test.ts"],+ "src/commands/repair.ts": ["test/e2e/repair-command.test.ts"],+ "src/core/timeline-marker.ts": ["test/e2e/timeline-materialize.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", "test/e2e/managed-extract-atoms.test.ts", "test/e2e/managed-atom-regressions.test.ts", "test/e2e/managed-atom-compaction.test.ts"],"src/core/cycle/synthesize*.ts": ["test/e2e/managed-maintenance.test.ts", "test/e2e/managed-synthesis-postprocess.test.ts"],diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 9a1bda18c6..699f2a6848 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -3,27 +3,27 @@# Raising a ceiling is a conscious, reviewer-visible act. Lower ceilings in# the same commit as any peel (the guard fails on >50 lines of stale slack).# Columns: path max_lines policy note-src/cli.ts 4124 ratchet +2 export engine-free detailed help dispatch; +48 fix wave: get_versions --json + honest ellipsis (#4692), boolean-flag literal true/false consume (#4602); grown v0.46.26.0 megawave: SIGCHLD reaper install, silent-failure surfacing, confirm-race gate (#2443 #2898 #2297); grown wave-g (#4488 #4508): in-band error exit codes + think --source validation; grown db-availability loop: engine/db-repair dispatch, degraded-serve catch, marker choke points (bottom handler + no-config exit + doctor fallback), engine-free config-set dispatch; fix cycle: static classifier imports, resolved-brain degraded gate, guarded reconnect, help rows; +chat-connectors wiring (master merge); wave-k +24 for #4083 auth self-help entry + top-level auth usage lines + takes self-help branch; +master-merge true-up; +20 gbrain backup pre-engine dispatch + startup backup nag rail (monthly backup check); wave-k: +24 for #4083 auth self-help entry + top-level auth usage lines + takes self-help branch; +3: doctor --no-migrate probeOnly seam (#4364); +37 v0.47 gmail-loops: google/creds dispatch + waiting/loops cases + self-help entries + OPEN LOOPS help section; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: CLI combines hosted access and explicit legacy queue review; lowered to 4077: GHSA wave v0.50.5.0 moved the #3688 guardrails block into core/cli-preflight.ts (-10); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; #5252 wave: partial-retrieval notices and resident code reindex delegation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared skills: parse typed object/array operation flags before resident-owner delegation; merged reliability/shared-skills source integration Explicit-policy thin recall routing before local engine connection; actual CLI subprocess regression coverage. Reject explicit thin recall brain selection before dispatch.; +10 A2 preview-bound attendance repair dispatch and help; integrated upstream provider retirement with thin recall and gated repair dispatch; +4 strict pre-engine rejection of unsupported brain-wide migration narrowing flags; merged upstream: 48 fix wave: get_versions --json + honest ellipsis (#4692), boolean-flag literal true/false consume (#4602); grown v0.46.26.0 megawave: SIGCHLD reaper install, silent-failure surfacing, confirm-race gate (#2443 #2898 #2297); grown wave-g (#4488 #4508): in-band error exit codes + think --source validation; grown db-availability loop: engine/db-repair dispatch, degraded-serve catch, marker choke points (bottom handler + no-config exit + doctor fallback), engine-free config-set dispatch; fix cycle: static classifier imports, resolved-brain degraded gate, guarded reconnect, help rows; +chat-connectors wiring (master merge); wave-k +24 for #4083 auth self-help entry + top-level auth usage lines + takes self-help branch; +master-merge true-up; +20 gbrain backup pre-engine dispatch + startup backup nag rail (monthly backup check); wave-k: +24 for #4083 auth self-help entry + top-level auth usage lines + takes self-help branch; +3: doctor --no-migrate probeOnly seam (#4364); +37 v0.47 gmail-loops: google/creds dispatch + waiting/loops cases + self-help entries + OPEN LOOPS help section; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: CLI combines hosted access and explicit legacy queue review; lowered to 4077: GHSA wave v0.50.5.0 moved the #3688 guardrails block into core/cli-preflight.ts (-10); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; #5252 wave: partial-retrieval notices and resident code reindex delegation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared skills: parse typed object/array operation flags before resident-owner delegation; merged reliability/shared-skills source integration Explicit-policy thin recall routing before local engine connection; actual CLI subprocess regression coverage. Reject explicit thin recall brain selection before dispatch.; +10 A2 preview-bound attendance repair dispatch and help; integrated upstream provider retirement with thin recall and gated repair dispatch; typed readiness, configuration-blocked lifecycle and bounded release-src/commands/autopilot.ts 2725 ratchet grown v0.46.26.0 megawave (#4300 #4285 #3696) + master v0.46.27.0 env-file lane + boot warning + reload-safe install (#2608 #4443) + 1 nosemgrep dataflow annotation (path-traversal audit); +chat-connectors wiring; +20 #4728 wrapper exec guard (baked CLI path gone -> PATH fallback / --install hint); +5 #4952 (refs #4399): syncEnabled=false skip in the freshness dispatch loop; typed readiness, configuration-blocked lifecycle and bounded release; +3 guard transaction callbacks and roll back on configuration block-src/commands/doctor.ts 4593 ratchet grown v0.46.26.0 megawave: silent-death checks, self-upgrade honesty, noise pruning (#3944 #3925 #3958); +21 lines (#4518: don't assert "supervisor not running" when the --fast mode DB-lock fallback was never attempted); +12 lines (#2036/#4484: schema_version warns on forward DB skew); +12 lines (#4476: oversized_pages excludes embed_skip pages via canonical EMBED_SKIP_FILTER_FRAGMENT); merged wave-g-prs (#4421 #4425 #4517 #4519): one in-branch live-column diff on detectMissingColumns + engine-aware superseded upgrade-error suppression (explicit ok); grown db-availability loop: classified connection check + synthesized total-outage entry + hoisted pgbouncer helper + engine-fit check wiring + report engine/db_url_source fields; +chat-connectors wiring (master merge); +12 lines (#2036/#4484: schema_version warns on forward DB skew via schemaVersionHealth); merged wave-g-prs (#4421 #4425 #4517 #4519): in-branch live-column diff + engine-aware superseded upgrade-error suppression; wave-k: schema_columns emitted as its own check inside the ledger-current branch (gbrain#4421), schema_version via schemaVersionHealth module, conversation_format_coverage peeled to doctor/checks/conversation-coverage.ts (#4193); +7 backup_coverage check registration (monthly backup check); +master-merge true-up; wave-k: schema_columns emitted as its own check inside the ledger-current branch (gbrain#4421), schema_version via schemaVersionHealth module, conversation_format_coverage peeled to doctor/checks/conversation-coverage.ts (#4193); +9 v0.47 gmail-loops: google_oauth vault-health check dispatch; +17 (#4712: git-root-pinned source skip note wiring + all-skipped warn-not-ok status for multi_source_drift); +8 memorable_relay_health wiring (check itself is a peel: doctor/checks/integrations-memorable.ts); +9 ambient-writeback WP6: memory_writeback check registration (logic lives in doctor/checks/memory-writeback.ts); +14 default_source_local_path registration (#4739 — check body peeled to doctor/checks/default-source-path.ts); +9 atom_provenance_drift registration (#4566 — check body lives in doctor/checks/extraction-sync.ts); master: | merged v0.48.1.0 true-up; #5252 wave: scoped projection readiness registration; shared content: register the separately scoped canonical publication/recovery check; merged reliability/shared-skills source integration+src/cli.ts 4136 ratchet +2 export engine-free detailed help dispatch; +48 fix wave: get_versions --json + honest ellipsis (#4692), boolean-flag literal true/false consume (#4602); grown v0.46.26.0 megawave: SIGCHLD reaper install, silent-failure surfacing, confirm-race gate (#2443 #2898 #2297); grown wave-g (#4488 #4508): in-band error exit codes + think --source validation; grown db-availability loop: engine/db-repair dispatch, degraded-serve catch, marker choke points (bottom handler + no-config exit + doctor fallback), engine-free config-set dispatch; fix cycle: static classifier imports, resolved-brain degraded gate, guarded reconnect, help rows; +chat-connectors wiring (master merge); wave-k +24 for #4083 auth self-help entry + top-level auth usage lines + takes self-help branch; +master-merge true-up; +20 gbrain backup pre-engine dispatch + startup backup nag rail (monthly backup check); wave-k: +24 for #4083 auth self-help entry + top-level auth usage lines + takes self-help branch; +3: doctor --no-migrate probeOnly seam (#4364); +37 v0.47 gmail-loops: google/creds dispatch + waiting/loops cases + self-help entries + OPEN LOOPS help section; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: CLI combines hosted access and explicit legacy queue review; lowered to 4077: GHSA wave v0.50.5.0 moved the #3688 guardrails block into core/cli-preflight.ts (-10); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; #5252 wave: partial-retrieval notices and resident code reindex delegation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared skills: parse typed object/array operation flags before resident-owner delegation; merged reliability/shared-skills source integration Explicit-policy thin recall routing before local engine connection; actual CLI subprocess regression coverage. Reject explicit thin recall brain selection before dispatch.; +10 A2 preview-bound attendance repair dispatch and help; integrated upstream provider retirement with thin recall and gated repair dispatch; +4 strict pre-engine rejection of unsupported brain-wide migration narrowing flags; merged upstream: 48 fix wave: get_versions --json + honest ellipsis (#4692), boolean-flag literal true/false consume (#4602); grown v0.46.26.0 megawave: SIGCHLD reaper install, silent-failure surfacing, confirm-race gate (#2443 #2898 #2297); grown wave-g (#4488 #4508): in-band error exit codes + think --source validation; grown db-availability loop: engine/db-repair dispatch, degraded-serve catch, marker choke points (bottom handler + no-config exit + doctor fallback), engine-free config-set dispatch; fix cycle: static classifier imports, resolved-brain degraded gate, guarded reconnect, help rows; +chat-connectors wiring (master merge); wave-k +24 for #4083 auth self-help entry + top-level auth usage lines + takes self-help branch; +master-merge true-up; +20 gbrain backup pre-engine dispatch + startup backup nag rail (monthly backup check); wave-k: +24 for #4083 auth self-help entry + top-level auth usage lines + takes self-help branch; +3: doctor --no-migrate probeOnly seam (#4364); +37 v0.47 gmail-loops: google/creds dispatch + waiting/loops cases + self-help entries + OPEN LOOPS help section; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: CLI combines hosted access and explicit legacy queue review; lowered to 4077: GHSA wave v0.50.5.0 moved the #3688 guardrails block into core/cli-preflight.ts (-10); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; #5252 wave: partial-retrieval notices and resident code reindex delegation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared skills: parse typed object/array operation flags before resident-owner delegation; merged reliability/shared-skills source integration Explicit-policy thin recall routing before local engine connection; actual CLI subprocess regression coverage. Reject explicit thin recall brain selection before dispatch.; +10 A2 preview-bound attendance repair dispatch and help; integrated upstream provider retirement with thin recall and gated repair dispatch; typed readiness, configuration-blocked lifecycle and bounded release; +12 wave-2 W3: gbrain repair dispatch, engine-free help, thin-client refusal and help row+src/commands/autopilot.ts 2726 ratchet grown v0.46.26.0 megawave (#4300 #4285 #3696) + master v0.46.27.0 env-file lane + boot warning + reload-safe install (#2608 #4443) + 1 nosemgrep dataflow annotation (path-traversal audit); +chat-connectors wiring; +20 #4728 wrapper exec guard (baked CLI path gone -> PATH fallback / --install hint); +5 #4952 (refs #4399): syncEnabled=false skip in the freshness dispatch loop; typed readiness, configuration-blocked lifecycle and bounded release; +3 guard transaction callbacks and roll back on configuration block; +1 #5609: shared staleExtractionBlocked probe in the dispatch-plan context+src/commands/doctor.ts 4603 ratchet grown v0.46.26.0 megawave: silent-death checks, self-upgrade honesty, noise pruning (#3944 #3925 #3958); +21 lines (#4518: don't assert "supervisor not running" when the --fast mode DB-lock fallback was never attempted); +12 lines (#2036/#4484: schema_version warns on forward DB skew); +12 lines (#4476: oversized_pages excludes embed_skip pages via canonical EMBED_SKIP_FILTER_FRAGMENT); merged wave-g-prs (#4421 #4425 #4517 #4519): one in-branch live-column diff on detectMissingColumns + engine-aware superseded upgrade-error suppression (explicit ok); grown db-availability loop: classified connection check + synthesized total-outage entry + hoisted pgbouncer helper + engine-fit check wiring + report engine/db_url_source fields; +chat-connectors wiring (master merge); +12 lines (#2036/#4484: schema_version warns on forward DB skew via schemaVersionHealth); merged wave-g-prs (#4421 #4425 #4517 #4519): in-branch live-column diff + engine-aware superseded upgrade-error suppression; wave-k: schema_columns emitted as its own check inside the ledger-current branch (gbrain#4421), schema_version via schemaVersionHealth module, conversation_format_coverage peeled to doctor/checks/conversation-coverage.ts (#4193); +7 backup_coverage check registration (monthly backup check); +master-merge true-up; wave-k: schema_columns emitted as its own check inside the ledger-current branch (gbrain#4421), schema_version via schemaVersionHealth module, conversation_format_coverage peeled to doctor/checks/conversation-coverage.ts (#4193); +9 v0.47 gmail-loops: google_oauth vault-health check dispatch; +17 (#4712: git-root-pinned source skip note wiring + all-skipped warn-not-ok status for multi_source_drift); +8 memorable_relay_health wiring (check itself is a peel: doctor/checks/integrations-memorable.ts); +9 ambient-writeback WP6: memory_writeback check registration (logic lives in doctor/checks/memory-writeback.ts); +14 default_source_local_path registration (#4739 — check body peeled to doctor/checks/default-source-path.ts); +9 atom_provenance_drift registration (#4566 — check body lives in doctor/checks/extraction-sync.ts); master: | merged v0.48.1.0 true-up; #5252 wave: scoped projection readiness registration; shared content: register the separately scoped canonical publication/recovery check; merged reliability/shared-skills source integration; +10 fix wave 2 (v0.60.5.0) integration: timeline_history/derived_visibility (+9 W3/W4), parked_effects/persistence_capacity (+6 W5) and dream_paid_loop (+10 W7) registrations used the 15 lines of slack under the prior ceilingsrc/commands/embed.ts 2169 ratchet lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment); #5105: guarded derived projection preparation and read seals; #5105: conditional embedding installer wiring; archived eligibility: active-only dispatch with honest stranded-work reporting; explicit archived admission: live-source snapshots and honest refused-installation failuressrc/commands/extract-conversation-facts.ts 2125 ratchet grown v0.46.x per-provider gateway-unavailable copy; grown wave-g (#4482): expected budget/deadline caps classified apart from error halts; wave-k: save-time resolution caller (#4052/#3729 — supersedes wave-g's per-row resolveEntitySlug mapper); +1: key-aware llm-fallback default (#3813); +1: pricingOverrides wiring into the owned BudgetTracker (#4633 adoption); +3: #4869 snapshot-mismatch counts as pages_failed; merged reliability/shared-skills source integration; +19: additive skip reasons and model-free dry-run (#5364)-src/commands/extract.ts 2578 ratchet grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges; T2: source-qualified inference and atomic origin-scoped derived links; standard DB extraction fences captured endpoint revisions; shared authoritative attendance/source reconciliation moved to the core module; +7 A2 preview-bound attendance repair import, help and authority dispatch; bounded incomplete-attendance diagnostics and consistent basename resolution; fail closed before graph mutation when active ontology is unavailable; +16 source-selected ontology cache, type-scoped preflight and non-starving failed stale drain; +7 write-path wave: per-slug extractors replace page links + retract removed timeline rows + rename-alias resolution-src/commands/jobs.ts 3260 ratchet grown v0.46.26.0 megawave (#4098 #2308) + master v0.46.26.0 worker startup recovery + stats gating; +typed provider-failure logging on the facts-absorb catch (#4308); +chat-connectors wiring (master merge); +16 v0.47 gmail-loops: loops_extract handler + gateway-refresh entry; +8 refs #4599: embed + embed-catch-up handlers fail the job on a stall_timeout result (assertEmbedNotStalled); security: durable queued authority and confined filesystem dispatch; drained cancellation and lease-safe partial results; queued import failures remain failures; master integration: grown v0.46.26.0 megawave (#4098 #2308) + master v0.46.26.0 worker startup recovery + stats gating; +typed provider-failure logging on the facts-absorb catch (#4308); +chat-connectors wiring (master merge); +16 v0.47 gmail-loops: loops_extract handler + gateway-refresh entry; +8 refs #4599: embed + embed-catch-up handlers fail the job on a stall_timeout result (assertEmbedNotStalled); #5105: two-line delegate validates revision and durable authority before fact backstop execution; upstream integration: preserve independently reviewed master additions with branch facade extraction; +13 v0.50.5.0 security merge (upstream delta; coordinated facade retained); merged reliability/shared-skills source integration; +1 #5584: skillopt job reflect_max_tokens (validated + clamped via skillopt/output-cap.ts); lowered #5585: skillopt handler body peeled to skillopt/job.ts (execution-time model re-resolution + strict re-check); typed readiness, configuration-blocked lifecycle and bounded release (issue #5560 merge)-src/commands/serve-http.ts 3098 ratchet registration and grant routes extracted; owner authentication and configured discovery remain in the HTTP facade; one shared bootstrap-token-shape import from serve-service; merged scoped shared-skill resources and named capability checks+src/commands/extract.ts 2604 ratchet grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges; T2: source-qualified inference and atomic origin-scoped derived links; standard DB extraction fences captured endpoint revisions; shared authoritative attendance/source reconciliation moved to the core module; +7 A2 preview-bound attendance repair import, help and authority dispatch; bounded incomplete-attendance diagnostics and consistent basename resolution; fail closed before graph mutation when active ontology is unavailable; +16 source-selected ontology cache, type-scoped preflight and non-starving failed stale drain; +7 write-path wave: per-slug extractors replace page links + retract removed timeline rows + rename-alias resolution; +26 #5609: managed extract --stale publishes links, canonical timeline and watermark per page in one coordinated transaction+src/commands/jobs.ts 3262 ratchet grown v0.46.26.0 megawave (#4098 #2308) + master v0.46.26.0 worker startup recovery + stats gating; +typed provider-failure logging on the facts-absorb catch (#4308); +chat-connectors wiring (master merge); +16 v0.47 gmail-loops: loops_extract handler + gateway-refresh entry; +8 refs #4599: embed + embed-catch-up handlers fail the job on a stall_timeout result (assertEmbedNotStalled); security: durable queued authority and confined filesystem dispatch; drained cancellation and lease-safe partial results; queued import failures remain failures; master integration: grown v0.46.26.0 megawave (#4098 #2308) + master v0.46.26.0 worker startup recovery + stats gating; +typed provider-failure logging on the facts-absorb catch (#4308); +chat-connectors wiring (master merge); +16 v0.47 gmail-loops: loops_extract handler + gateway-refresh entry; +8 refs #4599: embed + embed-catch-up handlers fail the job on a stall_timeout result (assertEmbedNotStalled); #5105: two-line delegate validates revision and durable authority before fact backstop execution; upstream integration: preserve independently reviewed master additions with branch facade extraction; +13 v0.50.5.0 security merge (upstream delta; coordinated facade retained); merged reliability/shared-skills source integration; +1 #5584: skillopt job reflect_max_tokens (validated + clamped via skillopt/output-cap.ts); lowered #5585: skillopt handler body peeled to skillopt/job.ts (execution-time model re-resolution + strict re-check); typed readiness, configuration-blocked lifecycle and bounded release (issue #5560 merge); +2 #5632: sync job passes its explicitly set processing options+src/commands/serve-http.ts 3108 ratchet registration and grant routes extracted; owner authentication and configured discovery remain in the HTTP facade; one shared bootstrap-token-shape import from serve-service; merged scoped shared-skill resources and named capability checks; +10 #5222 resource canonicalizer wiring (issuer/resource declared before the provider, shared verifier) + #5277 read write challenge hintsrc/core/ai/gateway.ts 4441 ratchet +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings-src/commands/sync.ts 5995 ratchet +1 #4786/#3068 pre-landing: pullFailed early return reports the sweep count (comment line); +1 #4786 x #2139 pre-landing: both embed-backfill submit gates require syncProducedEmbeddableContent (import line); re-summed after merging master v0.50.0.0 with the wave (include_hidden, sweep count, cost-gate envelope); +1 wave review: sync trigger --json emits {job_id} JSON; grown v0.46.26.0 megawave: image sync, ingest-log gating, dry-run purity, checkpoint honesty (#2683 #4342 #3875) + 3 nosemgrep dataflow annotations (path-traversal audit); +#2683 residual: status-error failure recording at both import sites; +143 wave G #3974: working-tree drift surfacing + opt-in --working-tree import; grown wave-g (#4412 #4543): break-lock ambient source resolution + named failing files; grown db-availability loop: GBRAIN_DB_ACCESS marker on checkpoint-dead aborts; fix cycle: marker via shared DB_ACCESS_MARKER_PREFIX + shouldEmitDbAccessMarker; wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +master-merge true-up; +25 post-sync backup-coverage stale-only refresh (monthly backup check); wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +1: #4412 refinement — explicit --source stays resolver-free (deleted-source locks breakable); +10 v0.47 gmail-loops: google source-kind dispatch branch; +48 #4667 adoption: persisted sync.exclude config union hoisted above the performFullSync early returns; +22 #4587: all 7 delete lanes swapped to softDeletePages (72h recovery window), decompose comments + summary wording; +16 #4583: seed_default write refusal on bulk-non-default brains (assessDefaultWriteGuard call site + escape-hatch comment); composition true-up (fix-wave multi-train); +33 #4597: trackedSlugIndex.anchorOnlyPaths (slug -> anchor paths that alone proved it) + the self-referential from-path rule in slugLiveness so a fallback rename's own pre-rename duplicate converges under incremental sync; +12 #4888: runSync wraps runSyncInner in withHumanLogsToStderr under --json (stdout = JSON lines only) + help text; wave composition: #4903 stored-strategy honor + #4597 fallback-rename duplicate convergence + #4888 --json stdout purity summed; security: durable queued authority and confined filesystem dispatch; drained cancellation and lease-safe partial results; master integration: +1 wave review: sync trigger --json emits {job_id} JSON; grown v0.46.26.0 megawave: image sync, ingest-log gating, dry-run purity, checkpoint honesty (#2683 #4342 #3875) + 3 nosemgrep dataflow annotations (path-traversal audit); +#2683 residual: status-error failure recording at both import sites; +143 wave G #3974: working-tree drift surfacing + opt-in --working-tree import; grown wave-g (#4412 #4543): break-lock ambient source resolution + named failing files; grown db-availability loop: GBRAIN_DB_ACCESS marker on checkpoint-dead aborts; fix cycle: marker via shared DB_ACCESS_MARKER_PREFIX + shouldEmitDbAccessMarker; wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +master-merge true-up; +25 post-sync backup-coverage stale-only refresh (monthly backup check); wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +1: #4412 refinement — explicit --source stays resolver-free (deleted-source locks breakable); +10 v0.47 gmail-loops: google source-kind dispatch branch; +48 #4667 adoption: persisted sync.exclude config union hoisted above the performFullSync early returns; +22 #4587: all 7 delete lanes swapped to softDeletePages (72h recovery window), decompose comments + summary wording; +16 #4583: seed_default write refusal on bulk-non-default brains (assessDefaultWriteGuard call site + escape-hatch comment); composition true-up (fix-wave multi-train); +33 #4597: trackedSlugIndex.anchorOnlyPaths (slug -> anchor paths that alone proved it) + the self-referential from-path rule in slugLiveness so a fallback rename's own pre-rename duplicate converges under incremental sync; +12 #4888: runSync wraps runSyncInner in withHumanLogsToStderr under --json (stdout = JSON lines only) + help text; wave composition: #4903 stored-strategy honor + #4597 fallback-rename duplicate convergence + #4888 --json stdout purity summed; #5252 wave: post-batch planner statistics refresh; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; merged reliability/shared-skills source integration; +1 cancellation guard before company dispatch-src/core/cycle.ts 3208 ratchet grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail-src/core/cycle/synthesize.ts 3222 ratchet merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring-src/core/cycle/extract-atoms.ts 1752 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration+src/commands/sync.ts 6002 ratchet +1 #4786/#3068 pre-landing: pullFailed early return reports the sweep count (comment line); +1 #4786 x #2139 pre-landing: both embed-backfill submit gates require syncProducedEmbeddableContent (import line); re-summed after merging master v0.50.0.0 with the wave (include_hidden, sweep count, cost-gate envelope); +1 wave review: sync trigger --json emits {job_id} JSON; grown v0.46.26.0 megawave: image sync, ingest-log gating, dry-run purity, checkpoint honesty (#2683 #4342 #3875) + 3 nosemgrep dataflow annotations (path-traversal audit); +#2683 residual: status-error failure recording at both import sites; +143 wave G #3974: working-tree drift surfacing + opt-in --working-tree import; grown wave-g (#4412 #4543): break-lock ambient source resolution + named failing files; grown db-availability loop: GBRAIN_DB_ACCESS marker on checkpoint-dead aborts; fix cycle: marker via shared DB_ACCESS_MARKER_PREFIX + shouldEmitDbAccessMarker; wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +master-merge true-up; +25 post-sync backup-coverage stale-only refresh (monthly backup check); wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +1: #4412 refinement — explicit --source stays resolver-free (deleted-source locks breakable); +10 v0.47 gmail-loops: google source-kind dispatch branch; +48 #4667 adoption: persisted sync.exclude config union hoisted above the performFullSync early returns; +22 #4587: all 7 delete lanes swapped to softDeletePages (72h recovery window), decompose comments + summary wording; +16 #4583: seed_default write refusal on bulk-non-default brains (assessDefaultWriteGuard call site + escape-hatch comment); composition true-up (fix-wave multi-train); +33 #4597: trackedSlugIndex.anchorOnlyPaths (slug -> anchor paths that alone proved it) + the self-referential from-path rule in slugLiveness so a fallback rename's own pre-rename duplicate converges under incremental sync; +12 #4888: runSync wraps runSyncInner in withHumanLogsToStderr under --json (stdout = JSON lines only) + help text; wave composition: #4903 stored-strategy honor + #4597 fallback-rename duplicate convergence + #4888 --json stdout purity summed; security: durable queued authority and confined filesystem dispatch; drained cancellation and lease-safe partial results; master integration: +1 wave review: sync trigger --json emits {job_id} JSON; grown v0.46.26.0 megawave: image sync, ingest-log gating, dry-run purity, checkpoint honesty (#2683 #4342 #3875) + 3 nosemgrep dataflow annotations (path-traversal audit); +#2683 residual: status-error failure recording at both import sites; +143 wave G #3974: working-tree drift surfacing + opt-in --working-tree import; grown wave-g (#4412 #4543): break-lock ambient source resolution + named failing files; grown db-availability loop: GBRAIN_DB_ACCESS marker on checkpoint-dead aborts; fix cycle: marker via shared DB_ACCESS_MARKER_PREFIX + shouldEmitDbAccessMarker; wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +master-merge true-up; +25 post-sync backup-coverage stale-only refresh (monthly backup check); wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +1: #4412 refinement — explicit --source stays resolver-free (deleted-source locks breakable); +10 v0.47 gmail-loops: google source-kind dispatch branch; +48 #4667 adoption: persisted sync.exclude config union hoisted above the performFullSync early returns; +22 #4587: all 7 delete lanes swapped to softDeletePages (72h recovery window), decompose comments + summary wording; +16 #4583: seed_default write refusal on bulk-non-default brains (assessDefaultWriteGuard call site + escape-hatch comment); composition true-up (fix-wave multi-train); +33 #4597: trackedSlugIndex.anchorOnlyPaths (slug -> anchor paths that alone proved it) + the self-referential from-path rule in slugLiveness so a fallback rename's own pre-rename duplicate converges under incremental sync; +12 #4888: runSync wraps runSyncInner in withHumanLogsToStderr under --json (stdout = JSON lines only) + help text; wave composition: #4903 stored-strategy honor + #4597 fallback-rename duplicate convergence + #4888 --json stdout purity summed; #5252 wave: post-batch planner statistics refresh; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; merged reliability/shared-skills source integration; +1 cancellation guard before company dispatch; +3 wave-2 W4: full sync carries the safe-chunk re-seal count and embedding cost (#5050); +4 #5632: CLI passes explicitly set processing options so a flagless resume adopts the cursor options+src/core/cycle.ts 3209 ratchet grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options+src/core/cycle/synthesize.ts 3241 ratchet merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack+src/core/cycle/extract-atoms.ts 1755 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +3 #5525: effectiveVisibility stamped on non-managed atomssrc/core/engine.ts 2665 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract-src/core/import-file.ts 2236 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor+src/core/import-file.ts 2252 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line countsrc/core/migrate.ts 722 region-exempt append-only MIGRATIONS array grows freely; runner logic is ratcheted — grown v0.46.26.0: repair-handler hooks (#3957 pages-upsert-arbiter); wave-k v142 takes-embedding resize is in-region (renumbered from v141; master consumed v141 for #4482); master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: projection migration helper; #5105: lease schema helper; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +1 import for focused topology migration module; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: static projection statistics import; DDL remains region-exempt; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestionsrc/core/operations.ts 329 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base-src/core/pglite-engine.ts 6149 ratchet +6 #4881: ontology provenance-page visibility gate (getOntology/findOntologyConflicts); grown v0.46.26.0 megawave parity twins + master v0.46.26.0 private-queue columns; +#3754 traverseGraph soft-delete filters; grown wave-g (#4524 #4527): canonical islanded orphans + timestamp-preserving migrate; wave-k: +1 semantic takes retrieval delegate (#3776), +5 NUL-sanitize shared chunk_text local (#3998), +7 getAllConfig bulk read (#3980); +22: pre-close WAL CHECKPOINT in disconnect (#3893); +10: #4109 atomic link/timeline mutation + typed per-endpoint miss (parity); +1: getBacklinkCounts page-id keying comment (#4380); +14: dream-verdict TTL expiry predicate + sweep (#4069); +7 test-gap-wave merge true-up; +23: softDeletePages batch soft-delete primitive (#4587, parity twin); +51: #4592 source-scoped getStats/getHealth (bound $1 scope, both-endpoint link rule); +5 file-bytes snapshot hash (coverage-immune — CI shards were silently cold-initting); +7 2026-09 fix wave (#3617 follow-up): OR-fallback rows tagged keyword_relaxed in searchKeyword + title arm (fusion demotion reads it); cold-initting); +11: #4280 orphan/health served-memory denominators (quarantine + leaf-type metadata); composition true-up (fix-wave multi-train); +14: traversePathsDetailed row cap (LIMIT + truncated probe, parity twin); +7: resolveSlugWithAliasDetailed (owning source_id, parity twin) | merged v0.48.1.0 true-up; corrective release: shared batched enrichment peel; concrete content and Chronicle authorization; +2: #4681 listPages projects updated_at_iso (microsecond keyset cursor); master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: grant and authority schema bootstrap parity; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; upstream integration: preserve independently reviewed master additions with branch facade extraction; +1 v0.50.5.0 security merge (upstream delta; coordinated facade retained); +7 ceiling: bounded in-memory create retry with attached-database exclusion and second-failure diagnostics; #5252 bounded candidate recovery and statistics snapshot dependency; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared-skills integration on company-ingestion base; shared skills: include explicit access DDL in snapshot invalidation; archived eligibility: source-locked drift and raw signature mutations; +6 write-path wave: updateSlug records its rename alias in one transaction; +11 read-path wave: searchKeyword type/exclude_slugs Postgres parity + getTags private/deleted filters; +5: updateSlug carries entity-scoped fact withdrawals-src/core/postgres-engine.ts 5577 ratchet +6 #4881: ontology provenance-page visibility gate (parity twin); lowered wave-g: #4477 bootstrap peel to src/core/postgres-engine/ modules (ratchet holds the win); +2 on wave-g-prs merge true-up; wave-k: +2 semantic takes retrieval (#3776), +5 NUL-sanitize shared chunk_text local (#3998), +11 getAllConfig bulk read (#3980); +13: #4109 atomic FOR KEY SHARE link/timeline mutation + typed per-endpoint miss; +2: getBacklinkCounts page-id keying comment (#4380); +12: dream-verdict TTL expiry predicate + sweep (#4069); +23: softDeletePages batch soft-delete primitive (#4587, parity twin); +61: #4592 source-scoped getStats/getHealth (scope predicate, both-endpoint link rule); +11 2026-09 fix wave (#3617 follow-up): OR-fallback rows tagged keyword_relaxed in searchKeyword + title arm (fusion demotion reads it); rule); +12: #4280 orphan/health served-memory denominators (quarantine + leaf-type metadata, parity twin); composition true-up (fix-wave multi-train); +14: traversePathsDetailed row cap (LIMIT + truncated probe, parity twin); +7: resolveSlugWithAliasDetailed (owning source_id, parity twin) | merged v0.48.1.0 true-up; corrective release: shared batched enrichment peel; concrete content and Chronicle authorization; +3: #4681 listPages projects updated_at_iso (microsecond keyset cursor, parity twin); #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop barrier and direct transaction route; upstream integration: preserve independently reviewed master additions with branch facade extraction; +1 v0.50.5.0 security merge (upstream delta; coordinated facade retained)+src/core/pglite-engine.ts 6167 ratchet +6 #4881: ontology provenance-page visibility gate (getOntology/findOntologyConflicts); grown v0.46.26.0 megawave parity twins + master v0.46.26.0 private-queue columns; +#3754 traverseGraph soft-delete filters; grown wave-g (#4524 #4527): canonical islanded orphans + timestamp-preserving migrate; wave-k: +1 semantic takes retrieval delegate (#3776), +5 NUL-sanitize shared chunk_text local (#3998), +7 getAllConfig bulk read (#3980); +22: pre-close WAL CHECKPOINT in disconnect (#3893); +10: #4109 atomic link/timeline mutation + typed per-endpoint miss (parity); +1: getBacklinkCounts page-id keying comment (#4380); +14: dream-verdict TTL expiry predicate + sweep (#4069); +7 test-gap-wave merge true-up; +23: softDeletePages batch soft-delete primitive (#4587, parity twin); +51: #4592 source-scoped getStats/getHealth (bound $1 scope, both-endpoint link rule); +5 file-bytes snapshot hash (coverage-immune — CI shards were silently cold-initting); +7 2026-09 fix wave (#3617 follow-up): OR-fallback rows tagged keyword_relaxed in searchKeyword + title arm (fusion demotion reads it); cold-initting); +11: #4280 orphan/health served-memory denominators (quarantine + leaf-type metadata); composition true-up (fix-wave multi-train); +14: traversePathsDetailed row cap (LIMIT + truncated probe, parity twin); +7: resolveSlugWithAliasDetailed (owning source_id, parity twin) | merged v0.48.1.0 true-up; corrective release: shared batched enrichment peel; concrete content and Chronicle authorization; +2: #4681 listPages projects updated_at_iso (microsecond keyset cursor); master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: grant and authority schema bootstrap parity; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; upstream integration: preserve independently reviewed master additions with branch facade extraction; +1 v0.50.5.0 security merge (upstream delta; coordinated facade retained); +7 ceiling: bounded in-memory create retry with attached-database exclusion and second-failure diagnostics; #5252 bounded candidate recovery and statistics snapshot dependency; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared-skills integration on company-ingestion base; shared skills: include explicit access DDL in snapshot invalidation; archived eligibility: source-locked drift and raw signature mutations; +6 write-path wave: updateSlug records its rename alias in one transaction; +11 read-path wave: searchKeyword type/exclude_slugs Postgres parity + getTags private/deleted filters; +5: updateSlug carries entity-scoped fact withdrawals; +12 wave-2 W4: upsertChunks writes content_chunks.embedding_input_hash with the vector (#5553, parity twin); +6 #5449 outermost-transaction WAL checkpoint guard admitted into the shutdown drain, reset per attached database (logic in pglite-engine/checkpoint-guard.ts)+src/core/postgres-engine.ts 5587 ratchet +6 #4881: ontology provenance-page visibility gate (parity twin); lowered wave-g: #4477 bootstrap peel to src/core/postgres-engine/ modules (ratchet holds the win); +2 on wave-g-prs merge true-up; wave-k: +2 semantic takes retrieval (#3776), +5 NUL-sanitize shared chunk_text local (#3998), +11 getAllConfig bulk read (#3980); +13: #4109 atomic FOR KEY SHARE link/timeline mutation + typed per-endpoint miss; +2: getBacklinkCounts page-id keying comment (#4380); +12: dream-verdict TTL expiry predicate + sweep (#4069); +23: softDeletePages batch soft-delete primitive (#4587, parity twin); +61: #4592 source-scoped getStats/getHealth (scope predicate, both-endpoint link rule); +11 2026-09 fix wave (#3617 follow-up): OR-fallback rows tagged keyword_relaxed in searchKeyword + title arm (fusion demotion reads it); rule); +12: #4280 orphan/health served-memory denominators (quarantine + leaf-type metadata, parity twin); composition true-up (fix-wave multi-train); +14: traversePathsDetailed row cap (LIMIT + truncated probe, parity twin); +7: resolveSlugWithAliasDetailed (owning source_id, parity twin) | merged v0.48.1.0 true-up; corrective release: shared batched enrichment peel; concrete content and Chronicle authorization; +3: #4681 listPages projects updated_at_iso (microsecond keyset cursor, parity twin); #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop barrier and direct transaction route; upstream integration: preserve independently reviewed master additions with branch facade extraction; +1 v0.50.5.0 security merge (upstream delta; coordinated facade retained); +3 wave-2 W4: upsertChunks writes content_chunks.embedding_input_hash with the vector (#5553, parity twin); +2 fix wave 2 (v0.60.5.0) integration: master grew 2 lines under the old ceiling while W4 raised it from its older base; +5 v0.60.5.0 master-merge true-up: W4 +12 re-summed over master v0.59.18.0 at 5575 linessrc/core/search/hybrid.ts 3215 ratchet +2: preserve local query-deadline classification through gateway error wrapping; grown v0.46.26.0 megawave: CRAG escalation seam, degradation visibility, excludePrivate knobs-fold v23 (#1663 #3873 #4352); grown #4356: semantic-cache-hit slice honors resolved mode searchLimit (double-resolution caveat); grown #4414: offset!==0 cache-skip widening + knobs-hash v24; grown #4487: chunkless rows join the cosine blend (no raw-score head start); grown wave-g (#4480 #4415): shared salience/recency resolution + pattern-aware cache keying; grown db-availability loop: all-lexical-arms-dead access-error rethrow (a dead DB must never return an empty success) — refined to both-arms-FAILED (a succeeded-but-empty arm proves the DB is alive); grown v0.46.26.0 megawave: CRAG escalation seam, degradation visibility, excludePrivate knobs-fold v23 (#1663 #3873 #4352); grown #4356: semantic-cache-hit slice honors resolved mode searchLimit (double-resolution caveat); grown #4414: offset!==0 cache-skip widening + knobs-hash v24; grown #4487: chunkless rows join the cosine blend (no raw-score head start); grown wave-g (#4480 #4415): shared salience/recency resolution + pattern-aware cache keying; +2: backlink-boost counts page-id keying doc (#4380); +59 2026-09 adversarial batch 2: both-mode text-only demotion gate (textVectorArmNonEmpty) + relaxed_dropped meta + keyword_relaxed_carried degraded stamp + intent-skew caveat docs; +35 #3617 follow-up: relaxed-row fusion demotion (vectorArmNonEmpty gate + keywordFusionList/titleFusionList) with the LongMemEval 51.3%-vs-93.8% receipt comment; +24 2026-08 eval fix wave (E5b/D8): adaptive-return knobs-hash v27 fold (resolved gate + intent class threaded to the cache key), adaptive-on skipCache removal, dedupOpts cache-skip honesty, explicit-maxPerPage min() precedence under walk widening; (#4380); +20 wave #4256: compiledTruthBoost helper — synthetic chunkless title rows (chunk_id 0 + empty chunk_text) never gain the 2x compiled-truth boost (#3695); composition true-up (fix-wave multi-train) | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: read-policy propagation and semantic result-cache containment; ranker wave v0.48.4.0: role-tagged fusion arms, relational rerank pin, metadata boost gate, per-call knob seams, onRerankPool hook (+150) merged over master's read-policy plumbing (+31); +11 #4359 (#4972): thread the loaded search-mode config snapshot from hybridSearchCached into the inner hybridSearch call (INTERNAL _searchModeInput opt) so both resolve from the same one DB-plane config read instead of two independent ones — closes the cache-key/result desync window and removes the second config-table round trip on every hybridSearchCached call; #5252 wave: inclusive date bounds and public vector incompleteness; shared date-bounds peel retains exports; merged company ingestion/schema routing changes; retired provider integration removed-src/core/types.ts 2076 ratchet +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note+src/core/types.ts 2078 ratchet +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553)src/core/minions/queue.ts 2522 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keyssrc/commands/init.ts 1932 ratchet grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 provider normalization; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only init; shared-skills integration on company-ingestion base; retired provider integration removed; retain stored-vector identity on re-initsrc/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900)@@ -31,13 +31,13 @@ src/core/minions/handlers/subagent.ts 1918 ratchet merged: master v131 settle resrc/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 1764 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; typed readiness, configuration-blocked lifecycle and bounded release; post-validation readiness publication and confirmed isolated-execution stop evidence; latch typed lock-renewal faults before generic retrysrc/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.ts-src/core/link-extraction.ts 2099 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 links; canonical attendance evidence, source-qualified orientation, strict attendee resolution, and relocated filesystem link scanner (command export preserved); +4: pack-owned fallback and ambiguous attendee guards Display-label attendance exclusion, indexed evidence membership, and bounded strict resolver caching; attendance-boundary review.; complete attendance resolution and fence-safe evidence traversal; frontmatter discovery, canonical basename admission and code-aware attendance comment masking; exclude inline HTML comment spans from admitted attendance ranges; +17 write-path wave: same-name rule for entity fuzzy matches + rename-alias fallback in makeResolver+src/core/link-extraction.ts 2100 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 links; canonical attendance evidence, source-qualified orientation, strict attendee resolution, and relocated filesystem link scanner (command export preserved); +4: pack-owned fallback and ambiguous attendee guards Display-label attendance exclusion, indexed evidence membership, and bounded strict resolver caching; attendance-boundary review.; complete attendance resolution and fence-safe evidence traversal; frontmatter discovery, canonical basename admission and code-aware attendance comment masking; exclude inline HTML comment spans from admitted attendance ranges; +17 write-path wave: same-name rule for entity fuzzy matches + rename-alias fallback in makeResolver; +1 #5567: materialized marker ends bullet detailsrc/core/embedding-migration.ts 1513 ratchet new row: crossed 1500 in v0.46.25.0 fix waves (#4305 #4306 chunk-model truth helpers); retired provider integration removed; safety wave: canonical projection readiness and fact-aware completion; file configuration publication retains lease-row locks; +8 transactional retained-vector rebuildability checks before destructive migration boundaries; archived eligibility: source-locked reconciliation and live/current smoke revalidationsrc/core/github-source.ts 1576 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper-src/commands/hook.ts 1881 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking+src/commands/hook.ts 1892 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcriptssrc/core/chunkers/code.ts 1582 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPESsrc/core/config.ts 1794 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wavesrc/core/bootstrap/harness.ts 2656 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base-src/core/oauth-provider.ts 1235 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies-src/core/ops/pages.ts 611 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts)+src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option+src/core/ops/pages.ts 613 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parametersrc/core/search/mode.ts 1495 ratchet +5 #3617 follow-up: v27 same-knobs behavioral-change note (relaxed-row fusion demotion rides the bump); new row: crossed the 1500 unlisted cap in the 2026-08 eval fix wave — KNOBS_HASH v=27 adaptive-return fold (ar/arem/arom/armk/ari parts + KnobsHashContext.adaptiveReturn field + contamination rationale comments) | merged v0.48.1.0 (+#4787) true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: four knobs (expansion_variant_budget, relational_rerank_pin, keyword_arm_confidence_floor, metadata_boost_gate) + v29 hash parts + doc receipts (+218); #4781 loadSearchModeConfig reads the config table once via loadConfigSnapshot (+6); +4 #4359: update loadSearchModeConfig docstring — the cached path now reads config once (threaded snapshot), not twice; retired provider integration removeddiff --git a/scripts/pglite-checkpoint-harness/supervisor.ts b/scripts/pglite-checkpoint-harness/supervisor.tsnew file mode 100644index 0000000000..8d351bd4f3--- /dev/null+++ b/scripts/pglite-checkpoint-harness/supervisor.ts@@ -0,0 +1,153 @@+#!/usr/bin/env bun+// #5449 large-store harness supervisor. Runs outside the default CI shards.+//+// It creates (or reuses) a PGLite store, optionally scales shared_buffers and+// max_wal_size down with ALTER SYSTEM so a small machine exercises the same+// eviction-plus-inline-checkpoint path as a multi-GB store, then spawns the+// worker as a separate process and watches it from outside: worker CPU from+// /proc, committed-page progress from the worker's progress file, WAL volume+// and checkpoint activity from the data directory. A wedge is a worker that+// burns CPU with no committed page and no checkpoint progress for+// --stall-sec. The run fails on a wedge, on the --timeout-sec cap, or when WAL+// written since the last redo ever exceeds the guard threshold plus the+// largest single transaction.+//+// bun scripts/pglite-checkpoint-harness/supervisor.ts --dir /tmp/h --pages 3000 \+// --shared-buffers 16MB --max-wal-size 32MB --stall-sec 120 --timeout-sec 1800+import { spawn } from 'node:child_process';+import { existsSync, readFileSync, readdirSync, statSync, writeFileSync, rmSync, mkdirSync } from 'node:fs';+import { join, resolve } from 'node:path';+import { PGlite } from '@electric-sql/pglite';+import { checkpointGuardThreshold } from '../../src/core/pglite-engine/checkpoint-guard.ts';++function arg(name: string, fallback: string): string {+ const i = process.argv.indexOf(`--${name}`);+ return i >= 0 && process.argv[i + 1] ? process.argv[i + 1]! : fallback;+}+const dir = resolve(arg('dir', '/tmp/gbrain-5449-harness'));+const pages = Number(arg('pages', '3000'));+const pageKb = Number(arg('page-kb', '40'));+const sharedBuffers = arg('shared-buffers', '');+const maxWalSize = arg('max-wal-size', '');+const stallSec = Number(arg('stall-sec', '600'));+const timeoutSec = Number(arg('timeout-sec', '1800'));+const fresh = process.argv.includes('--fresh');+const expectWedge = process.argv.includes('--expect-wedge');+const dataDir = join(dir, 'brain.pglite');+const progressPath = join(dir, 'progress.ndjson');++function dirBytes(path: string): number {+ if (!existsSync(path)) return 0;+ let total = 0;+ for (const entry of readdirSync(path, { withFileTypes: true })) {+ const full = join(path, entry.name);+ total += entry.isDirectory() ? dirBytes(full) : statSync(full).size;+ }+ return total;+}+function cpuTicks(pid: number): number | null {+ try {+ const fields = readFileSync(`/proc/${pid}/stat`, 'utf8').split(') ')[1]!.split(' ');+ return Number(fields[11]) + Number(fields[12]);+ } catch { return null; }+}+function readProgress(): Array<Record<string, number | boolean | string>> {+ if (!existsSync(progressPath)) return [];+ return readFileSync(progressPath, 'utf8').split('\n').filter(Boolean).map(line => JSON.parse(line));+}++if (fresh) rmSync(dir, { recursive: true, force: true });+mkdirSync(dir, { recursive: true });+let startIndex = 0;+if (existsSync(progressPath)) {+ const prior = readProgress().filter(row => typeof row.i === 'number');+ startIndex = prior.length ? Number(prior[prior.length - 1]!.i) + 1 : 0;+}+writeFileSync(progressPath, '');++const settings = await (async () => {+ const db = await PGlite.create({ dataDir });+ if (sharedBuffers) await db.query(`ALTER SYSTEM SET shared_buffers = '${sharedBuffers}'`);+ if (maxWalSize) {+ await db.query(`ALTER SYSTEM SET max_wal_size = '${maxWalSize}'`);+ await db.query(`ALTER SYSTEM SET min_wal_size = '${maxWalSize}'`);+ }+ await db.close();+ const check = await PGlite.create({ dataDir });+ const read = async (name: string) => (await check.query<{ v: string }>(`SELECT current_setting('${name}') AS v`)).rows[0]!.v;+ const bytes = async (name: string) => Number((await check.query<{ b: string }>(`SELECT pg_size_bytes(current_setting('${name}'))::text AS b`)).rows[0]!.b);+ const out = {+ shared_buffers: await read('shared_buffers'), max_wal_size: await read('max_wal_size'),+ shared_buffers_bytes: await bytes('shared_buffers'), max_wal_size_bytes: await bytes('max_wal_size'),+ wal_segment_bytes: await bytes('wal_segment_size'),+ checkpoint_completion_target: Number(await read('checkpoint_completion_target')),+ };+ await check.close();+ return out;+})();+const checkpointSegments = Math.max(1, Math.floor(settings.max_wal_size_bytes / (settings.wal_segment_bytes * (1 + settings.checkpoint_completion_target))));+const autoCheckpointBytes = (checkpointSegments - 1) * settings.wal_segment_bytes;+const guardThresholdBytes = checkpointGuardThreshold(settings.max_wal_size_bytes, settings.wal_segment_bytes, settings.checkpoint_completion_target);+const storeBytesAtStart = dirBytes(dataDir);+console.log(JSON.stringify({ event: 'start', dir, pages, page_kb: pageKb, start_index: startIndex, ...settings,+ auto_checkpoint_bytes: Math.round(autoCheckpointBytes), guard_threshold_bytes: Math.round(guardThresholdBytes),+ store_bytes: storeBytesAtStart, store_to_shared_buffers: +(storeBytesAtStart / settings.shared_buffers_bytes).toFixed(1) }));++const child = spawn(process.execPath, [join(import.meta.dir, 'worker.ts'), dataDir, progressPath, String(pages), String(startIndex), String(pageKb)],+ { stdio: ['ignore', 'inherit', 'inherit'], env: process.env });+const clk = 100;+const started = Date.now();+let lastProgressCount = 0, lastProgressAt = Date.now();+let lastControlMtime = statSync(join(dataDir, 'global', 'pg_control')).mtimeMs, lastCheckpointAt = Date.now();+let lastCpu = cpuTicks(child.pid!) ?? 0, lastSample = Date.now();+let exitCode: number | null | undefined;+child.on('exit', code => { exitCode = code; });++type Verdict = { verdict: 'wedged' | 'completed' | 'timeout' | 'worker_failed'; detail: Record<string, unknown> };+const verdict: Verdict = await new Promise(resolveVerdict => {+ const timer = setInterval(() => {+ const now = Date.now();+ const rows = readProgress();+ const committed = rows.filter(row => typeof row.i === 'number');+ const done = rows.some(row => row.done === true);+ const cpu = cpuTicks(child.pid!);+ const cpuPct = cpu === null ? 0 : ((cpu - lastCpu) / clk) / ((now - lastSample) / 1000) * 100;+ if (cpu !== null) lastCpu = cpu;+ lastSample = now;+ const controlMtime = existsSync(join(dataDir, 'global', 'pg_control')) ? statSync(join(dataDir, 'global', 'pg_control')).mtimeMs : lastControlMtime;+ if (controlMtime !== lastControlMtime) { lastControlMtime = controlMtime; lastCheckpointAt = now; }+ if (committed.length !== lastProgressCount) { lastProgressCount = committed.length; lastProgressAt = now; }+ const last = committed[committed.length - 1];+ const sample = { t_sec: Math.round((now - started) / 1000), committed: committed.length, cpu_pct: Math.round(cpuPct),+ wal_dir_bytes: dirBytes(join(dataDir, 'pg_wal')), store_bytes: dirBytes(dataDir),+ wal_since_redo: last?.since_redo ?? null, stall_sec: Math.round((now - lastProgressAt) / 1000),+ checkpoint_idle_sec: Math.round((now - lastCheckpointAt) / 1000) };+ if (sample.t_sec % 10 === 0) console.log(JSON.stringify({ event: 'sample', ...sample }));+ const finish = (v: Verdict['verdict']) => {+ clearInterval(timer);+ if (exitCode === undefined) child.kill('SIGKILL');+ resolveVerdict({ verdict: v, detail: { ...sample, exit_code: exitCode ?? null } });+ };+ if (done && exitCode !== undefined) return finish('completed');+ if (exitCode !== undefined && !done) return finish('worker_failed');+ if (now - lastProgressAt >= stallSec * 1000 && now - lastCheckpointAt >= stallSec * 1000 && cpuPct >= 80) return finish('wedged');+ if (now - started >= timeoutSec * 1000) return finish('timeout');+ }, 1000);+});++const committed = readProgress().filter(row => typeof row.i === 'number') as Array<{ i: number; since_redo: number; lsn: string }>;+const lsnBytes = (lsn: string) => { const [hi, lo] = lsn.split('/'); return parseInt(hi!, 16) * 2 ** 32 + parseInt(lo!, 16); };+let maxTransactionWal = 0, maxSinceRedo = 0;+for (let k = 0; k < committed.length; k++) {+ maxSinceRedo = Math.max(maxSinceRedo, committed[k]!.since_redo);+ if (k > 0) maxTransactionWal = Math.max(maxTransactionWal, lsnBytes(committed[k]!.lsn) - lsnBytes(committed[k - 1]!.lsn));+}+const walBound = guardThresholdBytes + maxTransactionWal;+const walWithinBound = maxSinceRedo <= walBound;+const report = { event: 'result', ...verdict, committed: committed.length, max_wal_since_redo: maxSinceRedo,+ max_transaction_wal: maxTransactionWal, wal_bound: Math.round(walBound), wal_within_bound: walWithinBound,+ elapsed_sec: Math.round((Date.now() - started) / 1000) };+console.log(JSON.stringify(report));+writeFileSync(join(dir, 'result.json'), JSON.stringify(report, null, 2));+if (expectWedge) process.exit(verdict.verdict === 'wedged' ? 0 : 1);+process.exit(verdict.verdict === 'completed' && walWithinBound ? 0 : 1);diff --git a/scripts/pglite-checkpoint-harness/worker.ts b/scripts/pglite-checkpoint-harness/worker.tsnew file mode 100644index 0000000000..bcf0dc80cc--- /dev/null+++ b/scripts/pglite-checkpoint-harness/worker.ts@@ -0,0 +1,43 @@+// #5449 harness worker: imports many large pages through PGLiteEngine.transaction+// (via importFromContent) into one long-lived PGLite store and appends one JSON+// progress line per committed page. The external supervisor owns wedge detection.+import { appendFileSync } from 'node:fs';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import { configureGateway } from '../../src/core/ai/gateway.ts';++const [dataDir, progressPath, countArg, startArg, pageKbArg] = process.argv.slice(2);+const count = Number(countArg ?? 3000);+const start = Number(startArg ?? 0);+const pageKb = Number(pageKbArg ?? 40);+configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: { OPENAI_API_KEY: 'sk-harness' } });+const engine = new PGLiteEngine();+await engine.connect({ engine: 'pglite', database_path: dataDir } as never);+await engine.initSchema();++const words = 'alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu nu xi omicron pi rho sigma tau upsilon phi chi psi omega'.split(' ');+let seed = start + 1;+const rand = () => { seed = (seed * 1103515245 + 12345) & 0x7fffffff; return seed; };+function body(i: number): string {+ const out: string[] = [];+ let size = 0;+ while (size < pageKb * 1024) {+ const sentence = Array.from({ length: 12 }, () => `${words[rand() % words.length]}${rand() % 9973}`).join(' ') + '.';+ out.push(sentence); size += sentence.length + 1;+ if (out.length % 8 === 0) out.push('\n');+ }+ return `---\ntype: note\ntitle: Harness page ${i}\n---\n# Page ${i}\n\n${out.join(' ')}\n`;+}+async function walSinceRedo(): Promise<{ since_redo: number; lsn: string }> {+ const rows = await engine.executeRaw<{ since_redo: string; lsn: string }>(+ `SELECT pg_wal_lsn_diff(pg_current_wal_lsn(), redo_lsn)::text AS since_redo, pg_current_wal_lsn()::text AS lsn FROM pg_control_checkpoint()`);+ return { since_redo: Number(rows[0]!.since_redo), lsn: rows[0]!.lsn };+}+for (let i = start; i < start + count; i++) {+ const t0 = performance.now();+ await importFromContent(engine, `harness/page-${i}`, body(i), { noEmbed: true });+ const wal = await walSinceRedo();+ appendFileSync(progressPath, JSON.stringify({ i, ms: Math.round(performance.now() - t0), ...wal, at: Date.now() }) + '\n');+}+await engine.disconnect();+appendFileSync(progressPath, JSON.stringify({ done: true, at: Date.now() }) + '\n');diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsvindex a33651d045..baee8fde6e 100644--- a/scripts/structural-suites.tsv+++ b/scripts/structural-suites.tsv@@ -205,6 +205,7 @@ test/ocr-run-budget.test.ts doctor ocr_health surfaces the budget-skip counter (test/openclaw-plugin-manifest.test.ts bundled-skill reference closure (nothing bundled points at a non-bundled skill) 1 readFileSynctest/openclaw-plugin-manifest.test.ts plugin membership curation (skills = plugin ∪ exclusions, disjoint) 9 readFileSynctest/openclaw-plugin-manifest.test.ts root OpenClaw plugin manifest 2 readFileSync+test/persistence-git-subdir-origin.test.ts (file-level) 6 readFileSynctest/persistence-sync-options.serial.test.ts (file-level) 1 readFileSynctest/pg-access-classify.test.ts marker contract (skill↔binary lockstep, the UPGRADE_AVAILABLE pattern) 3 bun-filetest/pglite-engine.test.ts PGLiteEngine: v0.13.1 error-wrap on connect() (#223) 1 readFileSync@@ -259,7 +260,7 @@ test/shared-skills-optimizer.serial.test.ts (file-level) 15 readFileSynctest/shared-skills-publication-sparse.test.ts (file-level) 4 readFileSynctest/shared-skills-setup.serial.test.ts packaged default skills 2 readFileSynctest/shared-skills-setup.serial.test.ts staged skill migration 7 readFileSync-test/shared-skills-writer-boundary.serial.test.ts (file-level) 5 readFileSync+test/shared-skills-writer-boundary.serial.test.ts (file-level) 7 readFileSynctest/skillify-scaffold.test.ts 11-item scaffold contract (T9 + Phase 3 cross-modal eval) 1 readFileSynctest/skillify-scaffold.test.ts applyScaffold 3 readFileSynctest/skillify-scaffold.test.ts planScaffold 13 readFileSyncdiff --git a/skills/migrations/v0.60.5.0.md b/skills/migrations/v0.60.5.0.mdnew file mode 100644index 0000000000..ac91e15907--- /dev/null+++ b/skills/migrations/v0.60.5.0.md@@ -0,0 +1,148 @@+# Upgrade to v0.60.5.0: keep database-only history, unwedge managed brains, stop paid loops++This release stops page writes from deleting timeline history that exists only+in the database, writes that history back into pages, and makes extracted atoms+and synthesized concepts private unless their origin is public. It also fixes+several ways a managed brain got permanently stuck, raises managed write+capacity, stops dream from re-billing the same transcripts, releases idle+Postgres connections and guards large PGLite imports.++Four additive schema migrations run automatically: v170 (partial index for+parked postcommit effects), v171 (nullable `content_chunks.embedding_input_hash`),+v172 (partial index of pages below the safe-chunk fence) and v173 (partial index+on dead subagent jobs). None deletes data, write IDs or receipts, and none+starts a background service.++1. **Confirm a database backup exists before anything else writes to the+ brain.** Ask the user whether they have a recent backup of the database+ itself: `pg_dump` for Postgres, or a copy of the PGLite data directory made+ while gbrain was stopped. A Markdown export (`gbrain export`) does not+ include database-only timeline entries. If there is no backup, tell the user+ and recommend making one now. Do not make it for them without asking.++2. **Upgrade every process that writes to this brain.** An older gbrain process+ keeps deleting database-only timeline history every time it republishes a+ page. List the writers with the user: `gbrain serve`, autopilot and job+ supervisors, session hooks and any other machine or global CLI install that+ uses this database. Each must run `gbrain upgrade` and then be restarted.++ ```bash+ gbrain --version # expect 0.60.5.0 on every writer+ gbrain autopilot --status --json+ gbrain jobs supervisor status --json+ ```++ If schema work did not complete, run+ `gbrain apply-migrations --yes --no-autopilot-install` on the brain host.+ Do not change the operator's search mode or engine.++3. **Tell the user what was lost, plainly.** If pages were edited, synced,+ imported, reconciled or refreshed by a connector while an older writer ran,+ timeline entries that had no Markdown bullet may be gone. This release+ cannot restore them. Recovering them needs a database backup taken before+ the loss. Do not promise recovery without one.++4. **Run one full doctor pass (not `--fast`) and relay the new signals.**++ ```bash+ gbrain doctor --json+ ```++ - `timeline_history` counts timeline entries that exist only in the+ database. `details.count` says whether the number is `exact` or a+ `lower_bound` (the scan stops after 2,000 pages or 10 seconds).+ `kept_unrenderable_rows` are entries that cannot be written as a bullet+ without changing them (for example an empty source); they are kept as-is+ and need no action.+ - `derived_visibility` counts atoms and synthesized concepts without an+ explicit visibility, or stored looser than their origin. Remote readers+ already treat all of them as private.+ - `contextual_retrieval_coverage` now counts pages of every kind below the+ safe-chunk index version (`details.unsealed_pages`, with+ `details.unsealed_code_pages` for code). Remote and MCP search withhold+ those pages' chunks. The count used to cover markdown only, so it may rise+ after upgrading even though nothing changed.+ - `persistence_capacity`: a principal or the brain uses 80% or more of its+ permanent write IDs or receipt bytes. Run the `gbrain config set+ persistence.limits.<key> <value>` command the check prints, on the brain+ host, after the user agrees. Raising a limit is a mitigation; IDs stay+ permanent.+ - `parked_effects`: a Git or withdrawal target failed five times in a row and+ was set aside. Inspect `gbrain sources writer status <source>`, fix the+ named cause, preview with the printed+ `gbrain sources writer retry-effects <source> --request-id <id> --dry-run`,+ then run it without `--dry-run` to authorize one more attempt.+ - `dream_paid_loop`: dream keys whose jobs died 3 times in 24 hours and are+ now refused. Show the operator the keys and the reset command it prints.+ Do not reset a key on your own: the operator should first fix why those+ jobs die (a missing provider key, a failing transcript, a quota), then run+ `gbrain dream reset-key '<key>'`. `gbrain dream reset-key --list` lists+ every refused key.++ Health scores may drop by these warnings until the repairs below run.++5. **Preview the repairs, then apply them on the brain host.** Every kind is a+ dry run unless `--apply` is passed. Show the user the preview first; it+ prints the resolved brain and sources, the pages affected, the request-ID+ cost and, for safe-chunks, the estimated embedding cost.++ ```bash+ gbrain repair # preview every kind+ gbrain repair timeline --apply # write database-only entries back into their pages+ gbrain repair visibility --apply # stamp explicit visibility, tighten-only+ gbrain repair safe-chunks --apply # re-seal withheld pages, then embed chunks that need it+ gbrain repair safe-chunks --apply --no-embed # re-seal text only; embed later+ ```++ Add `--source <id>` to limit a run to one source and `--limit <n>` to repair+ in batches; rerunning the same command resumes where it stopped. The+ safe-chunks kind takes no journal admissions and never hits a capacity+ limit. If the timeline or visibility repair stops near a journal capacity+ limit, it prints the exact `gbrain config set persistence.limits.<key>+ <value>` that lets it finish; ask the user before raising a limit. If it+ reports that the writer is held, inspect `gbrain sources writer status+ <source>` and rerun. With `--no-embed`, run `gbrain embed --stale` later (ask+ the user first; it calls the embedding provider). A thin client refuses+ `gbrain repair`; the brain host operator runs it.++6. **What changes for the user.**+ - Saved pages may gain marked bullets (`<!-- gbrain:materialized v1 <hash> -->`+ followed by a bullet) for history that previously existed only in the+ database. Deleting such a bullet with a `put_page` that passes the current+ `expected_revision` deletes its entry. A save without a revision, and a+ connector refresh, keep marked entries and write them back. Managed sync+ never rewrites the user's own file to add them.+ - A page write that adds a takes row whose number already belongs to a+ database-only take fails with `take_row_collision`. Renumber the new row,+ or add the existing take to the page's takes table with a revision-bound+ `put_page`.+ - Atoms from transcripts or from pages that are private or no longer exist+ are private. Do not set `search.remote_private_pages` to restore remote+ access; that exposes every private page.+ - Pages that refused writes because of a missing `type:` line, a trimmed+ title, a Git-subfolder source path, a macOS device renumbering or a+ `capture --file` path accept writes again without a repair. A refusal that+ remains now names its reason (`file_database_drift`,+ `ambiguous_source_path`, `physical_root_device_changed`,+ `cursor_processing_options_conflict`, `invalid_source_uri`) and the command+ to run.+ - `persistence.receipt_retention_days` (default 30) is configurable. Only+ change it when the user asks.+ - The first rebuild of a contextual-retrieval page re-embeds it once; after+ that, unchanged pages keep their vectors. Remote search results carry+ `safe_index_pending` whenever pages in the caller's scope are withheld,+ even when some results came back.+ - A claude.ai connector stuck read-only needs to be removed and re-added; a+ looping ChatGPT connector needs to be reconnected.++7. **Verify:**++ ```bash+ gbrain --version+ gbrain repair --json # every kind reports 0 items+ gbrain doctor --json # timeline_history, derived_visibility ok; unsealed_pages 0+ gbrain timeline <slug> # an edited page still lists its older entries+ ```++If a step fails, keep the doctor output and do not delete receipts, counters,+effect rows or dead jobs to make a warning disappear.diff --git a/skills/skills.lock.json b/skills/skills.lock.jsonindex 2051111db6..0ad207b32e 100644--- a/skills/skills.lock.json+++ b/skills/skills.lock.json@@ -151,6 +151,7 @@"migrations/v0.59.0.0.md": "7903e547e79ad3429a393d9102a610e2674388bfaa71607431b1cd857b4af939","migrations/v0.59.10.0.md": "e0268a05ab184d5518f88747313e772629b2af91db59eacbba728f2ebd9db3cd","migrations/v0.59.2.0.md": "b6d61af8ef48c154a26e8d427dd6f6570e99efb82b891728426046eea493247b",+ "migrations/v0.60.5.0.md": "0d3ee19359a2740de08ac9ec388ddc15e7c72d663afe33832e1e54170528acab","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 8581fdc1cc..826d0bc3ef 100755--- a/src/cli.ts+++ b/src/cli.ts@@ -83,7 +83,7 @@ export function normalizeLocalResult(rawResult: unknown): unknown {}// CLI-only commands that bypass the operation layer-export const CLI_ONLY = new Set(['mcp', 'init', 'reinit-pglite', 'pglite-repair', 'upgrade', 'post-upgrade', 'check-update', 'integrations', 'publish', 'check-backlinks', 'lint', 'report', 'import', 'export', 'files', 'embed', 'serve', 'call', 'config', 'doctor', 'migrate', 'eval', 'sync', 'extract', 'extract-conversation-facts', 'enrich', 'features', 'autopilot', 'graph-query', 'jobs', 'agent', 'apply-migrations', 'skillpack-check', 'skillpack', 'resolvers', 'integrity', 'repair-jsonb', 'orphans', 'maintain', 'sources', 'mounts', 'dream', 'check-resolvable', 'routing-eval', 'skillify', 'smoke-test', 'providers', 'storage', 'repos', 'code-def', 'code-refs', 'reindex', 'reindex-code', 'reindex-frontmatter', 'code-callers', 'code-callees', 'reconcile-links', 'frontmatter', 'auth', 'friction', 'claw-test', 'book-mirror', 'takes', 'think', 'salience', 'anomalies', 'calibration', 'transcripts', 'models', 'remote', 'recall', 'forget', 'edges-backfill', 'cache', 'retrieval-upgrade', 'founder', 'brainstorm', 'lsd', 'schema', 'capture', 'onboard', 'conversation-parser', 'status', 'connect', 'connectors', 'skillopt', 'quarantine', 'self-upgrade', 'protocol', 'advisor', 'watch', 'reindex-search-vector', 'pages', 'bench', 'backfill',+export const CLI_ONLY = new Set(['mcp', 'init', 'repair', 'reinit-pglite', 'pglite-repair', 'upgrade', 'post-upgrade', 'check-update', 'integrations', 'publish', 'check-backlinks', 'lint', 'report', 'import', 'export', 'files', 'embed', 'serve', 'call', 'config', 'doctor', 'migrate', 'eval', 'sync', 'extract', 'extract-conversation-facts', 'enrich', 'features', 'autopilot', 'graph-query', 'jobs', 'agent', 'apply-migrations', 'skillpack-check', 'skillpack', 'resolvers', 'integrity', 'repair-jsonb', 'orphans', 'maintain', 'sources', 'mounts', 'dream', 'check-resolvable', 'routing-eval', 'skillify', 'smoke-test', 'providers', 'storage', 'repos', 'code-def', 'code-refs', 'reindex', 'reindex-code', 'reindex-frontmatter', 'code-callers', 'code-callees', 'reconcile-links', 'frontmatter', 'auth', 'friction', 'claw-test', 'book-mirror', 'takes', 'think', 'salience', 'anomalies', 'calibration', 'transcripts', 'models', 'remote', 'recall', 'forget', 'edges-backfill', 'cache', 'retrieval-upgrade', 'founder', 'brainstorm', 'lsd', 'schema', 'capture', 'onboard', 'conversation-parser', 'status', 'connect', 'connectors', 'skillopt', 'quarantine', 'self-upgrade', 'protocol', 'advisor', 'watch', 'reindex-search-vector', 'pages', 'bench', 'backfill',// v0.42.58 (#2035 class, caught by the handleCliOnly reachability sweep):// full handler at `case 'notability-eval'` but never dispatchable.'notability-eval',@@ -253,6 +253,8 @@ const CLI_ONLY_SELF_HELP = new Set([// or help-before-engine; the generic stub would hide the [SHOW USER]// setup contract agents depend on.'google', 'creds', 'loops', 'waiting',+ // gbrain repair prints REPAIR_HELP (kinds + dry-run/apply contract).+ 'repair',]);/**@@ -270,6 +272,7 @@ const SELF_HELP_WITHOUT_ENGINE: Record<string, () => Promise<(engine: never, argwatch: async () => (await import('./commands/watch.ts')).runWatch as never,skillopt: async () => (await import('./commands/skillopt.ts')).runSkillOptCommand as never,maintain: async () => (await import('./commands/maintain.ts')).runMaintain as never,+ repair: async () => (await import('./commands/repair.ts')).runRepairCommand as never,'extract-conversation-facts': async () =>(await import('./commands/extract-conversation-facts.ts')).runExtractConversationFacts as never,transcripts: async () => (await import('./commands/transcripts.ts')).runTranscripts as never,@@ -2014,6 +2017,8 @@ export const THIN_CLIENT_REFUSED_COMMANDS = new Set([// cathedral-5: compiled views read the LOCAL brain (thin clients have// no engine to compile from; remote-brain support is a filed follow-up).'compile-context',+ // Wave 2 repair core: repairs publish coordinated writes on the brain host.+ 'repair',]);/**@@ -2063,6 +2068,7 @@ const THIN_CLIENT_REFUSE_HINTS: Record<string, string> = {// hint fires — these fire only for the host-bound remainder.search: '`search modes|stats|tune` route to the brain host automatically (search_modes / search_stats / search_tune MCP ops). The modes reset form, modes with the source flag (the reset dry-run), and tune apply mutate or preview host config, and `diagnose` runs live retrieval — run those on the host.',cache: '`cache stats` routes to the brain host automatically (cache_stats MCP op). clear/prune mutate the host cache — run those on the host.',+ repair: 'repair runs on the brain host (it publishes coordinated page writes against the local engine). Run `gbrain repair` on the brain host.',quarantine: '`quarantine list` routes to the brain host automatically (quarantine_list MCP op). scan/clear are host-bound (bulk re-import; the clear trust decision) — run those on the host.',};@@ -3234,6 +3240,11 @@ async function handleCliOnly(command: string, args: string[]) {await runReconcileLinksCli(engine, args);break;}+ case 'repair': {+ const { runRepairCommand } = await import('./commands/repair.ts');+ await runRepairCommand(engine, args);+ break;+ }case 'orphans': {const { runOrphans } = await import('./commands/orphans.ts');await runOrphans(engine, args);@@ -3862,6 +3873,7 @@ SETUPmigrate embeddings --to <p:model> Re-embed onto another embedding providerupgrade Self-updatecheck-update [--json] Check for new versions+ repair [<kind>] [--apply] Preview/apply residual repairs (timeline, visibility, safe-chunks)doctor [--json] [--fast] [--probe-pglite] Health check (resolver, skills, pgvector, RLS, embeddings; --probe-pglite runs the scratch-store probe)integrations [subcommand] Manage integration recipes (senses + reflexes)diff --git a/src/commands/autopilot.ts b/src/commands/autopilot.tsindex c10730f5d0..cedae7d1fc 100644--- a/src/commands/autopilot.ts+++ b/src/commands/autopilot.ts@@ -1348,6 +1348,7 @@ export async function runAutopilot(engine: BrainEngine, args: string[]) {// doctor's planner (file plane, per the #2662 rule above) said was// missing, so autopilot dispatched chat jobs doctor called blocked.hasChatApiKey: chatApiKeyConfigured(fileCfg),+ staleExtractionBlocked: await (await import('../core/remediation/context.ts')).staleExtractionBlocked(engine).catch(() => undefined),};// v0.41.18.0 (A5 + A19 + A22, T15): consult onboard recommendations// ALONGSIDE doctor's brain-score recommendations. Onboard's 4 newdiff --git a/src/commands/capture.ts b/src/commands/capture.tsindex 1c0b917e73..f059bd9786 100644--- a/src/commands/capture.ts+++ b/src/commands/capture.ts@@ -31,6 +31,7 @@*/import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';import type { BrainEngine } from '../core/engine.ts';import { loadConfig, isThinClient } from '../core/config.ts';import { callRemoteTool, unpackToolResult, RemoteMcpError } from '../core/mcp-client.ts';@@ -376,7 +377,8 @@ export async function runCapture(engine: BrainEngine | null, args: string[], opt...(parsed.kind ? { kind: parsed.kind } : {}),...(parsed.depth ? { depth: parsed.depth } : {}),source_kind: 'capture-cli',- source_uri: parsed.filePath ? `file://${parsed.filePath}` : parsed.stdin ? 'stdin' : 'cli-positional',+ // #5622: the owner maps a local file to its source-relative origin (or 'cli-file'); no file URI or home path is stored.+ ...(parsed.filePath ? isThinClient(cfg) ? {} : { local_file: resolve(parsed.filePath) } : { source_uri: parsed.stdin ? 'stdin' : 'cli-positional' }),ingested_via: 'capture-cli',};let result: Record<string, unknown>;diff --git a/src/commands/config.ts b/src/commands/config.tsindex 2d4806301b..bcda406046 100644--- a/src/commands/config.ts+++ b/src/commands/config.ts@@ -835,6 +835,14 @@ export async function runConfig(engine: BrainEngine, args: string[]) {const coverageOverride =args.includes('--coverage-override') || args.includes('--yes');+ // #5470: every admission parses the journal caps; a malformed value+ // would refuse all managed writes, so reject it here.+ const { JOURNAL_CONFIG_KEYS, parseJournalConfigValue } = await import('../core/persistence/limits.ts');+ if (JOURNAL_CONFIG_KEYS.includes(key)) {+ try { parseJournalConfigValue(key, value); }+ catch (error) { console.error(`[config] ${(error as Error).message}`); process.exit(1); }+ }+// #4348: validate cycle.timezone at set time — resolveCycleDate falls// back loudly at run time, but the typo should be rejected here, at the// moment the operator can fix it.diff --git a/src/commands/doctor.ts b/src/commands/doctor.tsindex 9745953c0b..2e99efade8 100644--- a/src/commands/doctor.ts+++ b/src/commands/doctor.ts@@ -25,6 +25,8 @@ import { VERSION as GBRAIN_BINARY_VERSION } from '../version.ts';import { schemaVersionHealth } from '../core/schema-version-health.ts';import { zeroTotalContradictionsCheck } from '../core/eval-contradictions/run-health.ts';import { checkProjectionReadiness } from './doctor/checks/projection-readiness.ts';+import { checkPersistenceCapacity } from './doctor/checks/persistence-capacity.ts';+import { checkParkedEffects } from './doctor/checks/parked-effects.ts';import { checkPostgresCancellationDriver } from './doctor/checks/postgres-cancellation.ts';export { checkPostgresCancellationDriver } from './doctor/checks/postgres-cancellation.ts';export { checkProjectionReadiness } from './doctor/checks/projection-readiness.ts';@@ -873,6 +875,16 @@ export async function buildChecks(}}+ // 2g. Dream paid-loop breaker: keys whose submissions keep dying.+ if (engine) {+ try {+ const { dreamPaidLoopCheck } = await import('./doctor/checks/dream-breaker.ts');+ checks.push(await dreamPaidLoopCheck(engine));+ } catch (e) {+ checks.push({ name: 'dream_paid_loop', status: 'warn', message: `Could not count dead dream submissions: ${e instanceof Error ? e.message : String(e)}` });+ }+ }+// 3. Half-migrated Minions detection (filesystem-only).// If completed.jsonl has any status:"partial" entry with no later// status:"complete" for the same version, the install is mid-migration.@@ -1886,6 +1898,10 @@ export async function buildChecks(checks.push(await pagesUpsertArbiterCheck(engine));checks.push(await checkProjectionReadiness(engine));+ // 4a-bis. Managed write capacity (#5470) and parked postcommit effects (#5612).+ progress.heartbeat('persistence_capacity');+ checks.push(await checkPersistenceCapacity(engine), await checkParkedEffects(engine));+// 4a-ter. #4613: links_link_source_check shape — a ledger-current brain// whose CHECK reverted to the pre-v114 allowlist rejects every kebab// provenance write; the version counter can't see it.@@ -2660,6 +2676,15 @@ export async function buildChecks(staleMentionsHb();}+ // 9d. Wave 2 residual-state signals (#5567, #5525): database-only timeline+ // rows and derived pages without explicit visibility. Bounded, never throw.+ progress.heartbeat('timeline_history');+ {+ const { timelineHistoryCheck } = await import('./doctor/checks/timeline-history.ts');+ const { derivedVisibilityCheck } = await import('./doctor/checks/derived-visibility.ts');+ checks.push(await timelineHistoryCheck(engine, orphanRatioSourceId), await derivedVisibilityCheck(engine, orphanRatioSourceId));+ }+// 10. Integrity sample scan (v0.13 knowledge runtime).// Read-only — no network, no writes, no resolver calls. Samples the first// 500 pages by slug order and surfaces bare-tweet + dead-link counts as adiff --git a/src/commands/doctor/checks/calibration.ts b/src/commands/doctor/checks/calibration.tsindex 17847c2738..1a6ecc601a 100644--- a/src/commands/doctor/checks/calibration.ts+++ b/src/commands/doctor/checks/calibration.ts@@ -59,25 +59,26 @@ export async function checkContextualRetrievalCoverage(): Promise<Check> {try {const { MARKDOWN_CHUNKER_VERSION } = await import('../../../core/chunkers/recursive.ts');- const rows = await engine.executeRaw<{ chunker_drift: number; unsealed: number; mode_null: number }>(+ const rows = await engine.executeRaw<{ chunker_drift: number; unsealed: number; unsealed_code: number; mode_null: number }>(`SELECT- COUNT(*) FILTER (WHERE chunker_version < $1)::int AS chunker_drift,- -- #5004: pages the safe-chunk fence withholds from every remote read.- -- Counted separately from drift: the chunker version may move past- -- the fence floor, and only the fence has this consequence.+ COUNT(*) FILTER (WHERE page_kind = 'markdown' AND chunker_version < $1)::int AS chunker_drift,+ -- #5004/#5247: pages of every kind the safe-chunk fence withholds from+ -- every remote read. Counted separately from drift: the chunker version+ -- may move past the fence floor, and only the fence has this consequence.COUNT(*) FILTER (WHERE NOT (${safeChunksFilter('pages')}))::int AS unsealed,+ COUNT(*) FILTER (WHERE page_kind = 'code' AND NOT (${safeChunksFilter('pages')}))::int AS unsealed_code,-- #4009 belt+braces: extract receipts are audit artifacts stamped-- mode 'none' at write time, but a reindex DB fallback can clear-- the stamp — never count them as "never evaluated".- COUNT(*) FILTER (WHERE contextual_retrieval_mode IS NULL AND type <> 'extract_receipt')::int AS mode_null+ COUNT(*) FILTER (WHERE page_kind = 'markdown' AND contextual_retrieval_mode IS NULL AND type <> 'extract_receipt')::int AS mode_nullFROM pages- WHERE page_kind = 'markdown'- AND deleted_at IS NULL+ WHERE deleted_at IS NULL${opts.sourceIds ? 'AND source_id = ANY($2::text[])' : ''}`,opts.sourceIds ? [MARKDOWN_CHUNKER_VERSION, opts.sourceIds] : [MARKDOWN_CHUNKER_VERSION],);const chunkerDrift = rows[0]?.chunker_drift ?? 0;const unsealed = rows[0]?.unsealed ?? 0;+ const unsealedCode = rows[0]?.unsealed_code ?? 0;const modeNull = rows[0]?.mode_null ?? 0;// Synopsis-failures audit summary (best-effort; missing audit file = 0).@@ -96,12 +97,14 @@ export async function checkContextualRetrievalCoverage(// Audit module unavailable — skip the summary line.}- const needsReindex = chunkerDrift > 0 || unsealed > 0 || modeNull > 0;- if (!needsReindex && failureSummaryLine === '') {+ const needsReindex = chunkerDrift > 0 || modeNull > 0;+ const details = { unsealed_pages: unsealed, unsealed_code_pages: unsealedCode, count: 'exact', repair: 'safe-chunks' };+ if (!needsReindex && unsealed === 0 && failureSummaryLine === '') {return {name: 'contextual_retrieval_coverage',status: 'ok',- message: 'All markdown pages aligned to current chunker + CR mode.',+ message: 'All pages aligned to current chunker + CR mode.',+ details,};}@@ -110,16 +113,18 @@ export async function checkContextualRetrievalCoverage(parts.push(`${chunkerDrift} page(s) at older chunker_version`);}if (unsealed > 0) {- parts.push(`${unsealed} page(s) below the safe-chunk index version — withheld from remote/MCP chunk retrieval until reindexed`);+ parts.push(`${unsealed} page(s) below the safe-chunk index version${unsealedCode ? ` (${unsealedCode} code)` : ''} — withheld from remote/MCP chunk retrieval until re-sealed`);}if (modeNull > 0) {parts.push(`${modeNull} page(s) never evaluated against CR ladder`);}- const fixHint = needsReindex ? ` Run \`gbrain reindex --markdown\` to align.` : '';+ const fixHint = (unsealed > 0 ? ' Preview the re-seal: gbrain repair safe-chunks — apply: gbrain repair safe-chunks --apply.' : '')+ + (needsReindex ? ` Run \`gbrain reindex --markdown\` to align.` : '');return {name: 'contextual_retrieval_coverage',- status: needsReindex ? 'warn' : 'ok',+ status: needsReindex || unsealed > 0 ? 'warn' : 'ok',message: `${parts.join('; ')}.${fixHint}${failureSummaryLine}`,+ details,};} catch (e) {return {diff --git a/src/commands/doctor/checks/derived-visibility.ts b/src/commands/doctor/checks/derived-visibility.tsnew file mode 100644index 0000000000..0956a979db--- /dev/null+++ b/src/commands/doctor/checks/derived-visibility.ts@@ -0,0 +1,42 @@+/**+ * derived_visibility doctor check (#5525): extracted atoms and synthesized+ * concepts without an explicit `visibility`, and ones stored looser than their+ * origin (a transcript or missing origin counts as private, as in the repair).+ * Remote reads treat unstamped rows as private; the warning names the+ * tighten-only backfill `gbrain repair visibility` that stamps the stored rows.+ * One indexed aggregate query; counts are exact.+ */+import type { BrainEngine } from '../../../core/engine.ts';+import type { Check } from '../../doctor.ts';+import { privateSnapshotFilterFragment } from '../../../core/search/private-visibility.ts';++export async function derivedVisibilityCheck(engine: BrainEngine, sourceId?: string): Promise<Check> {+ const name = 'derived_visibility';+ try {+ const [row] = await engine.executeRaw<{ unstamped_atoms: number; unstamped_concepts: number; looser_atoms: number; looser_concepts: number }>(+ `WITH derived AS (+ SELECT p.* FROM pages p WHERE p.deleted_at IS NULL ${sourceId ? 'AND p.source_id=$1' : ''}+ AND (p.type='atom' OR (p.type='concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)))+ SELECT+ COUNT(*) FILTER (WHERE d.type='atom' AND d.frontmatter->>'visibility' IS NULL)::int AS unstamped_atoms,+ COUNT(*) FILTER (WHERE d.type='concept' AND d.frontmatter->>'visibility' IS NULL)::int AS unstamped_concepts,+ COUNT(*) FILTER (WHERE d.type='atom' AND d.frontmatter->>'visibility'='world' AND NOT EXISTS (SELECT 1 FROM pages o+ WHERE o.source_id=d.source_id AND o.slug=d.frontmatter->>'source_slug' AND o.deleted_at IS NULL+ AND ${privateSnapshotFilterFragment('o')}))::int AS looser_atoms,+ COUNT(*) FILTER (WHERE d.type='concept' AND d.frontmatter->>'visibility'='world' AND EXISTS (SELECT 1 FROM links l+ JOIN pages a ON a.id=l.to_page_id WHERE l.from_page_id=d.id AND l.link_source='concept-provenance' AND l.link_type='synthesized_from'+ AND (COALESCE(a.frontmatter->>'visibility','private')='private' OR EXISTS (SELECT 1 FROM pages ao WHERE ao.source_id=a.source_id+ AND ao.slug=a.frontmatter->>'source_slug' AND ao.frontmatter->>'visibility'='private'))))::int AS looser_concepts+ FROM derived d`, sourceId ? [sourceId] : []);+ const details = { ...row, count: 'exact', truncated: false, repair: 'visibility' };+ const unstamped = row.unstamped_atoms + row.unstamped_concepts;+ const looser = row.looser_atoms + row.looser_concepts;+ if (unstamped + looser === 0) return { name, status: 'ok', details, message: 'Every extracted atom and synthesized concept carries an explicit visibility no looser than its origin.' };+ return { name, status: 'warn', details, message: `${unstamped} derived page(s) have no explicit visibility (${row.unstamped_atoms} atoms, ${row.unstamped_concepts} concepts) `+ + `and ${looser} are stored looser than their origin; remote reads treat the unstamped ones as private. `+ + `Preview: gbrain repair visibility — apply: gbrain repair visibility --apply` };+ } catch (e) {+ return { name, status: 'warn', message: `derived visibility check skipped: ${e instanceof Error ? e.message : String(e)}`,+ details: { count: 'lower_bound', truncated: true } };+ }+}diff --git a/src/commands/doctor/checks/dream-breaker.ts b/src/commands/doctor/checks/dream-breaker.tsnew file mode 100644index 0000000000..d9bbf59470--- /dev/null+++ b/src/commands/doctor/checks/dream-breaker.ts@@ -0,0 +1,27 @@+/**+ * dream_paid_loop: read-only view of the dream paid-loop breaker. Warns when a+ * dream synthesize or patterns key has died at least the breaker limit+ * (`dream.breaker.max_dead_submissions`, default 3) times within 24 hours,+ * using the same counting function the breaker enforces with.+ */+import type { BrainEngine } from '../../../core/engine.ts';+import { countDeadDreamSubmissions, dreamBreakerResetCommand, loadDreamBreakerThreshold, DREAM_BREAKER_CONFIG_KEY } from '../../../core/cycle/dream-breaker.ts';+import type { Check } from '../../doctor.ts';++export async function dreamPaidLoopCheck(engine: BrainEngine): Promise<Check> {+ const threshold = await loadDreamBreakerThreshold(engine);+ const rows = await countDeadDreamSubmissions(engine);+ const limit = threshold === 0 ? 3 : threshold;+ const looping = rows.filter(row => row.dead_submissions >= limit);+ const details = { threshold, breaker_enabled: threshold > 0, inspected_keys: rows.length, count_exact: true,+ keys: looping.map(row => ({ key_prefix: row.base_key.startsWith('dream:patterns:') ? 'dream:patterns:' : 'dream:synth-v2:', ...row })) };+ if (looping.length === 0) {+ return { name: 'dream_paid_loop', status: 'ok', message: `No dream key died ${limit}+ times in 24h`, details };+ }+ const shown = looping.slice(0, 3).map(row => `${row.base_key} (${row.dead_submissions}x)`).join('; ');+ const action = threshold === 0+ ? `The breaker is disabled (${DREAM_BREAKER_CONFIG_KEY}=0), so these keys are still being resubmitted.`+ : `The breaker refuses them until reset; fix the cause, then run ${dreamBreakerResetCommand(looping[0]!.base_key)}.`;+ return { name: 'dream_paid_loop', status: 'warn',+ message: `${looping.length} dream key(s) died ${limit}+ times in 24h: ${shown}. ${action}`, details };+}diff --git a/src/commands/doctor/checks/extraction-sync.ts b/src/commands/doctor/checks/extraction-sync.tsindex 3c7f87e02d..8cc55afb3b 100644--- a/src/commands/doctor/checks/extraction-sync.ts+++ b/src/commands/doctor/checks/extraction-sync.ts@@ -23,6 +23,7 @@ import {} from '../../../core/storage-config.ts';import { slugifyPath, slugifyCodePath, isCodeFilePath } from '../../../core/sync.ts';import { resolveSourceLocalFilePath } from '../../../core/markdown.ts';+import { scannerSlugRootMode } from '../../../core/write-through.ts';import { unverifiedExtractionFragment } from '../../../core/extraction-review.ts';import type { Check } from '../../doctor.ts';import { ownedContentFreshness } from '../../../core/shared-skills/content-freshness.ts';@@ -410,10 +411,11 @@ export async function checkUndeclaredDbOnlyPages(engine: BrainEngine): Promise<C);if (rows.length === 0) continue;let backedWithoutSourcePath: Set<string> | null = null;+ const mode = await scannerSlugRootMode(engine, src.id, src.local_path!);for (const { slug, source_path: sourcePath } of rows) {if (dbOnlyDirs.some(dir => slug.startsWith(dir))) continue;if (sourcePath) {- const filePath = resolveSourceLocalFilePath(src.local_path!, sourcePath, slug);+ const filePath = resolveSourceLocalFilePath(src.local_path!, sourcePath, slug, mode);if (filePath && existsSync(filePath)) continue;} else {backedWithoutSourcePath ??= collectMarkdownSlugs(src.local_path!);diff --git a/src/commands/doctor/checks/parked-effects.ts b/src/commands/doctor/checks/parked-effects.tsnew file mode 100644index 0000000000..181f4541f6--- /dev/null+++ b/src/commands/doctor/checks/parked-effects.ts@@ -0,0 +1,32 @@+import type { BrainEngine } from '../../../core/engine.ts';+import type { Check } from '../../doctor.ts';+import type { ParkedTarget } from '../../../core/persistence/effect-model.ts';++const SAMPLE = 20;++/**+ * #5612: Git and withdrawal targets that failed five consecutive times are+ * parked instead of retried forever. Reads the partial `persistence_effects_parked`+ * index: an exact count plus a capped sample naming each page and its retry command.+ */+export async function checkParkedEffects(engine: BrainEngine): Promise<Check> {+ try {+ const [{ count }] = await engine.executeRaw<{ count: number }>(`SELECT COUNT(*)::int AS count FROM persistence_effects WHERE data ? 'parked'`);+ const rows = await engine.executeRaw<{ request_id: string; source_id: string; kind: string; state: string; parked: ParkedTarget[] }>(+ `SELECT r.request_id::text AS request_id,e.source_id,e.kind,e.state,e.data->'parked' AS parked FROM persistence_effects e+ JOIN persistence_requests r ON r.id=e.request_id WHERE e.data ? 'parked' ORDER BY e.id LIMIT ${SAMPLE}`);+ const effects = rows.map(row => ({ ...row, command: `gbrain sources writer retry-effects ${row.source_id} --request-id ${row.request_id} --dry-run` }));+ const details = { parked_effects: count, exact: true, inspected: rows.length, truncated: count > rows.length, effects };+ if (!count) return { name: 'parked_effects', status: 'ok', message: 'No Git or withdrawal effect is parked.', details };+ const listed = effects.map(effect => `${effect.kind} ${effect.source_id}: ${effect.parked.map(target =>+ `${target.slug ?? '(whole effect)'} (${target.error_code})`).join(', ')}; ${effect.command}`);+ return { name: 'parked_effects', status: 'warn', details,+ message: `${count} Git or withdrawal effect(s) have parked targets after five consecutive failures; their withdrawal or Git backup is incomplete. ` ++ `Inspect \`gbrain sources writer status <source>\`, fix the cause, preview with the command shown, then rerun it without --dry-run to authorize one more attempt: ${listed.join(' | ')}` ++ (count > rows.length ? ` (first ${rows.length} of ${count} shown)` : '') };+ } catch (error) {+ return { name: 'parked_effects', status: 'warn',+ message: `Parked effects could not be read: ${error instanceof Error ? error.message : String(error)}. Health is unknown.`,+ details: { exact: false, inspected: 0, truncated: true } };+ }+}diff --git a/src/commands/doctor/checks/persistence-capacity.ts b/src/commands/doctor/checks/persistence-capacity.tsnew file mode 100644index 0000000000..de6249cf5d--- /dev/null+++ b/src/commands/doctor/checks/persistence-capacity.ts@@ -0,0 +1,39 @@+import type { BrainEngine } from '../../../core/engine.ts';+import type { Check } from '../../doctor.ts';+import { capacityDiagnostics } from '../../../core/persistence/diagnostics.ts';+import { oneYearCapacity, readJournalLimits } from '../../../core/persistence/limits.ts';++/**+ * #5470: warn at 80% of a cumulative managed-write cap (permanent request IDs,+ * receipt bytes) before admission refuses. Transient caps drain on their own.+ * Bounded: one indexed read per counter row (brain plus each principal).+ */+export async function checkPersistenceCapacity(engine: BrainEngine): Promise<Check> {+ try {+ const counters = await engine.executeRaw<{ key: string; outstanding_count: string; intent_bytes: string; lifetime_ids: string;+ terminal_bytes: string; recovery_bytes: string }>(`SELECT key,outstanding_count::text,intent_bytes::text,lifetime_ids::text,+ terminal_bytes::text,recovery_bytes::text FROM persistence_counters WHERE key='brain' OR key LIKE 'principal:%' ORDER BY key`);+ const limits = await readJournalLimits(engine);+ const near = capacityDiagnostics(counters, limits)+ .filter(row => row.approaching_capacity && (row.resource === 'lifetime_ids' || row.resource === 'terminal_bytes'));+ const resources = [];+ const needed = new Map<string, number>();+ for (const row of near) {+ const value = await oneYearCapacity(engine, row.scope, row.resource === 'lifetime_ids' ? 'LifetimeIds' : 'TerminalBytes', row.used, row.limit);+ resources.push({ scope: row.scope, resource: row.resource, used: row.used, limit: row.limit, config_key: row.config_key });+ needed.set(row.config_key, Math.max(needed.get(row.config_key) ?? 0, value));+ }+ // Every principal shares one brain-wide key, so each key gets the largest value any scope needs.+ const commands = [...needed].map(([key, value]) => `gbrain config set ${key} ${value}`);+ const details = { exact: true, inspected: counters.length, truncated: false, resources, commands };+ if (!resources.length) return { name: 'persistence_capacity', status: 'ok', message: 'Managed write capacity is below 80% of every cumulative limit.', details };+ return { name: 'persistence_capacity', status: 'warn', details,+ message: `${resources.length} managed write limit(s) at or above 80%: ${resources.map(r =>+ `${r.scope} ${r.resource} ${r.used}/${r.limit}`).join('; ')}. Admission refuses at the limit. Run on the brain host: ${commands.join('; ')} ` ++ '(each covers about one more year at the current admission rate). This is a mitigation: permanent request IDs are never evicted.' };+ } catch (error) {+ return { name: 'persistence_capacity', status: 'warn',+ message: `Managed write capacity could not be read: ${error instanceof Error ? error.message : String(error)}. Health is unknown.`,+ details: { exact: false, inspected: 0, truncated: true } };+ }+}diff --git a/src/commands/doctor/checks/timeline-history.ts b/src/commands/doctor/checks/timeline-history.tsnew file mode 100644index 0000000000..6bf369c534--- /dev/null+++ b/src/commands/doctor/checks/timeline-history.ts@@ -0,0 +1,44 @@+/**+ * timeline_history doctor check (#5567): timeline rows that exist only in the+ * database, with no bullet in their page. Materializable rows warn and name+ * `gbrain repair timeline`; rows that cannot round-trip through the page are+ * kept by every writer and reported as informational.+ *+ * Bounded: pages carrying non-event timeline rows are classified in id order+ * up to PAGE_CAP pages or TIME_BUDGET_MS. A truncated scan reports its counts+ * as a lower bound and is never reported as clean.+ */+import type { BrainEngine } from '../../../core/engine.ts';+import type { Check } from '../../doctor.ts';+import { scanTimelineHistory } from '../../../core/repair/timeline.ts';++const PAGE_CAP = 2_000;+const TIME_BUDGET_MS = 10_000;++export async function timelineHistoryCheck(engine: BrainEngine, sourceId?: string, opts: { pageCap?: number } = {}): Promise<Check> {+ const name = 'timeline_history';+ try {+ const sources = sourceId ? [sourceId] : (await engine.executeRaw<{ id: string }>('SELECT id FROM sources WHERE archived IS NOT TRUE')).map(r => r.id);+ const scan = await scanTimelineHistory(engine, sources, 0, { pages: opts.pageCap ?? PAGE_CAP, deadline: Date.now() + TIME_BUDGET_MS });+ const materializable = scan.pages.reduce((n, p) => n + p.materializable, 0);+ const unrenderable = scan.pages.reduce((n, p) => n + p.unrenderable, 0);+ const count = scan.truncated ? 'lower_bound' : 'exact';+ const details = { materializable_rows: materializable, kept_unrenderable_rows: unrenderable, pages_affected: scan.pages.filter(p => p.materializable).length,+ pages_inspected: scan.inspected, count, truncated: scan.truncated, repair: 'timeline' };+ const bound = scan.truncated ? `at least ` : '';+ const coverage = scan.truncated ? ` (scan stopped after ${scan.inspected} pages; counts are a lower bound)` : '';+ if (materializable > 0) {+ return { name, status: 'warn', details, message: `${bound}${materializable} timeline row(s) on ${details.pages_affected} page(s) exist only in the database${coverage}. `+ + `Preview: gbrain repair timeline — apply: gbrain repair timeline --apply` + (unrenderable ? `. ${unrenderable} other row(s) cannot round-trip and are kept as-is.` : '') };+ }+ if (scan.truncated) {+ return { name, status: 'warn', details, message: `Timeline history scan incomplete${coverage}; run \`gbrain repair timeline\` for the full count.` };+ }+ return { name, status: 'ok', details, message: unrenderable+ ? `No materializable database-only timeline rows; ${unrenderable} row(s) cannot round-trip through their page and are kept as-is (informational).`+ : `Every timeline row has a bullet in its page (${scan.inspected} page(s) inspected).` };+ } catch (e) {+ return { name, status: 'warn', message: `timeline history check skipped: ${e instanceof Error ? e.message : String(e)}`,+ details: { count: 'lower_bound', truncated: true } };+ }+}diff --git a/src/commands/dream-reset-key.ts b/src/commands/dream-reset-key.tsnew file mode 100644index 0000000000..c981f64dc4--- /dev/null+++ b/src/commands/dream-reset-key.ts@@ -0,0 +1,63 @@+/**+ * `gbrain dream reset-key <base-key>` / `gbrain dream reset-key --list [--json]`+ * — the operator controls for the dream paid-loop breaker (dream-breaker.ts).+ */+import type { BrainEngine } from '../core/engine.ts';+import {+ countDeadDreamSubmissions, dreamBreakerBaseKey, dreamBreakerResetCommand, loadDreamBreakerThreshold,+ resetDreamBreakerKey, DREAM_BREAKER_CONFIG_KEY, DREAM_BREAKER_KEY_PREFIXES,+} from '../core/cycle/dream-breaker.ts';+import { setCliExitVerdict } from '../core/cli-force-exit.ts';++const HELP = `Usage: gbrain dream reset-key <base-key>+ gbrain dream reset-key --list [--json]++The paid-loop breaker refuses to resubmit a dream synthesize or patterns key+whose submissions died ${'`'}${DREAM_BREAKER_CONFIG_KEY}${'`'} times (default 3) within 24 hours.++ <base-key> Re-enable one key (without any :c<i>of<n> chunk suffix). The reset+ is stored in the brain and survives restarts; deaths after it+ count again.+ --list Show tripped keys with their dead-submission counts.+ --json Machine-readable --list output.+`;++export async function runDreamResetKey(engine: BrainEngine | null, args: string[]): Promise<void> {+ if (args.includes('--help') || args.includes('-h')) { console.log(HELP); return; }+ const list = args.includes('--list');+ const json = args.includes('--json');+ const positional = args.filter(arg => !arg.startsWith('--'));+ if (list === (positional.length === 1) || positional.length > 1) {+ console.error(HELP);+ setCliExitVerdict(2);+ return;+ }+ if (!engine) {+ console.error('gbrain dream reset-key needs the brain database; the connection failed.');+ setCliExitVerdict(1);+ return;+ }+ if (list) {+ const threshold = await loadDreamBreakerThreshold(engine);+ const rows = await countDeadDreamSubmissions(engine);+ const tripped = threshold === 0 ? [] : rows.filter(row => row.dead_submissions >= threshold);+ if (json) {+ console.log(JSON.stringify({ threshold, enabled: threshold > 0, tripped: tripped.map(row => ({ ...row, reset_command: dreamBreakerResetCommand(row.base_key) })) }, null, 2));+ return;+ }+ if (threshold === 0) { console.log(`The paid-loop breaker is disabled (${DREAM_BREAKER_CONFIG_KEY}=0).`); return; }+ if (tripped.length === 0) { console.log(`No tripped dream keys (limit ${threshold} dead submissions in 24h).`); return; }+ console.log(`Tripped dream keys (limit ${threshold} dead submissions in 24h):`);+ for (const row of tripped) console.log(` ${row.dead_submissions}x ${row.base_key}\n last death ${row.last_dead_at}; reset: ${dreamBreakerResetCommand(row.base_key)}`);+ return;+ }+ const baseKey = dreamBreakerBaseKey(positional[0]!);+ if (!DREAM_BREAKER_KEY_PREFIXES.some(prefix => baseKey.startsWith(prefix))) {+ console.error(`Not a dream breaker key: ${baseKey}. Keys start with ${DREAM_BREAKER_KEY_PREFIXES.join(' or ')}; run gbrain dream reset-key --list.`);+ setCliExitVerdict(2);+ return;+ }+ const before = (await countDeadDreamSubmissions(engine)).find(row => row.base_key === baseKey)?.dead_submissions ?? 0;+ await resetDreamBreakerKey(engine, baseKey);+ console.log(`Reset ${baseKey} (${before} dead submission(s) in the last 24h no longer count). The next dream cycle may submit it again.`);+}diff --git a/src/commands/dream.ts b/src/commands/dream.tsindex 6be766c177..07c27b1d33 100644--- a/src/commands/dream.ts+++ b/src/commands/dream.ts@@ -375,6 +375,7 @@ async function resolveBrainDir(function printHelp() {console.log(`Usage: gbrain dream [options]gbrain dream retriage [flags] (see: gbrain dream retriage --help)+ gbrain dream reset-key <key> | --list (see: gbrain dream reset-key --help)Run one brain maintenance cycle. Eight phases:lint -> backlinks -> sync -> synthesize -> extract -> patterns -> embed -> orphans@@ -668,6 +669,11 @@ export async function runDream(engine: BrainEngine | null, args: string[]): Promawait runDreamRetriage(engine, args.slice(1));return;}+ if (args[0] === 'reset-key') {+ const { runDreamResetKey } = await import('./dream-reset-key.ts');+ await runDreamResetKey(engine, args.slice(1));+ return;+ }// Fail-loud guard (structured-review r3 P1): the CLI flag registry unions// retriage's flags into `dream`, so the pre-dispatch validator accepts// `gbrain dream --reconcile-queue` — but without the `retriage` positional,diff --git a/src/commands/export.ts b/src/commands/export.tsindex f414829f75..51a026ae2d 100644--- a/src/commands/export.ts+++ b/src/commands/export.ts@@ -2,6 +2,7 @@ import { existsSync } from 'node:fs';import { join, resolve } from 'node:path';import type { BrainEngine } from '../core/engine.ts';import { resolveSourceLocalFilePath, serializeMarkdown } from '../core/markdown.ts';+import { scannerSlugRootMode } from '../core/write-through.ts';import { createProgress } from '../core/progress.ts';import { getCliOptions, cliOptsToProgressOptions } from '../core/cli-options.ts';import { loadStorageConfig, isDbOnly } from '../core/storage-config.ts';@@ -108,7 +109,7 @@ a fresh directory. See docs/storage-tiering.md#safe-export.`);if (restoreOnly && storage && repo) {if (!isDbOnly(key.slug, storage)) continue;if (Number(key.source_path_bytes) > 4096) throw new Error('The recorded restore path exceeds the safe path limit.');- const recorded = resolveSourceLocalFilePath(repo, key.source_path, key.slug);+ const recorded = resolveSourceLocalFilePath(repo, key.source_path, key.slug, await scannerSlugRootMode(tx, batchSource, repo));if (key.source_path && !recorded) throw new Error('The recorded restore file path is unsafe. Reconcile it before exporting.');if (existsSync(nativeFileTarget(repo, recorded ?? join(repo, key.slug + '.md')))) continue;}diff --git a/src/commands/extract.ts b/src/commands/extract.tsindex b07932216f..9239e8e557 100644--- a/src/commands/extract.ts+++ b/src/commands/extract.ts@@ -65,6 +65,11 @@ import { inferLinkTypeFromPack } from '../core/schema-pack/link-inference.ts';import { PageRegexBudget } from '../core/schema-pack/redos-guard.ts';export { extractTimelineFromContent, type ExtractedTimelineEntry } from '../core/timeline-extract.ts';import { extractTimelineFromContent, retractRemovedTimelineEntries, type ExtractedTimelineEntry } from '../core/timeline-extract.ts';+import { managedPersistenceEnabled } from '../core/persistence/ownership.ts';+import { withCoordinatedWrite } from '../core/persistence/context.ts';+import { unrecordedCanonicalTimeline } from '../core/persistence/canonical-projections.ts';+import { PageRevisionConflictError } from '../core/page-state/types.ts';+import { DerivedLinkEndpointChangedError } from '../core/derived-links.ts';import { createProgress } from '../core/progress.ts';import { getCliOptions, cliOptsToProgressOptions } from '../core/cli-options.ts';import { pathToSlug, slugifyPath, slugifySegment, pruneDir, isSyncable } from '../core/sync.ts';@@ -2085,7 +2090,7 @@ export async function extractStaleFromDB(*/timeBudgetMs?: number;},-): Promise<{ linksCreated: number; timelineCreated: number; pagesProcessed: number; staleRemaining: number; skippedMissingTarget?: number; skippedCrossSource?: number; skippedAttendanceIncomplete?: number }> {+): Promise<{ linksCreated: number; timelineCreated: number; pagesProcessed: number; staleRemaining: number; skippedMissingTarget?: number; skippedCrossSource?: number; skippedAttendanceIncomplete?: number; skippedChanged?: number }> {const { dryRun, jsonMode, sourceIdFilter, catchUp } = opts;const includeFrontmatter = opts.includeFrontmatter ?? await resolveIncludeFrontmatter(engine);const log = opts.quiet ? (..._args: unknown[]) => {} : console.log;@@ -2151,8 +2156,10 @@ export async function extractStaleFromDB(let afterPageId = 0;let linksCreated = 0, timelineCreated = 0, pagesProcessed = 0;let skippedAttendanceIncomplete = 0;+ let skippedChanged = 0;let budgetHit = false;let packUnavailable = false;+ const managed = await managedPersistenceEnabled(engine);// #2576: candidates whose endpoint pages don't exist are skipped, not// persisted. Counted so a dropped reference is observable in the summary// instead of vanishing silently (the failure mode that hid bug 2).@@ -2172,6 +2179,7 @@ export async function extractStaleFromDB(const timelineRows: TimelineBatchInput[] = [];const processedRefs: Array<{ slug: string; source_id: string; extractedAt: string }> = [];+ let coordinated = 0;for (const page of rows) {const pack = packs.get(page.source_id);@@ -2208,9 +2216,30 @@ export async function extractStaleFromDB(}linkRows.push(resolvedLinkCandidate(c, page.slug, page.source_id, r));}- const written = await engine.replaceDerivedLinks({ slug: page.slug, sourceId: page.source_id,- expectedRevision: snapshot.revision, sourceIncarnation: snapshot.sourceIncarnation }, linkRows, { includeFrontmatter,- expectedEndpoints: capturedLinkEndpoints(linkRows, targetMetadata) });+ const origin = { slug: page.slug, sourceId: page.source_id, expectedRevision: snapshot.revision, sourceIncarnation: snapshot.sourceIncarnation };+ const linkOpts = { includeFrontmatter, expectedEndpoints: capturedLinkEndpoints(linkRows, targetMetadata) };+ const stampIso = page.updated_at.getTime() >= Date.parse(versionTs) ? page.updated_at_iso : versionTs;+ if (managed) {+ // #5609: the coordinator owns canonical projections. Derived links, the+ // canonical timeline tuples and the watermark publish in one+ // revision-bound coordinated transaction; a page edited since the+ // read stays stale for the next run.+ const published = await engine.transaction(tx => withCoordinatedWrite(tx, [page.source_id], async () => {+ const written = await tx.replaceDerivedLinks(origin, linkRows, linkOpts);+ const timeline = (await unrecordedCanonicalTimeline(tx, snapshot.page.id, snapshot.page, page.slug)).map(entry => ({ slug: page.slug, date: entry.date,+ source: entry.source, summary: entry.summary, detail: entry.detail || '', source_id: page.source_id }));+ const created = timeline.length ? await tx.addTimelineEntriesBatch(timeline, { auditSite: 'extract.stale' }) : 0;+ await tx.markPagesExtractedBatch([{ slug: page.slug, source_id: page.source_id }], stampIso);+ return { links: written.created, timeline: created };+ })).catch(error => {+ if (error instanceof PageRevisionConflictError || error instanceof DerivedLinkEndpointChangedError) return null;+ throw error;+ });+ if (!published) { skippedChanged++; continue; }+ linksCreated += published.links; timelineCreated += published.timeline; coordinated++;+ continue;+ }+ const written = await engine.replaceDerivedLinks(origin, linkRows, linkOpts);linksCreated += written.created;for (const entry of parseTimelineEntries(fullContent)) {// #3957: carry the parsed source label — omitting it wrote source=''@@ -2237,9 +2266,6 @@ export async function extractStaleFromDB(// GREATEST(updated_at, versionTs) preserves the race semantics (a real// future edit advances updated_at > versionTs >= stamp → re-extracts)// while lifting old pages to the threshold so they clear.- const stampIso = page.updated_at.getTime() >= Date.parse(versionTs)- ? page.updated_at_iso- : versionTs;processedRefs.push({ slug: page.slug, source_id: page.source_id, extractedAt: stampIso });}@@ -2250,8 +2276,8 @@ export async function extractStaleFromDB(// failure surfaces instead of looping forever.await engine.markPagesExtractedBatch(processedRefs, new Date().toISOString());- pagesProcessed += processedRefs.length;- progress.tick(processedRefs.length);+ pagesProcessed += processedRefs.length + coordinated;+ progress.tick(processedRefs.length + coordinated);afterPageId = rows[rows.length - 1]!.id;if (!catchUp && Date.now() - startMs > timeBudgetMs) { budgetHit = true; break; }@@ -2264,6 +2290,7 @@ export async function extractStaleFromDB(if (!jsonMode) {log(`Extract --stale: ${linksCreated} link(s) + ${timelineCreated} timeline entr(ies) from ${pagesProcessed} page(s).`);if (skippedAttendanceIncomplete) log(`Skipped ${skippedAttendanceIncomplete} page(s) with unresolved attendance; prior links and extraction watermarks were preserved.`);+ if (skippedChanged) log(`Skipped ${skippedChanged} page(s) edited during extraction; they stay stale for the next run.`);if (skippedMissingTarget > 0) {log(`Skipped ${skippedMissingTarget} candidate(s) whose target page doesn't exist (references to non-pages are never persisted).`);}@@ -2279,10 +2306,11 @@ export async function extractStaleFromDB(pages_processed: pagesProcessed, stale_remaining: staleRemaining, budget_hit: budgetHit,skipped_missing_target: skippedMissingTarget, skipped_cross_source: skippedCrossSource,...(skippedAttendanceIncomplete ? { skipped_attendance_incomplete: skippedAttendanceIncomplete } : {}),+ ...(skippedChanged ? { skipped_changed: skippedChanged } : {}),}) + '\n');}return { linksCreated, timelineCreated, pagesProcessed, staleRemaining, skippedMissingTarget, skippedCrossSource,- ...(skippedAttendanceIncomplete ? { skippedAttendanceIncomplete } : {}) };+ ...(skippedAttendanceIncomplete ? { skippedAttendanceIncomplete } : {}), ...(skippedChanged ? { skippedChanged } : {}) };}/**diff --git a/src/commands/hook.ts b/src/commands/hook.tsindex ec35af924c..d5bbc98a9c 100644--- a/src/commands/hook.ts+++ b/src/commands/hook.ts@@ -105,6 +105,7 @@ import {recordBackupSpawn,} from '../core/backup/status-file.ts';import { realpathOrResolve } from '../core/path-confine.ts';+import { isClaudeCliSelfTranscriptPath } from '../core/ai/providers/claude-cli-scratch.ts';// ── Tunables ────────────────────────────────────────────────────────────────@@ -1685,6 +1686,16 @@ async function hookSessionEnd(io: HookIo): Promise<number> {}if (!conf.ok) {degrade(`transcript_${conf.reason}`);+ } else if (+ isClaudeCliSelfTranscriptPath(conf.path) ||+ (ws !== undefined && isClaudeCliSelfTranscriptPath(ws))+ ) {+ // #5413: this session is gbrain's OWN claude-cli subprocess (the+ // scratch cwd fingerprint appears in the transcript path or the+ // payload cwd). Writing it to the dream corpus is a self-ingestion+ // feedback loop — extraction prompts and page content re-enter as+ // "conversations", and synthesize mints duplicate idea pages.+ segmentMode = 'self_transcript';} else {const parsed = spec.parse(conf.path, { collectToolCalls: memorableAllowed });if (sessionId === 'unknown') {diff --git a/src/commands/import.ts b/src/commands/import.tsindex 2795b5dd74..e5c8b24db3 100644--- a/src/commands/import.ts+++ b/src/commands/import.ts@@ -33,6 +33,8 @@ import { realpathOrResolve } from '../core/path-confine.ts';import { slog } from '../core/console-prefix.ts';import { refreshProjectionStatistics } from '../core/search/projection-statistics.ts';import { importManagedFile } from '../core/persistence/import-mutations.ts';+import { estimateCostFromChars, lookupEmbeddingPrice } from '../core/embedding-pricing.ts';+import { getEmbeddingModel } from '../core/ai/gateway.ts';/** Return a refusal when an import target lies outside every admitted root. */export function configuredRootImportError(dir: string, configuredRoots: string[]): string | null {@@ -157,6 +159,14 @@ export function shouldLogIngest(return counts.imported > 0 || counts.errors > 0 || counts.chunksCreated > 0;}+/** Embedding cost of the chunks a safe-chunk re-seal left without vectors; null when the model has no known price. */+function resealEmbeddingUsd(chars: number): number | null {+ try {+ const price = lookupEmbeddingPrice(getEmbeddingModel());+ return price.kind === 'known' ? estimateCostFromChars(chars, price.pricePerMTok) : null;+ } catch { return null; }+}+/** Bug 9 — surface per-file failures so callers (performFullSync) can gate state advances. */export interface RunImportResult {imported: number;@@ -168,6 +178,8 @@ export interface RunImportResult {malformedSkipped?: number;/** Aggregated alias/undeclared explicit-type warnings (schema.type_warnings). */type_warnings?: Array<{ kind: 'alias_of' | 'undeclared'; type: string; canonical?: string; directory?: string; count: number }>;+ /** #5050: unchanged pages re-sealed at the safe-chunk fence, and the embedding work that left. */+ resealed?: { pages: number; pending_chunks: number; embedding_usd: number | null };}export async function runImport(@@ -590,6 +602,7 @@ export async function runImport(let lastCheckpointMs = Date.now();let lastCheckpointSize = completed.size;let chunksCreated = 0;+ const resealed = { pages: 0, pendingChunks: 0, pendingChars: 0 };const importedSlugs: string[] = [];const errorCounts: Record<string, number> = {};const errorSamples: Record<string, string> = {};@@ -657,6 +670,11 @@ export async function runImport(succeededPaths.push(importRelPath); // #3839} else {skipped++;+ if ('resealed' in result && result.resealed) {+ resealed.pages++;+ resealed.pendingChunks += result.resealed.pendingChunks;+ resealed.pendingChars += result.resealed.pendingChars;+ }if (result.skip_reason === 'malformed_path') {// Informational skip (bracket/control-char filename): never a// failure-ledger row, and stable across runs — checkpoint as done.@@ -1073,6 +1091,9 @@ export async function runImport(else if (existsSync(checkpointPath)) info(` Checkpoint preserved (${errors} errors). Run again to retry failed files.`);const totalTime = ((Date.now() - startTime) / 1000).toFixed(1);+ const resealSummary = resealed.pages > 0+ ? { pages: resealed.pages, pending_chunks: resealed.pendingChunks, embedding_usd: resealEmbeddingUsd(resealed.pendingChars) }+ : null;if (jsonOutput) {// `skipped` includes every per-file failure importFile RETURNS (invalid// frontmatter, oversize, symlink, slug mismatch) as well as content-hash@@ -1084,6 +1105,7 @@ export async function runImport(console.log(JSON.stringify({status: errors > 0 ? 'partial' : 'success', duration_s: parseFloat(totalTime),imported, skipped, errors, chunks: chunksCreated,+ ...(resealSummary ? { resealed: resealSummary } : {}),total_files: allFiles.length,unchanged: skipped - failures.length - malformedFileSkips,malformed_skipped: malformedFileSkips,@@ -1096,11 +1118,16 @@ export async function runImport(slog(` ${imported} pages imported`);slog(` ${skipped} pages skipped (${skipped - failures.length - malformedFileSkips} unchanged, ${errors} errors, ${malformedFileSkips} malformed filenames)`);slog(` ${chunksCreated} chunks created`);+ if (resealSummary) {+ slog(` ${resealSummary.pages} unchanged page(s) re-sealed for remote search; ${resealSummary.pending_chunks} chunk(s) need embedding`+ + `${resealSummary.embedding_usd === null ? '' : ` (~$${resealSummary.embedding_usd.toFixed(4)})`}${noEmbed ? ' — run gbrain embed --stale' : ''}`);+ }}if (imported > 0 && !opts.managedBookmark) await refreshProjectionStatistics(engine);return {imported, skipped, errors, chunksCreated, failures,+ ...(resealSummary ? { resealed: resealSummary } : {}),...(totalMalformed > 0 ? { malformedSkipped: totalMalformed } : {}),...(typeWarningCounts.size > 0 && typeWarningsEnabled? { type_warnings: [...typeWarningCounts.values()] }diff --git a/src/commands/jobs.ts b/src/commands/jobs.tsindex eca5b0d732..22329a5aeb 100644--- a/src/commands/jobs.ts+++ b/src/commands/jobs.ts@@ -2210,6 +2210,7 @@ export async function registerBuiltinHandlers(const quiet = opts?.quiet === true;worker.register('sync', async (job) => {const { performSync } = await import('./sync.ts');+ const { explicitSyncProcessing } = await import('../core/persistence/sync-authority.ts');const repoPath = typeof job.data.repoPath === 'string' ? job.data.repoPath : undefined;const noPull = !resolveJobPull(job.data);// noEmbed defaults to true (embed is a separate job — submit `embed --stale`@@ -2264,6 +2265,7 @@ export async function registerBuiltinHandlers(try {result = await performSync(engine, {repoPath, sourceId, noPull, noEmbed, noExtract, signal: job.signal,+ explicitProcessing: explicitSyncProcessing(job.data),concurrency: concurrencyOverride,...(githubItem ? { githubItem } : {}),});diff --git a/src/commands/migrations/v0_13_1.ts b/src/commands/migrations/v0_13_1.tsindex 521b9ee645..6b4c1194df 100644--- a/src/commands/migrations/v0_13_1.ts+++ b/src/commands/migrations/v0_13_1.ts@@ -107,11 +107,15 @@ const GRANDFATHER_WHERE =// (same rationale as engine-constants.ts DELETE_BATCH_SIZE).const CHUNK_SIZE = 1000;+/** A page this run grandfathered and the revision its write produced. */+export interface GrandfatheredPage { id: number; revision: string | null; }+interface GrandfatherResult {touched: number;skipped: number;failed: number;failures: string[];+ grandfathered: GrandfatheredPage[];}// Exported for direct hermetic testing against a PGLite engine (the config /@@ -120,7 +124,7 @@ export async function phaseCGrandfather(engine: BrainEngine,opts: OrchestratorOpts,): Promise<{ result: OrchestratorPhaseResult; detail: GrandfatherResult }> {- const gf: GrandfatherResult = { touched: 0, skipped: 0, failed: 0, failures: [] };+ const gf: GrandfatherResult = { touched: 0, skipped: 0, failed: 0, failures: [], grandfathered: [] };try {if (opts.dryRun) {@@ -155,8 +159,11 @@ export async function phaseCGrandfather(gf.skipped += chunk.length - selected.length;for (const page of selected) {try {- if (await grandfatherCanonicalPage(engine, page, snapshot => appendRollbackBatch([snapshot])) === 'touched') gf.touched++;- else gf.skipped++;+ const outcome = await grandfatherCanonicalPage(engine, page, snapshot => appendRollbackBatch([snapshot]));+ if (outcome.status === 'touched') {+ gf.touched++;+ gf.grandfathered.push({ id: page.id, revision: outcome.revision });+ } else gf.skipped++;} catch (error) {gf.failed++;const reason = error instanceof OperationError@@ -184,17 +191,20 @@ export async function phaseCGrandfather(throw new Error('Page identity changed during grandfathering; retry the migration.');}appendRollbackBatch(snap);- await tx.executeRaw(+ // The revision trigger advances knowledge_revision on this update;+ // verification keys on it to tell a later rewrite from a lost write.+ const written = await tx.executeRaw<{ id: number; knowledge_revision: string }>(`UPDATE pages SET frontmatter = jsonb_set(COALESCE(frontmatter, '{}'::jsonb), '{validate}', 'false'::jsonb) ` +- 'WHERE id = ANY($1::int[])', [snap.map(row => row.id)]);+ 'WHERE id = ANY($1::int[]) RETURNING id, knowledge_revision::text AS knowledge_revision', [snap.map(row => row.id)]);const sealed = snap.filter(row => row.text_projection_revision === row.knowledge_revision).map(row => row.id);if (sealed.length) {await tx.executeRaw('UPDATE pages SET text_projection_revision=knowledge_revision WHERE id = ANY($1::int[])', [sealed]);}- return snap.length;+ return written.map(row => ({ id: Number(row.id), revision: row.knowledge_revision }));});- gf.touched += touched;- gf.skipped += chunk.length - touched;+ gf.touched += touched.length;+ gf.skipped += chunk.length - touched.length;+ gf.grandfathered.push(...touched);} catch (e) {gf.failed += chunk.length;const msg = e instanceof Error ? e.message : String(e);@@ -216,24 +226,47 @@ export async function phaseCGrandfather(// ---------------------------------------------------------------------------// Phase D — verify+//+// Checks only the pages this run grandfathered. A page whose knowledge_revision+// moved past the one our write produced (or that was deleted) was rewritten by+// a concurrent writer, such as a connector re-import; it is reported as+// `rewritten_concurrently`, not failed. A page still at our revision without+// `validate: false` means the write did not land, and fails the phase. A null+// revision (a replayed receipt that recorded none) cannot prove a rewrite, so+// the flag must be present.// ----------------------------------------------------------------------------async function phaseDVerify(engine: BrainEngine, expectedTouched: number): Promise<OrchestratorPhaseResult> {- if (expectedTouched === 0) {+// Exported for direct hermetic testing, like phaseCGrandfather.+export async function phaseDVerify(engine: BrainEngine, grandfathered: GrandfatheredPage[]): Promise<OrchestratorPhaseResult> {+ if (grandfathered.length === 0) {return { name: 'verify', status: 'complete', detail: 'nothing to verify' };}try {- // Count pages whose frontmatter has `validate` = false via raw SQL.- const rows = await engine.executeRaw<{ count: string | number }>(- "SELECT COUNT(*) AS count FROM pages WHERE (frontmatter->>'validate')::text = 'false'",- );- const count = rows[0]?.count ?? 0;- const n = typeof count === 'string' ? parseInt(count, 10) : Number(count);- return {- name: 'verify',- status: n >= expectedTouched ? 'complete' : 'failed',- detail: `pages with validate=false: ${n} (expected >= ${expectedTouched})`,- };+ let verified = 0;+ let rewritten = 0;+ const missing: number[] = [];+ for (let i = 0; i < grandfathered.length; i += CHUNK_SIZE) {+ const chunk = grandfathered.slice(i, i + CHUNK_SIZE);+ const rows = await engine.executeRaw<{ id: number; state: 'verified' | 'rewritten' | 'missing' }>(+ `SELECT t.id,+ CASE WHEN p.id IS NULL OR (t.revision IS NOT NULL AND p.knowledge_revision::text <> t.revision) THEN 'rewritten'+ WHEN p.frontmatter->>'validate' = 'false' THEN 'verified'+ ELSE 'missing' END AS state+ FROM unnest($1::int[], $2::text[]) AS t(id, revision)+ LEFT JOIN pages p ON p.id = t.id`,+ [chunk.map(page => page.id), chunk.map(page => page.revision)],+ );+ for (const row of rows) {+ if (row.state === 'verified') verified++;+ else if (row.state === 'rewritten') rewritten++;+ else missing.push(Number(row.id));+ }+ }+ const detail = `verified=${verified} rewritten_concurrently=${rewritten}`;+ return missing.length === 0+ ? { name: 'verify', status: 'complete', detail }+ : { name: 'verify', status: 'failed',+ detail: `${detail} missing_validate=${missing.length} (${missing.slice(0, 5).map(id => `page#${id}`).join(', ')})` };} catch (e) {return {name: 'verify',@@ -270,7 +303,7 @@ async function orchestrator(opts: OrchestratorOpts): Promise<OrchestratorResult>filesRewritten = gfDetail.touched;if (!opts.dryRun) {- const verifyRes = await phaseDVerify(engine, gfDetail.touched);+ const verifyRes = await phaseDVerify(engine, gfDetail.grandfathered);phases.push(verifyRes);}diff --git a/src/commands/persistence-admin.ts b/src/commands/persistence-admin.tsindex 0579fe3cf1..ad7290a18c 100644--- a/src/commands/persistence-admin.ts+++ b/src/commands/persistence-admin.ts@@ -39,9 +39,12 @@ Activation may explicitly remove exact dead local legacy holders with--cleanup-dead-local-locks; expiry alone is never evidence of death.--shared-skills activates recoverable skill bundles and blocks older writers.No command takes over an owner based on a stale heartbeat.-retry-effects handles embedding effects only: it reconciles existing complete-vectors or explicitly authorizes one additional bounded retry cycle per request.-Repeating the command never renews that allowance. --dry-run never queues work.+retry-effects handles parked Git/withdrawal effects and failed embedding effects.+A Git or withdrawal target parks after five consecutive failures; the command+previews parked targets with --dry-run and otherwise authorizes one more attempt+per parked target (a target that fails again parks again). For embeddings it+reconciles existing complete vectors or authorizes one additional bounded retry+cycle per request; repeating it never renews that allowance. --dry-run never queues work.It never changes ownership or activation and needs no topology admin-intent.`;export const LOCAL_WRITER_HELP = `Usage:diff --git a/src/commands/recall.ts b/src/commands/recall.tsindex 9aa65a5164..997229248e 100644--- a/src/commands/recall.ts+++ b/src/commands/recall.ts@@ -470,7 +470,10 @@ async function runRecallOnce(}}- if (flags.grep) {+ // `--grep` narrows in SQL before LIMIT on every engine path (op params,+ // thin-client params, and fetchRowsLocal's list calls). listSupersessions+ // takes no grep option, so the client-side filter remains only there.+ if (flags.grep && flags.supersessions) {const g = flags.grep;rows = rows.filter(r => r.fact.toLowerCase().includes(g));}@@ -533,11 +536,13 @@ async function fetchRowsLocal(sessionId: flags.sessionId || undefined,activeOnly: !flags.includeExpired,limit: flags.limit,+ grep: flags.grep ?? undefined,excludeAuditRows: true,}): await engine.listFactsByEntity(sourceId, slug, {activeOnly: !flags.includeExpired,limit: flags.limit,+ grep: flags.grep ?? undefined,excludeAuditRows: true,});// #4720: the bare positional is entity-first, but keyless/casual usage@@ -572,12 +577,14 @@ async function fetchRowsLocal(sessionId: flags.sessionId,activeOnly: !flags.includeExpired,limit: flags.limit,+ grep: flags.grep ?? undefined,excludeAuditRows: true,});}return engine.listFactsBySession(sourceId, flags.sessionId, {activeOnly: !flags.includeExpired,limit: flags.limit,+ grep: flags.grep ?? undefined,excludeAuditRows: true,});}@@ -595,6 +602,7 @@ async function fetchRowsLocal(eventTime: !flags.sinceLastRun,activeOnly: !flags.includeExpired,limit: flags.limit,+ grep: flags.grep ?? undefined,excludeAuditRows: true,});}@@ -602,6 +610,7 @@ async function fetchRowsLocal(eventTime: true,activeOnly: !flags.includeExpired,limit: flags.limit,+ grep: flags.grep ?? undefined,excludeAuditRows: true,});}diff --git a/src/commands/repair.ts b/src/commands/repair.tsnew file mode 100644index 0000000000..95851e50ff--- /dev/null+++ b/src/commands/repair.ts@@ -0,0 +1,107 @@+/**+ * `gbrain repair [<kind>] [--apply] [--source <id>] [--limit <n>] [--no-embed] [--json]`+ *+ * Host-side repairs for residual damage the doctor reports. Every kind is a+ * dry run unless `--apply` is passed; applying publishes each item through a+ * coordinated page write (or, for `safe-chunks`, a projection-only rebuild+ * that takes no admission), resumes after an interruption, and stops before+ * crossing 90% of a cumulative journal cap. Thin clients refuse (cli.ts).+ */+import type { BrainEngine } from '../core/engine.ts';+import { loadConfig } from '../core/config.ts';+import { setCliExitVerdict } from '../core/cli-force-exit.ts';+import { OperationError, type OperationContext } from '../core/ops/contract.ts';+import { REPAIR_KINDS, resolveRepairScope, runRepair, type RepairHandler, type RepairKind, type RepairResult } from '../core/repair/core.ts';+import { timelineRepair } from '../core/repair/timeline.ts';+import { visibilityRepair } from '../core/repair/visibility.ts';+import { safeChunksRepair } from '../core/repair/safe-chunks.ts';++const HANDLERS: Record<RepairKind, RepairHandler> = { timeline: timelineRepair, visibility: visibilityRepair, 'safe-chunks': safeChunksRepair };++export const REPAIR_HELP = `Usage: gbrain repair [<kind>] [--apply] [--source <id>] [--limit <n>] [--no-embed] [--json]+ gbrain repair --all [--apply] [--source <id>] [--json]++Repair residual damage that \`gbrain doctor\` reports. Dry run unless --apply.++Kinds:+ timeline Write database-only timeline rows back into their pages as marked+ bullets (#5567). Rows that cannot round-trip are kept and counted.+ visibility Stamp explicit visibility on extracted atoms and synthesized+ concepts, tighten-only (#5525). Transcript and missing origins+ become private; nothing is ever loosened.+ safe-chunks Re-seal pages of every kind (markdown and code) chunked before the+ safe-chunk fence, which remote/MCP search withholds (#5050, #5247).+ Projection-only: no page write and no journal admission. Unchanged+ vectors are kept; the rest are embedded unless --no-embed.++Options:+ --apply Write the repair (no prompt). Without it, only preview.+ --source <id> Limit to one source (default: every active source).+ --limit <n> Repair at most n items; rerun the same command to continue.+ --no-embed safe-chunks: re-seal text only; embed later with gbrain embed --stale.+ --all Run every kind in order (${REPAIR_KINDS.join(', ')}).+ --json Machine-readable output with a stable shape.++With no kind, previews every kind. Run it on the brain host.`;++function flag(args: string[], name: string): string | undefined {+ const at = args.indexOf(name);+ if (at < 0) return undefined;+ const value = args[at + 1];+ if (!value || value.startsWith('--')) throw new OperationError('invalid_params', `${name} requires a value.`);+ return value;+}++function human(result: RepairResult): string {+ const lines = [`${result.kind}: ${result.affected} item(s) ${result.mode === 'apply' ? 'pending before this run' : 'to repair'}`];+ if (result.sample.length) lines.push(` e.g. ${result.sample.join(', ')}`);+ const residuals = Object.entries(result.residuals).map(([k, v]) => `${k}=${v}`).join(', ');+ if (residuals) lines.push(` ${residuals}`);+ lines.push(` cost: ${result.cost.lifetime_ids} request ID(s), ${result.cost.receipt_bytes} receipt bytes, `+ + `${result.cost.embedding_pages} page(s) to re-embed${result.cost.embedding_usd === null ? '' : ` (~$${result.cost.embedding_usd.toFixed(4)})`}`);+ for (const c of result.capacity) lines.push(` capacity ${c.scope} ${c.resource}: ${c.used} of ${c.limit} (stops at ${c.stop_at})`);+ if (result.resumed_from) lines.push(` resuming after item ${result.resumed_from.phase}:${result.resumed_from.id}`);+ if (result.mode === 'apply') lines.push(` applied ${result.applied}, skipped ${result.skipped}${result.complete ? ', complete' : ''}`);+ if (result.stopped) lines.push(` STOPPED: ${result.stopped.message}`);+ if (result.mode === 'dry_run' && result.affected) lines.push(` apply: ${result.apply_command}`);+ return lines.join('\n');+}++export async function runRepairCommand(engine: BrainEngine, args: string[]): Promise<void> {+ if (args.includes('--help') || args.includes('-h')) { console.log(REPAIR_HELP); return; }+ if (args.includes('--yes')) throw new OperationError('invalid_params', '`--yes` is not accepted by gbrain repair; pass --apply to write.');+ const json = args.includes('--json');+ const noEmbed = args.includes('--no-embed');+ const apply = args.includes('--apply');+ const source = flag(args, '--source');+ const limitText = flag(args, '--limit');+ const limit = limitText === undefined ? undefined : Number(limitText);+ if (limit !== undefined && (!Number.isSafeInteger(limit) || limit < 1)) throw new OperationError('invalid_params', '--limit must be a positive integer.');+ const positional = args.filter((arg, i) => !arg.startsWith('--') && !['--source', '--limit'].includes(args[i - 1] ?? ''));+ const kind = positional[0];+ if (kind && !REPAIR_KINDS.includes(kind as RepairKind)) {+ throw new OperationError('invalid_params', `Unknown repair kind '${kind}'.`, `Kinds: ${REPAIR_KINDS.join(', ')}.`);+ }+ if (!kind && apply && !args.includes('--all')) throw new OperationError('invalid_params', 'Name a kind or pass --all with --apply.');+ const kinds: RepairKind[] = kind ? [kind as RepairKind] : [...REPAIR_KINDS];+ const scope = await resolveRepairScope(engine, source);+ const config = loadConfig() ?? { engine: engine.kind };+ const ctx: OperationContext = { engine, config, logger: { info: console.error, warn: console.error, error: console.error },+ dryRun: !apply, remote: false, sourceId: scope.source_ids[0] } as OperationContext;+ let embeddingModel: string | undefined;+ try { embeddingModel = config.embedding_disabled ? undefined : (await import('../core/ai/gateway.ts')).getEmbeddingModel(); } catch { embeddingModel = undefined; }+ const results: RepairResult[] = [];+ for (const k of kinds) {+ const result = await runRepair(ctx, HANDLERS[k], scope, { apply, limit, embeddingModel, sourceFlag: source,+ embed: !noEmbed && embeddingModel !== undefined, applyArgs: noEmbed && k === 'safe-chunks' ? ['--no-embed'] : [] });+ results.push(result);+ if (result.stopped) break;+ }+ if (json) {+ console.log(JSON.stringify({ scope, mode: apply ? 'apply' : 'dry_run', results }, null, 2));+ } else {+ console.log(`Scope: brain ${scope.brain_id}; sources ${scope.source_ids.join(', ') || '(none)'}`);+ for (const result of results) console.log(human(result));+ }+ if (results.some(r => r.stopped)) setCliExitVerdict(1);+}diff --git a/src/commands/serve-http.ts b/src/commands/serve-http.tsindex 3add630680..c3b6cbaaaa 100644--- a/src/commands/serve-http.ts+++ b/src/commands/serve-http.ts@@ -51,6 +51,7 @@ import {dcrRegistrationContext,DEFAULT_DCR_TTL_MIN_SECONDS,} from '../core/oauth-provider.ts';+import { canonicalOAuthResource } from '../core/oauth-grants.ts';import { hasScope, operationScopesAllowed, scopesSupportedForDiscovery } from '../core/scope.ts';import { normalizeTokenScopes } from '../core/legacy-token-scope.ts';import { summarizeMcpParams, dispatchToolCall, requestLogStatusForResult } from '../mcp/dispatch.ts';@@ -970,6 +971,34 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOptiondcrTtlMaxSeconds = dcrTtlMinSeconds;}+ // The issuer URL goes into discovery metadata + token iss claims. It MUST+ // match the URL clients actually hit, or strict OAuth clients reject tokens+ // (RFC 8414 §3.3). Honor --public-url for production deployments behind+ // reverse proxies / tunnels; default to localhost for dev.+ const issuerUrl = new URL(publicUrl || `http://localhost:${port}`);++ // MCP authorization spec (2025-06-18 draft §5.1) and RFC 9728 require the+ // protected resource server to return its discovery metadata URL in the+ // WWW-Authenticate header on 401 responses:+ //+ // WWW-Authenticate: Bearer resource_metadata="<URL>"+ //+ // Clients (claude.ai, Cursor, every other MCP-aware OAuth client) use that+ // URL to find the authorization-server discovery doc + token endpoint+ // without the user having to paste those URLs manually. Pre-fix the header+ // shipped `Bearer error="invalid_token", ...` with no resource_metadata+ // parameter, so MCP clients couldn't begin the OAuth flow from a fresh+ // 401 — they would silently fail to connect with a generic "couldn't+ // reach the MCP server" error.+ // RFC 9728 / MCP auth spec: the protected-resource metadata describes the+ // resource the client connects to (/mcp), not the authorization-server root.+ // Without resourceServerUrl the SDK falls back to issuerUrl, advertising+ // `resource: "https://host/"` and 404ing the path-based PRM URL+ // (/.well-known/oauth-protected-resource/mcp) that clients derive from the+ // connector URL (#4893). The 401 challenge's resource_metadata URL is+ // derived from the same value so the two can never drift apart.+ const mcpResourceUrl = new URL('/mcp', issuerUrl);+ const resourceMetadataUrl = getOAuthProtectedResourceMetadataUrl(mcpResourceUrl);const oauthProvider = new GBrainOAuthProvider({sql,transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))),@@ -978,6 +1007,7 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOptionallowClientCredentialsDcr: enableDcrInsecure === true,dcrTtlMinSeconds,dcrTtlMaxSeconds,+ resourceUrl: mcpResourceUrl,});// #1353: loud stderr security WARN when DCR is enabled. DCR is an@@ -1145,41 +1175,18 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOption// ---------------------------------------------------------------------------// MCP SDK Auth Router (OAuth endpoints)// ---------------------------------------------------------------------------- // The issuer URL goes into discovery metadata + token iss claims. It MUST- // match the URL clients actually hit, or strict OAuth clients reject tokens- // (RFC 8414 §3.3). Honor --public-url for production deployments behind- // reverse proxies / tunnels; default to localhost for dev.- const issuerUrl = new URL(publicUrl || `http://localhost:${port}`);-- // MCP authorization spec (2025-06-18 draft §5.1) and RFC 9728 require the- // protected resource server to return its discovery metadata URL in the- // WWW-Authenticate header on 401 responses:- //- // WWW-Authenticate: Bearer resource_metadata="<URL>"- //- // Clients (claude.ai, Cursor, every other MCP-aware OAuth client) use that- // URL to find the authorization-server discovery doc + token endpoint- // without the user having to paste those URLs manually. Pre-fix the header- // shipped `Bearer error="invalid_token", ...` with no resource_metadata- // parameter, so MCP clients couldn't begin the OAuth flow from a fresh- // 401 — they would silently fail to connect with a generic "couldn't- // reach the MCP server" error.- // RFC 9728 / MCP auth spec: the protected-resource metadata describes the- // resource the client connects to (/mcp), not the authorization-server root.- // Without resourceServerUrl the SDK falls back to issuerUrl, advertising- // `resource: "https://host/"` and 404ing the path-based PRM URL- // (/.well-known/oauth-protected-resource/mcp) that clients derive from the- // connector URL (#4893). The 401 challenge's resource_metadata URL is- // derived from the same value so the two can never drift apart.- const mcpResourceUrl = new URL('/mcp', issuerUrl);- const resourceMetadataUrl = getOAuthProtectedResourceMetadataUrl(mcpResourceUrl);// The SDK validates expiry/scopes but leaves audience enforcement to us.- // Legacy grants without a resource retain their existing compatibility.+ // Legacy grants without a resource retain their existing compatibility; an+ // origin-bound token minted before #5222 passes the same canonicalizer.const resourceVerifier = {async verifyAccessToken(token: string) {const auth = await oauthProvider.verifyAccessToken(token);- if (auth.resource && auth.resource.toString() !== mcpResourceUrl.toString()) {- throw new InvalidTokenError('Token is bound to a different resource');+ if (auth.resource) {+ try {+ canonicalOAuthResource(auth.resource, mcpResourceUrl);+ } catch {+ throw new InvalidTokenError('Token is bound to a different resource');+ }}return auth;},@@ -2017,8 +2024,11 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOptionres.status(405).json({ jsonrpc: '2.0', error: { code: -32000, message: 'Method not allowed' }, id: null });});+ // #5277: hint every scope a connector may need. Clients that request exactly+ // the hinted scope and never step up (claude.ai connectors) otherwise stay+ // read-only; grantScopes still caps each grant to the client row's scope.app.post('/mcp', withBearerScopeHint(- requireBearerAuth({ verifier: resourceVerifier, resourceMetadataUrl }), ['read'],+ requireBearerAuth({ verifier: resourceVerifier, resourceMetadataUrl }), ['read', 'write'],), async (req: Request, res: Response) => {const startTime = Date.now();const authInfo = (req as any).auth as AuthInfo;diff --git a/src/commands/sync.ts b/src/commands/sync.tsindex 7eebb1a522..2d1828493b 100644--- a/src/commands/sync.ts+++ b/src/commands/sync.ts@@ -292,6 +292,8 @@ export interface SyncResult {* the working tree was imported (detached HEAD or --working-tree).*/uncommitted?: { added: number; modified: number; deleted: number };+ /** #5050: full sync re-sealed unchanged pages at the safe-chunk fence (see RunImportResult.resealed). */+ resealed?: import('./import.ts').RunImportResult['resealed'];/*** v0.41.13.0 partial-sync fields (only set when status === 'partial').*@@ -355,6 +357,8 @@ export interface SyncOpts {* Threaded through performSync AND syncOneSource so `sync --all` honors it.*/noSchemaPack?: boolean;+ /** Processing options this caller set; an unfinished managed cursor supplies the rest (unset = all explicit). */+ explicitProcessing?: Array<'noEmbed' | 'noExtract' | 'noSchemaPack'>;/*** v0.18.0 Step 5 — sync a specific named source. When set, sync reads* local_path + last_commit from the sources table (not the global@@ -4469,6 +4473,7 @@ async function performFullSync(// topologies (codex re-review; same rationale as the incremental path)....(result.malformedSkipped ? { malformedSkipped: result.malformedSkipped } : {}),...(result.type_warnings ? { type_warnings: result.type_warnings } : {}),+ ...(result.resealed ? { resealed: result.resealed } : {}),};}@@ -4651,6 +4656,8 @@ See also:const skipFailed = args.includes('--skip-failed');const retryFailed = args.includes('--retry-failed');const noSchemaPack = args.includes('--no-schema-pack'); // v0.41.37.0 #1569+ const explicitProcessing = ([['--no-embed', 'noEmbed'], ['--no-extract', 'noExtract'], ['--no-schema-pack', 'noSchemaPack']] as const)+ .filter(([flag]) => args.includes(flag)).map(([, key]) => key);const includeGitignored = args.includes('--include-gitignored');// Untracked-gap fix: --working-tree imports uncommitted working-tree state.// The config fallback (sync.include_working_tree) resolves inside@@ -5118,7 +5125,7 @@ See also:dryRun, full, noPull,noEmbed: effectiveNoEmbed,noExtract,- skipFailed, retryFailed, noSchemaPack,+ skipFailed, retryFailed, noSchemaPack, explicitProcessing,includeGitignored,workingTree,sourceId: src.id,@@ -5353,7 +5360,7 @@ See also:const singleSourceInterrupt = new AbortController();const onSingleSourceSigint = () => { try { singleSourceInterrupt.abort(new Error('SIGINT')); } catch { /* */ } };const opts: SyncOpts = {- repoPath, dryRun, full, noPull, noEmbed, noExtract, skipFailed, retryFailed, noSchemaPack, includeGitignored, workingTree, sourceId,+ repoPath, dryRun, full, noPull, noEmbed, noExtract, skipFailed, retryFailed, noSchemaPack, explicitProcessing, includeGitignored, workingTree, sourceId,strategy: strategyArg, concurrency,srcSubpath,exclude: excludePatterns.length > 0 ? excludePatterns : undefined,diff --git a/src/commands/upgrade.ts b/src/commands/upgrade.tsindex 1ab3535d8f..5ea14b0d93 100644--- a/src/commands/upgrade.ts+++ b/src/commands/upgrade.ts@@ -641,16 +641,24 @@ export async function runPostUpgrade(args: string[] = []): Promise<void> {// v0.32.7 CJK wave: chunker-version bump → re-embed sweep.// Idempotent — `runReindex` short-circuits when no pages are pending.+ // A managed brain refuses the markdown reindex; name its drain instead.try {- const { runPostUpgradeReembedPrompt } = await import('../core/post-upgrade-reembed.ts');- const { getEmbeddingModel } = await import('../core/ai/gateway.ts');- let modelString = 'openai:text-embedding-3-large';- try { modelString = getEmbeddingModel(); } catch { /* gateway not configured — keep default */ }- const promptResult = await runPostUpgradeReembedPrompt(engine, modelString);- if (promptResult.proceeded) {- const { runReindex } = await import('./reindex.ts');- await runReindex(engine, ['--markdown']);+ const { managedPersistenceEnabled } = await import('../core/persistence/ownership.ts');+ const { safeChunkUpgradeAdvisory } = await import('../core/repair/safe-chunks.ts');+ const managed = await managedPersistenceEnabled(engine);+ if (!managed) {+ const { runPostUpgradeReembedPrompt } = await import('../core/post-upgrade-reembed.ts');+ const { getEmbeddingModel } = await import('../core/ai/gateway.ts');+ let modelString = 'openai:text-embedding-3-large';+ try { modelString = getEmbeddingModel(); } catch { /* gateway not configured — keep default */ }+ const promptResult = await runPostUpgradeReembedPrompt(engine, modelString);+ if (promptResult.proceeded) {+ const { runReindex } = await import('./reindex.ts');+ await runReindex(engine, ['--markdown']);+ }}+ const advisory = await safeChunkUpgradeAdvisory(engine, managed);+ if (advisory) console.log(advisory);} catch (re) {const msg = re instanceof Error ? re.message : String(re);console.warn(`\nChunker-bump reindex skipped: ${msg}`);diff --git a/src/core/ai/providers/claude-cli-scratch.ts b/src/core/ai/providers/claude-cli-scratch.tsindex 0c0ae1aba9..ef4e7e2c75 100644--- a/src/core/ai/providers/claude-cli-scratch.ts+++ b/src/core/ai/providers/claude-cli-scratch.ts@@ -18,6 +18,7 @@import { readdirSync, rmSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';+import { claudeProjectsDir } from '../../bootstrap/host-specs.ts';/** Basename prefix of the per-PID cwd the claude-cli subprocess runs in. */export const CLAUDE_CLI_CWD_PREFIX = 'gbrain-claude-cli-cwd-';@@ -43,6 +44,38 @@ export function isClaudeCliSelfTranscriptPath(path: string): boolean {return path.includes(CLAUDE_CLI_CWD_PREFIX);}+/**+ * #5413 — session ids of gbrain's own claude-cli subprocess sessions, read+ * from the harness transcripts Claude Code keeps under+ * `<projectsRoot>/<slugified scratch cwd>/<session id>.jsonl`. The+ * session-end hook names each corpus file `<session id>.txt`, so a corpus+ * file whose stem is in this set is a self-capture from before the hook+ * refused them. Best-effort: a capture whose harness transcript Claude Code+ * has since pruned is unclassifiable and stays in the corpus.+ */+export function claudeCliSelfSessionIds(projectsRoot: string = claudeProjectsDir()): Set<string> {+ const ids = new Set<string>();+ let projects: string[];+ try {+ projects = readdirSync(projectsRoot);+ } catch {+ return ids;+ }+ for (const project of projects) {+ if (!isClaudeCliSelfTranscriptPath(project)) continue;+ let files: string[];+ try {+ files = readdirSync(join(projectsRoot, project));+ } catch {+ continue;+ }+ for (const file of files) {+ if (file.endsWith('.jsonl')) ids.add(file.slice(0, -'.jsonl'.length));+ }+ }+ return ids;+}+function isPidAlive(pid: number): boolean {try {process.kill(pid, 0);diff --git a/src/core/brain-score-recommendations.ts b/src/core/brain-score-recommendations.tsindex afa81e0e27..fe84a5b0ad 100644--- a/src/core/brain-score-recommendations.ts+++ b/src/core/brain-score-recommendations.ts@@ -166,6 +166,12 @@ export interface RecommendationContext {* cohort is re-embedded instead of grandfathered forever.*/nullSignatureCohort?: number;+ /**+ * #5609: why `extract --stale` cannot run on this brain right now (it would+ * fail every dispatch). Probed by `staleExtractionBlocked()`; when set, the+ * `extract.stale` step is withheld and its check classifies as blocked.+ */+ staleExtractionBlocked?: string;}/** Triage result for one check. */@@ -281,7 +287,7 @@ export function computeRecommendations(});}- if (health.stale_pages > 0) {+ if (health.stale_pages > 0 && !ctx.staleExtractionBlocked) {const params = { stale: true, ...(ctx.sourceId ? { sourceId: ctx.sourceId } : {}) };out.push({id: 'extract.stale',@@ -353,6 +359,9 @@ function classifyOne(check: Check, ctx: RecommendationContext): CheckClassificatreturn { check: check.name, status: 'blocked', reason: 'embedding provider not configured' };}return { check: check.name, status: 'remediable' };+ case 'links_extraction_lag':+ if (ctx.staleExtractionBlocked) return { check: check.name, status: 'blocked', reason: ctx.staleExtractionBlocked };+ return { check: check.name, status: 'remediable' };case 'dead_links':if (!ctx.repoPath) {return { check: check.name, status: 'blocked', reason: 'no repo configured' };diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex a837b19ea2..ea90e64f43 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -19,7 +19,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'anomalies': ['--brain', '--help', '--json', '--lookback-days', '--mcp-only', '--sigma', '--since', '--source'],'apply-migrations': ['--acknowledge-no-backup', '--backup-confirmed', '--brain', '--break-lock', '--confirm-quiesced', '--content-root', '--dry-run', '--export-db-only', '--export-source', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--help', '--host-dir', '--json', '--list', '--locks', '--migrate-only', '--migration', '--mode', '--no-autopilot-install', '--non-interactive', '--require-db', '--skip-verify', '--source', '--yes'],'auth': ['--admin-intent', '--allowed-operations', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--cleanup-dead-local-locks', '--confirm-quiesced', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--enable-dcr-insecure', '--expected-epoch', '--expected-state', '--federated-read', '--fix', '--grant-types', '--help', '--id', '--if-version', '--json', '--limit', '--manifest', '--max-concurrent', '--path', '--probe', '--profile', '--redirect-uri', '--repair', '--replace', '--request-id', '--scopes', '--self-transfer', '--shared-skills', '--slug-prefixes', '--source', '--source-ids', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--usage', '--yes'],- 'autopilot': ['--batch', '--brain', '--check', '--dimensions', '--dir', '--drain', '--embedding-dimensions', '--embedding-model', '--explain', '--ff-only', '--force', '--force-retry', '--from-pages', '--help', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--no-autopilot-install', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--output', '--path', '--phase', '--refresh-cache', '--repo', '--source', '--status', '--swap-only', '--target', '--uninstall', '--user', '--version', '--yes'],+ 'autopilot': ['--batch', '--brain', '--check', '--dimensions', '--dir', '--drain', '--embedding-dimensions', '--embedding-model', '--explain', '--ff-only', '--force', '--force-retry', '--from-pages', '--help', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--no-autopilot-install', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--output', '--path', '--phase', '--refresh-cache', '--repo', '--source', '--stale', '--status', '--swap-only', '--target', '--uninstall', '--user', '--version', '--yes'],'backfill': ['--batch-size', '--brain', '--concurrency', '--dry-run', '--fresh', '--help', '--json', '--keep-index', '--list', '--max-errors', '--max-rows', '--resume', '--source'],'backup': ['--background', '--brain', '--confirm-authority-reviewed', '--confirm-backup-compatible', '--confirm-quiesced', '--dir', '--explain', '--follow', '--help', '--into', '--json', '--mode', '--output', '--progress-interval', '--progress-json', '--quiet', '--restore-only', '--source', '--timeout'],'bench': ['--baseline', '--brain', '--force', '--from', '--help', '--json', '--label', '--limit', '--source', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-top1', '--to', '--tool'],@@ -45,15 +45,15 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'conversation-parser': ['--brain', '--help', '--json', '--source'],'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--entity', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--prefer-postgres', '--provenance', '--provider', '--schema-pack', '--scopes', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--to', '--url', '--version'],'db-repair': ['--apply-rewrites', '--brain', '--break-lock', '--db-url', '--dry-run', '--filter', '--force', '--force-retry', '--format', '--help', '--json', '--locks', '--name', '--path', '--prefer-postgres', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--undo-last-rewrite', '--url', '--version', '--yes'],- 'doctor': ['--abbrev-ref', '--abort', '--all', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--check', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--delete-brain', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--env', '--exclude-standard', '--explain', '--fast', '--federated-read', '--file', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--fresh', '--from-pages', '--full', '--gbrain-bin', '--get', '--git-dir', '--git-path', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--include-flagged', '--include-gitignored', '--include-pseudo', '--index-audit', '--init', '--install', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--link-source', '--link-type', '--local', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--mcp-only', '--migrate-only', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-capture', '--no-cron', '--no-embed', '--no-embedding', '--no-hooks', '--no-migrate', '--no-pull', '--no-verify', '--older-than', '--once', '--others', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--prefer-postgres', '--preset', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--pure', '--push-only', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--refresh', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--repo', '--reranker', '--reset', '--restore-only', '--resume', '--retry-failed', '--review-lower', '--scope', '--scopes', '--session', '--set', '--short', '--show-current', '--show-token', '--show-toplevel', '--since', '--skills', '--skills-dir', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slugs', '--source', '--source-id', '--stale', '--status', '--strict', '--supabase', '--surface', '--symbol-kind', '--target', '--target-score', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--type', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--verbose', '--verify', '--version', '--window', '--workers', '--yes'],- 'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--force', '--force-retry', '--from', '--help', '--input', '--install', '--json', '--limit', '--max-usd', '--once', '--path', '--phase', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],+ 'doctor': ['--abbrev-ref', '--abort', '--all', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--check', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--delete-brain', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--env', '--exclude-standard', '--explain', '--fast', '--federated-read', '--file', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--fresh', '--from-pages', '--full', '--gbrain-bin', '--get', '--git-dir', '--git-path', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--include-flagged', '--include-gitignored', '--include-pseudo', '--index-audit', '--init', '--install', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--link-source', '--link-type', '--local', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--mcp-only', '--migrate-only', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-capture', '--no-cron', '--no-embed', '--no-embedding', '--no-hooks', '--no-migrate', '--no-pull', '--no-verify', '--older-than', '--once', '--others', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--prefer-postgres', '--preset', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--pure', '--push-only', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--refresh', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--repo', '--request-id', '--reranker', '--reset', '--restore-only', '--resume', '--retry-failed', '--review-lower', '--scope', '--scopes', '--session', '--set', '--short', '--show-current', '--show-token', '--show-toplevel', '--since', '--skills', '--skills-dir', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slugs', '--source', '--source-id', '--stale', '--status', '--strict', '--supabase', '--surface', '--symbol-kind', '--target', '--target-score', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--type', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--verbose', '--verify', '--version', '--window', '--workers', '--yes'],+ 'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--force', '--force-retry', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],'embed': ['--all', '--background', '--batch-size', '--brain', '--break-lock', '--budget-ms', '--catch-up', '--db-url', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--help', '--include-null-signature', '--json', '--max-cost-usd', '--max-facts', '--no-embed', '--no-embedding', '--pace', '--pace-max-concurrency', '--path', '--pglite', '--priority', '--progress-interval', '--progress-json', '--quiet', '--slugs', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--yes'],'engine': ['--apply-rewrites', '--brain', '--break-lock', '--db-url', '--help', '--json', '--path', '--prefer-postgres', '--probe', '--source', '--supabase', '--url', '--yes'],'enrich': ['--access', '--asof', '--background', '--bound-slug-prefixes', '--brain', '--concurrency', '--confirm-destructive', '--date', '--days', '--dry-run', '--embedding-dimensions', '--embedding-model', '--entities', '--explain', '--file', '--follow', '--force', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--min-context', '--mode', '--model', '--multimodal', '--once', '--order', '--page', '--path', '--progress-interval', '--progress-json', '--quiet', '--reenrich-after', '--resume', '--session', '--since', '--slug', '--slugs', '--source', '--source-id', '--stats', '--status', '--surface', '--thin', '--thin-threshold', '--timeout', '--trusted-extraction', '--types', '--url', '--workers', '--yes'],'eval': ['--ab-relational', '--against', '--allow-incomplete-judgments', '--allow-mixed-run-config', '--allow-regression', '--asof', '--autocut', '--background', '--baseline', '--batch', '--brain', '--budget-usd', '--budget-usd-answer', '--budget-usd-retrieval', '--by-type', '--by-type-floor', '--by-type-floor-metric', '--candidate', '--capture-pool', '--committed-baseline', '--compare', '--compare-limit', '--concurrent', '--config-a', '--config-b', '--corpus', '--cycles', '--days', '--dedup-cosine', '--dedup-max-per-page', '--dedup-type-ratio', '--dimensions', '--distance-min', '--draws', '--embed-cache', '--embedder', '--embedding-dimensions', '--embedding-model', '--expand', '--expansion', '--expansion-replay', '--expansion-variant-budget', '--explain', '--fixtures', '--follow', '--force-rechunk', '--format', '--from-capture', '--from-db', '--gold', '--grounding-min', '--harness', '--help', '--include-abstention', '--include-holdout', '--input', '--json', '--judge', '--judge-concurrency', '--judge-model', '--justification', '--k', '--keyword-only', '--limit', '--llm', '--max-pair-chars', '--max-tokens', '--max-usd', '--mcp-only', '--md', '--metric', '--min-recall', '--mode', '--model', '--models', '--modes', '--name-only', '--no-cache', '--no-embed-cache', '--no-expand', '--no-llm', '--no-trajectory', '--older-than', '--out', '--output', '--output-dir', '--parallel', '--parity-baseline', '--pglite', '--progress-interval', '--progress-json', '--qrels', '--queries-file', '--query', '--question-ids', '--questions', '--quiet', '--reader-max-tokens', '--reader-mode', '--receipt-dir', '--record', '--refresh-cache', '--reranker', '--resume-from', '--retrieval-only', '--rrf-k', '--rubric-version', '--runs', '--sample', '--sampling', '--save', '--search-pin', '--seed', '--severity', '--short', '--show-toplevel', '--since', '--skip-replay', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slug-prefix', '--source', '--stale', '--status', '--strategy', '--suite', '--suites', '--supabase', '--task', '--threshold', '--threshold-expected-top1', '--threshold-first-relevant-hit', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-recall-at-k', '--threshold-top1', '--timeout', '--tool', '--top-k', '--top-regressions', '--until', '--update-baseline', '--usefulness-min', '--verbose', '--verify', '--with-code-intel', '--yes'],'export': ['--background', '--brain', '--dir', '--explain', '--fix', '--follow', '--help', '--json', '--progress-interval', '--progress-json', '--quiet', '--repo', '--restore-only', '--slug-prefix', '--source', '--timeout', '--type'],- 'extract': ['--after-slug', '--apply-preview', '--background', '--backup-verified', '--brain', '--by-mention', '--catch-up', '--checkpoint', '--concurrency', '--confirm', '--dir', '--dry-run', '--explain', '--follow', '--from-meetings', '--help', '--include-frontmatter', '--infer-dates', '--json', '--kind', '--limit', '--ner', '--pack', '--path', '--progress-interval', '--progress-json', '--quiet', '--rebuild', '--repair-attendance', '--since', '--source', '--source-id', '--stale', '--timeout', '--type', '--verbose', '--workers', '--yes'],+ 'extract': ['--admin-intent', '--after-slug', '--apply-preview', '--background', '--backup-verified', '--brain', '--by-mention', '--catch-up', '--checkpoint', '--concurrency', '--confirm', '--dir', '--dry-run', '--expected-epoch', '--expected-state', '--explain', '--follow', '--from-meetings', '--help', '--include-frontmatter', '--infer-dates', '--json', '--kind', '--limit', '--manifest', '--ner', '--pack', '--path', '--progress-interval', '--progress-json', '--quiet', '--rebuild', '--repair-attendance', '--self-transfer', '--since', '--source', '--source-id', '--stale', '--timeout', '--type', '--verbose', '--workers', '--yes'],'extract-conversation-facts': ['--background', '--brain', '--concurrency', '--confirm-destructive', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--help', '--json', '--limit', '--max-cost', '--max-cost-usd', '--max-runtime', '--no-embedding', '--override-disabled', '--path', '--pglite', '--progress-interval', '--progress-json', '--quiet', '--segment-limit', '--since', '--sleep', '--slug', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--types', '--url', '--workers', '--yes'],'features': ['--all', '--auto', '--auto-fix', '--background', '--batch-size', '--brain', '--by-mention', '--catch-up', '--concurrency', '--dir', '--explain', '--facts', '--from-meetings', '--help', '--include-frontmatter', '--include-null-signature', '--infer-dates', '--json', '--kind', '--ner', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--path', '--priority', '--rebuild', '--refresh', '--repo', '--since', '--slugs', '--source', '--source-id', '--stale', '--target', '--type', '--verbose', '--workers'],'files': ['--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-pointer', '--page', '--progress-interval', '--progress-json', '--quiet', '--retry-failed', '--source', '--timeout', '--type', '--yes'],@@ -72,7 +72,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'lint': ['--abbrev-ref', '--abort', '--background', '--brain', '--branch', '--cached', '--dry-run', '--exclude', '--explain', '--file', '--fix', '--follow', '--get', '--git-dir', '--git-path', '--help', '--is-inside-work-tree', '--json', '--local', '--name-only', '--no-cron', '--no-verify', '--pat-file', '--path', '--progress-interval', '--progress-json', '--push-only', '--quiet', '--rebase', '--short', '--show-toplevel', '--source', '--timeout', '--unset-all'],'loops': ['--all', '--brain', '--help', '--json', '--source', '--stale-ok', '--status', '--top', '--type'],'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],- 'maintain': ['--all', '--background', '--brain', '--break-lock', '--by-mention', '--catch-up', '--concurrency', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--explain', '--fast', '--fix', '--force', '--force-retry', '--force-schema', '--from-meetings', '--full', '--harness', '--help', '--http', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-only', '--multimodal', '--ner', '--no-embed', '--no-pull', '--older-than', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--probe-pglite', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--reset', '--resume', '--retry-failed', '--safe', '--scope', '--scopes', '--show-current', '--since', '--skills-dir', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--symbol-kind', '--target', '--target-score', '--to', '--top-k', '--type', '--url', '--verbose', '--version', '--window', '--workers', '--yes'],+ 'maintain': ['--all', '--apply', '--background', '--brain', '--break-lock', '--by-mention', '--catch-up', '--concurrency', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--explain', '--fast', '--fix', '--force', '--force-retry', '--force-schema', '--from-meetings', '--full', '--harness', '--help', '--http', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-only', '--multimodal', '--ner', '--no-embed', '--no-pull', '--older-than', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--probe-pglite', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--request-id', '--reset', '--resume', '--retry-failed', '--safe', '--scope', '--scopes', '--show-current', '--since', '--skills-dir', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--symbol-kind', '--target', '--target-score', '--to', '--top-k', '--type', '--url', '--verbose', '--version', '--window', '--workers', '--yes'],'mcp': ['--admin-token-file', '--agent', '--arg', '--bearer-token-env-var', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--credentials-file', '--credentials-out', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr', '--federated-read', '--flow', '--force', '--funnel', '--harness', '--header', '--help', '--if-version', '--install', '--issuer-url', '--json', '--limit', '--mcp-only', '--mcp-url', '--no-install', '--no-service', '--no-tailscale', '--oauth-client-id', '--oauth-client-secret', '--oauth-request', '--port', '--profile', '--queue', '--redirect-uri', '--remove', '--resume', '--root', '--scope', '--scopes', '--skills', '--source', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'],'migrate': ['--all', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--force-retry', '--help', '--ignore-env-override', '--include-null-signature', '--json', '--locks', '--max-cost-usd', '--no-embed', '--non-interactive', '--pace', '--pace-max-concurrency', '--path', '--priority', '--progress-interval', '--progress-json', '--quiet', '--reranker', '--retarget', '--skip-verify', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--url', '--yes'],'models': ['--brain', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--skip', '--source', '--status'],@@ -82,7 +82,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'orphans': ['--background', '--brain', '--count', '--explain', '--follow', '--help', '--include-pseudo', '--json', '--mode', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout'],'pages': ['--brain', '--dry-run', '--help', '--json', '--older-than', '--source'],'pglite-repair': ['--brain', '--break-lock', '--dry-run', '--help', '--json', '--path', '--source', '--yes'],- 'post-upgrade': ['--acknowledge-no-backup', '--all', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--check', '--concurrency', '--confirm-quiesced', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-embed', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--quiet', '--repo', '--require-db', '--skills-dir', '--skip-verify', '--source', '--status', '--swap-only', '--target', '--uninstall', '--user', '--verify', '--version', '--workers', '--yes'],+ 'post-upgrade': ['--acknowledge-no-backup', '--admin-intent', '--all', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--check', '--concurrency', '--confirm-quiesced', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-embed', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--path', '--quiet', '--repo', '--require-db', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--swap-only', '--target', '--uninstall', '--user', '--verify', '--version', '--workers', '--yes'],'protocol': ['--access', '--asof', '--bound-slug-prefixes', '--brain', '--date', '--days', '--entities', '--file', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--mode', '--multimodal', '--once', '--page', '--path', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--surface', '--synthesize', '--target', '--token', '--trusted-extraction', '--types', '--url', '--yes'],'providers': ['--brain', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--model', '--source', '--status', '--touchpoint'],'publish': ['--accent', '--bg', '--border', '--brain', '--card-bg', '--code-bg', '--error', '--fg', '--help', '--json', '--link', '--muted', '--out', '--password', '--source', '--title'],@@ -95,6 +95,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'reindex-search-vector': ['--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--yes'],'reinit-pglite': ['--abbrev-ref', '--all', '--allow-create-db', '--allow-docker', '--allow-empty', '--brain', '--break-lock', '--cached', '--chat-model', '--concurrency', '--confirm-destructive', '--content-root', '--db-only', '--diff-filter', '--embedding-dimensions', '--embedding-model', '--empty', '--entity', '--exclude', '--exclude-standard', '--expansion-model', '--filters', '--fix', '--force', '--force-break-lock', '--format', '--full', '--full-history', '--git', '--grant-types', '--hard-deadline', '--help', '--http', '--include-gitignored', '--include-hidden', '--interval', '--is-ancestor', '--is-shallow-repository', '--issuer-url', '--json', '--key', '--local-postgres', '--max-age', '--max-sources', '--mcp-only', '--mcp-url', '--migrate-only', '--missing-path', '--model', '--name-only', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-git', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-renames', '--no-schema-pack', '--no-sync', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--others', '--parallel', '--path', '--pglite', '--prefer-postgres', '--priority', '--provenance', '--quiet', '--repo', '--retry-failed', '--schema-pack', '--scopes', '--serial', '--show-toplevel', '--skip-embed-check', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--supabase', '--surface', '--timeout', '--to', '--url', '--verify', '--version', '--watch', '--workers', '--working-tree', '--yes'],'remote': ['--brain', '--help', '--json', '--mcp-only', '--scopes', '--source', '--timeout'],+ 'repair': ['--all', '--apply', '--brain', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--limit', '--no-embed', '--source', '--stale', '--status', '--yes'],'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', '--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', '--cleanup-dead-local-locks', '--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', '--self-transfer', '--services', '--set', '--shared-skills', '--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'],@@ -114,11 +115,11 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'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'],- 'sync': ['--abbrev-ref', '--abort', '--account', '--all', '--allow-empty', '--apply-rewrites', '--auto', '--background', '--batch-size', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--catch-up', '--concurrency', '--confirm-destructive', '--content-audit', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--hard-deadline', '--harness', '--help', '--home', '--http', '--ids', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--log-noop', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-only', '--missing-path', '--multimodal', '--name-only', '--name-status', '--ner', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-recurse-submodules', '--no-renames', '--no-schema-pack', '--no-verify', '--older-than', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--prefer-postgres', '--priority', '--probe-pglite', '--progress-interval', '--progress-json', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--repo', '--reset', '--restore-only', '--resume', '--retry-failed', '--scope', '--scopes', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--target', '--target-score', '--timeout', '--to', '--top-k', '--type', '--url', '--verbose', '--verify', '--version', '--watch', '--window', '--workers', '--working-tree', '--yes'],+ 'sync': ['--abbrev-ref', '--abort', '--account', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--auto', '--background', '--batch-size', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--catch-up', '--concurrency', '--confirm-destructive', '--content-audit', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--hard-deadline', '--harness', '--help', '--home', '--http', '--ids', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--log-noop', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-only', '--missing-path', '--multimodal', '--name-only', '--name-status', '--ner', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-recurse-submodules', '--no-renames', '--no-schema-pack', '--no-verify', '--older-than', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--prefer-postgres', '--priority', '--probe-pglite', '--progress-interval', '--progress-json', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--repo', '--request-id', '--reset', '--restore-only', '--resume', '--retry-failed', '--scope', '--scopes', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--target', '--target-score', '--timeout', '--to', '--top-k', '--type', '--url', '--verbose', '--verify', '--version', '--watch', '--window', '--workers', '--working-tree', '--yes'],'takes': ['--accept', '--batch-size', '--brain', '--bucket-size', '--by', '--claim', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--force', '--from-pages', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--no-embed', '--no-embedding', '--offset', '--outcome', '--pglite', '--quality', '--reject', '--request-id', '--row', '--semantic', '--since', '--sort', '--source', '--source-id', '--stale', '--status', '--supabase', '--to', '--unit', '--until', '--value', '--weight', '--who', '--yes'],'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--json', '--mcp-only', '--model', '--rounds', '--save', '--since', '--source', '--take', '--until', '--with-calibration'],'transcripts': ['--all', '--all-discovery', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--progress-interval', '--progress-json', '--quiet', '--since', '--source', '--source-id', '--timeout'],- 'upgrade': ['--acknowledge-no-backup', '--all', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--check', '--concurrency', '--confirm-quiesced', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-embed', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--quiet', '--repo', '--require-db', '--skills-dir', '--skip-verify', '--source', '--status', '--swap-only', '--target', '--uninstall', '--user', '--verify', '--version', '--workers', '--yes'],+ 'upgrade': ['--acknowledge-no-backup', '--admin-intent', '--all', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--check', '--concurrency', '--confirm-quiesced', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-embed', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--path', '--quiet', '--repo', '--require-db', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--swap-only', '--target', '--uninstall', '--user', '--verify', '--version', '--workers', '--yes'],'waiting': ['--all', '--brain', '--help', '--json', '--source', '--stale-ok', '--status', '--top', '--type'],'watch': ['--brain', '--help', '--json', '--max-pages', '--min-confidence', '--source', '--window-turns'],'whoknows': ['--access', '--asof', '--bound-slug-prefixes', '--brain', '--date', '--days', '--entities', '--explain', '--file', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--mcp-only', '--mode', '--multimodal', '--once', '--page', '--path', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--surface', '--trusted-extraction', '--types', '--url', '--yes'],diff --git a/src/core/company-brain/profile.ts b/src/core/company-brain/profile.tsindex da01486614..2dca43e963 100644--- a/src/core/company-brain/profile.ts+++ b/src/core/company-brain/profile.ts@@ -89,7 +89,7 @@ export async function importCompanyBrainFile(engine: BrainEngine, filePath: striif (ready.slug !== entry.page!.slug || ready.observedRevision !== (snapshot?.revision ?? null)) {throw new OperationError('revision_conflict', 'The approved file no longer names the same page revision.');}- const project = prepareCanonicalProjections(ready.parsedPage, ready.slug, sourceId);+ const project = await prepareCanonicalProjections(engine, ready.parsedPage, ready.slug, sourceId, snapshot, 'immutable');await withCompanyBrainSource(engine, sourceId, async tx => { await ready.apply(tx); await project(tx); });return ready.result;} }).catch(error => {diff --git a/src/core/config.ts b/src/core/config.tsindex e839d4c129..93c747549b 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -1459,6 +1459,9 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [// dream.synthesize.* pair from #1594).'dream.patterns.subagent_timeout_ms','dream.patterns.subagent_wait_timeout_ms',+ // Paid-loop breaker: dead submissions of one dream key within 24h before+ // it is refused (default 3; 0 disables). `gbrain dream reset-key` clears one.+ 'dream.breaker.max_dead_submissions',// Emotional weight (v0.29)'emotional_weight.high_tags','emotional_weight.user_holder',@@ -1578,6 +1581,14 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = ['schema.type_warnings',// #4795 reindex-search-vector marker (doctor fts_reindex_incomplete reads it); `config unset` is the escape hatch.'fts.reindex_in_progress',+ // #5470: managed-write journal caps + receipt retention, read by+ // persistence/limits.ts (JOURNAL_CONFIG_KEYS; drift-guarded by test).+ 'persistence.limits.principal_outstanding', 'persistence.limits.brain_outstanding',+ 'persistence.limits.principal_intent_bytes', 'persistence.limits.brain_intent_bytes',+ 'persistence.limits.principal_lifetime_ids', 'persistence.limits.brain_lifetime_ids',+ 'persistence.limits.principal_terminal_bytes', 'persistence.limits.brain_terminal_bytes',+ 'persistence.limits.brain_recovery_bytes', 'persistence.limits.worktree_recovery_bytes',+ 'persistence.receipt_retention_days',];/**diff --git a/src/core/context/corpus-segments.ts b/src/core/context/corpus-segments.tsindex 06411cecb6..8aa95ec3fe 100644--- a/src/core/context/corpus-segments.ts+++ b/src/core/context/corpus-segments.ts@@ -325,6 +325,15 @@ export function parseWbFileName(name: string): { sessionId: string; hash: stringreturn m ? { sessionId: m[1], hash: m[2], ...(m[3] ? { sourceId: m[3] } : {}) } : null;}+/**+ * The harness session a `.txt` corpus file belongs to: the session-end+ * `<sessionId>.txt`, a checkpoint segment or a writeback turn file. Used to+ * classify gbrain's own claude-cli sessions (#5413) across every form.+ */+export function corpusFileSessionId(name: string): string {+ return parseSegmentFileName(name)?.sessionId ?? parseWbFileName(name)?.sessionId ?? name.replace(/\.txt$/, '');+}+/** The TERMINAL writeback_off `.ingested` sidecar payload — the wb state* machine's one terminal skip, written identically by the serve harvest and* the sweep backstop (shape drift between the two writers would be invisiblediff --git a/src/core/context/turn-context.ts b/src/core/context/turn-context.tsindex 53c5fa5e50..c545c901e4 100644--- a/src/core/context/turn-context.ts+++ b/src/core/context/turn-context.ts@@ -276,7 +276,12 @@ export async function assembleTurnContext(};const meta = await getBrainHotMemoryMeta('turn_context', metaCtx);const hot = meta?.brain_hot_memory as { facts?: TurnContextFact[] } | undefined;- return Array.isArray(hot?.facts) ? [...hot.facts] : [];+ const all = Array.isArray(hot?.facts) ? [...hot.facts] : [];+ // Cross-turn dedupe, same contract as volunteered pages: a fact already+ // injected this session is not repeated. Matched without the trailing+ // confidence, which drifts as facts age.+ const prior = opts.priorContextText;+ return prior ? all.filter((f) => !prior.includes(renderFactLine(f).replace(/ \([0-9.]+\)$/, ' ('))) : all;} catch {return [];}diff --git a/src/core/contextual-retrieval-service.ts b/src/core/contextual-retrieval-service.tsindex 25dea976ce..9a8813dbad 100644--- a/src/core/contextual-retrieval-service.ts+++ b/src/core/contextual-retrieval-service.ts@@ -47,7 +47,6 @@ import {buildContextualPrefix,modeRequiresSynopsis,modeRequiresWrapper,- sanitizeTitle,wrapChunkForEmbedding,} from './embedding-context.ts';import {@@ -322,7 +321,8 @@ export async function reembedPageWithContextualRetrieval(await tx.lockPageKeys([{ sourceId: page.source_id, slug: page.slug }]);if (digest(sourcePolicy(await loadSourceRow(tx, page.source_id))) !== digest(sourcePolicy(source))) return false;if (embedded) {- if (!await installPageEmbeddings(tx, prepared, embedded.map(chunk => ({ ...chunk, model: prepared.embeddingModel ?? undefined })))) return false;+ if (!await installPageEmbeddings(tx, prepared, embedded.map(chunk => ({ ...chunk, model: prepared.embeddingModel ?? undefined })),+ undefined, { tier: mode, corpusGeneration: generation })) return false;} else {const current = await readProjectionSnapshot(tx, page.slug, page.source_id, { allowUnsealed: true });if (!sameProjection(prepared, current)) return false;@@ -491,7 +491,8 @@ async function tryBuildPhase1(opts: {// Build the wrapper prefix for THIS page. Title-only tier: one prefix// reused across all chunks. per_chunk_synopsis tier: prefix is built// per-chunk with the chunk-specific generated synopsis.- const safeTitle = sanitizeTitle(page.title);+ // buildContextualPrefix sanitizes once, as every embedding writer and embedding-input-hash.ts do.+ const title = page.title;if (attemptMode === 'title' || !modeRequiresSynopsis(attemptMode)) {// Title-only path. No synopsis-model calls; pure string concat.@@ -499,7 +500,7 @@ async function tryBuildPhase1(opts: {// the title tier wants slightly more context — but per D2 the// balanced default is title-only without summary. Keep it pure for// now; the title block alone is what 'balanced' ships.- const prefix = buildContextualPrefix(safeTitle, null);+ const prefix = buildContextualPrefix(title, null);const wrappedTexts = chunks.map((c) =>modeRequiresWrapper(attemptMode)? wrapChunkForEmbedding(c.chunk_text, prefix, c.chunk_source)@@ -542,7 +543,7 @@ async function tryBuildPhase1(opts: {wrappedTexts[i] = await buildWrappedChunkText({chunk: c,sourceText,- safeTitle,+ title,page,args,synopsisModel,@@ -590,14 +591,14 @@ class ChunkSynopsisPhase1Error extends Error {async function buildWrappedChunkText(opts: {chunk: ChunkInput;sourceText: string;- safeTitle: string;+ title: string;page: Page;args: ReembedPageArgs;synopsisModel: string;/** #3883: resolved output-token cap (undefined → page-summary default). */synopsisMaxTokens?: number;}): Promise<string> {- const { chunk: c, sourceText, safeTitle, page, args, synopsisModel, synopsisMaxTokens } = opts;+ const { chunk: c, sourceText, title, page, args, synopsisModel, synopsisMaxTokens } = opts;// Code chunks always bypass the wrapper (D20-T4) — pass through.if (c.chunk_source === 'fenced_code') {@@ -648,7 +649,7 @@ async function buildWrappedChunkText(opts: {}if (synopsisResult.kind === 'success') {- const prefix = buildContextualPrefix(safeTitle, synopsisResult.synopsis);+ const prefix = buildContextualPrefix(title, synopsisResult.synopsis);return wrapChunkForEmbedding(c.chunk_text, prefix, c.chunk_source);}diff --git a/src/core/cycle.ts b/src/core/cycle.tsindex 1caf6d2707..ec5dd75683 100644--- a/src/core/cycle.ts+++ b/src/core/cycle.ts@@ -1274,6 +1274,7 @@ async function runPhaseSync(noExtract: willRunExtractPhase, // dedupe ONLY when cycle's extract phase will also run.// If extract isn't scheduled (e.g. `gbrain dream --phase sync`),// sync's inline extract still runs to preserve prior behavior.+ explicitProcessing: [], // unattended: an unfinished managed cursor keeps its own options (#5632)});const syncedCount = result.added + result.modified;// #3068: a pull_failed partial means the internal git pull failed and thediff --git a/src/core/cycle/dream-breaker.ts b/src/core/cycle/dream-breaker.tsnew file mode 100644index 0000000000..527a28ec97--- /dev/null+++ b/src/core/cycle/dream-breaker.ts@@ -0,0 +1,121 @@+/**+ * Paid-loop circuit breaker for dream synthesize and patterns.+ *+ * A dream idempotency key whose submissions died 3 times within 24 h is not+ * submitted again until an operator resets it. A submission is one+ * (base key, queue) pair: chunks of one run share the run's private inline+ * queue, so a chunked transcript counts once per run. Deaths are counted by+ * finish time over dead `subagent` rows, reading the live key or the key the+ * queue recorded when it released the slot (`__released_idempotency_key`).+ * Only dead rows count: a completed job, including a legitimate zero-write+ * completion, is never a death.+ *+ * Not covered: content-hashed keys change whenever a transcript grows, and+ * patterns runs outside maintenance carry no key.+ */+import type { BrainEngine } from '../engine.ts';++export const DREAM_BREAKER_KEY_PREFIXES = ['dream:synth-v2:', 'dream:patterns:'] as const;+export const DREAM_BREAKER_CONFIG_KEY = 'dream.breaker.max_dead_submissions';+export const DREAM_BREAKER_RESETS_KEY = 'dream.breaker.resets';+export const DEFAULT_MAX_DEAD_SUBMISSIONS = 3;++export interface DeadDreamSubmissions { base_key: string; dead_submissions: number; last_dead_at: string }++export function dreamBreakerBaseKey(key: string): string {+ return key.replace(/:c\d+of\d+$/, '');+}++export function dreamBreakerResetCommand(baseKey: string): string {+ return `gbrain dream reset-key '${baseKey.replaceAll("'", "'\\''")}'`;+}++/** 0 disables the breaker; unset or invalid values use the default. */+export async function loadDreamBreakerThreshold(engine: BrainEngine): Promise<number> {+ const raw = await engine.getConfig(DREAM_BREAKER_CONFIG_KEY);+ if (raw === null || raw === undefined || raw.trim() === '') return DEFAULT_MAX_DEAD_SUBMISSIONS;+ const value = Number(raw);+ return Number.isSafeInteger(value) && value >= 0 ? value : DEFAULT_MAX_DEAD_SUBMISSIONS;+}++async function loadResets(engine: BrainEngine): Promise<Record<string, string>> {+ const raw = await engine.getConfig(DREAM_BREAKER_RESETS_KEY);+ if (!raw) return {};+ try {+ const parsed = JSON.parse(raw) as unknown;+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return {};+ return Object.fromEntries(Object.entries(parsed).filter(([, at]) => typeof at === 'string' && Number.isFinite(Date.parse(at))));+ } catch { return {}; }+}++/**+ * The one counting rule shared by the breaker, `gbrain dream reset-key --list`+ * and the doctor check. Dead submissions finished before a key's persisted+ * reset time do not count. Backed by the partial index on dead subagent+ * finish times.+ */+export async function countDeadDreamSubmissions(engine: BrainEngine): Promise<DeadDreamSubmissions[]> {+ const resets = await loadResets(engine);+ return engine.executeRaw<DeadDreamSubmissions>(+ `WITH dead AS (+ SELECT regexp_replace(COALESCE(idempotency_key, data->>'__released_idempotency_key'), ':c[0-9]+of[0-9]+$', '') AS base_key,+ queue, finished_at+ FROM minion_jobs+ WHERE name = 'subagent' AND status = 'dead' AND finished_at > now() - interval '24 hours'+ )+ SELECT base_key, COUNT(DISTINCT queue)::int AS dead_submissions, MAX(finished_at)::text AS last_dead_at+ FROM dead+ WHERE (left(base_key, ${DREAM_BREAKER_KEY_PREFIXES[0].length}) = $1 OR left(base_key, ${DREAM_BREAKER_KEY_PREFIXES[1].length}) = $2)+ AND finished_at > COALESCE(($3::text::jsonb ->> base_key)::timestamptz, '-infinity'::timestamptz)+ GROUP BY base_key+ ORDER BY dead_submissions DESC, base_key`,+ [DREAM_BREAKER_KEY_PREFIXES[0], DREAM_BREAKER_KEY_PREFIXES[1], JSON.stringify(resets)],+ );+}++export interface DreamBreaker { threshold: number; tripped: Map<string, number> }++/**+ * Tripped base keys for this run, or null when the breaker is disabled or its+ * count failed. A failed count skips the breaker for the run with a warning,+ * the same posture as the synthesize daily cap.+ */+export async function loadDreamBreaker(engine: BrainEngine): Promise<DreamBreaker | null> {+ try {+ const threshold = await loadDreamBreakerThreshold(engine);+ if (threshold === 0) return null;+ const rows = await countDeadDreamSubmissions(engine);+ return { threshold, tripped: new Map(rows.filter(row => row.dead_submissions >= threshold).map(row => [row.base_key, row.dead_submissions])) };+ } catch (error) {+ process.stderr.write(`[dream] breaker count query failed (${error instanceof Error ? error.message : String(error)}); `+ + 'skipping the paid-loop breaker for this run\n');+ return null;+ }+}++/** Refusal line for the cycle summary and the autopilot log. */+export function dreamBreakerRefusal(breaker: DreamBreaker, baseKey: string): string | null {+ const count = breaker.tripped.get(baseKey);+ if (count === undefined) return null;+ return `dream_breaker_tripped: ${count} dead submissions in 24h (limit ${breaker.threshold}) for ${baseKey}; `+ + `no synthesis submitted. Fix the cause, then run: ${dreamBreakerResetCommand(baseKey)}`;+}++/**+ * Persist a reset: deaths of this key that finished before now (database+ * clock) stop counting. One atomic upsert merges the key into the stored map+ * and drops entries older than the window, so concurrent resets of different+ * keys both survive. Stored in config, so it survives restarts.+ */+export async function resetDreamBreakerKey(engine: BrainEngine, baseKey: string): Promise<void> {+ await engine.executeRaw(+ `INSERT INTO config (key, value)+ VALUES ($1, jsonb_build_object($2::text, to_char((now() + interval '1 millisecond') AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"'))::text)+ ON CONFLICT (key) DO UPDATE SET value = ((+ SELECT COALESCE(jsonb_object_agg(entry.key, entry.value), '{}'::jsonb)+ FROM jsonb_each_text(CASE WHEN config.value IS JSON OBJECT THEN config.value::jsonb ELSE '{}'::jsonb END) entry+ WHERE entry.key <> $2::text AND entry.value ~ '^[0-9]{4}-' AND entry.value::timestamptz > now() - interval '24 hours'+ ) || EXCLUDED.value::jsonb)::text`,+ [DREAM_BREAKER_RESETS_KEY, dreamBreakerBaseKey(baseKey)],+ );+}diff --git a/src/core/cycle/extract-atoms.ts b/src/core/cycle/extract-atoms.tsindex 4f48c79d16..e32e180e25 100644--- a/src/core/cycle/extract-atoms.ts+++ b/src/core/cycle/extract-atoms.ts@@ -79,6 +79,7 @@ import { isUndefinedTableError, warnOncePerProcess } from '../utils.ts';import { normalizeForGrounding } from './synthesize-verify.ts';import type { TranscriptPageIndex } from '../transcripts/discover.ts';import { managedAtomSession, readAtomOrigin, resumeManagedAtoms, publishManagedAtoms, MANAGED_ATOM_DISCOVERY_SQL, type AtomOrigin } from '../persistence/atom-maintenance.ts';+import { effectiveVisibility } from '../search/private-visibility.ts';import { OperationError } from '../ops/contract.ts';import type { WriteReceipt } from '../persistence/types.ts';import { AtomPageStateError, completeAtomReceipts, readAtomPageIdentity, writeAtomPageState, type AtomPageInput } from './extract-atoms-page-state.ts';@@ -1083,6 +1084,8 @@ export async function runPhaseExtractAtoms(const promptContent = truncateUtf8(item.content, maxInputChars);try {const origin: AtomOrigin | null = managed ? await readAtomOrigin(engine, managed, item) : null;+ const visibility = origin?.visibility ?? effectiveVisibility(item.kind === 'transcript' ? { kind: 'transcript' } // #5525+ : { kind: 'page', page: await engine.getPage(item.slug, { sourceId }) });if (!opts.dryRun && managed && origin && await resumeManagedAtoms(engine, managed, origin)) {duplicatesSkipped++;continue;@@ -1240,7 +1243,7 @@ export async function runPhaseExtractAtoms(...originFrontmatter,// Provisional until the whole item's atoms persist (see above).source_hash: `pending:${hash16}`,- ...(origin ? { visibility: origin.visibility, managed_extraction: true } : {}),+ visibility, ...(origin ? { managed_extraction: true } : {}),...quoteFields,...(atom.lesson && { lesson: atom.lesson }),...(atom.concepts && atom.concepts.length > 0 && { concepts: atom.concepts }),diff --git a/src/core/cycle/patterns.ts b/src/core/cycle/patterns.tsindex 385e9f9b52..7b05eb9a45 100644--- a/src/core/cycle/patterns.ts+++ b/src/core/cycle/patterns.ts@@ -45,6 +45,7 @@ import { loadAllowedSlugPrefixes, loadOutputRoot, runSubagentsInline } from './simport { probeChatModel } from '../ai/gateway.ts';import { normalizeModelId } from '../model-id.ts';import { throwIfAborted } from '../abort-check.ts';+import { dreamBreakerRefusal, loadDreamBreaker } from './dream-breaker.ts';export interface PatternsPhaseOpts {brainDir: string;@@ -257,8 +258,12 @@ export async function runPhasePatterns(max_turns: 30,// #4217/CDX-12: a patterns child whose every put_page failed must// dead-letter (its whole purpose is writing pattern pages), not report- // completed with zero pages.+ // completed with zero pages. #5540: a clean finish that examined the+ // evidence and named nothing completes, so the #4879 watermark stamps+ // instead of re-billing the same reflections every run. Older workers+ // ignore the opt-in and keep the strict behavior.require_writes: true,+ allow_clean_zero_writes: true,allowed_slug_prefixes: allowedSlugPrefixes,// #1586: scope every child tool call to the cycle's resolved source so// put_page writes land there instead of the hardcoded 'default'.@@ -274,6 +279,13 @@ export async function runPhasePatterns(private_queue_owner_token: privateQueueOwnerToken,private_queue_lease_ms: DEFAULT_PRIVATE_QUEUE_LEASE_MS,};+ // Paid-loop breaker: only maintenance runs carry a key, so only they are covered.+ const breaker = submitOpts.idempotency_key ? await loadDreamBreaker(engine) : null;+ const refusal = breaker && dreamBreakerRefusal(breaker, submitOpts.idempotency_key!);+ if (refusal) {+ process.stderr.write(`[dream] patterns: ${refusal}\n`);+ return skipped('dream_breaker_tripped', refusal);+ }let job: Awaited<ReturnType<typeof queue.add>>;try {job = await queue.add('subagent', data as unknown as Record<string, unknown>, submitOpts, {@@ -470,6 +482,11 @@ async function getSlugPrefixConfig(engine: BrainEngine, key: string, fallback: sreturn trimmed || fallback;}+/** Where pattern pages land; also a dream output directory synthesize discovery excludes (#5471). */+export async function loadPatternsOutputSlugPrefix(engine: BrainEngine, outputRoot: string): Promise<string> {+ return getSlugPrefixConfig(engine, 'dream.patterns.output_slug_prefix', `${outputRoot}/personal/patterns`);+}+async function loadPatternsConfig(engine: BrainEngine): Promise<PatternsConfig> {const enabledStr = await engine.getConfig('dream.patterns.enabled');const enabled = enabledStr === null ? true : enabledStr === 'true';@@ -493,9 +510,7 @@ async function loadPatternsConfig(engine: BrainEngine): Promise<PatternsConfig>sourceSlugPrefix: await getSlugPrefixConfig(engine, 'dream.patterns.source_slug_prefix', `${outputRoot}/personal/reflections`,),- outputSlugPrefix: await getSlugPrefixConfig(- engine, 'dream.patterns.output_slug_prefix', `${outputRoot}/personal/patterns`,- ),+ outputSlugPrefix: await loadPatternsOutputSlugPrefix(engine, outputRoot),subagentTimeoutMs: await getNumberConfig(engine, 'dream.patterns.subagent_timeout_ms', DEFAULT_PATTERNS_SUBAGENT_TIMEOUT_MS,),diff --git a/src/core/cycle/synthesize-concepts.ts b/src/core/cycle/synthesize-concepts.tsindex c217f83e6f..7c83704dfb 100644--- a/src/core/cycle/synthesize-concepts.ts+++ b/src/core/cycle/synthesize-concepts.ts@@ -35,6 +35,7 @@ import { createGlobalLlmHaltTracker, haltedClassOf, type GlobalLlmErrorClass } fimport { importFromContent } from '../import-file.ts';import { serializeMarkdown } from '../markdown.ts';import { canonicalLookup, type ModelPricing } from '../model-pricing.ts';+import { privatePagesFilterFragment, strictestVisibility, type Visibility } from '../search/private-visibility.ts';const DEFAULT_BUDGET_USD = 1.5;// Canonical-miss policy — mirrors skillopt/preflight.ts's lookupPrice:@@ -101,7 +102,7 @@ export interface SynthesizeConceptsOpts {/** Test seam: alternative chat function. */_chat?: typeof gatewayChat;/** Test seam: skip DB query; cluster these atoms directly. */- _atoms?: Array<{ slug: string; concept_refs: string[]; body: string; title: string }>;+ _atoms?: Array<{ slug: string; concept_refs: string[]; body: string; title: string; visibility?: Visibility }>;}interface AtomGroup {@@ -110,6 +111,8 @@ interface AtomGroup {atomSlugs: string[];atomTitles: string[];atomBodies: string[];+ /** #5525: strictest effective visibility of the member atoms. */+ visibility: Visibility;tier: 'T1' | 'T2' | 'T3' | 'T4';}@@ -141,11 +144,12 @@ export async function runPhaseSynthesizeConcepts(title: string;compiled_truth: string;frontmatter: { concepts?: string[]; imported_from?: string };+ private: boolean;}>(// Codex P2: scoped to the cycle source — the provenance edges below// are pinned to it, so a brain-global scan grouped same-slug atoms// from OTHER sources into this source's concepts.- `SELECT slug, title, compiled_truth, frontmatter+ `SELECT slug, title, compiled_truth, frontmatter, NOT (${privatePagesFilterFragment('pages')}) AS privateFROM pagesWHERE type = 'atom'AND source_id = $1@@ -160,6 +164,7 @@ export async function runPhaseSynthesizeConcepts(title: r.title,body: r.compiled_truth,concept_refs: r.frontmatter!.concepts!,+ visibility: r.private ? 'private' as const : 'world' as const,}));} catch {// No atoms table or query failed — phase no-ops cleanly.@@ -177,13 +182,15 @@ export async function runPhaseSynthesizeConcepts(}// 2. Group atoms by concept slug- const groups = new Map<string, { slugs: string[]; titles: string[]; bodies: string[] }>();+ const groups = new Map<string, { slugs: string[]; titles: string[]; bodies: string[]; visibilities: Visibility[] }>();for (const atom of atoms) {for (const conceptSlug of atom.concept_refs) {- const existing = groups.get(conceptSlug) ?? { slugs: [], titles: [], bodies: [] };+ const existing = groups.get(conceptSlug) ?? { slugs: [], titles: [], bodies: [], visibilities: [] };existing.slugs.push(atom.slug);existing.titles.push(atom.title);existing.bodies.push(atom.body);+ // An atom with no recorded visibility is private (derived pages fail closed).+ existing.visibilities.push(atom.visibility ?? 'private');groups.set(conceptSlug, existing);}}@@ -200,6 +207,7 @@ export async function runPhaseSynthesizeConcepts(atomSlugs: data.slugs,atomTitles: data.titles,atomBodies: data.bodies,+ visibility: strictestVisibility(data.visibilities),tier,});}@@ -365,27 +373,34 @@ export async function runPhaseSynthesizeConcepts(if (!opts.dryRun) {const title = conceptSlug.slice('concepts/'.length);+ // #5525: tighten-only — a concept already private stays private.+ const prior = await engine.getPage(conceptSlug, { sourceId: opts.sourceId ?? 'default' });+ const visibility = strictestVisibility([group.visibility, prior?.frontmatter?.visibility === 'private' ? 'private' : 'world']);// #2163: serialize to markdown and import via the canonical pipeline so// the page is chunked (+ embedded when a provider is configured) —// mirrors put_page's isAvailable('embedding') → noEmbed gate.- const md = serializeMarkdown(+ const synthesizedAt = new Date().toISOString();+ const publish = (pageVisibility: Visibility) => importFromContent(engine, conceptSlug, serializeMarkdown({tier: group.tier,mention_count: group.atomTitles.length,composite_score: group.atomTitles.length,synthesis_mode: synthesisMode,- synthesized_at: new Date().toISOString(),+ synthesized_at: synthesizedAt,synthesized_by: 'synthesize_concepts-v0.41',+ visibility: pageVisibility,},narrative,'',{ type: 'concept', title: title.replace(/-/g, ' '), tags: [] },- );- await importFromContent(engine, conceptSlug, md, {+ ), {noEmbed: !isAvailable('embedding'),// #4416: target the cycle's resolved source, not the 'default' literal.sourceId: opts.sourceId,});+ // #5525: a world concept stays private until every member's provenance+ // edge is durable, because a later private flip reaches it through them.+ await publish('private');// #4589: bank concept<->member-atom provenance edges. The prompt forbids// enumerating atoms in the body and no frontmatter field maps to a link// verb, so without this every concept page lands with zero edges (graph@@ -417,6 +432,14 @@ export async function runPhaseSynthesizeConcepts(linkWarnings.push({ concept: group.conceptSlug, warning: `provenance links failed: ${msg}` });console.error(`[synthesize_concepts] provenance links failed for ${conceptSlug} (non-fatal): ${msg}`);}+ if (visibility === 'world') {+ const members = [...new Set(group.atomSlugs)];+ const [{ linked }] = await engine.executeRaw<{ linked: number }>(`SELECT COUNT(DISTINCT a.slug)::int AS linked FROM links l+ JOIN pages c ON c.id=l.from_page_id JOIN pages a ON a.id=l.to_page_id+ WHERE c.source_id=$1 AND c.slug=$2 AND a.slug=ANY($3::text[]) AND l.link_source='concept-provenance' AND l.link_type='synthesized_from'`,+ [src, conceptSlug, members]);+ if (Number(linked) === members.length) await publish('world');+ }}conceptsWritten++;// v0.41.19.0 (T4): one tick per concept group with running count.diff --git a/src/core/cycle/synthesize-verify.ts b/src/core/cycle/synthesize-verify.tsindex 2f75ae078c..467cb98a54 100644--- a/src/core/cycle/synthesize-verify.ts+++ b/src/core/cycle/synthesize-verify.ts@@ -61,7 +61,7 @@ import { importFromContent } from '../import-file.ts';import { serializePageToMarkdown } from '../markdown.ts';import { throwIfAborted } from '../abort-check.ts';import type { Page } from '../types.ts';-import { prepareCanonicalProjections } from '../persistence/canonical-projections.ts';+import { materializedHistoryRanges, prepareCanonicalProjections } from '../persistence/canonical-projections.ts';import { prepareAutomaticLinks } from '../persistence/links-preparation.ts';import { isAutoLinkEnabled } from '../link-extraction.ts';@@ -795,8 +795,16 @@ export function verifyBody(body: string, sources: GroundedSource[], opts: { prioconst provenance: QuoteProvenance[] = [];let quotes = 0, exact = 0, normalized = 0, near = 0;+ // Materialized timeline history (#5567) is database history a write rendered+ // back into an existing page, not a claim this run authored. Only a marked+ // bullet absent from the pre-run revision was materialized during the run+ // (with its stored detail); an edit under a bullet that already existed is+ // verified like any other new unit. A new page has no history to render.+ const history = opts.priorNorm === undefined ? [] : materializedHistoryRanges(body)+ .filter(([start, end]) => !opts.priorNorm!.includes(normForGrounding(body.slice(start, end).split('\n')[1] ?? '')));for (const u of claimUnits(body, spans)) {const text = body.slice(u.start, u.end);+ if (history.some(([start, end]) => u.start >= start && u.start < end)) continue;if (opts.priorNorm !== undefined && opts.priorNorm.includes(normForGrounding(text))) continue;const unitSpans = spans.filter(sp => sp.start >= u.start && sp.end < u.end);const quoteRanges = unitSpans.map(sp => [sp.start - u.start, sp.end - u.start + 1] as [number, number]);@@ -1058,7 +1066,10 @@ export async function verifyAndRepairDreamPages(// from the unverified body; re-project from the verified body in the// same transaction so no derived row outlives its quarantined claim.const parsed = { type: page.type, title: page.title, compiled_truth: next.compiled_truth, timeline: next.timeline, frontmatter: next.frontmatter, tags };- const project = prepareCanonicalProjections(parsed, ref.slug, ref.source_id);+ // Preserving writer (#5567): rows for bullets the verifier removed are+ // deleted; database-only timeline history is kept.+ const project = await prepareCanonicalProjections(engine, parsed, ref.slug, ref.source_id,+ await engine.readPageSnapshot(ref.slug, { sourceId: ref.source_id }), 'preserving');const links = await isAutoLinkEnabled(engine) ? await prepareAutomaticLinks(engine, ref.slug, parsed, ref.source_id) : undefined;// noEmbed: the phase-end embed sweep backfills. Provenance fields// null → engine COALESCE keeps the first-write record intact.diff --git a/src/core/cycle/synthesize.ts b/src/core/cycle/synthesize.tsindex b697f1af6c..30c859c108 100644--- a/src/core/cycle/synthesize.ts+++ b/src/core/cycle/synthesize.ts@@ -62,7 +62,8 @@ import { parseLlmJson } from '../llm-json.ts';import type { BrainEngine, DreamVerdict, TriageSegment } from '../engine.ts';import type { PhaseResult, PhaseError } from '../cycle.ts';import { DEFAULT_PRIVATE_QUEUE_LEASE_MS, MinionQueue } from '../minions/queue.ts';-import { clampSubagentBudgets, CYCLE_DEADLINE_RESERVE_MS, MIN_PATTERNS_SUBAGENT_BUDGET_MS } from './patterns.ts';+import { clampSubagentBudgets, CYCLE_DEADLINE_RESERVE_MS, MIN_PATTERNS_SUBAGENT_BUDGET_MS, loadPatternsOutputSlugPrefix } from './patterns.ts';+import { claudeCliSelfSessionIds } from '../ai/providers/claude-cli-scratch.ts';import { isQueueQuotaExceededError } from '../minions/admission.ts';import { waitForCompletionRenewing, TimeoutError } from '../minions/wait-for-completion.ts';import type { MinionJobInput, SubagentHandlerData } from '../minions/types.ts';@@ -86,6 +87,7 @@ import { safeSplitIndex } from '../text-safe.ts';import { PAGE_SLUG_SEG } from '../cjk.ts';import { withChatPhase, estimateChatCostUsd } from '../ai/chat-usage.ts';import { verifyAndRepairDreamPages, normForGrounding, readVerifyEpoch, loadChildWriteEpochs, type QuoteVerifyStats, type TranscriptForVerify } from './synthesize-verify.ts';+import { dreamBreakerRefusal, loadDreamBreaker } from './dream-breaker.ts';import { passesTriageGate, rescueConfigOf, DEFAULT_RESCUE_FLOOR, DEFAULT_RESCUE_MIN_SEGMENTS, DEFAULT_RESCUE_CONTENT_TYPES, DEFAULT_RESCUE_CONFIG, type RescueConfig, type RescueVerdictLike } from './triage-rescue.ts';// Slug grammar from validatePageSlug — shared via PAGE_SLUG_SEG (#738).@@ -474,6 +476,18 @@ async function runPhaseSynthesizeInner(from: opts.from,to: opts.to,bypassGuard: opts.bypassDreamGuard,+ // #5471: outputs a failed postprocess left unmarked must not come+ // back as transcripts; the explicit bypass re-enables them.+ excludeDirs: opts.bypassDreamGuard+ ? []+ : [+ config.reflectionsPrefix,+ config.originalsPrefix,+ await loadPatternsOutputSlugPrefix(engine, config.outputRoot),+ dirname(buildDreamSummarySlug(config.outputRoot, 'x')),+ ].map(prefix => join(opts.brainDir, prefix)),+ // #5413: corpus files captured from gbrain's own claude-cli calls.+ selfCaptureSessionIds: claudeCliSelfSessionIds(),});if (transcripts.length === 0) {@@ -666,6 +680,7 @@ async function runPhaseSynthesizeInner(}}+ const breaker = await loadDreamBreaker(engine);// Admission-quota latch: once a submit is rejected, every later transcript// this run would be rejected too — record one skip per remaining file// without hammering the queue.@@ -740,6 +755,9 @@ async function runPhaseSynthesizeInner(continue;}+ const refusal = breaker && dreamBreakerRefusal(breaker,+ `dream:synth-v2:${encodeURIComponent(synthesisIdentity)}:filename:${encodeURIComponent(basename(t.filePath))}:${hash16}`);+ if (refusal) { process.stderr.write(`[dream] ${t.basename}: ${refusal}\n`); skipReports.push({ filePath: t.filePath, reason: refusal }); continue; }const chunks = splitTranscriptByBudget(t.content, t.contentHash, maxCharsPerChunk);// D5 cap hit: log + skip; do NOT write to dream_verdicts. Closes the@@ -1682,14 +1700,15 @@ export async function loadSynthConfig(engine: BrainEngine): Promise<SynthConfig>* Count dream synth-v2 subagent submissions for a source in the last 24h —* the opt-in daily-cap denominator. Filters on `data->>'source_id'` (NOT a* LIKE on the key's encoded source segment — avoids LIKE-metachar issues);- * cancelled rows are excluded so retriage-cancelled jobs don't eat budget.+ * cancelled rows are excluded so retriage-cancelled jobs don't eat budget;+ * dead rows count through the key the queue recorded when it released them.*/async function countRecentSynthSubmissions(engine: BrainEngine, sourceId: string): Promise<number> {const rows = await engine.executeRaw<{ n: number }>(`SELECT COUNT(*)::int AS nFROM minion_jobsWHERE name = 'subagent'- AND idempotency_key LIKE 'dream:synth-v2:%'+ AND (idempotency_key LIKE 'dream:synth-v2:%' OR idempotency_key IS NULL AND data->>'__released_idempotency_key' LIKE 'dream:synth-v2:%')AND COALESCE(NULLIF(data->>'source_id', ''), 'default') = $1AND status <> 'cancelled'AND created_at > NOW() - INTERVAL '24 hours'`,diff --git a/src/core/cycle/transcript-discovery.ts b/src/core/cycle/transcript-discovery.tsindex f78d4ebacd..9643f6715a 100644--- a/src/core/cycle/transcript-discovery.ts+++ b/src/core/cycle/transcript-discovery.ts@@ -10,9 +10,11 @@*/import { readFileSync, readdirSync, statSync } from 'node:fs';-import { join, basename } from 'node:path';+import { join, basename, sep } from 'node:path';import { createHash } from 'node:crypto';import { pruneDir } from '../sync.ts';+import { realpathOrResolve, resolvedPrefixContained } from '../path-confine.ts';+import { corpusFileSessionId } from '../context/corpus-segments.ts';export interface DiscoveredTranscript {/** Absolute path to the transcript file. */@@ -48,6 +50,20 @@ export interface DiscoverOpts {* that would let any caller silently re-trigger the loop bug.*/bypassGuard?: boolean;+ /**+ * #5471: absolute directories the dream phases write their outputs into+ * (reflections, originals, patterns, cycle summaries under the brain+ * checkout). A file whose resolved path sits inside one is skipped whatever+ * its frontmatter says, so an output left unmarked by a failed postprocess+ * is never re-synthesized. Matched on resolved paths, never on content.+ */+ excludeDirs?: string[];+ /**+ * #5413: session ids of gbrain's own claude-cli subprocess sessions+ * (`claudeCliSelfSessionIds`). A `.txt` corpus file of one of these+ * sessions (`corpusFileSessionId`) is a self-capture and is skipped.+ */+ selfCaptureSessionIds?: ReadonlySet<string>;}const DATE_RE = /^(\d{4}-\d{2}-\d{2})/;@@ -257,6 +273,8 @@ function listTextFiles(dir: string): string[] {* - aren't `.txt`* - have date-prefixed basenames outside the requested window* - have content shorter than `minChars`+ * - are gbrain claude-cli self-captures (`selfCaptureSessionIds`) or sit under a+ * dream output directory (`excludeDirs`); each class is counted in one stderr line* - carry the `dream_generated: true` self-consumption marker (unless `bypassGuard`)* - match any compiled exclude pattern (case-insensitive word-boundary by default);* these are summarised in ONE stderr line at the end (count + pattern labels,@@ -272,6 +290,9 @@ export function discoverTranscripts(opts: DiscoverOpts): DiscoveredTranscript[]const dirs = [opts.corpusDir, opts.meetingTranscriptsDir].filter((d): d is string => typeof d === 'string' && d.length > 0,);+ const outputDirs = (opts.excludeDirs ?? []).map(realpathOrResolve);+ let outputSkips = 0;+ let selfCaptureSkips = 0;const results: DiscoveredTranscript[] = [];for (const dir of dirs) {@@ -281,6 +302,17 @@ export function discoverTranscripts(opts: DiscoverOpts): DiscoveredTranscript[]const dateMatch = DATE_RE.exec(baseName);const inferredDate = dateMatch ? dateMatch[1] : null;if (!isInDateRange(inferredDate, opts)) continue;+ if (ext === '.txt' && opts.selfCaptureSessionIds?.has(corpusFileSessionId(basename(filePath)))) {+ selfCaptureSkips += 1;+ continue;+ }+ if (outputDirs.length > 0) {+ const resolved = realpathOrResolve(filePath);+ if (outputDirs.some(d => resolvedPrefixContained(resolved, d, sep))) {+ outputSkips += 1;+ continue;+ }+ }let content: string;try {@@ -310,6 +342,12 @@ export function discoverTranscripts(opts: DiscoverOpts): DiscoveredTranscript[]}tally.report();+ if (selfCaptureSkips > 0) {+ process.stderr.write(`[dream] skipped ${selfCaptureSkips} corpus file(s) captured from gbrain's own claude-cli sessions\n`);+ }+ if (outputSkips > 0) {+ process.stderr.write(`[dream] skipped ${outputSkips} file(s) under dream output directories (self-consumption guard)\n`);+ }return results.sort((a, b) => a.filePath.localeCompare(b.filePath));}diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex 6338851492..01980c7ef3 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -57,6 +57,7 @@ export type CheckCategory = 'brain' | 'skill' | 'ops' | 'meta';export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set(['abandoned_threads','atom_provenance_drift',+ 'derived_visibility','brain_score','calibration_freshness','child_table_orphans',@@ -111,6 +112,7 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set(['ocr_health','orphan_ratio','oversized_pages',+ 'parked_effects','pglite_scratch_probe','quarantined_pages','raw_provenance',@@ -127,6 +129,7 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set(['takes_weight_grid','text_projection_readiness','timeline_coverage',+ 'timeline_history','undeclared_db_only_pages','unified_multimodal_coverage','unverified_extractions',@@ -177,6 +180,7 @@ export const OPS_CHECK_NAMES: ReadonlySet<string> = new Set(['canonical_content_writes','brainstorm_health','connectors',+ 'dream_paid_loop','chat_fallback_chain_inert','connection','db_only_collector_collision',@@ -188,6 +192,7 @@ export const OPS_CHECK_NAMES: ReadonlySet<string> = new Set(['oauth_client_scope_health','oauth_confidential_client_health','orphan_clones',+ 'persistence_capacity','pgbouncer_prepare','pglite_data_dir',// db-availability loop: engine-fit + repair-recurrence signals.diff --git a/src/core/embedding-input-hash.ts b/src/core/embedding-input-hash.tsnew file mode 100644index 0000000000..6b8e5ed54e--- /dev/null+++ b/src/core/embedding-input-hash.ts@@ -0,0 +1,66 @@+/**+ * Per-chunk embedding-input provenance (#5553).+ *+ * `content_chunks.embedding_input_hash` is written in the same statement as the+ * vector. It digests the vector column, model and dimensions, the wrapping tier+ * the vector was built under, and the exact embedding input: the chunk text for+ * `none` and fenced code, the title prefix plus the chunk text for `title`, and+ * (because a generated synopsis cannot be recomputed) the page's synopsis+ * corpus generation, the full title the synopsis prompt read, the document-body hash and the chunk text for+ * `per_chunk_synopsis`. A projection rebuild keeps a vector only when the stored+ * hash equals one recomputed from the current page, so an unchanged input keeps+ * its vector and any change to it (title, body in synopsis mode, model, column,+ * dimensions, wrapper bytes) nulls it. `embedded_text_hash` keeps its meaning.+ */+import { digest, sha256 } from './persistence/digest.ts';+import { buildContextualPrefix, wrapChunkForEmbedding } from './embedding-context.ts';++export type EmbeddingTier = 'none' | 'title' | 'per_chunk_synopsis';++export interface EmbeddingInputContext {+ column: string;+ model: string | null;+ dimensions: number;+ title: string;+ /** The page's stored corpus generation; only the synopsis tier digests it. */+ corpusGeneration: string | null;+ /** `synopsisBodyHash` of the page's installed chunk set. */+ bodyHash: string;+}++type HashedChunk = { chunk_text: string; chunk_source?: string | null };++/** The document a synopsis is generated from: every non-image chunk, in order. */+export function synopsisBodyHash(chunks: ReadonlyArray<HashedChunk>): string {+ return sha256(chunks.filter(c => c.chunk_source !== 'image_asset').map(c => c.chunk_text).join('\n\n'));+}++/** The tier a plain re-embed uses for a stored mode (mirrors wrapChunkTextsForStoredMode). */+export function plainEmbeddingTier(mode: string | null | undefined): EmbeddingTier {+ return mode == null || mode === 'none' ? 'none' : 'title';+}++/** Chunks without provenance are only trusted where the input is the raw chunk text. */+export function isContextualMode(mode: string | null | undefined): boolean {+ return plainEmbeddingTier(mode) !== 'none';+}++export function embeddingInputHash(ctx: EmbeddingInputContext, tier: EmbeddingTier, chunk: HashedChunk): string {+ const raw = tier === 'none' || chunk.chunk_source === 'fenced_code';+ const input = raw ? chunk.chunk_text+ : tier === 'title' ? wrapChunkForEmbedding(chunk.chunk_text, buildContextualPrefix(ctx.title, null), chunk.chunk_source)+ : digest([ctx.title, ctx.bodyHash, chunk.chunk_text]);+ return digest(['embedding-input-v1', ctx.column, ctx.model, ctx.dimensions, tier,+ tier === 'per_chunk_synopsis' ? ctx.corpusGeneration : null, sha256(input)]);+}++/**+ * Hashes a vector on a page in `mode` may carry and still be current. A+ * synopsis page also accepts title-tier vectors: plain re-embeds wrap a+ * synopsis page's chunks with the title prefix, and those inputs do not+ * depend on the rest of the body.+ */+export function acceptedEmbeddingInputHashes(ctx: EmbeddingInputContext, mode: string | null | undefined, chunk: HashedChunk): string[] {+ const plain = embeddingInputHash(ctx, plainEmbeddingTier(mode), chunk);+ return mode === 'per_chunk_synopsis' ? [embeddingInputHash(ctx, 'per_chunk_synopsis', chunk), plain] : [plain];+}diff --git a/src/core/extract-timeline-from-meetings.ts b/src/core/extract-timeline-from-meetings.tsindex 9f671374d2..425390c86e 100644--- a/src/core/extract-timeline-from-meetings.ts+++ b/src/core/extract-timeline-from-meetings.ts@@ -168,7 +168,7 @@ export async function extractTimelineFromMeetings(// timelines: the row carries no event_page_id (the (event_page_id, date)// unique index allows one row per event, not one per attendee), so the// remote private-event filter could never hide it. Fail closed: skip.- if (isPrivatePage(frontmatter)) { privateSkipped++; continue; }+ if (isPrivatePage({ frontmatter })) { privateSkipped++; continue; }// put_page-written pages never get effective_date computed (column stays// NULL); derive it exactly as `gbrain backfill effective_date` would —// same filename recipe (import_filename, else the slug tail) — so a laterdiff --git a/src/core/import-file.ts b/src/core/import-file.tsindex 8bcaec3288..0cffb138cb 100644--- a/src/core/import-file.ts+++ b/src/core/import-file.ts@@ -13,7 +13,8 @@ import { prepareMarkdownChunks } from './markdown-chunks.ts';import { prepareCodeChunks, installCodeChunkEdges } from './code-chunks.ts';import { detectCodeLanguage, CHUNKER_VERSION } from './chunkers/code.ts';import { sanitizeRemoteBody } from './remote-body.ts';-import { installPageEmbeddings, installPageProjection, preparePageProjection, readProjectionSnapshot, sealPageTextProjection, type ProjectionSnapshot } from './page-state/projections.ts';+import { installPageEmbeddings, installPageProjection, preparePageProjection, projectionBelowSafeFence, queuePageProjection, readProjectionSnapshot, resealSafeChunks,+ sealPageTextProjection, stampEmbeddingInputs, type ProjectionSnapshot } from './page-state/projections.ts';import { sanitizeText } from './batch-rows.ts';import { hasProtectedBody, safeChunksFilter } from './search/safe-chunks.ts';import { findChunkForOffset } from './chunkers/edge-extractor.ts';@@ -46,7 +47,6 @@ import {buildContextualPrefix,modeRequiresSynopsis,modeRequiresWrapper,- sanitizeTitle,wrapChunkForEmbedding,} from './embedding-context.ts';import { loadSearchModeConfig, resolveSearchMode } from './search/mode.ts';@@ -139,6 +139,8 @@ export interface ImportResult {flagged?: boolean;/** Which flag tier fired, when `flagged`. */flag_reason?: 'markup_heavy' | 'oversized';+ /** #5050: unchanged content below the safe-chunk fence was re-sealed; chunks left to embed. */+ resealed?: { pendingChunks: number; pendingChars: number };/*** Machine-readable skip class for status='skipped' rows that must NOT be* treated as failures. 'malformed_path' = the FILENAME contains bracket or@@ -686,13 +688,18 @@ export async function importFromContent(// Rebuild stale projections without granting --force-rechunk's external-ID dedup override.const needsProjectionRebuild = !opts.prepare && existing && existing.text_projection_revision !== existing.knowledge_revision;if (existing?.content_hash === hash && !existing.deleted_at && !opts.forceRechunk && !needsProjectionRebuild && (!opts.prepare || sameCanonicalImport(existingSnapshot, parsedPage))) {+ // #5050: unchanged content chunked before the safe-chunk fence is re-sealed+ // projection-only; the canonical write stays a no-op.+ const reseal = await projectionBelowSafeFence(engine, existing.id);if (opts.prepare) {const result: ImportResult = { slug, status: 'skipped', chunks: 0, parsedPage, ...(typeWarning ? { type_warning: typeWarning } : {}) };return opts.prepare({ slug, parsedPage, observedRevision: (existing as typeof existing & { knowledge_revision?: string }).knowledge_revision ?? null,- noop: true, result, validate: async () => {}, apply: async () => {} });+ noop: true, result, validate: async () => {},+ apply: async tx => { if (reseal) await queuePageProjection(tx, sourceId ?? 'default', slug, 'safe_chunk_reseal'); } });}await persistUnchanged();- return { slug, status: 'skipped', chunks: 0, parsedPage, ...(typeWarning ? { type_warning: typeWarning } : {}) };+ const resealed = reseal ? await resealSafeChunks(engine, slug, sourceId ?? 'default') : null;+ return { slug, status: 'skipped', chunks: 0, parsedPage, ...(typeWarning ? { type_warning: typeWarning } : {}), ...(resealed ? { resealed } : {}) };}// #3694 one-time reconcile: a row written by the PRE-fix putPage formula@@ -710,7 +717,8 @@ export async function importFromContent(});if (existing.content_hash === legacyHash) {await persistUnchanged(true);- return { slug, status: 'skipped', chunks: 0, parsedPage, ...(typeWarning ? { type_warning: typeWarning } : {}) };+ const resealed = await projectionBelowSafeFence(engine, existing.id) ? await resealSafeChunks(engine, slug, sourceId ?? 'default') : null;+ return { slug, status: 'skipped', chunks: 0, parsedPage, ...(typeWarning ? { type_warning: typeWarning } : {}), ...(resealed ? { resealed } : {}) };}}@@ -825,10 +833,9 @@ export async function importFromContent(const embedChunks = async () => {if (opts.noEmbed || chunks.length === 0) return;- const safeTitle = sanitizeTitle(parsed.title);const prefix =modeRequiresWrapper(effectiveCRMode) && !modeRequiresSynopsis(effectiveCRMode)- ? buildContextualPrefix(safeTitle, null)+ ? buildContextualPrefix(parsed.title, null): null;const wrappedTexts = prefix? chunks.map((c) => wrapChunkForEmbedding(c.chunk_text, prefix, c.chunk_source))@@ -970,7 +977,9 @@ export async function importFromContent(// included a private sibling fragment. Replace every derived row atomically.await tx.deleteChunks(slug, txOpts);if (chunks.length > 0) {- await tx.upsertChunks(slug, chunks, txOpts);+ const embeddingColumn = await stampEmbeddingInputs(tx, chunks, null,+ { title: parsed.title, tier: effectiveCRMode === 'title' ? 'title' : 'none', corpusGeneration });+ await tx.upsertChunks(slug, chunks, embeddingColumn ? { ...txOpts, embeddingColumn } : txOpts);// v0.41.31: stamp embedding provenance when this import actually// embedded (not --no-embed), so a later model/dims swap is detectable// as stale via embed --stale. The deferred/backfill + per-slug embed@@ -1425,12 +1434,17 @@ export async function importCodeFile(const parsedPage: ParsedPage = { type: 'code', title, compiled_truth: storageContent, timeline: '',frontmatter: { ...existing?.frontmatter, language: lang, file: relativePath }, tags: ['code', lang] };if (!opts.force && existing?.content_hash === hash && !existing.deleted_at && existing.text_projection_revision === existing.knowledge_revision) {+ // #5247: an unchanged code page chunked before the safe-chunk fence is+ // re-sealed projection-only, as markdown is.+ const reseal = await projectionBelowSafeFence(engine, existing.id);if (opts.prepare) {const result: ImportResult = { slug, status: 'skipped', chunks: 0 };- return opts.prepare({ slug, parsedPage, observedRevision: existing.knowledge_revision ?? null, noop: true, result, validate: async () => {}, apply: async () => {} });+ return opts.prepare({ slug, parsedPage, observedRevision: existing.knowledge_revision ?? null, noop: true, result, validate: async () => {},+ apply: async tx => { if (reseal) await queuePageProjection(tx, sourceId ?? 'default', slug, 'safe_chunk_reseal'); } });}await engine.transaction(tx => assertImportBase(tx, slug, sourceId ?? 'default', existing));- return { slug, status: 'skipped', chunks: 0 };+ const resealed = reseal ? await resealSafeChunks(engine, slug, sourceId ?? 'default') : null;+ return { slug, status: 'skipped', chunks: 0, ...(resealed ? { resealed } : {}) };}if (existing?.content_hash === hash && !existing.deleted_at && opts.noEmbed) {const snapshot = await readProjectionSnapshot(engine, slug, txOpts.sourceId, { allowUnsealed: true });@@ -1526,7 +1540,9 @@ export async function importCodeFile(await tx.deleteChunks(slug, txOpts);if (chunks.length > 0) {- await tx.upsertChunks(slug, chunks, txOpts);+ const embeddingColumn = await stampEmbeddingInputs(tx, chunks, new Set(needsEmbedIndexes),+ { title, tier: 'none', corpusGeneration: null });+ await tx.upsertChunks(slug, chunks, embeddingColumn ? { ...txOpts, embeddingColumn } : txOpts);// v0.41.31: stamp embedding provenance ONLY when every chunk was// freshly embedded with the current model this call (no reuse-by-hash// carrying old-model vectors). Mixed pages stay unstamped rather thandiff --git a/src/core/link-extraction.ts b/src/core/link-extraction.tsindex ff8a1ea90c..a18846b312 100644--- a/src/core/link-extraction.ts+++ b/src/core/link-extraction.ts@@ -17,6 +17,7 @@ import { ensureWellFormed } from './text-safe.ts';import { stripCodeBlocks } from './markdown-code.ts';import { isValidSourceId } from './source-id.ts';import { parseInlineCitationTimelineEntries } from './timeline-citations.ts';+import { isMaterializedMarkerLine } from './timeline-marker.ts';import { slugifyPath, slugifySegment } from './sync.ts';import { SLUG_WORD_CHARS, SLUG_VARIATION_SELECTORS_RE } from './cjk.ts';import { foldNonDecomposingLatin } from './latin-fold.ts';@@ -1912,7 +1913,7 @@ export function parseTimelineEntries(content: string): TimelineCandidate[] {while (j < lines.length) {const next = lines[j];if (TIMELINE_LINE_RE.test(next)) break;- if (/^#{1,6}\s/.test(next)) break;+ if (/^#{1,6}\s/.test(next) || isMaterializedMarkerLine(next)) break; // #5567: a marker opens the next bulletif (next.trim().length === 0 && detailLines.length === 0) {// skip leading blank line; if we hit a blank after detail content// and still no new entry, treat detail as ended.diff --git a/src/core/markdown.ts b/src/core/markdown.tsindex 712b30380c..a1b6d66645 100644--- a/src/core/markdown.ts+++ b/src/core/markdown.ts@@ -1,7 +1,7 @@import { dataFrontmatter as matter, FrontmatterLanguageError } from './data-frontmatter.ts';import { safeLoad as yamlSafeLoad } from 'js-yaml';import type { Page, PageType } from './types.ts';-import { slugifyPath } from './sync.ts';+import { resolveSlugForPath, slugifyPath } from './sync.ts';export type ParseValidationCode =| 'MISSING_OPEN'@@ -914,7 +914,7 @@ function inferTitle(filePath?: string): string {// Extract filename without extension, convert dashes/underscores to spacesconst parts = filePath.split('/');const filename = parts[parts.length - 1]?.replace(/\.md$/i, '') || 'Untitled';- return filename.replace(/[-_]/g, ' ').replace(/\b\w/g, c => c.toUpperCase());+ return filename.replace(/[-_]/g, ' ').trim().replace(/\b\w/g, c => c.toUpperCase()) || 'Untitled';}function inferSlug(filePath?: string): string {@@ -1018,7 +1018,10 @@ export function resolvePageFilePath(* `sources.local_path` points at a subdirectory. A direct join duplicates the* scope (`.../public/changelog/public/changelog/...`). Find the same Git root* sync uses without spawning a subprocess, then remove that exact scope.- * Non-Git vaults and Git-root local paths keep the direct path. Historical+ * Non-Git vaults and Git-root local paths keep the direct path. Under+ * `slugRootMode: 'source-root'` the stored path is already source-relative, so+ * the scope is removed only from the legacy Git-root form write-through minted+ * from the slug (its scope-stripped path names `pageSlug`, #5610). Historical* rows may carry a basename-relative `source_path`; when the direct path is* absent and the caller provides the page slug, resolve that spelling under* the slug's directory before reporting the file as missing.@@ -1051,6 +1054,7 @@ export function resolveSourceLocalFilePath(localPath: string,rawSourcePath: string | null | undefined,pageSlug?: string | null,+ slugRootMode?: 'git-root' | 'source-root',): string | null {if (!rawSourcePath) return null;const value = rawSourcePath.trim();@@ -1067,7 +1071,9 @@ export function resolveSourceLocalFilePath(if (existsSync(join(cursor, '.git'))) {const scope = splitLocalPathSegments(relative(cursor, absoluteLocalPath));sourceScopeSegments = scope;- if (scope.length > 0 && scope.every((segment, index) => segment === sourceSegments[index])) {+ const scoped = scope.length > 0 && scope.every((segment, index) => segment === sourceSegments[index]);+ if (scoped && (slugRootMode !== 'source-root'+ || !!pageSlug && resolveSlugForPath(sourceSegments.slice(scope.length).join('/')) === pageSlug)) {resolvedSegments = sourceSegments.slice(scope.length);}break;@@ -1082,7 +1088,7 @@ export function resolveSourceLocalFilePath(const slugDirSegments = safeSlugDirSegments(pageSlug);if (sourceSegments.length === 1 && slugDirSegments && slugDirSegments.length > 0) {const scopedSlugDir =- sourceScopeSegments.length > 0 &&+ slugRootMode !== 'source-root' && sourceScopeSegments.length > 0 &&sourceScopeSegments.every((segment, index) => segment === slugDirSegments[index])? slugDirSegments.slice(sourceScopeSegments.length): slugDirSegments;@@ -1092,3 +1098,12 @@ export function resolveSourceLocalFilePath(return directPath;}++/**+ * A `file://` URI whose authority is neither empty, `localhost` nor a Windows+ * drive (`file://C:/...`): the relative path an older file capture stored+ * as typed (#5622), or a host-only alias. It names no local file, so readers treat it as absent.+ */+export function isRelativeFileUri(sourceUri: string | null | undefined): boolean {+ return typeof sourceUri === 'string' && /^file:\/\/(?!\/|localhost\/|[A-Za-z]:[\\/])/i.test(sourceUri);+}diff --git a/src/core/migrate.ts b/src/core/migrate.tsindex c72dc19046..2f0086d6f3 100644--- a/src/core/migrate.ts+++ b/src/core/migrate.ts@@ -2,7 +2,7 @@ import { SOURCE_INGESTION_RECEIPTS_SCHEMA_SQL } from './company-brain/receipt-scimport { MANAGED_WRITER_GUARD_SQL } from './persistence/writer-guard-schema.ts';import { PERSISTENCE_TOPOLOGY_SCHEMA_SQL } from './persistence/topology-schema.ts';import { PERSISTENCE_SCHEMA_STATEMENTS, PERSISTENCE_REQUEST_RECOVERY_INDEX_SQL, PERSISTENCE_DATABASE_PENDING_INDEX_SQL } from './persistence/schema.ts';-import { PERSISTENCE_EFFECT_SCHEMA_SQL } from './persistence/effect-schema.ts';+import { PERSISTENCE_EFFECT_PARKED_INDEX_SQL, PERSISTENCE_EFFECT_SCHEMA_SQL } from './persistence/effect-schema.ts';import { PAGE_PROJECTION_SCHEMA_SQL, PAGE_PROJECTION_ACTIVATION_SQL } from './page-state/projection-schema.ts';import { LEASE_TOKEN_SCHEMA_SQL } from './lease-schema.ts';import { PAGE_STATE_SCHEMA_SQL, PAGE_VERSION_DELETION_SCHEMA_SQL } from './page-state/schema.ts';@@ -6708,6 +6708,56 @@ CREATE TRIGGER minion_queue_protocol BEFORE INSERT OR UPDATE ON minion_jobsidempotent: true,sql: FACT_WITHDRAWAL_SUBJECT_SQL,},+ {+ version: 170, name: 'index_parked_persistence_effects', idempotent: true, transaction: false, sql: '',+ handler: async engine => {+ if (engine.kind === 'postgres') await dropInvalidConcurrentIndex(engine, 170, 'persistence_effects_parked');+ await engine.runMigration(170, engine.kind === 'postgres'+ ? PERSISTENCE_EFFECT_PARKED_INDEX_SQL.replace('CREATE INDEX', 'CREATE INDEX CONCURRENTLY')+ : PERSISTENCE_EFFECT_PARKED_INDEX_SQL);+ },+ },+ {+ version: 171,+ name: 'content_chunks_embedding_input_hash',+ // #5553: per-chunk embedding-input provenance, written in the same+ // statement as the vector (src/core/embedding-input-hash.ts). A projection+ // rebuild keeps a vector only when the stored hash equals the recomputed+ // one. Same shape as v133 and v166's fact provenance: nullable, no+ // backfill (a hash cannot be proven for an existing vector), no index+ // (read only per page during a rebuild; bootstrap-coverage: column-only).+ // NULL on a contextual page is nulled once and stamped by its re-embed.+ // Keep in sync with src/schema.sql (regenerate schema-embedded.ts via+ // build:schema) and src/core/pglite-schema.ts.+ idempotent: true,+ sql: `+ ALTER TABLE content_chunks ADD COLUMN IF NOT EXISTS embedding_input_hash TEXT;+ `,+ },+ {+ version: 172, name: 'pages_safe_chunk_pending_index', idempotent: true, transaction: false, sql: '',+ // #5050/#5247: the safe_index_pending probe (ops/search.ts) runs on every+ // remote search and now counts pages of every kind below the safe-chunk+ // fence, so the markdown-only partial pages_chunker_version_idx no longer+ // serves it. This partial index holds only unsealed pages (empty on a+ // sealed brain). The literal 4 is SAFE_FENCE_CHUNKER_VERSION when this+ // migration shipped; a later fence bump needs its own index.+ handler: async engine => {+ if (engine.kind === 'postgres') await dropInvalidConcurrentIndex(engine, 172, 'pages_safe_chunk_pending_idx');+ await engine.runMigration(172, `CREATE INDEX ${engine.kind === 'postgres' ? 'CONCURRENTLY ' : ''}IF NOT EXISTS pages_safe_chunk_pending_idx+ ON pages (source_id) WHERE chunker_version < 4`);+ },+ },+ {+ // Paid-loop breaker (dream-breaker.ts) and its doctor check count dead+ // subagent submissions by finish time over the last 24 h.+ version: 173, name: 'minion_jobs_dead_subagent_finished_index', idempotent: true, transaction: false, sql: '',+ handler: async engine => {+ if (engine.kind === 'postgres') await dropInvalidConcurrentIndex(engine, 173, 'idx_minion_jobs_dead_subagent_finished');+ await engine.runMigration(173, `CREATE INDEX ${engine.kind === 'postgres' ? 'CONCURRENTLY ' : ''}IF NOT EXISTS idx_minion_jobs_dead_subagent_finished+ ON minion_jobs (finished_at) WHERE name = 'subagent' AND status = 'dead'`);+ },+ },];export const LATEST_VERSION = MIGRATIONS.length > 0diff --git a/src/core/minions/handlers/subagent-oneshot.ts b/src/core/minions/handlers/subagent-oneshot.tsindex 1cf470d3cf..645a759845 100644--- a/src/core/minions/handlers/subagent-oneshot.ts+++ b/src/core/minions/handlers/subagent-oneshot.ts@@ -83,6 +83,19 @@ const ONESHOT_CALL_BUDGET_MS = 300_000;* per-write id template, and subagent.ts's accounting scope prefix.*/export const ONESHOT_TOOL_USE_ID_PREFIX = 'oneshot-';+/** #5590: ledger id suffix of a banked oneshot skip (`oneshot-<inv8>-skip`); write rows end `-p<i>`. */+const ONESHOT_SKIP_SUFFIX = '-skip';++function oneshotSkipText(reason: string | null): string {+ return `oneshot: nothing met the bar — ${reason ?? 'no reason given'}`;+}++function oneshotSkipResult(reason: string | null, tokens: SubagentResult['tokens']): SubagentResult {+ return {+ result: oneshotSkipText(reason), turns_count: 1, stop_reason: 'end_turn', tokens,+ synth_mode_used: 'oneshot', oneshot_skipped: true, written_refs: [],+ };+}/*** Static system contract — deliberately free of per-job content so the@@ -224,11 +237,12 @@ function isAbortShaped(e: unknown): boolean {return isAbortError(e) || (e instanceof Error && /\babort|\btimed?[ _-]?out/i.test(e.message));}-interface LedgerRow { tool_use_id: string; ordinal: number | null; status: string; slug: string | null; content: string | null; request_id: string | null }+interface LedgerRow { tool_use_id: string; ordinal: number | null; status: string; slug: string | null; content: string | null; request_id: string | null; skip_reason: string | null }async function loadOneshotLedger(engine: BrainEngine, jobId: number): Promise<LedgerRow[]> {return engine.executeRaw<LedgerRow>(- `SELECT tool_use_id, ordinal, status, input->>'slug' AS slug, input->>'content' AS content, input->>'request_id' AS request_id+ `SELECT tool_use_id, ordinal, status, input->>'slug' AS slug, input->>'content' AS content, input->>'request_id' AS request_id,+ input->>'skip_reason' AS skip_reasonFROM subagent_tool_executionsWHERE job_id = $1 AND tool_use_id LIKE $2ORDER BY id`,@@ -254,6 +268,10 @@ export async function runSubagentOneshot(args: OneshotArgs): Promise<OneshotOutc// re-call the model (nondeterministic output would double-write different// pages); the completed rows ARE the writes.const priorLedger = await loadOneshotLedger(engine, ctx.id);+ const bankedSkip = priorLedger.find(r => r.tool_use_id.endsWith(ONESHOT_SKIP_SUFFIX) && r.status === 'complete');+ if (bankedSkip) {+ return { kind: 'done', result: oneshotSkipResult(bankedSkip.skip_reason, { in: 0, out: 0, cache_read: 0, cache_create: 0 }) };+ }if (priorLedger.length > 0) {// Settle any PENDING rows first (crash between the pending bank and// the settle write). The ledger stores the exact input and request UUID;@@ -424,20 +442,20 @@ export async function runSubagentOneshot(args: OneshotArgs): Promise<OneshotOutc}if (parsed.pages.length === 0) {if (!parsed.skipped) return fb('empty_no_skip');- // Task-D skip: a legitimate zero-write completion.- const skipText = `oneshot: nothing met the bar — ${parsed.skip_reason ?? 'no reason given'}`;- await persistOneshotTranscript(engine, ctx.id, data.prompt, chatResult.text ?? skipText, model, tokens);- return {- kind: 'done',- result: {- result: skipText,- turns_count: 1,- stop_reason: 'end_turn',- tokens,- synth_mode_used: 'oneshot',- written_refs: [],- },- };+ // Task-D skip: a legitimate zero-write completion. #5590: the skip is+ // banked as a oneshot ledger row BEFORE the transcript, so a retry of this+ // job (accounting failure, crash, lost outcome write) takes ledger-first+ // recovery and completes as the same skip instead of replaying a+ // marker-less transcript that require_writes would dead-letter.+ await engine.executeRaw(+ `INSERT INTO subagent_tool_executions (job_id, message_idx, tool_use_id, tool_name, input, status, ordinal)+ VALUES ($1, 1, $2, 'oneshot_skip', $3::text::jsonb, 'complete', 0)+ ON CONFLICT (job_id, message_idx, ordinal) DO NOTHING`,+ [ctx.id, `${ONESHOT_TOOL_USE_ID_PREFIX}${randomUUID().replace(/-/g, '').slice(0, 8)}${ONESHOT_SKIP_SUFFIX}`,+ JSON.stringify({ skip_reason: parsed.skip_reason })],+ );+ await persistOneshotTranscript(engine, ctx.id, data.prompt, chatResult.text ?? oneshotSkipText(parsed.skip_reason), model, tokens);+ return { kind: 'done', result: oneshotSkipResult(parsed.skip_reason, tokens) };}if (parsed.pages.length > MAX_PAGES_PER_RESPONSE) return fb('too_many_pages');diff --git a/src/core/minions/handlers/subagent-persistence.ts b/src/core/minions/handlers/subagent-persistence.tsindex ad795241e8..19d6ce47d7 100644--- a/src/core/minions/handlers/subagent-persistence.ts+++ b/src/core/minions/handlers/subagent-persistence.ts@@ -235,7 +235,10 @@ export async function persistToolExecComplete(* throws UnrecoverableError: retrying is provably futile (the* replay path short-circuits to the persisted terminal turn and can never* re-run the failed tools), so the job routes straight to dead and the- * idempotency key releases for the next cycle.+ * idempotency key releases for the next cycle. The one exception is a+ * legitimate zero-write answer (`isLegitimateZeroWrite`): dead-lettering it+ * released the key and withheld the cooldown, so every cycle re-paid for the+ * same input (#5590, #5540).** `scopeToolUseIdPrefix` narrows the ledger scan (the oneshot runner scopes to* its own invocation's rows so a prior invocation's outcome can't distort the@@ -245,7 +248,7 @@ export async function finalizeWriteAccounting(engine: BrainEngine,jobId: number,result: SubagentResult,- opts: { requireWrites: boolean; scopeToolUseIdPrefix?: string },+ opts: { requireWrites: boolean; allowCleanZeroWrites?: boolean; scopeToolUseIdPrefix?: string },): Promise<SubagentResult> {let rows: Array<{ status: string; error: string | null; output: unknown }>;try {@@ -291,7 +294,7 @@ export async function finalizeWriteAccounting(`all ${failed} put_page write(s) failed — job produced zero pages (first error: ${firstError})`,);}- if (opts.requireWrites && attempted === 0) {+ if (opts.requireWrites && attempted === 0 && !(await isLegitimateZeroWrite(engine, jobId, result, opts))) {throw new UnrecoverableError(result.stop_reason === 'end_turn'? 'job produced zero required put_page writes — a clean model finish does not satisfy require_writes'@@ -301,6 +304,35 @@ export async function finalizeWriteAccounting(return accounted;}+/**+ * A zero-attempt, clean (`end_turn`) finish is a legitimate answer in exactly+ * two shapes: the oneshot model's explicit skip contract+ * (`{"pages":[],"skipped":true}`), or — when the submitter opted in with+ * `allow_clean_zero_writes` — a run whose ledger holds at least one completed+ * tool execution, proving the child examined evidence before naming nothing.+ * A prose-only finish, a dirty stop, or a run whose only tools failed stays a+ * real failure. The ledger read throws on error, failing the job closed.+ */+async function isLegitimateZeroWrite(+ engine: BrainEngine,+ jobId: number,+ result: SubagentResult,+ opts: { allowCleanZeroWrites?: boolean; scopeToolUseIdPrefix?: string },+): Promise<boolean> {+ if (result.stop_reason !== 'end_turn') return false;+ if (result.synth_mode_used === 'oneshot' && result.oneshot_skipped === true) return true;+ if (!opts.allowCleanZeroWrites) return false;+ const completed = await engine.executeRaw<{ id: number }>(+ opts.scopeToolUseIdPrefix+ ? `SELECT id FROM subagent_tool_executions+ WHERE job_id = $1 AND status = 'complete' AND tool_use_id LIKE $2 LIMIT 1`+ : `SELECT id FROM subagent_tool_executions+ WHERE job_id = $1 AND status = 'complete' LIMIT 1`,+ opts.scopeToolUseIdPrefix ? [jobId, `${opts.scopeToolUseIdPrefix}%`] : [jobId],+ );+ return completed.length > 0;+}+export async function persistToolExecFailed(engine: BrainEngine,jobId: number,diff --git a/src/core/minions/handlers/subagent.ts b/src/core/minions/handlers/subagent.tsindex 563f154fe4..47d528b2a1 100644--- a/src/core/minions/handlers/subagent.ts+++ b/src/core/minions/handlers/subagent.ts@@ -312,7 +312,7 @@ export function makeSubagentHandler(deps: SubagentDeps) {? { ...inner, synth_mode_used: 'agentic' }: inner;return finalizeWriteAccounting(engine, ctx.id, stamped, {- requireWrites: dataForAccounting.require_writes === true,+ requireWrites: dataForAccounting.require_writes === true, allowCleanZeroWrites: dataForAccounting.allow_clean_zero_writes === true,// OV-4: a successful oneshot job's verdict is scoped to its own// invocation family; a fallback wrote through the loop (no oneshot// rows exist — validation precedes all writes), so job-wide is exact.diff --git a/src/core/minions/queue.ts b/src/core/minions/queue.tsindex 096845d90e..89adbabfcb 100644--- a/src/core/minions/queue.ts+++ b/src/core/minions/queue.ts@@ -342,8 +342,8 @@ export class MinionQueue {//// Dead/cancelled jobs represent permanently-failed work whose// idempotency slot must be freed so a fresh attempt can be inserted.- // We NULL the key (preserving the row for audit) and fall through- // to the INSERT path below.+ // We NULL the key (preserving the row, with the released key in its+ // data for the dream breaker) and fall through to the INSERT below.if (opts?.idempotency_key) {const existing = await tx.executeRaw<Record<string, unknown>>(`SELECT * FROM minion_jobs WHERE idempotency_key = $1`,@@ -354,8 +354,8 @@ export class MinionQueue {assertSameAuthority(existingJob.submission_authority, authority);if (existingJob.status === 'dead' || existingJob.status === 'cancelled') {await tx.executeRaw(- `UPDATE minion_jobs SET idempotency_key = NULL WHERE id = $1`,- [existingJob.id]+ `UPDATE minion_jobs SET idempotency_key = NULL, data = data || $2::text::jsonb WHERE id = $1`,+ [existingJob.id, JSON.stringify({ __released_idempotency_key: opts.idempotency_key })]);} else {existingJob.coalesced = true;diff --git a/src/core/minions/types.ts b/src/core/minions/types.tsindex f83317ee9a..f04320e445 100644--- a/src/core/minions/types.ts+++ b/src/core/minions/types.ts@@ -568,6 +568,14 @@ export interface SubagentHandlerData {* Same trust story as `allowed_slug_prefixes` (PROTECTED_JOB_NAMES).*/require_writes?: boolean;+ /**+ * #5540 — only meaningful with `require_writes: true`. A clean finish+ * (`end_turn`) with zero attempted put_page calls completes instead of+ * dead-lettering when at least one tool execution completed. All attempted+ * writes failing, a dirty stop, or a prose-only finish still fail. Workers+ * that predate the field ignore it and keep the strict behavior.+ */+ allow_clean_zero_writes?: boolean;/*** #4216 — synthesis execution mode. 'oneshot' = single structured* completion + programmatic validated writes, falling back to the agentic@@ -751,4 +759,10 @@ export interface SubagentResult {written_refs?: Array<{ slug: string; status: 'complete' | 'failed' }>;/** #4216 — true when a retried oneshot job finalized from a prior invocation's ledger. */recovered?: boolean;+ /**+ * #5590 — true when the oneshot model answered with the explicit skip+ * contract (`{"pages":[],"skipped":true}`): a legitimate zero-write+ * completion that `require_writes` must not dead-letter.+ */+ oneshot_skipped?: boolean;}diff --git a/src/core/oauth-grants.ts b/src/core/oauth-grants.tsindex dfd29cd873..e8397a9cc5 100644--- a/src/core/oauth-grants.ts+++ b/src/core/oauth-grants.ts@@ -3,7 +3,7 @@ import { createHash } from 'node:crypto';import { redirectUriMatches } from '@modelcontextprotocol/sdk/server/auth/handlers/authorize.js';import type { AuthorizationParams } from '@modelcontextprotocol/sdk/server/auth/provider.js';import type { OAuthTokens } from '@modelcontextprotocol/sdk/shared/auth.js';-import { InvalidClientError, InvalidGrantError, InvalidRequestError, ServerError, TooManyRequestsError } from '@modelcontextprotocol/sdk/server/auth/errors.js';+import { InvalidClientError, InvalidGrantError, InvalidRequestError, InvalidTargetError, ServerError, TooManyRequestsError } from '@modelcontextprotocol/sdk/server/auth/errors.js';import type { SqlQuery } from './sql-query.ts';import { generateToken, hashToken } from './utils.ts';import { hasScope, parseScopeString } from './scope.ts';@@ -25,6 +25,33 @@ function grantScopes(row: ClientRow, requested?: string[]): string[] {return (requested?.length ? requested : allowed).filter(scope => hasScope(allowed, scope));}+/**+ * #5222 — the one RFC 8707 resource canonicalizer, shared by /authorize, code+ * exchange, refresh and bearer verification. `canonical` is the server's /mcp+ * resource, derived from the configured public URL and never from `Host` or+ * forwarded headers. The issuer origin is an alias of it (some clients send+ * the origin root even after reading the protected-resource metadata). URL+ * parsing normalizes scheme and host case and default ports; a trailing+ * slash is ignored. Anything else is `invalid_target`, naming the accepted+ * resource so the client fails loudly instead of looping on a token /mcp+ * will refuse.+ */+export function canonicalOAuthResource(requested: URL | string, canonical: URL): URL {+ const accepted = `use ${canonical.toString()} (or its origin ${canonical.origin})`;+ let url: URL;+ try {+ url = new URL(requested.toString());+ } catch {+ throw new InvalidTargetError(`Invalid resource; ${accepted}`);+ }+ const path = url.pathname.replace(/\/+$/, '');+ if (url.origin === canonical.origin && !url.username && !url.password && !url.search && !url.hash+ && (path === '' || path === canonical.pathname.replace(/\/+$/, ''))) {+ return new URL(canonical.toString());+ }+ throw new InvalidTargetError(`Resource ${url.toString()} is not served here; ${accepted}`);+}+/** Compare policy, not a mutable reference or only the display name. */function policyDigest(row: ClientRow): string {const fields = ['client_id', 'client_name', 'redirect_uris', 'grant_types', 'scope',@@ -81,8 +108,15 @@ export class OAuthGrants {tokenTtl: number;refreshTtl: number;now?: () => number;+ /** #5222: the canonical /mcp resource; unset keeps exact-match resource semantics. */+ resourceUrl?: URL;}) {}+ private canonicalResource(requested: URL | undefined): URL | undefined {+ if (!requested || !this.options.resourceUrl) return requested;+ return canonicalOAuthResource(requested, this.options.resourceUrl);+ }+private now(): number { return (this.options.now ?? Date.now)(); }private async locked<T>(clientId: string, fn: (sql: SqlQuery, row: ClientRow) => Promise<T>): Promise<T> {if (!this.options.transaction) throw new ServerError('OAuth grant transactions are unavailable');@@ -113,6 +147,7 @@ export class OAuthGrants {}async begin(clientId: string, params: AuthorizationParams): Promise<string> {+ const resource = this.canonicalResource(params.resource);this.assertCapacity(clientId);if (!/^[A-Za-z0-9_-]{43}$/.test(params.codeChallenge)) throw new InvalidRequestError('S256 PKCE challenge required');const [row] = await this.options.sql`SELECT * FROM oauth_clients WHERE client_id = ${clientId}`;@@ -136,10 +171,10 @@ export class OAuthGrants {delegatedTools: Array.isArray(row.bound_tools) ? [...row.bound_tools] as string[] : null,delegatedSlugPrefixes: Array.isArray(row.delegated_slug_prefixes) ? [...row.delegated_slug_prefixes] as string[] : null,delegatedNamespace: typeof row.delegated_namespace === 'string' ? row.delegated_namespace : null,- resource: params.resource?.toString() ?? null, expiresAt: this.now() + 10 * 60_000,+ resource: resource?.toString() ?? null, expiresAt: this.now() + 10 * 60_000,};this.pending.set(id, {- details, params: { ...params, scopes: [...details.scopes], resource: params.resource ? new URL(params.resource) : undefined },+ details, params: { ...params, scopes: [...details.scopes], resource },policy: policyDigest(row), status: 'pending',});return id;@@ -194,6 +229,7 @@ export class OAuthGrants {}async exchangeCode(clientId: string, code: string, verifier?: string, redirectUri?: string, resource?: URL, secretHash?: string): Promise<OAuthTokens> {+ const requested = this.canonicalResource(resource);return this.locked(clientId, async (sql, client) => {this.assertCredentialPolicy(client, secretHash);const [row] = await sql`SELECT * FROM oauth_codes WHERE code_hash = ${hashToken(code)} AND client_id = ${clientId} FOR UPDATE`;@@ -204,7 +240,7 @@ export class OAuthGrants {|| createHash('sha256').update(verifier).digest('base64url') !== row.code_challenge) {throw new InvalidGrantError('Invalid S256 PKCE verifier');}- const target = this.resource(row.resource, resource);+ const target = this.resource(row.resource, requested);const scopes = this.currentScopes(client, row.scopes as string[]);await sql`DELETE FROM oauth_codes WHERE code_hash = ${hashToken(code)} AND client_id = ${clientId}`;return this.issue(sql, client, scopes, target, true);@@ -212,6 +248,7 @@ export class OAuthGrants {}async refresh(clientId: string, token: string, requested?: string[], resource?: URL, secretHash?: string): Promise<OAuthTokens> {+ const requestedResource = this.canonicalResource(resource);return this.locked(clientId, async (sql, client) => {this.assertCredentialPolicy(client, secretHash);const [row] = await sql`SELECT * FROM oauth_tokens WHERE token_hash = ${hashToken(token)} AND token_type = 'refresh' AND client_id = ${clientId} FOR UPDATE`;@@ -221,7 +258,7 @@ export class OAuthGrants {if (requested?.some(scope => !hasScope(original, scope))) throw new InvalidGrantError('Requested scope exceeds refresh token grant');if (requested?.some(scope => !hasScope(parseScopeString(client.scope as string | undefined), scope))) throw new InvalidGrantError('Requested scope exceeds current client grant');const scopes = this.currentScopes(client, requested ?? original);- const target = this.resource(row.resource, resource);+ const target = this.resource(row.resource, requestedResource);await sql`DELETE FROM oauth_tokens WHERE token_hash = ${hashToken(token)} AND token_type = 'refresh' AND client_id = ${clientId}`;return this.issue(sql, client, scopes, target, true);});@@ -238,10 +275,17 @@ export class OAuthGrants {if (secretHash && expires > 0 && expires <= Math.floor(this.now() / 1000)) throw new InvalidClientError('Client credentials expired');}+ /** `requested` is already canonical; a stored origin-bound grant from before #5222 canonicalizes the same way. */private resource(stored: unknown, requested?: URL): URL | undefined {if (typeof stored === 'string' && stored) {- if (requested && requested.toString() !== stored) throw new InvalidGrantError('Requested resource exceeds the approved grant');- return new URL(stored);+ let approved: URL;+ try {+ approved = this.canonicalResource(new URL(stored))!;+ } catch {+ throw new InvalidGrantError('The approved grant is bound to a resource this server does not serve; reconnect the client');+ }+ if (requested && requested.toString() !== approved.toString()) throw new InvalidGrantError('Requested resource exceeds the approved grant');+ return approved;}return requested; // pre-resource grants remain valid on upgrade}diff --git a/src/core/oauth-provider.ts b/src/core/oauth-provider.tsindex c31a5afe41..71836ea265 100644--- a/src/core/oauth-provider.ts+++ b/src/core/oauth-provider.ts@@ -239,6 +239,8 @@ interface GBrainOAuthProviderOptions {* before mcpAuthRouter ran).*/dcrDisabled?: boolean;+ /** #5222: the canonical /mcp resource from the configured public URL; grants canonicalize `resource` against it. */+ resourceUrl?: URL;/*** Allow the consent-bypassing `client_credentials` grant on the unauthenticated* Dynamic Client Registration path. Default false (#1353): a self-registered@@ -558,7 +560,7 @@ export class GBrainOAuthProvider implements OAuthServerProvider {this.dcrDisabled = options.dcrDisabled === true;this.tokenTtl = options.tokenTtl || 3600;this.refreshTtl = options.refreshTtl || 30 * 24 * 3600;- this.grants = new OAuthGrants({ sql: this.sql, transaction: options.transaction, tokenTtl: this.tokenTtl, refreshTtl: this.refreshTtl });+ this.grants = new OAuthGrants({ sql: this.sql, transaction: options.transaction, tokenTtl: this.tokenTtl, refreshTtl: this.refreshTtl, resourceUrl: options.resourceUrl });// #2179 fail-closed: an unset DCR max is bounded by the operator's own// token TTL — never a fixed permissive ceiling — so a self-registering// client cannot elect a longer-lived token than the server defaultdiff --git a/src/core/ops/context.ts b/src/core/ops/context.tsindex 9b53f3a08b..1c94d5356d 100644--- a/src/core/ops/context.ts+++ b/src/core/ops/context.ts@@ -777,7 +777,7 @@ export async function requireWritablePage(includeDeleted: true,});if (writable) {- if (ctx.viaSubagent === true && ctx.auth && isPrivatePage(writable.frontmatter)+ if (ctx.viaSubagent === true && ctx.auth && isPrivatePage(writable)&& await resolveExcludePrivatePages(ctx.engine, ctx.remote)) {throw new OperationError('permission_denied', `${operation}: this page is outside your write visibility.`);}diff --git a/src/core/ops/pages.ts b/src/core/ops/pages.tsindex dfa11d1bc1..0cbd089934 100644--- a/src/core/ops/pages.ts+++ b/src/core/ops/pages.ts@@ -67,7 +67,8 @@ async function dropPrivateSlugs(* entirely, facts fence keeps only `world`-visibility rows.*/function stripPrivacyFencesForRemoteReader(page: Page): Page {- return { ...page, compiled_truth: sanitizeRemoteBody(page.compiled_truth, { includeWithdrawn: true }), timeline: sanitizeRemoteBody(page.timeline ?? '', { includeWithdrawn: true }) };+ const opts = { includeWithdrawn: true, keepMaterializedMarkers: true }; // #5567: markers round-trip remote edits+ return { ...page, compiled_truth: sanitizeRemoteBody(page.compiled_truth, opts), timeline: sanitizeRemoteBody(page.timeline ?? '', opts) };}const get_page: Operation = {@@ -111,7 +112,7 @@ const get_page: Operation = {let snapshot = await ctx.engine.readPageSnapshot(slug, { includeDeleted, excludePrivate, ...sourceOpts, resolveAlias: true });let page = snapshot?.page ?? null;- if (page && excludePrivate && isPrivatePage(page.frontmatter)) page = null;+ if (page && excludePrivate && isPrivatePage(page)) page = null;let resolved_slug: string | undefined = page && page.slug !== slug ? page.slug : undefined;if (!page && fuzzy) {@@ -125,7 +126,7 @@ const get_page: Operation = {? await tx.readPageSnapshot(candidates[0], { includeDeleted, excludePrivate, ...sourceOpts }) : null };});if (fallback.candidates.length > 1) return { error: 'ambiguous_slug', candidates: fallback.candidates };- if (fallback.snapshot && !(excludePrivate && isPrivatePage(fallback.snapshot.page.frontmatter))) {+ if (fallback.snapshot && !(excludePrivate && isPrivatePage(fallback.snapshot.page))) {snapshot = fallback.snapshot;page = snapshot.page;resolved_slug = page.slug;@@ -144,7 +145,7 @@ const get_page: Operation = {// gbrain-allow-unscoped-getpage: read-only diagnostic existence probe —// deliberately spans all sources to name where the slug lives.const elsewhere = await ctx.engine.getPage(slug, { includeDeleted });- if (elsewhere && !(excludePrivate && isPrivatePage(elsewhere.frontmatter))) {+ if (elsewhere && !(excludePrivate && isPrivatePage(elsewhere))) {hint = `Page exists in source '${elsewhere.source_id}' — pass --source ${elsewhere.source_id} (source_id: '${elsewhere.source_id}' over MCP). ${hint}`;}} catch {@@ -243,7 +244,7 @@ const fetch_page: Operation = {throw error;}const page = snapshot?.page;- if (!page || (excludePrivate && isPrivatePage(page.frontmatter))) throw missing();+ if (!page || (excludePrivate && isPrivatePage(page))) throw missing();bumpLastRetrievedAt(ctx.engine, [page.id]);const tags = snapshot!.tags;// Same privacy boundary as get_page: untrusted readers (ctx.remote ===@@ -579,6 +580,7 @@ const capture: Operation = {...PAGE_MUTATION_PARAMS,...CAPTURE_EVENT_PARAMS,content: { type: 'string', required: true, description: 'Markdown or plain text to capture. File paths are NOT accepted over MCP — read the file yourself and pass its content (the CLI --file lane is local-only).' },+ local_file: { type: 'string', required: false, description: 'Trusted local CLI only (--file): the absolute path of the captured file. Recorded as the page origin only when it lies inside the source and names the slug; the path itself is never stored. Remote callers are refused.' },slug: { type: 'string', required: false, description: "Target slug. Default: inbox/YYYY-MM-DD-<sha8-of-content> (stable per content — recapturing identical text hits the same slug); type diary/event routes under life/. Fenced clients: the default lands under your first bound prefix." },type: { type: 'string', required: false, description: "Page type for the stamped frontmatter. Omitted: the content's frontmatter `type:` when present, else 'note'. An explicit type (this param or a frontmatter `type:`) must be declared by the active schema pack; undeclared types are rejected before writing, naming the declared vocabulary." },},diff --git a/src/core/ops/search.ts b/src/core/ops/search.tsindex beeb913595..54311cb11a 100644--- a/src/core/ops/search.ts+++ b/src/core/ops/search.ts@@ -72,28 +72,38 @@ function searchOutput(ctx: OperationContext, results: SearchResult[], meta: Reco}/**- * #5004: does the caller's read scope still hold markdown pages below the- * safe-chunk index version? Every remote chunk read withholds them (the- * `requireSafeChunks` predicate in each engine leg) until- * `gbrain reindex --markdown` seals them, so an empty remote result on such- * a brain is a policy gap, not a clean miss. Same scope precedence as- * sourceScopeOpts (federated array > scalar > brain-wide); indexed LIMIT 1- * probe, portable SQL on both engines, fail-open.+ * #5004/#5247: does the caller's read scope still hold pages of any kind+ * below the safe-chunk index version? Every remote chunk read withholds them+ * (the `requireSafeChunks` predicate in each engine leg) until they are+ * re-sealed (`gbrain repair safe-chunks`, or an unchanged re-import), so a+ * remote result on such a brain may be incomplete, not a clean or complete+ * answer. Same scope precedence as sourceScopeOpts (federated array > scalar+ * > brain-wide); LIMIT 1 probe, portable SQL on both engines, fail-open.** The predicate is the plain range `chunker_version < N` (the column is* SMALLINT NOT NULL, so it is the same set as `NOT safeChunksFilter`), NOT- * the COALESCE form the read legs use: only the range is sargable, and this- * runs on every empty remote result — on a fully sealed brain the COALESCE- * form walked every markdown page.+ * the COALESCE form the read legs use: only the range matches the partial+ * `pages_safe_chunk_pending_idx`, which holds unsealed pages only, and this+ * runs on every remote result.*/-async function hasUnsealedPagesInScope(ctx: OperationContext, scope: SourceScope, excludePrivate: boolean): Promise<boolean> {+async function hasUnsealedPagesInScope(ctx: OperationContext, scope: SourceScope, excludePrivate: boolean,+ filters: { types?: string[]; excludeSlugPrefixes: string[] }): Promise<boolean> {if (scope.sourceIds?.length === 0) return false;const params: unknown[] = [];- const policy = pageReadFilter('p', { ...scope, excludePrivate }, params, true);+ // The same page filters the search itself applied: a withheld page it could never return is not a gap.+ const clauses = [pageReadFilter('p', { ...scope, excludePrivate }, params, true)];+ if (filters.types) {+ params.push(filters.types);+ clauses.push(`p.type = ANY($${params.length}::text[])`);+ }+ for (const prefix of filters.excludeSlugPrefixes) {+ params.push(prefix);+ clauses.push(`LEFT(p.slug, LENGTH($${params.length}::text)) <> $${params.length}`);+ }try {const rows = await ctx.engine.executeRaw(`SELECT 1 FROM pages p- WHERE p.page_kind = 'markdown' AND ${policy}+ WHERE ${clauses.join(' AND ')}AND p.chunker_version < ${SAFE_FENCE_CHUNKER_VERSION} LIMIT 1`,params,);@@ -113,8 +123,9 @@ async function hasUnsealedPagesInScope(ctx: OperationContext, scope: SourceScope** #5004: this is the ONE producer of the channel (keyword-only path included,* which never runs hybridSearch), so the safe-chunk fence is disclosed here:- * an empty result for a remote caller whose scope still holds unsealed pages- * gets `safe_index_pending` appended. The withholding itself is unchanged.+ * a result for a remote caller whose scope still holds unsealed pages gets+ * `safe_index_pending` appended, whether it came back empty or partial. The+ * withholding itself is unchanged.*/async function buildRetrievalResponseMeta(ctx: OperationContext,@@ -130,13 +141,14 @@ async function buildRetrievalResponseMeta('synonym-phrased matches this keyword-leaning search can miss.': undefined;const excludePrivate = await resolveExcludePrivatePages(ctx.engine, ctx.remote);- const safeIndexPending = results.length === 0 && ctx.remote !== false- && await hasUnsealedPagesInScope(ctx, scope, excludePrivate);+ const excludeSlugPrefixes = resolveHardExcludes();+ const safeIndexPending = ctx.remote !== false+ && await hasUnsealedPagesInScope(ctx, scope, excludePrivate, { types: opts.types, excludeSlugPrefixes });const readiness = await probeProjectionReadiness(ctx.engine, {...scope,excludePrivate,types: opts.types,- excludeSlugPrefixes: resolveHardExcludes(),+ excludeSlugPrefixes,});const degraded = [...(m?.degraded ?? [])];if (safeIndexPending) degraded.push({ stage: 'safe_index_pending' });diff --git a/src/core/page-state/projections.ts b/src/core/page-state/projections.tsindex b633d8c88b..47ad4d00e2 100644--- a/src/core/page-state/projections.ts+++ b/src/core/page-state/projections.ts@@ -12,6 +12,9 @@ import { quoteIdentifier, resolveWriteColumnFromConfigRows, vectorCastSuffix } fimport { getFtsLanguage } from '../fts-language.ts';import { getEmbeddingModel } from '../ai/gateway.ts';import { refreshProjectionStatistics } from '../search/projection-statistics.ts';+import { belowSafeChunkFence } from '../search/safe-chunks.ts';+import { acceptedEmbeddingInputHashes, embeddingInputHash, isContextualMode, plainEmbeddingTier, synopsisBodyHash,+ type EmbeddingInputContext, type EmbeddingTier } from '../embedding-input-hash.ts';/** Complete the searchable snapshot only after its sanitized chunks are installed. */export async function sealPageTextProjection(engine: BrainEngine, slug: string, sourceId: string): Promise<void> {@@ -44,16 +47,46 @@ export class PageProjectionConflictError extends PageRevisionConflictError {}}-async function indexingContext(engine: BrainEngine, snapshot: PageSnapshot, maxChunkTokensOverride?: number): Promise<{ key: string; model: string | null; maxChunkTokens: number; column: ResolvedColumn; pageKind: PageKind }> {+/** The vector column and model a write targets; `model` is what a stored chunk's label and provenance are compared to. */+export async function embeddingWriteTarget(engine: Pick<BrainEngine, 'executeRaw'>): Promise<{ config: Array<{ key: string; value: string }>; model: string | null; column: ResolvedColumn; provenanceModel: string | null }> {+ // A missing config table reads as defaults, as upsertChunks' own resolution does.const config = await engine.executeRaw<{ key: string; value: string }>(- "SELECT key,value FROM config WHERE key IN ('search_embedding_column','embedding_columns','embedding_model','embedding_dimensions','contextual_retrieval.mode') ORDER BY key");+ "SELECT key,value FROM config WHERE key IN ('search_embedding_column','embedding_columns','embedding_model','embedding_dimensions','contextual_retrieval.mode') ORDER BY key") ?? [];let model = config.find(row => row.key === 'embedding_model')?.value ?? null;try { model = getEmbeddingModel(); } catch { /* Unconfigured gateway: retain the brain's recorded model. */ }- const maxChunkTokens = maxChunkTokensOverride ?? resolveMaxChunkTokens();const column = resolveWriteColumnFromConfigRows({searchEmbeddingColumn: config.find(row => row.key === 'search_embedding_column')?.value ?? null,embeddingColumnsJson: config.find(row => row.key === 'embedding_columns')?.value ?? null,});+ return { config, model, column, provenanceModel: column.name === 'embedding' ? model : column.embeddingModel };+}++/** Provenance inputs for one page's chunk set under a write target. */+export function embeddingInputContext(target: { column: ResolvedColumn; provenanceModel: string | null }, title: string,+ corpusGeneration: string | null, chunks: ReadonlyArray<{ chunk_text: string; chunk_source?: string | null }>): EmbeddingInputContext {+ return { column: target.column.name, model: target.provenanceModel, dimensions: target.column.dimensions, title, corpusGeneration,+ bodyHash: synopsisBodyHash(chunks) };+}++/**+ * Record provenance on freshly embedded chunks of a full import, built under+ * `tier`, and return the column the hash names so the write targets it+ * (undefined when nothing was freshly embedded). Reused vectors stay unrecorded.+ */+export async function stampEmbeddingInputs(engine: Pick<BrainEngine, 'executeRaw'>, chunks: ChunkInput[], fresh: ReadonlySet<number> | null,+ page: { title: string; tier: EmbeddingTier; corpusGeneration: string | null }): Promise<ResolvedColumn | undefined> {+ if (!chunks.some((chunk, i) => chunk.embedding && (!fresh || fresh.has(i)))) return undefined;+ const target = await embeddingWriteTarget(engine);+ const provenance = embeddingInputContext(target, page.title, page.corpusGeneration, chunks);+ chunks.forEach((chunk, i) => {+ if (chunk.embedding && (!fresh || fresh.has(i))) chunk.embedding_input_hash = embeddingInputHash(provenance, page.tier, chunk);+ });+ return target.column;+}++async function indexingContext(engine: BrainEngine, snapshot: PageSnapshot, maxChunkTokensOverride?: number): Promise<{ key: string; model: string | null; maxChunkTokens: number; column: ResolvedColumn; pageKind: PageKind; provenanceModel: string | null; corpusGeneration: string | null }> {+ const { config, model, column, provenanceModel } = await embeddingWriteTarget(engine);+ const maxChunkTokens = maxChunkTokensOverride ?? resolveMaxChunkTokens();const [projection] = await engine.executeRaw<{ chunker_version: number | null; corpus_generation: string | null }>('SELECT chunker_version,corpus_generation FROM pages WHERE id=$1', [snapshot.page.id]);const [kind] = await engine.executeRaw<{ page_kind: PageKind }>('SELECT page_kind FROM pages WHERE id=$1', [snapshot.page.id]);@@ -61,7 +94,8 @@ async function indexingContext(engine: BrainEngine, snapshot: PageSnapshot, maxCreturn { key: digest({ config, mode: snapshot.page.contextual_retrieval_mode, model, column,maxChunkTokens, storedChunkerVersion: projection?.chunker_version ?? null, corpusGeneration: projection?.corpus_generation ?? null,chunkerVersion: MARKDOWN_CHUNKER_VERSION, codeChunkerVersion: CHUNKER_VERSION, pageKind: kind.page_kind,- ftsLanguage: getFtsLanguage() }), model, maxChunkTokens, column, pageKind: kind.page_kind };+ ftsLanguage: getFtsLanguage() }), model, maxChunkTokens, column, pageKind: kind.page_kind, provenanceModel,+ corpusGeneration: projection?.corpus_generation ?? null };}/** A short guarded read binds the exact chunk set and title/body revision. */@@ -112,11 +146,20 @@ export async function installPageProjection(engine: BrainEngine, prepared: Projereturn next && digest(identity(chunk)) === digest(identity(next));}).map(chunk => chunk.id);await tx.executeRaw(`DELETE FROM content_chunks WHERE page_id=$1 AND NOT(id=ANY($2::int[]))`, [snapshot.page.id, matching]);+ // #5553: keep a vector only when its recorded embedding input equals the+ // input the current page would produce. A chunk with no record is kept+ // only where that input is its raw text; on a contextual page it is+ // nulled once and stamped by its re-embed.+ const mode = current!.page.contextual_retrieval_mode;+ const provenance = embeddingInputContext(context, current!.page.title, context.corpusGeneration, chunks);+ const recorded = await tx.executeRaw<{ id: number; chunk_index: number; embedding_input_hash: string | null }>(+ 'SELECT id,chunk_index,embedding_input_hash FROM content_chunks WHERE page_id=$1', [snapshot.page.id]);+ const currentInput = recorded.filter(row => row.embedding_input_hash === null ? !isContextualMode(mode)+ : acceptedEmbeddingInputHashes(provenance, mode, byIndex.get(Number(row.chunk_index))!).includes(row.embedding_input_hash)).map(row => Number(row.id));await tx.executeRaw(`UPDATE content_chunks SET ${quoteIdentifier(context.column.name)}=NULL,- embedded_at=NULL,embedded_text_hash=NULL WHERE page_id=$1 AND- (model IS DISTINCT FROM $2 OR embedded_text_hash <> md5(chunk_text) OR $3::boolean)`,- [snapshot.page.id, context.column.name === 'embedding' ? context.model : context.column.embeddingModel,- ![null, undefined, 'none'].includes(snapshot.page.contextual_retrieval_mode)]);+ embedded_at=NULL,embedded_text_hash=NULL,embedding_input_hash=NULL WHERE page_id=$1 AND+ (model IS DISTINCT FROM $2 OR embedded_text_hash <> md5(chunk_text) OR NOT(id=ANY($3::int[])))`,+ [snapshot.page.id, context.provenanceModel, currentInput]);} else if (opts.seal) await tx.deleteChunks(slug, { sourceId });await tx.upsertChunks(slug, chunks, { sourceId, expectedRevision: snapshot.revision, embeddingColumn: context.column });if (opts.code) await installCodeChunkEdges(tx, slug, sourceId, opts.code);@@ -130,8 +173,14 @@ export async function installPageProjection(engine: BrainEngine, prepared: Proje});}-/** Embedding-only updates require the same chunk identities and text, too. */-export async function installPageEmbeddings(engine: BrainEngine, prepared: ProjectionSnapshot, chunks: ChunkInput[], signature?: string): Promise<boolean> {+/**+ * Embedding-only updates require the same chunk identities and text, too.+ * `built` names the wrapping the vectors were built under when it is not the+ * page's plain re-embed convention (the contextual service's synopsis tier and+ * its corpus generation); it is recorded with each vector.+ */+export async function installPageEmbeddings(engine: BrainEngine, prepared: ProjectionSnapshot, chunks: ChunkInput[], signature?: string,+ built?: { tier: EmbeddingTier; corpusGeneration?: string | null }): Promise<boolean> {const { snapshot } = prepared;const sourceId = snapshot.page.source_id;const slug = snapshot.page.slug;@@ -153,6 +202,9 @@ export async function installPageEmbeddings(engine: BrainEngine, prepared: Proje// Use the checked descriptor: config writes do not take the page guard,// so resolving again could send these vectors to a different model's column.const column = context.column;+ const tier = built?.tier ?? plainEmbeddingTier(current.page.contextual_retrieval_mode);+ const provenance = embeddingInputContext(context, current.page.title,+ built?.corpusGeneration !== undefined ? built.corpusGeneration : context.corpusGeneration, stored);// This is deliberately UPDATE-only: a late embed can never replace text,// chunk identity, metadata, or membership in the installed projection.for (const chunk of chunks) {@@ -163,11 +215,13 @@ export async function installPageEmbeddings(engine: BrainEngine, prepared: Projeawait tx.executeRaw(`UPDATE content_chunks SET${quoteIdentifier(column.name)}=CASE WHEN $2::text IS NULL THEN ${quoteIdentifier(column.name)} ELSE $2${vectorCastSuffix(column)} END,embedding_image=CASE WHEN $3::text IS NULL THEN embedding_image ELSE $3::vector END,+ embedding_input_hash=CASE WHEN $2::text IS NULL THEN embedding_input_hash ELSE $7 END,embedded_at=now(),embedded_text_hash=md5(chunk_text),model=COALESCE($4,model)WHERE id=$1 AND page_id=$5 AND chunk_text=$6`,// Bind the full provider:model captured before the provider call. Keeping// an old label on a new vector prevents provenance-complete migration.- [original.id, vector, image, chunk.model ?? (vector ? prepared.embeddingModel : null), snapshot.page.id, original.chunk_text]);+ [original.id, vector, image, chunk.model ?? (vector ? prepared.embeddingModel : null), snapshot.page.id, original.chunk_text,+ embeddingInputHash(provenance, tier, original)]);}if (signature) await tx.setPageEmbeddingSignature(slug, { sourceId, signature });return true;@@ -182,6 +236,34 @@ export async function queuePageProjection(engine: Pick<BrainEngine, 'executeRaw'ON CONFLICT(source_incarnation,slug) DO UPDATE SET revision=EXCLUDED.revision,reason=EXCLUDED.reason,updated_at=now()`, [sourceId, slug, reason]);}+/** #5050/#5247: whether a live page's installed chunks predate the safe-chunk fence. */+export async function projectionBelowSafeFence(engine: Pick<BrainEngine, 'executeRaw'>, pageId: number): Promise<boolean> {+ const [row] = await engine.executeRaw<{ chunker_version: number | null }>(+ 'SELECT chunker_version FROM pages WHERE id=$1 AND deleted_at IS NULL', [pageId]) ?? [];+ return row !== undefined && belowSafeChunkFence(row.chunker_version === null ? null : Number(row.chunker_version));+}++/**+ * #5050/#5247: re-seal a page chunked before the safe-chunk fence from its+ * unchanged canonical body. Projection-only: no page write, version, journal+ * admission or lifetime ID; vectors of unchanged inputs are kept. Returns the+ * chunks left without a vector (the re-seal's embedding work), or null when+ * the page is gone or already sealed at the fence; a concurrent change+ * surfaces as PageRevisionConflictError.+ */+export async function resealSafeChunks(engine: BrainEngine, slug: string, sourceId: string): Promise<{ pendingChunks: number; pendingChars: number } | null> {+ const prepared = await readProjectionSnapshot(engine, slug, sourceId, { allowUnsealed: true, requireLiveSource: true });+ if (!prepared || prepared.snapshot.page.deleted_at || !['markdown', 'code'].includes(prepared.pageKind)) return null;+ if (!await projectionBelowSafeFence(engine, prepared.snapshot.page.id)+ && prepared.snapshot.page.text_projection_revision === prepared.snapshot.revision) return null;+ const projection = await preparePageProjection(prepared);+ await installPageProjection(engine, prepared, projection.chunks, { seal: true, preserveEmbeddings: true, code: projection.code });+ const [pending] = await engine.executeRaw<{ chunks: number; chars: number }>(`SELECT COUNT(*)::int AS chunks,+ COALESCE(SUM(length(chunk_text)),0)::int AS chars FROM content_chunks+ WHERE page_id=$1 AND ${quoteIdentifier(prepared.embeddingColumn.name)} IS NULL AND modality='text'`, [prepared.snapshot.page.id]);+ return { pendingChunks: Number(pending?.chunks ?? 0), pendingChars: Number(pending?.chars ?? 0) };+}+export async function preparePageProjection(prepared: ProjectionSnapshot) {const page = prepared.snapshot.page;if (prepared.pageKind === 'code') {diff --git a/src/core/persistence/administration.ts b/src/core/persistence/administration.tsindex feb5e50339..69207c90a3 100644--- a/src/core/persistence/administration.ts+++ b/src/core/persistence/administration.ts@@ -89,7 +89,7 @@ export async function runPersistenceAdministration(engine: BrainEngine, operatiokeys(params, ['source_id', 'request_id', 'dry_run']);if (params.dry_run !== undefined && typeof params.dry_run !== 'boolean') throw invalid('dry_run must be a boolean.');if (!isWriteRequestId(params.request_id)) throw invalid('A valid original write request UUID is required.');- return (await import('./effect-retry.ts')).retryEmbeddingEffect(engine, source(params.source_id), params.request_id, params.dry_run === true, config, embeddingRetryPolicy);+ return (await import('./effect-retry.ts')).retryRequestEffects(engine, source(params.source_id), params.request_id, params.dry_run === true, config, embeddingRetryPolicy);}if (operation === 'source_add' || operation === 'source_lifecycle') {const { managedPersistenceEnabled } = await import('./ownership.ts');diff --git a/src/core/persistence/atom-maintenance.ts b/src/core/persistence/atom-maintenance.tsindex 66834903d9..baeb980b50 100644--- a/src/core/persistence/atom-maintenance.ts+++ b/src/core/persistence/atom-maintenance.ts@@ -15,6 +15,7 @@ import type { PreparedMutation } from './coordinator.ts';import type { WriteAuthority, WriteRequest } from './model.ts';import type { WriteReceipt } from './types.ts';import { writeAtomPageState } from '../cycle/extract-atoms-page-state.ts';+import { effectiveVisibility } from '../search/private-visibility.ts';export interface AtomOrigin {kind: 'page' | 'transcript';@@ -71,7 +72,7 @@ export async function managedAtomSession(engine: BrainEngine, sourceId: string,throw new OperationError('owner_unavailable', 'The canonical atom owner is unavailable; no extraction was started.');}if (writeThrough && binding) {- const lock = await acquireWorktree(binding);+ const lock = await acquireWorktree(binding, 0, undefined, engine);if (!lock) throw new OperationError('writer_lock_unavailable', 'The canonical atom writer is busy; no extraction was started.');await lock.release();}@@ -109,14 +110,15 @@ export async function readAtomOrigin(engine: BrainEngine, session: ManagedAtomSeitem: { kind: 'page'; slug: string; content: string; contentHash: string } | { kind: 'transcript'; filePath: string; content: string; contentHash: string }): Promise<AtomOrigin> {if (item.kind === 'transcript') {if (sha256(readFileSync(item.filePath)) !== sha256(item.content)) throw new OperationError('source_changed', 'The atom transcript changed before extraction.');- return { kind: item.kind, locator: item.filePath, contentHash: item.contentHash, textHash: sha256(item.content), pageId: null, revision: null, visibility: 'private' };+ return { kind: item.kind, locator: item.filePath, contentHash: item.contentHash, textHash: sha256(item.content), pageId: null, revision: null,+ visibility: effectiveVisibility({ kind: 'transcript' }) };}const snapshot = await engine.readPageSnapshot(item.slug, { sourceId: session.sourceId });if (!snapshot || snapshot.sourceIncarnation !== session.incarnation || snapshot.page.content_hash !== item.contentHash || snapshot.page.compiled_truth !== item.content) {throw new OperationError('revision_conflict', 'The atom input changed before extraction.');}return { kind: item.kind, locator: item.slug, contentHash: item.contentHash, textHash: sha256(item.content), pageId: snapshot.page.id,- revision: snapshot.revision, visibility: snapshot.page.frontmatter.visibility === 'world' ? 'world' : 'private' };+ revision: snapshot.revision, visibility: effectiveVisibility({ kind: 'page', page: snapshot.page }) };}function runKey(session: ManagedAtomSession, origin: AtomOrigin): string {diff --git a/src/core/persistence/canonical-projections.ts b/src/core/persistence/canonical-projections.tsindex 6b6773ccbc..fa8fcf4603 100644--- a/src/core/persistence/canonical-projections.ts+++ b/src/core/persistence/canonical-projections.ts@@ -1,16 +1,223 @@import type { BrainEngine } from '../engine.ts';import type { ParsedPage } from '../import-file.ts';+import type { PageSnapshot } from '../page-state/types.ts';import { FACTS_FENCE_BEGIN, FACTS_FENCE_END, parseFactsFence } from '../facts-fence.ts';import { TAKES_FENCE_BEGIN, TAKES_FENCE_END, parseTakesFence } from '../takes-fence.ts';import { extractFactsFromFenceText } from '../facts/extract-from-fence.ts';import { takesPreparation } from '../takes-write.ts';import { parseTimelineEntries } from '../link-extraction.ts';-import { extractTimelineFromContent } from '../timeline-extract.ts';+import { extractTimelineFromContent, type ExtractedTimelineEntry } from '../timeline-extract.ts';import { sanitizeRemoteBody } from '../remote-body.ts';+import { sanitizeForJsonb } from '../batch-rows.ts';+import { materializedMarker, materializedMarkerHash, timelineKey, timelineKeyHash } from '../timeline-marker.ts';import { OperationError } from '../ops/contract.ts';-/** Compile synchronous, provider-free projections before entering publication. */-export function prepareCanonicalProjections(page: ParsedPage, slug: string, sourceId: string): (tx: BrainEngine) => Promise<void> {+type CanonicalBody = Pick<ParsedPage, 'compiled_truth' | 'timeline'>;++/**+ * The caller's authority over the prior canonical content (#5567):+ * `editing` writers are bound to the observed revision and render from the+ * database, `preserving` writers regenerate or overwrite without that binding,+ * `file` writers import file edits bound to the file preimage and never+ * rewrite the user's file, and `immutable` imports publish approved bytes they+ * may never extend.+ */+export type ProjectionWriter = 'editing' | 'preserving' | 'file' | 'immutable';++/**+ * How one stored timeline row relates to the write, judged at preparation:+ * `in_body` exactly matches a new bullet, `drifted` matches one only after+ * normalization, `removed` / `removed_marked` had an unmarked / materialized+ * bullet in the prior body that the new body dropped, and `database_only`+ * has no bullet in either body.+ */+export type TimelineRowState = 'in_body' | 'drifted' | 'removed' | 'removed_marked' | 'database_only';+export type TimelineRowAction = 'refresh_detail' | 'delete' | 'keep' | 'materialize';++/**+ * row state | editing | preserving | file | immutable+ * ---------------+----------------+----------------+----------------+---------------+ * in_body | refresh_detail | refresh_detail | refresh_detail | refresh_detail+ * drifted | delete | delete | delete | delete+ * removed | delete | delete | delete | delete+ * removed_marked | delete | materialize | delete | keep+ * database_only | materialize | materialize | keep | keep+ *+ * A coordinated write deletes only rows whose bullet the writer can see in the+ * prior or new body. A materialized bullet is removed only by a writer bound to+ * a revision or file preimage that contained it; a preserving writer renders it+ * again. Writers that render from the database write bullet-less rows back into+ * the page (`materialize`); rows that fail the render round trip, and every+ * `materialize` row a caller did not render, are kept. `put_page` with the+ * current revision is the supported way to delete a materialized row. Deletes+ * and detail refreshes also require the row id and detail pinned at+ * preparation, so rows that change afterwards are left alone.+ */+const TIMELINE_DECISIONS: Record<ProjectionWriter, Record<TimelineRowState, TimelineRowAction>> = {+ editing: { in_body: 'refresh_detail', drifted: 'delete', removed: 'delete', removed_marked: 'delete', database_only: 'materialize' },+ preserving: { in_body: 'refresh_detail', drifted: 'delete', removed: 'delete', removed_marked: 'materialize', database_only: 'materialize' },+ file: { in_body: 'refresh_detail', drifted: 'delete', removed: 'delete', removed_marked: 'delete', database_only: 'keep' },+ immutable: { in_body: 'refresh_detail', drifted: 'delete', removed: 'delete', removed_marked: 'keep', database_only: 'keep' },+};++export function timelineRowAction(writer: ProjectionWriter, state: TimelineRowState): TimelineRowAction {+ return TIMELINE_DECISIONS[writer][state];+}++function exactTimelineKey(entry: { date: string; source?: string | null; summary: string }): string {+ return JSON.stringify([entry.date.slice(0, 10), sanitizeForJsonb(entry.source ?? ''), sanitizeForJsonb(entry.summary)]);+}++function safeBody(body: CanonicalBody): string {+ return sanitizeRemoteBody([body.compiled_truth, body.timeline ?? ''].join('\n'), { keepMaterializedMarkers: true });+}++function extractTimeline(safe: string, slug: string): Map<string, ExtractedTimelineEntry> {+ const timeline = new Map(extractTimelineFromContent(safe, slug).map(t => [timelineKey(t), t]));+ for (const t of parseTimelineEntries(safe)) timeline.set(timelineKey({ ...t, source: t.source ?? 'markdown' }), { ...t, source: t.source ?? 'markdown', slug });+ return timeline;+}++function canonicalTimeline(body: CanonicalBody, slug: string): Map<string, ExtractedTimelineEntry> {+ return extractTimeline(safeBody(body), slug);+}++/** Tuples whose bullet is introduced by a marker that still matches it. */+function markedTimeline(body: CanonicalBody, slug: string): Set<string> {+ const lines = safeBody(body).split('\n');+ const marked = new Set<string>();+ lines.forEach((line, i) => {+ const hash = materializedMarkerHash(line);+ if (!hash || i + 1 >= lines.length) return;+ for (const key of extractTimeline(lines[i + 1], slug).keys()) if (timelineKeyHash(key) === hash) marked.add(key);+ });+ return marked;+}++/**+ * Character ranges of materialized timeline history in a raw body: each marker+ * line whose hash matches the bullet after it, that bullet, and its indented+ * detail lines. This is database history written back into the page, not+ * newly authored text.+ */+export function materializedHistoryRanges(body: string): Array<[number, number]> {+ const lines = body.split('\n');+ const starts: number[] = [];+ let offset = 0;+ for (const line of lines) { starts.push(offset); offset += line.length + 1; }+ const ranges: Array<[number, number]> = [];+ lines.forEach((line, i) => {+ const hash = materializedMarkerHash(line);+ if (!hash || i + 1 >= lines.length) return;+ if (![...extractTimeline(lines[i + 1], '').keys()].some(key => timelineKeyHash(key) === hash)) return;+ let last = i + 1;+ while (last + 1 < lines.length && /^[ \t]+\S/.test(lines[last + 1]) && !/^[ \t]*[-*+] /.test(lines[last + 1])) last++;+ ranges.push([starts[i], starts[last] + lines[last].length]);+ });+ return ranges;+}++interface StoredTimelineRow { id: number; date: string; source: string; summary: string; detail: string }++function storedTimeline(engine: BrainEngine, pageId: number): Promise<StoredTimelineRow[]> {+ return engine.executeRaw<StoredTimelineRow>(`SELECT id,date::text AS date,source,summary,detail FROM timeline_entries+ WHERE page_id=$1 AND event_page_id IS NULL ORDER BY date,id`, [pageId]);+}++/**+ * Timeline tuples the coordinator projects from a canonical page body that+ * have no stored row on the page under the same normalized key. Insert-only+ * callers (managed `extract --stale`) add exactly these, so a stored row that+ * differs only by whitespace is not duplicated.+ */+export async function unrecordedCanonicalTimeline(engine: BrainEngine, pageId: number, body: CanonicalBody, slug: string): Promise<ExtractedTimelineEntry[]> {+ const stored = new Set((await storedTimeline(engine, pageId)).map(row => timelineKey(row)));+ return [...canonicalTimeline(body, slug)].filter(([key]) => !stored.has(key)).map(([, entry]) => entry);+}++/** Classify stored rows against a new body and the writer's prior snapshot. */+function classifyTimeline(rows: StoredTimelineRow[], body: CanonicalBody, prior: CanonicalBody | null, slug: string, writer: ProjectionWriter) {+ const timeline = canonicalTimeline(body, slug);+ const exactIncoming = new Map([...timeline.values()].map(t => [exactTimelineKey(t), sanitizeForJsonb(t.detail ?? '')]));+ const priorTimeline = prior ? new Set(canonicalTimeline(prior, slug).keys()) : new Set<string>();+ const priorMarked = prior ? markedTimeline(prior, slug) : new Set<string>();+ const pinned = rows.map(row => {+ const key = timelineKey(row);+ const state: TimelineRowState = exactIncoming.has(exactTimelineKey(row)) ? 'in_body' : timeline.has(key) ? 'drifted'+ : priorMarked.has(key) ? 'removed_marked' : priorTimeline.has(key) ? 'removed' : 'database_only';+ return { ...row, key, state, action: timelineRowAction(writer, state) };+ });+ return { timeline, exactIncoming, pinned };+}++const collapse = (text: string) => sanitizeForJsonb(text).replace(/\s+/g, ' ').trim();++/**+ * Render one row as a marked bullet, or null when render-then-extract would+ * not return exactly this tuple and its normalized detail (delimiters in the+ * source, `Referenced in [` backlink receipts, empty sources, ...).+ */+export function renderMaterializedBullet(row: { date: string; source: string; summary: string; detail?: string | null }, slug: string): string | null {+ // Same normalization as timelineKey: sources are trimmed, summaries and details collapsed.+ const tuple = { date: row.date.slice(0, 10), source: sanitizeForJsonb(row.source).trim(), summary: collapse(row.summary) };+ const detail = collapse(row.detail ?? '');+ // Pre-#4277 backlink receipts are graph noise the extractors deliberately skip.+ if (/^Referenced in\s+\[/i.test(tuple.summary)) return null;+ const block = [materializedMarker(tuple), `- **${tuple.date}** | ${tuple.source} — ${tuple.summary}`, ...(detail ? [` ${detail}`] : [])].join('\n');+ const extracted = [...canonicalTimeline({ compiled_truth: block, timeline: '' }, slug).values()];+ if (extracted.length !== 1) return null;+ const [entry] = extracted;+ const same = entry.date === tuple.date && entry.source === tuple.source && entry.summary === tuple.summary && (entry.detail ?? '') === detail;+ return same && markedTimeline({ compiled_truth: block, timeline: '' }, slug).size === 1 ? block : null;+}++export interface TimelineMaterialization { timeline: string; materialized: number; unrenderable: number }++/**+ * Write the writer's `materialize` rows back into the page's timeline section,+ * after existing bullets in date-then-row-id order, one bullet per normalized+ * tuple. Called during preparation, before the body is imported, rendered and+ * digested, by writers that render the canonical file from the database.+ */+export async function materializeTimeline(engine: BrainEngine, body: CanonicalBody, slug: string,+ prior: PageSnapshot | null, writer: ProjectionWriter): Promise<TimelineMaterialization> {+ const timelineText = body.timeline ?? '';+ if (!prior) return { timeline: timelineText, materialized: 0, unrenderable: 0 };+ const { pinned } = classifyTimeline(await storedTimeline(engine, prior.page.id), body, prior.page, slug, writer);+ const blocks: string[] = [];+ const seen = new Set<string>();+ let unrenderable = 0;+ for (const row of pinned) {+ if (row.action !== 'materialize' || seen.has(row.key)) continue;+ const block = renderMaterializedBullet(row, slug);+ if (!block) { unrenderable++; continue; }+ seen.add(row.key);+ blocks.push(block);+ }+ if (!blocks.length) return { timeline: timelineText, materialized: 0, unrenderable };+ const existing = timelineText.replace(/\s+$/, '');+ return { timeline: [...(existing ? [existing] : []), ...blocks].join('\n'), materialized: blocks.length, unrenderable };+}++/** Database-only timeline rows on one page, split by whether they can be materialized. */+export async function pendingTimelineRows(engine: BrainEngine, page: { id: number; slug: string } & CanonicalBody) {+ const { pinned } = classifyTimeline(await storedTimeline(engine, page.id), page, page, page.slug, 'editing');+ const renderable = new Set<string>();+ let unrenderable = 0;+ for (const row of pinned) {+ if (row.action !== 'materialize') continue;+ if (renderMaterializedBullet(row, page.slug)) renderable.add(row.key);+ else unrenderable++;+ }+ return { materializable: renderable.size, unrenderable };+}++function canonicalTakeRows(body: CanonicalBody): Set<number> {+ return new Set([body.compiled_truth, body.timeline ?? ''].flatMap(field => parseTakesFence(field).takes.map(t => t.rowNum)));+}++/** Validate a canonical body and compile its provider-free projections. */+export function compileCanonicalProjections(page: ParsedPage, slug: string, sourceId: string) {const fields=[page.compiled_truth,page.timeline ?? ''];for(const field of fields) for(const marker of [FACTS_FENCE_BEGIN,FACTS_FENCE_END,TAKES_FENCE_BEGIN,TAKES_FENCE_END]) {if(field.split(marker).length>2) throw new OperationError('invalid_params','Each canonical body section must contain at most one facts fence and one takes fence.');@@ -21,11 +228,37 @@ export function prepareCanonicalProjections(page: ParsedPage, slug: string, sourfor(const rows of [facts,takes]) if(new Set(rows.map(row=>row.rowNum)).size!==rows.length) {throw new OperationError('invalid_params','Canonical row numbers must be unique across the entire page.');}- const body=fields.join('\n');- const factRows=extractFactsFromFenceText(facts,slug,sourceId);- const safe=sanitizeRemoteBody(body);- const timeline=new Map(extractTimelineFromContent(safe,slug).map(t=>[JSON.stringify([t.date,t.source,t.summary]),t]));- for (const t of parseTimelineEntries(safe)) timeline.set(JSON.stringify([t.date,t.source??'markdown',t.summary]),{...t,source:t.source??'markdown',slug});+ return { factRows: extractFactsFromFenceText(facts,slug,sourceId), takes };+}++function takeCollision(): OperationError {+ return new OperationError('take_row_collision', 'A takes fence row number is already used by a different take that is not in this page\'s canonical fence.',+ 'Renumber the new takes row, or add the existing take to the fence with a revision-bound put_page.');+}++/**+ * Prepare provider-free projections outside publication. `prior` is the+ * caller's snapshot at its observed revision; stored timeline rows and take+ * row numbers are pinned here so the publication transaction only removes+ * what this writer actually edited.+ */+export async function prepareCanonicalProjections(engine: BrainEngine, page: ParsedPage, slug: string, sourceId: string,+ prior: PageSnapshot | null, writer: ProjectionWriter): Promise<(tx: BrainEngine) => Promise<void>> {+ const { factRows, takes } = compileCanonicalProjections(page, slug, sourceId);+ const { timeline, exactIncoming, pinned } = classifyTimeline(prior ? await storedTimeline(engine, prior.page.id) : [],+ page, prior?.page ?? null, slug, writer);+ const deletions = JSON.stringify(pinned.filter(row => row.action === 'delete')+ .map(({ id, date, source, summary, detail }) => ({ id, date, source, summary, detail })));+ const refreshes = JSON.stringify(pinned.filter(row => row.action === 'refresh_detail')+ .map(row => ({ id: row.id, detail: row.detail, next: exactIncoming.get(exactTimelineKey(row)) }))+ .filter(row => row.next !== row.detail));+ const priorTakes = prior ? canonicalTakeRows(prior.page) : new Set<number>();+ const newTakes = JSON.stringify(takes.filter(t => !priorTakes.has(t.rowNum)).map(t => ({ row_num: t.rowNum, claim: t.claim, kind: t.kind, holder: t.holder })));+ const takeRowsGone = [...priorTakes].filter(n => !takes.some(t => t.rowNum === n));+ const collides = async (db: BrainEngine, pageId: number) => (await db.executeRaw(`SELECT 1 FROM takes k+ JOIN jsonb_to_recordset($2::text::jsonb) AS n(row_num integer,claim text,kind text,holder text) ON n.row_num=k.row_num+ WHERE k.page_id=$1 AND (k.claim,k.kind,k.holder) IS DISTINCT FROM (n.claim,n.kind,n.holder) LIMIT 1`, [pageId, newTakes])).length > 0;+ if (prior && await collides(engine, prior.page.id)) throw takeCollision();return async tx=>{const snapshot=await tx.readPageSnapshot(slug,{sourceId});if (!snapshot) return;@@ -47,7 +280,8 @@ export function prepareCanonicalProjections(page: ParsedPage, slug: string, sourfact.claim_metric??null,fact.claim_value??null,fact.claim_unit??null,fact.claim_period??null]);}const pageId=snapshot.page.id;- await tx.executeRaw('DELETE FROM takes WHERE page_id=$1 AND NOT(row_num=ANY($2::integer[]))',[pageId,takes.map(t=>t.rowNum)]);+ if (await collides(tx,pageId)) throw takeCollision();+ await tx.executeRaw('DELETE FROM takes WHERE page_id=$1 AND row_num=ANY($2::integer[])',[pageId,takeRowsGone]);if (takes.length) await tx.addTakesBatch(takes.map(t=>takesPreparation.toBatchInput(pageId,t,t.active?null:Number(t.source?.match(/superseded by #(\d+)/)?.[1])||null)));// Full canonical versions include resolution fields; a revert restores those@@ -58,14 +292,12 @@ export function prepareCanonicalProjections(page: ParsedPage, slug: string, sourtake.resolvedQuality==='correct'?true:take.resolvedQuality==='incorrect'?false:null,take.resolvedEvidence??null,take.resolvedValue??null,take.resolvedUnit??null,take.resolvedBy??null]);// Event-page references have a different canonical origin and remain intact.- const tuples=[...timeline.values()];- await tx.executeRaw(`DELETE FROM timeline_entries t WHERE page_id=$1 AND event_page_id IS NULL- AND NOT EXISTS (SELECT 1 FROM jsonb_to_recordset($2::text::jsonb) AS n(date date,source text,summary text)- WHERE n.date=t.date AND n.source=t.source AND n.summary=t.summary)`,[pageId,JSON.stringify(tuples)]);- for (const entry of tuples) {- await tx.addTimelineEntry(slug,entry,{sourceId});- await tx.executeRaw(`UPDATE timeline_entries SET detail=$5 WHERE page_id=$1 AND date=$2::date- AND source=$3 AND summary=$4 AND event_page_id IS NULL`,[pageId,entry.date,entry.source,entry.summary,entry.detail??'']);- }+ await tx.executeRaw(`DELETE FROM timeline_entries t USING jsonb_to_recordset($2::text::jsonb) AS d(id integer,date date,source text,summary text,detail text)+ WHERE t.page_id=$1 AND t.event_page_id IS NULL AND t.id=d.id AND t.date=d.date AND t.source=d.source+ AND t.summary=d.summary AND t.detail=d.detail`,[pageId,deletions]);+ // New rows carry their Markdown detail on insert; pinned rows refresh only from their preimage.+ for (const entry of timeline.values()) await tx.addTimelineEntry(slug,entry,{sourceId});+ await tx.executeRaw(`UPDATE timeline_entries t SET detail=r.next FROM jsonb_to_recordset($2::text::jsonb) AS r(id integer,detail text,next text)+ WHERE t.page_id=$1 AND t.event_page_id IS NULL AND t.id=r.id AND t.detail=r.detail`,[pageId,refreshes]);};}diff --git a/src/core/persistence/connector-sync.ts b/src/core/persistence/connector-sync.tsindex ee3b5848f9..c616c4f871 100644--- a/src/core/persistence/connector-sync.ts+++ b/src/core/persistence/connector-sync.ts@@ -13,7 +13,7 @@ import { currentSubmissionAuthority } from '../minions/submission-authority.ts';import { sealPageTextProjection } from '../page-state/projections.ts';import { loadActivePackForEngine } from '../schema-pack/engine-resolution.ts';import { authorizeStoredRequest, authorizeWrite } from './authority.ts';-import { prepareCanonicalProjections } from './canonical-projections.ts';+import { materializeTimeline, prepareCanonicalProjections } from './canonical-projections.ts';import { digest, sha256 } from './digest.ts';import { admitWriteInTransaction, assertReplayIntent, getWriteRequest, getWriteRequestById, intentDigest, receiptFor } from './journal.ts';import { acquireWorktree, containsPath, getWorktreeBinding, type WorktreeBinding } from './ownership.ts';@@ -23,7 +23,7 @@ import { managedSyncAuthority, validateManagedSyncOptions, validateSyncAuthorityimport type { PreparedContentImport } from './prepared-import.ts';import { persistenceFileHash, type PreparedMutation } from './coordinator.ts';import { isTerminal, type WriteRequest } from './model.ts';-import { prepareFileTarget } from './page-prepare.ts';+import { databaseOnlyPublication, prepareFileTarget } from './page-prepare.ts';import { assertPhysicalRoot } from './physical-root.ts';import type { PageSnapshot } from '../page-state/types.ts';import { LockStolenError, syncLockId, withRefreshingLock, type DbLockHandle } from '../db-lock.ts';@@ -66,20 +66,26 @@ interface ConnectorIntent extends Record<string, unknown> {fileBeforeHash: string | null;}-function connectorBindingRoot(sourceId: string, source: ConnectorSource, binding: WorktreeBinding | null): string | null {- if (!binding) return null;+/** The connector binding's owner and incarnation checks; returns the paths they prove present. */+function checkedConnectorBinding(sourceId: string, source: ConnectorSource, binding: WorktreeBinding) {if (binding.owner_host_id !== localHostId() || !binding.local_path || !binding.coordination_path) {throw new OperationError('owner_unavailable', 'The connector canonical owner is unavailable on this host.');}if (binding.source_id !== sourceId || binding.source_incarnation !== source.incarnation || !source.local_path) {throw new OperationError('source_changed', 'The connector source does not match its canonical binding.');}- assertPhysicalRoot(binding.local_path, { worktreeId: binding.worktree_id, coordinationPath: binding.coordination_path });+ return { localPath: binding.local_path, coordinationPath: binding.coordination_path, sourcePath: source.local_path };+}++function connectorBindingRoot(sourceId: string, source: ConnectorSource, binding: WorktreeBinding | null): string | null {+ if (!binding) return null;+ const { localPath, coordinationPath, sourcePath } = checkedConnectorBinding(sourceId, source, binding);+ assertPhysicalRoot(localPath, { worktreeId: binding.worktree_id, coordinationPath });try {- const root = realpathSync(join(binding.local_path, binding.relative_path));+ const root = realpathSync(join(localPath, binding.relative_path));const configured = source.config[source.config.kind === 'google' ? 'g_dir' : 'gh_dir'];- const directory = typeof configured === 'string' && configured.length > 0 ? configured : source.local_path;- if (!containsPath(binding.local_path, root) || !statSync(root).isDirectory() || realpathSync(source.local_path) !== root || realpathSync(directory) !== root) {+ const directory = typeof configured === 'string' && configured.length > 0 ? configured : sourcePath;+ if (!containsPath(localPath, root) || !statSync(root).isDirectory() || realpathSync(sourcePath) !== root || realpathSync(directory) !== root) {throw new Error('root mismatch');}return root;@@ -132,9 +138,10 @@ export async function beginConnectorSync(engine: BrainEngine, sourceId: string,}const authority = await managedSyncAuthority(engine, sourceId, source.incarnation, source.local_path ?? '');const binding = await getWorktreeBinding(engine, sourceId);- const canonicalRoot = connectorBindingRoot(sourceId, source, binding);- if (binding) await (await acquireWorktree(binding))?.release();+ // The locked acquisition re-stamps a device-only physical-root change (#5604) before the root is asserted.+ if (binding) { checkedConnectorBinding(sourceId, source, binding); await (await acquireWorktree(binding, 0, undefined, engine))?.release(); }else authority.writer.databaseOnlyReason = 'connector_database';+ const canonicalRoot = connectorBindingRoot(sourceId, source, binding);const session = new ManagedConnectorSync(engine, sourceId, connector, source, authority, binding, canonicalRoot, opts.noEmbed === true, opts.noSchemaPack === true, opts.retryFailed === true, lease);await session.load();return session;@@ -349,7 +356,7 @@ export class ManagedConnectorSync {const prior = await selected(this.engine);let row = prior.row;if (mayRetry(row)) {- const lock = this.binding ? await acquireWorktree(this.binding, 1000) : null;+ const lock = this.binding ? await acquireWorktree(this.binding, 1000, undefined, this.engine) : null;try {if (this.binding && !lock) {await this.refuseRetryBlocker(this.engine);@@ -439,8 +446,9 @@ export async function prepareConnectorMutation(engine: BrainEngine, row: WriteResnapshot?.page.source_path != null && snapshot.page.source_path !== p.sourcePath) {throw new OperationError('revision_conflict', 'The connector page changed after admission.');}+ const deleteFile = p.kind === 'managed_connector_delete' ? await prepareFileTarget(engine, row, snapshot, null) : undefined;if (p.kind === 'managed_connector_delete') return { observedRevision: snapshot?.revision ?? null, sourceExclusive: true, validate,- file: await prepareFileTarget(engine, row, snapshot, null),+ file: deleteFile, ...databaseOnlyPublication(row, deleteFile),noop: !snapshot || snapshot.page.deleted_at != null, apply: async tx => {if (snapshot && snapshot.page.deleted_at == null) {await tx.createVersion(row.slug, { sourceId: row.source_id });@@ -459,9 +467,13 @@ export async function prepareConnectorMutation(engine: BrainEngine, row: WriteRethrow new OperationError('invalid_params', 'The connector import path is invalid.');}const activePack = p.noSchemaPack ? undefined : (await loadActivePackForEngine(engine, { remote: false, sourceId: row.source_id }).catch(() => null))?.manifest;- if (parseMarkdown(p.content, row.slug, { activePack }).slug !== row.slug) throw new OperationError('invalid_params', 'The connector content changes its page identity.');+ const parsed = parseMarkdown(p.content, row.slug, { activePack });+ if (parsed.slug !== row.slug) throw new OperationError('invalid_params', 'The connector content changes its page identity.');+ // #5567: carry materialized and database-only timeline rows forward into the connector render.+ const carried = await materializeTimeline(engine, parsed, row.slug, snapshot, 'preserving');+ const content = carried.materialized && snapshot ? serializePageToMarkdown({ ...snapshot.page, ...parsed, timeline: carried.timeline, type: parsed.typeExplicit ? parsed.type : snapshot.page.type }, parsed.tags) : p.content;let prepared: PreparedContentImport | undefined;- const result = await importFromContent(engine, row.slug, p.content, { sourceId: row.source_id, sourcePath: p.sourcePath,+ const result = await importFromContent(engine, row.slug, content, { sourceId: row.source_id, sourcePath: p.sourcePath,filename: basename(p.sourcePath).replace(/\.mdx?$/i, ''), noEmbed: true, allowEmptyOverwrite: true, activePack,prepareFrontmatter: page => {if (snapshot?.page.frontmatter.visibility === 'private') page.frontmatter.visibility = 'private';@@ -470,14 +482,14 @@ export async function prepareConnectorMutation(engine: BrainEngine, row: WriteReif (!prepared || prepared.slug !== row.slug) throw new OperationError('revision_conflict', result.error ?? 'A different page owns this connector content.');const ready = prepared;if (ready.observedRevision !== (snapshot?.revision ?? null)) throw new OperationError('revision_conflict', 'The connector page changed during preparation.');- const project = prepareCanonicalProjections(ready.parsedPage, row.slug, row.source_id);+ const project = await prepareCanonicalProjections(engine, ready.parsedPage, row.slug, row.source_id, snapshot, 'preserving');const tags = [...new Set([...(snapshot?.tags ?? []), ...ready.parsedPage.tags])].sort();const page: Page = { ...(snapshot?.page ?? { id: 0, slug: row.slug, source_id: row.source_id, created_at: new Date(row.created_at), updated_at: new Date(row.created_at) }), ...ready.parsedPage };const file = await connectorFileTarget(engine, row, snapshot, serializePageToMarkdown(page, tags), p.sourcePath, p.canonicalRoot);if (file && (file.path !== p.filePath || file.expectedBeforeHash !== p.fileBeforeHash)) throw new OperationError('source_changed', 'The connector canonical file changed during preparation.');return { observedRevision: ready.observedRevision, sourceExclusive: true,validate: async tx => { await validate(tx); await ready.validate(tx); },- file, noop: ready.noop, deferEmbedding: p.noEmbed, apply: async tx => {+ file, ...databaseOnlyPublication(row, file), noop: ready.noop, deferEmbedding: p.noEmbed, apply: async tx => {await ready.apply(tx);if (!ready.noop) { await project(tx); await sealPageTextProjection(tx, row.slug, row.source_id); }return { status: ready.noop ? 'skipped' : snapshot ? 'updated' : 'created', slug: row.slug, source_id: row.source_id,diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.tsindex 8d23cb7963..6e78ce1951 100644--- a/src/core/persistence/consumer.ts+++ b/src/core/persistence/consumer.ts@@ -1,4 +1,4 @@-import type { BrainEngine } from '../engine.ts';+import type { BrainEngine, ReservedConnection } from '../engine.ts';import type { GBrainConfig } from '../config.ts';import { claimNextWrite, compactWriteReceipts, getWriteRequestById, releaseUnpublishedClaim, renewWriteClaim } from './journal.ts';import { finishUnpublishedFailure, publishMutation, recoverPublication, type PreparedMutation } from './coordinator.ts';@@ -17,6 +17,13 @@ export class PersistenceConsumer {private timer: ReturnType<typeof setTimeout> | undefined;private tickPromise: Promise<void> | undefined;private wakeRequested = false;+ private fullTickRequested = true;+ private idleDelayMs = 0;+ private timerDueAt = 0;+ private nextDelayMs: number | undefined;+ private topologyRetryAfter = new Map<string, number>();+ private idleLane: { conn: ReservedConnection; release: () => Promise<void> } | undefined;+ private idleLaneRetryAt = 0;private active = new Set<Promise<void>>();private activeRoots = new Set<string>();private foregroundCounts = new Map<string, number>();@@ -36,18 +43,132 @@ export class PersistenceConsumer {private preparing = new Map<string, { request_id: string; started_at: string; deadline_exceeded: boolean; attempt: number }>();readonly hostId: string;constructor(readonly engine: BrainEngine, readonly config: GBrainConfig, readonly prepare: PrepareMutation,- private opts: { hostId?: string; concurrency?: number; pollMs?: number; phaseMs?: number; preparationMs?: number; onError?: (error: unknown) => void } = {}) {+ private opts: { hostId?: string; concurrency?: number; pollMs?: number; idleMaxMs?: number; phaseMs?: number; preparationMs?: number; onError?: (error: unknown) => void } = {}) {this.hostId = opts.hostId ?? localHostId();}- start(): void { this.stopping = false; this.abort = new AbortController(); this.schedule(0); }+ start(): void { this.stopping = false; this.abort = new AbortController(); this.fullTickRequested = true; this.idleDelayMs = this.pollMs; this.schedule(0); }+ /** Work admitted by this process: run a full tick now instead of waiting out the idle backoff. */+ wake(): void { this.idleDelayMs = this.pollMs; this.schedule(0); }+ private get pollMs(): number { return this.opts.pollMs ?? 250; }+ private get idleMaxMs(): number { return Math.max(this.pollMs, this.opts.idleMaxMs ?? 5000); }private schedule(ms: number): void {if (this.stopping) return;+ if (ms === 0) this.fullTickRequested = true;if (ms === 0 && this.tickPromise) { this.wakeRequested = true; return; }- if (this.timer && ms !== 0) return;+ if (this.timer && ms !== 0 && this.timerDueAt <= Date.now() + ms) return;if (this.timer) clearTimeout(this.timer);- this.timer = setTimeout(() => { this.timer = undefined; void this.tick().finally(() => this.schedule(this.opts.pollMs ?? 250)); }, ms);+ this.timerDueAt = Date.now() + ms;+ this.timer = setTimeout(() => {+ this.timer = undefined;+ void this.tick().finally(() => { const next = this.nextDelayMs ?? this.pollMs; this.nextDelayMs = undefined; this.schedule(next); });+ }, ms);this.timer.unref?.();}+ private backoff(): number {+ this.idleDelayMs = Math.min(Math.max(this.idleDelayMs, this.pollMs) * 2, this.idleMaxMs);+ return this.idleDelayMs;+ }+ /**+ * One statement on one connection that mirrors the selection predicates of+ * every worker a full tick fans out to. Rows those workers would skip+ * (retrying roots, capacity-blocked requests, failed projection jobs within+ * their retry window, topology recoveries that just failed to finish) do not+ * count, so unprocessable rows back off instead of pinning the fan-out.+ */+ private async hasWork(): Promise<boolean> {+ const now = Date.now();+ const excluded = [...this.activeRoots, ...[...this.rootRetryAfter].filter(([, at]) => at > now).map(([root]) => root)];+ for (const [id, at] of this.topologyRetryAfter) if (at <= now) this.topologyRetryAfter.delete(id);+ const retryingTopologies = [...this.topologyRetryAfter.keys()];+ const [row] = await this.phase('idle_probe', async signal => this.probeQuery<{ work: boolean }>(await this.acquireIdleLane(signal), `SELECT (+ EXISTS (SELECT 1 FROM persistence_requests r LEFT JOIN persistence_worktrees w ON w.id=r.worktree_id+ WHERE r.state='queued' AND (r.worktree_id IS NULL OR (w.owner_host_id=$1::uuid AND w.state='active'))+ AND NOT (COALESCE(r.worktree_id::text,'db:'||r.source_incarnation::text)=ANY($2::text[]))+ AND NOT EXISTS (SELECT 1 FROM persistence_effects blocked WHERE blocked.worktree_id=r.worktree_id AND blocked.recovery IS NOT NULL)+ AND NOT EXISTS (SELECT 1 FROM persistence_requests blocked WHERE blocked.worktree_id=r.worktree_id AND blocked.recovery IS NOT NULL)+ AND NOT EXISTS (SELECT 1 FROM persistence_requests earlier+ WHERE COALESCE(earlier.worktree_id::text,'db:'||earlier.source_incarnation::text)=COALESCE(r.worktree_id::text,'db:'||r.source_incarnation::text)+ AND earlier.sequence<r.sequence AND earlier.state IN ('queued','running','recovering'))+ AND ($3::boolean OR r.blocked_reason IS DISTINCT FROM 'writer_pool_capacity'))+ OR EXISTS (SELECT 1 FROM persistence_requests r JOIN persistence_worktrees w ON w.id=r.worktree_id+ WHERE w.owner_host_id=$1::uuid AND r.recovery IS NOT NULL AND NOT (r.worktree_id::text=ANY($2::text[])))+ OR EXISTS (SELECT 1 FROM persistence_requests r WHERE r.state='running' AND r.recovery IS NULL+ AND r.publication_started=false AND r.claim_expires_at<now()+ AND (r.worktree_id IS NULL OR EXISTS (SELECT 1 FROM persistence_worktrees w WHERE w.id=r.worktree_id AND w.owner_host_id=$1::uuid)))+ OR EXISTS (SELECT 1 FROM persistence_effects e LEFT JOIN persistence_worktrees w ON w.id=e.worktree_id+ WHERE (e.state='queued' OR e.state='running' AND e.claim_expires_at<now()) AND e.next_attempt_at<=now()+ AND (e.worktree_id IS NULL OR w.owner_host_id=$1::uuid) AND e.recovery IS NULL+ AND NOT EXISTS (SELECT 1 FROM persistence_effects blocked WHERE blocked.worktree_id=e.worktree_id AND blocked.recovery IS NOT NULL)+ AND NOT EXISTS (SELECT 1 FROM persistence_requests blocked WHERE blocked.worktree_id=e.worktree_id AND blocked.recovery IS NOT NULL)+ AND (e.kind='withdrawal-mirror' OR NOT EXISTS (SELECT 1 FROM persistence_effects mirror+ WHERE mirror.request_id=e.request_id AND mirror.kind='withdrawal-mirror' AND mirror.state<>'committed')))+ OR EXISTS (SELECT 1 FROM persistence_effects e JOIN persistence_worktrees w ON w.id=e.worktree_id+ WHERE e.recovery IS NOT NULL AND w.owner_host_id=$1::uuid AND e.next_attempt_at<=now())+ OR EXISTS (SELECT 1 FROM page_projection_jobs j JOIN sources s ON s.incarnation=j.source_incarnation+ JOIN pages p ON p.source_id=s.id AND p.slug=j.slug+ WHERE p.deleted_at IS NULL AND NOT s.archived AND p.page_kind IN ('markdown','code')+ AND (j.reason IS DISTINCT FROM 'rebuild_failed' OR j.updated_at<now()-interval '30 seconds'))+ OR EXISTS (SELECT 1 FROM persistence_topology_changes c+ JOIN persistence_worktrees w ON w.id=(c.recovery->>'worktreeId')::uuid+ WHERE c.recovery IS NOT NULL AND w.owner_host_id=$1::uuid AND NOT (c.id::text=ANY($4::text[])))+ ) AS work`, [this.hostId, excluded, publicationConcurrency(this.engine) > 0, retryingTopologies], signal));+ return row?.work === true;+ }+ /**+ * postgres.js hands out idle connections first-in-first-out, so a pooled+ * probe every few seconds would keep ceil(idle_timeout / interval) sockets+ * alive. Idle probes therefore share one reserved connection; the rest of+ * the pool drains through idle_timeout. Pools too small to spare a long-hold+ * permit fall back to pooled probes.+ */+ private async acquireIdleLane(signal?: AbortSignal): Promise<ReservedConnection | undefined> {+ if (this.idleLane) return this.idleLane.conn;+ if (this.engine.kind !== 'postgres' || this.stopping || Date.now() < this.idleLaneRetryAt) return undefined;+ const pool = (this.engine as { getPoolDiagnostics?: () => { poolMax: number | null; tracked: Record<string, number> } | null }).getPoolDiagnostics?.();+ // Only reserve from an otherwise idle pool: a saturated pool falls back to a cancellable pooled probe.+ if (!pool?.poolMax || pool.poolMax < 3 || Object.values(pool.tracked).some(count => count > 0)) return undefined;+ const held = Promise.withResolvers<void>();+ const reserved = Promise.withResolvers<ReservedConnection>();+ const done = this.engine.withReservedConnection(async conn => { reserved.resolve(conn); await held.promise; })+ .catch(error => { reserved.reject(error); });+ const aborted = Promise.withResolvers<undefined>();+ const onAbort = () => aborted.resolve(undefined);+ if (signal?.aborted) onAbort(); else signal?.addEventListener('abort', onAbort, { once: true });+ try {+ const conn = await Promise.race([reserved.promise, aborted.promise]);+ if (!conn) {+ reserved.promise.then(() => held.resolve(), () => {});+ return undefined;+ }+ this.idleLane = { conn, release: async () => { held.resolve(); await done; } };+ return conn;+ } catch {+ this.idleLaneRetryAt = Date.now() + 60_000;+ return undefined;+ } finally { signal?.removeEventListener('abort', onAbort); }+ }+ private async releaseIdleLane(): Promise<void> {+ const lane = this.idleLane;+ this.idleLane = undefined;+ await lane?.release();+ }+ private async probeQuery<T>(lane: ReservedConnection | undefined, sql: string, params: unknown[], signal?: AbortSignal): Promise<T[]> {+ if (!lane) return this.engine.executeRaw<T>(sql, params, { signal });+ const query = lane.executeRaw<T>(sql, params);+ if (!signal) return query;+ const aborted = Promise.withResolvers<never>();+ const onAbort = () => aborted.reject(signal.reason ?? new DOMException('aborted', 'AbortError'));+ if (signal.aborted) onAbort(); else signal.addEventListener('abort', onAbort, { once: true });+ try { return await Promise.race([query, aborted.promise]); }+ catch (error) {+ // The reserved query cannot be cancelled: stop using the lane now, return it to the pool once the query settles.+ const current = this.idleLane;+ if (current?.conn === lane) this.idleLane = undefined;+ this.idleLaneRetryAt = Date.now() + 60_000;+ void query.then(() => current?.release(), () => current?.release());+ throw error;+ } finally { signal.removeEventListener('abort', onAbort); }+ }async tick(): Promise<void> {if (this.tickPromise) return this.tickPromise;this.tickPromise = this.doTick().catch(error => { this.report(error); }).finally(() => {@@ -58,11 +179,41 @@ export class PersistenceConsumer {}private async doTick(): Promise<void> {if (this.stopping) return;+ const requested = this.fullTickRequested || this.active.size > 0;+ this.fullTickRequested = false;+ if (!requested) {+ let work: boolean;+ try { work = await this.hasWork(); }+ catch (error) {+ if (this.stopping) throw error;+ // One failure per tick: an unknown answer runs the full fan-out on the next tick.+ this.report(error);+ this.fullTickRequested = true;+ this.nextDelayMs = this.backoff();+ return;+ }+ if (this.stopping) return;+ if (!work) {+ this.nextDelayMs = this.backoff();+ if (!this.maintenanceWorker && Date.now() >= this.nextMaintenance) {+ this.nextMaintenance = Date.now() + 300_000;+ await this.phase('refresh_roots', signal => refreshManagedFilesystemRoots(this.engine,+ this.engine.kind === 'pglite' ? this.config.database_path : undefined, signal));+ this.maintenanceWorker = compactWriteReceipts(this.engine).catch(error => this.report(error))+ .finally(() => { this.maintenanceWorker = undefined; });+ }+ return;+ }+ }+ await this.releaseIdleLane();+ this.idleDelayMs = this.pollMs;+ this.nextDelayMs = this.pollMs;await this.phase('refresh_roots', signal => refreshManagedFilesystemRoots(this.engine,this.engine.kind === 'pglite' ? this.config.database_path : undefined, signal));if (this.stopping) return;if (!this.topologyWorker) this.topologyWorker = import('./topology-recovery.ts')- .then(({ recoverSourceTopologies }) => recoverSourceTopologies(this.engine, { hostId: this.hostId, limit: 2 }))+ .then(({ recoverSourceTopologies }) => recoverSourceTopologies(this.engine, { hostId: this.hostId, limit: 2,+ onAttempt: (id, recovered) => { if (recovered) this.topologyRetryAfter.delete(id); else this.topologyRetryAfter.set(id, Date.now() + 30_000); } })).catch(error => this.report(error)).finally(() => { this.topologyWorker = undefined; });if (!this.effectsWorker) this.effectsWorker = runPersistenceEffects(this.engine, this.config,{ hostId: this.hostId, limit: 2, signal: this.abort.signal }).catch(error => this.report(error))@@ -242,6 +393,7 @@ export class PersistenceConsumer {this.abort.abort();if (this.timer) { clearTimeout(this.timer); this.timer = undefined; }await this.tickPromise;+ await this.releaseIdleLane();await Promise.allSettled([...this.active]);await this.projectionWorker;await this.effectsWorker;diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.tsindex 43af2b5ba4..2c3ee6a90b 100644--- a/src/core/persistence/coordinator.ts+++ b/src/core/persistence/coordinator.ts@@ -29,6 +29,8 @@ interface PreparedMutationBase {additionalPageKeys?: readonly {sourceId:string;slug:string}[];noop?: boolean;deferEmbedding?: boolean;+ /** Why a page write bound to a worktree publishes no file (receipt `write_through.skipped`). */+ databaseOnlyReason?: 'db_only';/** Must perform only transaction-composable database work. */apply(tx: BrainEngine): Promise<Record<string, unknown>>;validate?(tx: BrainEngine): Promise<void>;@@ -121,7 +123,7 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, prawait releaseUnpublishedClaim(engine, row, 'owner_unavailable');return (await getWriteRequestById(engine, row.id))!;}- lock = await acquireWorktree(binding);+ lock = await acquireWorktree(binding, 0, undefined, engine);if (!lock) {await releaseUnpublishedClaim(engine, row, 'writer_busy');return (await getWriteRequestById(engine, row.id))!;@@ -231,7 +233,7 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, prconst final = skill ? null : await tx.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });if (final) outcome.revision = final.revision;outcome.persistence = { mode: files.length ? 'filesystem' : 'database', ...(files.length ? { file_written: !prepared.noop } : {}), ...(skill ? { git_state: 'not_requested' } : {}) };- outcome.write_through = files.length ? { written: !prepared.noop } : { written: false, skipped: row.authority.databaseOnlyReason ?? 'no_repo_configured' };+ outcome.write_through = files.length ? { written: !prepared.noop } : { written: false, skipped: prepared.databaseOnlyReason ?? row.authority.databaseOnlyReason ?? 'no_repo_configured' };if (row.operation === 'put_page' && row.authority.remote && row.authority.databaseOnlyReason === 'no_repo_configured') outcome.write_through = withNoRepoWriteThroughWarning(outcome.write_through as { written: boolean; skipped?: string }, row.source_id);await queuePublicationEffects(tx, row, final?.revision, outcome, prepared);await hooks.boundary?.('before_commit', row);@@ -274,7 +276,7 @@ export async function recoverPublication(engine: BrainEngine, id: string, hostIdassertMutationProtocol(row);const binding = await getWorktreeBinding(engine, row.source_id, hostId);if (!binding || binding.owner_host_id !== hostId) throw new OperationError('owner_unavailable', 'Recovery requires the canonical owner.');- const lock = alreadyLocked ? null : await acquireWorktree(binding);+ const lock = alreadyLocked ? null : await acquireWorktree(binding, 0, undefined, engine);if (!alreadyLocked && !lock) return row;const releaseCapacity = capacityAlreadyHeld ? null : tryAcquirePublicationCapacity(engine);try {diff --git a/src/core/persistence/effect-journal.ts b/src/core/persistence/effect-journal.tsindex 03467ca398..034602cf0e 100644--- a/src/core/persistence/effect-journal.ts+++ b/src/core/persistence/effect-journal.ts@@ -4,7 +4,7 @@ import type { BrainEngine } from '../engine.ts';import { OperationError } from '../ops/contract.ts';import type { PreparedMutation } from './coordinator.ts';import { sha256 } from './digest.ts';-import type { EffectKind, PersistenceEffect, EffectRequest } from './effect-model.ts';+import { PARK_AFTER_FAILURES, type EffectKind, type PersistenceEffect, type EffectRequest } from './effect-model.ts';import type { SqlEngine } from './model.ts';import { isFactsExtractionEnabled } from '../facts/extract.ts';import { resolveDefaultVisibility } from '../facts/visibility.ts';@@ -67,15 +67,28 @@ export async function renewPersistenceEffectClaim(engine: SqlEngine, effect: Per}export async function advanceEffectCursor(engine: SqlEngine, effect: PersistenceEffect, slug: string): Promise<void> {+ const retrying = effect.data.retry_slugs ?? [];+ if (retrying.includes(slug)) {+ // A retried parked target finishes without moving the scan cursor. Each+ // remaining retried target keeps a single authorized attempt.+ const { retry_slugs: _retry, target_failures: _failures, failing_target: _target, ...data } = effect.data;+ const remaining = retrying.filter(candidate => candidate !== slug);+ await requeueEffect(engine, effect, remaining.length ? { ...data, retry_slugs: remaining, target_failures: PARK_AFTER_FAILURES - 1 } : data, null, 0);+ return;+ }await engine.executeRaw(`UPDATE persistence_effects SET state='queued',data=jsonb_set(- CASE WHEN kind='embedding' THEN jsonb_set(data,'{embedding_attempt_base}',to_jsonb(attempts)) ELSE data END,'{after_slug}',to_jsonb($3::text)),+ CASE WHEN kind='embedding' THEN jsonb_set(data,'{embedding_attempt_base}',to_jsonb(attempts)) ELSE data-'target_failures'-'failing_target' END,'{after_slug}',to_jsonb($3::text)),execution_token=NULL,claim_expires_at=NULL,next_attempt_at=now(),error_code=NULL,updated_at=now()WHERE id=$1 AND execution_token=$2::uuid AND recovery IS NULL AND ${PERSISTENCE_PROTOCOL_PREDICATE}`, [effect.id, effect.execution_token, slug]);}+/** An effect with parked targets finishes as failed (`targets_parked`), never as committed. */export async function completeEffect(engine: SqlEngine, effect: PersistenceEffect, outcome: Record<string, unknown> = {}): Promise<void> {- await engine.executeRaw(`UPDATE persistence_effects SET state='committed',execution_token=NULL,claim_expires_at=NULL,error_code=NULL,+ await engine.executeRaw(`UPDATE persistence_effects SET+ state=CASE WHEN jsonb_array_length(COALESCE(data->'parked','[]'::jsonb))>0 THEN 'failed' ELSE 'committed' END,+ error_code=CASE WHEN jsonb_array_length(COALESCE(data->'parked','[]'::jsonb))>0 THEN 'targets_parked' END,+ data=data-'retry_slugs'-'target_failures'-'failing_target',execution_token=NULL,claim_expires_at=NULL,outcome=$3::text::jsonb,updated_at=now() WHERE id=$1 AND execution_token=$2::uuid AND recovery IS NULL AND ${PERSISTENCE_PROTOCOL_PREDICATE}`,[effect.id, effect.execution_token, JSON.stringify(outcome)]);}@@ -84,6 +97,18 @@ export async function retryEffect(engine: SqlEngine, effect: PersistenceEffect,next_attempt_at=now()+($4::double precision*interval '1 millisecond'),updated_at=now()WHERE id=$1 AND execution_token=$2::uuid AND ${PERSISTENCE_PROTOCOL_PREDICATE}`, [effect.id, effect.execution_token, reason, delayMs]);}+/** Release a claim with replacement bookkeeping; parking never applies while recovery is recorded. */+export async function requeueEffect(engine: SqlEngine, effect: PersistenceEffect, data: PersistenceEffect['data'], reason: string | null, delayMs: number): Promise<void> {+ await engine.executeRaw(`UPDATE persistence_effects SET state='queued',data=$3::text::jsonb,execution_token=NULL,claim_expires_at=NULL,error_code=$4,+ next_attempt_at=now()+($5::double precision*interval '1 millisecond'),updated_at=now()+ WHERE id=$1 AND execution_token=$2::uuid AND recovery IS NULL AND ${PERSISTENCE_PROTOCOL_PREDICATE}`,+ [effect.id, effect.execution_token, JSON.stringify(data), reason, delayMs]);+}+export async function parkEffect(engine: SqlEngine, effect: PersistenceEffect, data: PersistenceEffect['data']): Promise<void> {+ await engine.executeRaw(`UPDATE persistence_effects SET state='failed',data=$3::text::jsonb,execution_token=NULL,claim_expires_at=NULL,+ error_code='targets_parked',updated_at=now() WHERE id=$1 AND execution_token=$2::uuid AND recovery IS NULL AND ${PERSISTENCE_PROTOCOL_PREDICATE}`,+ [effect.id, effect.execution_token, JSON.stringify(data)]);+}export async function failEffect(engine: SqlEngine, effect: PersistenceEffect, reason: string): Promise<void> {await engine.executeRaw(`UPDATE persistence_effects SET state='failed',execution_token=NULL,claim_expires_at=NULL,error_code=$3,updated_at=now()WHERE id=$1 AND execution_token=$2::uuid AND recovery IS NULL AND ${PERSISTENCE_PROTOCOL_PREDICATE}`, [effect.id, effect.execution_token, reason]);diff --git a/src/core/persistence/effect-model.ts b/src/core/persistence/effect-model.tsindex 2ba2220359..33e947cfeb 100644--- a/src/core/persistence/effect-model.ts+++ b/src/core/persistence/effect-model.ts@@ -2,6 +2,9 @@ import type { WriteRequest } from './model.ts';import type { WithdrawalTarget } from '../facts/withdrawal-discovery.ts';export type EffectKind = 'git' | 'embedding' | 'withdrawal-mirror' | 'facts-backstop';+export interface ParkedTarget { slug?: string; error_code: string }+/** A Git or withdrawal target parks after this many consecutive execution failures. */+export const PARK_AFTER_FAILURES = 5;export interface EffectRecovery {version: 1;kind: 'withdrawal-mirror';@@ -26,7 +29,17 @@ export interface PersistenceEffect {source_id: string;source_incarnation: string;worktree_id: string | null;- data: { version?: 2; targets?: WithdrawalTarget[]; slug?: string; page_id?: number; relative_path?: string; expected_hash?: string | null; after_slug?: string; source_id?: string; source_scan?: boolean; visibility?: 'private' | 'world'; embedding_attempt_base?: number; embedding_retry_base?: number };+ data: { version?: 2; targets?: WithdrawalTarget[]; slug?: string; page_id?: number; relative_path?: string; expected_hash?: string | null; after_slug?: string; source_id?: string; source_scan?: boolean; visibility?: 'private' | 'world'; embedding_attempt_base?: number; embedding_retry_base?: number;+ /** Consecutive execution failures of the current Git or withdrawal target. */+ target_failures?: number;+ /** The target `target_failures` belongs to; a different target starts from zero. */+ failing_target?: string;+ /** Targets set aside after repeated failures; a slugless entry parks the whole effect. */+ parked?: ParkedTarget[];+ /** Parked scan targets an explicit retry authorized for one more attempt. */+ retry_slugs?: string[];+ /** Explicit retry authorizations granted to this effect's parked targets. */+ retried?: number };state: 'queued' | 'running' | 'committed' | 'failed';execution_token: string | null;claim_expires_at: string | Date | null;diff --git a/src/core/persistence/effect-recovery.ts b/src/core/persistence/effect-recovery.tsindex b7ed01af9e..82b68ac0d1 100644--- a/src/core/persistence/effect-recovery.ts+++ b/src/core/persistence/effect-recovery.ts@@ -15,6 +15,7 @@ import type { EffectRecovery, PersistenceEffect } from './effect-model.ts';import { tryAcquirePublicationCapacity } from './pool-capacity.ts';import { assertRecoveryStagingAbsent, cleanupRecoveryStaging, upgradeRecoveryStaging } from './staging.ts';import { declarePersistenceProtocol } from './protocol.ts';+import { advanceEffectCursor } from './effect-journal.ts';export async function guardEffectSource(tx: BrainEngine, effect: PersistenceEffect, hostId: string): Promise<WorktreeBinding | null> {await declarePersistenceProtocol(tx);@@ -113,9 +114,9 @@ export async function recoverEffectPublication(engine: BrainEngine, effect: Pers}await materializePageSnapshot(tx, snapshot);await clearRecovery(tx, current);- // One page per transaction/cursor checkpoint bounds work and restart cost.- await tx.executeRaw(`UPDATE persistence_effects SET state='queued',data=jsonb_set(data,'{after_slug}',to_jsonb($2::text)),- execution_token=NULL,claim_expires_at=NULL,next_attempt_at=now(),error_code=NULL,updated_at=now() WHERE id=$1`, [current.id, record.slug]);+ // One page per transaction/cursor checkpoint bounds work and restart cost;+ // a retried parked target is consumed without rewinding the cursor.+ await advanceEffectCursor(tx, current, record.slug);await hooks.boundary?.('before_mirror_commit');}); } finally { releaseCapacity(); }}diff --git a/src/core/persistence/effect-retry.ts b/src/core/persistence/effect-retry.tsindex f41472b5fe..296b095aab 100644--- a/src/core/persistence/effect-retry.ts+++ b/src/core/persistence/effect-retry.ts@@ -8,7 +8,7 @@ import { authorizeStoredRequest, authorizeWrite, submissionAuthority } from './aimport { existingLocalHostId } from './identity.ts';import { guardEffectSource } from './effect-recovery.ts';import { assertEmbeddingEffectEnabled, readEmbeddingEffectProjection, selectedEffectPage } from './effects.ts';-import type { PersistenceEffect } from './effect-model.ts';+import { PARK_AFTER_FAILURES, type PersistenceEffect } from './effect-model.ts';import type { WriteRequest } from './model.ts';import { targetedWithdrawalEffect, upgradeWithdrawalEffect } from './effect-targets.ts';@@ -43,6 +43,74 @@ async function mountedEmbeddingSignature(engine: BrainEngine): Promise<string> {return `${model}:${dimensions}`;}+/**+ * #5612: parked Git and withdrawal effects of one committed request. Returns+ * null when the request has none, so the caller falls through to embedding+ * retry. Each invocation authorizes exactly one more attempt per parked target.+ */+export async function retryParkedEffects(engine: BrainEngine, sourceId: string, requestId: string, dryRun: boolean): Promise<Record<string, unknown> | null> {+ const [request, ambiguous] = await engine.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE source_id=$1 AND request_id=$2::uuid LIMIT 2', [sourceId, requestId]);+ if (!request || ambiguous) return null;+ const tracked = await engine.executeRaw<PersistenceEffect>(`SELECT * FROM persistence_effects WHERE request_id=$1::uuid+ AND kind IN ('git','withdrawal-mirror') AND (data ? 'parked' OR data ? 'retried') ORDER BY kind`, [request.id]);+ if (!tracked.length) return null;+ const hostId = existingLocalHostId();+ if (!hostId) throw new OperationError('permission_denied', 'Retry requires the registered local CLI host.');+ return engine.transaction(async tx => {+ await authorizeStoredRequest(tx, request, true);+ const authority = await submissionAuthority({ engine: tx, remote: false, sourceId } as OperationContext,+ request.operation, sourceId, request.source_incarnation, request.slug);+ await authorizeWrite(tx, authority, request.operation, request.slug, true);+ const effects = [];+ for (const selected of tracked) {+ await guardEffectSource(tx, selected, hostId);+ const [effect] = await tx.executeRaw<PersistenceEffect>('SELECT * FROM persistence_effects WHERE id=$1 FOR UPDATE', [selected.id]);+ const parked = effect.data.parked ?? [];+ const summary = { kind: effect.kind, parked_targets: parked.length, targets: parked.slice(0, 20), retried: effect.data.retried ?? 0 };+ if (effect.state !== 'failed' || effect.error_code !== 'targets_parked') {+ effects.push({ ...summary, state: effect.state, terminal: effect.state === 'committed', action: 'unchanged' });+ continue;+ }+ if (effect.execution_token !== null || effect.recovery) throw new OperationError('write_claim_lost', 'A parked effect still has a claim or recovery record; inspect it before retrying.');+ if (dryRun) { effects.push({ ...summary, state: 'parked', terminal: true, action: 'would_retry' }); continue; }+ const { parked: _parked, retry_slugs: retrying = [], failing_target: _target, ...data } = effect.data;+ const scanning = targetedWithdrawalEffect(effect) || effect.data.source_scan === true;+ const slugs = scanning ? [...new Set([...retrying, ...parked.flatMap(entry => entry.slug ? [entry.slug] : [])])] : [];+ const [updated] = await tx.executeRaw<{ state: string }>(`UPDATE persistence_effects SET state='queued',data=$2::text::jsonb,error_code=NULL,+ next_attempt_at=now(),claim_expires_at=NULL,updated_at=now() WHERE id=$1 AND state='failed' AND error_code='targets_parked'+ AND execution_token IS NULL AND recovery IS NULL RETURNING state`,+ [effect.id, JSON.stringify({ ...data, ...(slugs.length ? { retry_slugs: slugs } : {}), target_failures: PARK_AFTER_FAILURES - 1,+ ...(!scanning && (effect.data.slug ?? effect.data.relative_path) ? { failing_target: effect.data.slug ?? effect.data.relative_path } : {}),+ retried: (effect.data.retried ?? 0) + 1 })]);+ if (!updated) throw new OperationError('write_claim_lost', 'The parked effect changed during retry approval.');+ effects.push({ ...summary, state: 'queued', terminal: false, action: 'retry_queued' });+ }+ const queued = effects.some(effect => effect.action === 'retry_queued');+ return { request_id: request.request_id, source_id: sourceId, dry_run: dryRun, effects,+ next_action: dryRun ? 'Fix the recorded cause, then run the same command without --dry-run to authorize one more attempt per parked target.'+ : queued ? 'The resident owner makes one more attempt per parked target. Rerun this command with --dry-run to read the terminal state; a target that fails again parks again.'+ : 'No parked target remains for this request.' };+ });+}++/**+ * `retry-effects` dispatch: parked Git/withdrawal work that still needs action+ * wins; otherwise the embedding obligation is handled, with any settled parked+ * history reported alongside (or alone when the request has no retryable embedding).+ */+export async function retryRequestEffects(engine: BrainEngine, sourceId: string, requestId: string, dryRun: boolean, baseConfig?: GBrainConfig,+ policy: 'owner' | 'mounted_database' = 'owner'): Promise<Record<string, unknown>> {+ const parked = await retryParkedEffects(engine, sourceId, requestId, dryRun);+ if (parked && (parked.effects as Array<{ state: string }>).some(effect => effect.state !== 'committed')) return parked;+ try {+ const embedding = await retryEmbeddingEffect(engine, sourceId, requestId, dryRun, baseConfig, policy);+ return parked ? { ...embedding, parked_effects: parked.effects } : embedding;+ } catch (error) {+ if (parked && error instanceof OperationError && ['invalid_params', 'effect_not_failed'].includes(error.code)) return parked;+ throw error;+ }+}+export async function retryEmbeddingEffect(engine: BrainEngine, sourceId: string, requestId: string, dryRun: boolean, baseConfig?: GBrainConfig,policy: 'owner' | 'mounted_database' = 'owner'): Promise<Record<string, unknown>> {const requests = await engine.executeRaw<WriteRequest>(`SELECT r.* FROM persistence_requests r WHERE source_id=$1 AND request_id=$2::uuiddiff --git a/src/core/persistence/effect-schema.ts b/src/core/persistence/effect-schema.tsindex d2068ac56c..4c3a0a3856 100644--- a/src/core/persistence/effect-schema.ts+++ b/src/core/persistence/effect-schema.ts@@ -31,3 +31,6 @@ CREATE INDEX IF NOT EXISTS persistence_effects_pending ON persistence_effects(neCREATE INDEX IF NOT EXISTS persistence_effects_recovery ON persistence_effects(worktree_id)WHERE recovery IS NOT NULL;`;+/** Effects holding parked Git/withdrawal targets, for the bounded doctor listing. */+export const PERSISTENCE_EFFECT_PARKED_INDEX_SQL = `CREATE INDEX IF NOT EXISTS persistence_effects_parked+ ON persistence_effects(id) WHERE data ? 'parked'`;diff --git a/src/core/persistence/effects.ts b/src/core/persistence/effects.tsindex 8505c7ad53..0624ba6ba2 100644--- a/src/core/persistence/effects.ts+++ b/src/core/persistence/effects.ts@@ -23,11 +23,12 @@ import { acquireWorktree, getWorktreeBinding, type WorktreeBinding } from './ownimport { persistenceFileHash, transientDatabaseFailure } from './coordinator.ts';import { sha256 } from './digest.ts';import { prepareFileTarget } from './page-prepare.ts';-import { advanceEffectCursor, claimPersistenceEffect, completeEffect, failEffect, renewPersistenceEffectClaim, retryEffect } from './effect-journal.ts';+import { isSourceDbOnlySlug } from './source-storage.ts';+import { advanceEffectCursor, claimPersistenceEffect, completeEffect, failEffect, parkEffect, renewPersistenceEffectClaim, requeueEffect, retryEffect } from './effect-journal.ts';import { guardEffectSource, recoverEffectPublication, reserveEffectRecovery } from './effect-recovery.ts';import { publishGitEffect } from './effect-git.ts';import { dispatchFactsBackstopEffect } from './effect-facts.ts';-import type { EffectRecovery, PersistenceEffect } from './effect-model.ts';+import { PARK_AFTER_FAILURES, type EffectRecovery, type PersistenceEffect } from './effect-model.ts';import { recoveryStagingFile } from './staging.ts';import { selectEffectRecoveries } from './effect-recovery-scan.ts';import { nativeFileTarget } from './native-file-target.ts';@@ -42,6 +43,12 @@ export interface EffectWorkerOptions {}export async function selectedEffectPage(engine: BrainEngine, effect: PersistenceEffect): Promise<PageSnapshot | null> {+ for (const slug of effect.data.retry_slugs ?? []) {+ const snapshot = await engine.readPageSnapshot(slug, { sourceId: effect.source_id, includeDeleted: true });+ if (snapshot?.sourceIncarnation !== effect.source_incarnation) continue;+ if (targetedWithdrawalEffect(effect) && effect.data.targets!.find(target => target.slug === slug)?.page_id !== snapshot.page.id) continue;+ return snapshot;+ }if (targetedWithdrawalEffect(effect)) {for (const target of effect.data.targets!) {if (effect.data.after_slug !== undefined && target.slug <= effect.data.after_slug) continue;@@ -80,9 +87,13 @@ async function materializeAndAdvance(engine: BrainEngine, effect: PersistenceEff});}-async function mirrorPage(engine: BrainEngine, effect: PersistenceEffect, binding: WorktreeBinding | null, opts: EffectWorkerOptions): Promise<void> {+/** The target a failing attempt was working on; unset means the failure is effect-wide. */+interface EffectAttempt { target?: string }++async function mirrorPage(engine: BrainEngine, effect: PersistenceEffect, binding: WorktreeBinding | null, opts: EffectWorkerOptions, attempt: EffectAttempt): Promise<void> {const snapshot = await selectedEffectPage(engine, effect);if (!snapshot) { await completeEffect(engine, effect); return; }+ attempt.target = snapshot.page.slug;if (snapshot.sourceIncarnation !== effect.source_incarnation) throw new OperationError('source_changed', 'The mirror source was replaced.');const content = serializePageToMarkdown(snapshot.page, snapshot.tags);const file = binding?.local_path ? await prepareFileTarget(engine, { ...effect, slug: snapshot.page.slug }, snapshot, content, opts.hostId, { allowMissing: true }) : undefined;@@ -101,12 +112,13 @@ async function mirrorPage(engine: BrainEngine, effect: PersistenceEffect, bindinawait recoverEffectPublication(engine, effect, opts.hostId, opts);}-async function gitPage(engine: BrainEngine, effect: PersistenceEffect, binding: WorktreeBinding | null, opts: EffectWorkerOptions): Promise<void> {+async function gitPage(engine: BrainEngine, effect: PersistenceEffect, binding: WorktreeBinding | null, opts: EffectWorkerOptions, attempt: EffectAttempt): Promise<void> {if (!binding?.local_path) { await completeEffect(engine, effect, { git: 'skipped', reason: 'no_repo_configured' }); return; }const snapshot = await selectedEffectPage(engine, effect);let path: string;if (targetedWithdrawalEffect(effect) || effect.data.source_scan) {if (!snapshot) { await completeEffect(engine, effect); return; }+ attempt.target = snapshot.page.slug;const file = await prepareFileTarget(engine, { ...effect, slug: snapshot.page.slug }, snapshot,snapshot.page.deleted_at ? null : serializePageToMarkdown(snapshot.page, snapshot.tags), opts.hostId, { allowMissing: true });if (!file) throw new OperationError('source_changed', 'The Git binding changed.');@@ -115,12 +127,21 @@ async function gitPage(engine: BrainEngine, effect: PersistenceEffect, binding:if (snapshot.page.deleted_at && existsSync(path)) { await finishPage(engine, effect, snapshot, { reason: 'deleted_page_file_present' }); return; }} else {if (!effect.data.relative_path) throw new OperationError('storage_error', 'The Git effect lost its target.');+ attempt.target = effect.data.slug ?? effect.data.relative_path;path = join(binding.local_path, effect.data.relative_path);if (!isWriteTargetContained(path, join(binding.local_path, binding.relative_path))) throw new OperationError('source_changed', 'The Git target escaped its registered source.');path = nativeFileTarget(binding.local_path, path, 'git_target_unsafe');if (persistenceFileHash(path) !== effect.data.expected_hash) { await completeEffect(engine, effect, { git: 'superseded' }); return; }}if (!isWriteTargetContained(path, join(binding.local_path, binding.relative_path))) throw new OperationError('source_changed', 'The Git target escaped its registered source.');+ // Declared db_only content stays out of Git. Its gitignored local cache file+ // is invisible to `git status`, so publishing it would be refused as unsafe.+ // An invalid gbrain.yml (logged by the loader) publishes as before.+ const slug = snapshot?.page.slug ?? effect.data.slug;+ if (slug && isSourceDbOnlySlug(join(binding.local_path, binding.relative_path), slug, 'not_db_only')) {+ await finishPage(engine, effect, snapshot, { git: 'skipped', reason: 'db_only' });+ return;+ }const result = await publishGitEffect(binding.local_path, relative(binding.local_path, path).split(sep).join('/'), opts.signal);if (result.reason === 'durability_not_enabled') await completeEffect(engine, effect, result);else await finishPage(engine, effect, snapshot, result);@@ -227,7 +248,7 @@ function embeddingStorageFailure(error: unknown): unknown {? new OperationError('embedding_storage_unavailable', 'Embedding policy or claim storage is temporarily unavailable.') : error;}-async function recordFailure(engine: BrainEngine, effect: PersistenceEffect, error: unknown, signal?: AbortSignal): Promise<void> {+async function recordFailure(engine: BrainEngine, effect: PersistenceEffect, error: unknown, signal?: AbortSignal, target?: string): Promise<void> {const code = error instanceof OperationError ? error.code : 'effect_unavailable';// Source replacement is final only without recovery. Unknown physical bytes// retain their record and continue to block this root for explicit repair.@@ -258,7 +279,41 @@ async function recordFailure(engine: BrainEngine, effect: PersistenceEffect, err: transientBackoffMs(attempt - 1);await retryEffect(engine, effect, reason, delay); return;}- await retryEffect(engine, effect, code, ['projection_pending', 'revision_conflict', 'writer_busy', 'writer_pool_capacity'].includes(code) ? 250 : 30_000);+ if (CONTENTION_CODES.includes(code)) { await retryEffect(engine, effect, code, 250); return; }+ if (!['git', 'withdrawal-mirror'].includes(effect.kind) || DEPENDENCY_CODES.includes(code) || signal?.aborted || transientDatabaseFailure(error)) {+ await retryEffect(engine, effect, code, 30_000); return;+ }+ const [current] = await engine.executeRaw<{ recovering: boolean }>('SELECT recovery IS NOT NULL AS recovering FROM persistence_effects WHERE id=$1', [effect.id]);+ if (current?.recovering) { await retryEffect(engine, effect, code, 30_000); return; }+ // A retried parked target has exactly one authorized attempt; otherwise the+ // counter only accumulates while the same target keeps failing.+ const prior = target !== undefined && effect.data.retry_slugs?.includes(target) ? PARK_AFTER_FAILURES - 1+ : effect.data.failing_target === target ? effect.data.target_failures ?? 0 : 0;+ const failures = prior + 1;+ if (failures < PARK_AFTER_FAILURES) {+ await requeueEffect(engine, effect, { ...effect.data, target_failures: failures, ...(target === undefined ? {} : { failing_target: target }) }, code, 30_000);+ return;+ }+ await parkEffectTarget(engine, effect, code, target);+}++/** Waits that say nothing about the target never count toward parking. */+const CONTENTION_CODES = ['projection_pending', 'revision_conflict', 'writer_busy', 'writer_pool_capacity'];+const DEPENDENCY_CODES = ['recovery_required', 'owner_unavailable', 'write_claim_lost', 'queue_capacity'];++/**+ * A scan sets its failing target aside and moves on; a single-target effect,+ * or a failure outside any target, parks the whole effect. Parked work stays+ * retained until `gbrain sources writer retry-effects` authorizes another attempt.+ */+async function parkEffectTarget(engine: BrainEngine, effect: PersistenceEffect, code: string, target: string | undefined): Promise<void> {+ const { target_failures: _failures, failing_target: _target, retry_slugs: retrying = [], ...data } = effect.data;+ const scanning = target !== undefined && (targetedWithdrawalEffect(effect) || effect.data.source_scan === true);+ const parked = [...(effect.data.parked ?? []), { ...(target ?? effect.data.slug ? { slug: target ?? effect.data.slug } : {}), error_code: code }];+ if (!scanning) { await parkEffect(engine, effect, { ...data, ...(retrying.length ? { retry_slugs: retrying } : {}), parked }); return; }+ const remaining = retrying.filter(slug => slug !== target);+ await requeueEffect(engine, effect, { ...data, parked, ...(retrying.includes(target) ? {} : { after_slug: target }),+ ...(remaining.length ? { retry_slugs: remaining, target_failures: PARK_AFTER_FAILURES - 1 } : {}) }, code, 0);}/** Bounded, idempotent work. Recovery obtains kernel exclusion before a DB claim. */@@ -270,7 +325,7 @@ export async function runPersistenceEffects(engine: BrainEngine, config: GBrainCif (opts.signal?.aborted) return;const binding = await getWorktreeBinding(engine, recovery.source_id, opts.hostId);if (!binding) continue;- const lock = await acquireWorktree(binding);+ const lock = await acquireWorktree(binding, 0, undefined, engine);if (!lock) continue;let claimed: PersistenceEffect | undefined;try {@@ -286,12 +341,13 @@ export async function runPersistenceEffects(engine: BrainEngine, config: GBrainCconst claimed = await claimPersistenceEffect(engine, opts.hostId);if (!claimed) return;let effect = claimed;+ const attempt: EffectAttempt = {};let lock: Awaited<ReturnType<typeof acquireWorktree>> = null;try {const binding = effect.worktree_id ? await getWorktreeBinding(engine, effect.source_id, opts.hostId) : null;if (effect.worktree_id && !['embedding', 'facts-backstop'].includes(effect.kind)) {if (!binding) throw new OperationError('owner_unavailable', 'The canonical effect owner is unavailable.');- lock = await acquireWorktree(binding);+ lock = await acquireWorktree(binding, 0, undefined, engine);if (!lock) throw new OperationError('writer_busy', 'The canonical worktree is busy.');}await engine.transaction(async tx => {@@ -302,11 +358,11 @@ export async function runPersistenceEffects(engine: BrainEngine, config: GBrainC}});effect = await upgradeWithdrawalEffect(engine, effect, opts.hostId);- if (effect.kind === 'withdrawal-mirror') await mirrorPage(engine, effect, binding, opts);- else if (effect.kind === 'git') await gitPage(engine, effect, binding, opts);+ if (effect.kind === 'withdrawal-mirror') await mirrorPage(engine, effect, binding, opts, attempt);+ else if (effect.kind === 'git') await gitPage(engine, effect, binding, opts, attempt);else if (effect.kind === 'facts-backstop') await dispatchFactsBackstopEffect(engine, effect, opts.hostId);else await embedPage(engine, config, effect, opts);- } catch (error) { await recordFailure(engine, effect, error, opts.signal); }+ } catch (error) { await recordFailure(engine, effect, error, opts.signal, attempt.target); }finally { await lock?.release(); }}}diff --git a/src/core/persistence/facts-maintenance.ts b/src/core/persistence/facts-maintenance.tsindex 735561b291..e5ca47aaf7 100644--- a/src/core/persistence/facts-maintenance.ts+++ b/src/core/persistence/facts-maintenance.ts@@ -152,7 +152,7 @@ export async function prepareManagedFactsSession(ctx: FactsBackstopCtx,if (writeThrough && binding) {if (binding.state !== 'active' || !binding.owner_host_id) throw new OperationError('owner_unavailable', 'The canonical fact writer is unavailable; extraction has not started.');if (binding.owner_host_id === localHostId()) {- const lock = await acquireWorktree(binding);+ const lock = await acquireWorktree(binding, 0, undefined, engine);if (!lock) throw new OperationError('writer_lock_unavailable', 'The canonical fact writer is busy; extraction has not started.');await lock.release();}diff --git a/src/core/persistence/grandfather.ts b/src/core/persistence/grandfather.tsindex da1fc7b709..177fe07dff 100644--- a/src/core/persistence/grandfather.ts+++ b/src/core/persistence/grandfather.ts@@ -12,18 +12,19 @@ import { admitWrite, assertReplayIntent, getWriteRequest, intentDigest } from '.import { getWorktreeBinding } from './ownership.ts';import { digest, requireUuid } from './digest.ts';import { waitForWrite, writeResponse } from './service.ts';-import { prepareFileTarget } from './page-prepare.ts';+import { databaseOnlyPublication, prepareFileTarget } from './page-prepare.ts';import type { WriteRequest } from './model.ts';import type { PreparedMutation } from './coordinator.ts';export async function grandfatherCanonicalPage(engine: BrainEngine,selected: { id: number; slug: string; source_id: string; source_incarnation: string },- before: (page: typeof selected & { frontmatter: Record<string, unknown>; knowledge_revision: string; request_id: string }) => void | Promise<void>): Promise<'touched' | 'skipped'> {+ before: (page: typeof selected & { frontmatter: Record<string, unknown>; knowledge_revision: string; request_id: string }) => void | Promise<void>,+): Promise<{ status: 'touched'; revision: string | null } | { status: 'skipped' }> {const snapshot = await engine.readPageSnapshot(selected.slug, { sourceId: selected.source_id });if (!snapshot || snapshot.page.id !== selected.id || snapshot.sourceIncarnation !== selected.source_incarnation ||- Object.hasOwn(snapshot.page.frontmatter ?? {}, 'validate')) return 'skipped';+ Object.hasOwn(snapshot.page.frontmatter ?? {}, 'validate')) return { status: 'skipped' };const extension = snapshot.page.source_path ? extname(snapshot.page.source_path).toLowerCase() : '';- if (['code', 'image'].includes(snapshot.page.type) || extension && !['.md', '.mdx'].includes(extension)) return 'skipped';+ if (['code', 'image'].includes(snapshot.page.type) || extension && !['.md', '.mdx'].includes(extension)) return { status: 'skipped' };const ctx: OperationContext = { engine, config: loadConfig() ?? { engine: engine.kind }, sourceId: selected.source_id,remote: false, dryRun: false, logger: { info() {}, warn() {}, error() {} } };await initializeLocalPersistence(ctx);@@ -47,9 +48,10 @@ export async function grandfatherCanonicalPage(engine: BrainEngine,sourceIncarnation: selected.source_incarnation, pageId: selected.id, slug: selected.slug, requestId, authority, callerIntent,intent: { kind: 'managed_grandfather', expected_revision: snapshot.revision },worktreeId: binding?.worktree_id, topologyGeneration: binding?.topology_generation });- writeResponse(await waitForWrite(engine, request, ctx.config));+ const committed = writeResponse(await waitForWrite(engine, request, ctx.config));await engine.executeRaw('DELETE FROM op_checkpoints WHERE op=$1 AND fingerprint=$2 AND completed_keys=$3::text::jsonb', [op, fingerprint, JSON.stringify([requestId])]);- return 'touched';+ // The publication revision lets verification tell a later rewrite from a lost grandfather.+ return { status: 'touched', revision: typeof committed.revision === 'string' ? committed.revision : null };} catch (error) {if (error instanceof OperationError && error.writeRequest && ['failed', 'conflict', 'cancelled'].includes(error.writeRequest.state)) {await engine.executeRaw('DELETE FROM op_checkpoints WHERE op=$1 AND fingerprint=$2 AND completed_keys=$3::text::jsonb', [op, fingerprint, JSON.stringify([requestId])]);@@ -76,7 +78,7 @@ export async function prepareGrandfatherMutation(engine: BrainEngine, row: Writeif (file && !['.md', '.mdx'].includes(extname(file.path).toLowerCase())) {throw new OperationError('invalid_params', 'Non-Markdown artifacts cannot be grandfathered by rewriting their bytes.');}- return { observedRevision: snapshot.revision, file, deferEmbedding: true, apply: async tx => {+ return { observedRevision: snapshot.revision, file, ...databaseOnlyPublication(row, file), deferEmbedding: true, apply: async tx => {await tx.createVersion(row.slug, { sourceId: row.source_id });const updated = await tx.executeRaw(`UPDATE pages SET frontmatter=jsonb_set(COALESCE(frontmatter,'{}'::jsonb),'{validate}','false'::jsonb),content_hash=$4WHERE id=$1 AND source_id=$2 AND knowledge_revision=$3::uuid AND NOT(COALESCE(frontmatter,'{}'::jsonb)?'validate') RETURNING id`,diff --git a/src/core/persistence/import-prepare.ts b/src/core/persistence/import-prepare.tsindex cd2fe98204..6d6d64e423 100644--- a/src/core/persistence/import-prepare.ts+++ b/src/core/persistence/import-prepare.ts@@ -135,7 +135,7 @@ export async function prepareManagedImportMutation(engine: BrainEngine, row: Wriconst rendered = imageBytes ?? (code ? p.content : serializePageToMarkdown({...(snapshot?.page ?? { id: 0, source_id: row.source_id, created_at: new Date(), updated_at: new Date() }), ...ready.parsedPage,} as Page, tags));- const project = code || image ? undefined : prepareCanonicalProjections(ready.parsedPage!, row.slug, row.source_id);+ const project = code || image ? undefined : await prepareCanonicalProjections(engine, ready.parsedPage!, row.slug, row.source_id, snapshot, 'file');return { observedRevision: ready.observedRevision, noop: ready.noop && p.targetHash === sha256(rendered),deferEmbedding: image || p.noEmbed, validate: async tx => { await checkPaths(tx); await ready.validate(tx); },file: { root, path, content: rendered, expectedBeforeHash: p.targetHash },diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.tsindex 983140a6e9..c8323caba5 100644--- a/src/core/persistence/journal.ts+++ b/src/core/persistence/journal.ts@@ -4,7 +4,7 @@ import { assertRecoveryStagingAbsent } from './staging.ts';import { OperationError } from '../ops/contract.ts';import { digest, jsonBytes, requireUuid } from './digest.ts';import { authorizeWrite } from './authority.ts';-import { readJournalLimits } from './limits.ts';+import { journalLimitKey, oneYearCapacity, readJournalLimits, readReceiptRetentionDays } from './limits.ts';import { retryWriteAdmission } from './admission-retry.ts';import { writeHealth, type WriteHealthFacts } from './health.ts';import { assertMutationProtocol, assertSharedSkillPersistence, declarePersistenceProtocol, PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';@@ -40,6 +40,16 @@ export function capacityError(resource: string): OperationError {return new OperationError('queue_capacity', `Write capacity exhausted: ${resource}.`,'Inspect writer status and configured persistence limits. Existing requests retain their reserved completion space.');}+/** Cumulative caps name their config key and a value that covers one more year at the current admission rate. */+async function cumulativeCapacityError(tx: SqlEngine, resource: string, scope: string, setting: keyof JournalLimits, used: number, limit: number): Promise<OperationError> {+ const key = journalLimitKey(setting);+ const value = await oneYearCapacity(tx, scope, setting.endsWith('LifetimeIds') ? 'LifetimeIds' : 'TerminalBytes', used, limit);+ const error = new OperationError('queue_capacity', `Write capacity exhausted: ${resource} (${used} used of ${limit}).`,+ `Run on the brain host: gbrain config set ${key} ${value} (covers about one more year at the current admission rate). ` ++ 'Keep the same request_id and retry after the change. Accepted request IDs and retained receipts are never evicted.');+ error.detail = key.slice('persistence.limits.'.length);+ return error;+}export async function lockCounters(tx: SqlEngine, keys: string[]): Promise<Counter[]> {const sorted = [...new Set(keys)].sort();for (const key of sorted) await tx.executeRaw('INSERT INTO persistence_counters(key) VALUES ($1) ON CONFLICT DO NOTHING', [key]);@@ -129,8 +139,11 @@ async function prepareAdmission(engine: BrainEngine, input: WriteAdmission, overconst brain = row.key === 'brain';if (Number(row.outstanding_count) + 1 > (brain ? limits.brainOutstanding : limits.principalOutstanding)) throw capacityError(`${brain ? 'brain' : 'principal'} outstanding requests`);if (Number(row.intent_bytes) + bytes > (brain ? limits.brainIntentBytes : limits.principalIntentBytes)) throw capacityError(`${brain ? 'brain' : 'principal'} intent bytes`);- if (Number(row.lifetime_ids) + 1 > (brain ? limits.brainLifetimeIds : limits.principalLifetimeIds)) throw capacityError(`${brain ? 'brain' : 'principal'} permanent request IDs; raise the quota to retain replay protection`);- if (Number(row.terminal_bytes) + terminalBytes > (brain ? limits.brainTerminalBytes : limits.principalTerminalBytes)) throw capacityError(`${brain ? 'brain' : 'principal'} reserved receipt bytes`);+ const scope = brain ? 'brain' : 'principal';+ if (Number(row.lifetime_ids) + 1 > limits[`${scope}LifetimeIds`]) throw await cumulativeCapacityError(tx, `${scope} permanent request IDs`,+ row.key, `${scope}LifetimeIds`, Number(row.lifetime_ids), limits[`${scope}LifetimeIds`]);+ if (Number(row.terminal_bytes) + terminalBytes > limits[`${scope}TerminalBytes`]) throw await cumulativeCapacityError(tx, `${scope} reserved receipt bytes`,+ row.key, `${scope}TerminalBytes`, Number(row.terminal_bytes), limits[`${scope}TerminalBytes`]);}const [row] = await tx.executeRaw<WriteRequest>(`INSERT INTO persistence_requests(principal_kind,principal_id,request_id,operation,source_id,source_incarnation,page_id,slug,@@ -249,11 +262,16 @@ export async function markRecovering(engine: SqlEngine, row: WriteRequest, reasoerror_code=COALESCE(error_code,$4),error_message=COALESCE(error_message,$5)WHERE id=$1::uuid AND execution_token=$2::uuid AND state IN ('running','recovering') AND ${PERSISTENCE_PROTOCOL_PREDICATE}`, [row.id, row.execution_token, reason, failure?.code ?? null, failure?.message ?? null]);}-export async function compactWriteReceipts(engine: BrainEngine, retentionDays = 30): Promise<number> {+export async function compactWriteReceipts(engine: BrainEngine, retentionDays?: number): Promise<number> {+ retentionDays ??= await readReceiptRetentionDays(engine);if (!Number.isFinite(retentionDays) || retentionDays < 0) throw new TypeError('Invalid receipt retention.');- const rows = await engine.executeRaw<WriteRequest>(`SELECT * FROM persistence_requests+ // Receipts with unfinished effects stay retained; filtering them before the+ // LIMIT keeps a backlog of parked effects from starving later receipts.+ const rows = await engine.executeRaw<WriteRequest>(`SELECT * FROM persistence_requests rWHERE state IN ('committed','conflict','failed','cancelled') AND recovery IS NULL AND NOT compacted- AND completed_at < now()-($1::double precision*interval '1 day') ORDER BY sequence LIMIT 100`, [retentionDays]);+ AND completed_at < now()-($1::double precision*interval '1 day')+ AND NOT EXISTS (SELECT 1 FROM persistence_effects e WHERE e.request_id=r.id AND e.state<>'committed')+ ORDER BY sequence LIMIT 100`, [retentionDays]);let count=0;for(const row of rows) count+=await engine.transaction(async tx=>{await declarePersistenceProtocol(tx);diff --git a/src/core/persistence/limits.ts b/src/core/persistence/limits.tsindex b1ad254120..4f2e0a5df4 100644--- a/src/core/persistence/limits.ts+++ b/src/core/persistence/limits.ts@@ -1,9 +1,22 @@import { OperationError } from '../ops/contract.ts';import { DEFAULT_JOURNAL_LIMITS, type JournalLimits, type SqlEngine } from './model.ts';+export const RECEIPT_RETENTION_KEY = 'persistence.receipt_retention_days';+export const DEFAULT_RECEIPT_RETENTION_DAYS = 30;+export function journalLimitKey(key:keyof JournalLimits):string {return `persistence.limits.${key.replace(/[A-Z]/g,letter=>`_${letter.toLowerCase()}`)}`;}+/** Every database config key the persistence journal reads. */+export const JOURNAL_CONFIG_KEYS: readonly string[] = [+ ...(Object.keys(DEFAULT_JOURNAL_LIMITS) as Array<keyof JournalLimits>).map(journalLimitKey), RECEIPT_RETENTION_KEY,+];+export function parseJournalConfigValue(key:string,value:string):number {+ if(!/^(0|[1-9]\d*)$/.test(value) || !Number.isSafeInteger(Number(value))) {+ throw new OperationError('invalid_params',`Invalid ${key}: expected a nonnegative integer.`);+ }+ return Number(value);+}/** Database configuration applies to every server sharing this brain. */export async function readJournalLimits(engine:SqlEngine,overrides?:Partial<JournalLimits>):Promise<JournalLimits> {const rows=await engine.executeRaw<{key:string;value:string}>("SELECT key,value FROM config WHERE key LIKE 'persistence.limits.%'");@@ -11,14 +24,33 @@ export async function readJournalLimits(engine:SqlEngine,overrides?:Partial<Jourconst limits={...DEFAULT_JOURNAL_LIMITS};for(const key of Object.keys(limits) as Array<keyof JournalLimits>) {const value=configured.get(journalLimitKey(key));- if(value!==undefined) {- if(!/^(0|[1-9]\d*)$/.test(value) || !Number.isSafeInteger(Number(value))) {- throw new OperationError('invalid_params',`Invalid ${journalLimitKey(key)}: expected a nonnegative integer.`);- }- limits[key]=Number(value);- }+ if(value!==undefined) limits[key]=parseJournalConfigValue(journalLimitKey(key),value);if(overrides?.[key]!==undefined) limits[key]=overrides[key]!;if(!Number.isSafeInteger(limits[key]) || limits[key]<0) throw new TypeError(`Invalid journal limit: ${key}`);}return limits;}+export async function readReceiptRetentionDays(engine:SqlEngine):Promise<number> {+ const [row]=await engine.executeRaw<{value:string}>('SELECT value FROM config WHERE key=$1',[RECEIPT_RETENTION_KEY]);+ return row ? parseJournalConfigValue(RECEIPT_RETENTION_KEY,row.value) : DEFAULT_RECEIPT_RETENTION_DAYS;+}+/** Permanent accounting a compacted receipt keeps (authority, outcome, effects); measured ~3.9 KB for put_page. */+const RETAINED_RECEIPT_BYTES = 4096;+const RESERVED_RECEIPT_BYTES = 16_384;+/**+ * A cumulative cap value that covers one more year at the scope's recent+ * admission rate (sampled from its latest 1,000 admissions), never less than+ * double the current cap.+ */+export async function oneYearCapacity(engine:SqlEngine,scope:string,setting:'LifetimeIds'|'TerminalBytes',used:number,limit:number):Promise<number> {+ const principal=/^principal:([^:]+):(.+)$/.exec(scope);+ const [sample]=await engine.executeRaw<{admissions:number;age_seconds:number|null}>(`SELECT count(*)::int AS admissions,+ EXTRACT(EPOCH FROM (now()-min(created_at)))::float8 AS age_seconds FROM (SELECT created_at FROM persistence_requests+ ${principal ? 'WHERE principal_kind=$1 AND principal_id=$2' : ''} ORDER BY sequence DESC LIMIT 1000) recent`,+ principal ? [principal[1],principal[2]] : []);+ const perDay=sample.admissions/Math.max(1/24,(sample.age_seconds ?? 0)/86_400);+ const retention=await readReceiptRetentionDays(engine).catch(()=>DEFAULT_RECEIPT_RETENTION_DAYS);+ const needed=setting==='LifetimeIds' ? used+perDay*365 : used+perDay*(365*RETAINED_RECEIPT_BYTES+retention*RESERVED_RECEIPT_BYTES);+ const value=Math.max(Math.ceil(needed),2*limit,1);+ return setting==='TerminalBytes' ? Math.ceil(value/1024**2)*1024**2 : value;+}diff --git a/src/core/persistence/model.ts b/src/core/persistence/model.tsindex 491b14718e..3f5dbe7164 100644--- a/src/core/persistence/model.ts+++ b/src/core/persistence/model.ts@@ -97,11 +97,17 @@ export interface JournalLimits {principalTerminalBytes: number; brainTerminalBytes: number;brainRecoveryBytes: number; worktreeRecoveryBytes: number;}+/**+ * Cumulative defaults are sized so one principal admitting 600 writes a day+ * (the reported autopilot workload) runs at least one year: lifetime IDs last+ * about 417 days; receipt bytes hold a 30-day window of 16 KiB reservations+ * plus about 4 KiB retained per compacted receipt for about 590 days.+ */export const DEFAULT_JOURNAL_LIMITS: Readonly<JournalLimits> = Object.freeze({principalOutstanding: 100, brainOutstanding: 1000,principalIntentBytes: 32 * 1024 ** 2, brainIntentBytes: 256 * 1024 ** 2,- principalLifetimeIds: 100_000, brainLifetimeIds: 1_000_000,- principalTerminalBytes: 128 * 1024 ** 2, brainTerminalBytes: 1024 ** 3,+ principalLifetimeIds: 250_000, brainLifetimeIds: 1_000_000,+ principalTerminalBytes: 1536 * 1024 ** 2, brainTerminalBytes: 8 * 1024 ** 3,brainRecoveryBytes: 1024 ** 3, worktreeRecoveryBytes: 256 * 1024 ** 2,});export type SqlEngine = Pick<BrainEngine, 'executeRaw'>;diff --git a/src/core/persistence/ownership.ts b/src/core/persistence/ownership.tsindex 257a0fd56c..b1ed24db0c 100644--- a/src/core/persistence/ownership.ts+++ b/src/core/persistence/ownership.ts@@ -9,7 +9,8 @@ import { localHostId, persistenceHome } from './identity.ts';import type { SqlEngine, WriteRequest } from './model.ts';import { acquireNativeLock, tryAcquireNativeLock, type NativeLockHandle } from './native-lock.ts';import { managedFilesystemDatastorePath, refreshManagedFilesystemRoots } from './filesystem-guard.ts';-import { assertPhysicalRoot, claimPhysicalRoot, isPhysicalRootMetadata, preparePhysicalRootTransfer, readPhysicalRootReservation } from './physical-root.ts';+import { assertPhysicalRoot, claimPhysicalRoot, isPhysicalRootMetadata, preparePhysicalRootTransfer, readPhysicalRootReservation, restampPhysicalRoot } from './physical-root.ts';+import { readPhysicalRootStamp } from './physical-root-record.ts';import { canonicalFilesystemPath, nativeFilesystemPath } from './root-registry.ts';import { assertWriterAdminState } from './admin-intent.ts';import { inspectPhysicalRootRecovery, repairPhysicalRoot, type PhysicalRootRecovery } from './physical-root-recovery.ts';@@ -105,13 +106,32 @@ export async function claimWorktree(engine: BrainEngine, sourceId: string, path:});return (await getWorktreeBinding(engine, sourceId, hostId))!;}-export async function acquireWorktree(binding: WorktreeBinding, waitMs = 0, signal?: AbortSignal): Promise<NativeLockHandle | null> {+/**+ * With an engine, a device-only physical-root change (#5604) is re-stamped under+ * this native lock after database ownership is verified; otherwise it refuses+ * with the filled self-transfer commands.+ */+export async function acquireWorktree(binding: WorktreeBinding, waitMs = 0, signal?: AbortSignal, engine?: BrainEngine): Promise<NativeLockHandle | null> {if (!binding.local_path || !binding.coordination_path) return null;const lock = await (waitMs > 0 ? acquireNativeLock(binding.coordination_path, { timeoutMs: waitMs, signal }): tryAcquireNativeLock(binding.coordination_path));if (!lock) return null;- try { assertPhysicalRoot(binding.local_path, { worktreeId: binding.worktree_id, coordinationPath: binding.coordination_path }); return lock; }- catch (error) { await lock.release(); throw error; }+ const identity = { worktreeId: binding.worktree_id, coordinationPath: binding.coordination_path };+ try { assertPhysicalRoot(binding.local_path, identity); return lock; }+ catch (error) {+ try {+ if (!(error instanceof OperationError) || error.detail !== 'physical_root_device_changed') throw error;+ if (engine && await restampPhysicalRoot(engine, binding, localHostId())) { assertPhysicalRoot(binding.local_path, identity); return lock; }+ const why = !engine ? 'this caller cannot verify database ownership'+ : readPhysicalRootStamp(binding.local_path)?.birth === '0' ? 'this filesystem reports no birth time'+ : 'database ownership of this checkout did not verify';+ error.suggestion = `The automatic device re-stamp did not apply because ${why}. On the brain host, run gbrain sources writer status ${binding.source_id} and note admin_state, `+ + `then gbrain sources writer transfer prepare ${binding.source_id} --self-transfer --admin-intent writer_transfer_prepare --expected-state <admin_state>, `+ + `then gbrain sources writer transfer accept ${binding.source_id} --path ${binding.local_path} --expected-epoch ${binding.owner_epoch} --manifest <manifest digest printed by prepare> `+ + `--self-transfer --admin-intent writer_transfer_accept --expected-state <admin_state from a fresh status>. Retry the original write with the same request_id afterwards.`;+ throw error;+ } catch (failure) { await lock.release(); throw failure; }+ }}export async function guardOwnership(tx: SqlEngine, row: WriteRequest, hostId: string): Promise<WorktreeBinding | null> {if (!row.worktree_id) return null;diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.tsindex c8ce399df8..a35825c75b 100644--- a/src/core/persistence/page-mutations.ts+++ b/src/core/persistence/page-mutations.ts@@ -1,11 +1,14 @@import { randomUUID } from 'node:crypto';import { realpathSync } from 'node:fs';-import { join, resolve } from 'node:path';+import { isAbsolute, join, relative, resolve, sep } from 'node:path';import type { OperationContext } from '../ops/contract.ts';import { OperationError } from '../ops/contract.ts';import { enforceClientSlugFence, enforceSubagentSlugFence, normalizeSlugPrefix, parseSourceIdParam, requireWritablePage, validatePageSlug } from '../ops/context.ts';import { defaultSlug, detectBinaryNullByte, explicitCaptureType, mergeCaptureFrontmatter, normalizeForHash } from '../capture-content.ts';import { computeContentHash } from '../ingestion/types.ts';+import { resolveSlugForPath } from '../sync.ts';+import { scannerSlugRootMode, scannerSourcePath } from '../write-through.ts';+import { sha256 } from './digest.ts';import { assertPersistenceAccepting, waitForWrite, writeResponse } from './service.ts';import { admitWrite, assertPageRequestIdentity, assertReplayIntent, getWriteRequest, intentDigest } from './journal.ts';import { submissionAuthority, authorizeStoredRequest } from './authority.ts';@@ -39,6 +42,36 @@ export function pageMutationSource(ctx: OperationContext, params: Record<string,}return sourceId;}+/**+ * #5622: a trusted `capture --file` path becomes a source-relative physical path+ * or 'cli-file'; the host path is never stored. Returns the slug sync would give+ * that file, so only a capture under that slug binds the file as its origin.+ */+async function resolveCaptureFile(ctx: OperationContext, sourceId: string, p: Record<string, unknown>): Promise<string | null> {+ if (Object.hasOwn(p, 'capture_path')) throw new OperationError('invalid_params', 'capture_path is reserved for the capture owner.');+ if (p.local_file === undefined) return null;+ if (ctx.remote !== false || typeof p.local_file !== 'string' || !isAbsolute(p.local_file)) {+ throw new OperationError('invalid_params', 'Capture file paths are accepted only from the trusted local CLI.',+ 'Read the file yourself and pass its content; file capture runs through the gbrain capture command on the brain host.');+ }+ const file = p.local_file;+ delete p.local_file;+ const [source] = await ctx.engine.executeRaw<{ local_path: string | null }>('SELECT local_path FROM sources WHERE id=$1', [sourceId]);+ const binding = await getWorktreeBinding(ctx.engine, sourceId);+ const root = binding ? binding.owner_host_id === localHostId() && binding.local_path ? join(binding.local_path, binding.relative_path) : null+ : source?.local_path || (sourceId === 'default' ? await ctx.engine.getConfig('sync.repo_path') : null);+ let origin: string | null = null;+ try { if (root) origin = relative(realpathSync(root), realpathSync(file)); } catch { /* unreadable or absent root */ }+ if (!root || !origin || isAbsolute(origin) || origin === '..' || origin.startsWith(`..${sep}`) || !/\.mdx?$/i.test(origin)) {+ p.source_uri = 'cli-file';+ return null;+ }+ const capturePath = origin.split(sep).join('/');+ p.capture_path = capturePath;+ const canonicalRoot = realpathSync(root);+ return resolveSlugForPath(scannerSourcePath(canonicalRoot, join(canonicalRoot, capturePath), await scannerSlugRootMode(ctx.engine, sourceId, canonicalRoot)));+}+export async function submitPageMutation(ctx: OperationContext,input: { operation: string; params: Record<string, unknown>; waitMs?: number; managedFileImport?: true }): Promise<Record<string, unknown>> {if (input.operation === 'put_page' && ['kind', 'preview', 'backup_reference'].some(key => Object.hasOwn(input.params, key))) {@@ -52,6 +85,7 @@ export async function submitPageMutation(ctx: OperationContext,const requestId = typeof p.request_id === 'string' ? p.request_id : randomUUID();const sourceId = pageMutationSource(ctx, p, input.operation);await initializeLocalPersistence(ctx);+ const captureSlug = input.operation === 'capture' ? await resolveCaptureFile(ctx, sourceId, p) : null;const principal = await requestPrincipalForContext(ctx);await assertPageRequestIdentity(ctx.engine, principal, requestId);const prior = await getWriteRequest(ctx.engine, principal, requestId);@@ -90,6 +124,12 @@ export async function submitPageMutation(ctx: OperationContext,intent.content = mergeCaptureFrontmatter(p.content, { type, capturedVia: ctx.remote === false ? 'capture-cli' : 'capture-mcp',...Object.fromEntries(['who','what','where','kind','depth'].filter(key => typeof p[key] === 'string').map(key => [key, p[key]])) });intent.capture_hash = computeContentHash(normalizeForHash(p.content));+ // Only a file whose own path names this slug can be the page's origin; sync keys origins by path.+ if (typeof intent.capture_path === 'string' && captureSlug !== slug) {+ delete intent.capture_path;+ intent.source_uri = 'cli-file';+ }+ if (typeof intent.capture_path === 'string') intent.capture_file_hash = sha256(p.content);}validatePageSlug(slug);enforceClientSlugFence(ctx, slug, input.operation);diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.tsindex 8fad9c0924..6ce4493079 100644--- a/src/core/persistence/page-prepare.ts+++ b/src/core/persistence/page-prepare.ts@@ -10,7 +10,7 @@ import { parseMarkdown, serializePageToMarkdown, resolveSourceLocalFilePath } frimport { OperationError } from '../ops/contract.ts';import { assertPageRevision, type PageSnapshot } from '../page-state/types.ts';import { isWriteTargetContained } from '../path-confine.ts';-import { recordedPathFromFileUri, scannerSourcePath } from '../write-through.ts';+import { recordedPathFromFileUri, scannerSlugRootMode, scannerSourcePath } from '../write-through.ts';import { engineMutationPrecondition, parseMutationPrecondition } from './preconditions.ts';import { assertPurgeParams } from './purge-params.ts';import { authorizeWrite } from './authority.ts';@@ -21,18 +21,22 @@ import type { PreparedMutation } from './coordinator.ts';import type { WriteRequest } from './model.ts';import { sealPageTextProjection } from '../page-state/projections.ts';import { overlayCanonicalBodies } from '../page-state/snapshot.ts';-import { prepareCanonicalProjections } from './canonical-projections.ts';+import { materializeTimeline, prepareCanonicalProjections } from './canonical-projections.ts';import { preserveProtectedTakes } from './protected-takes.ts';import { isAutoLinkEnabled } from '../link-extraction.ts';import { prepareAutomaticLinks } from './links-preparation.ts';import { preparePageAdvisories, remoteLinkHint, pageNoopAdvisories } from './page-advisories.ts';import { assertKnowledgePublicationAllowed } from '../shared-skills/knowledge-guard.ts';import { nativeFileTarget } from './native-file-target.ts';+import { isSourceDbOnlySlug } from './source-storage.ts';+import { SOURCE_CONFIG_OBJECT_SQL } from '../source-config-sql.ts';+import { readSlugRootMode } from '../sync-anchor.ts';const PURGE_RESIDUALS = 'Brain-repo git history, synced working-tree copies, exports, compiled context files and slug-keyed derived rows (takes, open loops, file records) may still hold the content — rotate the credential and rewrite or regenerate those copies.';+/** The parser trims titles, so a stored title differing only in surrounding whitespace is not drift (#5635). */function canonical(page: Pick<Page, 'type' | 'title' | 'compiled_truth' | 'timeline' | 'frontmatter'>, tags: string[]) {- return { type: page.type, title: page.title, compiled_truth: page.compiled_truth, timeline: page.timeline ?? '',+ return { type: page.type, title: page.title.trim(), compiled_truth: page.compiled_truth, timeline: page.timeline ?? '',frontmatter: page.frontmatter, tags: [...new Set(tags)].sort() };}interface CanonicalProvenance { source_kind: string; ingested_via: string; ingested_at: string; }@@ -62,17 +66,23 @@ function putProvenance(row: WriteRequest, snapshot: PageSnapshot | null, parsed:return stamp;}export async function prepareFileTarget(engine: BrainEngine, row: Pick<WriteRequest, 'source_id' | 'worktree_id' | 'slug'>, snapshot: PageSnapshot | null,- content: string | null, hostId?: string, options: { allowMissing?: boolean } = {}): Promise<PreparedMutation['file']> {+ content: string | null, hostId?: string, options: { allowMissing?: boolean; capture?: { path: string; hash: string } } = {}): Promise<PreparedMutation['file']> {if (!row.worktree_id) return undefined;const binding = await getWorktreeBinding(engine, row.source_id, hostId);if (!binding?.local_path) throw new OperationError('owner_unavailable', 'The canonical worktree is unavailable on this host.');const root = join(binding.local_path, binding.relative_path);- const capturedPath = recordedPathFromFileUri(snapshot?.page.source_uri, root);- const path = nativeFileTarget(root, resolveSourceLocalFilePath(root, snapshot?.page.source_path, row.slug)+ // #5622: a new page captured from a file inside the source is published to that file.+ const capturedPath = !snapshot && options.capture ? options.capture.path : recordedPathFromFileUri(snapshot?.page.source_uri, root);+ const mode = snapshot?.page.source_path ? await scannerSlugRootMode(engine, row.source_id, root) : undefined;+ const path = nativeFileTarget(root, resolveSourceLocalFilePath(root, snapshot?.page.source_path, row.slug, mode)?? (capturedPath ? join(root, capturedPath) : join(root, `${row.slug}.md`)));if (!isWriteTargetContained(path, root)) throw new OperationError('source_changed', 'The canonical file target is outside its registered source.');const before = existsSync(path) ? readFileSync(path) : null;if (!before && snapshot && !snapshot.page.deleted_at && !options.allowMissing) {+ // A declared db_only page has no canonical file by design and publishes to+ // the database only. gbrain.yml is consulted only here, where the write+ // would otherwise refuse, so an invalid config can only change the refusal.+ if (isSourceDbOnlySlug(root, row.slug, 'refuse')) return undefined;throw new OperationError('source_changed', 'The canonical file was removed outside coordinated publication.','Import the local deletion or recover the canonical file before editing this page.');}@@ -81,19 +91,34 @@ export async function prepareFileTarget(engine: BrainEngine, row: Pick<WriteRequif (before && snapshot) {const parsed = parseMarkdown(before.toString('utf8'), row.slug);const expected = canonical(snapshot.page, snapshot.tags);- const actual = canonical({ ...parsed, ...await overlayCanonicalBodies(engine.executeRaw.bind(engine),+ // #1035 parity (#5521): a file without an explicit `type:` keeps the stored type on import.+ const type = parsed.typeExplicit ? parsed.type : snapshot.page.type;+ const actual = canonical({ ...parsed, type, ...await overlayCanonicalBodies(engine.executeRaw.bind(engine),parsed.compiled_truth, parsed.timeline ?? '', snapshot.withdrawals) }, parsed.tags);// Withdrawal overlays intentionally precede physical mirroring. The ledger// is applied by the import preparation and cannot be undone by this check.if (digest(actual) !== digest(expected)) {- throw new OperationError('source_changed', 'The canonical file contains an uncoordinated local edit.', 'Import or recover the local edit before replacing this page.');+ const error = new OperationError('source_changed', 'The canonical file contains an uncoordinated local edit.',+ `On the brain host, run gbrain sources reconcile ${row.source_id} ${row.slug} --brain <brain id, host by default> --preview, review and apply the resolved preview, then retry this write with a new request_id. Neither copy was overwritten.`);+ error.detail = 'file_database_drift';+ throw error;}- } else if (before && !snapshot && content !== null && sha256(before) !== sha256(content)) {+ } else if (before && !snapshot && content !== null && sha256(before) !== sha256(content)+ && !(options.capture && sha256(before) === options.capture.hash)) {throw new OperationError('source_changed', 'An unindexed file already occupies the canonical page path.', 'Import the file before replacing it.');}return { path, root, content, expectedBeforeHash: before ? sha256(before) : null };}+/**+ * Receipt reason for a page write that publishes no file. Invariant: for a+ * bound row, prepareFileTarget returns no target only for a live declared+ * db_only page whose file is absent; every other case returns a target or throws.+ */+export function databaseOnlyPublication(row: Pick<WriteRequest, 'worktree_id'>, file: PreparedMutation['file']): Pick<PreparedMutation, 'databaseOnlyReason'> {+ return row.worktree_id && !file ? { databaseOnlyReason: 'db_only' } : {};+}+/** Providers and parsing run before the OS lock and before any publication transaction. */export async function preparePageMutation(engine: BrainEngine, row: WriteRequest, _config: GBrainConfig,preparedIntent?: { content: string; expectedRevision: string; tags?: string[] }, signal?: AbortSignal): Promise<PreparedMutation> {@@ -123,7 +148,8 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequest// Tombstones still own their recorded artifact. Purge always attempts its// removal before the guarded hard-delete and receipt commit; failure rolls// back to the prior row, and replay survives the eventual absence of that row.- return { observedRevision, noop, file: await prepareFileTarget(engine, row, snapshot, null, undefined, { allowMissing: purge }), apply: async tx => {+ const file = await prepareFileTarget(engine, row, snapshot, null, undefined, { allowMissing: purge });+ return { observedRevision, noop, file, ...databaseOnlyPublication(row, file), apply: async tx => {if (purge) {await tx.deletePage(row.slug, source);return { status: 'purged', slug: row.slug, source_id: row.source_id, residuals: PURGE_RESIDUALS };@@ -163,13 +189,24 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequestif (compiled_truth!==parsed.compiled_truth || timeline!==(parsed.timeline??'')) content=serializePageToMarkdown({...(snapshot?.page??{id:0,source_id:row.source_id,created_at:new Date(),updated_at:new Date()}),...parsed,compiled_truth,timeline},parsed.tags);}+ const projected = !(row.operation === 'remember' || row.operation.startsWith('takes_') || (row.operation === 'extract_facts' && p.kind === 'managed_facts_entity'));+ const writer = row.operation === 'put_page' && p.kind !== 'managed_maintenance_page'+ && (preparedIntent !== undefined || typeof p.expected_revision === 'string') ? 'editing' : 'preserving';+ // #5567: database-only timeline rows are written back into the page before+ // the no-op check, digest, rendering and chunking see the body.+ if (projected && snapshot && typeof content === 'string') {+ const parsed = parseMarkdown(content,row.slug);+ const { timeline, materialized } = await materializeTimeline(engine,parsed,row.slug,snapshot,writer);+ if (materialized) content = serializePageToMarkdown({...snapshot.page,...parsed,timeline,type:parsed.typeExplicit ? parsed.type : snapshot.page.type},parsed.tags);+ }// Detect an exact canonical no-op before ingestion can invoke any provider.// Revision/identity checks above still apply to stale identical replacements.if (snapshot && (snapshot.page.deleted_at != null) === targetDeleted && typeof content === 'string') {const incoming = parseMarkdown(content,row.slug);const tags = versionTags ?? [...new Set([...snapshot.tags,...incoming.tags])].sort();if (digest(canonical(snapshot.page,snapshot.tags)) === digest(canonical(incoming,tags))) {- return {observedRevision,noop:true,file:await prepareFileTarget(engine,row,snapshot,targetDeleted ? null : serializePageToMarkdown(snapshot.page,snapshot.tags)),+ const file=await prepareFileTarget(engine,row,snapshot,targetDeleted ? null : serializePageToMarkdown(snapshot.page,snapshot.tags));+ return {observedRevision,noop:true,file,...databaseOnlyPublication(row,file),apply:async()=>({...pageNoopAdvisories(row),status:'skipped',slug:row.slug,source_id:row.source_id,noop:true,chunks:0,chunk_skip_reason:'write_skipped',...(row.operation==='capture'?{channel:'capture',content_hash:p.capture_hash}:{})})};}@@ -211,21 +248,31 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequestconst rendered = serializePageToMarkdown(renderedPage, tags);const logicalNoop = snapshot !== null && digest(canonical(snapshot.page, snapshot.tags)) === digest(canonical(ready.parsedPage, tags));const noop = logicalNoop && (snapshot?.page.deleted_at != null) === targetDeleted;- const project = row.operation === 'remember' || row.operation.startsWith('takes_') || (row.operation === 'extract_facts' && p.kind === 'managed_facts_entity') ? undefined- : prepareCanonicalProjections(ready.parsedPage,row.slug,row.source_id);+ const project = projected ? await prepareCanonicalProjections(engine,ready.parsedPage,row.slug,row.source_id,snapshot,writer) : undefined;const ordinaryPage = ['put_page','capture','restore_page','revert_version'].includes(row.operation);const advisories = noop || targetDeleted ? pageNoopAdvisories(row) : !ordinaryPage ? remoteLinkHint(row) : await preparePageAdvisories(engine,row,ready.parsedPage);const links = !noop && !targetDeleted && ordinaryPage && (row.authority.autoLinkTrusted ?? !row.authority.remote) && await isAutoLinkEnabled(engine)? await prepareAutomaticLinks(engine,row.slug,ready.parsedPage,row.source_id) : undefined;- const file = await prepareFileTarget(engine, row, snapshot, targetDeleted ? null : rendered);- const sourcePath = file ? scannerSourcePath(file.root, file.path) : undefined;- return { observedRevision, noop, additionalPageKeys:links?.pageKeys, file, validate: ready.validate, apply: async tx => {+ const capture = row.operation === 'capture' && typeof p.capture_path === 'string' && typeof p.capture_file_hash === 'string'+ ? { path: p.capture_path, hash: p.capture_file_hash } : undefined;+ const file = await prepareFileTarget(engine, row, snapshot, targetDeleted ? null : rendered, undefined, { capture });+ const mintMode = file && !snapshot?.page.source_path ? await scannerSlugRootMode(engine, row.source_id, file.root) : undefined;+ const sourcePath = file && mintMode ? scannerSourcePath(file.root, file.path, mintMode) : undefined;+ // An inferred mode is pinned with the first origin it mints, so later pages cannot flip the inference (#5610).+ const pinMode = sourcePath && mintMode && scannerSourcePath(file!.root, file!.root) && !await readSlugRootMode(engine, row.source_id) ? mintMode : undefined;+ return { observedRevision, noop, additionalPageKeys:links?.pageKeys, file, ...databaseOnlyPublication(row, file), validate: ready.validate, apply: async tx => {let autoLinks: Awaited<ReturnType<NonNullable<typeof links>['apply']>> | undefined;if (!noop) {await ready.apply(tx);// Mandatory metadata shares publication rollback; exact no-ops never heal it.if (sourcePath && !snapshot?.page.source_path) await tx.executeRaw(`UPDATE pages SET source_path = $1WHERE source_id=$2 AND slug=$3 AND source_path IS NULL`, [sourcePath, row.source_id, row.slug]);+ if (pinMode) {+ const [pinned] = await tx.executeRaw<{ mode: string | null }>(`UPDATE sources SET config=CASE WHEN config->>'slug_root_mode' IS NULL+ THEN jsonb_set(${SOURCE_CONFIG_OBJECT_SQL},'{slug_root_mode}',to_jsonb($2::text)) ELSE config END WHERE id=$1 RETURNING config->>'slug_root_mode' AS mode`,+ [row.source_id, pinMode]);+ if (pinned?.mode !== pinMode) throw new OperationError('revision_conflict', 'The source slug-root mode changed during preparation.');+ }if (provenance) await tx.executeRaw(`UPDATE pages SET source_kind=$3,ingested_via=$4,ingested_at=$5::timestamptzWHERE source_id=$1 AND slug=$2`, [row.source_id, row.slug, provenance.source_kind, provenance.ingested_via, provenance.ingested_at]);if (row.operation === 'restore_page') await tx.restorePage(row.slug, source);diff --git a/src/core/persistence/page-visibility.ts b/src/core/persistence/page-visibility.tsindex 20de49a76b..62b0a61ce3 100644--- a/src/core/persistence/page-visibility.ts+++ b/src/core/persistence/page-visibility.ts@@ -1,5 +1,5 @@import { OperationError } from '../ops/contract.ts';-import { REMOTE_PRIVATE_PAGES_KEY } from '../search/private-visibility.ts';+import { REMOTE_PRIVATE_PAGES_KEY, privatePagesFilterFragment } from '../search/private-visibility.ts';import type { SqlEngine, WriteAuthority } from './model.ts';/** Publication uses fresh policy, independent of the read-side telemetry cache. */@@ -14,6 +14,6 @@ export async function authorizePageVisibility(engine: SqlEngine, authority: Writif (!authority.remote) return;if (!(authority.excludePrivate ?? true) && !await excludesPrivateWrites(engine, true)) return;const rows = await engine.executeRaw(`SELECT 1 FROM pages WHERE source_id=$1 AND slug=$2- AND frontmatter->>'visibility'='private' LIMIT 1`, [authority.sourceId, slug]);+ AND NOT (${privatePagesFilterFragment('pages')}) LIMIT 1`, [authority.sourceId, slug]);if (rows.length) throw new OperationError('page_not_found', 'Page not found.');}diff --git a/src/core/persistence/physical-root-record.ts b/src/core/persistence/physical-root-record.tsindex 84f36583f0..811e487136 100644--- a/src/core/persistence/physical-root-record.ts+++ b/src/core/persistence/physical-root-record.ts@@ -116,10 +116,42 @@ export function assertPhysicalRootStamp(directory: string, reservation: Physicalif (!value || value.version !== 1 || value.token !== reservation.token || value.brainId !== reservation.brainId || value.worktreeId !== reservation.worktreeId|| value.root !== reservation.root || value.inode !== info.ino.toString() || value.birth !== info.birthtimeNs.toString()) throw physicalRootError();if (value.device !== info.dev.toString()) {- if (typeof value.device === 'string' && /^\d+$/.test(value.device)) throw physicalRootError('The filesystem device identifier changed while the other checkout identity fields still match. Inspect writer status and use deliberate self-transfer to re-stamp this same root.');+ if (typeof value.device === 'string' && /^\d+$/.test(value.device)) {+ const error = physicalRootError('The filesystem device identifier changed while the other checkout identity fields still match. Inspect writer status and use deliberate self-transfer to re-stamp this same root.');+ error.detail = 'physical_root_device_changed';+ throw error;+ }throw physicalRootError();}}+/**+ * #5604: macOS may give the same checkout a new st_dev after a reboot. The+ * owner token binds the stamp, so a change is device-only when the stamp still+ * names this reservation, root, inode and a non-zero birth time. Filesystems+ * that report no birth time (some Linux mounts) keep the refusal.+ */+export function physicalRootDeviceChange(stamp: PhysicalRootStamp, reservation: Pick<PhysicalRootReservation, 'token' | 'brainId' | 'worktreeId' | 'root'>,+ info: { dev: bigint; ino: bigint; birthtimeNs: bigint }): { from: string; to: string } | null {+ if (stamp.token !== reservation.token || stamp.brainId !== reservation.brainId || stamp.worktreeId !== reservation.worktreeId+ || stamp.root !== reservation.root || stamp.inode !== info.ino.toString() || stamp.birth !== info.birthtimeNs.toString()+ || info.birthtimeNs === 0n || stamp.device === info.dev.toString()) return null;+ return { from: stamp.device, to: info.dev.toString() };+}+function replacePrivate(path: string, value: unknown): void {+ const temporary = `${path}.${randomUUID()}.tmp`;+ let created = false;+ try {+ created = createPrivate(temporary, value);+ if (!created || digest(readPrivate(temporary)) !== digest(value)) throw physicalRootError('The re-stamped ownership record contains unexpected bytes.');+ renameSync(temporary, path); created = false; flushDirectory(dirname(path));+ } finally { if (created) try { unlinkSync(temporary); } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; } }+}+/** Caller holds the outside-root native lock and verified database ownership; only the device fields change. */+export function restampPhysicalRootDevice(root: string, reservation: PhysicalRootReservation, stamp: PhysicalRootStamp, change: { from: string; to: string }): void {+ if (reservation.initialDevice === change.from) replacePrivate(physicalRootReservationPath(root), { ...reservation, initialDevice: change.to });+ replacePrivate(join(root, PHYSICAL_ROOT_MARKER), { ...stamp, device: change.to });+ assertPhysicalRootStamp(root, readPhysicalRootReservation(root)!);+}/** Explicit verified transfer may adopt a copied stamp of this same logical worktree. */export function adoptTransferredRootStamp(directory: string, reservation: PhysicalRootReservation, temporaryToken: string = randomUUID()): void {const path = join(directory, PHYSICAL_ROOT_MARKER);diff --git a/src/core/persistence/physical-root.ts b/src/core/persistence/physical-root.tsindex 8b66054a01..799a9bdf52 100644--- a/src/core/persistence/physical-root.ts+++ b/src/core/persistence/physical-root.ts@@ -1,11 +1,12 @@import { randomUUID } from 'node:crypto';-import { existsSync, statSync } from 'node:fs';+import { existsSync, lstatSync, realpathSync, statSync } from 'node:fs';import { join } from 'node:path';+import type { BrainEngine } from '../engine.ts';import type { SqlEngine } from './model.ts';import { persistenceHome } from './identity.ts';import { canonicalFilesystemPath } from './root-registry.ts';-import { adoptTransferredRootStamp, assertNoPhysicalRootOverlap, assertPhysicalRoot, assertPhysicalRootStamp, PHYSICAL_ROOT_MARKER, physicalRootError,- readPhysicalRootReservation, reservePhysicalRootRecord, writePhysicalRootStamp, type PhysicalRootReservation } from './physical-root-record.ts';+import { adoptTransferredRootStamp, assertNoPhysicalRootOverlap, assertPhysicalRoot, assertPhysicalRootStamp, PHYSICAL_ROOT_MARKER, physicalRootDeviceChange, physicalRootError,+ readPhysicalRootReservation, readPhysicalRootStamp, reservePhysicalRootRecord, restampPhysicalRootDevice, writePhysicalRootStamp, type PhysicalRootReservation } from './physical-root-record.ts';export { assertPhysicalRoot, isPhysicalRootMetadata, readPhysicalRootReservation } from './physical-root-record.ts';export interface PhysicalRootClaim { hostId: string; worktreeId?: string; coordinationPath?: string; }@@ -76,3 +77,61 @@ export async function preparePhysicalRootTransfer(tx: SqlEngine, path: string,assertNoPhysicalRootOverlap(root);adoptTransferredRootStamp(root, reservation);}++type DeviceChange = { from: string; to: string };+function restampRecovery(recovery: Record<string, any> | undefined, change: DeviceChange): boolean {+ let changed = false;+ for (const [record, field] of [[recovery?.before?.reservation, 'initialDevice'], [recovery?.before?.stamp, 'device'],+ [recovery?.reservation, 'initialDevice'], [recovery?.stamp, 'device']] as const) {+ if (record?.[field] === change.from) { record[field] = change.to; changed = true; }+ }+ return changed;+}+/**+ * #5604: re-stamp every persisted device copy (ownership stamp, reservation,+ * recorded self-transfer and retained topology staging identity) when only the+ * filesystem device id changed. The caller holds the outside-root native lock;+ * database ownership is verified in the same transaction that rewrites the+ * database copies, and the files are rewritten after it commits.+ */+export async function restampPhysicalRoot(engine: BrainEngine, binding: { worktree_id: string; local_path: string | null; coordination_path: string | null },+ hostId: string): Promise<DeviceChange | null> {+ const root = binding.local_path;+ if (!root || !binding.coordination_path || realpathSync(root) !== root || lstatSync(root).isSymbolicLink()) return null;+ const reservation = readPhysicalRootReservation(root), stamp = readPhysicalRootStamp(root);+ if (!reservation || !stamp || reservation.worktreeId !== binding.worktree_id || reservation.coordinationPath !== binding.coordination_path) return null;+ const change = physicalRootDeviceChange(stamp, reservation, statSync(root, { bigint: true }));+ if (!change) return null;+ const applied = await engine.transaction(async tx => {+ await tx.executeRaw("SELECT set_config('synchronous_commit','on',true)");+ const [owner] = await tx.executeRaw<{ owner_host_id: string | null; manifest: Record<string, any> | null }>(+ 'SELECT owner_host_id,manifest FROM persistence_worktrees WHERE id=$1::uuid FOR UPDATE', [binding.worktree_id]);+ const [brain] = await tx.executeRaw<{ brain_id: string }>('SELECT brain_id FROM persistence_brain WHERE singleton=1');+ const [bound] = await tx.executeRaw<{ local_path: string; coordination_path: string }>(+ 'SELECT local_path,coordination_path FROM persistence_host_bindings WHERE worktree_id=$1::uuid AND host_id=$2::uuid', [binding.worktree_id, hostId]);+ if (!owner || owner.owner_host_id !== hostId || brain?.brain_id !== stamp.brainId+ || bound?.local_path !== root || bound.coordination_path !== binding.coordination_path) return false;+ const manifest = owner.manifest;+ if (manifest && restampRecovery(manifest.self_transfer, change)) {+ await tx.executeRaw('UPDATE persistence_worktrees SET manifest=$2::text::jsonb WHERE id=$1::uuid', [binding.worktree_id, JSON.stringify(manifest)]);+ }+ const topology = await tx.executeRaw<{ id: string; recovery: Record<string, any> | null }>(+ "SELECT id,recovery FROM persistence_topology_changes WHERE state='recovering' AND $1::uuid=ANY(worktree_ids) FOR UPDATE", [binding.worktree_id]);+ for (const row of topology) {+ const identity = row.recovery?.stageIdentity, stage = row.recovery?.stage;+ if (identity?.device !== change.from || typeof stage !== 'string' || !existsSync(stage)) continue;+ const info = lstatSync(stage, { bigint: true });+ if (!info.isDirectory() || info.ino.toString() !== identity.inode || info.birthtimeNs.toString() !== identity.birthNs || info.dev.toString() !== change.to) continue;+ identity.device = change.to;+ await tx.executeRaw('UPDATE persistence_topology_changes SET recovery=$2::text::jsonb,updated_at=now() WHERE id=$1::uuid', [row.id, JSON.stringify(row.recovery)]);+ }+ return true;+ });+ if (!applied) return null;+ // Database copies commit first; each update is conditional on the old device, so+ // a crash before the files are rewritten leaves a device-only change that the next+ // locked acquisition re-stamps again.+ restampPhysicalRootDevice(root, reservation, stamp, change);+ process.stderr.write(`[persistence] physical root ${root} filesystem device id changed ${change.from} -> ${change.to}; inode, birth time and owner token matched, so every persisted copy was re-stamped.\n`);+ return change;+}diff --git a/src/core/persistence/reconcile-audit.ts b/src/core/persistence/reconcile-audit.tsindex 5eec55a4d5..202dd09814 100644--- a/src/core/persistence/reconcile-audit.ts+++ b/src/core/persistence/reconcile-audit.ts@@ -5,7 +5,7 @@ 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 { recordedPathFromFileUri, scannerSlugRootMode } from '../write-through.ts';import { isWriteTargetContained } from '../path-confine.ts';import { submissionAuthority } from './authority.ts';import { currentVerifiedLocalWriter, existingLocalHostId, readLocalWriter, verifyLocalWriter } from './identity.ts';@@ -45,6 +45,7 @@ export async function auditCanonicalSource(engine: BrainEngine, sourceId: stringORDER 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 };+ const mode = await scannerSlugRootMode(engine, sourceId, root);for (const candidate of rows.slice(0, limit)) {report.inspected++;try {@@ -52,7 +53,7 @@ export async function auditCanonicalSource(engine: BrainEngine, sourceId: stringconst 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)+ const path = resolveSourceLocalFilePath(root, snapshot.page.source_path, candidate.slug, mode)?? (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;diff --git a/src/core/persistence/reconcile-prepare.ts b/src/core/persistence/reconcile-prepare.tsindex 2f4aa46909..0e663fa81c 100644--- a/src/core/persistence/reconcile-prepare.ts+++ b/src/core/persistence/reconcile-prepare.ts@@ -13,7 +13,7 @@ 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 { materializeTimeline, 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';@@ -39,6 +39,10 @@ export async function prepareReconcileResult(engine: BrainEngine, state: Reconcifor (const key of ['compiled_truth', 'timeline'] as const) {result[key] = preservePrivateFacts(preserveProtectedTakes(result[key], state.snapshot.page[key] ?? ''), state.snapshot.page[key] ?? '');}+ // #5567: reconcile renders from the merged database state; an operator-approved+ // body decision edits the file side, every other merge preserves history.+ const writer = decisions.some(d => d.path === '/timeline' || d.path === '/compiled_truth') ? 'editing' : 'preserving';+ result.timeline = (await materializeTimeline(engine, result, state.pins.slug, state.snapshot, writer)).timeline;const content = serializePageToMarkdown({ ...state.snapshot.page, ...result }, result.tags);let ready: PreparedContentImport | undefined;const imported = await importFromContent(engine, state.pins.slug, content, {@@ -50,7 +54,7 @@ export async function prepareReconcileResult(engine: BrainEngine, state: Reconciif (!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);+ const project = await prepareCanonicalProjections(engine, resolved, state.pins.slug, state.pins.source_id, state.snapshot, writer);return { ...merged, result: resolved, ready, project };}diff --git a/src/core/persistence/reconcile-state.ts b/src/core/persistence/reconcile-state.tsindex 870f774410..6876481d79 100644--- a/src/core/persistence/reconcile-state.ts+++ b/src/core/persistence/reconcile-state.ts@@ -9,7 +9,7 @@ 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 { recordedPathFromFileUri, scannerSlugRootMode } from '../write-through.ts';import { localHostId } from './identity.ts';import { getWorktreeBinding, type WorktreeBinding } from './ownership.ts';import { digest, requireUuid, sha256, stableJson } from './digest.ts';@@ -39,8 +39,9 @@ export async function reconcilePolicyDigest(engine: BrainEngine, sourceId: strinexport 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);+function recordedReconcilePath(root: string, page: { slug: string; source_path?: string | null; source_uri?: string | null },+ mode: 'git-root' | 'source-root'): string | null {+ const path = resolveSourceLocalFilePath(root, page.source_path, page.slug, mode);if (path) return path;const recorded = recordedPathFromFileUri(page.source_uri, root);return recorded ? join(root, recorded) : null;@@ -58,7 +59,8 @@ export async function readReconcileState(engine: BrainEngine, sourceId: string,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);+ const mode = await scannerSlugRootMode(engine, sourceId, root);+ const path = recordedReconcilePath(root, snapshot.page, mode);if (!path || !isWriteTargetContained(path, root)) throw new OperationError('source_changed', 'The page has no unambiguous confined recorded Markdown origin.');let size: number;try {@@ -82,7 +84,7 @@ export async function readReconcileState(engine: BrainEngine, sourceId: string,'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);+ const candidatePath = recordedReconcilePath(root, candidate, mode);if (!candidatePath || !isWriteTargetContained(candidatePath, root)) continue;let canonicalCandidate: string;try { canonicalCandidate = realpathSync(candidatePath); }diff --git a/src/core/persistence/service.ts b/src/core/persistence/service.tsindex efd5338d39..704573669a 100644--- a/src/core/persistence/service.ts+++ b/src/core/persistence/service.ts@@ -97,7 +97,8 @@ export function assertPersistenceAccepting(engine: BrainEngine): void {/** The waiter never owns a provider, database connection, or kernel lock. */export async function waitForWrite(engine: BrainEngine, row: WriteRequest, config: GBrainConfig, waitMs = 5000): Promise<WriteRequest> {if (isTerminal(row)) return row;- startPersistenceConsumer(engine, config);+ // The admission transaction has committed: publish now, not after the idle backoff.+ startPersistenceConsumer(engine, config).wake();const service = services.get(engine)!;let reads = receiptReads.get(engine);if (!reads) { reads = new Map(); receiptReads.set(engine, reads); }diff --git a/src/core/persistence/source-storage.ts b/src/core/persistence/source-storage.tsnew file mode 100644index 0000000000..1471ed4a53--- /dev/null+++ b/src/core/persistence/source-storage.ts@@ -0,0 +1,56 @@+import { statSync } from 'node:fs';+import { join } from 'node:path';+import { OperationError } from '../ops/contract.ts';+import { hasUnresolvedDbOnlyDeclaration, isDeclaredDbOnlySlug, loadStorageConfig, type StorageConfig } from '../storage-config.ts';++type Loaded = { version: string; config: StorageConfig | null } | { version: string; cause: unknown };+// One parse per gbrain.yml version per source root: bulk scans and migrations+// ask once per page, and a rejected file is logged once rather than per page.+const loaded = new Map<string, Loaded>();++function load(root: string): StorageConfig | null {+ const path = join(root, 'gbrain.yml');+ let version: string;+ let statError: unknown;+ try {+ const stat = statSync(path);+ // On 1s-granularity filesystems a same-size rewrite within one second keeps this key.+ version = `${stat.mtimeMs}:${stat.ctimeMs}:${stat.size}`;+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') { loaded.delete(root); return null; }+ version = 'unreadable'; statError = error;+ }+ let entry = loaded.get(root);+ if (entry?.version !== version) {+ try {+ if (statError) throw statError;+ const config = loadStorageConfig(root);+ if (hasUnresolvedDbOnlyDeclaration(root, config)) throw new Error('storage.db_only is declared but no directory resolved from it');+ entry = { version, config };+ } catch (cause) {+ console.warn(`[persistence] Rejected ${path}: ${cause instanceof Error ? cause.message : String(cause)}`);+ entry = { version, cause };+ }+ loaded.set(root, entry);+ }+ // A fresh error per throw: callers may annotate the instance they receive.+ if ('cause' in entry) throw Object.assign(new OperationError('storage_error', 'The source storage configuration in gbrain.yml is invalid.',+ 'Run `gbrain storage status` for the exact problem, then fix gbrain.yml at the source root before writing to this source.'), { cause: entry.cause });+ return entry.config;+}++/**+ * Whether a page slug falls under a `storage.db_only` dir declared in the+ * gbrain.yml at this source root. A gbrain.yml that cannot be read, whose+ * tiers overlap, or that declares db_only in syntax resolving nothing is+ * logged once per version; `refuse` then throws `storage_error`, while+ * `not_db_only` answers false so the caller keeps its non-db_only behavior.+ */+export function isSourceDbOnlySlug(root: string, slug: string, onInvalid: 'refuse' | 'not_db_only'): boolean {+ try {+ return isDeclaredDbOnlySlug(slug, load(root));+ } catch (error) {+ if (onInvalid === 'refuse') throw error;+ return false;+ }+}diff --git a/src/core/persistence/sync-administration.ts b/src/core/persistence/sync-administration.tsindex f40ac935ac..f0028a1a72 100644--- a/src/core/persistence/sync-administration.ts+++ b/src/core/persistence/sync-administration.ts@@ -5,6 +5,7 @@ import { currentVerifiedLocalWriter } from './identity.ts';import { submissionAuthority } from './authority.ts';import type { OperationContext } from '../ops/contract.ts';import { validateSyncWireParams } from './sync-wire.ts';+import { explicitSyncProcessing } from './sync-authority.ts';/** Private CLI transport: wire fields can never manufacture a trust lane. */export async function runAuthenticatedSyncSlice(engine: BrainEngine, params: Record<string,unknown>): Promise<Record<string,unknown>> {@@ -35,7 +36,7 @@ export async function runAuthenticatedSyncSlice(engine: BrainEngine, params: Recreturn {...result,source_id:sourceId};}const {performManagedSync}=await import('./sync-run.ts');- return {...await performManagedSync(engine,{...wire.options,sourceId,signal:controller.signal},{maxPages:25,maxMs:1000}),source_id:sourceId};+ return {...await performManagedSync(engine,{...wire.options,sourceId,explicitProcessing:explicitSyncProcessing(wire.options as Record<string,unknown>),signal:controller.signal},{maxPages:25,maxMs:1000}),source_id:sourceId};})();return await work;} finally {if(timer)clearTimeout(timer);unregister();}diff --git a/src/core/persistence/sync-authority.ts b/src/core/persistence/sync-authority.tsindex 071a44aa2c..fdf77d40d3 100644--- a/src/core/persistence/sync-authority.ts+++ b/src/core/persistence/sync-authority.ts@@ -23,6 +23,11 @@ export interface SyncProcessingOptions { noEmbed: boolean; noExtract: boolean; nexport function syncProcessingOptions(opts: SyncOpts): SyncProcessingOptions {return { noEmbed: opts.noEmbed === true, noExtract: opts.noExtract === true, noSchemaPack: opts.noSchemaPack === true };}+export const SYNC_PROCESSING_KEYS = ['noEmbed', 'noExtract', 'noSchemaPack'] as const;+/** The processing options a caller set itself; an unfinished cursor supplies the rest (#5632). */+export function explicitSyncProcessing(values: Record<string, unknown>): Array<keyof SyncProcessingOptions> {+ return SYNC_PROCESSING_KEYS.filter(key => typeof values[key] === 'boolean');+}export function assertSyncDispatchActive(): void {assertSourceFilesystemActive(true);throwIfAborted(currentJobSignal());@@ -87,7 +92,7 @@ export function validateManagedSyncOptions(opts: SyncOpts): void {assertDurableSyncCaller();const current = currentSubmissionAuthority();if (current?.kind !== 'remote_generic') return;- const allowed = new Set(['repoPath','sourceId','noPull','noEmbed','noExtract','signal','concurrency','onProgress','auto_embed_backfill']);+ const allowed = new Set(['repoPath','sourceId','noPull','noEmbed','noExtract','explicitProcessing','signal','concurrency','onProgress','auto_embed_backfill']);if (current.grant.jobName !== 'sync' || opts.repoPath !== current.grant.canonicalRoot || opts.sourceId !== current.grant.sourceId ||opts.noPull !== true || opts.noEmbed !== true || opts.noExtract !== true ||Object.entries(opts).some(([key,value]) => value !== undefined && !allowed.has(key)) ||diff --git a/src/core/persistence/sync-discovery.ts b/src/core/persistence/sync-discovery.tsindex 917c7b857c..a97eb00489 100644--- a/src/core/persistence/sync-discovery.ts+++ b/src/core/persistence/sync-discovery.ts@@ -14,7 +14,7 @@ import { localHostId } from './identity.ts';import { sha256 } from './digest.ts';import { currentCompanyBrainSync } from '../company-brain/profile.ts';import type { CompanyBrainPlan } from '../company-brain/types.ts';-import { assertDistinctSyncOrigins, syncOriginPath } from './sync-origin.ts';+import { assertDistinctSyncOrigins, legacySyncOrigin, sameSyncOrigin, syncOriginPath, type SyncOriginScope } from './sync-origin.ts';import { assertManagedSyncActive } from './sync-authority.ts';export interface SyncEntry { path: string; sourcePath: string; action: 'import' | 'delete'; working: boolean; slug?: string; pageId?: number | null; revision?: string | null; }@@ -113,6 +113,7 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, cconst slugMode = company ? 'source-root' : scope ? await resolveSlugRootMode(engine, { sourceId, explicitGitRoot: opts.srcSubpath !== undefined,slugPrefix: probe.slice(0, -2), dryRun: true }) : 'git-root';const sourcePath = (path: string) => slugMode === 'source-root' && scope ? path.slice(scope.length + 1) : path;+ const originScope: SyncOriginScope = { sourceId, root, scope, slugMode };const exclude = [...(opts.exclude ?? []), ...(await engine.getConfig('sync.exclude') ?? '').split(/[\n,]/).map(v => v.trim()).filter(Boolean)].map(v => v.endsWith('/') ? `${v}**` : v);const includeHidden = [...new Set([...(opts.includeHidden ?? []), ...(await engine.getConfig('sync.include_hidden') ?? '')@@ -140,11 +141,13 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, cassertDistinctSyncOrigins(paths);const present = new Set(paths.map(path => syncOriginPath(sourcePath(path))));for (const path of paths) put(path, 'import');- const pages = await engine.executeRaw<{ source_path: string }>('SELECT source_path FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND source_path IS NOT NULL', [sourceId]);+ const pages = await engine.executeRaw<{ slug: string; source_path: string }>('SELECT slug,source_path FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND source_path IS NOT NULL', [sourceId]);assertDistinctSyncOrigins([...present, ...pages.map(page => page.source_path)]);for (const page of pages) {const origin = syncOriginPath(page.source_path);- if (!present.has(origin)) put(slugMode === 'source-root' && scope ? `${scope}/${origin}` : origin, 'delete');+ const stripped = slugMode === 'source-root' && scope && origin.startsWith(`${scope}/`) ? origin.slice(scope.length + 1) : null;+ if (present.has(origin) || stripped !== null && present.has(stripped) && sameSyncOrigin(origin, stripped, originScope, page.slug)) continue;+ put(slugMode === 'source-root' && scope ? `${scope}/${origin}` : origin, 'delete');}}if (working) {@@ -180,13 +183,20 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, cbyPath.set(origin, [...(byPath.get(origin) ?? []), page]);}for (const entry of selected) {- const origins = byPath.get(syncOriginPath(entry.sourcePath)) ?? [];+ const legacy = legacySyncOrigin(originScope, syncOriginPath(entry.sourcePath));+ const origins = [...byPath.get(syncOriginPath(entry.sourcePath)) ?? [],+ ...(legacy ? byPath.get(legacy) ?? [] : []).filter(page => sameSyncOrigin(page.source_path!, entry.sourcePath, originScope, page.slug))];if (origins.length > 1) throw new OperationError('page_identity_changed', 'Several pages claim the same imported origin.');let slug = entry.slug ?? origins[0]?.slug ?? resolveSlugForPath(entry.sourcePath);if (!slug && entry.action === 'import') slug = parseMarkdown(readSyncContent(discovered, entry), '').slug;if (!slug) throw new OperationError('invalid_params', 'The imported file has no usable page slug.');const page = origins[0] ?? bySlug.get(slug);- if (page?.source_path != null && syncOriginPath(page.source_path) !== syncOriginPath(entry.sourcePath)) throw new OperationError('page_identity_changed', 'A different origin occupies the imported slug.');+ if (page?.source_path != null && !sameSyncOrigin(page.source_path, entry.sourcePath, originScope, page.slug)) {+ const error = new OperationError('page_identity_changed', 'A different origin occupies the imported slug.',+ `Page ${slug} in source ${sourceId} records the origin '${page.source_path}', but sync found it at '${entry.sourcePath}'. On the brain host, rename or move one of the two files so each page has one origin, commit, then run gbrain sync --source ${sourceId} --no-pull --retry-failed.`);+ error.detail = 'sync_origin_mismatch';+ throw error;+ }Object.assign(entry, { slug, pageId: page?.id ?? null, revision: page?.knowledge_revision ?? null });}if (!working) {diff --git a/src/core/persistence/sync-origin.ts b/src/core/persistence/sync-origin.tsindex 1f12cde4cd..0e5ce221c4 100644--- a/src/core/persistence/sync-origin.ts+++ b/src/core/persistence/sync-origin.ts@@ -1,5 +1,47 @@+import { existsSync, realpathSync } from 'node:fs';+import { join, relative, sep } from 'node:path';import type { BrainEngine } from '../engine.ts';import { OperationError } from '../ops/contract.ts';+import { resolveSlugForPath } from '../sync.ts';++/** The source's position inside its Git repository and the origin form sync records. */+export interface SyncOriginScope { sourceId: string; root: string; scope: string; slugMode: 'git-root' | 'source-root'; }++export function syncOriginScope(context: { sourceId: string; root: string; gitRoot: string; slugMode: 'git-root' | 'source-root' }): SyncOriginScope {+ const scope = relative(realpathSync.native(context.gitRoot), realpathSync.native(context.root)).split(sep).join('/');+ return { sourceId: context.sourceId, root: context.root, scope, slugMode: context.slugMode };+}++/** The Git-root spelling write-through minted for a source-root origin before #5610. */+export function legacySyncOrigin(context: SyncOriginScope | undefined, origin: string): string | null {+ return context?.slugMode === 'source-root' && context.scope ? `${context.scope}/${origin}` : null;+}++/**+ * Whether a stored page origin names this sync origin. Under source-root mode a+ * stored `<scope>/<origin>` is the legacy Git-root form of `<origin>` only when+ * the page's slug is the slug of `<origin>` (write-through minted it from the+ * slug) and the source-relative reading names no real file; when both files+ * exist the stored origin is ambiguous and sync refuses instead of guessing.+ */+export function sameSyncOrigin(stored: string, origin: string, context?: SyncOriginScope, pageSlug?: string): boolean {+ const recorded = syncOriginPath(stored), expected = syncOriginPath(origin);+ const prefix = context?.slugMode === 'source-root' && context.scope ? `${context.scope}/` : null;+ if (!context || !prefix || !recorded.startsWith(prefix)) return recorded === expected;+ const stripped = recorded.slice(prefix.length);+ const legacy = pageSlug !== undefined && resolveSlugForPath(stripped) === pageSlug;+ if (recorded !== expected && (stripped !== expected || !legacy)) return false;+ if (!legacy) return true;+ const nested = existsSync(join(context.root, recorded));+ if (nested && existsSync(join(context.root, stripped))) {+ const error = new OperationError('page_identity_changed', 'A recorded page origin could name two files in this source.',+ `Source '${context.sourceId}' records '${recorded}', which can mean the file '${stripped}' or the file '${recorded}' under the source directory. `+ + `On the source host, rename or move one of those two files, commit, then run gbrain sync --source ${context.sourceId} --no-pull --retry-failed.`);+ error.detail = 'ambiguous_source_path';+ throw error;+ }+ return recorded === expected || !nested;+}export function syncOriginPath(path: string, platform = process.platform): string {const normalized = platform === 'win32' ? path.replaceAll('\\', '/') : path;@@ -24,13 +66,18 @@ export function assertDistinctSyncOrigins(paths: Iterable<string>, platform = pr}}-export async function assertSyncPageOrigin(engine: BrainEngine, sourceId: string, sourcePath: string, pageId: number | null, requireOrigin = false): Promise<void> {+export async function assertSyncPageOrigin(engine: BrainEngine, sourceId: string, sourcePath: string, pageId: number | null, requireOrigin = false,+ context?: SyncOriginScope): Promise<void> {const origin = syncOriginPath(sourcePath);- const pathSql = process.platform === 'win32' ? "lower(replace(source_path,chr(92),'/'))=lower($2)" : 'source_path=$2';- const pages = await engine.executeRaw<{ id: number; source_path: string }>(- `SELECT id,source_path FROM pages WHERE source_id=$1 AND ${pathSql}`, [sourceId, origin]);+ const legacy = legacySyncOrigin(context, origin);+ const candidates = [origin, ...(legacy ? [legacy] : [])];+ const pathSql = process.platform === 'win32' ? "lower(replace(source_path,chr(92),'/'))=ANY($2::text[])" : 'source_path=ANY($2::text[])';+ const key = (path: string) => process.platform === 'win32' ? syncOriginPath(path).toLowerCase() : syncOriginPath(path);+ const rows = await engine.executeRaw<{ id: number; slug: string; source_path: string }>(+ `SELECT id,slug,source_path FROM pages WHERE source_id=$1 AND ${pathSql}`, [sourceId, candidates.map(key)]);+ const pages = rows.filter(page => legacy === null || key(page.source_path) !== key(legacy) || sameSyncOrigin(page.source_path, origin, context, page.slug));if (pages.length > 1 || requireOrigin && pageId !== null && pages.length !== 1 ||- pages.some(page => page.id !== pageId || syncOriginPath(page.source_path) !== origin)) {+ pages.some(page => page.id !== pageId || !sameSyncOrigin(page.source_path, origin, context, page.slug))) {throw new OperationError('page_identity_changed', 'The imported origin no longer identifies exactly the accepted page.');}}diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.tsindex 2170348ab9..f508dc3420 100644--- a/src/core/persistence/sync-prepare.ts+++ b/src/core/persistence/sync-prepare.ts@@ -16,7 +16,7 @@ import { digest, sha256 } from './digest.ts';import { preserveProtectedTakes } from './protected-takes.ts';import { getWorktreeBinding } from './ownership.ts';import { assertConfiguredSyncRoot, assertSyncEntryOrigin, syncGit, syncRawHash } from './sync-discovery.ts';-import { assertSyncPageOrigin, syncOriginPath } from './sync-origin.ts';+import { assertSyncPageOrigin, sameSyncOrigin, syncOriginPath, syncOriginScope, type SyncOriginScope } from './sync-origin.ts';import { assertManagedSyncActive, validateSyncAuthority, type SyncAuthority, type SyncProcessingOptions } from './sync-authority.ts';import type { PreparedContentImport } from './prepared-import.ts';import type { PreparedMutation } from './coordinator.ts';@@ -57,6 +57,7 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Writep.path === null ? undefined : { root, path: join(root, p.path) });let origin: Parameters<typeof assertSyncEntryOrigin>[1] | undefined;let originContext: Parameters<typeof assertSyncEntryOrigin>[0] | undefined;+ let originScope: SyncOriginScope | undefined;if (p.kind !== 'managed_sync_checkpoint') {if (typeof p.path !== 'string' || typeof p.sourcePath !== 'string') throw new OperationError('storage_error', 'The accepted sync origin is missing.');let working = p.working;@@ -74,7 +75,8 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Writeorigin = { path: p.path, sourcePath: p.sourcePath, action: p.kind === 'managed_sync_delete' ? 'delete' : 'import', working };originContext = { root, gitRoot: realpathSync(syncGit(root, ['rev-parse', '--show-toplevel']).trim()), target: p.target, slugMode: p.slugMode };assertSyncEntryOrigin(originContext, origin);- await assertSyncPageOrigin(engine, row.source_id, p.sourcePath, row.page_id, p.kind === 'managed_sync_delete');+ originScope = syncOriginScope({ ...originContext, sourceId: row.source_id });+ await assertSyncPageOrigin(engine, row.source_id, p.sourcePath, row.page_id, p.kind === 'managed_sync_delete', originScope);}const validate = async (tx: BrainEngine) => {await assertManagedSyncActive(tx, true);@@ -91,7 +93,7 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Writeif (p.path !== null && syncRawHash(root, p.path) !== p.rawHash) throw new OperationError('source_changed', 'The imported file changed after sync admission.');if (origin && originContext) {assertSyncEntryOrigin(originContext, origin);- await assertSyncPageOrigin(tx, row.source_id, origin.sourcePath, row.page_id, p.kind === 'managed_sync_delete');+ await assertSyncPageOrigin(tx, row.source_id, origin.sourcePath, row.page_id, p.kind === 'managed_sync_delete', originScope);}if (p.companyApproval) {const [source] = await tx.executeRaw<{ config: unknown }>('SELECT config FROM sources WHERE id=$1', [row.source_id]);@@ -129,7 +131,7 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Writeconst source = { sourceId: row.source_id };const snapshot = await engine.readPageSnapshot(row.slug, { ...source, includeDeleted: true });assertPageRevision(snapshot, p.expected_revision === null ? {} : { expectedRevision: p.expected_revision });- if ((snapshot?.page.id ?? null) !== row.page_id || (snapshot?.page.source_path != null && syncOriginPath(snapshot.page.source_path) !== syncOriginPath(p.sourcePath!))) {+ if ((snapshot?.page.id ?? null) !== row.page_id || (snapshot?.page.source_path != null && !sameSyncOrigin(snapshot.page.source_path, p.sourcePath!, originScope, snapshot.page.slug))) {throw new OperationError('page_identity_changed', 'The imported path no longer names the accepted page.');}if (p.kind === 'managed_sync_delete') return { observedRevision: snapshot?.revision ?? null, noop: !snapshot || snapshot.page.deleted_at != null,@@ -200,7 +202,7 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Writeconst overlay = digest(canonical(parsed, parsed.tags)) !== digest(canonical(ready.parsedPage, tags));if (overlay && p.companyApproval) throw new OperationError('source_writeback_required', 'Canonical preparation requires a source-content correction; this profile never writes repository files.');if (overlay && !p.lineEndingOnly && p.rawHash !== sha256(p.content)) throw new OperationError('source_changed', 'Canonical sanitization cannot overwrite newer working-tree bytes.');- const project = prepareCanonicalProjections(ready.parsedPage, row.slug, row.source_id);+ const project = await prepareCanonicalProjections(engine, ready.parsedPage, row.slug, row.source_id, snapshot, p.companyApproval ? 'immutable' : 'file');return { observedRevision: snapshot?.revision ?? null,validate: async tx => { await validate(tx); await ready.validate(tx); },deferEmbedding: p.processingOptions?.noEmbed,diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.tsindex d166183312..7523ccfbae 100644--- a/src/core/persistence/sync-run.ts+++ b/src/core/persistence/sync-run.ts@@ -10,8 +10,8 @@ import { getWriteRequest, admitWriteInTransaction, receiptFor } from './journal.import { retryWriteAdmission } from './admission-retry.ts';import { assertPersistenceAccepting, foregroundWriteCompletions, startPersistenceConsumer, waitForWrite } from './service.ts';import { assertSyncEntryOrigin, discoverManagedSync, resolveManagedSyncContext, readSyncContent, readSyncFile, syncGit, type SyncDiscovery } from './sync-discovery.ts';-import { assertSyncPageOrigin, syncOriginPath } from './sync-origin.ts';-import { assertManagedSyncActive, assertSyncDispatchActive, managedSyncAuthority, validateSyncAuthority, validateManagedSyncOptions, syncProcessingOptions, type SyncAuthority, type SyncProcessingOptions } from './sync-authority.ts';+import { assertSyncPageOrigin, sameSyncOrigin, syncOriginScope } from './sync-origin.ts';+import { assertManagedSyncActive, assertSyncDispatchActive, managedSyncAuthority, validateSyncAuthority, validateManagedSyncOptions, syncProcessingOptions, SYNC_PROCESSING_KEYS, type SyncAuthority, type SyncProcessingOptions } 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';@@ -142,7 +142,8 @@ async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string, asslet lineEndingOnly = false;if (entry) {assertSyncEntryOrigin(cursor, entry);- await assertSyncPageOrigin(engine, cursor.sourceId, entry.sourcePath, entry.pageId ?? null, entry.action === 'delete');+ const originScope = syncOriginScope(cursor);+ await assertSyncPageOrigin(engine, cursor.sourceId, entry.sourcePath, entry.pageId ?? null, entry.action === 'delete', originScope);assertActive();const bytes = readSyncFile(cursor.root, entry.path);rawHash = bytes === null ? null : sha256(bytes);@@ -159,7 +160,7 @@ async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string, assconst snapshot = await engine.readPageSnapshot(slug, { sourceId: cursor.sourceId, includeDeleted: true });assertActive();if ((snapshot?.page.id ?? null) !== pageId || (snapshot?.revision ?? null) !== revision ||- (snapshot?.page.source_path != null && syncOriginPath(snapshot.page.source_path) !== syncOriginPath(entry.sourcePath))) {+ (snapshot?.page.source_path != null && !sameSyncOrigin(snapshot.page.source_path, entry.sourcePath, originScope, snapshot.page.slug))) {throw new OperationError('revision_conflict', 'A page changed after this sync cursor was enumerated.');}}@@ -286,9 +287,20 @@ export async function performManagedSync(engine: BrainEngine, opts: SyncOpts, slString(cursor.binding.owner_epoch) !== String(context.binding.owner_epoch) || cursor.root !== context.root) {throw new OperationError('source_changed', 'The unfinished sync cursor belongs to an older source binding.');}- if (cursor.processingOptions ? digest(cursor.processingOptions) !== digest(processingOptions) : !cursor.pending) {- throw new OperationError('invalid_params', 'The unfinished sync has different or unknown processing options.',- 'Resume with the original --no-embed, --no-extract and --no-schema-pack options. After resolving pending requests, use --retry-failed for explicit rediscovery; existing requests are not rewritten.');+ const stored = cursor.processingOptions;+ if (stored ? digest(stored) !== digest(processingOptions) : !cursor.pending) {+ // An unattended or flagless resume adopts the cursor's options; freezeEntry reads them from the cursor.+ const explicit = opts.explicitProcessing ?? SYNC_PROCESSING_KEYS;+ if (!stored || explicit.some(key => stored[key] !== processingOptions[key])) {+ const flags = { noEmbed: '--no-embed', noExtract: '--no-extract', noSchemaPack: '--no-schema-pack' } as const;+ const resume = stored ? ` Resume it with: gbrain sync --source ${cursor.sourceId} --no-pull${SYNC_PROCESSING_KEYS.filter(key => stored[key]).map(key => ` ${flags[key]}`).join('')}`+ + ' (or omit the conflicting flag to adopt the stored options).' : '';+ const error = new OperationError('invalid_params', 'The unfinished sync has different or unknown processing options.',+ `The unfinished sync cursor for source ${cursor.sourceId} stores ${stored ? SYNC_PROCESSING_KEYS.map(key => `${key}=${stored[key]}`).join(', ') : 'no processing options'}.${resume}`+ + ' After resolving pending requests, use --retry-failed for explicit rediscovery; existing requests are not rewritten.');+ error.detail = 'cursor_processing_options_conflict';+ throw error;+ }}if (opts.dryRun) return result(cursor, 'dry_run');const config = loadConfig() ?? { engine: engine.kind };diff --git a/src/core/persistence/topology-recovery.ts b/src/core/persistence/topology-recovery.tsindex 022fe61bb5..68c59982ef 100644--- a/src/core/persistence/topology-recovery.ts+++ b/src/core/persistence/topology-recovery.ts@@ -179,7 +179,7 @@ export async function finishTopologyClone(engine:BrainEngine,id:string,hooks:Cloconst recoveryCursors=new WeakMap<BrainEngine,string>();/** A bounded rotating scan keeps persistent conflicts from starving other roots. */-export async function recoverSourceTopologies(engine:BrainEngine,opts:{hostId?:string;limit?:number}={}):Promise<number>{+export async function recoverSourceTopologies(engine:BrainEngine,opts:{hostId?:string;limit?:number;onAttempt?:(id:string,recovered:boolean)=>void}={}):Promise<number>{const host=opts.hostId??localHostId(),limit=Math.max(1,Math.min(16,opts.limit??2));const scan=async(after:string|null)=>engine.executeRaw<TopologyChange>(`SELECT c.* FROM persistence_topology_changes cJOIN persistence_worktrees w ON w.id=(c.recovery->>'worktreeId')::uuid@@ -190,8 +190,10 @@ export async function recoverSourceTopologies(engine:BrainEngine,opts:{hostId?:sif(rows.length)recoveryCursors.set(engine,rows[rows.length-1].id);let recovered=0;for(const row of rows){- try{await withTopologyLocks(engine,row.source_id,async()=>{const done=await finishTopologyClone(engine,row.id);if(!done.recovery)recovered++;},undefined,0);}+ let finished=false;+ try{await withTopologyLocks(engine,row.source_id,async()=>{const done=await finishTopologyClone(engine,row.id);if(!done.recovery){recovered++;finished=true;}},undefined,0);}catch(error){if(!(error instanceof OperationError&&['write_pending','recovery_required'].includes(error.code)))throw error;}+ finally{opts.onAttempt?.(row.id,finished);}}return recovered;}diff --git a/src/core/persistence/types.ts b/src/core/persistence/types.tsindex e68f6208aa..a3cc58e8c5 100644--- a/src/core/persistence/types.ts+++ b/src/core/persistence/types.ts@@ -14,7 +14,7 @@ export const WRITE_ERROR_CODES = ['writer_registration_required', 'writer_identity_invalid', 'writer_not_initialized','writer_coordinator_required', 'fact_already_expired', 'source_writeback_required','unsupported_mutation_protocol', 'writer_upgrade_required', 'writer_not_quiesced',- 'skill_bundle_required',+ 'skill_bundle_required', 'take_row_collision', 'invalid_source_uri',] as const;export type WriteErrorCode = typeof WRITE_ERROR_CODES[number];diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.tsindex 69a047e9ae..7a1ddd6f53 100644--- a/src/core/pglite-engine.ts+++ b/src/core/pglite-engine.ts@@ -113,7 +113,7 @@ import { PAGE_SORT_SQL, MIN_ENTITY_PAGES_FOR_COVERAGE } from './types.ts';import { finalizeLastSeen } from './chronicle/last-seen.ts';import { resolveBoostMap, resolveHardExcludes } from './search/source-boost.ts';import { buildSourceFactorCase, buildHardExcludeClause, buildVisibilityClause, buildBestPerPagePoolCte, buildOrFallbackWebsearchQuery, boundWebsearchQuery } from './search/sql-ranking.ts';-import { privatePagesFilterFragment, privateLinkOriginFilterFragment, privateTimelineEventFilterFragment, privateProvenanceFilterFragment } from './search/private-visibility.ts';+import { privatePagesFilterFragment, privateSnapshotFilterFragment, privateLinkOriginFilterFragment, privateTimelineEventFilterFragment, privateProvenanceFilterFragment } from './search/private-visibility.ts';import { unverifiedExtractionFragment } from './extraction-review.ts';import { shouldExcludeFromOrphanReporting, loadOrphanPolicyOverrides } from './orphan-policy.ts';import { LINK_EXTRACTOR_VERSION_TS } from './link-extraction.ts';@@ -133,6 +133,7 @@ import { hasCJK } from './cjk.ts';import * as factsImpl from './pglite-engine/facts.ts';import type { PgliteFactsDeps } from './pglite-engine/facts.ts';import * as takesImpl from './pglite-engine/takes.ts';+import { PgliteCheckpointGuard } from './pglite-engine/checkpoint-guard.ts';import type { PgliteTakesDeps } from './pglite-engine/takes.ts';import * as codeEdgesImpl from './pglite-engine/code-edges.ts';import type { PgliteCodeEdgesDeps } from './pglite-engine/code-edges.ts';@@ -700,6 +701,7 @@ export class PGLiteEngine implements BrainEngine {private vectorIterativeScan?: Promise<boolean>;/** Transaction clones keep chunk invalidation and replacement atomic. */private _chunkWritesInTransaction = false;+ private _checkpointGuard: PgliteCheckpointGuard | undefined;readonly kind = 'pglite' as const;private _db: PGLiteDB | null = null;private _lock: LockHandle | null = null;@@ -719,6 +721,7 @@ export class PGLiteEngine implements BrainEngine {private _attachDatabase(database: PGLiteDB): PGLiteDB {this._dbWork = trackPgliteDatabase(database);+ this._checkpointGuard = undefined;return this._dbWork.database;}// #2034: captured at connect() so reconnect() can restore the same data dir@@ -1707,7 +1710,7 @@ export class PGLiteEngine implements BrainEngine {}async transaction<T>(fn: (engine: BrainEngine) => Promise<T>): Promise<T> {- return this.db.transaction(async handle => {+ const run = (db = this.db) => db.transaction(async handle => {const tx = composablePgliteTransaction(handle);const txEngine = Object.create(this) as PGLiteEngine;Object.defineProperty(txEngine, '_chunkWritesInTransaction', { value: true });@@ -1715,6 +1718,9 @@ export class PGLiteEngine implements BrainEngine {Object.defineProperty(txEngine, 'db', { get: () => tx });return fn(txEngine);});+ if (this._pageTransaction || !this._dbWork) return run();+ const guard = this._checkpointGuard ??= new PgliteCheckpointGuard();+ return this._dbWork.admit(db => guard.runOutermost(sql => db.query(sql), () => run(db)));}async transactionDirect<T>(fn: (engine: BrainEngine) => Promise<T>): Promise<T> {@@ -3202,7 +3208,7 @@ export class PGLiteEngine implements BrainEngine {// #4246: embedded_text_hash records md5(chunk_text) AT EMBED TIME so a// later text rewrite that keeps the vector is detectable as content// drift (invalidateContentDriftEmbeddings). NULL when no embedding lands.- const cols = `(page_id, chunk_index, chunk_text, chunk_source, ${writeColId}, model, token_count, embedded_at, embedded_text_hash, language, symbol_name, symbol_type, start_line, end_line, parent_symbol_path, doc_comment, symbol_name_qualified, modality, embedding_image)`;+ const cols = `(page_id, chunk_index, chunk_text, chunk_source, ${writeColId}, model, token_count, embedded_at, embedded_text_hash, embedding_input_hash, language, symbol_name, symbol_type, start_line, end_line, parent_symbol_path, doc_comment, symbol_name_qualified, modality, embedding_image)`;const rowParts: string[] = [];const params: unknown[] = [];let paramIdx = 1;@@ -3247,10 +3253,13 @@ export class PGLiteEngine implements BrainEngine {// #4246: hash in SQL (not JS) so stamp + drift comparison share ONE// md5 implementation. Binds chunk_text a second time.const embeddedTextHashPh = embeddingStr ? `md5($${paramIdx++})` : 'NULL';+ // #5553: embedding-input provenance travels only with the vector it describes.+ const embeddingInputHash = embeddingStr ? chunk.embedding_input_hash ?? null : null;+ const embeddingInputHashPh = embeddingInputHash ? `$${paramIdx++}` : 'NULL';rowParts.push(`($${paramIdx++}, $${paramIdx++}, $${paramIdx++}, $${paramIdx++}, ` +- `${embeddingPh}, $${paramIdx++}, $${paramIdx++}, ${embeddedAtPh}, ${embeddedTextHashPh}, ` ++ `${embeddingPh}, $${paramIdx++}, $${paramIdx++}, ${embeddedAtPh}, ${embeddedTextHashPh}, ${embeddingInputHashPh}, ` +`$${paramIdx++}, $${paramIdx++}, $${paramIdx++}, $${paramIdx++}, $${paramIdx++}, ` +`$${paramIdx++}::text[], $${paramIdx++}, $${paramIdx++}, ` +`$${paramIdx++}, ${embeddingImagePh})`,@@ -3265,6 +3274,7 @@ export class PGLiteEngine implements BrainEngine {if (embeddingStr) params.push(embeddingStr);if (embeddingImageStr) params.push(embeddingImageStr);if (embeddingStr) params.push(sanitizedChunkText); // embedded_text_hash md5() input+ if (embeddingInputHash) params.push(embeddingInputHash);params.push(pageId, chunk.chunk_index, sanitizedChunkText, chunk.chunk_source,chunk.model || resolvedModel, chunk.token_count || null,@@ -3327,6 +3337,14 @@ export class PGLiteEngine implements BrainEngine {THEN EXCLUDED.embedded_text_hashELSE content_chunks.embedded_text_hashEND,+ embedding_input_hash = CASE+ WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.embedding_input_hash+ WHEN content_chunks.${writeColId} IS NULL THEN EXCLUDED.embedding_input_hash+ WHEN EXCLUDED.embedded_at IS NOT NULL+ AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at)+ THEN EXCLUDED.embedding_input_hash+ ELSE content_chunks.embedding_input_hash+ END,language = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.language ELSE COALESCE(EXCLUDED.language, content_chunks.language) END,symbol_name = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_name ELSE COALESCE(EXCLUDED.symbol_name, content_chunks.symbol_name) END,symbol_type = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_type ELSE COALESCE(EXCLUDED.symbol_type, content_chunks.symbol_type) END,@@ -5432,7 +5450,7 @@ export class PGLiteEngine implements BrainEngine {async getVersions(slug: string, opts?: { sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean }): Promise<PageVersion[]> {const privacy = opts?.excludePrivate- ? `AND ${privatePagesFilterFragment('p')} AND ${privatePagesFilterFragment('pv')}` : '';+ ? `AND ${privatePagesFilterFragment('p')} AND ${privateSnapshotFilterFragment('pv')}` : '';if (opts?.sourceIds && opts.sourceIds.length > 0) {const { rows } = await this.db.query(`SELECT pv.* FROM page_versions pvdiff --git a/src/core/pglite-engine/checkpoint-guard.ts b/src/core/pglite-engine/checkpoint-guard.tsnew file mode 100644index 0000000000..efca898876--- /dev/null+++ b/src/core/pglite-engine/checkpoint-guard.ts@@ -0,0 +1,82 @@+/**+ * #5449/#5284: PGLite runs Postgres as one in-process backend with no+ * checkpointer. When WAL since the last redo point reaches the automatic+ * trigger, Postgres runs the checkpoint inline inside whatever WAL write+ * crossed the segment boundary, and on PGLite 0.4.x that nested checkpoint+ * spins forever at 100% CPU. The guard keeps the automatic trigger from ever+ * firing mid-transaction: before an outermost write transaction begins, it+ * runs a top-level CHECKPOINT once WAL since redo passes half of the trigger+ * distance (256 MB with the default 1 GB max_wal_size).+ */+import { GBrainError } from '../types.ts';++export const CHECKPOINT_GUARD_MAX_BYTES = 256 * 1024 * 1024;++type Query = (sql: string) => Promise<{ rows: Array<Record<string, unknown>> }>;++/**+ * Postgres requests a checkpoint when a new WAL segment number reaches+ * redo_segment + CheckPointSegments - 1, where CheckPointSegments is+ * floor(max_wal_size / (segment * (1 + checkpoint_completion_target))), at+ * least 1. Half that distance leaves room for one large transaction.+ */+export function checkpointGuardThreshold(maxWalBytes: number, segmentBytes: number, completionTarget: number): number {+ const segments = Math.max(1, Math.floor(maxWalBytes / (segmentBytes * (1 + completionTarget))));+ return Math.min(CHECKPOINT_GUARD_MAX_BYTES, Math.max(segmentBytes, (segments - 1) * segmentBytes) / 2);+}++export class PgliteCheckpointGuard {+ private threshold: number | undefined;+ private warned = false;+ private tail: Promise<void> = Promise.resolve();++ /** `query` replaces the admitted database's query function (tests inject failures here). */+ constructor(private readonly override?: Query, private readonly warn: (message: string) => void = message => console.warn(message)) {}++ /**+ * PGLite already runs one transaction at a time; queuing the probe with its+ * transaction makes each outermost transaction see the WAL its predecessors+ * wrote, so concurrent callers cannot all pass one stale probe.+ */+ async runOutermost<T>(query: Query, transaction: () => Promise<T>): Promise<T> {+ const prior = this.tail;+ const turn = Promise.withResolvers<void>();+ this.tail = turn.promise;+ await prior;+ try {+ await this.beforeOutermostTransaction(this.override ?? query);+ return await transaction();+ } finally { turn.resolve(); }+ }++ private async beforeOutermostTransaction(query: Query): Promise<void> {+ let walSinceRedo: number;+ try {+ if (this.threshold === undefined) {+ const [settings] = (await query(`SELECT pg_size_bytes(current_setting('max_wal_size'))::float8 AS max_wal,+ pg_size_bytes(current_setting('wal_segment_size'))::float8 AS segment,+ current_setting('checkpoint_completion_target')::float8 AS target`)).rows;+ this.threshold = checkpointGuardThreshold(Number(settings!.max_wal), Number(settings!.segment), Number(settings!.target));+ }+ const [probe] = (await query(+ 'SELECT pg_wal_lsn_diff(pg_current_wal_lsn(), redo_lsn)::float8 AS since_redo FROM pg_control_checkpoint()')).rows;+ walSinceRedo = Number(probe!.since_redo);+ if (!Number.isFinite(walSinceRedo)) throw new Error('WAL position is unavailable');+ } catch (error) {+ if (!this.warned) {+ this.warned = true;+ this.warn(`[pglite] WAL checkpoint guard is unavailable (${error instanceof Error ? error.message : String(error)}); `+ + 'continuing without it. Large imports may stall; restart the command to resume if one does.');+ }+ return;+ }+ if (walSinceRedo < this.threshold) return;+ try {+ await query('CHECKPOINT');+ } catch (error) {+ throw new GBrainError('PGLite checkpoint failed',+ `a top-level CHECKPOINT before the next write transaction failed (${error instanceof Error ? error.message : String(error)}); the transaction was not started`,+ 'stop other gbrain processes, restart the command, and run `gbrain pglite-repair --dry-run` if it fails again');+ }+ }+}diff --git a/src/core/pglite-lifecycle.ts b/src/core/pglite-lifecycle.tsindex 2f94c03f87..e1c0418a84 100644--- a/src/core/pglite-lifecycle.ts+++ b/src/core/pglite-lifecycle.ts@@ -21,6 +21,7 @@ export function trackPgliteDatabase<T extends object>(database: T): {database: T;stopAndDrain(): Promise<void>;checkpoint(): Promise<void>;+ admit<R>(run: (database: T) => Promise<R>): Promise<R>;} {const pending = new Set<Promise<unknown>>();const tracked = new Set(['query', 'exec', 'transaction', 'runExclusive']);@@ -55,6 +56,14 @@ export function trackPgliteDatabase<T extends object>(database: T): {accepting = false;await Promise.allSettled([...pending]);},+ /** Admit a multi-step operation once; it runs on the raw database and shutdown drains it. */+ admit<R>(run: (raw: T) => Promise<R>): Promise<R> {+ if (!accepting) return Promise.reject(new Error('PGLite not connected: datastore is closing'));+ const result = Promise.resolve().then(() => run(database));+ pending.add(result);+ void result.then(() => pending.delete(result), () => pending.delete(result));+ return result;+ },async checkpoint() {const query = Reflect.get(database, 'query', database);if (typeof query !== 'function') throw new TypeError('PGLite query method is unavailable');diff --git a/src/core/pglite-schema.ts b/src/core/pglite-schema.tsindex f01f27c0fb..5f80868f6c 100644--- a/src/core/pglite-schema.ts+++ b/src/core/pglite-schema.ts@@ -241,6 +241,8 @@ CREATE TABLE IF NOT EXISTS content_chunks (-- #4246 (v133): md5(chunk_text) at embed time. NULL = no embedding or-- pre-v133 row (grandfathered by invalidateContentDriftEmbeddings).embedded_text_hash TEXT,+ -- #5553 (v171): embedding-input provenance written with the vector.+ embedding_input_hash TEXT,created_at TIMESTAMPTZ NOT NULL DEFAULT now(),-- v0.19.0: code chunk metadata (markdown chunks leave NULL).language TEXT,diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex 5fe1e810e7..564ba9abe3 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -103,7 +103,7 @@ import { drainBackgroundWorkBeforeDisconnect } from './background-work.ts';import { validateSlug, contentHash, isBlankBody, rowToPage, rowToStalePage, rowToChunk, rowToSearchResult, parseEmbedding, tryParseEmbedding, isUndefinedTableError, warnOncePerProcess } from './utils.ts';import { resolveBoostMap, resolveHardExcludes } from './search/source-boost.ts';import { buildSourceFactorCase, buildHardExcludeClause, buildVisibilityClause, buildBestPerPagePoolCte, buildOrFallbackWebsearchQuery, boundWebsearchQuery } from './search/sql-ranking.ts';-import { privatePagesFilterFragment, privateLinkOriginFilterFragment, privateTimelineEventFilterFragment, privateProvenanceFilterFragment } from './search/private-visibility.ts';+import { privatePagesFilterFragment, privateSnapshotFilterFragment, privateLinkOriginFilterFragment, privateTimelineEventFilterFragment, privateProvenanceFilterFragment } from './search/private-visibility.ts';import { unverifiedExtractionFragment } from './extraction-review.ts';import { DEFAULT_EMBEDDING_MODEL, DEFAULT_EMBEDDING_DIMENSIONS } from './ai/defaults.ts';import { readStoredEmbeddingIdentity } from './stored-embedding-identity.ts';@@ -2355,7 +2355,7 @@ export class PostgresEngine implements BrainEngine {// #4246: embedded_text_hash records md5(chunk_text) AT EMBED TIME so a// later text rewrite that keeps the vector is detectable as content// drift (invalidateContentDriftEmbeddings). NULL when no embedding lands.- const cols = `(page_id, chunk_index, chunk_text, chunk_source, ${writeColId}, model, token_count, embedded_at, embedded_text_hash, language, symbol_name, symbol_type, start_line, end_line, parent_symbol_path, doc_comment, symbol_name_qualified, modality, embedding_image)`;+ const cols = `(page_id, chunk_index, chunk_text, chunk_source, ${writeColId}, model, token_count, embedded_at, embedded_text_hash, embedding_input_hash, language, symbol_name, symbol_type, start_line, end_line, parent_symbol_path, doc_comment, symbol_name_qualified, modality, embedding_image)`;const rows: string[] = [];const params: unknown[] = [];let paramIdx = 1;@@ -2397,10 +2397,13 @@ export class PostgresEngine implements BrainEngine {// #4246: hash in SQL (not JS) so stamp + drift comparison share ONE// md5 implementation. Binds chunk_text a second time.const embeddedTextHashPh = embeddingStr ? `md5($${paramIdx++})` : 'NULL';+ // #5553: embedding-input provenance travels only with the vector it describes.+ const embeddingInputHash = embeddingStr ? chunk.embedding_input_hash ?? null : null;+ const embeddingInputHashPh = embeddingInputHash ? `$${paramIdx++}` : 'NULL';rows.push(`($${paramIdx++}, $${paramIdx++}, $${paramIdx++}, $${paramIdx++}, ` +- `${embeddingPh}, $${paramIdx++}, $${paramIdx++}, ${embeddedAtPh}, ${embeddedTextHashPh}, ` ++ `${embeddingPh}, $${paramIdx++}, $${paramIdx++}, ${embeddedAtPh}, ${embeddedTextHashPh}, ${embeddingInputHashPh}, ` +`$${paramIdx++}, $${paramIdx++}, $${paramIdx++}, $${paramIdx++}, $${paramIdx++}, ` +`$${paramIdx++}::text[], $${paramIdx++}, $${paramIdx++}, ` +`$${paramIdx++}, ${embeddingImagePh})`,@@ -2413,6 +2416,7 @@ export class PostgresEngine implements BrainEngine {if (embeddingStr) params.push(embeddingStr);if (embeddingImageStr) params.push(embeddingImageStr);if (embeddingStr) params.push(sanitizedChunkText); // embedded_text_hash md5() input+ if (embeddingInputHash) params.push(embeddingInputHash);params.push(pageId, chunk.chunk_index, sanitizedChunkText, chunk.chunk_source,chunk.model || resolvedModel, chunk.token_count || null,@@ -2491,6 +2495,14 @@ export class PostgresEngine implements BrainEngine {THEN EXCLUDED.embedded_text_hashELSE content_chunks.embedded_text_hashEND,+ embedding_input_hash = CASE+ WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.embedding_input_hash+ WHEN content_chunks.${writeColId} IS NULL THEN EXCLUDED.embedding_input_hash+ WHEN EXCLUDED.embedded_at IS NOT NULL+ AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at)+ THEN EXCLUDED.embedding_input_hash+ ELSE content_chunks.embedding_input_hash+ END,language = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.language ELSE COALESCE(EXCLUDED.language, content_chunks.language) END,symbol_name = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_name ELSE COALESCE(EXCLUDED.symbol_name, content_chunks.symbol_name) END,symbol_type = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_type ELSE COALESCE(EXCLUDED.symbol_type, content_chunks.symbol_type) END,@@ -4636,7 +4648,7 @@ export class PostgresEngine implements BrainEngine {async getVersions(slug: string, opts?: { sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean }): Promise<PageVersion[]> {const sql = this.sql;const privacy = opts?.excludePrivate- ? sql.unsafe(`AND ${privatePagesFilterFragment('p')} AND ${privatePagesFilterFragment('pv')}`) : sql``;+ ? sql.unsafe(`AND ${privatePagesFilterFragment('p')} AND ${privateSnapshotFilterFragment('pv')}`) : sql``;if (opts?.sourceIds && opts.sourceIds.length > 0) {const rows = await sql`SELECT pv.* FROM page_versions pvdiff --git a/src/core/remediation/context.ts b/src/core/remediation/context.tsindex 1d31351000..7198b67408 100644--- a/src/core/remediation/context.ts+++ b/src/core/remediation/context.ts@@ -14,6 +14,24 @@ import type { RecommendationContext } from '../brain-score-recommendations.ts';// brain-score-recommendations.ts (it's also the input to computeRecommendations).export type { RecommendationContext };+/**+ * #5609: `extract --stale` refuses without the active schema pack, so a+ * recommendation would dispatch a job that fails every cycle. Shared by doctor+ * and autopilot so both planners withhold it together.+ */+export async function staleExtractionBlocked(engine: BrainEngine, sourceId?: string): Promise<string | undefined> {+ const { loadActivePackForLocalEngine } = await import('../schema-pack/best-effort.ts');+ const { LINK_EXTRACTOR_VERSION_TS } = await import('../link-extraction.ts');+ const sourceIds = sourceId ? [sourceId]+ : (await engine.executeRaw<{ id: string }>('SELECT id FROM sources WHERE NOT archived ORDER BY id')).map(row => row.id);+ for (const id of sourceIds) {+ if (await loadActivePackForLocalEngine(engine, { sourceId: id })) continue;+ if (!sourceId && !await engine.countStalePagesForExtraction({ sourceId: id, versionTs: LINK_EXTRACTOR_VERSION_TS })) continue;+ return `active schema pack is unavailable for source ${id}; extract --stale cannot run until \`gbrain doctor\` schema-pack checks pass`;+ }+ return undefined;+}+/*** Build RecommendationContext from engine + config. Pure read; no* side effects. Used by computeRemediationPlan, runRemediation, and@@ -73,5 +91,7 @@ export async function loadRecommendationContext(// dispatch loop, so the two planners can never disagree on this).hasChatApiKey: chatApiKeyConfigured(fileCfg),nullSignatureCohort,+ // Fail open like the cohort probe: a probe bug must never hide remediation.+ staleExtractionBlocked: await staleExtractionBlocked(engine).catch(() => undefined),};}diff --git a/src/core/remediation/plan.ts b/src/core/remediation/plan.tsindex d2a4bb69d7..e003e388fc 100644--- a/src/core/remediation/plan.ts+++ b/src/core/remediation/plan.ts@@ -25,6 +25,7 @@ export const SYNTHETIC_CHECK_NAMES = ['missing_embeddings','dead_links','orphan_pages',+ 'links_extraction_lag',] as const;/**diff --git a/src/core/remote-body.ts b/src/core/remote-body.tsindex 30da48eaf9..a2851b67ea 100644--- a/src/core/remote-body.ts+++ b/src/core/remote-body.ts@@ -1,6 +1,7 @@import { FACTS_FENCE_BEGIN, FACTS_FENCE_END, parseFactsFence, renderFactsTable } from './facts-fence.ts';import { TAKES_FENCE_BEGIN, TAKES_FENCE_END } from './takes-fence.ts';import { sanitizeText } from './batch-rows.ts';+import { stripMaterializedMarkers } from './timeline-marker.ts';const protectedMarkerPattern = new RegExp([FACTS_FENCE_BEGIN, FACTS_FENCE_END, TAKES_FENCE_BEGIN, TAKES_FENCE_END]@@ -8,12 +9,17 @@ const protectedMarkerPattern = new RegExp('g',);-/** Strict protected-body boundary shared by remote reads and chunk creation. */-export function sanitizeRemoteBody(body: string, opts: { includeWithdrawn?: boolean } = {}): string {+/**+ * Strict protected-body boundary shared by remote reads and chunk creation.+ * #5567 materialized-timeline marker lines are dropped unless the caller+ * round-trips the body (`keepMaterializedMarkers`).+ */+export function sanitizeRemoteBody(body: string, opts: { includeWithdrawn?: boolean; keepMaterializedMarkers?: boolean } = {}): string {if (typeof body !== 'string') return '';// Parse the same free-text bytes storage accepts. Removing NUL after fence// detection could turn an unrecognized marker into a protected stored fence.body = sanitizeText(body);+ if (!opts.keepMaterializedMarkers) body = stripMaterializedMarkers(body);let cursor = 0;const output: string[] = [];let open: { start: number; endMarker: string; facts: boolean } | undefined;diff --git a/src/core/repair/core.ts b/src/core/repair/core.tsnew file mode 100644index 0000000000..af1b826355--- /dev/null+++ b/src/core/repair/core.ts@@ -0,0 +1,205 @@+/**+ * `gbrain repair <kind>` core: one scope resolver, a resumable per-kind cursor,+ * the capacity stop, and the dry-run / apply loop shared by every kind.+ *+ * Every applied item is one coordinated page write (a `put_page` bound to the+ * page's current revision), so a repair never bypasses the persistence+ * coordinator and each item commits or fails on its own. A kind that only+ * rebuilds derived projections (`safe-chunks`) takes no admission instead: its+ * items cost no lifetime IDs or receipt bytes and never hit the capacity stop.+ * Items are processed in+ * a stable order and the cursor after the last committed item is stored in+ * `op_checkpoints` under a fingerprint of (kind, brain, sources): a rerun with+ * the same scope resumes after it, and a finished scan clears it.+ */+import type { BrainEngine } from '../engine.ts';+import type { OperationContext } from '../ops/contract.ts';+import { OperationError } from '../ops/contract.ts';+import { digest } from '../persistence/digest.ts';+import { readJournalLimits, journalLimitKey } from '../persistence/limits.ts';+import { isTerminal, principalKey } from '../persistence/model.ts';+import { getWriteRequest } from '../persistence/journal.ts';+import { initializeLocalPersistence, requestPrincipalForContext } from '../persistence/page-mutations.ts';+import { lookupEmbeddingPrice, estimateCostFromChars } from '../embedding-pricing.ts';++export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks'] as const;+export type RepairKind = typeof REPAIR_KINDS[number];++export interface RepairScope { brain_id: string; source_ids: string[] }++/** A stable position in a kind's item order; items after it are pending. */+export interface RepairCursor { phase: number; id: number }++export interface RepairItem {+ cursor: RepairCursor; source_id: string; slug: string; chars: number; action: string;+ /** Kind-specific planned change, rechecked against the page before it is applied. */+ change?: { from: string | null; to: string };+}++export interface RepairPlan {+ items: RepairItem[];+ /** Counts of rows the kind keeps and reports instead of repairing. */+ residuals: Record<string, number>;+}++export interface RepairHandler {+ kind: RepairKind;+ /** `projection`: items rebuild derived rows only and take no journal admission. Default `coordinated`. */+ publication?: 'coordinated' | 'projection';+ /** Pending items after `after`, in cursor order. */+ plan(engine: BrainEngine, scope: RepairScope, after: RepairCursor | null): Promise<RepairPlan>;+ /** Apply one item; `false` when it no longer needs repair. `embed` is false under --no-embed. */+ apply(ctx: OperationContext, item: RepairItem, opts?: { embed: boolean }): Promise<boolean>;+}++export interface RepairResult {+ kind: RepairKind;+ mode: 'dry_run' | 'apply';+ scope: RepairScope;+ affected: number;+ sample: string[];+ residuals: Record<string, number>;+ cost: { lifetime_ids: number; receipt_bytes: number; embedding_pages: number; embedding_usd: number | null };+ capacity: Array<{ scope: string; resource: string; used: number; limit: number; stop_at: number }>;+ resumed_from: RepairCursor | null;+ applied: number;+ skipped: number;+ complete: boolean;+ stopped?: { reason: string; message: string };+ apply_command: string;+}++const RECEIPT_BYTES = 16_384;+const STOP_RATIO = 0.9;+const SAMPLE = 10;++/** Default: every active source. `--source` narrows to one active source. */+export async function resolveRepairScope(engine: BrainEngine, source?: string): Promise<RepairScope> {+ const [brain] = await engine.executeRaw<{ brain_id: string }>('SELECT brain_id FROM persistence_brain WHERE singleton=1').catch(() => []);+ const rows = await engine.executeRaw<{ id: string }>(+ `SELECT id FROM sources WHERE archived IS NOT TRUE ${source ? 'AND id=$1' : ''} ORDER BY id`, source ? [source] : []);+ if (source && !rows.length) throw new OperationError('invalid_params', `Source '${source}' does not exist or is archived.`, 'Run `gbrain sources list` and pass an active source id.');+ return { brain_id: brain?.brain_id ?? 'host', source_ids: rows.map(row => row.id) };+}++function fingerprint(kind: RepairKind, scope: RepairScope): string {+ return digest(['repair-v1', kind, scope.brain_id, scope.source_ids]);+}++async function readCursor(engine: BrainEngine, kind: RepairKind, scope: RepairScope): Promise<RepairCursor | null> {+ const [row] = await engine.executeRaw<{ completed_keys: Array<{ cursor?: RepairCursor }> }>(+ "SELECT completed_keys FROM op_checkpoints WHERE op='repair' AND fingerprint=$1", [fingerprint(kind, scope)]);+ return row?.completed_keys[0]?.cursor ?? null;+}++async function writeCursor(engine: BrainEngine, kind: RepairKind, scope: RepairScope, cursor: RepairCursor | null): Promise<void> {+ if (!cursor) {+ await engine.executeRaw("DELETE FROM op_checkpoints WHERE op='repair' AND fingerprint=$1", [fingerprint(kind, scope)]);+ return;+ }+ await engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES('repair',$1,$2::text::jsonb)+ ON CONFLICT(op,fingerprint) DO UPDATE SET completed_keys=EXCLUDED.completed_keys,updated_at=now()`,+ [fingerprint(kind, scope), JSON.stringify([{ kind, scope, cursor }])]);+}++/** Cumulative journal counters this repair's admissions consume, with their 90% stop line. */+async function capacity(ctx: OperationContext) {+ // A dry run never registers a writer; an unregistered installation has consumed nothing yet.+ const principal = await requestPrincipalForContext(ctx).then(principalKey, () => 'principal:unregistered');+ const limits = await readJournalLimits(ctx.engine);+ const rows = await ctx.engine.executeRaw<{ key: string; lifetime_ids: string; terminal_bytes: string }>(+ 'SELECT key,lifetime_ids::text,terminal_bytes::text FROM persistence_counters WHERE key=ANY($1::text[])', [['brain', principal]]);+ return (['brain', principal] as const).flatMap(key => {+ const row = rows.find(r => r.key === key);+ const scope = key === 'brain' ? 'brain' : 'principal';+ return ([['lifetime_ids', `${scope}LifetimeIds`], ['terminal_bytes', `${scope}TerminalBytes`]] as const).map(([resource, setting]) => ({+ scope: key, resource, used: Number(row?.[resource] ?? 0), limit: limits[setting], stop_at: Math.floor(limits[setting] * STOP_RATIO),+ config_key: journalLimitKey(setting),+ }));+ });+}++function embeddingUsd(chars: number, model: string | undefined): number | null {+ if (!model) return null;+ const price = lookupEmbeddingPrice(model);+ return price.kind === 'known' ? estimateCostFromChars(chars, price.pricePerMTok) : null;+}++/**+ * Deterministic per-item request id: a rerun after a crash replays the same+ * admission (and waits for it if still pending). An attempt that ended in a+ * terminal failure is not replayed forever; the next attempt gets a new id.+ */+export async function repairRequestId(ctx: OperationContext, kind: RepairKind, item: Pick<RepairItem, 'source_id' | 'slug'>, revision: string): Promise<string> {+ await initializeLocalPersistence(ctx);+ const principal = await requestPrincipalForContext(ctx);+ for (let attempt = 0; ; attempt++) {+ const h = digest(['repair-request-v1', kind, item.source_id, item.slug, revision, attempt]);+ const id = `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-a${h.slice(17, 20)}-${h.slice(20, 32)}`;+ const prior = await getWriteRequest(ctx.engine, principal, id);+ if (!prior || !isTerminal(prior) || prior.state === 'committed') return id;+ }+}++function writerHeld(error: unknown): error is OperationError {+ return error instanceof OperationError && ['owner_unavailable', 'writer_lock_unavailable', 'writer_busy'].includes(error.code);+}++export async function runRepair(ctx: OperationContext, handler: RepairHandler, scope: RepairScope,+ opts: { apply: boolean; limit?: number; embeddingModel?: string; sourceFlag?: string; embed?: boolean; applyArgs?: string[] }): Promise<RepairResult> {+ if (opts.apply) await initializeLocalPersistence(ctx);+ const resumed = await readCursor(ctx.engine, handler.kind, scope);+ const plan = await handler.plan(ctx.engine, scope, resumed);+ const pending = opts.limit !== undefined ? plan.items.slice(0, opts.limit) : plan.items;+ const counters = await capacity(ctx);+ const admits = (handler.publication ?? 'coordinated') === 'coordinated' ? pending.length : 0;+ const result: RepairResult = {+ kind: handler.kind, mode: opts.apply ? 'apply' : 'dry_run', scope, affected: plan.items.length,+ sample: plan.items.slice(0, SAMPLE).map(item => `${item.source_id}:${item.slug}`), residuals: plan.residuals,+ cost: { lifetime_ids: admits, receipt_bytes: admits * RECEIPT_BYTES, embedding_pages: pending.length,+ embedding_usd: embeddingUsd(pending.reduce((sum, item) => sum + item.chars, 0), opts.embeddingModel) },+ capacity: counters.map(({ scope: key, resource, used, limit, stop_at }) => ({ scope: key, resource, used, limit, stop_at })),+ resumed_from: resumed, applied: 0, skipped: 0, complete: false,+ apply_command: `gbrain repair ${handler.kind}${opts.sourceFlag ? ` --source ${opts.sourceFlag}` : ''}${(opts.applyArgs ?? []).map(arg => ` ${arg}`).join('')} --apply`,+ };+ if (!opts.apply) {+ result.complete = pending.length === plan.items.length;+ return result;+ }+ for (const [index, item] of pending.entries()) {+ const remaining = pending.length - index;+ const full = admits ? (await capacity(ctx)).find(c => c.used + (c.resource === 'lifetime_ids' ? 1 : RECEIPT_BYTES) > c.stop_at) : undefined;+ if (full) {+ const perItem = full.resource === 'lifetime_ids' ? 1 : RECEIPT_BYTES;+ const needed = Math.ceil((full.used + remaining * perItem) / STOP_RATIO) + 1;+ result.stopped = { reason: 'capacity', message: `Stopped before crossing 90% of ${full.scope} ${full.resource} (${full.used} of ${full.limit} used; `+ + `${remaining} item(s) still need ${remaining * perItem} more). Run: gbrain config set ${full.config_key} ${needed} — then rerun \`${result.apply_command}\` to resume.` };+ return result;+ }+ try {+ if (await handler.apply({ ...ctx, sourceId: item.source_id }, item, { embed: opts.embed === true })) result.applied++;+ else result.skipped++;+ } catch (error) {+ // A page edited since planning is left for the next full scan.+ if (error instanceof OperationError && error.code === 'revision_conflict') { result.skipped++; continue; }+ if (error instanceof OperationError && error.code === 'write_pending') {+ result.stopped = { reason: 'write_pending', message: `The repair of ${item.source_id}:${item.slug} was accepted and is still pending publication. `+ + `Rerun \`${result.apply_command}\` to resume; the same request is replayed.` };+ return result;+ }+ if (!writerHeld(error)) throw error;+ result.stopped = { reason: error.code, message: `The canonical writer for source '${item.source_id}' is held (${error.code}). `+ + `Inspect it with: gbrain sources writer status ${item.source_id} — then rerun \`${result.apply_command}\` to resume.` };+ return result;+ }+ await writeCursor(ctx.engine, handler.kind, scope, item.cursor);+ }+ result.complete = pending.length === plan.items.length;+ if (result.complete) await writeCursor(ctx.engine, handler.kind, scope, null);+ return result;+}++/** Cursor order shared by the kinds' SQL: (phase, id) strictly after `after`. */+export function afterCursor(item: RepairCursor, after: RepairCursor | null): boolean {+ return !after || item.phase > after.phase || (item.phase === after.phase && item.id > after.id);+}diff --git a/src/core/repair/safe-chunks.ts b/src/core/repair/safe-chunks.tsnew file mode 100644index 0000000000..be049f0c97--- /dev/null+++ b/src/core/repair/safe-chunks.ts@@ -0,0 +1,76 @@+/**+ * `gbrain repair safe-chunks` (#5050/#5247): re-seal pages of every kind that+ * were chunked before the safe-chunk fence (chunker v4). Remote reads withhold+ * their chunks until then. Each item rebuilds the page's chunks from its+ * unchanged canonical body through the projection installer: no page write,+ * version, journal admission or lifetime ID, so it is safe on a managed brain.+ * Vectors of unchanged embedding inputs are kept; the rest are embedded after+ * the re-seal unless --no-embed is passed (then `gbrain embed --stale` does it).+ *+ * Code pages need their recorded source path to re-chunk; pages without one,+ * and page kinds the projection installer cannot rebuild (images), are counted+ * as residuals and left for their importer.+ */+import type { BrainEngine } from '../engine.ts';+import { resealSafeChunks } from '../page-state/projections.ts';+import { PageRevisionConflictError } from '../page-state/types.ts';+import { SAFE_FENCE_CHUNKER_VERSION } from '../search/safe-chunks.ts';+import { embedStalePages } from '../embed-stale.ts';+import { afterCursor, type RepairCursor, type RepairHandler, type RepairItem, type RepairScope } from './core.ts';++/**+ * DX-D7: post-upgrade names the drain for pages still withheld. On a managed+ * brain `gbrain reindex --markdown` refuses; elsewhere it covers markdown only,+ * so code pages can remain. Null when nothing is withheld.+ */+export async function safeChunkUpgradeAdvisory(engine: Pick<BrainEngine, 'executeRaw'>, managed: boolean): Promise<string | null> {+ const [row] = await engine.executeRaw<{ pending: number }>(`SELECT COUNT(*)::int AS pending FROM pages+ WHERE deleted_at IS NULL AND chunker_version < ${SAFE_FENCE_CHUNKER_VERSION}+ AND source_id IN (SELECT id FROM sources WHERE archived IS NOT TRUE)`);+ const pending = Number(row?.pending ?? 0);+ if (pending === 0) return null;+ return `[gbrain] ${pending} page(s) are below the safe-chunk index version and withheld from remote/MCP search. `+ + (managed ? 'This brain is managed, so the markdown reindex does not run here. ' : '')+ + 'Preview: gbrain repair safe-chunks — apply: gbrain repair safe-chunks --apply';+}++interface PendingRow { id: number; source_id: string; slug: string; page_kind: string; rebuildable: boolean; chars: number }++export const safeChunksRepair: RepairHandler = {+ kind: 'safe-chunks',+ publication: 'projection',+ async plan(engine: BrainEngine, scope: RepairScope, after: RepairCursor | null) {+ const rows = await engine.executeRaw<PendingRow>(`SELECT p.id,p.source_id,p.slug,p.page_kind,+ (p.page_kind='markdown' OR (p.page_kind='code' AND COALESCE(p.frontmatter->>'file',p.source_path) IS NOT NULL)) AS rebuildable,+ length(p.compiled_truth)+length(COALESCE(p.timeline,'')) AS chars+ FROM pages p WHERE p.source_id=ANY($1::text[]) AND p.deleted_at IS NULL AND p.chunker_version < ${SAFE_FENCE_CHUNKER_VERSION}+ ORDER BY p.id`, [scope.source_ids]);+ const items: RepairItem[] = rows.filter(row => row.rebuildable)+ .map(row => ({ cursor: { phase: 0, id: Number(row.id) }, source_id: row.source_id, slug: row.slug, chars: Number(row.chars),+ action: `re-seal ${row.page_kind} chunks` }))+ .filter(item => afterCursor(item.cursor, after));+ const kept = rows.filter(row => !row.rebuildable);+ return { items, residuals: {+ code_without_source_path: kept.filter(row => row.page_kind === 'code').length,+ unsupported_page_kind: kept.filter(row => row.page_kind !== 'code').length,+ } };+ },+ async apply(ctx, item, opts) {+ let resealed: Awaited<ReturnType<typeof resealSafeChunks>>;+ try {+ resealed = await resealSafeChunks(ctx.engine, item.slug, item.source_id);+ } catch (error) {+ // A page edited since planning is re-sealed by its own write.+ if (error instanceof PageRevisionConflictError) return false;+ throw error;+ }+ if (!resealed) return false;+ if (opts?.embed && resealed.pendingChunks > 0) {+ const embedded = await embedStalePages(ctx.engine, [item.slug], item.source_id);+ // The re-seal stands; vectors the provider did not return stay in the ordinary stale backlog.+ if (embedded.pagesProcessed === 0) ctx.logger.warn(`[repair safe-chunks] ${item.source_id}:${item.slug} re-sealed, but some chunks were not embedded. `+ + `Run: gbrain embed --stale --source ${item.source_id}`);+ }+ return true;+ },+};diff --git a/src/core/repair/timeline.ts b/src/core/repair/timeline.tsnew file mode 100644index 0000000000..0aff6dc353--- /dev/null+++ b/src/core/repair/timeline.ts@@ -0,0 +1,66 @@+/**+ * `gbrain repair timeline` (#5567): materialize database-only timeline rows on+ * pages that are never written again. Each page is re-published with its own+ * current body through a revision-bound `put_page`; preparation writes every+ * round-trippable bullet-less row back into the page as a marked bullet.+ * Rows that cannot round-trip are kept and reported, never deleted.+ */+import type { BrainEngine } from '../engine.ts';+import { serializePageToMarkdown } from '../markdown.ts';+import { pendingTimelineRows } from '../persistence/canonical-projections.ts';+import { submitPageMutation } from '../persistence/page-mutations.ts';+import { repairRequestId, type RepairHandler, type RepairItem, type RepairScope, type RepairCursor } from './core.ts';++interface TimelinePage { id: number; source_id: string; slug: string; compiled_truth: string; timeline: string | null }++const BATCH = 200;++/**+ * Pages carrying non-event timeline rows, in id order after `afterId`, each+ * classified exactly. `budget` caps the pages inspected (doctor's bound).+ */+export async function scanTimelineHistory(engine: BrainEngine, sourceIds: string[], afterId: number,+ budget: { pages?: number; deadline?: number } = {}) {+ const pages: Array<TimelinePage & { materializable: number; unrenderable: number }> = [];+ let cursor = afterId, inspected = 0, truncated = false;+ for (;;) {+ const batch = await engine.executeRaw<TimelinePage>(`SELECT p.id,p.source_id,p.slug,p.compiled_truth,p.timeline FROM pages p+ WHERE p.source_id=ANY($1::text[]) AND p.deleted_at IS NULL AND p.id>$2+ AND EXISTS (SELECT 1 FROM timeline_entries t WHERE t.page_id=p.id AND t.event_page_id IS NULL)+ ORDER BY p.id LIMIT ${BATCH}`, [sourceIds, cursor]);+ for (const page of batch) {+ if ((budget.pages !== undefined && inspected >= budget.pages) || (budget.deadline !== undefined && Date.now() > budget.deadline)) {+ truncated = true;+ return { pages, inspected, truncated };+ }+ inspected++;+ cursor = page.id;+ const counts = await pendingTimelineRows(engine, { ...page, timeline: page.timeline ?? '' });+ if (counts.materializable || counts.unrenderable) pages.push({ ...page, ...counts });+ }+ if (batch.length < BATCH) return { pages, inspected, truncated };+ }+}++export const timelineRepair: RepairHandler = {+ kind: 'timeline',+ async plan(engine: BrainEngine, scope: RepairScope, after: RepairCursor | null) {+ const { pages } = await scanTimelineHistory(engine, scope.source_ids, after?.id ?? 0);+ const items: RepairItem[] = pages.filter(p => p.materializable > 0).map(p => ({ cursor: { phase: 0, id: p.id }, source_id: p.source_id,+ slug: p.slug, chars: p.compiled_truth.length + (p.timeline ?? '').length, action: `materialize ${p.materializable} row(s)` }));+ return { items, residuals: {+ materializable_rows: pages.reduce((n, p) => n + p.materializable, 0),+ kept_unrenderable_rows: pages.reduce((n, p) => n + p.unrenderable, 0),+ } };+ },+ async apply(ctx, item) {+ const snapshot = await ctx.engine.readPageSnapshot(item.slug, { sourceId: item.source_id });+ if (!snapshot) return false;+ const counts = await pendingTimelineRows(ctx.engine, { ...snapshot.page, timeline: snapshot.page.timeline ?? '' });+ if (!counts.materializable) return false;+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug: item.slug, source_id: item.source_id,+ content: serializePageToMarkdown(snapshot.page, snapshot.tags), expected_revision: snapshot.revision,+ request_id: await repairRequestId(ctx, 'timeline', item, snapshot.revision) } });+ return true;+ },+};diff --git a/src/core/repair/visibility.ts b/src/core/repair/visibility.tsnew file mode 100644index 0000000000..69db7278d4--- /dev/null+++ b/src/core/repair/visibility.ts@@ -0,0 +1,112 @@+/**+ * `gbrain repair visibility` (#5525): tighten-only backfill that stamps an+ * explicit `visibility` on extracted atoms and synthesized concepts.+ *+ * atom origin page -> effectiveVisibility(origin); transcript or missing origin -> private+ * concept strictest visibility of its input atoms (provenance edges + atoms' `concepts:`);+ * a member without a provenance edge counts as private+ *+ * An item is only ever made stricter than it is now: explicit `private` stays,+ * explicit `world` becomes `private` when its origin is stricter, and a missing+ * field (read as private) is stamped with the origin's value. A concept with no+ * recoverable lineage is left unchanged and counted. Atoms are applied before+ * concepts so a concept is judged against its repaired inputs.+ */+import type { BrainEngine } from '../engine.ts';+import { serializePageToMarkdown } from '../markdown.ts';+import { submitPageMutation } from '../persistence/page-mutations.ts';+import { effectiveVisibility, strictestVisibility, type Visibility } from '../search/private-visibility.ts';+import { afterCursor, repairRequestId, type RepairHandler, type RepairItem, type RepairScope, type RepairCursor } from './core.ts';++interface DerivedRow { id: number; source_id: string; slug: string; type: string; visibility: string | null; chars: number }+interface AtomRow extends DerivedRow { source_slug: string | null; origin_id: number | null; origin_type: string | null; origin_frontmatter: Record<string, unknown> | null }+interface InputRow { concept_id: number; atom_id: number; linked: boolean }++export interface VisibilityChange { id: number; source_id: string; slug: string; phase: 0 | 1; from: string | null; to: Visibility }++/** Tighten-only: never loosen an explicit value; stamp a missing one. */+function tightened(current: string | null, target: Visibility): Visibility | null {+ if (current === 'private') return null;+ if (current === 'world') return target === 'private' ? 'private' : null;+ return target;+}++/**+ * Every atom / synthesized concept in scope whose stored visibility should+ * change. `only` narrows the plan to one page (and, for a concept, its inputs)+ * so an item is re-decided against current state just before it is applied.+ */+export async function planVisibilityRepair(engine: BrainEngine, sourceIds: string[], only?: number) {+ const [kind] = only === undefined ? [] : await engine.executeRaw<{ type: string }>('SELECT type FROM pages WHERE id=$1', [only]);+ const conceptIds = only === undefined ? null : kind?.type === 'concept' ? [only] : [];+ const concepts = await engine.executeRaw<DerivedRow>(`SELECT c.id,c.source_id,c.slug,c.type,c.frontmatter->>'visibility' AS visibility,+ length(c.compiled_truth) AS chars+ FROM pages c WHERE c.type='concept' AND c.frontmatter->>'synthesized_by' IS NOT NULL AND c.deleted_at IS NULL+ AND c.source_id=ANY($1::text[]) AND ($2::integer[] IS NULL OR c.id=ANY($2::integer[])) ORDER BY c.id`, [sourceIds, conceptIds]);+ // A member recovered only from an atom's `concepts:` list has no provenance+ // edge, so a later private flip could not reach the concept: it stays private.+ const inputs = concepts.length ? await engine.executeRaw<InputRow>(`SELECT c.id AS concept_id,a.id AS atom_id,+ EXISTS (SELECT 1 FROM links l WHERE l.from_page_id=c.id AND l.to_page_id=a.id+ AND l.link_source='concept-provenance' AND l.link_type='synthesized_from') AS linked+ FROM pages c JOIN pages a ON a.source_id=c.source_id AND a.type='atom' AND a.deleted_at IS NULL+ WHERE c.id=ANY($1::integer[]) AND (+ EXISTS (SELECT 1 FROM links l WHERE l.from_page_id=c.id AND l.to_page_id=a.id+ AND l.link_source='concept-provenance' AND l.link_type='synthesized_from')+ OR (jsonb_typeof(a.frontmatter->'concepts')='array' AND EXISTS (SELECT 1 FROM jsonb_array_elements_text(a.frontmatter->'concepts') ref+ WHERE regexp_replace(ref,'^.*/','')=regexp_replace(c.slug,'^concepts/',''))))`, [concepts.map(c => Number(c.id))]) : [];+ const atomIds = only === undefined ? null : kind?.type === 'atom' ? [only] : inputs.map(row => Number(row.atom_id));+ const atoms = await engine.executeRaw<AtomRow>(`SELECT a.id,a.source_id,a.slug,a.type,a.frontmatter->>'visibility' AS visibility,+ length(a.compiled_truth) AS chars, a.frontmatter->>'source_slug' AS source_slug,+ o.id AS origin_id,o.type AS origin_type,o.frontmatter AS origin_frontmatter+ FROM pages a LEFT JOIN pages o ON o.source_id=a.source_id AND o.slug=a.frontmatter->>'source_slug' AND o.deleted_at IS NULL+ WHERE a.type='atom' AND a.deleted_at IS NULL AND a.source_id=ANY($1::text[])+ AND ($2::integer[] IS NULL OR a.id=ANY($2::integer[])) ORDER BY a.id`, [sourceIds, atomIds]);++ const changes: VisibilityChange[] = [];+ const atomVisibility = new Map<number, Visibility>();+ let originGone = 0;+ for (const atom of atoms) {+ const origin = atom.source_slug ? { kind: 'page' as const, page: atom.origin_id == null ? null : { type: atom.origin_type, frontmatter: atom.origin_frontmatter } }+ : { kind: 'transcript' as const };+ const target = effectiveVisibility(origin);+ const next = tightened(atom.visibility, target);+ if (next && origin.kind === 'page' && !origin.page) originGone++;+ const effective = next ?? (atom.visibility === 'world' ? 'world' : 'private');+ atomVisibility.set(Number(atom.id), effective);+ if (next) changes.push({ id: Number(atom.id), source_id: atom.source_id, slug: atom.slug, phase: 0, from: atom.visibility, to: next });+ }+ let noLineage = 0;+ for (const concept of concepts) {+ const rows = inputs.filter(row => Number(row.concept_id) === Number(concept.id));+ if (!rows.length) { noLineage++; continue; }+ const members = rows.map(row => row.linked ? atomVisibility.get(Number(row.atom_id)) ?? 'private' : 'private');+ const next = tightened(concept.visibility, strictestVisibility(members));+ if (next) changes.push({ id: Number(concept.id), source_id: concept.source_id, slug: concept.slug, phase: 1, from: concept.visibility, to: next });+ }+ const chars = new Map([...atoms, ...concepts].map(row => [Number(row.id), Number(row.chars)]));+ return { changes, chars, residuals: { atoms_origin_gone_to_private: originGone, concepts_without_lineage: noLineage } };+}++export const visibilityRepair: RepairHandler = {+ kind: 'visibility',+ async plan(engine: BrainEngine, scope: RepairScope, after: RepairCursor | null) {+ const { changes, chars, residuals } = await planVisibilityRepair(engine, scope.source_ids);+ const items: RepairItem[] = changes.map(change => ({ cursor: { phase: change.phase, id: change.id }, source_id: change.source_id,+ slug: change.slug, chars: chars.get(change.id) ?? 0, action: `visibility ${change.from ?? '(none)'} -> ${change.to}`,+ change: { from: change.from, to: change.to } }))+ .filter(item => afterCursor(item.cursor, after));+ return { items, residuals };+ },+ async apply(ctx, item) {+ const snapshot = await ctx.engine.readPageSnapshot(item.slug, { sourceId: item.source_id });+ if (!snapshot || !item.change) return false;+ // Re-decide against current origins and inputs; a changed decision waits for the next run.+ const fresh = (await planVisibilityRepair(ctx.engine, [item.source_id], snapshot.page.id)).changes.find(c => c.id === snapshot.page.id);+ if (!fresh || fresh.from !== item.change.from || fresh.to !== item.change.to) return false;+ const page = { ...snapshot.page, frontmatter: { ...snapshot.page.frontmatter, visibility: item.change.to } };+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug: item.slug, source_id: item.source_id,+ content: serializePageToMarkdown(page, snapshot.tags), expected_revision: snapshot.revision,+ request_id: await repairRequestId(ctx, 'visibility', item, snapshot.revision) } });+ return true;+ },+};diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.tsindex 693f2cc8d3..8feba4ce91 100644--- a/src/core/schema-embedded.generated.ts+++ b/src/core/schema-embedded.generated.ts@@ -312,6 +312,8 @@ CREATE TABLE IF NOT EXISTS content_chunks (-- #4246 (v133): md5(chunk_text) at embed time. NULL = no embedding or-- pre-v133 row (grandfathered by invalidateContentDriftEmbeddings).embedded_text_hash TEXT,+ -- #5553 (v171): embedding-input provenance written with the vector.+ embedding_input_hash TEXT,created_at TIMESTAMPTZ NOT NULL DEFAULT now(),-- v0.19.0: code chunk metadata. Nullable — markdown chunks leave these NULL.-- Powers \`query --lang\`, \`code-def <symbol>\`, and \`code-refs <symbol>\`.diff --git a/src/core/search/hybrid.ts b/src/core/search/hybrid.tsindex d42a099698..a674f094a7 100644--- a/src/core/search/hybrid.ts+++ b/src/core/search/hybrid.ts@@ -77,6 +77,7 @@ import { expandAnchors, hydrateChunks } from './two-pass.ts';import { enforceTokenBudget, searchSalvageEnabled, type TokenBudgetMeta } from './token-budget.ts';import { warnOncePerProcess } from '../utils.ts';import { recordSearchTelemetry } from './telemetry.ts';+import { isPrivatePage } from './private-visibility.ts';import {weightsForIntent,effectiveRrfK,@@ -975,10 +976,7 @@ export async function applyAliasHop(// #4352 — the alias inject path bypasses the engines' SQL visibility// clause (getPage, not search); re-apply the private predicate here so// an untrusted caller can't hop into a `visibility: private` page.- if (- opts.excludePrivate &&- ((page.frontmatter as Record<string, unknown> | null | undefined)?.visibility === 'private')- ) continue;+ if (opts.excludePrivate && isPrivatePage(page)) continue;injectScore += 1e-6;out.unshift({// #2339-sibling: include page_id. The `as SearchResult` cast hid itsdiff --git a/src/core/search/private-visibility.ts b/src/core/search/private-visibility.tsindex 040b5351be..233808f92c 100644--- a/src/core/search/private-visibility.ts+++ b/src/core/search/private-visibility.ts@@ -24,15 +24,74 @@ import type { BrainEngine } from '../engine.ts';export const REMOTE_PRIVATE_PAGES_KEY = 'search.remote_private_pages';+/**+ * #5525 — extracted atoms and synthesized concept pages are derived from+ * other pages or from private transcripts, so a missing `visibility` field on+ * them means "origin unknown", not "world". They fail closed; every other page+ * keeps the documented default (absent visibility is world).+ */+function derivedPageSql(pageAlias: string): string {+ return `(${pageAlias}.type = 'atom' OR (${pageAlias}.type = 'concept' AND ${pageAlias}.frontmatter->>'synthesized_by' IS NOT NULL))`;+}+/*** Raw SQL predicate hiding `visibility: private` pages (absent visibility- * defaults to 'world'). Single source of truth for the fragment — consumed by+ * defaults to 'world', except on derived atoms and concepts where it defaults+ * to 'private'). Single source of truth for the fragment — consumed by* buildVisibilityClause (search paths), both engines' listPages, the* relational-arm hydrate, and get_page's fuzzy-candidate filter. `pageAlias`* is a code-provided literal, never user input.*/export function privatePagesFilterFragment(pageAlias: string): string {- return `COALESCE(${pageAlias}.frontmatter->>'visibility', 'world') <> 'private'`;+ return `(${privateSnapshotFilterFragment(pageAlias)}+ AND NOT ${derivedOriginPrivateSql(pageAlias)})`;+}++/**+ * The same rule on a row's own `type`/`frontmatter` only, for snapshots such+ * as `page_versions` that have no page identity to follow to an origin. Callers+ * pair it with privatePagesFilterFragment on the live page.+ */+export function privateSnapshotFilterFragment(alias: string): string {+ return `COALESCE(${alias}.frontmatter->>'visibility', CASE WHEN ${derivedPageSql(alias)} THEN 'private' ELSE 'world' END) <> 'private'`;+}++/**+ * #5525 — a later private flip of an origin page reaches its derived pages+ * before any repair runs: an atom whose origin page is explicitly private, and+ * a synthesized concept with a private input atom (or an input atom whose+ * origin is private), are private whatever their own field says.+ * `gbrain repair visibility` then stamps the stricter value on the rows.+ */+function derivedOriginPrivateSql(p: string): string {+ const privateOrigin = (atom: string, alias: string) => `EXISTS (SELECT 1 FROM pages ${alias} WHERE ${alias}.source_id = ${atom}.source_id+ AND ${alias}.slug = ${atom}.frontmatter->>'source_slug' AND ${alias}.frontmatter->>'visibility' = 'private')`;+ return `(CASE WHEN ${p}.type = 'atom' THEN ${privateOrigin(p, 'derived_origin')}+ WHEN ${derivedPageSql(p)} THEN EXISTS (SELECT 1 FROM links derived_input_link+ JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id+ WHERE derived_input_link.from_page_id = ${p}.id AND derived_input_link.link_source = 'concept-provenance'+ AND derived_input_link.link_type = 'synthesized_from'+ AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private'+ OR ${privateOrigin('derived_input', 'derived_input_origin')}))+ ELSE false END)`;+}++export type Visibility = 'private' | 'world';++/**+ * #5525 — the visibility a derived page takes from its origin under the+ * read-side rule: transcripts and missing origins are private, and a page+ * origin is private exactly when remote readers cannot see it.+ */+export function effectiveVisibility(origin: { kind: 'transcript' } | { kind: 'page'; page: { type?: string | null; frontmatter?: unknown } | null }): Visibility {+ if (origin.kind === 'transcript' || !origin.page) return 'private';+ return isPrivatePage(origin.page) ? 'private' : 'world';+}++/** Derived outputs take the strictest visibility of their inputs. */+export function strictestVisibility(values: Iterable<Visibility>): Visibility {+ for (const value of values) if (value === 'private') return 'private';+ return 'world';}/** Check the actual origin, independently of joins that redact its source. */@@ -70,15 +129,14 @@ export function privateProvenanceFilterFragment(factAlias: string): string {/*** Row-side twin of privatePagesFilterFragment for pages already fetched* (get_page / fetch read one row by slug; re-querying just to filter would- * be a second round-trip). Same semantics: only the exact string 'private'- * hides a page; absent/other values default to world-visible.+ * be a second round-trip). Same semantics: an explicit 'private' hides a+ * page, and an absent value hides only derived atoms and concepts.*/-export function isPrivatePage(frontmatter: unknown): boolean {- return (- typeof frontmatter === 'object' &&- frontmatter !== null &&- (frontmatter as Record<string, unknown>).visibility === 'private'- );+export function isPrivatePage(page: { type?: string | null; frontmatter?: unknown }): boolean {+ const frontmatter = typeof page.frontmatter === 'object' && page.frontmatter !== null+ ? page.frontmatter as Record<string, unknown> : {};+ const derived = page.type === 'atom' || (page.type === 'concept' && frontmatter.synthesized_by != null);+ return (frontmatter.visibility ?? (derived ? 'private' : 'world')) === 'private';}/**diff --git a/src/core/search/safe-chunks.ts b/src/core/search/safe-chunks.tsindex 0ab6dc8c28..8e96f4b6af 100644--- a/src/core/search/safe-chunks.ts+++ b/src/core/search/safe-chunks.ts@@ -37,6 +37,11 @@ export function currentTextProjectionFilter(alias: string): string {return `(${alias}.text_projection_revision = ${alias}.knowledge_revision) IS TRUE`;}+/** A page of any kind chunked before the fence; remote reads withhold it until it is re-sealed. */+export function belowSafeChunkFence(chunkerVersion: number | null | undefined): boolean {+ return (chunkerVersion ?? 0) < SAFE_FENCE_CHUNKER_VERSION;+}+/** Older fragments lack trustworthy provenance, even if markers were removed later. */export function safeChunksFilter(alias: string): string {return `COALESCE(${alias}.chunker_version, 0) >= ${SAFE_FENCE_CHUNKER_VERSION}`;diff --git a/src/core/search/sql-ranking.ts b/src/core/search/sql-ranking.tsindex 81d97e9abd..1294ebcef4 100644--- a/src/core/search/sql-ranking.ts+++ b/src/core/search/sql-ranking.ts@@ -177,7 +177,8 @@ export function buildVisibilityClause(opts?: {/*** #4352 — untrusted-caller predicate: hide pages whose frontmatter- * carries `visibility: private` (absent visibility defaults to 'world').+ * carries `visibility: private` (absent visibility defaults to 'world',+ * or to 'private' on derived atoms and synthesized concepts).* Set from SearchOpts.excludePrivate by both engines; callers resolve* trust + the config gate via resolveExcludePrivatePages* (search/private-visibility.ts). Off by default — trusted local readsdiff --git a/src/core/shared-skills/knowledge-guard.ts b/src/core/shared-skills/knowledge-guard.tsindex 1018782605..d861d0a469 100644--- a/src/core/shared-skills/knowledge-guard.ts+++ b/src/core/shared-skills/knowledge-guard.ts@@ -1,7 +1,7 @@import { isAbsolute, relative, resolve, sep } from 'node:path';import { fileURLToPath } from 'node:url';import { OperationError } from '../ops/contract.ts';-import { resolveSourceLocalFilePath } from '../markdown.ts';+import { isRelativeFileUri, resolveSourceLocalFilePath } from '../markdown.ts';import { localHostId } from '../persistence/identity.ts';import type { SqlEngine, WriteRequest } from '../persistence/model.ts';import { canonicalFilesystemPath } from '../persistence/root-registry.ts';@@ -62,8 +62,16 @@ export async function assertKnowledgePublicationAllowed(const recorded = resolveSourceLocalFilePath(root, alias.source_path, row.slug);if (recorded) paths.push(recorded);}- if (alias.source_uri?.startsWith('file:')) {- try { paths.push(fileURLToPath(alias.source_uri)); } catch { reject(); }+ if (alias.source_uri?.startsWith('file:') && !isRelativeFileUri(alias.source_uri)) {+ try { paths.push(fileURLToPath(alias.source_uri)); } catch {+ // An unresolved alias must still fail closed, but it does not prove+ // that this ordinary page is part of a shared skillpack.+ const error = new OperationError('invalid_source_uri',+ 'The page has a stored file source_uri that cannot be resolved to a local filesystem path. Have the source owner inspect and repair the stored source_uri before retrying.',+ `On the brain host, inspect the stored source_uri of page ${row.slug} in source ${row.source_id} and replace it with an absolute file URI or clear it, then retry the knowledge write with a new request_id. Shared skillpack protection remains enabled.`);+ error.detail = 'invalid_source_uri';+ throw error;+ }}}}diff --git a/src/core/shared-skills/migration-projection.ts b/src/core/shared-skills/migration-projection.tsindex b084ccdce4..7790d146ad 100644--- a/src/core/shared-skills/migration-projection.ts+++ b/src/core/shared-skills/migration-projection.ts@@ -1,7 +1,7 @@import type { BrainEngine } from '../engine.ts';import type { ParsedMarkdown } from '../markdown.ts';import { OperationError } from '../ops/contract.ts';-import { prepareCanonicalProjections } from '../persistence/canonical-projections.ts';+import { compileCanonicalProjections } from '../persistence/canonical-projections.ts';import { extractFactsFromFenceText } from '../facts/extract-from-fence.ts';import { parseFactsFence } from '../facts-fence.ts';import { parseTakesFence } from '../takes-fence.ts';@@ -27,7 +27,7 @@ function differences(stored: Row, expected: Row): string[] {}export async function assertExportProjectionRoundtrip(engine: BrainEngine, page: ParsedMarkdown, pageId: number, sourceId: string): Promise<void> {- prepareCanonicalProjections(page, page.slug, sourceId);+ compileCanonicalProjections(page, page.slug, sourceId);const fields = [page.compiled_truth, page.timeline];const facts = extractFactsFromFenceText(fields.flatMap(field => parseFactsFence(field).facts), page.slug, sourceId);const takes = fields.flatMap(field => parseTakesFence(field).takes);diff --git a/src/core/storage-config.ts b/src/core/storage-config.tsindex 29fa82a940..89692ee839 100644--- a/src/core/storage-config.ts+++ b/src/core/storage-config.ts@@ -356,6 +356,37 @@ export function isDbOnly(slug: string, config: StorageConfig): boolean {return config.db_only.some((dir) => matchesTierDir(slug, dir));}+/**+ * Declared db_only match for a page slug. Slugs are always lowercase, so the+ * declared directory is lowercased before matching (same reasoning as+ * `effectiveDbOnlyDirs`, issue #3766). Only declared dirs count: the+ * derive-phase defaults may be file-backed on some brains.+ */+export function isDeclaredDbOnlySlug(slug: string, config: StorageConfig | null): boolean {+ return config?.db_only.some((dir) => matchesTierDir(slug, dir.toLowerCase())) ?? false;+}++/**+ * True when gbrain.yml has a `db_only` (or deprecated `supabase_only`) key+ * line but no db_only directory resolved from it. `loadStorageConfig` warns+ * and resolves nothing for syntax the narrow parser does not handle (e.g.+ * flow-style `db_only: [dir/]`), so a caller that must not guess a tier+ * refuses instead. Only YAML key lines count, not comments or prose that+ * mention the word. Known false positive: an intentionally empty+ * `db_only: []` also counts, since it resolves to the same empty config.+ */+export function hasUnresolvedDbOnlyDeclaration(repoPath: string, config: StorageConfig | null): boolean {+ if (config && config.db_only.length > 0) return false;+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- repoPath is the registered local source root and the file name is a constant; this only reads its gbrain.yml+ const yamlPath = join(repoPath, 'gbrain.yml');+ const yamlContent = existsSync(yamlPath) ? readFileSync(yamlPath, 'utf-8') : '';+ return yamlContent.split('\n').some((line) => {+ const trimmed = line.trim();+ if (trimmed.startsWith('#')) return false;+ return /^(db_only|supabase_only)\s*:/.test(trimmed);+ });+}+/*** Derive-phase output prefixes the engine itself writes as DB-only machine* output (issue #2784, reported by @alexputici). These are re-derivable bydiff --git a/src/core/sweep.ts b/src/core/sweep.tsindex f1b7e2d8e5..98893ac7c2 100644--- a/src/core/sweep.ts+++ b/src/core/sweep.ts@@ -575,7 +575,7 @@ async function runCorpusIngestPass(// OFF retires banked turns even when the brain cannot extract — otherwise// the files linger eligible and a later re-enable would extract turns the// operator already revoked (codex re-review, this wave).- const { parseWbFileName, writebackOffSidecarJson } = await import('./context/corpus-segments.ts');+ const { parseWbFileName, writebackOffSidecarJson, corpusFileSessionId } = await import('./context/corpus-segments.ts');const { resolveWritebackConfig } = await import('./facts/writeback-config.ts');const { loadConfig: loadFileCfg } = await import('./config.ts');const { isValidSourceId } = await import('./source-id.ts');@@ -623,6 +623,8 @@ async function runCorpusIngestPass(const { runFactsPipeline } = await import('./facts/backstop.ts');const { isDreamOutput } = await import('./cycle/transcript-discovery.ts');+ const { claudeCliSelfSessionIds } = await import('./ai/providers/claude-cli-scratch.ts');+ const selfCaptureIds = claudeCliSelfSessionIds();for (let i = 0; i < candidates.length; i++) {if (overBudget()) {@@ -650,6 +652,18 @@ async function runCorpusIngestPass(continue;}+ // #5413: a corpus file captured from gbrain's own claude-cli call, in+ // any capture form. Extracting it spawns another claude-cli call; the+ // classification is permanent, so the terminal sidecar stops the retry.+ if (selfCaptureIds.has(corpusFileSessionId(name))) {+ await writeFile(+ full + CORPUS_INGESTED_SUFFIX,+ JSON.stringify({ ingested_at: new Date().toISOString(), skipped: 'self_capture' }) + '\n',+ );+ skip('self_capture');+ continue;+ }+const wbMeta = parseWbFileName(name);if (wbMeta && wbCfg.read_error) {skip('writeback_gate_unreadable');diff --git a/src/core/sync-git.ts b/src/core/sync-git.tsindex c6c1692a4d..30f40d2063 100644--- a/src/core/sync-git.ts+++ b/src/core/sync-git.ts@@ -3,13 +3,13 @@* baseline-commit self-heal, and path-containment guards. Peeled out of* src/commands/sync.ts (containment sprint C13-C14) as a pure move.*/-import { existsSync, readFileSync, realpathSync } from 'fs';+import { realpathSync } from 'fs';import { execFileSync } from 'child_process';import { isAbsolute, join, relative, sep } from 'path';import type { BrainEngine } from './engine.ts';import { resolveSlugForPath, DEFAULT_SOURCE_ID } from './sync.ts';import { DELETE_BATCH_SIZE } from './engine-constants.ts';-import { loadStorageConfig } from './storage-config.ts';+import { hasUnresolvedDbOnlyDeclaration, loadStorageConfig } from './storage-config.ts';/*** v0.32.7 CJK wave (codex post-merge F4): resolve a slug by `pages.source_path`@@ -472,46 +472,21 @@ export function createSyncBaselineCommit(repoPath: string): void {const dbOnlyDirs = storageConfig?.db_only ?? [];// Sniff-test fail-closed (round 6, P2): `loadStorageConfig` warns-and-// returns an EMPTY config for syntactically-valid-but-unsupported YAML- // (e.g. flow-style `db_only: [dir/]` — the narrow custom parser only+ // (e.g. flow-style `db_only: [dir/]`; the narrow custom parser only// handles block-style lists), which would silently resolve zero- // exclusions from a file that clearly intended some. If gbrain.yml- // exists and mentions db_only (or its deprecated pre-v0.22.11 alias- // `supabase_only` — same keep-out-of-git semantics, still a supported- // backward-compat key per storage-config.ts) but nothing resolved from- // it, refuse rather than guess "genuinely empty" vs "syntax ignored".- //- // Known false-positive (round 8 review): a genuinely, intentionally- // empty `db_only: []` mentioning the word also refuses, and can't be- // told apart from the unsupported-syntax case — `loadStorageConfig`- // returns the IDENTICAL `{db_tracked:[],db_only:[]}` for both (verified- // directly: flow-style `[dir/]` and literal `[]` both collapse to that- // same shape). Distinguishing them would mean teaching this function- // about the parser's internal line-recognition rules, which belongs in- // storage-config.ts, not here. Accepted trade-off: the false-positive- // cost is low and self-resolving (the brain stays wedged with a clear,- // actionable error until the user drops the pointless empty stanza or- // fixes their syntax; retried on every subsequent sync); the- // false-negative this guards against — silently committing db_only- // content into permanent git history — is high-cost and hard to undo.- if (dbOnlyDirs.length === 0) {+ // exclusions from a file that clearly intended some. If gbrain.yml has a+ // db_only (or deprecated `supabase_only`) key line but nothing resolved+ // from it, refuse rather than guess; `hasUnresolvedDbOnlyDeclaration`+ // owns the key-line rules. Accepted trade-off: an intentionally empty+ // `db_only: []` also refuses (same empty config); silently committing+ // db_only content into permanent git history is high-cost and hard to undo.+ if (hasUnresolvedDbOnlyDeclaration(repoPath, storageConfig)) {const yamlPath = join(repoPath, 'gbrain.yml');- const yamlContent = existsSync(yamlPath) ? readFileSync(yamlPath, 'utf-8') : '';- // A YAML KEY line (`db_only:` / `supabase_only:`, ignoring leading- // whitespace and `#` comments), not a bare substring search — round 9,- // P2: a comment or unrelated prose value that happens to mention the- // word (e.g. `# db_only handling TBD`) must not trip this guard on an- // otherwise-genuinely-config-free gbrain.yml.- const mentionsUnresolvedKey = yamlContent.split('\n').some((line) => {- const trimmed = line.trim();- return !trimmed.startsWith('#') && /^(db_only|supabase_only)\s*:/.test(trimmed);- });- if (mentionsUnresolvedKey) {- throw new Error(- `${yamlPath} mentions db_only but no directories resolved from it — refusing to ` +- `auto-commit (cannot tell "genuinely empty" from "unsupported syntax silently ignored"). ` +- `Fix gbrain.yml's storage.db_only syntax, or git-init this directory manually.`,- );- }+ throw new Error(+ `${yamlPath} mentions db_only but no directories resolved from it — refusing to ` ++ `auto-commit (cannot tell "genuinely empty" from "unsupported syntax silently ignored"). ` ++ `Fix gbrain.yml's storage.db_only syntax, or git-init this directory manually.`,+ );}// #2964 (round 9, P1): every db_only dir is ALWAYS pathspec-excluded,// unconditionally — never pre-filtered against what an existingdiff --git a/src/core/tailscale.ts b/src/core/tailscale.tsindex 3319321a15..7266e1a307 100644--- a/src/core/tailscale.ts+++ b/src/core/tailscale.ts@@ -10,8 +10,10 @@* - `tailscale status --json` → `BackendState` ('Running' | 'NeedsLogin' |* 'NeedsMachineAuth' | 'NoState' | 'Stopped' | 'Starting'), `Self.DNSName`* (trailing dot), `Self.TailscaleIPs`, `Self.CapMap` (object keyed by- * capability URL) or `Self.Capabilities` (string array) — the Funnel node- * attribute shows up as `https://tailscale.com/cap/funnel`,+ * capability) or `Self.Capabilities` (string array, deprecated and `null`+ * on current CLIs) — the Funnel node attribute shows up as `funnel` and+ * `https://tailscale.com/cap/funnel-ports?ports=…` on current control+ * planes, `https://tailscale.com/cap/funnel` on older ones,* `CurrentTailnet.MagicDNSEnabled`, `CertDomains` (non-empty when HTTPS* certificates are enabled), `Version`. The `--json` form exits 0 in EVERY* BackendState (only the human-readable form exits 1 when logged out), so@@ -262,8 +264,19 @@ export function tailscaleDaemonStartHint(platform: string): string {export type TailscaleBackendState = 'Running' | 'NeedsLogin' | 'NeedsMachineAuth' | 'NoState' | 'Stopped' | 'Starting' | string;-/** Node capability that Tailscale Funnel requires (the `funnel` node attribute in the tailnet policy). */+/** Legacy URL form of the Funnel node capability (older control planes). */export const TAILSCALE_FUNNEL_CAPABILITY = 'https://tailscale.com/cap/funnel';+/** Current form: `tailcfg.NodeAttrFunnel` (the `funnel` node attribute in the tailnet policy). */+export const TAILSCALE_FUNNEL_NODE_ATTR = 'funnel';+/** Current form: `tailcfg.CapabilityFunnelPorts`, emitted with a `?ports=` query. */+export const TAILSCALE_FUNNEL_PORTS_CAPABILITY = 'https://tailscale.com/cap/funnel-ports';++/** #5599: any form of the Funnel capability a `CapMap` key or `Capabilities` entry can carry. */+function isFunnelCapability(key: unknown): boolean {+ return key === TAILSCALE_FUNNEL_CAPABILITY || key === TAILSCALE_FUNNEL_NODE_ATTR+ || key === TAILSCALE_FUNNEL_PORTS_CAPABILITY+ || (typeof key === 'string' && key.startsWith(`${TAILSCALE_FUNNEL_PORTS_CAPABILITY}?`));+}export interface TailscaleStatus {backendState: TailscaleBackendState;@@ -304,10 +317,10 @@ export function parseTailscaleStatus(stdout: string): TailscaleStatus | null {const rawDns = typeof self.DNSName === 'string' ? normalizeDnsName(self.DNSName) : '';let funnelCapable: boolean | null = null;if (self.CapMap && typeof self.CapMap === 'object' && !Array.isArray(self.CapMap)) {- funnelCapable = Object.keys(self.CapMap as Record<string, unknown>).includes(TAILSCALE_FUNNEL_CAPABILITY);+ funnelCapable = Object.keys(self.CapMap as Record<string, unknown>).some(isFunnelCapability);}if (Array.isArray(self.Capabilities)) {- funnelCapable = funnelCapable === true || self.Capabilities.includes(TAILSCALE_FUNNEL_CAPABILITY);+ funnelCapable = funnelCapable === true || self.Capabilities.some(isFunnelCapability);}return {backendState: typeof doc.BackendState === 'string' ? doc.BackendState : 'NoState',diff --git a/src/core/takes-write.ts b/src/core/takes-write.tsindex 2dcbbda0b3..721bfc2d55 100644--- a/src/core/takes-write.ts+++ b/src/core/takes-write.ts@@ -52,7 +52,7 @@ import {} from './takes-fence.ts';import { withPageLock } from './page-lock.ts';import { resolvePageFilePath, resolveSourceLocalFilePath } from './markdown.ts';-import { sanitizeRecordedSourcePath, recordedPathFromFileUri } from './write-through.ts';+import { sanitizeRecordedSourcePath, recordedPathFromFileUri, scannerSlugRootMode } from './write-through.ts';import { isWriteTargetContained, msysToNativePath } from './path-confine.ts';import { atomicWriteFileSync } from './atomic-write.ts';@@ -168,7 +168,7 @@ async function resolveTakesFilePath(const recordedUri = rows[0]?.source_uri ?? null;if (sourceLocalPath) {const recordedPath =- resolveSourceLocalFilePath(sourceLocalPath, recordedSourcePath, slug) ??+ (recordedSourcePath ? resolveSourceLocalFilePath(sourceLocalPath, recordedSourcePath, slug, await scannerSlugRootMode(engine, src, sourceLocalPath)) : null) ??(() => {const fromUri = recordedPathFromFileUri(recordedUri, sourceLocalPath);return fromUri ? join(sourceLocalPath, fromUri) : null;diff --git a/src/core/timeline-extract.ts b/src/core/timeline-extract.tsindex 30b49a44cc..cfe81f1dc9 100644--- a/src/core/timeline-extract.ts+++ b/src/core/timeline-extract.ts@@ -13,6 +13,7 @@import { parseInlineCitationTimelineEntries, findTimelineSourceDelimiter } from './link-extraction.ts';import type { BrainEngine } from './engine.ts';+import { firstMaterializedMarkerIndex } from './timeline-marker.ts';export interface ExtractedTimelineEntry {slug: string;@@ -66,7 +67,10 @@ export function extractTimelineFromContent(content: string, slug: string): ExtranextHeader >= 0 ? nextHeader : content.length,nextSection >= 0 ? nextSection : content.length,);- const detail = content.slice(afterIdx, endIdx).trim();+ // #5567: a materialized bullet appended after this header is its own entry.+ const section = content.slice(afterIdx, endIdx);+ const marker = firstMaterializedMarkerIndex(section);+ const detail = (marker >= 0 ? section.slice(0, marker) : section).trim();entries.push({ slug, date: match[1], source: 'markdown', summary: match[2].trim(), detail: detail || undefined });}diff --git a/src/core/timeline-marker.ts b/src/core/timeline-marker.tsnew file mode 100644index 0000000000..8c5fd91f55--- /dev/null+++ b/src/core/timeline-marker.ts@@ -0,0 +1,59 @@+/**+ * #5567 materialized timeline markers.+ *+ * A timeline row that existed only in the database is written back into its+ * page as an ordinary bullet preceded by a standalone comment line:+ *+ * <!-- gbrain:materialized v1 <12-hex tuple hash> -->+ * - **2026-07-01** | legacy — Kickoff held before write-through+ * detail+ *+ * The marker is provenance only. Timeline extractors skip it, remote bodies and+ * chunk text drop it, and a marker whose hash no longer matches the bullet+ * below it (a hand edit) marks nothing.+ */+import { createHash } from 'node:crypto';+import { sanitizeForJsonb } from './batch-rows.ts';++const MARKER_LINE = /^[ \t]*<!-- gbrain:materialized v1 ([0-9a-f]{12}) -->[ \t]*$/;+const MARKER_LINES = /^[ \t]*<!-- gbrain:materialized v1 [0-9a-f]{12} -->[ \t]*(?:\r?\n|$)/gm;++export interface TimelineTuple { date: string; source?: string | null; summary: string }++/** One normalization for prior-set membership, dedup, stored-row matching and marker hashes. */+export function timelineKey(entry: TimelineTuple): string {+ return JSON.stringify([entry.date.slice(0, 10), sanitizeForJsonb(entry.source ?? '').trim(),+ sanitizeForJsonb(entry.summary).replace(/\s+/g, ' ').trim()]);+}++/** Marker hash of an already-normalized `timelineKey`. */+export function timelineKeyHash(key: string): string {+ return createHash('sha256').update(key).digest('hex').slice(0, 12);+}++export function timelineTupleHash(entry: TimelineTuple): string {+ return timelineKeyHash(timelineKey(entry));+}++export function materializedMarker(entry: TimelineTuple): string {+ return `<!-- gbrain:materialized v1 ${timelineTupleHash(entry)} -->`;+}++/** The hash a marker line carries, or null when the line is not a marker. */+export function materializedMarkerHash(line: string): string | null {+ return MARKER_LINE.exec(line)?.[1] ?? null;+}++export function isMaterializedMarkerLine(line: string): boolean {+ return MARKER_LINE.test(line);+}++/** Offset of the first marker line in `text`, or -1. */+export function firstMaterializedMarkerIndex(text: string): number {+ return text.search(/^[ \t]*<!-- gbrain:materialized v1 [0-9a-f]{12} -->[ \t]*$/m);+}++/** Remove whole marker lines so they never reach summaries, details or chunk text. */+export function stripMaterializedMarkers(text: string): string {+ return text.includes('gbrain:materialized') ? text.replace(MARKER_LINES, '') : text;+}diff --git a/src/core/types.ts b/src/core/types.tsindex bc31ffb89b..7a8bb3f4d0 100644--- a/src/core/types.ts+++ b/src/core/types.ts@@ -760,6 +760,8 @@ export interface ChunkInput {*/chunk_source: 'compiled_truth' | 'timeline' | 'fenced_code' | 'image_asset';embedding?: Float32Array;+ /** #5553: embedding-input provenance (see embedding-input-hash.ts); written only with `embedding`. */+ embedding_input_hash?: string;model?: string;token_count?: number;/**@@ -1295,9 +1297,9 @@ export interface SearchOpts extends PageReadPolicy {/*** #4352 — page-level `visibility: private` enforcement for untrusted* callers. When true, both engines' search paths (keyword, titles,- * keyword-chunks, vector) add- * `COALESCE(p.frontmatter->>'visibility','world') <> 'private'` to the- * visibility clause. Callers resolve trust + the config gate via+ * keyword-chunks, vector) add `privatePagesFilterFragment` to the+ * visibility clause (absent visibility is world, except on derived atoms+ * and synthesized concepts, where it is private). Callers resolve trust + the config gate via* `resolveExcludePrivatePages` (search/private-visibility.ts):* ctx.remote !== false → true unless the operator opted out. Omitted /* false = pre-fix behavior (trusted local reads see everything).diff --git a/src/core/write-through.ts b/src/core/write-through.tsindex 97fb48b16c..a5085a5120 100644--- a/src/core/write-through.ts+++ b/src/core/write-through.ts@@ -26,8 +26,10 @@ import { existsSync, statSync, mkdirSync, unlinkSync, readdirSync } from 'fs';import { basename, dirname, isAbsolute, join, relative, resolve } from 'path';import { atomicWriteFileSync } from './atomic-write.ts';import type { BrainEngine } from './engine.ts';-import { serializePageToMarkdown, resolvePageFilePath, resolveSourceLocalFilePath } from './markdown.ts';+import { isRelativeFileUri, serializePageToMarkdown, resolvePageFilePath, resolveSourceLocalFilePath } from './markdown.ts';import { isWriteTargetContained, msysToNativePath } from './path-confine.ts';+import { readSlugRootMode, resolveSlugRootMode, type SlugRootMode } from './sync-anchor.ts';+import { resolveSlugForPath } from './sync.ts';import {isDurabilityHardened, commitWriteThroughFile, currentBranch, getLastPushOutcome,type PushLogOutcome,@@ -145,8 +147,8 @@ export function sanitizeRecordedSourcePath(raw: string | null | undefined): stri* to the slug path.*/export function recordedPathFromFileUri(sourceUri: string | null | undefined, pageRoot: string): string | null {- if (!sourceUri || !sourceUri.startsWith('file://')) return null;- let abs = sourceUri.slice('file://'.length);+ if (!sourceUri || !sourceUri.startsWith('file://') || isRelativeFileUri(sourceUri)) return null;+ let abs = sourceUri.slice('file://'.length).replace(/^localhost(?=\/)/i, '');if (!abs) return null;// Percent-decode only when it looks encoded — the CLI stores raw paths, so a// literal '%' in a filename must not be mangled.@@ -227,18 +229,19 @@ export type PageWriteTarget =/*** Scanner-convention `pages.source_path` for a file under `scanRoot` (the- * root a sync of this source walks). Mirrors sync's #774 rule — a scan root- * INSIDE a git repo records GIT-ROOT-relative paths (scoped sync), a git-root- * or non-git root records root-relative — and must stay the exact inverse of- * `resolveSourceLocalFilePath` (markdown.ts): delete-reconcile keys on this- * form, so a local_path-relative bind for a subdirectory-scoped source would- * read as stale and sweep the page while its file is still on disk.+ * root a sync of this source walks). Mirrors sync's origin rule — a scan root+ * INSIDE a git repo records GIT-ROOT-relative paths under `git-root` slug mode+ * (#774) and scan-root-relative paths under `source-root` mode (#4342, #5610);+ * a git-root or non-git root records root-relative — and must stay the exact+ * inverse of `resolveSourceLocalFilePath` (markdown.ts): delete-reconcile keys+ * on this form, so a bind in the other form reads as stale or as a different+ * origin while its file is still on disk.*/-export function scannerSourcePath(scanRoot: string, filePath: string): string {+export function scannerSourcePath(scanRoot: string, filePath: string, slugRootMode: SlugRootMode = 'git-root'): string {// nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- scanRoot is the operator-written sources.local_path / sync.repo_path config root; canonicalizing it here mints no fs read/write pathconst absRoot = resolve(scanRoot);let cursor = absRoot;- while (true) {+ while (slugRootMode === 'git-root') {// nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- cursor only walks UP (dirname) from the operator-config root joined with the literal '.git' segment; existsSync boolean probe, no content ever read or servedif (existsSync(join(cursor, '.git'))) {// nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- filePath was proven inside writeRoot by isWriteTargetContained before the sole call site (resolvePageWriteTarget); output is an in-memory source_path string, not an fs operand@@ -252,6 +255,15 @@ export function scannerSourcePath(scanRoot: string, filePath: string): string {return relative(absRoot, resolve(filePath)).replaceAll('\\', '/');}+/** The slug-root mode sync records origins in for this scan root: the pin, or the mode the first sync would pin. */+export async function scannerSlugRootMode(engine: BrainEngine, sourceId: string, scanRoot: string): Promise<SlugRootMode> {+ const pinned = await readSlugRootMode(engine, sourceId) ?? (sourceId === 'default' ? await readSlugRootMode(engine, undefined) : null);+ if (pinned) return pinned;+ const scope = scannerSourcePath(scanRoot, scanRoot);+ if (!scope) return 'git-root';+ return resolveSlugRootMode(engine, { sourceId, explicitGitRoot: false, slugPrefix: resolveSlugForPath(`${scope}/x.md`).slice(0, -2), dryRun: true });+}+/*** Compute the ONE file a (source, slug) pair lives in on disk.*@@ -328,7 +340,7 @@ export async function resolvePageWriteTarget(}filePath = recordedPath// nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- result passes isWriteTargetContained before any write (#4204/#4289 guard)- ? resolveSourceLocalFilePath(sourceLocalPath, recordedPath, slug) ?? join(sourceLocalPath, `${slug}.md`)+ ? resolveSourceLocalFilePath(sourceLocalPath, recordedPath, slug, await scannerSlugRootMode(engine, sourceId, sourceLocalPath)) ?? join(sourceLocalPath, `${slug}.md`): join(sourceLocalPath, recordedPathFromFileUri(recordedUri, sourceLocalPath) ?? `${slug}.md`); // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- result passes isWriteTargetContained before any write (#4204/#4289 guard)writeRoot = sourceLocalPath;scanRoot = sourceLocalPath;@@ -367,7 +379,7 @@ export async function resolvePageWriteTarget(return { ok: false, skipped: 'path_escapes_source_root' };}- return { ok: true, filePath, writeRoot, sourcePathToBind: scannerSourcePath(scanRoot, filePath) };+ return { ok: true, filePath, writeRoot, sourcePathToBind: scannerSourcePath(scanRoot, filePath, await scannerSlugRootMode(engine, sourceId, scanRoot)) };}/**diff --git a/src/schema.sql b/src/schema.sqlindex a925442f2e..3f38bdebe9 100644--- a/src/schema.sql+++ b/src/schema.sql@@ -308,6 +308,8 @@ CREATE TABLE IF NOT EXISTS content_chunks (-- #4246 (v133): md5(chunk_text) at embed time. NULL = no embedding or-- pre-v133 row (grandfathered by invalidateContentDriftEmbeddings).embedded_text_hash TEXT,+ -- #5553 (v171): embedding-input provenance written with the vector.+ embedding_input_hash TEXT,created_at TIMESTAMPTZ NOT NULL DEFAULT now(),-- v0.19.0: code chunk metadata. Nullable — markdown chunks leave these NULL.-- Powers `query --lang`, `code-def <symbol>`, and `code-refs <symbol>`.diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.mdindex 44b887a794..2db7729509 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.59.20.0 -->+<!-- gbrain-template-stamp: 0.60.5.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/canonical-projection-history.test.ts b/test/canonical-projection-history.test.tsnew file mode 100644index 0000000000..6080762be3--- /dev/null+++ b/test/canonical-projection-history.test.ts@@ -0,0 +1,287 @@+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { execFileSync } from 'node:child_process';+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 { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { prepareCanonicalProjections, timelineRowAction, type ProjectionWriter } from '../src/core/persistence/canonical-projections.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { withEnv } from './helpers/with-env.ts';+import { testBackends } from './helpers/test-backends.ts';++const backends = testBackends();+const engines: BrainEngine[] = [];+const dataDir = mkdtempSync(join(tmpdir(), 'gbrain-projection-history-'));+let closePostgres: (() => Promise<void>) | undefined;++beforeAll(async () => {+ if (backends.includes('pglite')) {+ const engine = new PGLiteEngine();+ await engine.connect({}); await engine.initSchema(); engines.push(engine);+ }+ if (backends.includes('postgres')) {+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);+ engines.push(pg.engine); closePostgres = pg.close;+ }+}, 120_000);++afterAll(async () => {+ for (const engine of engines) { await disposePersistenceConsumer(engine); if (engine.kind === 'pglite') await engine.disconnect(); }+ await closePostgres?.();+ rmSync(dataDir, { recursive: true, force: true });+});++interface Fixture { engine: BrainEngine; sourceId: string; put(slug: string, content: string, extra?: Record<string, unknown>): Promise<Record<string, unknown>>;+ revision(slug: string): Promise<string>; pageId(slug: string): Promise<number>;+ legacyTimeline(slug: string, row: { date: string; source: string; summary: string; detail?: string }): Promise<void>;+ legacyTake(slug: string, rowNum: number, claim: string): Promise<void>;+ timeline(slug: string): Promise<Array<{ date: string; source: string; summary: string; detail: string }>>;+ takes(slug: string): Promise<Array<{ row_num: number; claim: string }>> }++async function fixture(run: (f: Fixture) => Promise<void>) {+ for (const engine of engines) {+ const dir = mkdtempSync(join(dataDir, 'case-'));+ const root = join(dir, 'brain'); mkdirSync(root);+ const sourceId = `history-${randomUUID().slice(0, 8)}`;+ const ctx = { engine, sourceId, remote: false as const, config: { engine: engine.kind, embedding_disabled: true },+ dryRun: false, logger: { info() {}, warn() {}, error() {} } };+ const coordinated = (sql: string, params: unknown[]) =>+ engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => tx.executeRaw(sql, params)));+ const f: Fixture = {+ engine, sourceId,+ put: (slug, content, extra = {}) => submitPageMutation(ctx, { operation: 'put_page', params: { slug, content, request_id: randomUUID(), ...extra } }),+ revision: async slug => (await engine.readPageSnapshot(slug, { sourceId }))!.revision,+ pageId: async slug => (await engine.readPageSnapshot(slug, { sourceId }))!.page.id,+ legacyTimeline: async (slug, row) => { await coordinated(`INSERT INTO timeline_entries(page_id,date,source,summary,detail)+ SELECT id,$3::date,$4,$5,$6 FROM pages WHERE source_id=$1 AND slug=$2`, [sourceId, slug, row.date, row.source, row.summary, row.detail ?? '']); },+ legacyTake: async (slug, rowNum, claim) => { await coordinated(`INSERT INTO takes(page_id,row_num,claim,kind,holder,weight)+ SELECT id,$3,$4,'take','brain',0.5 FROM pages WHERE source_id=$1 AND slug=$2`, [sourceId, slug, rowNum, claim]); },+ timeline: async slug => engine.executeRaw(`SELECT t.date::text AS date,t.source,t.summary,t.detail FROM timeline_entries t+ JOIN pages p ON p.id=t.page_id WHERE p.source_id=$1 AND p.slug=$2 AND t.event_page_id IS NULL ORDER BY t.date,t.summary`, [sourceId, slug]),+ takes: async slug => engine.executeRaw(`SELECT k.row_num,k.claim FROM takes k JOIN pages p ON p.id=k.page_id+ WHERE p.source_id=$1 AND p.slug=$2 ORDER BY k.row_num`, [sourceId, slug]),+ };+ try {+ await withEnv({ GBRAIN_HOME: join(dir, 'home') }, async () => {+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);+ await claimWorktree(engine, sourceId, root);+ await run(f);+ });+ } finally {+ await disposePersistenceConsumer(engine);+ }+ }+}++const page = (body: string, timeline = '') =>+ `---\ntype: note\ntitle: Example project\n---\n${body}\n${timeline ? `\n## Timeline\n\n${timeline}\n` : ''}`;+const legacy = { date: '2026-07-01', source: 'legacy', summary: 'Kickoff held before write-through', detail: 'pre-write-through evidence' };+const derived = { date: '2026-07-02', source: '', summary: 'Example project', detail: '' };++describe('#5567 coordinated writes keep database-only timeline history', () => {+ test('a forced put_page without a revision keeps legacy and extracted rows that have no bullet', async () => {+ await fixture(async f => {+ await f.put('projects/example', page('First draft.'));+ await f.legacyTimeline('projects/example', legacy);+ await f.legacyTimeline('projects/example', derived);+ await f.put('projects/example', page('Second draft.'), { force: true });+ expect(await f.timeline('projects/example')).toEqual([legacy, derived]);+ });+ });++ test('a put_page with the current revision keeps database-only rows and adds its own bullets', async () => {+ await fixture(async f => {+ await f.put('projects/example', page('First draft.'));+ await f.legacyTimeline('projects/example', legacy);+ await f.put('projects/example', page('Second draft.', '- **2026-08-01** | markdown — Launch review'),+ { expected_revision: await f.revision('projects/example') });+ expect(await f.timeline('projects/example')).toEqual([legacy,+ { date: '2026-08-01', source: 'markdown', summary: 'Launch review', detail: '' }]);+ });+ });++ test('removing a bullet still deletes its own row and nothing else', async () => {+ await fixture(async f => {+ await f.put('projects/example', page('Draft.', '- **2026-08-01** | markdown — Launch review\n- **2026-08-02** | markdown — Follow-up'));+ await f.legacyTimeline('projects/example', legacy);+ await f.put('projects/example', page('Draft.', '- **2026-08-02** | markdown — Follow-up'),+ { expected_revision: await f.revision('projects/example') });+ expect(await f.timeline('projects/example')).toEqual([legacy,+ { date: '2026-08-02', source: 'markdown', summary: 'Follow-up', detail: '' }]);+ });+ });++ test('a user-removed bullet whose legacy row drifted in whitespace is deleted, not resurrected', async () => {+ await fixture(async f => {+ await f.put('projects/example', page('Draft.', '- **2026-08-01** | markdown — Launch review'));+ const pageId = await f.pageId('projects/example');+ await f.engine.transaction(tx => withCoordinatedWrite(tx, [f.sourceId], () => tx.executeRaw(+ `UPDATE timeline_entries SET summary='Launch review ' WHERE page_id=$1`, [pageId])));+ await f.put('projects/example', page('Draft without the bullet.'), { expected_revision: await f.revision('projects/example') });+ expect(await f.timeline('projects/example')).toEqual([]);+ });+ });++ test('a kept bullet replaces its drifted legacy row instead of duplicating it', async () => {+ await fixture(async f => {+ await f.put('projects/example', page('Draft.', '- **2026-08-01** | markdown — Launch review'));+ const pageId = await f.pageId('projects/example');+ await f.engine.transaction(tx => withCoordinatedWrite(tx, [f.sourceId], () => tx.executeRaw(+ `UPDATE timeline_entries SET summary='Launch review ' WHERE page_id=$1`, [pageId])));+ await f.put('projects/example', page('Edited draft.', '- **2026-08-01** | markdown — Launch review'), { force: true });+ expect(await f.timeline('projects/example')).toEqual([{ date: '2026-08-01', source: 'markdown', summary: 'Launch review', detail: '' }]);+ });+ });++ test('editing a bullet detail refreshes its row detail', async () => {+ await fixture(async f => {+ await f.put('projects/example', page('Draft.', '- **2026-08-01** | markdown — Launch review\n First detail'));+ await f.put('projects/example', page('Draft.', '- **2026-08-01** | markdown — Launch review\n Revised detail'),+ { expected_revision: await f.revision('projects/example') });+ expect(await f.timeline('projects/example')).toEqual([{ date: '2026-08-01', source: 'markdown', summary: 'Launch review', detail: 'Revised detail' }]);+ });+ });++ test('rows that change between preparation and apply are never touched by that write', async () => {+ await fixture(async f => {+ const slug = 'projects/example';+ await f.put(slug, page('Draft.', '- **2026-08-01** | markdown — Removed later\n- **2026-08-02** | markdown — Kept bullet'));+ const pageId = await f.pageId(slug);+ const snapshot = await f.engine.readPageSnapshot(slug, { sourceId: f.sourceId, includeDeleted: true });+ const next = parseMarkdown(page('Draft.', '- **2026-08-02** | markdown — Kept bullet\n Canonical detail'), slug);+ const project = await prepareCanonicalProjections(f.engine, next, slug, f.sourceId, snapshot, 'editing');+ await f.engine.transaction(tx => withCoordinatedWrite(tx, [f.sourceId], async () => {+ await tx.executeRaw(`DELETE FROM timeline_entries WHERE page_id=$1 AND summary='Removed later'`, [pageId]);+ await tx.executeRaw(`INSERT INTO timeline_entries(page_id,date,source,summary,detail) VALUES($1,'2026-08-01','markdown','Removed later','recreated')`, [pageId]);+ await tx.executeRaw(`UPDATE timeline_entries SET detail='concurrent detail' WHERE page_id=$1 AND summary='Kept bullet'`, [pageId]);+ await tx.executeRaw(`INSERT INTO timeline_entries(page_id,date,source,summary,detail) VALUES($1,'2026-08-03','','Arrived mid-flight','')`, [pageId]);+ }));+ await f.engine.transaction(tx => withCoordinatedWrite(tx, [f.sourceId], () => project(tx)));+ expect(await f.timeline(slug)).toEqual([+ { date: '2026-08-01', source: 'markdown', summary: 'Removed later', detail: 'recreated' },+ { date: '2026-08-02', source: 'markdown', summary: 'Kept bullet', detail: 'concurrent detail' },+ { date: '2026-08-03', source: '', summary: 'Arrived mid-flight', detail: '' },+ ]);+ });+ });++ test('every writer class keeps database-only rows and deletes only the prior bullets it removed', async () => {+ await fixture(async f => {+ const slug = 'projects/example';+ for (const writer of ['editing', 'preserving', 'immutable'] as ProjectionWriter[]) {+ await f.put(slug, page(`Draft for ${writer}.`, '- **2026-08-01** | markdown — Removed bullet'), { force: true });+ await f.legacyTimeline(slug, legacy);+ const snapshot = await f.engine.readPageSnapshot(slug, { sourceId: f.sourceId, includeDeleted: true });+ const project = await prepareCanonicalProjections(f.engine, parseMarkdown(page(`Next for ${writer}.`), slug), slug, f.sourceId, snapshot, writer);+ await f.engine.transaction(tx => withCoordinatedWrite(tx, [f.sourceId], () => project(tx)));+ expect(await f.timeline(slug)).toEqual([legacy]);+ await f.engine.transaction(tx => withCoordinatedWrite(tx, [f.sourceId], () => tx.executeRaw(+ 'DELETE FROM timeline_entries WHERE page_id=$1', [snapshot!.page.id])));+ }+ });+ });+});++describe('#5567 managed sync keeps database-only timeline history', () => {+ const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });+ const commit = (root: string) => { git(root, 'add', '.'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'edit'); };++ test('a committed file edit synced by the owner keeps legacy rows, deletes only its removed bullet and leaves the file alone', async () => {+ for (const engine of engines) {+ const dir = mkdtempSync(join(dataDir, 'sync-'));+ const root = join(dir, 'brain'); mkdirSync(join(root, 'projects'), { recursive: true });+ const sourceId = `history-sync-${randomUUID().slice(0, 8)}`;+ const file = join(root, 'projects/example.md');+ try {+ await withEnv({ GBRAIN_HOME: join(dir, 'home') }, async () => {+ git(root, 'init', '-q');+ writeFileSync(file, page('Draft.', '- **2026-08-01** | markdown — Launch review\n- **2026-08-02** | markdown — Follow-up'));+ commit(root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [sourceId, root]);+ await claimWorktree(engine, sourceId, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ await performManagedSync(engine, { sourceId, noPull: true });+ await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => tx.executeRaw(`INSERT INTO timeline_entries(page_id,date,source,summary,detail)+ SELECT id,$3::date,$4,$5,$6 FROM pages WHERE source_id=$1 AND slug=$2`, [sourceId, 'projects/example', legacy.date, legacy.source, legacy.summary, legacy.detail])));+ const edited = page('Edited draft.', '- **2026-08-02** | markdown — Follow-up');+ writeFileSync(file, edited); commit(root);+ expect(await performManagedSync(engine, { sourceId, noPull: true })).toMatchObject({ status: 'synced' });+ expect(await engine.executeRaw(`SELECT t.date::text AS date,t.source,t.summary,t.detail FROM timeline_entries t JOIN pages p ON p.id=t.page_id+ WHERE p.source_id=$1 AND p.slug='projects/example' ORDER BY t.date`, [sourceId])).toEqual([legacy,+ { date: '2026-08-02', source: 'markdown', summary: 'Follow-up', detail: '' }]);+ expect(readFileSync(file, 'utf8')).toBe(edited);+ });+ } finally {+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ }+ }+ }, 120_000);+});++describe('#5567 coordinated writes keep database-only takes', () => {+ const fence = (rows: string[]) => ['<!--- gbrain:takes:begin -->', '| # | claim | kind | who | weight | since | source |',+ '|---|-------|------|-----|--------|-------|--------|', ...rows, '<!--- gbrain:takes:end -->'].join('\n');+ const row = (n: number, claim: string) => `| ${n} | ${claim} | take | brain | 0.5 | 2026-07 | notes |`;++ test('a fenced take and a database-only take both survive a page write', async () => {+ await fixture(async f => {+ await f.put('projects/example', page(`Draft.\n\n${fence([row(1, 'Fenced claim')])}`));+ await f.legacyTake('projects/example', 7, 'Database-only claim');+ await f.put('projects/example', page(`Edited.\n\n${fence([row(1, 'Fenced claim')])}`), { force: true });+ expect(await f.takes('projects/example')).toEqual([{ row_num: 1, claim: 'Fenced claim' }, { row_num: 7, claim: 'Database-only claim' }]);+ });+ });++ test('removing a fenced take still deletes it', async () => {+ await fixture(async f => {+ await f.put('projects/example', page(`Draft.\n\n${fence([row(1, 'Fenced claim'), row(2, 'Removed claim')])}`));+ await f.put('projects/example', page(`Edited.\n\n${fence([row(1, 'Fenced claim')])}`), { expected_revision: await f.revision('projects/example') });+ expect(await f.takes('projects/example')).toEqual([{ row_num: 1, claim: 'Fenced claim' }]);+ });+ });++ test('an incoming fence row that collides with a database-only take refuses and leaves the take unchanged', async () => {+ await fixture(async f => {+ await f.put('projects/example', page(`Draft.\n\n${fence([row(1, 'Fenced claim')])}`));+ await f.legacyTake('projects/example', 2, 'Database-only claim');+ const before = await f.revision('projects/example');+ await expect(f.put('projects/example', page(`Edited.\n\n${fence([row(1, 'Fenced claim'), row(2, 'New claim')])}`), { force: true }))+ .rejects.toMatchObject({ code: 'take_row_collision', writeError: 'take_row_collision' });+ expect(await f.takes('projects/example')).toEqual([{ row_num: 1, claim: 'Fenced claim' }, { row_num: 2, claim: 'Database-only claim' }]);+ expect(await f.revision('projects/example')).toBe(before);+ });+ });++ test('an incoming fence row identical to a database-only take adopts it instead of refusing', async () => {+ await fixture(async f => {+ await f.put('projects/example', page(`Draft.\n\n${fence([row(1, 'Fenced claim')])}`));+ await f.legacyTake('projects/example', 2, 'Same claim');+ await f.put('projects/example', page(`Edited.\n\n${fence([row(1, 'Fenced claim'), row(2, 'Same claim')])}`), { force: true });+ expect(await f.takes('projects/example')).toEqual([{ row_num: 1, claim: 'Fenced claim' }, { row_num: 2, claim: 'Same claim' }]);+ });+ });+});++describe('#5567 writer decision table', () => {+ const table: Record<ProjectionWriter, Record<Parameters<typeof timelineRowAction>[1], ReturnType<typeof timelineRowAction>>> = {+ editing: { in_body: 'refresh_detail', drifted: 'delete', removed: 'delete', removed_marked: 'delete', database_only: 'materialize' },+ preserving: { in_body: 'refresh_detail', drifted: 'delete', removed: 'delete', removed_marked: 'materialize', database_only: 'materialize' },+ file: { in_body: 'refresh_detail', drifted: 'delete', removed: 'delete', removed_marked: 'delete', database_only: 'keep' },+ immutable: { in_body: 'refresh_detail', drifted: 'delete', removed: 'delete', removed_marked: 'keep', database_only: 'keep' },+ };+ for (const [writer, rows] of Object.entries(table) as Array<[ProjectionWriter, (typeof table)[ProjectionWriter]]>) {+ for (const [state, action] of Object.entries(rows) as Array<[Parameters<typeof timelineRowAction>[1], ReturnType<typeof timelineRowAction>]>) {+ test(`${writer} writer: ${state} row -> ${action}`, () => { expect(timelineRowAction(writer, state)).toBe(action); });+ }+ }+});diff --git a/test/capture-file-source-path.test.ts b/test/capture-file-source-path.test.tsnew file mode 100644index 0000000000..5b604e0947--- /dev/null+++ b/test/capture-file-source-path.test.ts@@ -0,0 +1,144 @@+/**+ * #5622 / #5603: `capture --file` stored `file://<path as typed>`. A relative+ * path produced a host-bearing URI that resolves differently per process and,+ * once a shared skillpack exists, refused every write to the page. Capture now+ * records a source-relative source_path for a file inside the source (never a+ * file URI or a home path), `cli-file` for anything else, and legacy relative+ * URIs are read as absent.+ * The relative-path and special-character filename cases are adapted from+ * community PR #5670.+ */+import { afterAll, beforeAll, beforeEach, expect, test } from 'bun:test';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { runCapture } from '../src/commands/capture.ts';+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';+import { recordedPathFromFileUri } from '../src/core/write-through.ts';+import { isRelativeFileUri, resolveSourceLocalFilePath } from '../src/core/markdown.ts';+import { execFileSync } from 'node:child_process';+import { resolveSlugForPath } from '../src/core/sync.ts';+import { operationsByName } from '../src/core/operations.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';++let engine: PGLiteEngine;+let tmpRoot: string;+let brainDir: string;+beforeAll(async () => {+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} });+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();+});+afterAll(async () => { await engine.disconnect(); resetGateway(); });+beforeEach(async () => {+ await resetPgliteState(engine);+ tmpRoot = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'gbrain-capture-path-')));+ brainDir = path.join(tmpRoot, 'brain');+ fs.mkdirSync(path.join(brainDir, 'notes'), { recursive: true });+ await engine.setConfig('sync.repo_path', brainDir);+ await engine.setConfig('schema_pack', 'gbrain-base');+});+async function capture(args: string[]) {+ const log = console.log; console.log = () => {};+ try { await runCapture(engine, [...args, '--quiet']); } finally { console.log = log; }+}+const row = async (slug: string) => (await engine.executeRaw<{ source_path: string | null; source_uri: string | null }>(+ "SELECT source_path,source_uri FROM pages WHERE source_id='default' AND slug=$1", [slug]))[0];++test('relative and absolute captures of an in-source file record its source-relative path and no file URI', async () => {+ const relativeFile = path.join(brainDir, 'notes', 'in-source.md');+ fs.writeFileSync(relativeFile, '# In source\n\nA captured observation inside the source.\n');+ await capture(['--file', path.relative(process.cwd(), relativeFile), '--slug', 'notes/in-source']);+ expect(await row('notes/in-source')).toEqual({ source_path: 'notes/in-source.md', source_uri: null });+ expect(fs.readFileSync(relativeFile, 'utf8')).toContain('A captured observation inside the source.');+ expect(fs.readdirSync(path.join(brainDir, 'notes'))).toEqual(['in-source.md']);++ const special = path.join(brainDir, 'notes', 'note #1.md');+ fs.writeFileSync(special, '# Special\n\nA captured observation with a special file name.\n');+ const slug = resolveSlugForPath('notes/note #1.md');+ await capture(['--file', special, '--slug', slug]);+ expect(await row(slug)).toEqual({ source_path: 'notes/note #1.md', source_uri: null });+});++test('an external file or an in-source file captured under another slug records no path and targets the slug', async () => {+ const outside = path.join(tmpRoot, 'outside.md');+ fs.writeFileSync(outside, '# Outside\n\nA captured observation outside the source.\n');+ await capture(['--file', path.relative(process.cwd(), outside), '--slug', 'inbox/external']);+ expect(await row('inbox/external')).toEqual({ source_path: 'inbox/external.md', source_uri: 'cli-file' });+ expect(fs.readFileSync(outside, 'utf8')).toBe('# Outside\n\nA captured observation outside the source.\n');++ const inside = path.join(brainDir, 'notes', 'other-name.md');+ fs.writeFileSync(inside, '# Inside\n\nAn in-source observation captured under an inbox slug.\n');+ await capture(['--file', inside, '--slug', 'inbox/renamed']);+ expect(await row('inbox/renamed')).toEqual({ source_path: 'inbox/renamed.md', source_uri: 'cli-file' });+ expect(fs.readFileSync(inside, 'utf8')).toBe('# Inside\n\nAn in-source observation captured under an inbox slug.\n');++ const ctx = { engine, remote: true, sourceId: 'default', config: { engine: 'pglite' }, dryRun: false,+ auth: { clientId: 'example-reader', scopes: ['read'], sourceId: 'default' },+ logger: { info() {}, warn() {}, error() {} } } as unknown as OperationContext;+ for (const slug of ['inbox/external', 'inbox/renamed']) {+ const page = await operationsByName.get_page!.handler(ctx, { slug });+ expect(JSON.stringify(page)).not.toContain(tmpRoot);+ }+});++test('a legacy relative file URI never resolves against the process directory', () => {+ const previous = process.cwd();+ process.chdir(tmpRoot);+ try {+ fs.writeFileSync(path.join(brainDir, 'notes', 'legacy.md'), 'Legacy captured file.\n');+ expect(recordedPathFromFileUri('file://brain/notes/legacy.md', brainDir)).toBeNull();+ expect(recordedPathFromFileUri('file://notes/legacy.md', brainDir)).toBeNull();+ expect(recordedPathFromFileUri(`file://${path.join(brainDir, 'notes', 'legacy.md')}`, brainDir)).toBe(path.join('notes', 'legacy.md'));+ expect(recordedPathFromFileUri(`file://localhost${path.join(brainDir, 'notes', 'legacy.md')}`, brainDir)).toBe(path.join('notes', 'legacy.md'));+ } finally { process.chdir(previous); }+});++test('remote callers cannot name a local capture file or a capture path', async () => {+ const ctx = { engine, remote: true, sourceId: 'default', config: { engine: 'pglite' }, dryRun: false,+ auth: { clientId: 'example-writer', scopes: ['write'], sourceId: 'default' },+ logger: { info() {}, warn() {}, error() {} } } as unknown as OperationContext;+ for (const extra of [{ local_file: path.join(brainDir, 'notes', 'x.md') }, { capture_path: 'notes/x.md' }]) {+ await expect(operationsByName.capture!.handler(ctx, { content: 'Remote capture body.', slug: 'notes/x', ...extra }))+ .rejects.toMatchObject({ code: 'invalid_params' });+ }+});++test('historical absolute Windows drive URIs stay absolute while relative and host-only URIs are absent', () => {+ for (const uri of ['file:///home/example/notes/a.md', 'file://localhost/home/example/a.md', 'file://C:/vault/notes/a.md', 'file://C:\\vault\\notes\\a.md']) {+ expect(isRelativeFileUri(uri)).toBe(false);+ }+ for (const uri of ['file://notes/a.md', 'file://example-note.md', 'file://server/share/a.md', 'file://../../tmp/a.md']) {+ expect(isRelativeFileUri(uri)).toBe(true);+ }+});++test('a git-root subdirectory source binds an in-source capture under its Git-prefixed slug without a twin', async () => {+ const repo = path.join(tmpRoot, 'repo');+ const scoped = path.join(repo, 'docs');+ fs.mkdirSync(scoped, { recursive: true });+ execFileSync('git', ['init', '-q', repo]);+ await engine.setConfig('sync.repo_path', scoped);+ await engine.setConfig('sync.slug_root_mode', 'git-root');+ const file = path.join(scoped, 'a.md');+ fs.writeFileSync(file, '# A\n\nA git-root scoped capture.\n');+ await capture(['--file', file, '--slug', 'docs/a']);+ expect(await row('docs/a')).toEqual({ source_path: 'docs/a.md', source_uri: null });+ expect(fs.readFileSync(file, 'utf8')).toContain('A git-root scoped capture.');+ expect(fs.existsSync(path.join(scoped, 'docs'))).toBe(false);+});++test('source-path decoding follows the slug-root mode, including the legacy Git-root form and basename rows', () => {+ const repo = path.join(tmpRoot, 'decode');+ const scoped = path.join(repo, 'docs');+ fs.mkdirSync(path.join(scoped, 'docs'), { recursive: true });+ execFileSync('git', ['init', '-q', repo]);+ fs.writeFileSync(path.join(scoped, 'docs', 'a.md'), 'nested');+ fs.writeFileSync(path.join(scoped, 'a.md'), 'sibling');+ expect(resolveSourceLocalFilePath(scoped, 'docs/a.md', 'docs/a', 'source-root')).toBe(path.join(scoped, 'docs', 'a.md'));+ expect(resolveSourceLocalFilePath(scoped, 'docs/a.md', 'a', 'source-root')).toBe(path.join(scoped, 'a.md'));+ expect(resolveSourceLocalFilePath(scoped, 'docs/a.md', 'docs/a', 'git-root')).toBe(path.join(scoped, 'a.md'));+ fs.rmSync(path.join(scoped, 'a.md'));+ expect(resolveSourceLocalFilePath(scoped, 'a.md', 'docs/a', 'source-root')).toBe(path.join(scoped, 'docs', 'a.md'));+});diff --git a/test/cli-help-without-brain.serial.test.ts b/test/cli-help-without-brain.serial.test.tsindex f6571a00dd..86b766f3b9 100644--- a/test/cli-help-without-brain.serial.test.ts+++ b/test/cli-help-without-brain.serial.test.ts@@ -35,6 +35,8 @@ const HELP_WITHOUT_BRAIN = ['sources',// cathedral-6: agent answers --help (incl. `register --help`) engine-free.'agent',+ // wave-2 repair core: runRepairCommand prints REPAIR_HELP before the engine.+ 'repair',];/**diff --git a/test/config-set.test.ts b/test/config-set.test.tsindex d7ba062922..b0337f9c5d 100644--- a/test/config-set.test.ts+++ b/test/config-set.test.ts@@ -328,6 +328,25 @@ describe('#2753 — the doctor-proposed gateway-loop command is accepted by `conexpect(setCalls).toEqual([]);});+ test('persistence.limits.*: accepted without --force and never called unread (#5470)', async () => {+ for (const key of ['persistence.limits.principal_terminal_bytes', 'persistence.limits.principal_lifetime_ids', 'persistence.receipt_retention_days']) {+ const { engine, setCalls } = setStubEngine();+ const { errs, exit } = await runConfigCapture(engine, ['set', key, '268435456']);+ expect(exit).toBeNull();+ expect(errs.join('\n')).not.toContain('Unknown config key');+ expect(errs.join('\n')).not.toContain('Nothing in gbrain reads this');+ expect(setCalls).toEqual([[key, '268435456']]);+ }+ });++ test('persistence.limits.*: rejects a value every admission would refuse (#5470)', async () => {+ const { engine, setCalls } = setStubEngine();+ const { errs, exit } = await runConfigCapture(engine, ['set', 'persistence.limits.principal_lifetime_ids', '1.5e6']);+ expect(exit).toBe(1);+ expect(errs.join('\n')).toContain('expected a nonnegative integer');+ expect(setCalls).toEqual([]);+ });+test('cycle.timezone: accepts a valid IANA timezone (#4348)', async () => {const { engine, setCalls } = setStubEngine();const { errs, exit } = await runConfigCapture(diff --git a/test/connector-physical-root-device.test.ts b/test/connector-physical-root-device.test.tsnew file mode 100644index 0000000000..2fe9810630--- /dev/null+++ b/test/connector-physical-root-device.test.ts@@ -0,0 +1,47 @@+/**+ * #5604 for managed connectors: a device-only physical-root change (a macOS+ * reboot renumbering the filesystem) is re-stamped by the connector's locked+ * worktree acquisition before the connector root is asserted, so Google and+ * GitHub sync keep running like every other managed writer.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { readFileSync, statSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { parseGitHubSourceConfig, runGitHubSync } from '../src/core/github-source.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { PHYSICAL_ROOT_MARKER, physicalRootReservationPath } from '../src/core/persistence/physical-root-record.ts';+import { withEnv } from './helpers/with-env.ts';+import { createConnectorFixture, options, json, githubConfig, issueFixture, githubFetch } from './helpers/connector-fixture.ts';++const { engines, env, boundSource, setup, teardown } = createConnectorFixture();+beforeAll(setup, 120_000);+afterAll(teardown);++const readJson = (path: string) => JSON.parse(readFileSync(path, 'utf8'));+const writeJson = (path: string, value: unknown) => writeFileSync(path, JSON.stringify(value), { mode: 0o600 });++test('a device-only change is re-stamped and managed connector sync continues', async () => {+ await withEnv(env, async () => {+ for (const engine of engines) {+ const f = await boundSource(engine, githubConfig);+ let body = 'Before the reboot';+ const run = () => runGitHubSync(engine, f.id, parseGitHubSourceConfig(githubConfig, f.dir),+ { ...options, githubItem: { repo: 'acme-example/app', number: 1, kind: 'issue' } },+ async url => new URL(url).pathname.endsWith('/issues/1') ? json({ ...issueFixture, body }) : githubFetch()(url));+ await run();+ await disposePersistenceConsumer(engine);+ const root = f.binding.local_path!;+ const live = statSync(root, { bigint: true }).dev.toString();+ const previous = String(BigInt(live) + 1n);+ const marker = join(root, PHYSICAL_ROOT_MARKER), reservation = physicalRootReservationPath(root);+ writeJson(marker, { ...readJson(marker), device: previous });+ writeJson(reservation, { ...readJson(reservation), initialDevice: previous });+ body = 'After the reboot';+ expect((await run()).modified).toBe(1);+ await disposePersistenceConsumer(engine);+ expect(readFileSync(join(f.dir, 'gh/acme-example/app/1.md'), 'utf8')).toContain('After the reboot');+ expect(readJson(marker).device).toBe(live);+ expect(readJson(reservation).initialDevice).toBe(live);+ }+ });+}, 120_000);diff --git a/test/contextual-retrieval-doctor.serial.test.ts b/test/contextual-retrieval-doctor.serial.test.tsindex 080c18d72d..2a792f226e 100644--- a/test/contextual-retrieval-doctor.serial.test.ts+++ b/test/contextual-retrieval-doctor.serial.test.ts@@ -110,16 +110,30 @@ describe('contextual_retrieval_coverage doctor check', () => {expect(result.status).toBe('ok');});- test('non-markdown pages (code) are not counted', async () => {+ test('sealed code pages are not counted for chunker drift or CR mode', async () => {await engine.executeRaw(`INSERT INTO pages (source_id, slug, type, title, compiled_truth, chunker_version, contextual_retrieval_mode, page_kind)- VALUES ('default', $1, 'code', 'Code page', 'body', 2, NULL, 'code')`,+ VALUES ('default', $1, 'code', 'Code page', 'body', 4, NULL, 'code')`,['test/code-page'],);const result = await checkContextualRetrievalCoverage(engine);expect(result.status).toBe('ok');});+ test('#5247: a code page below the safe-chunk fence is counted and names the re-seal repair', async () => {+ await engine.executeRaw(+ `INSERT INTO pages (source_id, slug, type, title, compiled_truth, chunker_version, contextual_retrieval_mode, page_kind)+ VALUES ('default', $1, 'code', 'Code page', 'body', 2, NULL, 'code')`,+ ['test/code-page'],+ );+ const result = await checkContextualRetrievalCoverage(engine);+ expect(result.status).toBe('warn');+ expect(result.message).toContain('1 page(s) below the safe-chunk index version (1 code)');+ expect(result.message).toContain('gbrain repair safe-chunks');+ expect(result.message).not.toContain('older chunker_version');+ expect(result.details).toMatchObject({ unsealed_pages: 1, unsealed_code_pages: 1, repair: 'safe-chunks' });+ });+test('audit summary line surfaces recent synopsis failures', async () => {// Drop a failure event into the audit JSONL.const { computeSynopsisAuditFilename } = await import('../src/core/audit-synopsis.ts');diff --git a/test/cycle-patterns-child-outcome.test.ts b/test/cycle-patterns-child-outcome.test.tsindex 28b9155f3f..84737003bc 100644--- a/test/cycle-patterns-child-outcome.test.ts+++ b/test/cycle-patterns-child-outcome.test.ts@@ -94,11 +94,13 @@ describe('runPhasePatterns child-outcome status (#2782)', () => {runPhasePatterns(engine, { brainDir, dryRun: false }),);- const jobs = await engine.executeRaw<{ timeout_ms: string | number | null }>(- `SELECT timeout_ms FROM minion_jobs WHERE name = 'subagent' ORDER BY id DESC LIMIT 1`,+ const jobs = await engine.executeRaw<{ timeout_ms: string | number | null; data: Record<string, unknown> }>(+ `SELECT timeout_ms, data FROM minion_jobs WHERE name = 'subagent' ORDER BY id DESC LIMIT 1`,);expect(jobs).toHaveLength(1);expect(Number(jobs[0]!.timeout_ms)).toBe(600000);+ expect(jobs[0]!.data.require_writes).toBe(true);+ expect(jobs[0]!.data.allow_clean_zero_writes).toBe(true);} finally {rmSync(brainDir, { recursive: true, force: true });}diff --git a/test/cycle-synthesize-breaker.test.ts b/test/cycle-synthesize-breaker.test.tsnew file mode 100644index 0000000000..baae269942--- /dev/null+++ b/test/cycle-synthesize-breaker.test.ts@@ -0,0 +1,226 @@+/**+ * Paid-loop breaker at the synthesize phase: a transcript key whose+ * submissions died 3 times in 24h is refused before any job row is inserted,+ * with the reset command in the cycle's skip report. Same keyless PGLite rig+ * as cycle-synthesize-daily-cap.test.ts.+ */++import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';+import { mkdtempSync, rmSync, writeFileSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import { createHash } from 'node:crypto';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { withEnv } from './helpers/with-env.ts';+import { runPhaseSynthesize, TRIAGE_VERSION } from '../src/core/cycle/synthesize.ts';+import { TIER_DEFAULTS } from '../src/core/model-config.ts';++// Canonical shared-engine block (check-test-isolation R3/R4).+let engine: PGLiteEngine;+let schemaVersion: string;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({ engine: 'pglite' } as never);+ await engine.initSchema();+ // resetPgliteState truncates `config`, wiping the `version` row that+ // MinionQueue.ensureSchema checks. Capture it so beforeEach can restore.+ schemaVersion = (await engine.getConfig('version')) ?? '7';+}, 60_000);++afterAll(async () => {+ await engine.disconnect();+});++beforeEach(async () => {+ await resetPgliteState(engine);+ await engine.setConfig('version', schemaVersion);+});++interface Rig {+ engine: PGLiteEngine;+ brainDir: string;+ corpusDir: string;+ cleanup: () => Promise<void>;+}++/** Per-test dirs + dream config on the SHARED engine (reset by beforeEach). */+async function setupRig(): Promise<Rig> {+ const brainDir = mkdtempSync(join(tmpdir(), 'gbrain-breaker-brain-'));+ const corpusDir = mkdtempSync(join(tmpdir(), 'gbrain-breaker-corpus-'));+ await engine.setConfig('dream.synthesize.enabled', 'true');+ await engine.setConfig('dream.synthesize.session_corpus_dir', corpusDir);+ return {+ engine,+ brainDir,+ corpusDir,+ cleanup: async () => {+ try { rmSync(brainDir, { recursive: true, force: true }); } catch { /* */ }+ try { rmSync(corpusDir, { recursive: true, force: true }); } catch { /* */ }+ },+ };+}++async function withSubagentAutoCancel<T>(+ engine: PGLiteEngine,+ body: () => Promise<T>,+ opts: { excludeQueue?: string } = {},+): Promise<T> {+ let stopped = false;+ const loop = (async () => {+ while (!stopped) {+ await new Promise(r => setTimeout(r, 50));+ try {+ // excludeQueue: deliberately-seeded fixture rows must be handled by+ // the code under test, not this poller (a poller cancel changes the+ // row's coalescibility and races the assertion).+ await engine.executeRaw(+ `UPDATE minion_jobs+ SET status = 'cancelled', finished_at = now()+ WHERE name = 'subagent' AND status IN ('waiting', 'active')+ AND ($1::text IS NULL OR queue <> $1)`,+ [opts.excludeQueue ?? null],+ );+ } catch { /* race against shutdown is fine */ }+ }+ })();+ try {+ return await body();+ } finally {+ stopped = true;+ await loop;+ }+}++/** Write a small transcript + seed a passing triage-v1 verdict for it. */+async function seedPassingFile(rig: Rig, name: string): Promise<string> {+ const content = `conversation in ${name}\n`.repeat(200);+ const filePath = join(rig.corpusDir, name);+ writeFileSync(filePath, content);+ const hash = createHash('sha256').update(content, 'utf8').digest('hex');+ await rig.engine.putDreamVerdict(filePath, hash, {+ worth_processing: true,+ reasons: ['seed'],+ score: 0.9,+ content_type: null,+ segments: [],+ entities: [],+ model: TIER_DEFAULTS.utility,+ triage_version: TRIAGE_VERSION,+ });+ return filePath;+}++/** Seed a recent (or old) synth-v2 submission row for the cap counter. */+async function seedSubmissionRow(rig: Rig, opts: { ageHours?: number; status?: string; sourceId?: string; tag: string }): Promise<void> {+ await rig.engine.executeRaw(+ `INSERT INTO minion_jobs (submission_authority, name, queue, status, data, idempotency_key, created_at)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'subagent', 'dream-inline-old-run', $1,+ jsonb_build_object('source_id', $2::text),+ $3,+ now() - ($4 || ' hours')::interval)`,+ [opts.status ?? 'waiting', opts.sourceId ?? 'default',+ `dream:synth-v2:default:filename:${opts.tag}:0123456789abcdef`,+ String(opts.ageHours ?? 1)],+ );+}++interface CapDetails {+ children_submitted: number;+ skips: Array<{ filePath: string; reason: string }>;+}++async function runPhase(+ rig: Rig,+ opts: { date?: string; excludeQueue?: string; now?: () => Date } = {},+): Promise<CapDetails> {+ // No key + isolated GBRAIN_HOME: every seeded verdict is a cache hit, so no+ // judge call happens; the env isolation is belt-and-suspenders against a+ // dev machine whose config file carries a real key.+ const { excludeQueue, ...phaseOpts } = opts;+ const tmpHome = mkdtempSync(join(tmpdir(), 'gbrain-breaker-isol-'));+ try {+ const result = await withEnv({ ANTHROPIC_API_KEY: undefined, GBRAIN_HOME: tmpHome }, () =>+ withSubagentAutoCancel(rig.engine, () =>+ runPhaseSynthesize(rig.engine, { brainDir: rig.brainDir, dryRun: false, ...phaseOpts }),+ { excludeQueue }));+ // CDX-4 (#4217 family): in this keyless harness every submitted child+ // dies, and an all-children-dead run is now an honest phase failure+ // (fan-out details preserved). Zero-submission runs still report 'ok'.+ // This suite's subject is the CAP accounting in details, not the phase+ // verdict.+ if (result.status !== 'ok') {+ expect(result.error?.code).toBe('SYNTH_ALL_CHILDREN_DEAD');+ }+ return result.details as unknown as CapDetails;+ } finally {+ try { rmSync(tmpHome, { recursive: true, force: true }); } catch { /* */ }+ }+}+++function keyFor(name: string): string {+ const content = `conversation in ${name}\n`.repeat(200);+ const hash16 = createHash('sha256').update(content, 'utf8').digest('hex').slice(0, 16);+ return `dream:synth-v2:default:filename:${name}:${hash16}`;+}++async function seedDead(rig: Rig, key: string, queue: string): Promise<void> {+ await rig.engine.executeRaw(+ `INSERT INTO minion_jobs (submission_authority, name, queue, status, data, idempotency_key, created_at, finished_at)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'subagent', $1, 'dead', $2::text::jsonb, NULL, now() - interval '1 hour', now() - interval '1 hour')`,+ [queue, JSON.stringify({ source_id: 'default', __released_idempotency_key: key })],+ );+}++async function liveRows(rig: Rig, key: string): Promise<number> {+ const rows = await rig.engine.executeRaw<{ n: number }>(+ `SELECT count(*)::int AS n FROM minion_jobs WHERE idempotency_key = $1`, [key]);+ return rows[0]!.n;+}++describe('synthesize paid-loop breaker', () => {+ test('after three dead submissions the fourth is refused before any job row is inserted', async () => {+ const rig = await setupRig();+ try {+ const looping = await seedPassingFile(rig, '2026-08-10-loop.txt');+ await seedPassingFile(rig, '2026-08-11-fresh.txt');+ for (const queue of ['dream-inline-1', 'dream-inline-2', 'dream-inline-3']) await seedDead(rig, keyFor('2026-08-10-loop.txt'), queue);+ const details = await runPhase(rig);+ expect(details.children_submitted).toBe(1);+ expect(await liveRows(rig, keyFor('2026-08-10-loop.txt'))).toBe(0);+ const refusal = details.skips.find(s => s.filePath === looping)!;+ expect(refusal.reason).toStartWith('dream_breaker_tripped: 3 dead submissions');+ expect(refusal.reason).toContain(`gbrain dream reset-key '${keyFor('2026-08-10-loop.txt')}'`);+ } finally { await rig.cleanup(); }+ }, 60_000);++ test('two dead submissions still submit; a reset re-enables a tripped key', async () => {+ const rig = await setupRig();+ try {+ await seedPassingFile(rig, '2026-08-12-two.txt');+ for (const queue of ['dream-inline-1', 'dream-inline-2']) await seedDead(rig, keyFor('2026-08-12-two.txt'), queue);+ expect((await runPhase(rig)).children_submitted).toBe(1);+ await rig.engine.executeRaw(`DELETE FROM minion_jobs WHERE status <> 'dead'`);+ await seedDead(rig, keyFor('2026-08-12-two.txt'), 'dream-inline-3');+ expect((await runPhase(rig)).children_submitted).toBe(0);+ const { resetDreamBreakerKey } = await import('../src/core/cycle/dream-breaker.ts');+ await resetDreamBreakerKey(rig.engine, keyFor('2026-08-12-two.txt'));+ expect((await runPhase(rig)).children_submitted).toBe(1);+ } finally { await rig.cleanup(); }+ }, 90_000);++ test('the daily cap counts dead rows whose key the queue released', async () => {+ const rig = await setupRig();+ try {+ await rig.engine.setConfig('dream.synthesize.max_submissions_per_source_per_day', '2');+ await rig.engine.setConfig('dream.breaker.max_dead_submissions', '0');+ await seedPassingFile(rig, '2026-08-13-capped.txt');+ for (const queue of ['dream-inline-1', 'dream-inline-2']) await seedDead(rig, 'dream:synth-v2:default:filename:other.txt:0123456789abcdef', queue);+ const details = await runPhase(rig);+ expect(details.children_submitted).toBe(0);+ expect(details.skips.some(s => s.reason.startsWith('daily_cap_reached: 2/2'))).toBe(true);+ } finally { await rig.cleanup(); }+ }, 60_000);+});diff --git a/test/cycle-synthesize-verify.test.ts b/test/cycle-synthesize-verify.test.tsindex d208b72202..09b8cb8fa2 100644--- a/test/cycle-synthesize-verify.test.ts+++ b/test/cycle-synthesize-verify.test.ts@@ -20,6 +20,7 @@ import {} from '../src/core/cycle/synthesize-verify.ts';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { importFromContent } from '../src/core/import-file.ts';+import { renderMaterializedBullet } from '../src/core/persistence/canonical-projections.ts';function grounded(content: string) {const { norm, map } = normalizeForGrounding(content);@@ -210,6 +211,34 @@ describe('verifyBody', () => {});});+describe('verifyBody — materialized timeline history (#5567)', () => {+ const src = groundSource('/t/history.txt', 'user: We shipped the repair pass on Monday.');+ const marked = renderMaterializedBullet({ date: '2024-01-02', source: 'meeting', summary: 'Said "we will open a second office in 2025"', detail: 'Recorded "before write-through" in 2023.' }, 'x')!;+ const fabricated = '- **2026-08-30** | session — Said "we are shutting down the company next quarter"';+ const priorNorm = normForGrounding('A reflection.');++ test('a bullet materialized during the run is database history and is left alone, detail included', () => {+ expect(marked).toBeTruthy();+ const kept = verifyBody(`${marked}\n${fabricated}`, [src], { priorNorm });+ expect(kept.body).toBe(marked);+ expect(kept.quarantined.map(q => q.text)).toEqual([fabricated.slice(2)]);+ });++ test('a claim added under a marked bullet that already existed is verified', () => {+ const lines = marked.split('\n');+ const edited = [lines[0], lines[1], ' Also said "we are shutting down the company next quarter".'].join('\n');+ const result = verifyBody(edited, [src], { priorNorm: normForGrounding(`A reflection.\n${lines[0]}\n${lines[1]}`) });+ expect(result.body).toBe([lines[0], lines[1]].join('\n'));+ expect(result.quarantined).toHaveLength(1);+ });++ test('a new page has no history to exempt, and a forged marker is verified', () => {+ expect(verifyBody(marked, [src]).quarantined.length).toBeGreaterThan(0);+ const forged = marked.replace(/v1 [0-9a-f]+/, 'v1 000000000000');+ expect(verifyBody(forged, [src], { priorNorm }).quarantined.length).toBeGreaterThan(0);+ });+});+describe('speaker provenance (write-path audit C-6)', () => {const transcript = ['user (t1): I think the real insight is that memory systems fail at the',@@ -509,4 +538,27 @@ describe('verifyAndRepairDreamPages — PGLite write-back integration', () => {const hits = await engine.searchKeyword('rewrite entire engine Rust', { limit: 5 });expect(hits.filter(h => h.slug === slug)).toHaveLength(0);}, 60_000);++ test('re-projection deletes the rows of quarantined bullets and keeps database-only timeline history (#5567)', async () => {+ const transcript = 'user: We shipped the repair pass on Monday.';+ const since = await readVerifyEpoch(engine);+ const slug = 'wiki/personal/reflections/2026-08-31-history-abc789';+ await importFromContent(engine, slug, [+ '---', 'type: note', '---', 'A reflection.', '', '## Timeline', '',+ '- **2026-08-30** | session — Said "we are shutting down the company next quarter"',+ ].join('\n'), { noEmbed: true, remote: false, sourceId: 'default' });+ const [page] = await engine.executeRaw<{ id: number }>("SELECT id FROM pages WHERE slug=$1 AND source_id='default'", [slug]);+ const rows = () => engine.executeRaw<{ summary: string }>('SELECT summary FROM timeline_entries WHERE page_id=$1 ORDER BY summary', [page.id]);+ await engine.executeRaw(`INSERT INTO timeline_entries(page_id,date,source,summary,detail) VALUES+ ($1,'2026-08-30','session','Said "we are shutting down the company next quarter"',''),+ ($1,'2024-01-02','extract','Database-only history','')+ ON CONFLICT DO NOTHING`, [page.id]);+ expect((await rows()).map(r => r.summary)).toEqual(['Database-only history', 'Said "we are shutting down the company next quarter"']);++ const stats = await verifyAndRepairDreamPages(engine, [{ slug, source_id: 'default', raw_source: '/t/history.md' }],+ new Map([['/t/history.md', { content: transcript }]]), { since, checkedAt: '2026-08-31' });+ expect(stats.pages_repaired).toBe(1);+ expect((await engine.getPage(slug, { sourceId: 'default' }))!.timeline).not.toContain('shutting down');+ expect((await rows()).map(r => r.summary)).toEqual(['Database-only history']);+ }, 60_000);});diff --git a/test/cycle-write-path-mini-eval.test.ts b/test/cycle-write-path-mini-eval.test.tsindex 8348dc1855..9f8809a2c4 100644--- a/test/cycle-write-path-mini-eval.test.ts+++ b/test/cycle-write-path-mini-eval.test.ts@@ -268,7 +268,7 @@ describe('F-Eval: hermetic write-path mini-eval (real phase, scripted transport)}}, 120_000);- test('kill switch: quote_verify=false leaves fabricated quotes intact and reports quote_verify null; a declining required-write child stays incomplete', async () => {+ test('kill switch: quote_verify=false leaves fabricated quotes intact and reports quote_verify null; a declining child completes and counts in children_zero_pages (#5590)', async () => {const brainDir2 = mkdtempSync(join(tmpdir(), 'gbrain-minieval-brain2-'));const corpusDir2 = mkdtempSync(join(tmpdir(), 'gbrain-minieval-corpus2-'));try {@@ -307,10 +307,10 @@ describe('F-Eval: hermetic write-path mini-eval (real phase, scripted transport)expect(result.status).toBe('ok');const d = result.details as { written_slugs: string[]; child_outcomes: Array<{ status: string }>; synthesis: { quote_verify: unknown; children_zero_pages: number; non_completed_jobs: number } };expect(d.synthesis.quote_verify).toBeNull(); // pass skipped entirely- expect(d.synthesis.children_zero_pages).toBe(0);- expect(d.synthesis.non_completed_jobs).toBe(1);- expect(d.child_outcomes.filter(child => child.status !== 'completed')).toEqual([expect.objectContaining({ status: 'dead' })]);- expect(await engine.getConfig('dream.synthesize.last_completion_ts')).toBe('');+ expect(d.synthesis.children_zero_pages).toBe(1); // rule-D decliner counted+ expect(d.synthesis.non_completed_jobs).toBe(0);+ expect(d.child_outcomes.every(child => child.status === 'completed')).toBe(true);+ expect(await engine.getConfig('dream.synthesize.last_completion_ts')).not.toBe('');const killSlug = d.written_slugs.find(s => s.includes('killswitch'));expect(killSlug).toBeDefined();const page = await engine.getPage(killSlug!, { sourceId: 'default' });diff --git a/test/derived-page-visibility.test.ts b/test/derived-page-visibility.test.tsnew file mode 100644index 0000000000..5933d90beb--- /dev/null+++ b/test/derived-page-visibility.test.ts@@ -0,0 +1,111 @@+/**+ * #5525 read-side containment: extracted atoms and synthesized concepts with+ * no `visibility` field fail closed for remote readers. An explicit value wins,+ * ordinary pages keep "absent means world", and trusted local readers see all.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { serializeMarkdown } from '../src/core/markdown.ts';+import { operationsByName } from '../src/core/operations.ts';+import { isPrivatePage, __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts';+import { authorizePageVisibility } from '../src/core/persistence/page-visibility.ts';+import type { WriteAuthority } from '../src/core/persistence/model.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';++const backends = testBackends();+const engines: BrainEngine[] = [];+let closePostgres: (() => Promise<void>) | undefined;++const pages = [+ ['atoms/transcript-origin', 'atom', 'quokka transcript atom body', { source_path: '/sessions/example.jsonl' }],+ ['atoms/private-origin', 'atom', 'quokka private page atom body', { source_slug: 'notes/private-origin' }],+ ['atoms/world-origin', 'atom', 'quokka world atom body', { source_slug: 'notes/world-origin', visibility: 'world' }],+ ['concepts/unstamped', 'concept', 'quokka synthesized concept body', { synthesized_by: 'synthesize_concepts-v0.41' }],+ ['concepts/stamped-world', 'concept', 'quokka stamped concept body', { synthesized_by: 'synthesize_concepts-v0.41', visibility: 'world' }],+ ['notes/ordinary-concept', 'concept', 'quokka ordinary concept body', {}],+ ['notes/ordinary-note', 'note', 'quokka ordinary note body', {}],+] as const;+const hidden = ['atoms/transcript-origin', 'atoms/private-origin', 'concepts/unstamped'];+const visible = ['atoms/world-origin', 'concepts/stamped-world', 'notes/ordinary-concept', 'notes/ordinary-note'];++beforeAll(async () => {+ if (backends.includes('pglite')) {+ const engine = new PGLiteEngine();+ await engine.connect({}); await engine.initSchema(); engines.push(engine);+ }+ if (backends.includes('postgres')) {+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);+ engines.push(pg.engine); closePostgres = pg.close;+ }+ for (const engine of engines) {+ for (const [slug, type, body, frontmatter] of pages) {+ const result = await importFromContent(engine, slug, serializeMarkdown(frontmatter, body, '', { type, title: slug, tags: [] }),+ { noEmbed: true, forceRechunk: true });+ expect(result.status).toBe('imported');+ }+ }+}, 120_000);++afterAll(async () => {+ for (const engine of engines) if (engine.kind === 'pglite') await engine.disconnect();+ await closePostgres?.();+});++const ctx = (engine: BrainEngine, remote: boolean) => ({ engine, config: { engine: engine.kind }, logger: { info() {}, warn() {}, error() {} },+ dryRun: false, remote, sourceId: 'default' }) as never;++describe('#5525 derived pages without visibility are private to remote readers', () => {+ test('row-side rule matches the SQL rule', () => {+ for (const [, type, , frontmatter] of pages) {+ const slug = pages.find(p => p[3] === frontmatter)![0];+ expect(isPrivatePage({ type, frontmatter })).toBe(hidden.includes(slug));+ }+ expect(isPrivatePage({ type: 'note', frontmatter: { visibility: 'private' } })).toBe(true);+ });++ test('remote list_pages omits unstamped atoms and concepts; local lists them', async () => {+ for (const engine of engines) {+ __resetPrivateVisibilityCacheForTests();+ const remote = ((await operationsByName.list_pages.handler(ctx(engine, true), { limit: 100 })) as Array<{ slug: string }>).map(r => r.slug);+ for (const slug of hidden) expect(remote).not.toContain(slug);+ for (const slug of visible) expect(remote).toContain(slug);+ const local = ((await operationsByName.list_pages.handler(ctx(engine, false), { limit: 100 })) as Array<{ slug: string }>).map(r => r.slug);+ for (const slug of [...hidden, ...visible]) expect(local).toContain(slug);+ }+ });++ test('remote get_page refuses unstamped atoms and concepts; local reads them', async () => {+ for (const engine of engines) {+ __resetPrivateVisibilityCacheForTests();+ for (const slug of hidden) {+ await expect(operationsByName.get_page.handler(ctx(engine, true), { slug })).rejects.toThrow(/Page not found/);+ expect(((await operationsByName.get_page.handler(ctx(engine, false), { slug })) as { slug: string }).slug).toBe(slug);+ }+ for (const slug of visible) expect(((await operationsByName.get_page.handler(ctx(engine, true), { slug })) as { slug: string }).slug).toBe(slug);+ }+ });++ test('remote search omits unstamped atoms and concepts; local finds them', async () => {+ for (const engine of engines) {+ __resetPrivateVisibilityCacheForTests();+ const slugs = async (remote: boolean) => ((await operationsByName.search.handler(ctx(engine, remote), { query: 'quokka', limit: 50 })) as+ Array<{ slug: string }>).map(r => r.slug);+ const remote = await slugs(true);+ for (const slug of hidden) expect(remote).not.toContain(slug);+ for (const slug of visible) expect(remote).toContain(slug);+ const local = await slugs(false);+ for (const slug of hidden) expect(local).toContain(slug);+ }+ });++ test('remote publication rechecks treat unstamped derived pages as private', async () => {+ for (const engine of engines) {+ const authority = { remote: true, sourceId: 'default', excludePrivate: true } as unknown as WriteAuthority;+ for (const slug of hidden) await expect(authorizePageVisibility(engine, authority, slug)).rejects.toMatchObject({ code: 'page_not_found' });+ for (const slug of visible) await authorizePageVisibility(engine, authority, slug);+ }+ });+});diff --git a/test/derived-visibility-repair.test.ts b/test/derived-visibility-repair.test.tsnew file mode 100644index 0000000000..5449e01b71--- /dev/null+++ b/test/derived-visibility-repair.test.ts@@ -0,0 +1,298 @@+/**+ * #5525 completion: extraction, synthesis and the tighten-only backfill stamp+ * explicit visibility on derived pages, and a later private flip of an origin+ * page reaches its atoms and concepts. Stubbed LLM; PGLite + Postgres.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { mkdtempSync, rmSync } 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 type { ChatOpts, ChatResult } from '../src/core/ai/gateway.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { serializeMarkdown } from '../src/core/markdown.ts';+import { operationsByName } from '../src/core/operations.ts';+import { runPhaseSynthesizeConcepts } from '../src/core/cycle/synthesize-concepts.ts';+import { runPhaseExtractAtoms } from '../src/core/cycle/extract-atoms.ts';+import { __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { resolveRepairScope, runRepair } from '../src/core/repair/core.ts';+import { visibilityRepair } from '../src/core/repair/visibility.ts';+import { derivedVisibilityCheck } from '../src/commands/doctor/checks/derived-visibility.ts';+import { runPhaseWithStoredPageFixtures } from './helpers/extract-atoms-page-fixtures.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { withEnv } from './helpers/with-env.ts';+import { testBackends } from './helpers/test-backends.ts';++const backends = testBackends();+const engines: BrainEngine[] = [];+let closePostgres: (() => Promise<void>) | undefined;+const home = mkdtempSync(join(tmpdir(), 'gbrain-derived-visibility-'));++beforeAll(async () => {+ if (backends.includes('pglite')) {+ const engine = new PGLiteEngine();+ await engine.connect({}); await engine.initSchema(); engines.push(engine);+ }+ if (backends.includes('postgres')) {+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);+ engines.push(pg.engine); closePostgres = pg.close;+ }+}, 120_000);++afterAll(async () => {+ for (const engine of engines) { await disposePersistenceConsumer(engine); if (engine.kind === 'pglite') await engine.disconnect(); }+ await closePostgres?.();+ rmSync(home, { recursive: true, force: true });+});++const ctx = (engine: BrainEngine, remote: boolean, sourceId = 'default') => ({ engine, config: { engine: engine.kind, embedding_disabled: true },+ logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote, sourceId }) as never;++async function remoteSees(engine: BrainEngine, slug: string): Promise<boolean> {+ __resetPrivateVisibilityCacheForTests();+ try { return ((await operationsByName.get_page.handler(ctx(engine, true), { slug })) as { slug: string }).slug === slug; }+ catch (error) { if (/Page not found/.test(String(error))) return false; throw error; }+}++async function seed(engine: BrainEngine, slug: string, type: string, frontmatter: Record<string, unknown>, body = `${slug} body text`) {+ const result = await importFromContent(engine, slug, serializeMarkdown(frontmatter, body, '', { type: type as never, title: slug, tags: [] }),+ { noEmbed: true, forceRechunk: true });+ expect(['imported', 'skipped']).toContain(result.status);+}++const visibilityOf = async (engine: BrainEngine, slug: string) =>+ (await engine.executeRaw<{ v: string | null }>("SELECT frontmatter->>'visibility' AS v FROM pages WHERE slug=$1 AND source_id='default'", [slug]))[0]?.v ?? null;++async function reset(engine: BrainEngine) {+ await engine.executeRaw("DELETE FROM links"); await engine.executeRaw("DELETE FROM content_chunks"); await engine.executeRaw("DELETE FROM pages");+ await engine.executeRaw("DELETE FROM op_checkpoints WHERE op='repair'");+}++const stubChat = async (o: ChatOpts): Promise<ChatResult> => {+ const label = String(o.messages[0]?.content ?? '').split('\n')[0].replace('Source: ', '').replace(/[^a-z0-9]+/gi, ' ').trim();+ return { text: JSON.stringify([{ title: `Insight from ${label}`, atom_type: 'insight', body: `Quokkaword insight distilled from ${label}.` }]),+ 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' };+};++describe('#5525 extraction stamps the origin visibility on every atom (non-managed path)', () => {+ test('private page and transcript atoms are private and hidden remotely; a world page yields a readable world atom', async () => {+ for (const engine of engines) {+ await reset(engine);+ await seed(engine, 'notes/private-origin', 'note', { visibility: 'private' }, 'A private planning record.');+ await seed(engine, 'notes/world-origin', 'note', {}, 'A public planning record.');+ const pageRow = async (slug: string) => (await engine.getPage(slug, { sourceId: 'default' }))!;+ const result = await runPhaseWithStoredPageFixtures(engine, {+ _pages: await Promise.all(['notes/private-origin', 'notes/world-origin'].map(async slug => {+ const p = await pageRow(slug); return { slug, content: p.compiled_truth, contentHash: p.content_hash! };+ })),+ _transcripts: [{ filePath: '/fake/private-session.txt', content: 'a private conversation', contentHash: 'abcdef0123456789' }],+ _chat: stubChat,+ });+ expect(result.details?.atoms_extracted).toBe(3);+ const atoms = await engine.executeRaw<{ slug: string; origin: string | null; transcript: string | null; v: string | null }>(+ "SELECT slug,frontmatter->>'source_slug' AS origin,frontmatter->>'source_path' AS transcript,frontmatter->>'visibility' AS v FROM pages WHERE type='atom' ORDER BY slug");+ const bySource = Object.fromEntries(atoms.map(a => [a.origin ?? a.transcript, a]));+ expect(bySource['notes/private-origin'].v).toBe('private');+ expect(bySource['/fake/private-session.txt'].v).toBe('private');+ expect(bySource['notes/world-origin'].v).toBe('world');+ expect(await remoteSees(engine, bySource['notes/private-origin'].slug)).toBe(false);+ expect(await remoteSees(engine, bySource['/fake/private-session.txt'].slug)).toBe(false);+ expect(await remoteSees(engine, bySource['notes/world-origin'].slug)).toBe(true);+ }+ }, 120_000);+});++describe('#5525 extraction stamps the origin visibility on every atom (managed path)', () => {+ test('a world page yields a world atom and a private page a private atom', async () => {+ for (const engine of engines) {+ await reset(engine);+ const dir = mkdtempSync(join(home, 'managed-'));+ try {+ await withEnv({ GBRAIN_HOME: dir }, async () => {+ await seed(engine, 'notes/managed-world', 'note', {}, 'A public project record. '.repeat(20));+ await seed(engine, 'notes/managed-private', 'note', { visibility: 'private' }, 'A private project record. '.repeat(20));+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const items = await Promise.all(['notes/managed-world', 'notes/managed-private'].map(async slug => {+ const p = (await engine.getPage(slug, { sourceId: 'default' }))!; return { slug, content: p.compiled_truth, contentHash: p.content_hash! };+ }));+ const result = await runPhaseExtractAtoms(engine, { _transcripts: [], _pages: items, _chat: stubChat });+ expect(result.details?.atoms_extracted).toBe(2);+ const atoms = await engine.executeRaw<{ origin: string; v: string }>(+ "SELECT frontmatter->>'source_slug' AS origin,frontmatter->>'visibility' AS v FROM pages WHERE type='atom' ORDER BY 1");+ expect(atoms).toEqual([{ origin: 'notes/managed-private', v: 'private' }, { origin: 'notes/managed-world', v: 'world' }]);+ });+ } finally {+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ }+ }+ }, 120_000);+});++describe('#5525 concepts take the strictest visibility of their inputs', () => {+ test('one private and one world input make a private concept; two world inputs a world concept; tighten-only on re-synthesis', async () => {+ for (const engine of engines) {+ await reset(engine);+ await seed(engine, 'atoms/a1', 'atom', { visibility: 'world', concepts: ['concepts/mixed', 'concepts/open'] });+ await seed(engine, 'atoms/a2', 'atom', { visibility: 'private', concepts: ['concepts/mixed'] });+ await seed(engine, 'atoms/a3', 'atom', { visibility: 'world', concepts: ['concepts/open', 'concepts/later'] });+ await seed(engine, 'atoms/a4', 'atom', { visibility: 'world', concepts: ['concepts/later'] });+ await runPhaseSynthesizeConcepts(engine, { _chat: stubChat as never, sourceId: 'default' });+ expect(await visibilityOf(engine, 'concepts/mixed')).toBe('private');+ expect(await visibilityOf(engine, 'concepts/open')).toBe('world');+ expect(await visibilityOf(engine, 'concepts/later')).toBe('world');+ expect(await remoteSees(engine, 'concepts/mixed')).toBe(false);+ expect(await remoteSees(engine, 'concepts/open')).toBe(true);+ // A re-synthesized concept that gains a private input becomes private ...+ await seed(engine, 'atoms/a5', 'atom', { visibility: 'private', concepts: ['concepts/later'] });+ await runPhaseSynthesizeConcepts(engine, { _chat: stubChat as never, sourceId: 'default' });+ expect(await visibilityOf(engine, 'concepts/later')).toBe('private');+ // ... and stays private when that input goes away (tighten-only).+ await engine.executeRaw("UPDATE pages SET deleted_at=now() WHERE slug='atoms/a5'");+ await runPhaseSynthesizeConcepts(engine, { _chat: stubChat as never, sourceId: 'default' });+ expect(await visibilityOf(engine, 'concepts/later')).toBe('private');+ }+ }, 120_000);+});++describe('#5525 backfill edge cases', () => {+ test('a concept whose members are known only from atoms\' concepts: lists is stamped private', async () => {+ for (const engine of engines) {+ await reset(engine);+ await seed(engine, 'notes/public', 'note', {});+ await seed(engine, 'atoms/m1', 'atom', { visibility: 'world', source_slug: 'notes/public', concepts: ['concepts/legacy'] });+ await seed(engine, 'concepts/legacy', 'concept', { synthesized_by: 'synthesize_concepts-v0.41' });+ await withEnv({ GBRAIN_HOME: home }, async () => {+ await runRepair(ctx(engine, false), visibilityRepair, await resolveRepairScope(engine), { apply: true });+ });+ expect(await visibilityOf(engine, 'concepts/legacy')).toBe('private');+ }+ }, 120_000);++ test('an item whose origin turned private after planning is not stamped with the stale decision', async () => {+ for (const engine of engines) {+ await reset(engine);+ await seed(engine, 'notes/flips', 'note', {});+ await seed(engine, 'atoms/flipping', 'atom', { source_slug: 'notes/flips' });+ await withEnv({ GBRAIN_HOME: home }, async () => {+ const scope = await resolveRepairScope(engine);+ const plan = await visibilityRepair.plan(engine, scope, null);+ expect(plan.items.map(i => i.change)).toEqual([{ from: null, to: 'world' }]);+ await seed(engine, 'notes/flips', 'note', { visibility: 'private' });+ expect(await visibilityRepair.apply(ctx(engine, false), plan.items[0])).toBe(false);+ expect(await visibilityOf(engine, 'atoms/flipping')).toBeNull();+ await runRepair(ctx(engine, false), visibilityRepair, scope, { apply: true });+ });+ expect(await visibilityOf(engine, 'atoms/flipping')).toBe('private');+ }+ }, 120_000);+});++describe('#5525 a concept whose provenance edges cannot land stays private', () => {+ test('world inputs that are not pages in this source leave the concept private', async () => {+ for (const engine of engines) {+ await reset(engine);+ await runPhaseSynthesizeConcepts(engine, { _chat: stubChat as never, sourceId: 'default', _atoms: [+ { slug: 'atoms/elsewhere-1', title: 'One', body: 'One.', concept_refs: ['concepts/unlinked'], visibility: 'world' },+ { slug: 'atoms/elsewhere-2', title: 'Two', body: 'Two.', concept_refs: ['concepts/unlinked'], visibility: 'world' },+ ] });+ expect(await visibilityOf(engine, 'concepts/unlinked')).toBe('private');+ }+ }, 120_000);+});++describe('#5525 a concept made private while its narrative is generated stays private', () => {+ test('the tighten-only check reads the concept after the model call', async () => {+ for (const engine of engines) {+ await reset(engine);+ await seed(engine, 'notes/origin', 'note', {});+ const synthesized = { synthesized_by: 'synthesize_concepts-v0.41' };+ await seed(engine, 'concepts/race', 'concept', { ...synthesized, visibility: 'world' }, 'An earlier narrative.');+ for (let i = 1; i <= 5; i++) await seed(engine, `atoms/race-${i}`, 'atom', { visibility: 'world', source_slug: 'notes/origin', concepts: ['concepts/race'] }, `Race atom ${i}.`);+ let calls = 0;+ const flippingChat = async (o: ChatOpts): Promise<ChatResult> => {+ calls++;+ await seed(engine, 'concepts/race', 'concept', { ...synthesized, visibility: 'private' }, 'An earlier narrative.');+ return { ...(await stubChat(o)), text: 'The race atoms describe one recurring insight about planning under uncertainty.' };+ };+ await runPhaseSynthesizeConcepts(engine, { _chat: flippingChat as never, sourceId: 'default' });+ expect(calls).toBeGreaterThan(0);+ expect(await visibilityOf(engine, 'concepts/race')).toBe('private');+ }+ }, 120_000);+});++describe('#5525 a later private flip of an origin page reaches derived atoms and concepts', () => {+ test('flipping the origin hides its world atom and the concept built from it; the backfill then stamps them', async () => {+ for (const engine of engines) {+ await reset(engine);+ await seed(engine, 'notes/origin', 'note', {});+ await seed(engine, 'atoms/from-origin', 'atom', { visibility: 'world', source_slug: 'notes/origin', concepts: ['concepts/flip'] });+ await seed(engine, 'atoms/other', 'atom', { visibility: 'world', source_slug: 'notes/other', concepts: ['concepts/flip'] });+ await seed(engine, 'notes/other', 'note', {});+ await runPhaseSynthesizeConcepts(engine, { _chat: stubChat as never, sourceId: 'default' });+ expect(await visibilityOf(engine, 'concepts/flip')).toBe('world');+ expect(await remoteSees(engine, 'atoms/from-origin')).toBe(true);+ expect(await remoteSees(engine, 'concepts/flip')).toBe(true);+ await seed(engine, 'notes/origin', 'note', { visibility: 'private' });+ expect(await remoteSees(engine, 'atoms/from-origin')).toBe(false);+ expect(await remoteSees(engine, 'concepts/flip')).toBe(false);+ expect(await remoteSees(engine, 'atoms/other')).toBe(true);+ const doctor = await derivedVisibilityCheck(engine);+ expect(doctor.status).toBe('warn');+ expect(doctor.details).toMatchObject({ looser_atoms: 1, count: 'exact' });+ await withEnv({ GBRAIN_HOME: home }, async () => {+ const scope = await resolveRepairScope(engine);+ const applied = await runRepair(ctx(engine, false), visibilityRepair, scope, { apply: true });+ expect(applied.applied).toBe(2);+ });+ expect(await visibilityOf(engine, 'atoms/from-origin')).toBe('private');+ expect(await visibilityOf(engine, 'concepts/flip')).toBe('private');+ expect(await visibilityOf(engine, 'atoms/other')).toBe('world');+ }+ }, 120_000);+});++describe('#5525 tighten-only visibility backfill', () => {+ test('stamps, tightens and reports; never loosens; a second run changes nothing', async () => {+ for (const engine of engines) {+ await reset(engine);+ await seed(engine, 'notes/world', 'note', {});+ await seed(engine, 'notes/private', 'note', { visibility: 'private' });+ await seed(engine, 'atoms/unstamped-world', 'atom', { source_slug: 'notes/world' });+ await seed(engine, 'atoms/leaked-transcript', 'atom', { visibility: 'world', source_path: '/sessions/example.jsonl' });+ await seed(engine, 'atoms/leaked-gone-origin', 'atom', { visibility: 'world', source_slug: 'notes/deleted-origin' });+ await seed(engine, 'atoms/over-private', 'atom', { visibility: 'private', source_slug: 'notes/world', managed_extraction: true });+ await seed(engine, 'atoms/unstamped-private', 'atom', { source_slug: 'notes/private' });+ await seed(engine, 'concepts/orphan', 'concept', { synthesized_by: 'synthesize_concepts-v0.41', visibility: 'world' });+ expect(await remoteSees(engine, 'atoms/leaked-transcript')).toBe(true);+ expect(await remoteSees(engine, 'atoms/leaked-gone-origin')).toBe(true);+ expect(await remoteSees(engine, 'atoms/unstamped-world')).toBe(false);+ expect((await derivedVisibilityCheck(engine)).details).toMatchObject({ unstamped_atoms: 2, looser_atoms: 2, count: 'exact' });+ await withEnv({ GBRAIN_HOME: home }, async () => {+ const scope = await resolveRepairScope(engine);+ const preview = await runRepair(ctx(engine, false), visibilityRepair, scope, { apply: false });+ expect(preview.affected).toBe(4);+ expect(preview.residuals).toEqual({ atoms_origin_gone_to_private: 1, concepts_without_lineage: 1 });+ expect(await visibilityOf(engine, 'atoms/unstamped-world')).toBeNull();+ const applied = await runRepair(ctx(engine, false), visibilityRepair, scope, { apply: true });+ expect(applied).toMatchObject({ applied: 4, complete: true });+ const again = await runRepair(ctx(engine, false), visibilityRepair, scope, { apply: true });+ expect(again).toMatchObject({ affected: 0, applied: 0, complete: true });+ });+ expect(await visibilityOf(engine, 'atoms/unstamped-world')).toBe('world');+ expect(await visibilityOf(engine, 'atoms/leaked-transcript')).toBe('private');+ expect(await visibilityOf(engine, 'atoms/leaked-gone-origin')).toBe('private');+ expect(await visibilityOf(engine, 'atoms/over-private')).toBe('private');+ expect(await visibilityOf(engine, 'atoms/unstamped-private')).toBe('private');+ expect(await visibilityOf(engine, 'concepts/orphan')).toBe('world');+ expect(await remoteSees(engine, 'atoms/leaked-transcript')).toBe(false);+ expect(await remoteSees(engine, 'atoms/leaked-gone-origin')).toBe(false);+ expect(await remoteSees(engine, 'atoms/unstamped-world')).toBe(true);+ expect((await derivedVisibilityCheck(engine)).status).toBe('ok');+ }+ }, 120_000);+});diff --git a/test/dream-breaker.test.ts b/test/dream-breaker.test.tsnew file mode 100644index 0000000000..c453007c51--- /dev/null+++ b/test/dream-breaker.test.ts@@ -0,0 +1,196 @@+/**+ * Dream paid-loop breaker: released-key recording, the shared dead-submission+ * counter, persisted resets, the fail-open posture, and the #5590 boundary+ * (a legitimate zero-write completion never counts; a real zero-write+ * failure still dead-letters and does).+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { MinionQueue } from '../src/core/minions/queue.ts';+import { UnrecoverableError } from '../src/core/minions/types.ts';+import { finalizeWriteAccounting } from '../src/core/minions/handlers/subagent-persistence.ts';+import {+ countDeadDreamSubmissions, dreamBreakerRefusal, loadDreamBreaker, resetDreamBreakerKey, DREAM_BREAKER_CONFIG_KEY,+} from '../src/core/cycle/dream-breaker.ts';+import { dreamPaidLoopCheck } from '../src/commands/doctor/checks/dream-breaker.ts';++let engine: PGLiteEngine;+let schemaVersion: string;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ schemaVersion = (await engine.getConfig('version')) ?? '7';+}, 60_000);++afterAll(async () => {+ await engine.disconnect();+});++beforeEach(async () => {+ await resetPgliteState(engine);+ await engine.setConfig('version', schemaVersion);+});++const KEY = 'dream:synth-v2:default:filename:loop.txt:0123456789abcdef';++async function seedJob(opts: { key: string; status: string; queue: string; hoursAgo?: number; released?: boolean }, target: PGLiteEngine = engine): Promise<void> {+ await target.executeRaw(+ `INSERT INTO minion_jobs (submission_authority, name, queue, status, data, idempotency_key, created_at, finished_at)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'subagent', $1, $2, $3::text::jsonb, $4,+ now() - ($5 || ' hours')::interval, now() - ($5 || ' hours')::interval)`,+ [opts.queue, opts.status, JSON.stringify(opts.released ? { source_id: 'default', __released_idempotency_key: opts.key } : { source_id: 'default' }),+ opts.released ? null : opts.key, String(opts.hoursAgo ?? 1)],+ );+}++describe('queue key release', () => {+ test('re-submitting a dead key records the released key in the dead row', async () => {+ const queue = new MinionQueue(engine);+ const first = await queue.add('breaker-probe', { n: 1 }, { idempotency_key: KEY });+ await engine.executeRaw(`UPDATE minion_jobs SET status='dead', finished_at=now() WHERE id=$1`, [first.id]);+ const second = await queue.add('breaker-probe', { n: 2 }, { idempotency_key: KEY });+ expect(second.id).not.toBe(first.id);+ const [dead] = await engine.executeRaw<{ idempotency_key: string | null; released: string | null; n: string }>(+ `SELECT idempotency_key, data->>'__released_idempotency_key' AS released, data->>'n' AS n FROM minion_jobs WHERE id=$1`, [first.id]);+ expect(dead).toEqual({ idempotency_key: null, released: KEY, n: '1' });+ });+});++describe('dead-submission counter', () => {+ test('counts distinct runs by finish time, live or released keys, chunks of one run once', async () => {+ await seedJob({ key: `${KEY}:c0of2`, status: 'dead', queue: 'dream-inline-1' });+ await seedJob({ key: `${KEY}:c1of2`, status: 'dead', queue: 'dream-inline-1', released: true });+ await seedJob({ key: KEY, status: 'dead', queue: 'dream-inline-2', released: true });+ await seedJob({ key: KEY, status: 'dead', queue: 'dream-inline-3', hoursAgo: 30, released: true });+ await seedJob({ key: 'unrelated:key', status: 'dead', queue: 'dream-inline-4' });+ expect(await countDeadDreamSubmissions(engine)).toEqual([+ expect.objectContaining({ base_key: KEY, dead_submissions: 2 }),+ ]);+ });++ test('the third dead submission trips the key; completed zero-write jobs never count', async () => {+ for (const [i, queue] of ['q1', 'q2', 'q3'].entries()) await seedJob({ key: `${KEY}:c${i}of3`, status: 'completed', queue });+ expect((await loadDreamBreaker(engine))!.tripped.size).toBe(0);+ for (const queue of ['d1', 'd2']) await seedJob({ key: KEY, status: 'dead', queue, released: true });+ const breaker = (await loadDreamBreaker(engine))!;+ expect(dreamBreakerRefusal(breaker, KEY)).toBeNull();+ await seedJob({ key: KEY, status: 'dead', queue: 'd3', released: true });+ const tripped = (await loadDreamBreaker(engine))!;+ expect(dreamBreakerRefusal(tripped, KEY)).toContain(`gbrain dream reset-key '${KEY}'`);+ });++ test('the threshold is configurable and 0 disables the breaker', async () => {+ for (const queue of ['d1', 'd2']) await seedJob({ key: KEY, status: 'dead', queue, released: true });+ await engine.setConfig(DREAM_BREAKER_CONFIG_KEY, '2');+ expect((await loadDreamBreaker(engine))!.tripped.get(KEY)).toBe(2);+ await engine.setConfig(DREAM_BREAKER_CONFIG_KEY, '0');+ expect(await loadDreamBreaker(engine)).toBeNull();+ });++ test('concurrent resets of different keys both persist', async () => {+ const other = KEY.replace('loop.txt', 'other.txt');+ for (const key of [KEY, other]) {+ await seedJob({ key, status: 'dead', queue: 'd1' });+ for (const queue of ['d2', 'd3']) await seedJob({ key, status: 'dead', queue, released: true });+ }+ expect((await loadDreamBreaker(engine))!.tripped.size).toBe(2);+ await Promise.all([resetDreamBreakerKey(engine, KEY), resetDreamBreakerKey(engine, other)]);+ expect(Object.keys(JSON.parse((await engine.getConfig('dream.breaker.resets'))!)).sort()).toEqual([KEY, other].sort());+ expect((await loadDreamBreaker(engine))!.tripped.size).toBe(0);+ });++ test('a failing count query leaves the breaker off for the run', async () => {+ const broken = new Proxy(engine, { get(target, key) {+ if (key === 'executeRaw') return async () => { throw new Error('pool reaped'); };+ const value = Reflect.get(target, key);+ return typeof value === 'function' ? value.bind(target) : value;+ } });+ expect(await loadDreamBreaker(broken)).toBeNull();+ });+});++describe('#5590 boundary', () => {+ test('a real zero-write failure still dead-letters, and that death counts', async () => {+ const proseOnly = { result: 'I will write the page next.', turns_count: 1, stop_reason: 'end_turn' as const,+ tokens: { in: 1, out: 1, cache_read: 0, cache_create: 0 } };+ const failure = await finalizeWriteAccounting(engine, 999_999, proseOnly, { requireWrites: true }).catch(error => error);+ expect(failure).toBeInstanceOf(UnrecoverableError);+ for (const queue of ['d1', 'd2', 'd3']) await seedJob({ key: KEY, status: 'dead', queue, released: true });+ expect((await loadDreamBreaker(engine))!.tripped.get(KEY)).toBe(3);+ });+});++describe('doctor dream_paid_loop', () => {+ test('warns with the base key, prefix and reset command; ok when clean', async () => {+ expect((await dreamPaidLoopCheck(engine)).status).toBe('ok');+ await seedJob({ key: KEY, status: 'dead', queue: 'd1' });+ for (const queue of ['d2', 'd3']) await seedJob({ key: KEY, status: 'dead', queue, released: true });+ const check = await dreamPaidLoopCheck(engine);+ expect(check.status).toBe('warn');+ expect(check.message).toContain(KEY);+ expect(check.message).toContain('gbrain dream reset-key');+ expect((check.details!.keys as Array<{ key_prefix: string }>)[0]!.key_prefix).toBe('dream:synth-v2:');+ });+});++describe('gbrain dream reset-key', () => {+ async function captured(run: () => Promise<void>): Promise<string> {+ const lines: string[] = [];+ const log = console.log;+ console.log = (...args: unknown[]) => { lines.push(args.join(' ')); };+ try { await run(); } finally { console.log = log; }+ return lines.join('\n');+ }++ test('--list shows tripped keys and a reset clears them', async () => {+ const { runDreamResetKey } = await import('../src/commands/dream-reset-key.ts');+ await seedJob({ key: KEY, status: 'dead', queue: 'd1' });+ for (const queue of ['d2', 'd3']) await seedJob({ key: KEY, status: 'dead', queue, released: true });+ const listed = JSON.parse(await captured(() => runDreamResetKey(engine, ['--list', '--json'])));+ expect(listed.tripped).toEqual([expect.objectContaining({ base_key: KEY, dead_submissions: 3 })]);+ expect(await captured(() => runDreamResetKey(engine, [KEY]))).toContain(`Reset ${KEY}`);+ expect(await captured(() => runDreamResetKey(engine, ['--list']))).toContain('No tripped dream keys');+ });++ test('the dead-submission index exists after schema init', async () => {+ const rows = await engine.executeRaw(`SELECT indexname FROM pg_indexes WHERE indexname = 'idx_minion_jobs_dead_subagent_finished'`);+ expect(rows).toHaveLength(1);+ });+});++describe('breaker reset persistence', () => {+ let dir: string;+ let reopened: PGLiteEngine;+ let trippedBeforeReset = 0;+ beforeAll(async () => {+ dir = mkdtempSync(join(tmpdir(), 'gbrain-dream-breaker-'));+ const path = join(dir, 'brain.pglite');+ const first = new PGLiteEngine();+ await first.connect({ engine: 'pglite', database_path: path } as never);+ await first.initSchema();+ for (const queue of ['d1', 'd2', 'd3']) await seedJob({ key: KEY, status: 'dead', queue, hoursAgo: 2, released: true }, first);+ trippedBeforeReset = (await loadDreamBreaker(first))!.tripped.get(KEY) ?? 0;+ await resetDreamBreakerKey(first, `${KEY}:c0of3`);+ await first.disconnect();+ reopened = new PGLiteEngine();+ await reopened.connect({ engine: 'pglite', database_path: path } as never);+ }, 120_000);+ afterAll(async () => {+ await reopened.disconnect();+ rmSync(dir, { recursive: true, force: true });+ });++ test('a reset survives a restart and later deaths count again', async () => {+ expect(trippedBeforeReset).toBe(3);+ expect((await loadDreamBreaker(reopened))!.tripped.size).toBe(0);+ for (const queue of ['d4', 'd5', 'd6']) await seedJob({ key: KEY, status: 'dead', queue, hoursAgo: 0, released: true }, reopened);+ await reopened.executeRaw(`UPDATE minion_jobs SET finished_at = now() + interval '1 second' WHERE queue IN ('d4','d5','d6')`);+ expect((await loadDreamBreaker(reopened))!.tripped.get(KEY)).toBe(3);+ });+});diff --git a/test/e2e/canonical-projection-history.test.ts b/test/e2e/canonical-projection-history.test.tsnew file mode 100644index 0000000000..29cb292c3e--- /dev/null+++ b/test/e2e/canonical-projection-history.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../canonical-projection-history.test.ts'));diff --git a/test/e2e/derived-page-visibility.test.ts b/test/e2e/derived-page-visibility.test.tsnew file mode 100644index 0000000000..888eccf3ab--- /dev/null+++ b/test/e2e/derived-page-visibility.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../derived-page-visibility.test.ts'));diff --git a/test/e2e/derived-visibility-repair.test.ts b/test/e2e/derived-visibility-repair.test.tsnew file mode 100644index 0000000000..7f8ec1eb7f--- /dev/null+++ b/test/e2e/derived-visibility-repair.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../derived-visibility-repair.test.ts'));diff --git a/test/e2e/dream-breaker-postgres.test.ts b/test/e2e/dream-breaker-postgres.test.tsnew file mode 100644index 0000000000..a7031bf1c1--- /dev/null+++ b/test/e2e/dream-breaker-postgres.test.ts@@ -0,0 +1,46 @@+/**+ * Dream paid-loop breaker on Postgres: the released key lands as a real jsonb+ * member through postgres.js (not a double-encoded string scalar), the shared+ * counter trips on it, and migration 173's partial index is valid.+ */+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { hasDatabase, setupDB, teardownDB, getEngine } from './helpers.ts';+import { MinionQueue } from '../../src/core/minions/queue.ts';+import { loadDreamBreaker, resetDreamBreakerKey } from '../../src/core/cycle/dream-breaker.ts';++const describePg = hasDatabase() ? describe : describe.skip;+const KEY = 'dream:synth-v2:default:filename:pg-loop.txt:0123456789abcdef';++describePg('dream paid-loop breaker — Postgres', () => {+ beforeAll(async () => { await setupDB(); }, 90_000);+ afterAll(async () => { await teardownDB(); }, 30_000);++ test('released keys are recorded as jsonb members and three dead runs trip the key', async () => {+ const engine = getEngine();+ await engine.executeRaw(`DELETE FROM minion_jobs WHERE name = 'breaker-probe'`);+ await engine.setConfig('dream.breaker.resets', '{}');+ const queue = new MinionQueue(engine);+ for (let run = 0; run < 3; run++) {+ const job = await queue.add('breaker-probe', { run }, { idempotency_key: KEY, queue: `dream-inline-pg-${run}` });+ await engine.executeRaw(`UPDATE minion_jobs SET status = 'dead', finished_at = now(), name = 'subagent' WHERE id = $1`, [job.id]);+ }+ await queue.add('breaker-probe', { run: 3 }, { idempotency_key: KEY });+ const released = await engine.executeRaw<{ kind: string; key: string }>(+ `SELECT jsonb_typeof(data) AS kind, data->>'__released_idempotency_key' AS key+ FROM minion_jobs WHERE status = 'dead' AND idempotency_key IS NULL AND data->>'__released_idempotency_key' = $1`, [KEY]);+ expect(released).toHaveLength(3);+ expect(released.every(row => row.kind === 'object' && row.key === KEY)).toBe(true);+ expect((await loadDreamBreaker(engine))!.tripped.get(KEY)).toBe(3);+ await resetDreamBreakerKey(engine, KEY);+ expect((await loadDreamBreaker(engine))!.tripped.has(KEY)).toBe(false);+ });++ test('migration 173 leaves a valid partial index on dead subagent finish times', async () => {+ const rows = await getEngine().executeRaw<{ valid: boolean; def: string }>(+ `SELECT i.indisvalid AS valid, pg_get_indexdef(i.indexrelid) AS def FROM pg_index i+ WHERE i.indexrelid = to_regclass('idx_minion_jobs_dead_subagent_finished')`);+ expect(rows).toHaveLength(1);+ expect(rows[0]!.valid).toBe(true);+ expect(rows[0]!.def).toContain("status = 'dead'");+ });+});diff --git a/test/e2e/dream-synthesize-pglite.test.ts b/test/e2e/dream-synthesize-pglite.test.tsindex 66e21da6b0..114fa23224 100644--- a/test/e2e/dream-synthesize-pglite.test.ts+++ b/test/e2e/dream-synthesize-pglite.test.ts@@ -527,6 +527,80 @@ describe('E2E synthesize — round-trip self-consumption guard (v0.23.2)', () =>}, 30_000);});+describe('E2E synthesize — internal inputs never re-enter discovery (#5413, #5471)', () => {+ test('a corpus file captured from a claude-cli scratch session is not discovered; an ordinary session is (#5413)', async () => {+ const rig = await setupRig();+ const claudeHome = mkdtempSync(join(tmpdir(), 'gbrain-synth-claude-'));+ const savedClaude = process.env.CLAUDE_CONFIG_DIR;+ process.env.CLAUDE_CONFIG_DIR = claudeHome;+ try {+ await rig.engine.setConfig('dream.synthesize.enabled', 'true');+ await rig.engine.setConfig('dream.synthesize.session_corpus_dir', rig.corpusDir);+ const selfId = '11111111-2222-4333-8444-555555555555';+ const userId = '66666666-7777-4888-9999-000000000000';+ const { mkdirSync } = require('node:fs') as typeof import('node:fs');+ mkdirSync(join(claudeHome, 'projects', '-tmp-gbrain-claude-cli-cwd-4242'), { recursive: true });+ mkdirSync(join(claudeHome, 'projects', '-home-user-app'), { recursive: true });+ writeFileSync(join(claudeHome, 'projects', '-tmp-gbrain-claude-cli-cwd-4242', `${selfId}.jsonl`), '{"type":"user"}\n');+ writeFileSync(join(claudeHome, 'projects', '-home-user-app', `${userId}.jsonl`), '{"type":"user"}\n');+ writeFileSync(join(rig.corpusDir, `${selfId}.txt`), 'User: <turn>extract facts from this page</turn>\n'.repeat(80));+ writeFileSync(join(rig.corpusDir, `${selfId}.seg-aaaaaaaaaaaa.txt`), 'User: <turn>extract facts from this segment</turn>\n'.repeat(80));+ writeFileSync(join(rig.corpusDir, `${userId}.txt`), 'User: an ordinary conversation about widgets\n'.repeat(80));++ await withoutAnthropicKey(async () => {+ const result = await runPhaseSynthesize(rig.engine, { brainDir: rig.brainDir, dryRun: false });+ expect(result.status).toBe('ok');+ const verdicts = (result.details as { verdicts: Array<{ filePath: string }> }).verdicts;+ expect(verdicts.map(v => v.filePath)).toEqual([join(rig.corpusDir, `${userId}.txt`)]);+ });+ } finally {+ if (savedClaude === undefined) delete process.env.CLAUDE_CONFIG_DIR;+ else process.env.CLAUDE_CONFIG_DIR = savedClaude;+ rmSync(claudeHome, { recursive: true, force: true });+ await rig.cleanup();+ }+ }, 30_000);++ test('unmarked dream outputs under the brain tree are not discovered; a transcript naming their paths is (#5471)', async () => {+ const rig = await setupRig();+ try {+ await rig.engine.setConfig('dream.synthesize.enabled', 'true');+ await rig.engine.setConfig('dream.synthesize.session_corpus_dir', rig.brainDir);+ await rig.engine.setConfig('dream.patterns.output_slug_prefix', 'notes/patterns');+ const { mkdirSync, symlinkSync } = require('node:fs') as typeof import('node:fs');+ const unmarked = (title: string) =>+ `---\ntitle: ${title}\ntype: note\n---\n\n` + `A synthesized paragraph about ${title}. `.repeat(80);+ const outputs = [+ 'wiki/personal/reflections/2026-09-01-widget-thinking-abc123.md',+ 'wiki/originals/ideas/2026-09-01-widget-scaling-abc123.md',+ 'notes/patterns/widget-pattern.md',+ 'dream-cycle-summaries/2026-09-01.md',+ ];+ for (const rel of outputs) {+ mkdirSync(join(rig.brainDir, rel, '..'), { recursive: true });+ writeFileSync(join(rig.brainDir, rel), unmarked(rel));+ }+ mkdirSync(join(rig.brainDir, 'transcripts'), { recursive: true });+ const convo = join(rig.brainDir, 'transcripts', '2026-09-01-convo.txt');+ writeFileSync(convo,+ 'User: compare wiki/personal/reflections/2026-09-01-widget-thinking-abc123.md with notes/patterns/widget-pattern.md\n' ++ 'Agent: ' + 'meaningful conversation '.repeat(200));+ // A second corpus root reaching the same outputs through a symlink.+ symlinkSync(join(rig.brainDir, 'wiki'), join(rig.corpusDir, 'linked-wiki'));+ await rig.engine.setConfig('dream.synthesize.meeting_transcripts_dir', rig.corpusDir);++ await withoutAnthropicKey(async () => {+ const result = await runPhaseSynthesize(rig.engine, { brainDir: rig.brainDir, dryRun: false });+ expect(result.status).toBe('ok');+ const verdicts = (result.details as { verdicts: Array<{ filePath: string }> }).verdicts;+ expect(verdicts.map(v => v.filePath)).toEqual([convo]);+ });+ } finally {+ await rig.cleanup();+ }+ }, 30_000);+});+describe('E2E synthesize — verdict cache (Q-2)', () => {test('subsequent run with same content reads from dream_verdicts cache', async () => {// Two synth runs through the verdict-cache path; default 5s is tight.@@ -1069,6 +1143,57 @@ describe('E2E synthesize — oneshot mode (#4216, DEFAULT)', () => {}}, 60_000);+ test('explicit skip: the child completes, keeps its key, and the cooldown stamps so the next cycle does not re-bill (#5590)', async () => {+ const rig = await setupRig();+ const savedKey = process.env.ANTHROPIC_API_KEY;+ process.env.ANTHROPIC_API_KEY = 'sk-test-oneshot-e2e';+ try {+ await rig.engine.setConfig('dream.synthesize.enabled', 'true');+ await rig.engine.setConfig('dream.synthesize.session_corpus_dir', rig.corpusDir);+ const content = 'User: a verbatim paste of an existing page\n'.repeat(120);+ const filePath = join(rig.corpusDir, '2026-08-16-paste.txt');+ writeFileSync(filePath, content);+ await seedVerdictFor(rig, filePath, content);++ let oneshotCalls = 0;+ __setChatTransportForTests(async () => {+ oneshotCalls++;+ const text = JSON.stringify({ pages: [], skipped: true, skip_reason: 'already captured' });+ return {+ text,+ blocks: [{ type: 'text', text }],+ stopReason: 'end',+ usage: { input_tokens: 2000, output_tokens: 40, cache_read_tokens: 0, cache_creation_tokens: 0 },+ model: 'anthropic:claude-sonnet-4-6',+ providerId: 'anthropic',+ } as any;+ });++ const result = await runPhaseSynthesize(rig.engine, { brainDir: rig.brainDir, dryRun: false });+ expect(result.status).toBe('ok');+ expect(oneshotCalls).toBe(1);+ const synthesis = (result.details as { synthesis: Record<string, unknown> }).synthesis;+ expect(synthesis.dead_jobs).toBe(0);++ const jobs = await rig.engine.executeRaw<{ status: string; idempotency_key: string | null }>(+ `SELECT status, idempotency_key FROM minion_jobs WHERE name = 'subagent'`);+ expect(jobs).toHaveLength(1);+ expect(jobs[0]!.status).toBe('completed');+ expect(jobs[0]!.idempotency_key).not.toBeNull();+ expect(await rig.engine.getConfig('dream.synthesize.last_completion_ts')).not.toBeNull();++ const again = await runPhaseSynthesize(rig.engine, { brainDir: rig.brainDir, dryRun: false });+ expect(again.status).toBe('skipped');+ expect(oneshotCalls).toBe(1);+ } finally {+ if (savedKey === undefined) delete process.env.ANTHROPIC_API_KEY;+ else process.env.ANTHROPIC_API_KEY = savedKey;+ __setChatTransportForTests(null);+ resetGateway();+ await rig.cleanup();+ }+ }, 60_000);+test('invalid output: same job falls back to the (gateway) agentic loop and completes', async () => {const rig = await setupRig();const savedKey = process.env.ANTHROPIC_API_KEY;diff --git a/test/e2e/grandfather-projection-postgres.test.ts b/test/e2e/grandfather-projection-postgres.test.tsindex 77b714dac4..4d8048ed16 100644--- a/test/e2e/grandfather-projection-postgres.test.ts+++ b/test/e2e/grandfather-projection-postgres.test.ts@@ -6,7 +6,7 @@ import { hasDatabase } from './helpers.ts';import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';import { installFixtureChunks } from '../helpers/page-projection.ts';import { withEnv } from '../helpers/with-env.ts';-import { phaseCGrandfather } from '../../src/commands/migrations/v0_13_1.ts';+import { phaseCGrandfather, phaseDVerify } from '../../src/commands/migrations/v0_13_1.ts';import type { BrainEngine } from '../../src/core/engine.ts';function afterTransactionQuery(engine: BrainEngine, after: (tx: BrainEngine, query: string) => Promise<void>): BrainEngine {@@ -86,6 +86,32 @@ describe.skipIf(!hasDatabase())('Postgres grandfather migration projection publi}}, 60_000);+ test('verify keys on the revision each write produced, including a batch of unrecorded revisions', async () => {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-grandfather-verify-pg-'));+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);+ const engine = pg.engine;+ try {+ await sealedPage(engine, 'concepts/kept', 'Kept fixture.');+ await sealedPage(engine, 'concepts/reimported', 'Reimported fixture.');+ await withEnv({ GBRAIN_HOME: home }, async () => {+ const { detail } = await phaseCGrandfather(engine, { yes: true, dryRun: false, noAutopilotInstall: true });+ expect(await phaseDVerify(engine, detail.grandfathered)).toMatchObject({ status: 'complete', detail: 'verified=2 rewritten_concurrently=0' });+ // A connector re-import replaces the page and drops the flag.+ await sealedPage(engine, 'concepts/reimported', 'Reimported again.');+ expect(await phaseDVerify(engine, detail.grandfathered)).toMatchObject({ status: 'complete', detail: 'verified=1 rewritten_concurrently=1' });+ await sealedPage(engine, 'concepts/unwritten', 'Never grandfathered.');+ const kept = (await engine.getPage('concepts/kept', { sourceId: 'default' }))!;+ const unwritten = (await engine.getPage('concepts/unwritten', { sourceId: 'default' }))!;+ // A receipt without a revision cannot prove a rewrite, so the flag must be present.+ expect(await phaseDVerify(engine, [{ id: kept.id, revision: null }, { id: unwritten.id, revision: null }])).toMatchObject({+ status: 'failed', detail: `verified=1 rewritten_concurrently=0 missing_validate=1 (page#${unwritten.id})` });+ });+ } finally {+ await pg.close();+ rmSync(home, { recursive: true, force: true });+ }+ }, 60_000);+test('waits for a canonical page guard and preserves the competing writer validation decision', async () => {const home = mkdtempSync(join(tmpdir(), 'gbrain-grandfather-writer-pg-'));const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);diff --git a/test/e2e/knowledge-source-uri-postgres.test.ts b/test/e2e/knowledge-source-uri-postgres.test.tsnew file mode 100644index 0000000000..36421acdb0--- /dev/null+++ b/test/e2e/knowledge-source-uri-postgres.test.ts@@ -0,0 +1,26 @@+import { expect, test } from 'bun:test';+import { join } from 'node:path';+import { requirePostgresTestDatabase } from '../helpers/test-backends.ts';++requirePostgresTestDatabase();++test('invalid source URI diagnostics survive managed publication on Postgres', async () => {+ const child = Bun.spawn([process.execPath, 'test', 'test/shared-skills-writer-boundary.serial.test.ts',+ '--test-name-pattern', 'unresolvable stored file aliases'], {+ cwd: join(import.meta.dir, '../..'),+ env: { ...process.env, GBRAIN_TEST_ALLOW_DATABASE_URL: '1', GBRAIN_TEST_BACKEND: 'postgres' },+ stdout: 'pipe', stderr: 'pipe',+ });+ const timer = setTimeout(() => child.kill('SIGKILL'), 120_000);+ try {+ const [stdout, stderr, code] = await Promise.all([+ new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited,+ ]);+ expect({ code, stdout, stderr }).toMatchObject({ code: 0 });+ expect(stderr).toContain('1 pass');+ expect(stderr).toContain('0 fail');+ } finally {+ clearTimeout(timer);+ if (child.exitCode === null) { child.kill('SIGKILL'); await child.exited; }+ }+}, 140_000);diff --git a/test/e2e/persistence-idle-pool.test.ts b/test/e2e/persistence-idle-pool.test.tsnew file mode 100644index 0000000000..694b633765--- /dev/null+++ b/test/e2e/persistence-idle-pool.test.ts@@ -0,0 +1,141 @@+/**+ * #5370: an idle resident consumer must let its Postgres pool drain. Idle+ * probes share one reserved connection, every other pooled connection closes+ * through the engine's 20 s idle_timeout, and no LISTEN is involved, so the+ * transaction-mode PgBouncer path behaves the same as a direct server.+ */+import { describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { existsSync, mkdtempSync, readFileSync, readdirSync, readlinkSync, rmSync } from 'node:fs';+import { lookup } from 'node:dns/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import postgres from '#postgres'+import { PostgresEngine } from '../../src/core/postgres-engine.ts';+import { PersistenceConsumer } from '../../src/core/persistence/consumer.ts';+import { admitWrite, getWriteRequestById } from '../../src/core/persistence/journal.ts';+import { admission, fixtures, initializeFixtures, prepared, selectFixtureHost, type HarnessConfig } from '../../scripts/persistence/harness.ts';+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';+import { withEnv } from '../helpers/with-env.ts';+import { waitFor } from '../helpers/wait-for.ts';++const direct = process.env.DATABASE_URL;+const pooled = process.env.GBRAIN_PGBOUNCER_URL;+const pooledAdmin = process.env.GBRAIN_PGBOUNCER_DIRECT_URL;+if (process.env.GBRAIN_CI_REQUIRE_PGBOUNCER === '1' && !(pooled && pooledAdmin)) throw new Error('Idle pool drain requires the configured CI PgBouncer fixture.');+const IDLE_DRAIN_MS = 28_000;++async function scratchDatabase(adminUrl: string, clientUrl: string) {+ assertSafeE2eDatabaseUrl(adminUrl);+ const name = `gbrain_test_idle_pool_${randomUUID().replaceAll('-', '')}`;+ const admin = postgres(adminUrl, { max: 1, prepare: false });+ await admin.unsafe(`CREATE DATABASE ${name}`);+ const url = new URL(clientUrl);+ url.pathname = `/${name}`;+ return { name, admin, url: url.toString(),+ drop: async () => { try { await admin.unsafe(`DROP DATABASE IF EXISTS ${name} WITH (FORCE)`); } finally { await admin.end(); } } };+}++async function withConsumer(url: string, run: (engine: PostgresEngine, consumer: PersistenceConsumer, config: HarnessConfig) => Promise<void>) {+ const root = mkdtempSync(join(tmpdir(), 'gbrain-idle-pool-'));+ const config: HarnessConfig = { kind: 'postgres', root, dataDir: join(root, 'unused'), hostId: randomUUID(),+ seed: 5370, schedules: 0, operations: 0, sourceIds: ['idle-pool'], principalIds: [randomUUID()] };+ const engine = new PostgresEngine();+ try {+ await withEnv({ GBRAIN_HOME: root, GBRAIN_PERSISTENCE_FIXTURE_HOME: root }, async () => {+ await engine.connect({ database_url: url, poolSize: 4 });+ await engine.initSchema();+ selectFixtureHost(config.hostId);+ await initializeFixtures(engine, config);+ const sources = await fixtures(engine, config);+ const consumer = new PersistenceConsumer(engine, { engine: 'postgres' }, async (_e, row) => prepared(row, sources),+ { hostId: config.hostId });+ // Saturate the pool the way a busy tick does, then go idle.+ await Promise.all(Array.from({ length: 4 }, () => engine.executeRaw('SELECT pg_sleep(0.2)')));+ consumer.start();+ try { await run(engine, consumer, config); } finally { await consumer.stop(); }+ });+ } finally {+ await engine.disconnect();+ rmSync(root, { recursive: true, force: true });+ }+}++/** Established TCP sockets this process holds to host:port (Linux /proc). */+async function ownSockets(host: string, port: number): Promise<number> {+ const inodes = new Set<string>();+ for (const fd of readdirSync('/proc/self/fd')) {+ try { const link = readlinkSync(`/proc/self/fd/${fd}`); if (link.startsWith('socket:[')) inodes.add(link.slice(8, -1)); } catch { /* closed */ }+ }+ const { address, family } = await lookup(host);+ const want = family === 4+ ? address.split('.').map(part => Number(part).toString(16).padStart(2, '0')).reverse().join('').toUpperCase()+ : null;+ const portHex = port.toString(16).toUpperCase().padStart(4, '0');+ let count = 0;+ for (const table of ['/proc/self/net/tcp', '/proc/self/net/tcp6']) {+ if (!existsSync(table)) continue;+ for (const line of readFileSync(table, 'utf8').split('\n').slice(1)) {+ const cols = line.trim().split(/\s+/);+ if (cols.length < 10 || cols[3] !== '01' || !inodes.has(cols[9]!)) continue;+ const [remoteIp, remotePort] = cols[2]!.split(':');+ if (remotePort !== portHex) continue;+ if (want === null || remoteIp === want || remoteIp!.endsWith(want)) count++;+ }+ }+ return count;+}++describe.skipIf(!direct)('idle persistence consumer on PostgreSQL', () => {+ test('an idle consumer drains a direct pool to one backend', async () => {+ const db = await scratchDatabase(direct!, direct!);+ try {+ await withConsumer(db.url, async () => {+ const backends = async () => Number((await db.admin.unsafe(+ 'SELECT count(*)::int AS n FROM pg_stat_activity WHERE datname=$1', [db.name]))[0]!.n);+ expect(await backends()).toBeGreaterThanOrEqual(3);+ await Bun.sleep(IDLE_DRAIN_MS);+ expect(await backends()).toBe(1);+ });+ } finally { await db.drop(); }+ }, 120_000);++ test('a write from another process is published within the idle cap; a same-process wake is immediate', async () => {+ const db = await scratchDatabase(direct!, direct!);+ try {+ await withConsumer(db.url, async (engine, consumer, config) => {+ const sources = await fixtures(engine, config);+ const other = new PostgresEngine();+ await other.connect({ database_url: db.url, poolSize: 2 });+ try {+ await Bun.sleep(12_000);+ let started = performance.now();+ const remote = await admitWrite(other, admission(config, sources[0], 'idle/cross-process', 'remote body'));+ await waitFor(async () => (await getWriteRequestById(other, remote.id))?.state === 'committed', { timeoutMs: 10_000 });+ expect(performance.now() - started).toBeLessThan(5_000 + 3_000);+ await Bun.sleep(12_000);+ started = performance.now();+ const local = await admitWrite(engine, admission(config, sources[0], 'idle/same-process', 'local body'));+ consumer.wake();+ await waitFor(async () => (await getWriteRequestById(engine, local.id))?.state === 'committed', { timeoutMs: 10_000 });+ expect(performance.now() - started).toBeLessThan(3_000);+ } finally { await other.disconnect(); }+ });+ } finally { await db.drop(); }+ }, 120_000);+});++describe.skipIf(!(pooled && pooledAdmin) || !existsSync('/proc/self/net/tcp'))('idle persistence consumer behind transaction-mode PgBouncer', () => {+ test('an idle consumer drains its pooler client pool to one connection without LISTEN', async () => {+ const db = await scratchDatabase(pooledAdmin!, pooled!);+ const target = new URL(pooled!);+ const port = Number(target.port || 5432);+ try {+ await withConsumer(db.url, async () => {+ expect(await ownSockets(target.hostname, port)).toBeGreaterThanOrEqual(3);+ await Bun.sleep(IDLE_DRAIN_MS);+ expect(await ownSockets(target.hostname, port)).toBe(1);+ });+ } finally { await db.drop(); }+ }, 120_000);+});diff --git a/test/e2e/projection-embedding-input-hash.test.ts b/test/e2e/projection-embedding-input-hash.test.tsnew file mode 100644index 0000000000..4614746f50--- /dev/null+++ b/test/e2e/projection-embedding-input-hash.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../projection-embedding-input-hash.test.ts'));diff --git a/test/e2e/repair-command.test.ts b/test/e2e/repair-command.test.tsnew file mode 100644index 0000000000..220c3f252e--- /dev/null+++ b/test/e2e/repair-command.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../repair-command.test.ts'));diff --git a/test/e2e/safe-chunk-reseal.test.ts b/test/e2e/safe-chunk-reseal.test.tsnew file mode 100644index 0000000000..98c458571e--- /dev/null+++ b/test/e2e/safe-chunk-reseal.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../safe-chunk-reseal.test.ts'));diff --git a/test/e2e/serve-http-oauth.test.ts b/test/e2e/serve-http-oauth.test.tsindex 1d2c53251a..4ef6b57b00 100644--- a/test/e2e/serve-http-oauth.test.ts+++ b/test/e2e/serve-http-oauth.test.ts@@ -490,8 +490,61 @@ describeE2E('serve-http OAuth 2.1 E2E (v0.26.1 + v0.26.2 + v0.26.3)', () => {});});+ // #5277: the challenge hints `read write`, so a writer connector that asks+ // for exactly the hinted scope gets write, while grantScopes still caps a+ // read-only row to read.+ // #5222: the issuer origin is an alias of the canonical /mcp resource+ // (ChatGPT sends the origin root); any other resource fails loudly at+ // /authorize instead of minting a token /mcp refuses forever.+ test('an origin-root resource completes OAuth and the token works at /mcp; a foreign resource is invalid_target', async () => {+ const redirectUri = 'https://example.test/callback';+ const registration = await fetch(`${BASE}/register`, { method: 'POST', headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ client_name: `e2e-origin-resource-${Date.now()}`, redirect_uris: [redirectUri],+ grant_types: ['authorization_code', 'refresh_token'], response_types: ['code'], token_endpoint_auth_method: 'none', scope: 'read write' }) });+ expect(registration.status).toBe(201);+ const client = await registration.json() as any;+ dcrClientIds.push(client.client_id);+ const verifier = 'e2e-origin-resource-verifier-0123456789abcdefghijklmnop';+ const authorizeUrl = (resource: string) => `${BASE}/authorize?${new URLSearchParams({ client_id: client.client_id,+ response_type: 'code', redirect_uri: redirectUri, scope: 'read write', state: 'origin-state', resource,+ code_challenge: createHash('sha256').update(verifier).digest('base64url'), code_challenge_method: 'S256' })}`;++ const foreign = await fetch(authorizeUrl('https://different.example/'), { redirect: 'manual' });+ expect(foreign.status).toBe(302);+ const foreignRedirect = new URL(foreign.headers.get('location')!);+ expect(foreignRedirect.searchParams.get('error')).toBe('invalid_target');+ expect(foreignRedirect.searchParams.get('error_description')).toContain(`${BASE}/mcp`);++ const pending = await fetch(authorizeUrl(`${BASE}/`), { redirect: 'manual' });+ expect(pending.status).toBe(302);+ const requestId = new URL(pending.headers.get('location')!, BASE).searchParams.get('oauth_request');+ expect(requestId).toBeTruthy();+ const login = await fetch(`${BASE}/admin/login`, { method: 'POST',+ headers: { 'Content-Type': 'application/json', 'X-Forwarded-For': '192.0.2.52' },+ body: JSON.stringify({ token: ADMIN_BOOTSTRAP_TOKEN }) });+ expect(login.status).toBe(200);+ const cookie = `gbrain_admin=${login.headers.get('set-cookie')!.match(/gbrain_admin=([^;]+)/)![1]}`;+ const details = await (await fetch(`${BASE}/admin/api/oauth-requests/${requestId}`, {+ headers: { Cookie: cookie, 'X-Forwarded-For': '192.0.2.52' } })).json() as any;+ expect(details.resource).toBe(`${BASE}/mcp`);+ const approval = await fetch(`${BASE}/admin/api/oauth-requests/${requestId}`, { method: 'POST',+ headers: { Cookie: cookie, 'Content-Type': 'application/json', 'X-Forwarded-For': '192.0.2.52' },+ body: JSON.stringify({ decision: 'approve', csrf: details.csrf }) });+ expect(approval.status).toBe(200);+ const code = new URL((await approval.json() as any).redirectUrl).searchParams.get('code')!;+ const tokenResponse = await fetch(`${BASE}/token`, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' },+ body: new URLSearchParams({ grant_type: 'authorization_code', code, redirect_uri: redirectUri, client_id: client.client_id,+ code_verifier: verifier, resource: `${BASE}/` }) });+ expect(tokenResponse.status).toBe(200);+ const tokens = await tokenResponse.json() as any;+ expect(tokens.scope).toBe('read write');+ const listed = await mcpToolResult(tokens.access_token, 'tools/list');+ expect(listed.tools.some((tool: any) => tool.name === 'put_page')).toBe(true);+ });+for (const [label, registeredScope, explicitScope, expectedRequest] of [- ['read-only discovery', 'read', undefined, 'read'],+ ['read-only discovery', 'read', undefined, 'read write'],+ ['writer discovery', 'read write', undefined, 'read write'],['read-only overbroad hint', 'read', 'read write', 'read write'],['explicit writer request', 'read write', 'read write', 'read write'],] as const) {@@ -544,7 +597,7 @@ describeE2E('serve-http OAuth 2.1 E2E (v0.26.1 + v0.26.2 + v0.26.3)', () => {const code = new URL((await approval.json() as any).redirectUrl).searchParams.get('code')!;expect(await auth(provider, { serverUrl: `${BASE}/mcp`, authorizationCode: code })).toBe('AUTHORIZED');expect(tokens!.scope).toBe(registeredScope);- if (label === 'read-only overbroad hint') expect(tokens!.scope).not.toBe(expectedRequest);+ if (registeredScope !== expectedRequest) expect(tokens!.scope).not.toBe(expectedRequest);else expect(tokens!.scope).toBe(expectedRequest);const listed = await mcpToolResult(tokens!.access_token, 'tools/list');expect(listed.tools.some((tool: any) => tool.name === 'get_page')).toBe(true);diff --git a/test/e2e/timeline-materialize.test.ts b/test/e2e/timeline-materialize.test.tsnew file mode 100644index 0000000000..a674353327--- /dev/null+++ b/test/e2e/timeline-materialize.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../timeline-materialize.test.ts'));diff --git a/test/e2e/w5-persistence-postgres.test.ts b/test/e2e/w5-persistence-postgres.test.tsnew file mode 100644index 0000000000..6c5ae120f8--- /dev/null+++ b/test/e2e/w5-persistence-postgres.test.ts@@ -0,0 +1,23 @@+/**+ * Postgres arms of the managed capacity (#5470), effect parking (#5612) and+ * coordinated stale extraction (#5609) scenarios. Each run gets a fresh+ * isolated database from the persistence Postgres helper.+ */+import { describe, test } from 'bun:test';+import {+ capacityWarnsAndRefusalNamesTheKey, compactionSkipsUnfinishedReceipts, failuresDoNotCarryToAnotherTarget, healthyScanAndContentionNeverPark,+ managedStaleSweep, managedStaleSweepKeepsNormalizedTimeline, scanParksOneTargetAndContinues, singleTargetParksAndRetries, staleExtractionWithheldWhenItCannotRun,+} from '../helpers/w5-scenarios.ts';++const url = process.env.DATABASE_URL;+describe.skipIf(!url)('Postgres managed capacity, parking and stale extraction', () => {+ test('a failing Git target parks and retries', () => singleTargetParksAndRetries(url), 180_000);+ test('a Git scan parks one target and continues', () => scanParksOneTargetAndContinues(url), 180_000);+ test('failures do not carry to another target', () => failuresDoNotCarryToAnotherTarget(url), 180_000);+ test('a healthy scan and contention never park', () => healthyScanAndContentionNeverPark(url), 180_000);+ test('configured retention compacts past unfinished receipts', () => compactionSkipsUnfinishedReceipts(url), 240_000);+ test('capacity warning and refusal hint', () => capacityWarnsAndRefusalNamesTheKey(url), 180_000);+ test('managed extract --stale is coordinated', () => managedStaleSweep(url), 180_000);+ test('managed extract --stale keeps normalized timeline rows single', () => managedStaleSweepKeepsNormalizedTimeline(url), 180_000);+ test('extract.stale withheld when it cannot run', () => staleExtractionWithheldWhenItCannotRun(url), 180_000);+});diff --git a/test/extract-stale-managed.test.ts b/test/extract-stale-managed.test.tsnew file mode 100644index 0000000000..44dccaff86--- /dev/null+++ b/test/extract-stale-managed.test.ts@@ -0,0 +1,20 @@+/**+ * #5609: `extract --stale` on a managed-persistence brain publishes through a+ * coordinated write, stamps the extraction watermark in that transaction, and+ * the `extract.stale` recommendation stops once extraction is current or is+ * withheld when the sweep cannot run. Postgres arm: test/e2e/w5-persistence-postgres.test.ts.+ */+import { expect, test } from 'bun:test';+import { managedStaleSweep, managedStaleSweepKeepsNormalizedTimeline, staleExtractionWithheldWhenItCannotRun } from './helpers/w5-scenarios.ts';++test('managed extract --stale publishes through the coordinator and clears the recommendation', () => managedStaleSweep(), 120_000);+test('managed extract --stale does not duplicate a stored row that differs only by whitespace', () => managedStaleSweepKeepsNormalizedTimeline(), 120_000);+test('extract.stale is withheld while the sweep cannot run', () => staleExtractionWithheldWhenItCannotRun(), 120_000);++test('the remediation plan reports blocked stale extraction with its reason', async () => {+ const { SYNTHETIC_CHECK_NAMES } = await import('../src/core/remediation/plan.ts');+ const { classifyChecks } = await import('../src/core/brain-score-recommendations.ts');+ const checks = SYNTHETIC_CHECK_NAMES.map(name => ({ name, status: 'ok' as const, message: '' }));+ expect(classifyChecks(checks, { staleExtractionBlocked: 'pack unavailable' })).toContainEqual(+ { check: 'links_extraction_lag', status: 'blocked', reason: 'pack unavailable' });+});diff --git a/test/grandfather-managed.test.ts b/test/grandfather-managed.test.tsindex a36db4cb2a..5213a56b23 100644--- a/test/grandfather-managed.test.ts+++ b/test/grandfather-managed.test.ts@@ -1,23 +1,29 @@import { expect, test } from 'bun:test';-import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';-import { join } from 'node:path';+import { dirname, join } from 'node:path';import { randomUUID } from 'node:crypto';import type { BrainEngine } from '../src/core/engine.ts';import type { OperationContext } from '../src/core/ops/contract.ts';-import { phaseCGrandfather } from '../src/commands/migrations/v0_13_1.ts';+import { phaseCGrandfather, phaseDVerify } from '../src/commands/migrations/v0_13_1.ts';import { claimWorktree } from '../src/core/persistence/ownership.ts';import { activateSharedSkillPersistence } from '../src/core/persistence/skill-activation.ts';import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';import { grandfatherCanonicalPage } from '../src/core/persistence/grandfather.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { runPersistenceEffects } from '../src/core/persistence/effects.ts';+import { declarePersistenceProtocol } from '../src/core/persistence/protocol.ts';import { serializePageToMarkdown } from '../src/core/markdown.ts';+import { importFromContent } from '../src/core/import-file.ts';import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';import { withEnv } from './helpers/with-env.ts';+import { durableGitRepo, git } from './helpers/git-publication.ts';import { localHostId } from '../src/core/persistence/identity.ts';-async function fixture(run: (f: { engine: BrainEngine; ctx: OperationContext; home: string; root: string; slug: string }) => Promise<void>, databaseUrl?: string) {+type FixtureOptions = { databaseUrl?: string; setup?: (f: { engine: BrainEngine; root: string }) => Promise<void> };+async function fixture(run: (f: { engine: BrainEngine; ctx: OperationContext; home: string; root: string; slug: string }) => Promise<void>,+ { databaseUrl, setup }: FixtureOptions = {}) {const home = mkdtempSync(join(tmpdir(), 'gbrain-managed-grandfather-'));try {await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {@@ -25,6 +31,7 @@ async function fixture(run: (f: { engine: BrainEngine; ctx: OperationContext; hotry {const root = join(home, 'content'); mkdirSync(root);await engine.executeRaw("UPDATE sources SET local_path=$1 WHERE id='default'", [root]);+ await setup?.({ engine, root });await claimWorktree(engine, 'default', root);await activateSharedSkillPersistence(engine, { confirmQuiesced: true });const ctx: OperationContext = { engine, config: { engine: engine.kind, embedding_disabled: true }, sourceId: 'default',@@ -68,7 +75,7 @@ async function preservesManagedPage(databaseUrl?: string) {expect(snapshot.pre_frontmatter).not.toHaveProperty('validate');if (process.platform !== 'win32') expect(statSync(rollback).mode & 0o777).toBe(0o600);expect((await phaseCGrandfather(engine, { yes: true, dryRun: false, noAutopilotInstall: true })).detail.touched).toBe(0);- }, databaseUrl);+ }, { databaseUrl });}test('managed grandfathering publishes metadata without changing vectors or spending on derived effects', () => preservesManagedPage(), 120_000);@@ -111,7 +118,8 @@ test('pending grandfathering reuses its admitted request and its original rollbaawait tx.executeRaw("SELECT set_config('gbrain.topology_change','on',true)");await tx.executeRaw('UPDATE persistence_worktrees SET owner_host_id=$1::uuid', [host]);});- expect(await grandfatherCanonicalPage(engine, selected, () => { backups++; })).toBe('touched');+ expect(await grandfatherCanonicalPage(engine, selected, () => { backups++; }))+ .toEqual({ status: 'touched', revision: (await engine.readPageSnapshot(slug, { sourceId: 'default' }))!.revision });expect(backups).toBe(1);expect(await engine.executeRaw("SELECT request_id,state FROM persistence_requests WHERE intent->>'kind'='managed_grandfather'")).toEqual([{ request_id: requestId, state: 'committed' }]);@@ -137,3 +145,130 @@ test('archived sources and non-Markdown artifacts are not rewritten by managed gexpect(readFileSync(join(root, 'source/example.ts'), 'utf8')).toBe('export const fixture = 1;\n');expect((await engine.getPage(slug, { sourceId: 'default' }))?.frontmatter).not.toHaveProperty('validate');}), 120_000);++const DB_ONLY_SLUG = 'conversations/sessions/probe-session';+const DB_ONLY_CACHE = `${DB_ONLY_SLUG}.md`;+// A durability-hardened Git worktree makes Git effects publish for real, so an+// ignored db_only cache file reaches the path that refuses unsafe targets.+// Transcript ingestion publishes db_only pages before persistence activation;+// a direct import is refused once the source is managed.+const dbOnlySource = (gbrainYml: string, { cache = false } = {}) => async ({ engine, root }: { engine: BrainEngine; root: string }) => {+ writeFileSync(join(root, 'gbrain.yml'), gbrainYml);+ writeFileSync(join(root, '.gitignore'), 'conversations/\n');+ durableGitRepo(root, ['.gitignore', 'gbrain.yml']);+ await importFromContent(engine, DB_ONLY_SLUG, '---\ntype: conversation\ntitle: Probe session\n---\n\nTranscript body.\n', { sourceId: 'default', noEmbed: true });+ if (cache) {+ const snapshot = (await engine.readPageSnapshot(DB_ONLY_SLUG, { sourceId: 'default' }))!;+ mkdirSync(dirname(join(root, DB_ONLY_CACHE)), { recursive: true });+ writeFileSync(join(root, DB_ONLY_CACHE), serializePageToMarkdown(snapshot.page, snapshot.tags));+ }+};+const declaring = (dir: string) => `storage:\n db_only:\n - ${dir}\n`;+const replacePage = async (ctx: OperationContext, slug: string, body: string) => {+ const current = (await ctx.engine.readPageSnapshot(slug, { sourceId: 'default' }))!;+ return submitPageMutation(ctx, { operation: 'put_page', params: { slug, request_id: randomUUID(), expected_revision: current.revision,+ content: serializePageToMarkdown({ ...current.page, compiled_truth: body }, current.tags) } });+};+const deletePage = async (ctx: OperationContext, slug: string, purge: boolean) => submitPageMutation(ctx, { operation: 'delete_page',+ params: { slug, request_id: randomUUID(), expected_revision: (await ctx.engine.readPageSnapshot(slug, { sourceId: 'default' }))!.revision, purge } });+// Runs every queued Git effect and returns their final rows.+async function settledGitEffects(engine: BrainEngine, ctx: OperationContext) {+ await disposePersistenceConsumer(engine);+ await runPersistenceEffects(engine, ctx.config, { hostId: localHostId(), limit: 20 });+ return engine.executeRaw<{ slug: string; state: string; error_code: string | null; outcome: Record<string, unknown> | null }>(+ "SELECT r.slug,e.state,e.error_code,e.outcome FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id WHERE e.kind='git' ORDER BY e.id");+}++for (const declared of ['conversations/', 'Conversations/']) {+ test(`managed writes publish a page under declared db_only ${declared} without a cache file database-only`, () => fixture(async ({ engine, ctx, root }) => {+ expect((await engine.readPageSnapshot(DB_ONLY_SLUG, { sourceId: 'default' }))?.page.source_path).toBeNull();+ expect(await phaseCGrandfather(engine, { yes: true, dryRun: false, noAutopilotInstall: true }))+ .toMatchObject({ result: { status: 'complete' }, detail: { touched: 2, failed: 0 } });+ expect((await engine.getPage(DB_ONLY_SLUG, { sourceId: 'default' }))?.frontmatter.validate).toBe(false);+ expect(await engine.executeRaw("SELECT slug,state FROM persistence_requests WHERE intent->>'kind'='managed_grandfather' ORDER BY slug"))+ .toEqual([{ slug: DB_ONLY_SLUG, state: 'committed' }, { slug: 'notes/example', state: 'committed' }]);+ expect(await replacePage(ctx, DB_ONLY_SLUG, 'Revised transcript body.')).toMatchObject({ write_through: { written: false, skipped: 'db_only' } });+ expect((await engine.getPage(DB_ONLY_SLUG, { sourceId: 'default' }))?.compiled_truth).toContain('Revised transcript body.');+ expect(existsSync(join(root, 'conversations'))).toBe(false);+ expect((await settledGitEffects(engine, ctx)).filter(effect => effect.slug === DB_ONLY_SLUG)).toEqual([]);+ }, { setup: dbOnlySource(declaring(declared)) }), 120_000);+}++const cacheCases: Array<[string, (ctx: OperationContext) => Promise<unknown>, string | null]> = [+ ['an edit rewrites', ctx => replacePage(ctx, DB_ONLY_SLUG, 'Revised transcript body.'), 'Revised transcript body.'],+ ['a soft delete removes', ctx => deletePage(ctx, DB_ONLY_SLUG, false), null],+ ['a purge removes', ctx => deletePage(ctx, DB_ONLY_SLUG, true), null],+];+for (const [name, act, expected] of cacheCases) {+ test(`${name} a present db_only cache file and completes its Git effect as skipped`, () => fixture(async ({ engine, ctx, root }) => {+ expect(await act(ctx)).toMatchObject({ state: 'committed', write_through: { written: true } });+ const cache = join(root, DB_ONLY_CACHE);+ if (expected === null) expect(existsSync(cache)).toBe(false);+ else expect(readFileSync(cache, 'utf8')).toContain(expected);+ const effects = await settledGitEffects(engine, ctx);+ expect(effects.filter(effect => effect.slug === DB_ONLY_SLUG)).toEqual([+ { slug: DB_ONLY_SLUG, state: 'committed', error_code: null, outcome: { git: 'skipped', reason: 'db_only' } }]);+ expect(effects.filter(effect => effect.error_code === 'git_target_unsafe')).toEqual([]);+ expect(git(root, 'log', '--name-only', '--pretty=format:')).not.toContain('conversations');+ }, { setup: dbOnlySource(declaring('conversations/'), { cache: true }) }), 120_000);+}++test('an uncoordinated edit of a db_only cache file still refuses a managed write', () => fixture(async ({ engine, ctx, root }) => {+ const cache = join(root, DB_ONLY_CACHE);+ const edited = readFileSync(cache, 'utf8').replace('Transcript body.', 'Local unpublished edit.');+ writeFileSync(cache, edited);+ const before = (await engine.readPageSnapshot(DB_ONLY_SLUG, { sourceId: 'default' }))!;+ await expect(replacePage(ctx, DB_ONLY_SLUG, 'Revised transcript body.')).rejects.toMatchObject({ code: 'source_changed' });+ expect(readFileSync(cache, 'utf8')).toBe(edited);+ expect((await engine.readPageSnapshot(DB_ONLY_SLUG, { sourceId: 'default' }))?.revision).toBe(before.revision);+}, { setup: dbOnlySource(declaring('conversations/'), { cache: true }) }), 120_000);++test('the missing-file guard still refuses outside declared db_only dirs', () => fixture(async ({ ctx, root, slug }) => {+ rmSync(join(root, `${slug}.md`));+ await expect(replacePage(ctx, slug, 'Replacement body.')).rejects.toMatchObject({ code: 'source_changed' });+}, { setup: dbOnlySource(declaring('conversations/')) }), 120_000);++const invalidStorage: Array<[string, string]> = [+ ['overlapping tiers', 'storage:\n db_tracked:\n - conversations/\n db_only:\n - conversations/\n'],+ ['flow-style db_only', 'storage:\n db_only: [conversations/]\n'],+];+for (const [name, gbrainYml] of invalidStorage) {+ test(`${name} in gbrain.yml only turn the missing-file refusal into storage_error`, () => fixture(async ({ engine, ctx, root }) => {+ writeFileSync(join(root, 'gbrain.yml'), gbrainYml);+ const before = (await engine.readPageSnapshot(DB_ONLY_SLUG, { sourceId: 'default' }))!;+ await expect(replacePage(ctx, DB_ONLY_SLUG, 'Replacement transcript.')).rejects.toMatchObject({ code: 'storage_error' });+ expect((await engine.readPageSnapshot(DB_ONLY_SLUG, { sourceId: 'default' }))?.revision).toBe(before.revision);+ expect(existsSync(join(root, 'conversations'))).toBe(false);+ // New pages never read gbrain.yml: both publish their file as on baseline.+ for (const slug of ['notes/created', 'conversations/sessions/created']) {+ expect(await submitPageMutation(ctx, { operation: 'put_page', params: { slug, request_id: randomUUID(),+ content: '---\ntype: note\ntitle: Created\n---\n\nCreated body.\n' } })).toMatchObject({ state: 'committed', write_through: { written: true } });+ expect(readFileSync(join(root, `${slug}.md`), 'utf8')).toContain('Created body.');+ }+ }, { setup: dbOnlySource(declaring('conversations/')) }), 120_000);+}++// cache=false is a regression guard (passes on baseline); cache=true fails there with an unsafe Git target.+for (const cache of [false, true]) {+ test(`a Git source scan passes a db_only page ${cache ? 'with' : 'without'} a cache file`, () => fixture(async ({ engine, ctx }) => {+ // Source scans walk every page in slug order, so the db_only page is visited first.+ const [effect] = await engine.executeRaw<{ id: number }>(+ "SELECT e.id FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id WHERE e.kind='git' AND r.slug='notes/example'");+ await engine.transaction(async tx => {+ await declarePersistenceProtocol(tx);+ await tx.executeRaw(`UPDATE persistence_effects SET data='{"source_scan":true}'::jsonb,state='queued',execution_token=NULL,+ claim_expires_at=NULL,next_attempt_at=now(),error_code=NULL WHERE id=$1`, [effect.id]);+ });+ await runPersistenceEffects(engine, ctx.config, { hostId: localHostId(), limit: 5 });+ expect(await engine.executeRaw('SELECT state,error_code FROM persistence_effects WHERE id=$1', [effect.id]))+ .toEqual([{ state: 'committed', error_code: null }]);+ }, { setup: dbOnlySource(declaring('conversations/'), { cache }) }), 120_000);+}++test('verify reports a managed page rewritten after grandfathering without failing the phase', () => fixture(async ({ engine, slug }) => {+ const { detail } = await phaseCGrandfather(engine, { yes: true, dryRun: false, noAutopilotInstall: true });+ expect(await phaseDVerify(engine, detail.grandfathered)).toMatchObject({ status: 'complete', detail: 'verified=1 rewritten_concurrently=0' });+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () =>+ tx.executeRaw("UPDATE pages SET frontmatter=frontmatter-'validate' WHERE source_id='default' AND slug=$1", [slug])));+ expect(await phaseDVerify(engine, detail.grandfathered)).toMatchObject({ status: 'complete', detail: 'verified=0 rewritten_concurrently=1' });+}), 120_000);diff --git a/test/helpers/git-publication.ts b/test/helpers/git-publication.tsindex 2b3bb82bd4..8cda5138c0 100644--- a/test/helpers/git-publication.ts+++ b/test/helpers/git-publication.ts@@ -8,6 +8,17 @@ export function git(root: string, ...args: string[]): string {return result.stdout.toString();}+/** A durability-hardened repo with no remote: Git effects publish for real and the hook is inert. */+export function durableGitRepo(root: string, committed: string[]): void {+ git(root, 'init', '-q');+ git(root, 'config', 'user.name', 'Example Writer');+ git(root, 'config', 'user.email', '[email protected]');+ git(root, 'add', ...committed); git(root, 'commit', '-q', '-m', 'Initial');+ const hook = join(root, '.git', 'hooks', 'post-commit');+ writeFileSync(hook, '#!/bin/sh\n# gbrain brain-durability post-commit hook (v0.42.44+)\n');+ chmodSync(hook, 0o755);+}+export function gitFixture() {const requestedHome = mkdtempSync(join(tmpdir(), 'gbrain-git-publication-'));const home = realpathSync.native(requestedHome);diff --git a/test/helpers/managed-brain.ts b/test/helpers/managed-brain.tsnew file mode 100644index 0000000000..e870185254--- /dev/null+++ b/test/helpers/managed-brain.ts@@ -0,0 +1,33 @@+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../../src/core/engine.ts';+import type { OperationContext } from '../../src/core/ops/contract.ts';+import { claimWorktree } from '../../src/core/persistence/ownership.ts';+import { activateSharedSkillPersistence } from '../../src/core/persistence/skill-activation.ts';+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';+import { isolatedSharedSkillsEngine } from './shared-skills-engine.ts';+import { withEnv } from './with-env.ts';++export interface ManagedBrain { engine: BrainEngine; ctx: OperationContext; root: string }++/** An activated managed brain whose default source is a claimed worktree; PGLite unless a database URL is given. */+export async function managedBrain(run: (brain: ManagedBrain) => Promise<void>,+ opts: { databaseUrl?: string; setup?: (brain: { engine: BrainEngine; root: string }) => Promise<void> | void } = {}): Promise<void> {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-managed-brain-'));+ try {+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {+ const { engine, close } = await isolatedSharedSkillsEngine(opts.databaseUrl);+ try {+ const root = join(home, 'content'); mkdirSync(root);+ await engine.executeRaw("UPDATE sources SET local_path=$1 WHERE id='default'", [root]);+ await opts.setup?.({ engine, root });+ await claimWorktree(engine, 'default', root);+ await activateSharedSkillPersistence(engine, { confirmQuiesced: true });+ const ctx: OperationContext = { engine, config: { engine: engine.kind, embedding_disabled: true }, sourceId: 'default',+ remote: false, dryRun: false, logger: { info() {}, warn() {}, error() {} } };+ await run({ engine, ctx, root });+ } finally { await disposePersistenceConsumer(engine); await close(); }+ });+ } finally { rmSync(home, { recursive: true, force: true }); }+}diff --git a/test/helpers/w5-scenarios.ts b/test/helpers/w5-scenarios.tsnew file mode 100644index 0000000000..b64c14120e--- /dev/null+++ b/test/helpers/w5-scenarios.ts@@ -0,0 +1,258 @@+/**+ * Engine-parametrized scenarios for managed capacity (#5470), effect parking+ * (#5612) and coordinated stale extraction (#5609). PGLite runs them from+ * test/; test/e2e/ runs the same bodies on Postgres.+ */+import { expect } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { writeFileSync } from 'node:fs';+import { join } from 'node:path';+import type { BrainEngine } from '../../src/core/engine.ts';+import type { OperationContext } from '../../src/core/ops/contract.ts';+import { submitPageMutation } from '../../src/core/persistence/page-mutations.ts';+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';+import { runPersistenceEffects } from '../../src/core/persistence/effects.ts';+import { retryParkedEffects, retryRequestEffects } from '../../src/core/persistence/effect-retry.ts';+import { compactWriteReceipts } from '../../src/core/persistence/journal.ts';+import { declarePersistenceProtocol } from '../../src/core/persistence/protocol.ts';+import { localHostId } from '../../src/core/persistence/identity.ts';+import { withCoordinatedWrite } from '../../src/core/persistence/context.ts';+import { acquireWorktree, getWorktreeBinding } from '../../src/core/persistence/ownership.ts';+import { extractStaleFromDB } from '../../src/commands/extract.ts';+import { computeRecommendations } from '../../src/core/brain-score-recommendations.ts';+import { staleExtractionBlocked } from '../../src/core/remediation/context.ts';+import { LINK_EXTRACTOR_VERSION_TS } from '../../src/core/link-extraction.ts';+import { checkParkedEffects } from '../../src/commands/doctor/checks/parked-effects.ts';+import { checkPersistenceCapacity } from '../../src/commands/doctor/checks/persistence-capacity.ts';+import { managedBrain } from './managed-brain.ts';+import { durableGitRepo, git } from './git-publication.ts';++const put = (ctx: OperationContext, slug: string, body: string, type = 'note') => submitPageMutation(ctx, { operation: 'put_page',+ params: { slug, request_id: randomUUID(), content: `---\ntype: ${type}\ntitle: ${slug}\n---\n\n${body}\n` } });+type GitEffect = { id: number; request_id: string; state: string; error_code: string | null; attempts: number; data: Record<string, unknown> };+const gitEffect = async (engine: BrainEngine, slug: string) => (await engine.executeRaw<GitEffect>(`SELECT e.id,r.request_id::text AS request_id,e.state,+ e.error_code,e.attempts,e.data FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id WHERE e.kind='git' AND r.slug=$1`, [slug]))[0];+/** Stops the resident consumer and puts one effect back to a fresh queued state with the given data. */+async function resetEffect(engine: BrainEngine, id: number, data: Record<string, unknown>) {+ await disposePersistenceConsumer(engine);+ await engine.transaction(async tx => {+ await declarePersistenceProtocol(tx);+ await tx.executeRaw(`UPDATE persistence_effects SET data=$2::text::jsonb,state='queued',attempts=0,execution_token=NULL,+ claim_expires_at=NULL,error_code=NULL,outcome=NULL WHERE id=$1`, [id, JSON.stringify(data)]);+ });+}+/** Runs one effect attempt at a time with every other effect deferred. */+async function runOnly(engine: BrainEngine, ctx: OperationContext, id: number, times = 1) {+ await disposePersistenceConsumer(engine);+ for (let i = 0; i < times; i++) {+ await engine.transaction(async tx => {+ await declarePersistenceProtocol(tx);+ await tx.executeRaw("UPDATE persistence_effects SET next_attempt_at=CASE WHEN id=$1 THEN now() ELSE now()+interval '1 hour' END", [id]);+ });+ await runPersistenceEffects(engine, ctx.config, { hostId: localHostId(), limit: 1 });+ }+}+const ignoredPages = (root: string) => { writeFileSync(join(root, '.gitignore'), 'aa/\n'); durableGitRepo(root, ['.gitignore']); };+const unignore = (root: string) => { writeFileSync(join(root, '.gitignore'), '\n'); git(root, 'commit', '-q', '-am', 'Stop ignoring aa/'); };+const committed = (root: string) => git(root, 'log', '--name-only', '--pretty=format:');++export async function singleTargetParksAndRetries(databaseUrl?: string) {+ await managedBrain(async ({ engine, ctx, root }) => {+ await put(ctx, 'aa/page', 'Ignored by Git.');+ const effect = await gitEffect(engine, 'aa/page');+ await resetEffect(engine, effect.id, { slug: 'aa/page', page_id: effect.data.page_id, relative_path: effect.data.relative_path, expected_hash: effect.data.expected_hash });+ await runOnly(engine, ctx, effect.id, 4);+ expect(await gitEffect(engine, 'aa/page')).toMatchObject({ state: 'queued', error_code: 'git_target_unsafe', data: { target_failures: 4 } });+ await runOnly(engine, ctx, effect.id);+ expect(await gitEffect(engine, 'aa/page')).toMatchObject({ state: 'failed', error_code: 'targets_parked',+ data: { parked: [{ slug: 'aa/page', error_code: 'git_target_unsafe' }] } });+ await runOnly(engine, ctx, effect.id, 3);+ expect((await gitEffect(engine, 'aa/page')).attempts).toBe(5);++ const doctor = await checkParkedEffects(engine);+ expect(doctor).toMatchObject({ status: 'warn', details: { parked_effects: 1, exact: true, truncated: false } });+ expect(doctor.message).toContain(`gbrain sources writer retry-effects default --request-id ${effect.request_id} --dry-run`);+ expect(doctor.message).toContain('aa/page (git_target_unsafe)');++ unignore(root);+ expect(await retryParkedEffects(engine, 'default', effect.request_id, true)).toMatchObject({ dry_run: true,+ effects: [{ kind: 'git', parked_targets: 1, state: 'parked', action: 'would_retry' }] });+ expect(await gitEffect(engine, 'aa/page')).toMatchObject({ state: 'failed', error_code: 'targets_parked' });+ expect(await retryParkedEffects(engine, 'default', effect.request_id, false)).toMatchObject({+ effects: [{ kind: 'git', state: 'queued', terminal: false, action: 'retry_queued' }] });+ await runOnly(engine, ctx, effect.id);+ expect(await gitEffect(engine, 'aa/page')).toMatchObject({ state: 'committed', error_code: null });+ expect(committed(root)).toContain('aa/page.md');+ expect(await retryParkedEffects(engine, 'default', effect.request_id, true)).toMatchObject({+ effects: [{ kind: 'git', state: 'committed', terminal: true, action: 'unchanged', retried: 1 }] });+ await engine.transaction(async tx => {+ await declarePersistenceProtocol(tx);+ await tx.executeRaw("UPDATE persistence_effects SET state='failed',error_code='embedding_attempts_exhausted' WHERE kind='embedding' AND request_id=(SELECT request_id FROM persistence_effects WHERE id=$1)", [effect.id]);+ });+ expect(await retryRequestEffects(engine, 'default', effect.request_id, true, ctx.config)).toMatchObject({ kind: 'embedding',+ parked_effects: [{ kind: 'git', state: 'committed', terminal: true }] });+ expect(await checkParkedEffects(engine)).toMatchObject({ status: 'ok', details: { parked_effects: 0 } });+ }, { databaseUrl, setup: ({ root }) => ignoredPages(root) });+}++export async function scanParksOneTargetAndContinues(databaseUrl?: string) {+ await managedBrain(async ({ engine, ctx, root }) => {+ for (const slug of ['aa/page', 'bb', 'cc']) await put(ctx, slug, `Body of ${slug}.`);+ const scan = await gitEffect(engine, 'bb');+ await resetEffect(engine, scan.id, { source_scan: true });+ await runOnly(engine, ctx, scan.id, 5);+ expect(await gitEffect(engine, 'bb')).toMatchObject({ state: 'queued', data: { after_slug: 'aa/page',+ parked: [{ slug: 'aa/page', error_code: 'git_target_unsafe' }] } });+ await runOnly(engine, ctx, scan.id, 3);+ expect(await gitEffect(engine, 'bb')).toMatchObject({ state: 'failed', error_code: 'targets_parked', data: { after_slug: 'cc' } });+ expect(committed(root)).toContain('cc.md');+ expect(committed(root)).not.toContain('aa/page.md');++ unignore(root);+ await retryParkedEffects(engine, 'default', scan.request_id, false);+ expect((await gitEffect(engine, 'bb')).data).toMatchObject({ retry_slugs: ['aa/page'], target_failures: 4 });+ await runOnly(engine, ctx, scan.id, 2);+ expect(await gitEffect(engine, 'bb')).toMatchObject({ state: 'committed', error_code: null });+ expect(committed(root)).toContain('aa/page.md');+ }, { databaseUrl, setup: ({ root }) => ignoredPages(root) });+}++export async function failuresDoNotCarryToAnotherTarget(databaseUrl?: string) {+ await managedBrain(async ({ engine, ctx }) => {+ for (const slug of ['aa/first', 'aa/second', 'cc']) await put(ctx, slug, `Body of ${slug}.`);+ const scan = await gitEffect(engine, 'cc');+ await resetEffect(engine, scan.id, { source_scan: true });+ await runOnly(engine, ctx, scan.id, 4);+ expect((await gitEffect(engine, 'cc')).data).toMatchObject({ target_failures: 4, failing_target: 'aa/first' });+ const first = (await engine.readPageSnapshot('aa/first', { sourceId: 'default' }))!;+ await submitPageMutation(ctx, { operation: 'delete_page', params: { slug: 'aa/first', request_id: randomUUID(), expected_revision: first.revision, purge: true } });+ await runOnly(engine, ctx, scan.id);+ expect(await gitEffect(engine, 'cc')).toMatchObject({ state: 'queued', error_code: 'git_target_unsafe',+ data: { target_failures: 1, failing_target: 'aa/second' } });+ expect((await gitEffect(engine, 'cc')).data.parked).toBeUndefined();+ }, { databaseUrl, setup: ({ root }) => ignoredPages(root) });+}++export async function healthyScanAndContentionNeverPark(databaseUrl?: string) {+ await managedBrain(async ({ engine, ctx, root }) => {+ const slugs = Array.from({ length: 8 }, (_, i) => `notes/page-${i}`);+ for (const slug of slugs) await put(ctx, slug, `Body ${slug}.`);+ const scan = await gitEffect(engine, slugs[0]);+ await resetEffect(engine, scan.id, { source_scan: true });+ const lock = await acquireWorktree((await getWorktreeBinding(engine, 'default', localHostId()))!);+ try { await runOnly(engine, ctx, scan.id, 7); }+ finally { await lock!.release(); }+ const busy = await gitEffect(engine, slugs[0]);+ expect(busy).toMatchObject({ state: 'queued', error_code: 'writer_busy' });+ expect(busy.data.target_failures).toBeUndefined();+ await runOnly(engine, ctx, scan.id, slugs.length + 1);+ const done = await gitEffect(engine, slugs[0]);+ expect(done).toMatchObject({ state: 'committed', error_code: null });+ expect(done.attempts).toBeGreaterThan(slugs.length);+ expect(done.data.parked).toBeUndefined();+ for (const slug of slugs) expect(committed(root)).toContain(`${slug}.md`);+ }, { databaseUrl, setup: ({ root }) => ignoredPages(root) });+}++export async function compactionSkipsUnfinishedReceipts(databaseUrl?: string) {+ await managedBrain(async ({ engine, ctx }) => {+ for (let i = 0; i < 102; i++) await put(ctx, `notes/receipt-${i}`, `Receipt ${i}.`);+ await disposePersistenceConsumer(engine);+ const [last] = await engine.executeRaw<{ id: string }>("SELECT id FROM persistence_requests WHERE slug='notes/receipt-101'");+ await engine.transaction(async tx => {+ await declarePersistenceProtocol(tx);+ await tx.executeRaw("UPDATE persistence_effects SET state=CASE WHEN request_id=$1::uuid THEN 'committed' ELSE 'failed' END,error_code=NULL", [last.id]);+ });+ await engine.setConfig('persistence.receipt_retention_days', '0');+ expect(await compactWriteReceipts(engine)).toBe(1);+ expect(await engine.executeRaw('SELECT slug FROM persistence_requests WHERE compacted ORDER BY sequence')).toEqual([{ slug: 'notes/receipt-101' }]);+ }, { databaseUrl });+}++export async function capacityWarnsAndRefusalNamesTheKey(databaseUrl?: string) {+ await managedBrain(async ({ engine, ctx }) => {+ expect(await checkPersistenceCapacity(engine)).toMatchObject({ status: 'ok', details: { exact: true, truncated: false } });+ for (let i = 0; i < 8; i++) await put(ctx, `notes/cap-${i}`, `Cap ${i}.`);+ await engine.setConfig('persistence.limits.principal_outstanding', '10');+ expect((await checkPersistenceCapacity(engine)).status).toBe('ok');+ await engine.setConfig('persistence.limits.principal_lifetime_ids', '10');+ const warning = await checkPersistenceCapacity(engine);+ expect(warning.status).toBe('warn');+ const details = warning.details as { resources: Array<{ scope: string; resource: string; used: number; limit: number }>; commands: string[] };+ expect(details.resources).toHaveLength(1);+ expect(details.resources[0]).toMatchObject({ resource: 'lifetime_ids', used: 8, limit: 10 });+ expect(details.resources[0].scope).toStartWith('principal:');+ expect(details.commands).toHaveLength(1);+ const value = Number(details.commands[0].match(/^gbrain config set persistence\.limits\.principal_lifetime_ids (\d+)$/)![1]);+ expect(value).toBeGreaterThanOrEqual(20);+ expect(warning.message).toContain(details.commands[0]);++ await put(ctx, 'notes/cap-8', 'Cap 8.'); await put(ctx, 'notes/cap-9', 'Cap 9.');+ const refusal = await put(ctx, 'notes/cap-10', 'Cap 10.').then(() => null, error => error);+ expect(refusal).toMatchObject({ code: 'queue_capacity', detail: 'principal_lifetime_ids' });+ expect(refusal.message).toContain('10 used of 10');+ expect(refusal.suggestion).toMatch(/gbrain config set persistence\.limits\.principal_lifetime_ids \d+/);+ }, { databaseUrl });+}++const stale = (engine: BrainEngine) => engine.countStalePagesForExtraction({ versionTs: LINK_EXTRACTOR_VERSION_TS });+const recommended = async (engine: BrainEngine) => computeRecommendations({ stale_pages: await stale(engine), dead_links: 0, missing_embeddings: 0 } as never,+ { staleExtractionBlocked: await staleExtractionBlocked(engine) }).some(step => step.id === 'extract.stale');+const extractStale = (engine: BrainEngine) => extractStaleFromDB(engine, { dryRun: false, jsonMode: true, quiet: true, catchUp: true });++export async function managedStaleSweep(databaseUrl?: string) {+ await managedBrain(async ({ engine, ctx }) => {+ await engine.setConfig('auto_link', 'false');+ await put(ctx, 'companies/acme-example', 'A company.', 'company');+ await put(ctx, 'people/alice-example', 'Works with [[companies/acme-example]].\n\n## Timeline\n\n- **2026-01-02** | test — Met Acme', 'person');+ await disposePersistenceConsumer(engine);+ const [alice] = await engine.executeRaw<{ id: number }>("SELECT id FROM pages WHERE slug='people/alice-example'");+ const timeline = () => engine.executeRaw('SELECT date::text,source,summary FROM timeline_entries WHERE page_id=$1 ORDER BY id', [alice.id]);+ const before = await timeline();+ expect(before).toHaveLength(1);+ expect(await stale(engine)).toBe(2);+ expect(await recommended(engine)).toBe(true);++ expect(await extractStale(engine)).toMatchObject({ pagesProcessed: 2, staleRemaining: 0 });+ expect(await timeline()).toEqual(before);+ expect(await engine.executeRaw(`SELECT t.slug FROM links l JOIN pages f ON f.id=l.from_page_id JOIN pages t ON t.id=l.to_page_id+ WHERE f.slug='people/alice-example'`)).toEqual([{ slug: 'companies/acme-example' }]);+ expect(await stale(engine)).toBe(0);+ expect(await recommended(engine)).toBe(false);+ expect(await extractStale(engine)).toMatchObject({ pagesProcessed: 0, staleRemaining: 0 });+ }, { databaseUrl });+}++/** A stored row that differs from its bullet only by whitespace is the same entry to the coordinator; stale extraction must not add a twin. */+export async function managedStaleSweepKeepsNormalizedTimeline(databaseUrl?: string) {+ await managedBrain(async ({ engine, ctx }) => {+ await engine.setConfig('auto_link', 'false');+ await put(ctx, 'people/alice-example', 'A person.\n\n## Timeline\n\n- **2026-01-02** | test — Met Acme', 'person');+ await disposePersistenceConsumer(engine);+ const [alice] = await engine.executeRaw<{ id: number }>("SELECT id FROM pages WHERE slug='people/alice-example'");+ // A row written before timeline normalization (whitespace differs from the bullet).+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () =>+ tx.executeRaw("UPDATE timeline_entries SET summary='Met Acme ' WHERE page_id=$1", [alice.id])));+ const timeline = () => engine.executeRaw('SELECT date::text,source,summary FROM timeline_entries WHERE page_id=$1 ORDER BY id', [alice.id]);+ const before = await timeline();+ expect(before).toEqual([{ date: '2026-01-02', source: 'test', summary: 'Met Acme ' }]);+ expect(await extractStale(engine)).toMatchObject({ pagesProcessed: 1, staleRemaining: 0 });+ expect(await timeline()).toEqual(before);+ }, { databaseUrl });+}++export async function staleExtractionWithheldWhenItCannotRun(databaseUrl?: string) {+ await managedBrain(async ({ engine, ctx }) => {+ await engine.setConfig('auto_link', 'false');+ await put(ctx, 'notes/example', 'Stale page.');+ await disposePersistenceConsumer(engine);+ expect(await recommended(engine)).toBe(true);+ await engine.setConfig('schema_pack.source.default', 'missing-pack-example');+ expect(await staleExtractionBlocked(engine)).toContain('active schema pack is unavailable for source default');+ expect(await recommended(engine)).toBe(false);+ await engine.setConfig('schema_pack', 'missing-pack-example');+ await engine.setConfig('schema_pack.source.default', 'gbrain-base');+ expect(await staleExtractionBlocked(engine)).toBeUndefined();+ expect(await recommended(engine)).toBe(true);+ }, { databaseUrl });+}diff --git a/test/helpers/with-env.ts b/test/helpers/with-env.tsindex 20d8f97466..04651e28a5 100644--- a/test/helpers/with-env.ts+++ b/test/helpers/with-env.ts@@ -54,6 +54,9 @@ export async function withEnv<T>(for (const key of keys) {prior[key] = process.env[key];}+ // Bun keeps the last explicitly set zone when TZ is deleted (bun test pins+ // UTC without setting TZ), so restore an absent TZ as the zone in effect.+ if ('TZ' in overrides && prior.TZ === undefined) prior.TZ = Intl.DateTimeFormat().resolvedOptions().timeZone;try {for (const [key, value] of Object.entries(overrides)) {if (value === undefined) {diff --git a/test/hook-command.serial.test.ts b/test/hook-command.serial.test.tsindex a211abe81d..d8a856aff4 100644--- a/test/hook-command.serial.test.ts+++ b/test/hook-command.serial.test.ts@@ -679,6 +679,45 @@ describe('session-end', () => {expect(readFileSync(join(corpusDir, 'sess-dup.txt'), 'utf8')).toContain('resumed pass content');});+ // #5413: a claude-cli scratch session (gbrain's own LLM call) must never+ // reach the dream corpus — path fingerprint OR payload cwd both refuse.+ test('claude-cli self-transcript is skipped, not written to the corpus (#5413)', async () => {+ const projRoot = join(tmp, 'projects');+ const scratch = join(tmp, 'gbrain-claude-cli-cwd-4242');+ mkdirSync(scratch, { recursive: true });+ // The scratch session's rollout lives under the slugified scratch cwd.+ const transcript = seedTranscript(join(projRoot, '-tmp-gbrain-claude-cli-cwd-4242'), 's.jsonl', [+ userLine('extract facts from this page'),+ assistantLine('{"facts": []}'),+ ]);+ expect(+ await runHook(['session-end'], {+ stdin: JSON.stringify({ session_id: 'sess-self', transcript_path: transcript, cwd: scratch }),+ transcriptRoot: projRoot,+ }),+ ).toBe(0);+ const corpusDir = join(home(), 'transcripts', 'corpus');+ expect(existsSync(join(corpusDir, 'sess-self.txt'))).toBe(false);+ const hb = await lastHeartbeat();+ expect(hb?.outcome).toBe('ok');+ expect(hb?.segment).toBe('self_transcript');+ });++ test('claude-cli scratch cwd alone refuses the corpus write even with a clean path (#5413)', async () => {+ const projRoot = join(tmp, 'projects');+ const transcript = seedTranscript(join(projRoot, 'p1'), 's.jsonl', [userLine('ordinary looking turn')]);+ const scratch = join(tmp, 'gbrain-claude-cli-cwd-7777');+ mkdirSync(scratch, { recursive: true });+ expect(+ await runHook(['session-end'], {+ stdin: JSON.stringify({ session_id: 'sess-self2', transcript_path: transcript, cwd: scratch }),+ transcriptRoot: projRoot,+ }),+ ).toBe(0);+ expect(existsSync(join(home(), 'transcripts', 'corpus', 'sess-self2.txt'))).toBe(false);+ expect((await lastHeartbeat())?.segment).toBe('self_transcript');+ });+test('resumed session rewrite drops the stale .ingested/.in-progress sidecars so the sweep re-ingests', async () => {const projRoot = join(tmp, 'projects');const ws = join(tmp, 'ws');diff --git a/test/mcp-backup-nag.serial.test.ts b/test/mcp-backup-nag.serial.test.tsindex 1078ab90ec..c8ef6e643f 100644--- a/test/mcp-backup-nag.serial.test.ts+++ b/test/mcp-backup-nag.serial.test.ts@@ -57,6 +57,9 @@ const { __resetBackupRefreshForTests } = await import('../src/core/backup/covera// ── engine stub (records executeRaw SQL; never a real PGLite) ───────────────let rawCalls: string[] = [];+// A source listing. Search's own live read policy (the safe-chunk probe runs on+// every remote result) references `FROM sources read_source`; that is not one.+const BACKUP_SOURCES_QUERY = /\bfrom\s+sources\b(?!\s+read_source)/i;const engineStub = {kind: 'pglite',getConfig: async () => null,@@ -286,7 +289,7 @@ describe('stdio-gated refresher (TRUST PIN)', () => {// to land before asserting it never did.await new Promise((r) => setTimeout(r, 300));expect(existsSync(backupStatusPath())).toBe(false);- expect(rawCalls.filter((sql) => /\bfrom\s+sources\b/i.test(sql))).toEqual([]);+ expect(rawCalls.filter((sql) => BACKUP_SOURCES_QUERY.test(sql))).toEqual([]);});test('transport UNSET is fail-closed: no compute, no sources query', async () => {@@ -294,7 +297,7 @@ describe('stdio-gated refresher (TRUST PIN)', () => {await callSearch({ remote: true, transport: undefined });await new Promise((r) => setTimeout(r, 300));expect(existsSync(backupStatusPath())).toBe(false);- expect(rawCalls.filter((sql) => /\bfrom\s+sources\b/i.test(sql))).toEqual([]);+ expect(rawCalls.filter((sql) => BACKUP_SOURCES_QUERY.test(sql))).toEqual([]);});test("transport 'stdio' kicks the in-process refresher: absent cache gets computed + persisted", async () => {@@ -310,7 +313,7 @@ describe('stdio-gated refresher (TRUST PIN)', () => {expect(s!.overall).toBe('ok'); // zero sources, zero pages → nothing at riskexpect(s!.totals.assets).toBe(0);// The refresher DID walk the sources table on the stdio path.- expect(rawCalls.some((sql) => /\bfrom\s+sources\b/i.test(sql))).toBe(true);+ expect(rawCalls.some((sql) => BACKUP_SOURCES_QUERY.test(sql))).toBe(true);});test('attempt floor arms on the fresh-cache no-op path: a deleted cache is NOT recomputed within the hour', async () => {@@ -319,7 +322,7 @@ describe('stdio-gated refresher (TRUST PIN)', () => {saveBackupStatus(okStatus());await callSearch({ remote: true, transport: 'stdio' });await new Promise((r) => setTimeout(r, 100));- expect(rawCalls.filter((sql) => /\bfrom\s+sources\b/i.test(sql))).toEqual([]);+ expect(rawCalls.filter((sql) => BACKUP_SOURCES_QUERY.test(sql))).toEqual([]);// Delete the cache. A second stdio call within the hour is still a no-op// — the floor, not the cache, gates the attempt.@@ -327,13 +330,13 @@ describe('stdio-gated refresher (TRUST PIN)', () => {await callSearch({ remote: true, transport: 'stdio' });await new Promise((r) => setTimeout(r, 300));expect(existsSync(backupStatusPath())).toBe(false);- expect(rawCalls.filter((sql) => /\bfrom\s+sources\b/i.test(sql))).toEqual([]);+ expect(rawCalls.filter((sql) => BACKUP_SOURCES_QUERY.test(sql))).toEqual([]);// __resetBackupRefreshForTests clears the floor → the compute runs.__resetBackupRefreshForTests();await callSearch({ remote: true, transport: 'stdio' });const appeared = await waitFor(() => existsSync(backupStatusPath()), 2000);expect(appeared).toBe(true);- expect(rawCalls.some((sql) => /\bfrom\s+sources\b/i.test(sql))).toBe(true);+ expect(rawCalls.some((sql) => BACKUP_SOURCES_QUERY.test(sql))).toBe(true);});});diff --git a/test/mcp-expose.test.ts b/test/mcp-expose.test.tsindex fac6cb1e15..279b0b6259 100644--- a/test/mcp-expose.test.ts+++ b/test/mcp-expose.test.ts@@ -44,6 +44,8 @@ interface TailnetOpts {dnsName?: string | null;/** Self.CapMap: true → carries the Funnel capability, false → CapMap without it, undefined → no CapMap field. */funnelCapable?: boolean;+ /** Self.CapMap verbatim (overrides funnelCapable). */+ capMap?: Record<string, unknown>;/** Pre-existing root handlers: port → funnel flag. */existingHandlers?: Record<number, boolean>;publishStatus?: number | null;@@ -95,7 +97,7 @@ function fakeTailnet(o: TailnetOpts = {}): Fake {Version: '1.80.0', BackendState: state,Self: {DNSName: o.dnsName === undefined ? `${DNS}.` : (o.dnsName ?? ''), TailscaleIPs: ['100.64.0.1'],- ...(o.funnelCapable === undefined ? {} : { CapMap: o.funnelCapable ? { 'https://tailscale.com/cap/funnel': [] } : { 'https://tailscale.com/cap/is-admin': [] } }),+ ...(o.capMap ? { CapMap: o.capMap } : o.funnelCapable === undefined ? {} : { CapMap: o.funnelCapable ? { 'https://tailscale.com/cap/funnel': [] } : { 'https://tailscale.com/cap/is-admin': [] } }),},CurrentTailnet: { MagicDNSEnabled: true }, CertDomains: o.certDomains ?? [DNS],});@@ -442,6 +444,15 @@ describe('tailscale steps', () => {expect(await runMcpExpose(['--yes', '--funnel', '--json'], i.deps)).toBe(0);expect(checkOf(jsonDoc(i), 'tailscale.identity')?.detail).toContain('publish step decides');});+ test('--funnel publishes on a Tailscale 1.102 node whose CapMap carries `funnel` + `…/cap/funnel-ports` (#5599)', async () => {+ const f = fakeTailnet({ capMap: {+ 'default-auto-update': [], funnel: [], https: [],+ 'https://tailscale.com/cap/funnel-ports?ports=443,8443,10000': [],+ 'https://tailscale.com/cap/is-admin': [],+ } });+ expect(await runMcpExpose(['--yes', '--funnel', '--json'], f.deps)).toBe(0);+ expect(joinedCalls(f)).toContain(`${TS} funnel --bg 3131`);+ });test('publish failure is classified: https_not_enabled surfaces the admin URL, exit 1', async () => {const f = fakeTailnet({ publishStatus: 1, publishStderr: 'error: HTTPS certificates are not enabled for this tailnet; enable them in the admin console' });expect(await runMcpExpose(['--yes', '--json'], f.deps)).toBe(1);diff --git a/test/migrations-v0_13_1-grandfather.test.ts b/test/migrations-v0_13_1-grandfather.test.tsindex aa81689481..94e0d215a8 100644--- a/test/migrations-v0_13_1-grandfather.test.ts+++ b/test/migrations-v0_13_1-grandfather.test.ts@@ -11,7 +11,7 @@ import { join } from 'path';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { resetPgliteState } from './helpers/reset-pglite.ts';import { withEnv } from './helpers/with-env.ts';-import { phaseCGrandfather } from '../src/commands/migrations/v0_13_1.ts';+import { phaseCGrandfather, phaseDVerify } from '../src/commands/migrations/v0_13_1.ts';import { installFixtureChunks } from './helpers/page-projection.ts';import type { OrchestratorOpts } from '../src/commands/migrations/types.ts';@@ -174,4 +174,30 @@ describe('#1581 phaseCGrandfather (chunked, source-safe)', () => {expect((await fmOf('bulk/1199'))?.validate).toBe(false);expect(Date.now() - t0).toBeLessThan(30_000);});++ test('verify fails only for grandfathered pages still missing validate at the revision this run wrote', async () => {+ const home = mkdtempSync(join(tmpdir(), 'gf-verify-'));+ try {+ await seed('kept', {});+ await seed('reimported', {});+ const { detail } = await gf(home);+ expect(detail.grandfathered.map(page => page.id).sort()).toEqual(+ [(await engine.getPage('kept'))!.id, (await engine.getPage('reimported'))!.id].sort());+ // A connector re-import during the run replaces the page and drops the flag.+ await seed('reimported', { connector: 'sync' });+ expect(await phaseDVerify(engine, detail.grandfathered)).toMatchObject({ status: 'complete', detail: 'verified=1 rewritten_concurrently=1' });+ // A claimed write that never landed: the recorded revision is current and the flag is absent.+ await seed('unwritten', {});+ const unwritten = (await engine.getPage('unwritten'))!;+ const failed = await phaseDVerify(engine, [...detail.grandfathered, { id: unwritten.id, revision: unwritten.knowledge_revision! }]);+ expect(failed.status).toBe('failed');+ expect(failed.detail).toBe(`verified=1 rewritten_concurrently=1 missing_validate=1 (page#${unwritten.id})`);+ // A receipt without a revision cannot prove a rewrite, so the flag must be present.+ const kept = (await engine.getPage('kept'))!;+ expect(await phaseDVerify(engine, [{ id: kept.id, revision: null }, { id: unwritten.id, revision: null }])).toMatchObject({+ status: 'failed', detail: `verified=1 rewritten_concurrently=0 missing_validate=1 (page#${unwritten.id})` });+ } finally {+ rmSync(home, { recursive: true, force: true });+ }+ });});diff --git a/test/oauth-resource-canonical.test.ts b/test/oauth-resource-canonical.test.tsnew file mode 100644index 0000000000..1658f3a6d0--- /dev/null+++ b/test/oauth-resource-canonical.test.ts@@ -0,0 +1,202 @@+/**+ * #5222 — one RFC 8707 resource canonicalizer across /authorize, code+ * exchange and refresh, derived from the configured public URL.+ *+ * Pre-fix, /authorize stored any `resource` and minted a token bound to it,+ * then /mcp rejected that token forever (ChatGPT sends the origin root). Pins:+ * 1. the issuer origin (any trailing slash, default port, host case) is an+ * alias of the canonical /mcp resource at every stage;+ * 2. any other resource is refused with `invalid_target` naming the+ * accepted URL, at /authorize before a request is pending and at /token+ * without consuming the code;+ * 3. pre-resource grants and origin-bound grants minted before the fix keep+ * working and now yield /mcp-bound tokens.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { PGlite } from '@electric-sql/pglite';+import { vector } from '@electric-sql/pglite/vector';+import { pg_trgm } from '@electric-sql/pglite/contrib/pg_trgm';+import express from 'express';+import cookieParser from 'cookie-parser';+import { mcpAuthRouter } from '@modelcontextprotocol/sdk/server/auth/router.js';+import { InvalidTargetError } from '@modelcontextprotocol/sdk/server/auth/errors.js';+import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';+import { canonicalOAuthResource } from '../src/core/oauth-grants.ts';+import type { SqlQuery } from '../src/core/sql-query.ts';+import { PGLITE_SCHEMA_SQL } from '../src/core/pglite-schema.ts';+import { mountConfidentialOAuth, mountOAuthConsent } from '../src/commands/serve-http-oauth.ts';+import { generateToken, hashToken } from '../src/core/utils.ts';+import { pgliteOAuthTransaction, TEST_PKCE_CHALLENGE, TEST_PKCE_VERIFIER } from './helpers/oauth.ts';++const PUBLIC_URL = 'https://brain.example';+const CANONICAL = `${PUBLIC_URL}/mcp`;+const REDIRECT = 'https://client.example/callback';+const OWNER = 'gbrain_admin=synthetic-owner-session';++let db: PGlite;+let sql: SqlQuery;+let provider: GBrainOAuthProvider;+let server: ReturnType<ReturnType<typeof express>['listen']>;+let base: string;++beforeAll(async () => {+ db = new PGlite({ extensions: { vector, pg_trgm } });+ await db.exec(PGLITE_SCHEMA_SQL);+ sql = async (strings, ...values) => (await db.query<Record<string, unknown>>(+ strings.reduce((query, fragment, i) => query + fragment + (i < values.length ? `$${i + 1}` : ''), ''), values)).rows;+ provider = new GBrainOAuthProvider({ sql, transaction: pgliteOAuthTransaction(db), resourceUrl: new URL(CANONICAL) });+ const app = express();+ app.use(cookieParser());+ const pass: express.RequestHandler = (_req, _res, next) => next();+ const requireAdmin: express.RequestHandler = (req, res, next) => {+ if (req.cookies?.gbrain_admin !== 'synthetic-owner-session') { res.status(401).json({ error: 'unauthorized' }); return; }+ next();+ };+ mountConfidentialOAuth(app, provider, pass);+ mountOAuthConsent(app, provider, requireAdmin, pass);+ app.use(mcpAuthRouter({ provider, issuerUrl: new URL(PUBLIC_URL), scopesSupported: ['read', 'write'] }));+ server = app.listen(0, '127.0.0.1');+ await new Promise<void>(resolve => server.once('listening', resolve));+ const address = server.address();+ if (!address || typeof address === 'string') throw new Error('Expected TCP listener');+ base = `http://127.0.0.1:${address.port}`;+}, 30_000);++afterAll(async () => {+ if (server) { server.closeAllConnections(); await new Promise<void>(resolve => server.close(() => resolve())); }+ if (db) await db.close();+});++async function register(): Promise<string> {+ const { clientId } = await provider.registerClientManual('resource-client', ['authorization_code', 'refresh_token'], 'read write', [REDIRECT], 'default', undefined, 'none');+ return clientId;+}++function authorizeUrl(clientId: string, resource?: string): string {+ const query = new URLSearchParams({ client_id: clientId, response_type: 'code', redirect_uri: REDIRECT,+ code_challenge: TEST_PKCE_CHALLENGE, code_challenge_method: 'S256', scope: 'read write', state: 's1' });+ if (resource !== undefined) query.set('resource', resource);+ return `${base}/authorize?${query}`;+}++async function approve(clientId: string, resource?: string): Promise<{ code: string; requested: string | null }> {+ const response = await fetch(authorizeUrl(clientId, resource), { redirect: 'manual' });+ expect(response.status).toBe(302);+ const id = new URL(response.headers.get('location')!, base).searchParams.get('oauth_request')!;+ expect(id).toBeTruthy();+ const details = await (await fetch(`${base}/admin/api/oauth-requests/${id}`, { headers: { Cookie: OWNER } })).json() as any;+ const decided = await fetch(`${base}/admin/api/oauth-requests/${id}`, { method: 'POST',+ headers: { Cookie: OWNER, 'Content-Type': 'application/json' }, body: JSON.stringify({ csrf: details.csrf, decision: 'approve' }) });+ expect(decided.status).toBe(200);+ return { code: new URL((await decided.json() as any).redirectUrl).searchParams.get('code')!, requested: details.resource };+}++async function exchange(clientId: string, code: string, resource?: string): Promise<Response> {+ const body = new URLSearchParams({ grant_type: 'authorization_code', code, redirect_uri: REDIRECT, client_id: clientId, code_verifier: TEST_PKCE_VERIFIER });+ if (resource !== undefined) body.set('resource', resource);+ return fetch(`${base}/token`, { method: 'POST', body });+}++async function refresh(clientId: string, refreshToken: string, resource?: string): Promise<Response> {+ const body = new URLSearchParams({ grant_type: 'refresh_token', refresh_token: refreshToken, client_id: clientId });+ if (resource !== undefined) body.set('resource', resource);+ return fetch(`${base}/token`, { method: 'POST', body });+}++async function boundResource(accessToken: string): Promise<string | undefined> {+ return (await provider.verifyAccessToken(accessToken)).resource?.toString();+}++describe('canonicalOAuthResource (#5222)', () => {+ const canonical = new URL(CANONICAL);+ for (const alias of ['https://brain.example', 'https://brain.example/', 'https://BRAIN.example:443/', 'https://brain.example/mcp', 'https://brain.example/mcp/']) {+ test(`${alias} canonicalizes to ${CANONICAL}`, () => {+ expect(canonicalOAuthResource(alias, canonical).toString()).toBe(CANONICAL);+ });+ }+ for (const foreign of ['https://other.example/mcp', 'http://brain.example/mcp', 'https://brain.example:8443/mcp',+ 'https://brain.example/other', 'https://brain.example/mcp?x=1', 'https://brain.example/mcp#frag', 'https://[email protected]/mcp']) {+ test(`${foreign} is invalid_target naming the accepted resource`, () => {+ let thrown: unknown;+ try { canonicalOAuthResource(foreign, canonical); } catch (e) { thrown = e; }+ expect(thrown).toBeInstanceOf(InvalidTargetError);+ expect((thrown as Error).message).toContain(CANONICAL);+ });+ }+});++describe('OAuth resource lifecycle over HTTP (#5222)', () => {+ test('an origin-root resource yields a /mcp-bound token at authorize, exchange and refresh', async () => {+ const clientId = await register();+ const { code, requested } = await approve(clientId, `${PUBLIC_URL}/`);+ expect(requested).toBe(CANONICAL);+ const response = await exchange(clientId, code, `${PUBLIC_URL}/`);+ expect(response.status).toBe(200);+ const tokens = await response.json() as any;+ expect(await boundResource(tokens.access_token)).toBe(CANONICAL);+ const rotated = await refresh(clientId, tokens.refresh_token, PUBLIC_URL);+ expect(rotated.status).toBe(200);+ expect(await boundResource((await rotated.json() as any).access_token)).toBe(CANONICAL);+ });++ test('the canonical /mcp resource is unchanged', async () => {+ const clientId = await register();+ const { code, requested } = await approve(clientId, CANONICAL);+ expect(requested).toBe(CANONICAL);+ const tokens = await (await exchange(clientId, code)).json() as any;+ expect(await boundResource(tokens.access_token)).toBe(CANONICAL);+ });++ test('any other resource is refused at /authorize with invalid_target and no pending request', async () => {+ const clientId = await register();+ const response = await fetch(authorizeUrl(clientId, 'https://other.example/'), { redirect: 'manual' });+ expect(response.status).toBe(302);+ const location = new URL(response.headers.get('location')!);+ expect(location.origin + location.pathname).toBe(REDIRECT);+ expect(location.searchParams.get('error')).toBe('invalid_target');+ expect(location.searchParams.get('error_description')).toContain(CANONICAL);+ expect(location.searchParams.get('state')).toBe('s1');+ expect(await sql`SELECT * FROM oauth_codes WHERE client_id = ${clientId}`).toHaveLength(0);+ });++ test('a resource matching the request Host but not the configured public URL is refused', async () => {+ const clientId = await register();+ const response = await fetch(authorizeUrl(clientId, `${base}/mcp`), { redirect: 'manual' });+ expect(new URL(response.headers.get('location')!).searchParams.get('error')).toBe('invalid_target');+ });++ test('a foreign resource at /token is invalid_target and does not consume the code', async () => {+ const clientId = await register();+ const { code } = await approve(clientId, CANONICAL);+ const refused = await exchange(clientId, code, 'https://other.example/mcp');+ expect(refused.status).toBe(400);+ const body = await refused.json() as any;+ expect(body.error).toBe('invalid_target');+ expect(body.error_description).toContain(CANONICAL);+ const response = await exchange(clientId, code, PUBLIC_URL);+ expect(response.status).toBe(200);+ expect(await boundResource((await response.json() as any).access_token)).toBe(CANONICAL);+ });++ test('a pre-resource grant keeps working and binds the canonical resource when one is requested', async () => {+ const clientId = await register();+ const { code, requested } = await approve(clientId);+ expect(requested).toBeNull();+ const tokens = await (await exchange(clientId, code, `${PUBLIC_URL}/`)).json() as any;+ expect(await boundResource(tokens.access_token)).toBe(CANONICAL);+ const unbound = await approve(clientId);+ const legacy = await (await exchange(clientId, unbound.code)).json() as any;+ expect(await boundResource(legacy.access_token)).toBeUndefined();+ });++ test('an origin-bound refresh token minted before the fix refreshes to a /mcp-bound token', async () => {+ const clientId = await register();+ const legacyRefresh = generateToken('gbrain_rt_');+ const expires = Math.floor(Date.now() / 1000) + 3600;+ await sql`INSERT INTO oauth_tokens (token_hash, token_type, client_id, scopes, expires_at, resource)+ VALUES (${hashToken(legacyRefresh)}, ${'refresh'}, ${clientId}, ${'{"read","write"}'}, ${expires}, ${`${PUBLIC_URL}/`})`;+ const rotated = await refresh(clientId, legacyRefresh);+ expect(rotated.status).toBe(200);+ expect(await boundResource((await rotated.json() as any).access_token)).toBe(CANONICAL);+ });+});diff --git a/test/persistence-capacity.test.ts b/test/persistence-capacity.test.tsnew file mode 100644index 0000000000..68db0d11a5--- /dev/null+++ b/test/persistence-capacity.test.ts@@ -0,0 +1,48 @@+/**+ * #5470: configurable receipt retention, a compaction candidate filter that+ * cannot be starved by receipts with unfinished effects, the 80% cumulative+ * capacity warning, refusal hints naming the exact key, and defaults that+ * carry the reported workload for a year. Postgres arm: test/e2e/w5-persistence-postgres.test.ts.+ */+import { expect, test } from 'bun:test';+import { DEFAULT_JOURNAL_LIMITS } from '../src/core/persistence/model.ts';+import { JOURNAL_CONFIG_KEYS } from '../src/core/persistence/limits.ts';+import { KNOWN_CONFIG_KEYS } from '../src/core/config.ts';+import { capacityWarnsAndRefusalNamesTheKey, compactionSkipsUnfinishedReceipts } from './helpers/w5-scenarios.ts';++test('every journal config key is registered for `gbrain config set`', () => {+ expect(JOURNAL_CONFIG_KEYS).toHaveLength(11);+ for (const key of JOURNAL_CONFIG_KEYS) expect(KNOWN_CONFIG_KEYS).toContain(key);+});++test('cumulative principal and brain defaults carry 600 admissions a day for at least a year', () => {+ const perDay = 600, windowDays = 30, reserved = 16_384, retained = 4096;+ const bytesDays = (limit: number) => windowDays + (limit - perDay * windowDays * reserved) / (perDay * retained);+ expect(DEFAULT_JOURNAL_LIMITS.principalLifetimeIds / perDay).toBeGreaterThanOrEqual(365);+ expect(DEFAULT_JOURNAL_LIMITS.brainLifetimeIds / perDay).toBeGreaterThanOrEqual(365);+ expect(bytesDays(DEFAULT_JOURNAL_LIMITS.principalTerminalBytes)).toBeGreaterThanOrEqual(365);+ expect(bytesDays(DEFAULT_JOURNAL_LIMITS.brainTerminalBytes)).toBeGreaterThanOrEqual(365);+});++test('configured retention compacts receipts past a backlog of unfinished effects', () => compactionSkipsUnfinishedReceipts(), 180_000);+test('doctor warns at 80% of a cumulative cap and the refusal names the key and a value', () => capacityWarnsAndRefusalNamesTheKey(), 120_000);++test('the one-year capacity hint uses the sampled interval, not a one-day floor', async () => {+ const { oneYearCapacity } = await import('../src/core/persistence/limits.ts');+ const engine = { executeRaw: async (sql: string) => sql.includes('persistence_requests') ? [{ admissions: 1000, age_seconds: 8640 }] : [] };+ expect(await oneYearCapacity(engine as never, 'principal:local_cli:example', 'LifetimeIds', 250_000, 250_000)).toBe(250_000 + 10_000 * 365);+});++test('doctor emits one command per brain-wide key with the largest value any principal needs', async () => {+ const { checkPersistenceCapacity } = await import('../src/commands/doctor/checks/persistence-capacity.ts');+ const counter = (key: string) => ({ key, outstanding_count: '0', intent_bytes: '0', lifetime_ids: '9', terminal_bytes: '0', recovery_bytes: '0' });+ const engine = { executeRaw: async (sql: string, params: unknown[] = []) => {+ if (sql.includes('FROM persistence_counters')) return [counter('principal:local_cli:fast'), counter('principal:local_cli:slow')];+ if (sql.includes("LIKE 'persistence.limits.%'")) return [{ key: 'persistence.limits.principal_lifetime_ids', value: '10' }];+ if (sql.includes('persistence_requests')) return [{ admissions: 1000, age_seconds: params[1] === 'fast' ? 8640 : 864_000 }];+ return [];+ } };+ const check = await checkPersistenceCapacity(engine as never);+ expect(check.status).toBe('warn');+ expect((check.details as { commands: string[] }).commands).toEqual(['gbrain config set persistence.limits.principal_lifetime_ids 3650009']);+});diff --git a/test/persistence-cli-delegation.test.ts b/test/persistence-cli-delegation.test.tsindex 64db5e8c05..2212fe4fe0 100644--- a/test/persistence-cli-delegation.test.ts+++ b/test/persistence-cli-delegation.test.ts@@ -73,7 +73,8 @@ describe('CLI-only persistence delegation before engine connection', () => {expect(calls[0].params).toEqual(calls[1].params);expect(calls[0].operation).toBe('capture');expect(calls[0].params).toMatchObject({ content: raw, request_id: ID, who: 'example-person', what: 'met', type: 'event',- source_kind: 'capture-cli', source_uri: `file://${file}` });+ source_kind: 'capture-cli', local_file: file });+ expect(calls[0].params).not.toHaveProperty('source_uri');expect(calls[0].params).not.toHaveProperty('slug');expect(calls[0].params.content).not.toContain('captured_at:');expect(calls[0].routing.source).toBe('client-source');diff --git a/test/persistence-consumer-idle.test.ts b/test/persistence-consumer-idle.test.tsnew file mode 100644index 0000000000..2186e7b761--- /dev/null+++ b/test/persistence-consumer-idle.test.ts@@ -0,0 +1,150 @@+/** #5370: an idle consumer probes once per tick, backs off to its cap, and wakes on same-process admission. */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { PersistenceConsumer } from '../src/core/persistence/consumer.ts';+import { admitWrite, getWriteRequestById } from '../src/core/persistence/journal.ts';+import { disposePersistenceConsumer, startPersistenceConsumer, waitForWrite } from '../src/core/persistence/service.ts';+import { admission, fixtures, initializeFixtures, prepared, selectFixtureHost, type HarnessConfig } from '../scripts/persistence/harness.ts';+import { withEnv } from './helpers/with-env.ts';+import { waitFor } from './helpers/wait-for.ts';++const home = mkdtempSync(join(tmpdir(), 'gbrain-consumer-idle-'));+const config: HarnessConfig = {+ kind: 'pglite', root: home, dataDir: join(home, 'data'), hostId: randomUUID(),+ seed: 5370, schedules: 0, operations: 0, sourceIds: ['consumer-idle'], principalIds: [randomUUID()],+};+const env = { GBRAIN_HOME: home, GBRAIN_PERSISTENCE_FIXTURE_HOME: home };+let engine: PGLiteEngine;++beforeAll(async () => withEnv(env, async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ selectFixtureHost(config.hostId);+ await initializeFixtures(engine, config);+}), 120_000);++afterAll(async () => {+ await engine.disconnect();+ rmSync(home, { recursive: true, force: true });+});++function counting(target: PGLiteEngine) {+ const statements: string[] = [];+ const proxy = new Proxy(target, { get(obj, key) {+ if (key === 'executeRaw') return (sql: string, ...rest: unknown[]) => {+ statements.push(sql);+ return (obj.executeRaw as (...args: unknown[]) => Promise<unknown>)(sql, ...rest);+ };+ const value = Reflect.get(obj, key);+ return typeof value === 'function' ? value.bind(obj) : value;+ } });+ return { proxy, statements };+}++async function settled(consumer: PersistenceConsumer): Promise<void> {+ const workers = consumer as unknown as Record<string, Promise<unknown> | undefined>;+ await Promise.all(['projectionWorker', 'effectsWorker', 'topologyWorker', 'maintenanceWorker'].map(name => workers[name]));+}++test('an idle tick runs one probe statement instead of the worker fan-out', async () => withEnv(env, async () => {+ const { proxy, statements } = counting(engine);+ const consumer = new PersistenceConsumer(proxy, { engine: 'pglite' }, async () => { throw new Error('no work expected'); },+ { hostId: config.hostId, onError: () => {} });+ try {+ await consumer.tick();+ await settled(consumer);+ await consumer.tick();+ await settled(consumer);+ statements.length = 0;+ for (let i = 0; i < 5; i++) { await consumer.tick(); await settled(consumer); }+ expect(statements.length).toBe(5);+ } finally { await consumer.stop(); }+}));++test('a queued request behind another process\'s running head does not trigger the fan-out', async () => withEnv(env, async () => {+ const sources = await fixtures(engine, config);+ const head = await admitWrite(engine, admission(config, sources[0], `fifo-head-${randomUUID().slice(0, 8)}`, 'head'));+ const follower = await admitWrite(engine, admission(config, sources[0], `fifo-follower-${randomUUID().slice(0, 8)}`, 'follower'));+ await engine.executeRaw(`UPDATE persistence_requests SET state='running', execution_token=gen_random_uuid(),+ claim_expires_at=now()+interval '10 minutes' WHERE id=$1::uuid`, [head.id]);+ const { proxy, statements } = counting(engine);+ const consumer = new PersistenceConsumer(proxy, { engine: 'pglite' }, async () => { throw new Error('the follower is not claimable'); },+ { hostId: config.hostId, onError: () => {} });+ try {+ await consumer.tick();+ await settled(consumer);+ statements.length = 0;+ for (let i = 0; i < 3; i++) { await consumer.tick(); await settled(consumer); }+ expect(statements.length).toBe(3);+ } finally {+ await consumer.stop();+ await engine.executeRaw(`UPDATE persistence_requests SET state='cancelled', execution_token=NULL, claim_expires_at=NULL+ WHERE id = ANY($1::uuid[])`, [[head.id, follower.id]]);+ }+}));++test('idle polling backs off to the cap, then a wake runs a full tick immediately', async () => withEnv(env, async () => {+ const { proxy, statements } = counting(engine);+ const consumer = new PersistenceConsumer(proxy, { engine: 'pglite' }, async () => { throw new Error('no work expected'); },+ { hostId: config.hostId, pollMs: 20, idleMaxMs: 160, onError: () => {} });+ const refreshes = () => statements.filter(sql => sql.startsWith('SELECT brain_id,enabled FROM persistence_brain')).length;+ consumer.start();+ try {+ await Bun.sleep(2_000);+ // 20 ms polling for 2 s would be ~100 ticks; doubling to a 160 ms cap is ~15.+ const ticks = statements.length;+ expect(ticks).toBeLessThan(40);+ const full = refreshes();+ consumer.wake();+ await waitFor(() => refreshes() > full, { timeoutMs: 1_000 });+ } finally { await consumer.stop(); }+}));++test('concurrent wakes during a tick coalesce into one follow-up tick', async () => {+ const release = Promise.withResolvers<void>();+ const consumer = new PersistenceConsumer(engine, { engine: 'pglite' }, async () => { throw new Error('no work expected'); },+ { hostId: config.hostId, pollMs: 60_000 });+ const scheduler = consumer as unknown as { doTick(): Promise<void> };+ let ticks = 0;+ scheduler.doTick = async () => { if (++ticks === 1) await release.promise; };+ try {+ const active = consumer.tick();+ for (let i = 0; i < 10; i++) consumer.wake();+ release.resolve();+ await active;+ await waitFor(() => ticks === 2, { timeoutMs: 5_000 });+ await Bun.sleep(100);+ expect(ticks).toBe(2);+ } finally { await consumer.stop(); }+});++test('a write admitted by another process is published within the idle cap', async () => withEnv(env, async () => {+ const sources = await fixtures(engine, config);+ const consumer = new PersistenceConsumer(engine, { engine: 'pglite' }, async (_e, row) => prepared(row, sources),+ { hostId: config.hostId, pollMs: 20, idleMaxMs: 300 });+ consumer.start();+ try {+ await Bun.sleep(1_000);+ const started = performance.now();+ const row = await admitWrite(engine, admission(config, sources[0], `cross-process-${randomUUID().slice(0, 8)}`, 'body'));+ await waitFor(async () => (await getWriteRequestById(engine, row.id))?.state === 'committed', { timeoutMs: 5_000 });+ expect(performance.now() - started).toBeLessThan(300 + 3_000);+ } finally { await consumer.stop(); }+}));++test('waiting on an admitted write wakes the resident consumer', async () => withEnv(env, async () => {+ const consumer = startPersistenceConsumer(engine, { engine: 'pglite' });+ let wakes = 0;+ const wake = consumer.wake.bind(consumer);+ consumer.wake = () => { wakes++; wake(); };+ const row = { id: randomUUID(), request_id: randomUUID(), state: 'queued' } as import('../src/core/persistence/model.ts').WriteRequest;+ try {+ await waitForWrite(engine, row, { engine: 'pglite' }, 50);+ expect(wakes).toBe(1);+ } finally { await disposePersistenceConsumer(engine); }+}));diff --git a/test/persistence-diagnostics.test.ts b/test/persistence-diagnostics.test.tsindex c44e797219..1d6bbb19f8 100644--- a/test/persistence-diagnostics.test.ts+++ b/test/persistence-diagnostics.test.ts@@ -2,7 +2,7 @@ import { afterAll, beforeAll, expect, test } from 'bun:test';import { randomUUID } from 'node:crypto';import type { BrainEngine } from '../src/core/engine.ts';import { PGLiteEngine } from '../src/core/pglite-engine.ts';-import { runMigrations } from '../src/core/migrate.ts';+import { LATEST_VERSION, runMigrations } from '../src/core/migrate.ts';import type { OperationContext } from '../src/core/ops/contract.ts';import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';import { submissionAuthority } from '../src/core/persistence/authority.ts';@@ -78,6 +78,7 @@ test('fresh and upgraded engines agree on the database-only pending index', asynexpect(fresh.indexdef).toContain('source_incarnation, sequence');expect(fresh.indexdef).toContain('worktree_id IS NULL');await engine.executeRaw('DROP INDEX persistence_requests_database_pending');+ await engine.executeRaw('DROP INDEX persistence_effects_parked');if (engine.kind === 'postgres') {const held = Promise.withResolvers<void>(), release = Promise.withResolvers<void>();const holding = engine.transaction(async tx => {@@ -96,11 +97,14 @@ test('fresh and upgraded engines agree on the database-only pending index', asyn} finally { abort.abort(); release.resolve(); await holding; await interrupted; }}await engine.setConfig('version', '164');- expect(await runMigrations(engine)).toEqual({ applied: 5, current: 169 });+ expect(LATEST_VERSION).toBe(173);+ expect(await runMigrations(engine)).toEqual({ applied: 9, current: 173 });const [upgraded] = await engine.executeRaw<{ indexdef: string }>("SELECT indexdef FROM pg_indexes WHERE indexname='persistence_requests_database_pending'");expect(upgraded.indexdef).toBe(fresh.indexdef);- expect(await engine.getConfig('version')).toBe('169');+ const [parked] = await engine.executeRaw<{ indexdef: string }>("SELECT indexdef FROM pg_indexes WHERE indexname='persistence_effects_parked'");+ expect(parked.indexdef).toContain('parked');+ expect(await engine.getConfig('version')).toBe('173');}}, 15000);diff --git a/test/persistence-effect-parking.test.ts b/test/persistence-effect-parking.test.tsnew file mode 100644index 0000000000..0aeae63c12--- /dev/null+++ b/test/persistence-effect-parking.test.ts@@ -0,0 +1,13 @@+/**+ * #5612: a Git or withdrawal target parks after five consecutive execution+ * failures instead of retrying forever, a scan moves past it, contention never+ * counts, and `retry-effects` authorizes one more attempt per parked target.+ * Postgres arm: test/e2e/w5-persistence-postgres.test.ts.+ */+import { test } from 'bun:test';+import { failuresDoNotCarryToAnotherTarget, healthyScanAndContentionNeverPark, scanParksOneTargetAndContinues, singleTargetParksAndRetries } from './helpers/w5-scenarios.ts';++test('a failing Git target parks after five failures and commits after an explicit retry', () => singleTargetParksAndRetries(), 120_000);+test('a Git scan parks its failing target, continues, and retries only that target', () => scanParksOneTargetAndContinues(), 120_000);+test('a healthy multi-page scan and worktree contention never park', () => healthyScanAndContentionNeverPark(), 120_000);+test('failures on a vanished target do not count against the next target', () => failuresDoNotCarryToAnotherTarget(), 120_000);diff --git a/test/persistence-effects.test.ts b/test/persistence-effects.test.tsindex bead07be83..fd060cbc42 100644--- a/test/persistence-effects.test.ts+++ b/test/persistence-effects.test.ts@@ -2,7 +2,7 @@ import { afterAll, beforeAll, expect, test } from 'bun:test';import { randomUUID } from 'node:crypto';import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';-import { join } from 'node:path';+import { dirname, join } from 'node:path';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import type { OperationContext } from '../src/core/ops/contract.ts';import { claimWorktree, prepareWriterTransfer } from '../src/core/persistence/ownership.ts';@@ -18,6 +18,8 @@ import { recordFactWithdrawal } from '../src/core/facts/withdrawal.ts';import { parseFactsFence, upsertFactRow } from '../src/core/facts-fence.ts';import { serializePageToMarkdown } from '../src/core/markdown.ts';import { installPageProjection, readProjectionSnapshot } from '../src/core/page-state/projections.ts';+import { durableGitRepo } from './helpers/git-publication.ts';+import { declarePersistenceProtocol } from '../src/core/persistence/protocol.ts';let engine: PGLiteEngine;const roots: string[] = [];@@ -29,28 +31,29 @@ beforeAll(async () => {}, 120_000);afterAll(async () => { await engine.disconnect(); for (const root of roots) rmSync(root, { recursive: true, force: true }); });-async function fixture(body = 'Before') {+async function fixture(body = 'Before', slug = 'page') {const root = mkdtempSync(join(tmpdir(), 'gbrain-effects-')); roots.push(root);const sourceId = `effects-${randomUUID()}`;await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);const binding = await claimWorktree(engine, sourceId, root, hostId);- await engine.putPage('page', page(body), { sourceId });- const snapshot = (await engine.readPageSnapshot('page', { sourceId }))!;- const file = join(root, 'page.md'); writeFileSync(file, serializePageToMarkdown(snapshot.page, snapshot.tags));+ await engine.putPage(slug, page(body), { sourceId });+ const snapshot = (await engine.readPageSnapshot(slug, { sourceId }))!;+ const file = join(root, `${slug}.md`); mkdirSync(dirname(file), { recursive: true });+ writeFileSync(file, serializePageToMarkdown(snapshot.page, snapshot.tags));const ctx: OperationContext = { engine, config, remote: false, dryRun: false, sourceId, logger: { info() {}, warn() {}, error() {} } };- const authority = await submissionAuthority(ctx, 'put_page', sourceId, binding.source_incarnation, 'page');- return { root, file, sourceId, binding, snapshot, authority };+ const authority = await submissionAuthority(ctx, 'put_page', sourceId, binding.source_incarnation, slug);+ return { root, file, sourceId, binding, snapshot, authority, slug };}async function admit(f: Awaited<ReturnType<typeof fixture>>) {return admitWrite(engine, { principal: f.authority.principal, authority: f.authority, operation: 'put_page', sourceId: f.sourceId,- sourceIncarnation: f.binding.source_incarnation, slug: 'page', pageId: f.snapshot.page.id, requestId: randomUUID(),+ sourceIncarnation: f.binding.source_incarnation, slug: f.slug, pageId: f.snapshot.page.id, requestId: randomUUID(),callerIntent: { content: 'After' }, intent: { content: 'After' }, worktreeId: f.binding.worktree_id, topologyGeneration: f.binding.topology_generation });}async function withdraw(f: Awaited<ReturnType<typeof fixture>>, opts: { subjectless?: boolean } = {}) {const row = await admit(f);// Withdrawals are entity-scoped; a subjectless fact withdraws source-wide.const [fact] = await engine.executeRaw<{ id: number }>(`INSERT INTO facts(source_id,entity_slug,fact,source,visibility)- VALUES($1,$2,'Withdraw this claim','test conversation','world') RETURNING id`, [f.sourceId, opts.subjectless ? null : 'page']);+ VALUES($1,$2,'Withdraw this claim','test conversation','world') RETURNING id`, [f.sourceId, opts.subjectless ? null : f.slug]);await engine.transaction(async tx => {await recordFactWithdrawal(tx, Number(fact.id), f.sourceId, false, { requestId: row.id });await completeWrite(tx, row, 'committed', { status: 'forgotten' });@@ -147,6 +150,72 @@ test('missing withdrawal files materialize and advance mirror and Git scans withexpect((await getWriteRequestById(engine, row.id))!.state).toBe('committed');});+test('withdrawal redacts a present db_only cache file and keeps it out of a durable Git worktree', async () => {+ const f = await fixture(body(), 'conversations/page');+ writeFileSync(join(f.root, 'gbrain.yml'), 'storage:\n db_only:\n - conversations/\n');+ writeFileSync(join(f.root, '.gitignore'), 'conversations/\n');+ durableGitRepo(f.root, ['.gitignore', 'gbrain.yml']);+ const row = await withdraw(f); await onlyEffects(row.id);+ await runPersistenceEffects(engine, config, { hostId, limit: 10 });+ expect(parseFactsFence(readFileSync(f.file, 'utf8')).facts.filter(fact => fact.active)).toHaveLength(0);+ expect(await engine.executeRaw("SELECT kind,state,error_code FROM persistence_effects WHERE request_id=$1::uuid AND kind<>'embedding' ORDER BY kind", [row.id])).toEqual([+ { kind: 'git', state: 'committed', error_code: null },+ { kind: 'withdrawal-mirror', state: 'committed', error_code: null }]);+ expect(git(f.root, ['log', '--name-only', '--pretty=format:'])).not.toContain('conversations');+});++test('a withdrawal Git scan parks a failing target after five failures and still commits the rest (#5612)', async () => {+ const f = await fixture(body(), 'aa/page');+ await engine.putPage('page', page(body()), { sourceId: f.sourceId });+ const later = (await engine.readPageSnapshot('page', { sourceId: f.sourceId }))!;+ writeFileSync(join(f.root, 'page.md'), serializePageToMarkdown(later.page, later.tags));+ writeFileSync(join(f.root, '.gitignore'), 'aa/\n');+ durableGitRepo(f.root, ['.gitignore', 'page.md']);+ const row = await withdraw(f, { subjectless: true }); await onlyEffects(row.id);+ await engine.executeRaw("UPDATE persistence_effects SET next_attempt_at=now()+interval '1 hour' WHERE request_id=$1::uuid AND kind<>'withdrawal-mirror'", [row.id]);+ await runPersistenceEffects(engine, config, { hostId, limit: 3 });+ const effect = async () => (await engine.executeRaw<{ state: string; error_code: string | null; data: Record<string, unknown> }>(+ "SELECT state,error_code,data FROM persistence_effects WHERE request_id=$1::uuid AND kind='git'", [row.id]))[0];+ for (let attempt = 0; attempt < 7; attempt++) {+ await engine.executeRaw("UPDATE persistence_effects SET next_attempt_at=now() WHERE request_id=$1::uuid AND kind='git'", [row.id]);+ await runPersistenceEffects(engine, config, { hostId, limit: 1 });+ }+ expect(await effect()).toMatchObject({ state: 'failed', error_code: 'targets_parked', data: { after_slug: 'page',+ parked: [{ slug: 'aa/page', error_code: 'git_target_unsafe' }] } });+ expect(git(f.root, ['log', '-1', '--name-only', '--pretty=format:'])).toBe('page.md');+ expect(await publicEffectsForRequest(engine, row.id)).toContainEqual({ kind: 'git', state: 'failed', reason: 'targets_parked' });+});++test('a parked withdrawal mirror target retries through physical publication without rewinding (#5612)', async () => {+ const f = await fixture(body());+ await engine.putPage('z-later', page(body()), { sourceId: f.sourceId });+ const later = (await engine.readPageSnapshot('z-later', { sourceId: f.sourceId }))!;+ const laterFile = join(f.root, 'z-later.md'); writeFileSync(laterFile, serializePageToMarkdown(later.page, later.tags));+ const row = await withdraw(f, { subjectless: true }); await onlyEffects(row.id);+ const mirror = async () => (await engine.executeRaw<{ id: number; state: string; error_code: string | null; data: Record<string, unknown> }>(+ "SELECT id,state,error_code,data FROM persistence_effects WHERE request_id=$1::uuid AND kind='withdrawal-mirror'", [row.id]))[0];+ const attempt = async () => {+ await engine.executeRaw("UPDATE persistence_effects SET next_attempt_at=CASE WHEN kind='withdrawal-mirror' THEN now() ELSE now()+interval '1 hour' END WHERE request_id=$1::uuid", [row.id]);+ await runPersistenceEffects(engine, config, { hostId, limit: 1 });+ };+ await engine.setConfig('persistence.limits.worktree_recovery_bytes', '1');+ try { for (let i = 0; i < 11; i++) await attempt(); }+ finally { await engine.executeRaw("DELETE FROM config WHERE key='persistence.limits.worktree_recovery_bytes'"); }+ expect(await mirror()).toMatchObject({ state: 'failed', error_code: 'targets_parked', data: { parked: [+ { slug: 'page', error_code: 'request_too_large' }, { slug: 'z-later', error_code: 'request_too_large' }] } });+ const [effect] = await engine.executeRaw<{ id: number; data: Record<string, unknown> }>('SELECT id,data FROM persistence_effects WHERE id=$1', [(await mirror()).id]);+ const { parked: _parked, ...data } = effect.data;+ await engine.transaction(async tx => {+ await declarePersistenceProtocol(tx);+ await tx.executeRaw("UPDATE persistence_effects SET state='queued',error_code=NULL,data=$2::text::jsonb WHERE id=$1",+ [effect.id, JSON.stringify({ ...data, retry_slugs: ['page', 'z-later'], target_failures: 4, retried: 1 })]);+ });+ for (let i = 0; i < 3; i++) await attempt();+ expect(await mirror()).toMatchObject({ state: 'committed', error_code: null, data: { after_slug: 'z-later' } });+ expect((await mirror()).data.retry_slugs).toBeUndefined();+ for (const file of [f.file, laterFile]) expect(parseFactsFence(readFileSync(file, 'utf8')).facts.filter(fact => fact.active)).toHaveLength(0);+});+test('configured recovery capacity refuses file mutation without undoing withdrawal', async () => {const f = await fixture(body()); const original = readFileSync(f.file, 'utf8'); const row = await withdraw(f); await onlyEffects(row.id);await engine.setConfig('persistence.limits.worktree_recovery_bytes', '1');diff --git a/test/persistence-git-subdir-origin.test.ts b/test/persistence-git-subdir-origin.test.tsnew file mode 100644index 0000000000..b4afe1b73c--- /dev/null+++ b/test/persistence-git-subdir-origin.test.ts@@ -0,0 +1,178 @@+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { execFileSync } from 'node:child_process';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';+import { operationsByName } from '../src/core/operations.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { registerLocalWriter, withVerifiedLocalRegistration, type LocalRegistration } from '../src/core/persistence/identity.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { withEnv } from './helpers/with-env.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';++// #5610 / #5398 (Linux residual): a source registered at a git subdirectory and+// pinned to slug_root_mode=source-root stores source-relative origins on sync.+// Write-through used to mint git-root-relative origins, so every page created by+// put_page wedged the next managed sync with page_identity_changed.++const home = mkdtempSync(join(tmpdir(), 'gbrain-subdir-origin-'));+const engines: BrainEngine[] = [];+let closePostgres: (() => Promise<void>) | undefined;+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+const commit = (root: string, message = 'content') => {+ git(root, 'add', '-A'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message);+};+beforeAll(async () => {+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);+ 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, files: Record<string, string>, opts: { managed?: boolean; scope?: string; pinned?: boolean } = {}) {+ const scope = opts.scope ?? 'brain';+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ const id = `subdir-${randomUUID().slice(0, 12)}`, repo = join(home, id), root = join(repo, scope);+ mkdirSync(root, { recursive: true }); git(repo, 'init', '-q');+ writeFileSync(join(repo, 'README.md'), 'Repository outside the source.\n');+ for (const [path, body] of Object.entries(files)) { mkdirSync(dirname(join(root, path)), { recursive: true }); writeFileSync(join(root, path), body); }+ commit(repo, 'seed');+ await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,$3::text::jsonb)',+ [id, root, JSON.stringify(opts.pinned === false ? {} : { slug_root_mode: 'source-root' })]);+ await claimWorktree(engine, id, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=$1 WHERE singleton=1', [opts.managed !== false]);+ const registration = await registerLocalWriter(engine, 'cli');+ const ctx: OperationContext = { engine, remote: false, sourceId: id, config: { engine: engine.kind, embedding_disabled: true } as never, dryRun: false,+ logger: { info() {}, warn() {}, error() {} } };+ return { id, repo, root, registration, ctx };+}+type Fixture = Awaited<ReturnType<typeof fixture>>;+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 put(engine: BrainEngine, f: Fixture, slug: string, body: string) {+ return local(engine, f.registration, () => operationsByName.put_page!.handler(f.ctx, { source_id: f.id, slug, request_id: randomUUID(),+ content: `---\ntype: note\ntitle: ${slug}\n---\n${body}\n` })) as Promise<Record<string, unknown>>;+}+const sourcePath = async (engine: BrainEngine, f: Fixture, slug: string) =>+ (await engine.executeRaw<{ source_path: string | null }>('SELECT source_path FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL', [f.id, slug]))[0]?.source_path;+const sync = (engine: BrainEngine, f: Fixture, full = false) => performManagedSync(engine, { sourceId: f.id, noPull: true, noEmbed: true, full });++test('managed put_page mints the source-relative origin and the next sync succeeds', async () => isolated(async engine => {+ const f = await fixture(engine, { 'notes/existing.md': '---\ntitle: Existing\n---\nA synced observation.\n' });+ expect((await sync(engine, f)).status).toBe('first_sync');+ expect(await sourcePath(engine, f, 'notes/existing')).toBe('notes/existing.md');+ expect((await put(engine, f, 'notes/new-person', 'A new observation written through the coordinator.')).state).toBe('committed');+ expect(existsSync(join(f.root, 'notes/new-person.md'))).toBe(true);+ expect(await sourcePath(engine, f, 'notes/new-person')).toBe('notes/new-person.md');+ commit(f.repo, 'commit the written page');+ expect((await sync(engine, f)).status).toBe('synced');+ expect(await sourcePath(engine, f, 'notes/new-person')).toBe('notes/new-person.md');+ expect((await sync(engine, f, true)).status).not.toBe('failed');+ expect(await sourcePath(engine, f, 'notes/new-person')).toBe('notes/new-person.md');+}), 120_000);++test('legacy git-root origins sync, are repaired in place on import, survive full sync and delete cleanly', async () => isolated(async engine => {+ const f = await fixture(engine, { 'notes/edited.md': '---\ntitle: Edited\n---\nOriginal edited body.\n',+ 'notes/kept.md': '---\ntitle: Kept\n---\nKept body.\n', 'notes/removed.md': '---\ntitle: Removed\n---\nRemoved body.\n' });+ expect((await sync(engine, f)).status).toBe('first_sync');+ for (const slug of ['notes/edited', 'notes/kept', 'notes/removed']) {+ await engine.executeRaw('UPDATE pages SET source_path=$3 WHERE source_id=$1 AND slug=$2', [f.id, slug, `brain/${slug}.md`]);+ }+ writeFileSync(join(f.root, 'notes/edited.md'), '---\ntitle: Edited\n---\nA newer committed body.\n');+ rmSync(join(f.root, 'notes/removed.md'));+ commit(f.repo, 'edit and remove');+ const result = await sync(engine, f);+ expect(result.status).toBe('synced');+ expect(await sourcePath(engine, f, 'notes/edited')).toBe('notes/edited.md');+ expect((await engine.getPage('notes/edited', { sourceId: f.id }))?.compiled_truth).toContain('A newer committed body.');+ expect(await engine.getPage('notes/removed', { sourceId: f.id })).toBeNull();+ expect(await sourcePath(engine, f, 'notes/kept')).toBe('brain/notes/kept.md');+ expect((await sync(engine, f, true)).status).not.toBe('failed');+ expect(await engine.getPage('notes/kept', { sourceId: f.id })).not.toBeNull();+ expect(readFileSync(join(f.root, 'notes/kept.md'), 'utf8')).toContain('Kept body.');+}), 120_000);++test('a legacy origin that could name two files refuses with a reason id instead of guessing', async () => isolated(async engine => {+ const f = await fixture(engine, { 'a.md': '---\ntitle: A\n---\nRoot body.\n', 'sub/a.md': '---\ntitle: Nested\n---\nNested body.\n' }, { scope: 'sub' });+ expect((await sync(engine, f)).status).toBe('first_sync');+ await engine.executeRaw("UPDATE pages SET source_path='sub/a.md' WHERE source_id=$1 AND slug='a'", [f.id]);+ await engine.executeRaw("UPDATE pages SET source_path=NULL WHERE source_id=$1 AND slug='sub/a'", [f.id]);+ writeFileSync(join(f.root, 'a.md'), '---\ntitle: A\n---\nChanged root body.\n');+ commit(f.repo, 'change root file');+ const refused = await sync(engine, f).then(() => null, (error: unknown) => error as { code?: string; detail?: string });+ expect(refused).toMatchObject({ code: 'page_identity_changed', detail: 'ambiguous_source_path' });+ expect((await engine.getPage('a', { sourceId: f.id }))?.compiled_truth).toContain('Root body.');+}), 120_000);++test.each([true, false])('write-through put_page on an unmanaged subdirectory source binds the source-relative origin (pinned=%p)', async pinned => isolated(async engine => {+ const f = await fixture(engine, { 'notes/existing.md': '---\ntitle: Existing\n---\nA synced observation.\n' }, { managed: false, pinned });+ await put(engine, f, 'notes/unmanaged-new', 'A new observation written through write-through.');+ expect(existsSync(join(f.root, 'notes/unmanaged-new.md'))).toBe(true);+ expect(await sourcePath(engine, f, 'notes/unmanaged-new')).toBe('notes/unmanaged-new.md');+}), 120_000);++test('an unpinned subdirectory source whose pages carry the Git prefix keeps minting the Git-root origin', async () => isolated(async engine => {+ const f = await fixture(engine, {}, { managed: false, pinned: false });+ await engine.putPage('brain/notes/prefixed', { type: 'note', title: 'Prefixed', compiled_truth: 'Legacy prefixed page.' }, { sourceId: f.id });+ await put(engine, f, 'notes/git-root-new', 'A new observation in a Git-root namespace.');+ expect(await sourcePath(engine, f, 'notes/git-root-new')).toBe('brain/notes/git-root-new.md');+}), 120_000);++test('a page whose source-relative path repeats the scope directory is edited and deleted in its own file', async () => isolated(async engine => {+ const f = await fixture(engine, { 'notes/existing.md': '---\ntitle: Existing\n---\nA synced observation.\n' }, { scope: 'docs' });+ expect((await sync(engine, f)).status).toBe('first_sync');+ const sibling = join(f.root, 'a.md');+ expect((await put(engine, f, 'docs/a', 'The nested page body.')).state).toBe('committed');+ expect(await sourcePath(engine, f, 'docs/a')).toBe('docs/a.md');+ const nested = join(f.root, 'docs/a.md');+ writeFileSync(sibling, readFileSync(nested, 'utf8'));+ const siblingBytes = readFileSync(sibling, 'utf8');+ const snapshot = (await engine.readPageSnapshot('docs/a', { sourceId: f.id }))!;+ const edited = await local(engine, f.registration, () => operationsByName.put_page!.handler(f.ctx, { source_id: f.id, slug: 'docs/a',+ request_id: randomUUID(), expected_revision: snapshot.revision, content: '---\ntype: note\ntitle: docs/a\n---\nAn edited nested body.\n' })) as Record<string, unknown>;+ expect(edited.state).toBe('committed');+ expect(readFileSync(nested, 'utf8')).toContain('An edited nested body.');+ expect(readFileSync(sibling, 'utf8')).toBe(siblingBytes);+ const current = (await engine.readPageSnapshot('docs/a', { sourceId: f.id }))!;+ const deleted = await local(engine, f.registration, () => operationsByName.delete_page!.handler(f.ctx, { source_id: f.id, slug: 'docs/a',+ request_id: randomUUID(), expected_revision: current.revision })) as Record<string, unknown>;+ expect(deleted.state).toBe('committed');+ expect(existsSync(nested)).toBe(false);+ expect(readFileSync(sibling, 'utf8')).toBe(siblingBytes);+}), 120_000);++test.each([false, true])('renaming a nested scope-named file out of the scope directory is a delete plus a new page (full=%p)', async full => isolated(async engine => {+ const f = await fixture(engine, { 'sub/a.md': '---\ntitle: Nested\n---\nNested body.\n' }, { scope: 'sub' });+ expect((await sync(engine, f)).status).toBe('first_sync');+ expect(await sourcePath(engine, f, 'sub/a')).toBe('sub/a.md');+ git(f.repo, 'mv', 'sub/sub/a.md', 'sub/a.md'); commit(f.repo, 'rename');+ expect((await sync(engine, f, full)).status).toBe('synced');+ expect(await engine.getPage('sub/a', { sourceId: f.id })).toBeNull();+ expect((await engine.getPage('a', { sourceId: f.id }))?.compiled_truth).toContain('Nested body.');+ expect(await sourcePath(engine, f, 'a')).toBe('a.md');+}), 120_000);++test('an unpinned subdirectory source pins its inferred mode with the first origin, so a scope-named slug keeps its file', async () => isolated(async engine => {+ const f = await fixture(engine, {}, { scope: 'docs', pinned: false });+ expect((await put(engine, f, 'docs/a', 'The first nested page body.')).state).toBe('committed');+ expect(await sourcePath(engine, f, 'docs/a')).toBe('docs/a.md');+ expect((await engine.executeRaw<{ mode: string | null }>("SELECT config->>'slug_root_mode' AS mode FROM sources WHERE id=$1", [f.id]))[0].mode).toBe('source-root');+ const nested = join(f.root, 'docs/a.md'), sibling = join(f.root, 'a.md');+ writeFileSync(sibling, readFileSync(nested, 'utf8'));+ const snapshot = (await engine.readPageSnapshot('docs/a', { sourceId: f.id }))!;+ const edited = await local(engine, f.registration, () => operationsByName.put_page!.handler(f.ctx, { source_id: f.id, slug: 'docs/a',+ request_id: randomUUID(), expected_revision: snapshot.revision, content: '---\ntype: note\ntitle: docs/a\n---\nAn edited nested body.\n' })) as Record<string, unknown>;+ expect(edited.state).toBe('committed');+ expect(readFileSync(nested, 'utf8')).toContain('An edited nested body.');+ expect(readFileSync(sibling, 'utf8')).not.toContain('An edited nested body.');+}), 120_000);diff --git a/test/persistence-guard-digest.test.ts b/test/persistence-guard-digest.test.tsnew file mode 100644index 0000000000..3172a7670d--- /dev/null+++ b/test/persistence-guard-digest.test.ts@@ -0,0 +1,93 @@+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { dirname, join } from 'node:path';+import { tmpdir } from 'node:os';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { parseMarkdown, serializePageToMarkdown } from '../src/core/markdown.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { prepareFileTarget } from '../src/core/persistence/page-prepare.ts';++// #5521 / #5635: the coordinated write guard compares the parsed canonical file+// with the stored row. A file with no frontmatter `type:` keeps the stored type+// on import (#1035), and the parser trims titles, so neither can be drift.++let engine: PGLiteEngine;+let worktreeId: string;+let home: string;+let root: string;+const sourceId = 'guard-digest';++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({}); await engine.initSchema();+ home = mkdtempSync(join(tmpdir(), 'gbrain-guard-digest-'));+ root = join(home, 'source'); mkdirSync(root);+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);+ worktreeId = (await claimWorktree(engine, sourceId, root)).worktree_id;+}, 60000);+afterAll(async () => { await engine.disconnect(); rmSync(home, { recursive: true, force: true }); }, 60000);++async function seed(slug: string, page: { type: string; title: string }, edit: (markdown: string) => string = m => m) {+ await engine.putPage(slug, { ...page, compiled_truth: 'Mirrored body' }, { sourceId });+ await engine.executeRaw('UPDATE pages SET source_path=$1 WHERE source_id=$2 AND slug=$3', [`${slug}.md`, sourceId, slug]);+ const snapshot = (await engine.readPageSnapshot(slug, { sourceId }))!;+ const file = join(root, `${slug}.md`);+ mkdirSync(dirname(file), { recursive: true });+ writeFileSync(file, edit(serializePageToMarkdown(snapshot.page, snapshot.tags)));+ return { snapshot, file, row: { source_id: sourceId, worktree_id: worktreeId, slug } };+}+const withoutType = (markdown: string) => markdown.replace(/^type:.*\n/m, '');++test('#5521 a type-less canonical file does not conflict with a stored non-default type', async () => {+ const { snapshot, row, file } = await seed('raw/mirror/type-less', { type: 'note', title: 'Type less' }, withoutType);+ expect(readFileSync(file, 'utf8')).not.toMatch(/^type:/m);+ expect(parseMarkdown(readFileSync(file, 'utf8'), row.slug).type).not.toBe('note');+ for (const attempt of [1, 2]) {+ expect((await prepareFileTarget(engine, row, snapshot, `Replacement ${attempt}`))?.path).toBe(file);+ }+ expect((await prepareFileTarget(engine, row, snapshot, null))?.path).toBe(file);+});++test('#5521 an explicit frontmatter type that disagrees with the row is still refused', async () => {+ const { snapshot, row, file } = await seed('raw/mirror/explicit-type', { type: 'note', title: 'Explicit' }, withoutType);+ writeFileSync(file, readFileSync(file, 'utf8').replace(/^---\n/, '---\ntype: concept\n'));+ await expect(prepareFileTarget(engine, row, snapshot, 'Replacement')).rejects.toMatchObject({ code: 'source_changed' });+});++test('#5521 a local body edit on a type-less file is still refused', async () => {+ const { snapshot, row, file } = await seed('raw/mirror/body-edit', { type: 'note', title: 'Body edit' }, withoutType);+ writeFileSync(file, `${readFileSync(file, 'utf8')}\nUncoordinated local edit\n`);+ await expect(prepareFileTarget(engine, row, snapshot, 'Replacement')).rejects.toMatchObject({ code: 'source_changed' });+});++test('#5635 a stored title with surrounding whitespace is not an uncoordinated edit', async () => {+ const { snapshot, row, file } = await seed('raw/padded-title', { type: 'note', title: ' Probe Cli 20260928 ' });+ expect(snapshot.page.title).toBe(' Probe Cli 20260928 ');+ expect(parseMarkdown(readFileSync(file, 'utf8'), row.slug).title).toBe('Probe Cli 20260928');+ expect((await prepareFileTarget(engine, row, snapshot, 'Replacement'))?.path).toBe(file);+ expect((await prepareFileTarget(engine, row, snapshot, null))?.path).toBe(file);+});++test('#5635 a real local title edit is still refused', async () => {+ const { snapshot, row, file } = await seed('raw/title-edit', { type: 'note', title: 'Original Title ' });+ writeFileSync(file, readFileSync(file, 'utf8').replace(/^title:.*$/m, 'title: Renamed Title'));+ await expect(prepareFileTarget(engine, row, snapshot, 'Replacement')).rejects.toMatchObject({ code: 'source_changed', detail: 'file_database_drift',+ suggestion: expect.stringContaining(`gbrain sources reconcile ${sourceId} raw/title-edit --brain`) });+});++test('#5635 a title humanized from a slug with edge separators is stored trimmed', () => {+ expect(parseMarkdown('Body only, no heading', '__probe_cli_20260928.md').title).toBe('Probe Cli 20260928');+ expect(parseMarkdown('Body only, no heading', 'inbox/sources/micromotion-and-wound-.md').title).toBe('Micromotion And Wound');+ expect(parseMarkdown('Body only, no heading', '---.md').title).toBe('Untitled');+});++test('#5622 a new captured page claims its in-source file only when the bytes are exactly the captured input', async () => {+ const { sha256 } = await import('../src/core/persistence/digest.ts');+ const file = join(root, 'notes', 'captured-race.md');+ mkdirSync(dirname(file), { recursive: true });+ writeFileSync(file, 'x2 observation\n');+ const row = { source_id: sourceId, worktree_id: worktreeId, slug: 'notes/captured-race' };+ await expect(prepareFileTarget(engine, row, null, 'Rendered page', undefined, { capture: { path: 'notes/captured-race.md', hash: sha256('x² observation\n') } }))+ .rejects.toMatchObject({ code: 'source_changed' });+ expect((await prepareFileTarget(engine, row, null, 'Rendered page', undefined, { capture: { path: 'notes/captured-race.md', hash: sha256('x2 observation\n') } }))?.path).toBe(file);+});diff --git a/test/persistence-physical-root-device.test.ts b/test/persistence-physical-root-device.test.tsnew file mode 100644index 0000000000..2517cb9b0c--- /dev/null+++ b/test/persistence-physical-root-device.test.ts@@ -0,0 +1,152 @@+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, 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 type { OperationContext } from '../src/core/ops/contract.ts';+import { operationsByName } from '../src/core/operations.ts';+import { runPersistenceAdministration } from '../src/core/persistence/administration.ts';+import { acquireWorktree, claimWorktree, getWorktreeBinding } from '../src/core/persistence/ownership.ts';+import { registerLocalWriter, withVerifiedLocalRegistration } from '../src/core/persistence/identity.ts';+import { assertPhysicalRoot } from '../src/core/persistence/physical-root.ts';+import * as rootRecord from '../src/core/persistence/physical-root-record.ts';+import { PHYSICAL_ROOT_MARKER, physicalRootReservationPath } from '../src/core/persistence/physical-root-record.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { reviewedWriterIntent } from './helpers/writer-admin-intent.ts';+import { withEnv } from './helpers/with-env.ts';+import { testBackends } from './helpers/test-backends.ts';++// #5604: macOS can assign a checkout's filesystem a new st_dev across reboots.+// The persisted physical-root identity kept the old device, so every managed+// write refused with recovery_required until a manual self-transfer.++const readJson = (path: string) => JSON.parse(readFileSync(path, 'utf8'));+const writeJson = (path: string, value: unknown) => writeFileSync(path, JSON.stringify(value), { mode: 0o600 });++test('device-only change is recognized only with a non-zero matching birth time and inode', () => {+ const stamp = { version: 1 as const, token: randomUUID(), brainId: randomUUID(), worktreeId: randomUUID(), root: '/example/root', device: '7', inode: '11', birth: '13' };+ const reservation = { token: stamp.token, brainId: stamp.brainId, worktreeId: stamp.worktreeId, root: stamp.root };+ const info = (dev: bigint, ino: bigint, birth: bigint) => ({ dev, ino, birthtimeNs: birth });+ const physicalRootDeviceChange = (rootRecord as Record<string, any>).physicalRootDeviceChange;+ expect(physicalRootDeviceChange(stamp, reservation, info(8n, 11n, 13n))).toEqual({ from: '7', to: '8' });+ expect(physicalRootDeviceChange(stamp, reservation, info(7n, 11n, 13n))).toBeNull();+ expect(physicalRootDeviceChange({ ...stamp, birth: '0' }, reservation, info(8n, 11n, 0n))).toBeNull();+ expect(physicalRootDeviceChange(stamp, reservation, info(8n, 12n, 13n))).toBeNull();+ expect(physicalRootDeviceChange(stamp, reservation, info(8n, 11n, 14n))).toBeNull();+ expect(physicalRootDeviceChange(stamp, { ...reservation, token: randomUUID() }, info(8n, 11n, 13n))).toBeNull();+ expect(physicalRootDeviceChange({ ...stamp, root: '/other' }, reservation, info(8n, 11n, 13n))).toBeNull();+});++for (const kind of testBackends()) describe(`physical root device change (${kind})`, () => {+ const directory = mkdtempSync(join(tmpdir(), 'gbrain-root-device-'));+ let engine: BrainEngine, close: (() => Promise<void>) | undefined;+ beforeAll(async () => {+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ else { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }+ }, 120_000);+ afterAll(async () => {+ await withEnv({ GBRAIN_HOME: directory }, () => disposePersistenceConsumer(engine));+ if (close) await close(); else await engine.disconnect();+ rmSync(directory, { recursive: true, force: true });+ });++ async function fixture(run: (f: { root: string; source: string; live: string; ctx: OperationContext;+ registration: Awaited<ReturnType<typeof registerLocalWriter>> }) => Promise<void>) {+ const home = join(directory, randomUUID()), root = join(home, 'root'); mkdirSync(root, { recursive: true });+ const source = `device-${randomUUID().slice(0, 8)}`;+ await withEnv({ GBRAIN_HOME: home, GBRAIN_BRAIN_ID: 'host', GBRAIN_SOURCE: undefined, OPENAI_API_KEY: undefined, ANTHROPIC_API_KEY: undefined }, async () => {+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [source, root]);+ await claimWorktree(engine, source, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const registration = await registerLocalWriter(engine, 'cli');+ const ctx: OperationContext = { engine, remote: false, sourceId: source, config: { engine: engine.kind, embedding_disabled: true } as never,+ dryRun: false, logger: { info() {}, warn() {}, error() {} } };+ await run({ root, source, live: statSync(root, { bigint: true }).dev.toString(), ctx, registration });+ });+ }+ /** Simulate the reboot: every persisted copy still names the previous device. */+ async function reboot(root: string, source: string, previous: string) {+ const marker = join(root, PHYSICAL_ROOT_MARKER), reservation = physicalRootReservationPath(root);+ writeJson(marker, { ...readJson(marker), device: previous });+ writeJson(reservation, { ...readJson(reservation), initialDevice: previous });+ const binding = (await getWorktreeBinding(engine, source))!;+ const selfTransfer = { hostId: randomUUID(), before: { reservation: { ...readJson(reservation) }, stamp: { ...readJson(marker) } },+ reservation: { ...readJson(reservation) }, stamp: { ...readJson(marker) } };+ await engine.executeRaw('UPDATE persistence_worktrees SET manifest=$2::text::jsonb WHERE id=$1::uuid',+ [binding.worktree_id, JSON.stringify({ digest: 'previous-transfer', files: {}, self_transfer: selfTransfer })]);+ const stage = `${root}.stage-${randomUUID().slice(0, 8)}`; mkdirSync(stage);+ const info = statSync(stage, { bigint: true });+ await engine.executeRaw(`INSERT INTO persistence_topology_changes(principal_id,request_id,digest,operation,source_id,worktree_ids,state,recovery)+ VALUES($1::uuid,$2::uuid,'example','reclone',$3,ARRAY[$4::uuid],'recovering',$5::text::jsonb)`, [randomUUID(), randomUUID(), source, binding.worktree_id,+ JSON.stringify({ stage, stageIdentity: { device: previous, inode: info.ino.toString(), birthNs: info.birthtimeNs.toString() } })]);+ return binding;+ }+ const put = (f: Parameters<Parameters<typeof fixture>[0]>[0], slug: string) => withVerifiedLocalRegistration(engine, f.registration, () =>+ operationsByName.put_page!.handler(f.ctx, { source_id: f.source, slug, request_id: randomUUID(),+ content: '---\ntype: note\ntitle: Example\n---\nA managed observation after a reboot.\n' })) as Promise<Record<string, unknown>>;++ test('a device-only change re-stamps every persisted copy under the native lock and managed writes succeed', () => fixture(async f => {+ const previous = String(BigInt(f.live) + 1n);+ const binding = await reboot(f.root, f.source, previous);+ expect(await put(f, 'notes/after-reboot').then(r => r.state, (e: { code?: string }) => e.code)).toBe('committed');+ expect(readJson(join(f.root, PHYSICAL_ROOT_MARKER)).device).toBe(f.live);+ expect(readJson(physicalRootReservationPath(f.root)).initialDevice).toBe(f.live);+ const [owner] = await engine.executeRaw<{ manifest: { self_transfer: Record<string, any> } }>('SELECT manifest FROM persistence_worktrees WHERE id=$1::uuid', [binding.worktree_id]);+ const recorded = owner.manifest.self_transfer;+ expect([recorded.before.reservation.initialDevice, recorded.before.stamp.device, recorded.reservation.initialDevice, recorded.stamp.device]).toEqual([f.live, f.live, f.live, f.live]);+ const [topology] = await engine.executeRaw<{ recovery: { stageIdentity: { device: string } } }>(+ "SELECT recovery FROM persistence_topology_changes WHERE state='recovering' AND $1::uuid=ANY(worktree_ids)", [binding.worktree_id]);+ expect(topology.recovery.stageIdentity.device).toBe(f.live);+ await engine.executeRaw("UPDATE persistence_topology_changes SET state='failed' WHERE $1::uuid=ANY(worktree_ids)", [binding.worktree_id]);+ assertPhysicalRoot(f.root, { worktreeId: binding.worktree_id, coordinationPath: binding.coordination_path });+ expect((await put(f, 'notes/second-write')).state).toBe('committed');+ }), 60_000);++ test('a re-stamp interrupted after its database commit finishes on the next locked write', () => fixture(async f => {+ const binding = await reboot(f.root, f.source, String(BigInt(f.live) + 1n));+ const [owner] = await engine.executeRaw<{ manifest: { self_transfer: Record<string, any> } }>('SELECT manifest FROM persistence_worktrees WHERE id=$1::uuid', [binding.worktree_id]);+ const recorded = owner.manifest.self_transfer;+ recorded.before.reservation.initialDevice = recorded.before.stamp.device = recorded.reservation.initialDevice = recorded.stamp.device = f.live;+ await engine.executeRaw('UPDATE persistence_worktrees SET manifest=$2::text::jsonb WHERE id=$1::uuid', [binding.worktree_id, JSON.stringify(owner.manifest)]);+ await engine.executeRaw("UPDATE persistence_topology_changes SET state='failed' WHERE $1::uuid=ANY(worktree_ids)", [binding.worktree_id]);+ expect((await put(f, 'notes/after-interrupted-restamp')).state).toBe('committed');+ expect(readJson(join(f.root, PHYSICAL_ROOT_MARKER)).device).toBe(f.live);+ expect(readJson(physicalRootReservationPath(f.root)).initialDevice).toBe(f.live);+ }), 60_000);++ test('a device change with a different inode or birth time still refuses and rewrites nothing', () => fixture(async f => {+ const previous = String(BigInt(f.live) + 1n);+ const binding = await reboot(f.root, f.source, previous);+ const marker = join(f.root, PHYSICAL_ROOT_MARKER);+ for (const change of [{ inode: String(BigInt(readJson(marker).inode) + 1n) }, { birth: '0' }]) {+ const original = readJson(marker);+ writeJson(marker, { ...original, ...change });+ await expect(acquireWorktree(binding, 0, undefined, engine)).rejects.toMatchObject({ code: 'recovery_required' });+ expect(readJson(marker)).toEqual({ ...original, ...change });+ expect(readJson(physicalRootReservationPath(f.root)).initialDevice).toBe(previous);+ writeJson(marker, original);+ }+ }), 60_000);++ test('the device refusal names the filled self-transfer commands and they restore writes', () => fixture(async f => {+ const binding = await reboot(f.root, f.source, String(BigInt(f.live) + 1n));+ const refusal = await acquireWorktree(binding).then(() => null, (error: unknown) => error as { code: string; detail?: string; suggestion?: string });+ expect(refusal).toMatchObject({ code: 'recovery_required', detail: 'physical_root_device_changed' });+ expect(refusal!.suggestion).toContain(`gbrain sources writer transfer prepare ${f.source} --self-transfer`);+ expect(refusal!.suggestion).toContain(`gbrain sources writer transfer accept ${f.source} --path ${f.root} --expected-epoch ${binding.owner_epoch}`);+ expect(() => assertPhysicalRoot(f.root, { worktreeId: binding.worktree_id, coordinationPath: binding.coordination_path }))+ .toThrow(expect.objectContaining({ code: 'recovery_required', detail: 'physical_root_device_changed' }));+ expect(readJson(join(f.root, PHYSICAL_ROOT_MARKER)).device).toBe(String(BigInt(f.live) + 1n));+ const administer = async (operation: 'writer_transfer_prepare' | 'writer_transfer_accept', params: Record<string, unknown>) =>+ runPersistenceAdministration(engine, operation, { ...params, ...await reviewedWriterIntent(engine, operation) });+ const prepared = await administer('writer_transfer_prepare', { source_id: f.source, self_transfer: true }) as { owner_epoch: string; manifest: { digest: string } };+ expect(prepared.owner_epoch).toBe(String(binding.owner_epoch));+ await administer('writer_transfer_accept', { source_id: f.source, path: f.root, expected_epoch: prepared.owner_epoch, manifest: prepared.manifest.digest, self_transfer: true });+ const lock = await acquireWorktree((await getWorktreeBinding(engine, f.source))!); expect(lock).not.toBeNull(); await lock?.release();+ }), 60_000);+});diff --git a/test/persistence-sync-cursor-options.test.ts b/test/persistence-sync-cursor-options.test.tsnew file mode 100644index 0000000000..2e28e3de97--- /dev/null+++ b/test/persistence-sync-cursor-options.test.ts@@ -0,0 +1,107 @@+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { execFileSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import type { SyncOpts } from '../src/commands/sync.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import * as syncAuthority from '../src/core/persistence/sync-authority.ts';+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 { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';++// #5632: an interrupted managed sync stores its processing options on the+// cursor. Autopilot (noEmbed+noExtract defaults) and a plain CLI run (neither)+// resolve different defaults, so each refused to finish the other's cursor+// forever. A resume that chose no processing flag now adopts the stored ones.++const home = mkdtempSync(join(tmpdir(), 'gbrain-cursor-options-'));+const engines: BrainEngine[] = [];+let closePostgres: (() => Promise<void>) | undefined;+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+beforeAll(async () => {+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);+ 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) {+ const id = `options-${randomUUID().slice(0, 12)}`, root = join(home, id);+ mkdirSync(root); git(root, 'init', '-q');+ for (const name of ['a', 'b', 'c']) writeFileSync(join(root, `${name}.md`), `---\ntitle: ${name}\n---\nA durable observation named ${name}.\n`);+ git(root, 'add', '.'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'seed');+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,\'{}\')', [id, root]);+ await claimWorktree(engine, id, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ return id;+}+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);+});+const storedOptions = async (engine: BrainEngine, id: string) => (await engine.executeRaw<{ options: unknown }>(+ "SELECT c.completed_keys->0->'processingOptions' AS options FROM op_checkpoints c WHERE c.op='managed-sync' AND c.completed_keys->0->>'sourceId'=$1", [id]))[0]?.options;+// What each caller passes: the autopilot job fills noEmbed/noExtract defaults; the plain CLI passes no flag.+const autopilot = (sourceId: string): SyncOpts => ({ sourceId, noPull: true, noEmbed: true, noExtract: true, explicitProcessing: [] } as SyncOpts);+const plainCli = (sourceId: string): SyncOpts => ({ sourceId, noPull: true, explicitProcessing: [] } as SyncOpts);++test('explicit processing flags are the ones the caller set', () => {+ const explicit = (syncAuthority as Record<string, any>).explicitSyncProcessing;+ expect(explicit({ noEmbed: true, noExtract: false })).toEqual(['noEmbed', 'noExtract']);+ expect(explicit({ noPull: true })).toEqual([]);+});++test('a CLI-partial cursor is finished by an autopilot resume with the stored options', async () => isolated(async engine => {+ const id = await fixture(engine);+ expect(await performManagedSync(engine, plainCli(id), { maxPages: 1, maxMs: 1000 })).toMatchObject({ status: 'partial' });+ expect(await storedOptions(engine, id)).toEqual({ noEmbed: false, noExtract: false, noSchemaPack: false });+ expect((await performManagedSync(engine, autopilot(id))).status).toBe('first_sync');+ expect(await engine.getPage('c', { sourceId: id })).not.toBeNull();+ const intents = await engine.executeRaw<{ options: unknown }>("SELECT intent->'processingOptions' AS options FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_sync_import'", [id]);+ expect(intents.map(row => row.options)).toEqual(Array(3).fill({ noEmbed: false, noExtract: false, noSchemaPack: false }));+}), 120_000);++test('an autopilot-partial cursor is finished by a plain CLI resume', async () => isolated(async engine => {+ const id = await fixture(engine);+ expect(await performManagedSync(engine, autopilot(id), { maxPages: 1, maxMs: 1000 })).toMatchObject({ status: 'partial' });+ expect((await performManagedSync(engine, plainCli(id))).status).toBe('first_sync');+}), 120_000);++test('an explicit conflicting flag refuses with the stored options and the printed resume command finishes the cursor', async () => isolated(async engine => {+ const id = await fixture(engine);+ expect(await performManagedSync(engine, autopilot(id), { maxPages: 1, maxMs: 1000 })).toMatchObject({ status: 'partial' });+ const refused = await performManagedSync(engine, { sourceId: id, noPull: true, noExtract: false, explicitProcessing: ['noExtract'] } as SyncOpts)+ .then(() => null, (error: unknown) => error as { code: string; detail?: string; suggestion?: string });+ expect(refused).toMatchObject({ code: 'invalid_params', detail: 'cursor_processing_options_conflict' });+ expect(refused!.suggestion).toContain('noEmbed=true, noExtract=true, noSchemaPack=false');+ const command = `gbrain sync --source ${id} --no-pull --no-embed --no-extract`;+ expect(refused!.suggestion).toContain(command);+ const args = command.split(' ').slice(2);+ const resumed = await performManagedSync(engine, { sourceId: id, noPull: true, noEmbed: args.includes('--no-embed'), noExtract: args.includes('--no-extract'),+ explicitProcessing: ['noEmbed', 'noExtract'] } as SyncOpts);+ expect(resumed.status).toBe('first_sync');+}), 120_000);++test('a remote sync job keeps its frozen options while the worker adds explicit processing keys', async () => isolated(async engine => {+ const id = await fixture(engine);+ const clientId = `options-client-${randomUUID()}`;+ await engine.executeRaw(`INSERT INTO oauth_clients(client_id,client_name,client_secret_hash,scope,source_id,allowed_operations)+ VALUES($1,'example-client','test-only','admin',$2,ARRAY['submit_job'])`, [clientId, id]);+ const ctx = { engine, remote: true, sourceId: id, auth: { clientId, principal: { kind: 'oauth_client', id: clientId }, scopes: ['admin'], sourceId: id,+ allowedOperations: ['submit_job'] } } as unknown as OperationContext;+ const accepted = await prepareRemoteJob(ctx, 'sync', { noPull: true });+ const explicit = (syncAuthority as Record<string, any>).explicitSyncProcessing;+ const result = await withSubmissionAuthority(accepted.authority, () => performManagedSync(engine,+ { ...accepted.data, explicitProcessing: explicit(accepted.data) } as SyncOpts));+ expect(result.status).toBe('first_sync');+ await engine.executeRaw('DELETE FROM oauth_clients WHERE client_id=$1', [clientId]);+}), 120_000);diff --git a/test/persistence-sync-options.serial.test.ts b/test/persistence-sync-options.serial.test.tsindex 161be7da08..a669e850aa 100644--- a/test/persistence-sync-options.serial.test.ts+++ b/test/persistence-sync-options.serial.test.ts@@ -588,9 +588,9 @@ async function syncState(engine: BrainEngine, sourceId: string) {type SyncBarrier = 'discovery' | 'discovery-commit' | 'foreground' | 'freeze' | 'freeze-commit' | 'request-lookup' | 'admission-commit';function matchesSyncBarrier(boundary: SyncBarrier, sql: string, params: unknown[] | undefined, transactional: boolean): boolean {- if (boundary === 'discovery') return sql.startsWith('SELECT source_path FROM pages WHERE source_id=');+ if (boundary === 'discovery') return sql.startsWith('SELECT slug,source_path FROM pages WHERE source_id=');if (boundary === 'foreground') return sql.includes("NOT(COALESCE(intent->>'kind','') LIKE 'managed_sync_%') LIMIT 1");- if (boundary === 'freeze') return sql.startsWith('SELECT id,source_path FROM pages WHERE source_id=') && !transactional;+ if (boundary === 'freeze') return sql.startsWith('SELECT id,slug,source_path FROM pages WHERE source_id=') && !transactional;if (boundary === 'request-lookup') return sql.startsWith('SELECT') && sql.includes('FROM persistence_requests') && sql.includes('request_id=') && !transactional;if (boundary === 'admission-commit') return sql.includes('UPDATE persistence_counters SET outstanding_count=outstanding_count+1');return transactional && sql === 'SELECT completed_keys FROM op_checkpoints WHERE op=$1 AND fingerprint=$2' && params?.[0] === 'managed-sync';@@ -696,7 +696,7 @@ for (const boundary of ['retry-discovery', 'retry-commit', 'missing-manifest', 'let observed = false;engine.executeRaw = async function (this: BrainEngine, sql: string, params?: unknown[]) {const rows = await execute.call(this, sql, params);- if (!observed && (boundary === 'retry-discovery' ? sql.startsWith('SELECT source_path FROM pages WHERE source_id=')+ if (!observed && (boundary === 'retry-discovery' ? sql.startsWith('SELECT slug,source_path FROM pages WHERE source_id='): boundary === 'completed-cleanup' ? sql.startsWith('DELETE FROM op_checkpoints WHERE op=$1'): this !== engine && sql === 'SELECT completed_keys FROM op_checkpoints WHERE op=$1 AND fingerprint=$2' && params?.[0] === 'managed-sync')) {observed = true; abort.abort();diff --git a/test/pglite-checkpoint-guard.test.ts b/test/pglite-checkpoint-guard.test.tsnew file mode 100644index 0000000000..2cbd93af3f--- /dev/null+++ b/test/pglite-checkpoint-guard.test.ts@@ -0,0 +1,176 @@+/** #5449: the outermost PGLite write transaction checkpoints before BEGIN; savepoints never do. */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { CHECKPOINT_GUARD_MAX_BYTES, PgliteCheckpointGuard, checkpointGuardThreshold } from '../src/core/pglite-engine/checkpoint-guard.ts';+import { GBrainError } from '../src/core/types.ts';++const MB = 1024 * 1024;+type Guarded = { _checkpointGuard: PgliteCheckpointGuard | undefined; db: { query(sql: string): Promise<{ rows: Array<Record<string, unknown>> }> } };++function install(engine: PGLiteEngine, opts: { threshold?: number; fail?: RegExp; warnings?: string[] } = {}) {+ const calls: string[] = [];+ const inner = engine as unknown as Guarded;+ const guard = new PgliteCheckpointGuard(async sql => {+ calls.push(sql);+ if (opts.fail?.test(sql)) throw new Error('synthetic failure');+ return inner.db.query(sql);+ }, message => opts.warnings?.push(message));+ if (opts.threshold !== undefined) (guard as unknown as { threshold: number }).threshold = opts.threshold;+ inner._checkpointGuard = guard;+ return { checkpoints: () => calls.filter(sql => sql === 'CHECKPOINT').length, calls };+}++describe('checkpoint guard threshold', () => {+ test('default max_wal_size keeps the plan threshold of 256 MB', () => {+ expect(checkpointGuardThreshold(1024 * MB, 16 * MB, 0.9)).toBe(CHECKPOINT_GUARD_MAX_BYTES);+ });+ test('small max_wal_size stays below the automatic trigger distance', () => {+ // floor(160 / (16 * 1.9)) = 5 segments: the trigger fires >= 48 MB after redo.+ expect(checkpointGuardThreshold(160 * MB, 16 * MB, 0.9)).toBe(32 * MB);+ expect(checkpointGuardThreshold(32 * MB, 16 * MB, 0.9)).toBe(8 * MB);+ });+});++describe('PGLite outermost transaction guard', () => {+ let engine: PGLiteEngine;+ beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.executeRaw('CREATE TABLE guard_probe (id int PRIMARY KEY, v text)');+ });+ afterAll(async () => { await engine.disconnect(); });++ test('a nested transaction composes as a savepoint and never checkpoints', async () => {+ const spy = install(engine, { threshold: 0 });+ await engine.transaction(async tx => {+ await tx.executeRaw("INSERT INTO guard_probe VALUES (1, 'outer')");+ await tx.transaction(async inner => { await inner.executeRaw("INSERT INTO guard_probe VALUES (2, 'inner')"); });+ });+ expect(spy.checkpoints()).toBe(1);+ expect((await engine.executeRaw('SELECT count(*)::int AS n FROM guard_probe'))[0]).toEqual({ n: 2 });+ });++ test('a rolled-back transaction leaves no rows and the next transaction still runs', async () => {+ install(engine, { threshold: 0 });+ await expect(engine.transaction(async tx => {+ await tx.executeRaw("INSERT INTO guard_probe VALUES (3, 'rolled back')");+ throw new Error('abort');+ })).rejects.toThrow('abort');+ await engine.transaction(async tx => { await tx.executeRaw("INSERT INTO guard_probe VALUES (4, 'after')"); });+ expect((await engine.executeRaw<{ id: number }>('SELECT id FROM guard_probe ORDER BY id')).map(row => row.id)).toEqual([1, 2, 4]);+ });++ test('concurrent outermost transactions each probe the WAL their predecessors wrote', async () => {+ await engine.executeRaw('CREATE TABLE IF NOT EXISTS guard_bulk (id int, v text)');+ await engine.executeRaw('CHECKPOINT');+ const spy = install(engine, { threshold: 64 * 1024 });+ await Promise.all([0, 1, 2].map(n => engine.transaction(async tx => {+ await tx.executeRaw("INSERT INTO guard_bulk SELECT g, repeat('x', 200) FROM generate_series(1, 2000) g");+ return n;+ })));+ // A shared stale probe would let all three pass unguarded after the manual checkpoint.+ expect(spy.checkpoints()).toBeGreaterThanOrEqual(2);+ });++ test('below the threshold no checkpoint runs', async () => {+ const spy = install(engine, { threshold: Number.MAX_SAFE_INTEGER });+ await engine.transaction(async tx => { await tx.executeRaw("UPDATE guard_probe SET v='x' WHERE id=4"); });+ expect(spy.checkpoints()).toBe(0);+ });++ test('a WAL probe failure warns once and proceeds unguarded', async () => {+ const warnings: string[] = [];+ const spy = install(engine, { fail: /pg_control_checkpoint|current_setting/, warnings });+ await engine.transaction(async tx => { await tx.executeRaw("INSERT INTO guard_probe VALUES (5, 'probe failed')"); });+ await engine.transaction(async tx => { await tx.executeRaw("INSERT INTO guard_probe VALUES (6, 'probe failed')"); });+ expect(warnings.length).toBe(1);+ expect(spy.checkpoints()).toBe(0);+ expect((await engine.executeRaw('SELECT count(*)::int AS n FROM guard_probe WHERE id IN (5,6)'))[0]).toEqual({ n: 2 });+ });++ test('a CHECKPOINT failure refuses before BEGIN with a typed error', async () => {+ install(engine, { threshold: 0, fail: /^CHECKPOINT$/ });+ let entered = false;+ const refused = await engine.transaction(async tx => {+ entered = true;+ await tx.executeRaw("INSERT INTO guard_probe VALUES (7, 'never')");+ }).catch(error => error);+ expect(refused).toBeInstanceOf(GBrainError);+ expect(String(refused.message)).toContain('gbrain pglite-repair');+ expect(entered).toBe(false);+ expect(await engine.executeRaw('SELECT id FROM guard_probe WHERE id=7')).toEqual([]);+ });+});++describe('guard checkpoint durability', () => {+ let dir: string;+ let reopened: PGLiteEngine;+ let checkpoints = 0;+ beforeAll(async () => {+ dir = mkdtempSync(join(tmpdir(), 'gbrain-checkpoint-guard-'));+ const path = join(dir, 'brain.pglite');+ const first = new PGLiteEngine();+ await first.connect({ engine: 'pglite', database_path: path } as never);+ await first.executeRaw('CREATE TABLE guard_durable (id int PRIMARY KEY)');+ const spy = install(first, { threshold: 0 });+ for (let i = 0; i < 3; i++) await first.transaction(async tx => { await tx.executeRaw('INSERT INTO guard_durable VALUES ($1)', [i]); });+ checkpoints = spy.checkpoints();+ await first.disconnect();+ reopened = new PGLiteEngine();+ await reopened.connect({ engine: 'pglite', database_path: path } as never);+ }, 60_000);+ afterAll(async () => {+ await reopened.disconnect();+ rmSync(dir, { recursive: true, force: true });+ });++ test('writes committed after a guard checkpoint survive a reopen', async () => {+ expect(checkpoints).toBe(3);+ expect((await reopened.executeRaw('SELECT count(*)::int AS n FROM guard_durable'))[0]).toEqual({ n: 3 });+ });+});++describe('guarded transactions and shutdown', () => {+ let engine: PGLiteEngine;+ beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.executeRaw('CREATE TABLE guard_drain (id int PRIMARY KEY)');+ });+ afterAll(async () => { await engine.disconnect(); });++ test('a transaction queued behind another still completes when disconnect starts', async () => {+ install(engine, { threshold: 0 });+ const release = Promise.withResolvers<void>();+ const entered = Promise.withResolvers<void>();+ const first = engine.transaction(async tx => {+ await tx.executeRaw('INSERT INTO guard_drain VALUES (1)');+ entered.resolve();+ await release.promise;+ });+ await entered.promise;+ const second = engine.transaction(async tx => { await tx.executeRaw('INSERT INTO guard_drain VALUES (2)'); return 'second'; });+ const closing = engine.disconnect();+ release.resolve();+ await first;+ expect(await second).toBe('second');+ await closing;+ await engine.connect({});+ });++ test('a reattached database gets a fresh guard that rereads WAL settings', async () => {+ const guarded = engine as unknown as Guarded;+ delete (guarded as { _checkpointGuard?: unknown })._checkpointGuard;+ await engine.transaction(async tx => { await tx.executeRaw('SELECT 1'); });+ const before = guarded._checkpointGuard;+ expect(before).toBeInstanceOf(PgliteCheckpointGuard);+ await engine.disconnect();+ await engine.connect({});+ expect(guarded._checkpointGuard).toBeUndefined();+ await engine.transaction(async tx => { await tx.executeRaw('SELECT 1'); });+ expect(guarded._checkpointGuard).not.toBe(before);+ });+});diff --git a/test/private-visibility.test.ts b/test/private-visibility.test.tsindex 0c13ef504c..08e3a620ff 100644--- a/test/private-visibility.test.ts+++ b/test/private-visibility.test.ts@@ -63,7 +63,7 @@ describe('buildVisibilityClause (#4352)', () => {test('excludePrivate: adds the COALESCE predicate', () => {const clause = buildVisibilityClause('p', 's', { excludePrivate: true });- expect(clause).toContain(`COALESCE(p.frontmatter->>'visibility', 'world') <> 'private'`);+ expect(clause).toContain(`COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private'`);});});diff --git a/test/projection-embedding-input-hash.test.ts b/test/projection-embedding-input-hash.test.tsnew file mode 100644index 0000000000..170af41d61--- /dev/null+++ b/test/projection-embedding-input-hash.test.ts@@ -0,0 +1,249 @@+/**+ * #5553: a projection rebuild (the page_projection_jobs drain) and the+ * embed-oversize heal must keep a chunk's vector when its embedding input is+ * unchanged, on contextual-mode pages too. Each vector carries a per-chunk+ * `content_chunks.embedding_input_hash`, written with the vector; a rebuild+ * nulls only chunks whose recomputed hash differs. A chunk written before the+ * column existed (NULL hash) on a contextual page is nulled once, then stamped+ * when it is re-embedded. In per_chunk_synopsis mode any body change nulls every+ * synopsis-tier chunk, while title-tier chunks on the same page keep theirs.+ */+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../src/core/engine.ts';+import type { ChunkInput } from '../src/core/types.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { healOversizedPageChunks } from '../src/core/embed-oversize-heal.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';+import { installPageEmbeddings, installPageProjection, preparePageProjection, queuePageProjection,+ readProjectionSnapshot, rebuildPendingPageProjections } from '../src/core/page-state/projections.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';++const backends = testBackends();+const sourceId = 'input-hash-test';+const slug = 'notes/cedar';+const body = 'Synthetic cedar memory about alpine lakes.\n\nA second paragraph about granite ridges.';+const timeline = '2026-01-02: Synthetic event with exact provenance.';+const SYNOPSIS_GENERATION = 'synopsis-generation-fixture';++function vec(seed: number): Float32Array {+ const v = new Float32Array(1536); v[0] = seed; v[1] = -seed / 2; return v;+}++describe('#5553 embedding input hash is the exact wrapped input', () => {+ test('a title-tier hash matches the plain re-embed wrapper byte for byte, including at the 300-character cap', async () => {+ const { embeddingInputHash } = await import('../src/core/embedding-input-hash.ts');+ const { wrapChunkTextsForStoredMode } = await import('../src/core/embedding-context.ts');+ const chunk = { chunk_text: 'Body text.', chunk_source: 'compiled_truth' };+ const base = { column: 'embedding', model: 'openai:m', dimensions: 1536, corpusGeneration: null, bodyHash: '' };+ const prefix = 'P'.repeat(299);+ const hashes = [`${prefix} more`, prefix].map(title => embeddingInputHash({ ...base, title }, 'title', chunk));+ const inputs = [`${prefix} more`, prefix].map(title => wrapChunkTextsForStoredMode({ title, contextual_retrieval_mode: 'title' }, [chunk])[0]);+ expect(inputs[0]).not.toBe(inputs[1]);+ expect(hashes[0]).not.toBe(hashes[1]);+ // Same input, same hash: the hash covers exactly the bytes sent to the provider.+ expect(embeddingInputHash({ ...base, title: prefix }, 'title', chunk)).toBe(hashes[1]);+ });+});++for (const kind of backends) {+ describe(`#5553 embedding input provenance ${kind}`, () => {+ let engine: BrainEngine;+ let closePostgres: (() => Promise<void>) | undefined;+ beforeAll(async () => {+ if (kind === 'postgres') ({ engine, close: closePostgres } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ else { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }+ }, 120_000);+ beforeEach(async () => { await engine.executeRaw('INSERT INTO sources(id,name) VALUES ($1,$1)', [sourceId]); });+ afterEach(async () => { await engine.executeRaw('DELETE FROM sources WHERE id=$1', [sourceId]); });+ afterAll(async () => { if (kind === 'pglite') await engine.disconnect(); await closePostgres?.(); });++ const vectors = async () => (await engine.executeRaw<{ chunk_index: number; has: boolean; hash: string | null }>(+ `SELECT cc.chunk_index, cc.embedding IS NOT NULL AS has, to_jsonb(cc)->>'embedding_input_hash' AS hash FROM content_chunks cc+ JOIN pages p ON p.id=cc.page_id WHERE p.source_id=$1 AND p.slug=$2 ORDER BY cc.chunk_index`, [sourceId, slug]))+ .map(r => ({ i: Number(r.chunk_index), has: r.has, hash: r.hash }));+ const present = async () => (await vectors()).map(v => v.has);++ async function seed(opts: { mode: string | null; generation?: string | null; chunks?: ChunkInput[]; title?: string } = { mode: 'title' }) {+ await engine.putPage(slug, { type: 'note', title: opts.title ?? 'Cedar notes', compiled_truth: body, timeline,+ frontmatter: {}, source_path: 'notes/cedar.md' }, { sourceId });+ const prepared = (await readProjectionSnapshot(engine, slug, sourceId, { allowUnsealed: true }))!;+ const chunks = opts.chunks ?? (await preparePageProjection(prepared)).chunks;+ await installPageProjection(engine, prepared, chunks, { seal: true });+ await engine.updatePageContextualRetrievalState(slug, sourceId, opts.mode as never, opts.generation ?? null);+ }+ async function embedAll(override?: { tier: string; corpusGeneration?: string | null }, only?: number[]) {+ const prepared = (await readProjectionSnapshot(engine, slug, sourceId))!;+ const chunks = prepared.chunks.filter(c => !only || only.includes(c.chunk_index))+ .map(c => ({ chunk_index: c.chunk_index, chunk_text: c.chunk_text, chunk_source: c.chunk_source, embedding: vec(c.chunk_index + 1) }));+ expect(await (installPageEmbeddings as (...a: unknown[]) => Promise<boolean>)(engine, prepared, chunks, undefined, override)).toBe(true);+ }+ async function rebuild() {+ await queuePageProjection(engine, sourceId, slug, 'test_rebuild');+ expect(await rebuildPendingPageProjections(engine, 10)).toEqual({ rebuilt: 1, superseded: 0 });+ }+ async function editBody(nextBody: string, title = 'Cedar notes') {+ await engine.putPage(slug, { type: 'note', title, compiled_truth: nextBody, timeline, frontmatter: {}, source_path: 'notes/cedar.md' }, { sourceId });+ }++ test('baseline shape (PR #5630 repro): a title-mode rebuild with nothing changed keeps every vector', async () => {+ await seed({ mode: 'title' });+ await embedAll();+ expect(await present()).toEqual([true, true]);+ const stamped = await vectors();+ await rebuild();+ expect(await present()).toEqual([true, true]);+ expect(await vectors()).toEqual(stamped);+ for (const v of stamped) expect(v.hash).toMatch(/^[0-9a-f]{64}$/);+ });++ test('an unchanged none-mode rebuild also keeps its vectors and stamps', async () => {+ await seed({ mode: 'none' });+ await embedAll();+ const stamped = await vectors();+ await rebuild();+ expect(await vectors()).toEqual(stamped);+ });++ test('changing one chunk nulls only that chunk', async () => {+ await seed({ mode: 'title' });+ await embedAll();+ await editBody(body.replace('granite ridges', 'basalt ridges'));+ await rebuild();+ expect(await present()).toEqual([false, true]);+ });++ test('a title change nulls every title-tier vector', async () => {+ await seed({ mode: 'title' });+ await embedAll();+ await editBody(body, 'Renamed cedar notes');+ await rebuild();+ expect(await present()).toEqual([false, false]);+ });++ test('a hash for another model, dimension or column never keeps the vector', async () => {+ const { embeddingInputHash } = await import('../src/core/embedding-input-hash.ts');+ for (const change of [{ model: 'openai:other-model' }, { dimensions: 3 }, { column: 'embedding_other' }]) {+ await seed({ mode: 'title' });+ await embedAll();+ const prepared = (await readProjectionSnapshot(engine, slug, sourceId))!;+ const chunk = prepared.chunks[0];+ const forged = embeddingInputHash({ column: 'embedding', model: prepared.embeddingModel, dimensions: 1536,+ title: 'Cedar notes', corpusGeneration: null, bodyHash: '', ...change }, 'title', chunk);+ await engine.executeRaw('UPDATE content_chunks SET embedding_input_hash=$2 WHERE page_id=$1 AND chunk_index=0', [prepared.snapshot.page.id, forged]);+ await rebuild();+ expect(await present()).toEqual([false, true]);+ await engine.executeRaw('DELETE FROM pages WHERE source_id=$1', [sourceId]);+ }+ });++ test('a legacy chunk with no provenance on a contextual page is nulled once, then stamped and kept', async () => {+ await seed({ mode: 'title' });+ await embedAll();+ await engine.executeRaw(`UPDATE content_chunks SET embedding_input_hash=NULL WHERE page_id=(SELECT id FROM pages WHERE source_id=$1 AND slug=$2)`, [sourceId, slug]);+ await rebuild();+ expect(await present()).toEqual([false, false]);+ await embedAll();+ const stamped = await vectors();+ expect(stamped.every(v => v.has && v.hash)).toBe(true);+ await rebuild();+ expect(await vectors()).toEqual(stamped);+ });++ test('a legacy chunk with no provenance on a none-mode page keeps its vector (unchanged behavior)', async () => {+ await seed({ mode: null });+ await embedAll();+ await engine.executeRaw(`UPDATE content_chunks SET embedding_input_hash=NULL WHERE page_id=(SELECT id FROM pages WHERE source_id=$1 AND slug=$2)`, [sourceId, slug]);+ await rebuild();+ expect(await present()).toEqual([true, true]);+ });++ test('synopsis mode: an unchanged rebuild keeps mixed synopsis and title tiers; a body edit nulls every synopsis chunk', async () => {+ await seed({ mode: 'per_chunk_synopsis', generation: SYNOPSIS_GENERATION });+ await embedAll({ tier: 'per_chunk_synopsis', corpusGeneration: SYNOPSIS_GENERATION }, [0]);+ await embedAll(undefined, [1]);+ const stamped = await vectors();+ expect(stamped.map(v => v.has)).toEqual([true, true]);+ expect(stamped[0].hash).not.toBe(stamped[1].hash);+ await rebuild();+ expect(await vectors()).toEqual(stamped);+ // The body edit touches only the timeline chunk's neighbour text, so chunk 0's+ // own text is unchanged: its synopsis read the whole body and is still nulled.+ await engine.putPage(slug, { type: 'note', title: 'Cedar notes', compiled_truth: body, timeline: `${timeline} Extra detail.`,+ frontmatter: {}, source_path: 'notes/cedar.md' }, { sourceId });+ await rebuild();+ expect(await present()).toEqual([false, false]);+ });++ test('synopsis mode: a title-tier chunk keeps its vector through a body edit that leaves its own text unchanged', async () => {+ await seed({ mode: 'per_chunk_synopsis', generation: SYNOPSIS_GENERATION });+ await embedAll(undefined, [0]);+ await embedAll({ tier: 'per_chunk_synopsis', corpusGeneration: SYNOPSIS_GENERATION }, [1]);+ await engine.putPage(slug, { type: 'note', title: 'Cedar notes', compiled_truth: body, timeline: `${timeline} Extra detail.`,+ frontmatter: {}, source_path: 'notes/cedar.md' }, { sourceId });+ await rebuild();+ expect(await present()).toEqual([true, false]);+ });++ test('synopsis mode: a title change past the 300-character wrapper cap still nulls synopsis-tier vectors', async () => {+ const long = 'T'.repeat(320);+ await seed({ mode: 'per_chunk_synopsis', generation: SYNOPSIS_GENERATION, title: `${long} one` });+ await embedAll({ tier: 'per_chunk_synopsis', corpusGeneration: SYNOPSIS_GENERATION }, [0]);+ await embedAll(undefined, [1]);+ await editBody(body, `${long} two`);+ await engine.updatePageContextualRetrievalState(slug, sourceId, 'per_chunk_synopsis', SYNOPSIS_GENERATION);+ await rebuild();+ // The synopsis prompt read the full title; the title wrapper keeps only its first 300 characters.+ expect(await present()).toEqual([false, true]);+ });++ test('a stale synopsis generation nulls synopsis-tier vectors', async () => {+ await seed({ mode: 'per_chunk_synopsis', generation: SYNOPSIS_GENERATION });+ await embedAll({ tier: 'per_chunk_synopsis', corpusGeneration: SYNOPSIS_GENERATION });+ await engine.updatePageContextualRetrievalState(slug, sourceId, 'per_chunk_synopsis', 'another-generation');+ await rebuild();+ expect(await present()).toEqual([false, false]);+ });++ test('the oversize heal keeps vectors of unchanged chunks on a title-mode page', async () => {+ const big = Array.from({ length: 60 }, (_, i) => `Sentence ${i} about the long synthetic ridge walk.`).join(' ');+ await seed({ mode: 'title', chunks: [+ { chunk_index: 0, chunk_text: body, chunk_source: 'compiled_truth' },+ { chunk_index: 1, chunk_text: big, chunk_source: 'timeline' },+ ] });+ await embedAll();+ const before = await vectors();+ const healed = await healOversizedPageChunks(engine, slug, { sourceId, maxTokens: 200 });+ expect(healed.changed).toBe(true);+ const after = await vectors();+ expect(after.length).toBeGreaterThan(2);+ expect(after[0]).toEqual(before[0]);+ expect(after.slice(1).every(v => !v.has && v.hash === null)).toBe(true);+ });++ test('an inline title-mode import stamps provenance, so a later rebuild keeps its vectors', async () => {+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: { OPENAI_API_KEY: 'sk-fake' } });+ __setEmbedTransportForTests((async (args: { values: string[] }) => ({+ embeddings: args.values.map((_, i) => Array.from(vec(i + 1))),+ })) as never);+ try {+ await engine.setConfig('search.contextual_retrieval', 'title').catch(() => undefined);+ await engine.executeRaw('UPDATE sources SET contextual_retrieval_mode=$2 WHERE id=$1', [sourceId, 'title']);+ const md = `---\ntitle: Cedar notes\ntype: note\n---\n\n${body}\n`;+ const result = await importFromContent(engine, slug, md, { sourceId });+ expect(result.status).toBe('imported');+ const [page] = await engine.executeRaw<{ mode: string }>('SELECT contextual_retrieval_mode AS mode FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, slug]);+ expect(page.mode).toBe('title');+ const stamped = await vectors();+ expect(stamped.length).toBeGreaterThan(0);+ for (const v of stamped) expect(v.has && typeof v.hash === 'string').toBe(true);+ await rebuild();+ expect(await vectors()).toEqual(stamped);+ } finally {+ __setEmbedTransportForTests(null);+ resetGateway();+ }+ });+ });+}diff --git a/test/put-page-persistence.test.ts b/test/put-page-persistence.test.tsindex 1ca0f06692..0e8a183c36 100644--- a/test/put-page-persistence.test.ts+++ b/test/put-page-persistence.test.ts@@ -126,6 +126,7 @@ describe('put_page persistence boundary', () => {execFileSync('git', ['init', root], { stdio: 'ignore' });const scoped = join(root, 'public'); mkdirSync(scoped);await engine.setConfig('sync.repo_path', scoped);+ await engine.setConfig('sync.slug_root_mode', 'git-root');const slug = 'notes/scoped-path';expect((await put(slug, content('Original scoped body.'))).payload.state).toBe('committed');const initial = (await engine.readPageSnapshot(slug, { sourceId: 'default' }))!;diff --git a/test/recall-grep-local-cli.test.ts b/test/recall-grep-local-cli.test.tsnew file mode 100644index 0000000000..5656cc4911--- /dev/null+++ b/test/recall-grep-local-cli.test.ts@@ -0,0 +1,113 @@+/**+ * gbrain#5607 — `gbrain recall --grep` on the local (non-thin-client) path+ * must filter in SQL, BEFORE the LIMIT.+ *+ * fetchRowsLocal used to fetch `limit` rows and leave grep to a client-side+ * post-limit filter, so any match older than the newest-N window reported+ * "No matching facts." while the fact existed and was active — and+ * `--limit` caps at 100, so older facts were unreachable.+ *+ * Seed order matters: the needle goes in FIRST, then `limit`-plus fillers,+ * so the needle falls outside the newest-N window — a post-limit filter+ * finds nothing. PGLite-only; no DATABASE_URL, no API keys.+ */++import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { runRecall } from '../src/commands/recall.ts';++let engine: PGLiteEngine;+const origWrite = process.stdout.write.bind(process.stdout);+let captured = '';++const SRC = 'default';+const FILLER = 10;+const LIMIT = 5;++async function recallJson(args: string[]): Promise<{ facts: Array<{ fact: string }>; total: number }> {+ captured = '';+ await runRecall(engine, [...args, '--json', '--source', SRC]);+ return JSON.parse(captured);+}++async function seed(opts: { entity: string; session?: string }): Promise<string> {+ const needle = `g5607 needle ${opts.entity}`;+ await engine.insertFact(+ { fact: needle, kind: 'fact', entity_slug: opts.entity, source: 'test', source_session: opts.session },+ { source_id: SRC },+ );+ for (let i = 0; i < FILLER; i++) {+ await engine.insertFact(+ { fact: `g5607 filler ${i} ${opts.entity} (no match)`, kind: 'fact', entity_slug: opts.entity, source: 'test', source_session: opts.session },+ { source_id: SRC },+ );+ }+ return needle;+}++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+});++afterAll(async () => {+ await engine.disconnect();+ process.stdout.write = origWrite;+});++beforeEach(() => {+ captured = '';+ process.stdout.write = ((chunk: string | Uint8Array) => {+ captured += typeof chunk === 'string' ? chunk : Buffer.from(chunk).toString();+ return true;+ }) as typeof process.stdout.write;+});++describe('gbrain#5607 — local recall --grep filters in SQL before LIMIT', () => {+ test('needle older than the newest-N window is still found (no-filter arm)', async () => {+ const needle = await seed({ entity: 'g5607-a' });+ const out = await recallJson(['--grep', 'g5607 needle', '--limit', String(LIMIT)]);+ expect(out.total).toBe(1);+ expect(out.facts[0].fact).toBe(needle);+ await engine.executeRaw(`DELETE FROM facts WHERE entity_slug='g5607-a'`);+ });++ test('entity arm: --grep narrows entity rows in SQL too', async () => {+ const needle = await seed({ entity: 'g5607-b' });+ const out = await recallJson(['g5607-b', '--grep', 'g5607 needle', '--limit', String(LIMIT)]);+ expect(out.total).toBe(1);+ expect(out.facts[0].fact).toBe(needle);+ await engine.executeRaw(`DELETE FROM facts WHERE entity_slug='g5607-b'`);+ });++ test('session arm: --grep reaches facts outside the newest-N window', async () => {+ const needle = await seed({ entity: 'g5607-c', session: 'g5607-sess' });+ const out = await recallJson(['--session', 'g5607-sess', '--grep', 'g5607 needle', '--limit', String(LIMIT)]);+ expect(out.total).toBe(1);+ expect(out.facts[0].fact).toBe(needle);+ await engine.executeRaw(`DELETE FROM facts WHERE entity_slug='g5607-c'`);+ });++ test('non-matching grep returns empty, not the unfiltered window', async () => {+ await seed({ entity: 'g5607-d' });+ const out = await recallJson(['--grep', 'absent-needle-xyz', '--limit', String(LIMIT)]);+ expect(out.total).toBe(0);+ await engine.executeRaw(`DELETE FROM facts WHERE entity_slug='g5607-d'`);+ });++ test('since arm: --grep reaches facts outside the newest-N window', async () => {+ const needle = await seed({ entity: 'g5607-e' });+ const out = await recallJson(['--since', '1 day', '--grep', 'g5607 needle', '--limit', String(LIMIT)]);+ expect(out.facts.map(f => f.fact)).toEqual([needle]);+ await engine.executeRaw(`DELETE FROM facts WHERE entity_slug='g5607-e'`);+ });++ test('LIKE metacharacters in --grep match literally', async () => {+ await engine.insertFact({ fact: 'g5607 rollout at 50%_done', kind: 'fact', entity_slug: 'g5607-f', source: 'test' }, { source_id: SRC });+ await engine.insertFact({ fact: 'g5607 rollout at 50 and more done', kind: 'fact', entity_slug: 'g5607-f', source: 'test' }, { source_id: SRC });+ const out = await recallJson(['--grep', '50%_d', '--limit', String(LIMIT)]);+ expect(out.facts.map(f => f.fact)).toEqual(['g5607 rollout at 50%_done']);+ await engine.executeRaw(`DELETE FROM facts WHERE entity_slug='g5607-f'`);+ });+});diff --git a/test/repair-command.test.ts b/test/repair-command.test.tsnew file mode 100644index 0000000000..2f28169ce8--- /dev/null+++ b/test/repair-command.test.ts@@ -0,0 +1,222 @@+/**+ * `gbrain repair` core: dry run by default, --apply writes through coordinated+ * page writes, --limit + resume, the shared scope resolver, the 90% capacity+ * stop, the thin-client refusal, and the timeline_history doctor signal.+ */+import { afterAll, beforeAll, describe, 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 type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { resolveRepairScope, runRepair } from '../src/core/repair/core.ts';+import { timelineRepair } from '../src/core/repair/timeline.ts';+import { runRepairCommand } from '../src/commands/repair.ts';+import { timelineHistoryCheck } from '../src/commands/doctor/checks/timeline-history.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { withEnv } from './helpers/with-env.ts';+import { testBackends } from './helpers/test-backends.ts';+import { runCli } from './helpers/cli-spawn.ts';++const backends = testBackends();+const engines: BrainEngine[] = [];+let closePostgres: (() => Promise<void>) | undefined;+const dataDir = mkdtempSync(join(tmpdir(), 'gbrain-repair-'));++beforeAll(async () => {+ if (backends.includes('pglite')) {+ const engine = new PGLiteEngine();+ await engine.connect({}); await engine.initSchema(); engines.push(engine);+ }+ if (backends.includes('postgres')) {+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);+ engines.push(pg.engine); closePostgres = pg.close;+ }+}, 120_000);++afterAll(async () => {+ for (const engine of engines) { await disposePersistenceConsumer(engine); if (engine.kind === 'pglite') await engine.disconnect(); }+ await closePostgres?.();+ rmSync(dataDir, { recursive: true, force: true });+});++const ctxFor = (engine: BrainEngine, sourceId: string) => ({ engine, sourceId, remote: false as const, config: { engine: engine.kind, embedding_disabled: true },+ dryRun: false, logger: { info() {}, warn() {}, error() {} } }) as never;+const page = (body: string) => `---\ntype: note\ntitle: Example\n---\n${body}\n`;++async function brain(run: (engine: BrainEngine, sources: string[]) => Promise<void>, sourceCount = 1) {+ for (const engine of engines) {+ const dir = mkdtempSync(join(dataDir, 'case-'));+ const sources = Array.from({ length: sourceCount }, () => `repair-${randomUUID().slice(0, 8)}`);+ try {+ await withEnv({ GBRAIN_HOME: join(dir, 'home') }, async () => {+ await engine.executeRaw("DELETE FROM op_checkpoints WHERE op='repair'");+ await engine.executeRaw("DELETE FROM config WHERE key LIKE 'persistence.limits.%'");+ await engine.executeRaw('UPDATE sources SET archived=true WHERE archived IS NOT TRUE');+ for (const id of sources) {+ const root = join(dir, id); mkdirSync(root);+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [id, root]);+ await claimWorktree(engine, id, root);+ }+ await run(engine, sources);+ });+ } finally {+ await disposePersistenceConsumer(engine);+ }+ }+}++async function pageWithHistory(engine: BrainEngine, sourceId: string, slug: string) {+ await submitPageMutation(ctxFor(engine, sourceId), { operation: 'put_page', params: { slug, content: page(`Body of ${slug}.`), request_id: randomUUID() } });+ await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => tx.executeRaw(+ `INSERT INTO timeline_entries(page_id,date,source,summary,detail) SELECT id,'2026-07-01','legacy',$3,'' FROM pages WHERE source_id=$1 AND slug=$2`,+ [sourceId, slug, `History of ${slug}`])));+}++const markedPages = async (engine: BrainEngine, sourceId: string) => (await engine.executeRaw<{ slug: string }>(+ `SELECT slug FROM pages WHERE source_id=$1 AND timeline LIKE '%gbrain:materialized%' ORDER BY slug`, [sourceId])).map(r => r.slug);++describe('gbrain repair timeline', () => {+ test('previews without writing, applies, and a second apply changes nothing', async () => {+ await brain(async (engine, [source]) => {+ await pageWithHistory(engine, source, 'notes/a');+ const scope = await resolveRepairScope(engine);+ expect(scope.source_ids).toEqual([source]);+ const preview = await runRepair(ctxFor(engine, source), timelineRepair, scope, { apply: false });+ expect(preview).toMatchObject({ mode: 'dry_run', affected: 1, sample: [`${source}:notes/a`], cost: { lifetime_ids: 1, receipt_bytes: 16_384 },+ apply_command: 'gbrain repair timeline --apply' });+ expect(await markedPages(engine, source)).toEqual([]);+ const applied = await runRepair(ctxFor(engine, source), timelineRepair, scope, { apply: true });+ expect(applied).toMatchObject({ applied: 1, complete: true });+ expect(await markedPages(engine, source)).toEqual(['notes/a']);+ const again = await runRepair(ctxFor(engine, source), timelineRepair, scope, { apply: true });+ expect(again).toMatchObject({ affected: 0, applied: 0, complete: true });+ });+ }, 120_000);++ test('--limit stops after n items and a rerun resumes from the scope-bound checkpoint', async () => {+ await brain(async (engine, [source]) => {+ for (const slug of ['notes/a', 'notes/b', 'notes/c']) await pageWithHistory(engine, source, slug);+ const scope = await resolveRepairScope(engine);+ const first = await runRepair(ctxFor(engine, source), timelineRepair, scope, { apply: true, limit: 1 });+ expect(first).toMatchObject({ affected: 3, applied: 1, complete: false });+ expect(await markedPages(engine, source)).toEqual(['notes/a']);+ const second = await runRepair(ctxFor(engine, source), timelineRepair, scope, { apply: true });+ expect(second.resumed_from).not.toBeNull();+ expect(second).toMatchObject({ affected: 2, applied: 2, complete: true });+ expect(await markedPages(engine, source)).toEqual(['notes/a', 'notes/b', 'notes/c']);+ expect(await engine.executeRaw("SELECT 1 FROM op_checkpoints WHERE op='repair'")).toEqual([]);+ });+ }, 120_000);++ test('preview and apply on a two-source brain with identical slugs report and touch the same scope', async () => {+ await brain(async (engine, [a, b]) => {+ await pageWithHistory(engine, a, 'notes/same');+ await pageWithHistory(engine, b, 'notes/same');+ const scope = await resolveRepairScope(engine, a);+ expect(scope.source_ids).toEqual([a]);+ const preview = await runRepair(ctxFor(engine, a), timelineRepair, scope, { apply: false, sourceFlag: a });+ expect(preview).toMatchObject({ affected: 1, sample: [`${a}:notes/same`], apply_command: `gbrain repair timeline --source ${a} --apply` });+ await runRepair(ctxFor(engine, a), timelineRepair, scope, { apply: true, sourceFlag: a });+ expect(await markedPages(engine, a)).toEqual(['notes/same']);+ expect(await markedPages(engine, b)).toEqual([]);+ await expect(resolveRepairScope(engine, 'no-such-source')).rejects.toMatchObject({ code: 'invalid_params' });+ }, 2);+ }, 120_000);++ test('an applying run stops before crossing 90% of a cumulative cap, prints the config command, and resumes after it is raised', async () => {+ await brain(async (engine, [source]) => {+ for (const slug of ['notes/a', 'notes/b']) await pageWithHistory(engine, source, slug);+ const [{ used }] = await engine.executeRaw<{ used: string }>("SELECT lifetime_ids::text AS used FROM persistence_counters WHERE key='brain'");+ await engine.executeRaw("INSERT INTO config(key,value) VALUES('persistence.limits.brain_lifetime_ids',$1)", [String(Number(used) + 2)]);+ const scope = await resolveRepairScope(engine);+ const stopped = await runRepair(ctxFor(engine, source), timelineRepair, scope, { apply: true });+ expect(stopped.applied).toBe(0);+ expect(stopped.stopped?.reason).toBe('capacity');+ expect(stopped.stopped?.message).toMatch(/gbrain config set persistence\.limits\.brain_lifetime_ids \d+/);+ const needed = stopped.stopped!.message.match(/brain_lifetime_ids (\d+)/)![1];+ await engine.executeRaw("UPDATE config SET value=$1 WHERE key='persistence.limits.brain_lifetime_ids'", [needed]);+ const resumed = await runRepair(ctxFor(engine, source), timelineRepair, scope, { apply: true });+ expect(resumed).toMatchObject({ applied: 2, complete: true });+ });+ }, 120_000);++ test('a terminal failure does not block the retry once its cause is fixed', async () => {+ await brain(async (engine, [source]) => {+ await pageWithHistory(engine, source, 'notes/a');+ const [{ local_path }] = await engine.executeRaw<{ local_path: string }>('SELECT local_path FROM sources WHERE id=$1', [source]);+ const file = join(local_path, 'notes/a.md');+ const original = readFileSync(file, 'utf8');+ writeFileSync(file, `${original}\nAn uncoordinated local edit.\n`);+ const scope = await resolveRepairScope(engine);+ await expect(runRepair(ctxFor(engine, source), timelineRepair, scope, { apply: true })).rejects.toBeDefined();+ writeFileSync(file, original);+ const retried = await runRepair(ctxFor(engine, source), timelineRepair, scope, { apply: true });+ expect(retried).toMatchObject({ applied: 1, complete: true });+ expect(await markedPages(engine, source)).toEqual(['notes/a']);+ });+ }, 120_000);++ test('the command prints the resolved scope, refuses --yes and unknown kinds, and previews every kind by default', async () => {+ await brain(async (engine, [source]) => {+ await pageWithHistory(engine, source, 'notes/a');+ const out: string[] = [];+ const log = console.log;+ console.log = (...args: unknown[]) => { out.push(args.join(' ')); };+ try {+ await runRepairCommand(engine, ['--json']);+ await runRepairCommand(engine, ['timeline']);+ } finally { console.log = log; }+ const json = JSON.parse(out[0]);+ expect(json.scope.source_ids).toEqual([source]);+ expect(json.results.map((r: { kind: string }) => r.kind)).toEqual(['timeline', 'visibility', 'safe-chunks']);+ expect(json.results[0]).toMatchObject({ mode: 'dry_run', affected: 1 });+ expect(out[1]).toContain(`Scope: brain `);+ expect(out[1]).toContain(`sources ${source}`);+ await expect(runRepairCommand(engine, ['timeline', '--yes'])).rejects.toMatchObject({ code: 'invalid_params' });+ await expect(runRepairCommand(engine, ['bogus'])).rejects.toMatchObject({ code: 'invalid_params' });+ await expect(runRepairCommand(engine, ['--apply'])).rejects.toMatchObject({ code: 'invalid_params' });+ expect(await markedPages(engine, source)).toEqual([]);+ });+ }, 120_000);+});++describe('timeline_history doctor check', () => {+ test('exact counts on a seeded brain, a lower bound when the scan is capped, and ok after the repair', async () => {+ await brain(async (engine, [source]) => {+ await pageWithHistory(engine, source, 'notes/a');+ await pageWithHistory(engine, source, 'notes/b');+ await engine.transaction(tx => withCoordinatedWrite(tx, [source], () => tx.executeRaw(+ `INSERT INTO timeline_entries(page_id,date,source,summary,detail) SELECT id,'2026-07-02','','No source row','' FROM pages WHERE source_id=$1 AND slug='notes/a'`, [source])));+ const full = await timelineHistoryCheck(engine, source);+ expect(full.status).toBe("warn");+ expect(full.details).toMatchObject({ materializable_rows: 2, kept_unrenderable_rows: 1, pages_affected: 2, count: 'exact', truncated: false });+ expect(full.message).toContain('gbrain repair timeline');+ const capped = await timelineHistoryCheck(engine, source, { pageCap: 1 });+ expect(capped.status).toBe('warn');+ expect(capped.details).toMatchObject({ materializable_rows: 1, count: 'lower_bound', truncated: true });+ expect(capped.message).toContain('at least');+ await runRepair(ctxFor(engine, source), timelineRepair, await resolveRepairScope(engine), { apply: true });+ const after = await timelineHistoryCheck(engine, source);+ expect(after.status).toBe('ok');+ expect(after.details).toMatchObject({ materializable_rows: 0, kept_unrenderable_rows: 1, count: 'exact' });+ });+ }, 120_000);+});++describe('thin clients', () => {+ test('gbrain repair refuses with a run-on-the-brain-host hint', async () => {+ const home = mkdtempSync(join(dataDir, 'thin-'));+ mkdirSync(join(home, '.gbrain'), { recursive: true });+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'postgres', remote_mcp: {+ issuer_url: 'https://brain-host.example', mcp_url: 'https://brain-host.example/mcp', oauth_client_id: 'cid', oauth_client_secret: 'csecret' } }));+ const result = await runCli(['repair', 'timeline'], { home, env: { GBRAIN_REMOTE_CLIENT_SECRET: undefined } });+ expect(result.exitCode).toBe(1);+ expect(result.stderr).toContain('Run `gbrain repair` on the brain host');+ }, 60_000);+});diff --git a/test/safe-chunk-reseal.test.ts b/test/safe-chunk-reseal.test.tsnew file mode 100644index 0000000000..e709e6d373--- /dev/null+++ b/test/safe-chunk-reseal.test.ts@@ -0,0 +1,249 @@+/**+ * #5050 + #5247: pages chunked before the safe-chunk fence (chunker v4) are+ * withheld from every remote read. Re-importing their unchanged content+ * re-seals them projection-only (no page write, no journal admission, no+ * lifetime ID); doctor and the `safe_index_pending` hint count code pages as+ * well as markdown and fire on partial results; `gbrain repair safe-chunks`+ * drains the rest on a managed brain with zero admissions.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import type { SearchResult } from '../src/core/types.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { importCodeFile, importFromContent } from '../src/core/import-file.ts';+import { operationsByName, type OperationContext } from '../src/core/operations.ts';+import { rebuildPendingPageProjections } from '../src/core/page-state/projections.ts';+import { SAFE_FENCE_CHUNKER_VERSION } from '../src/core/search/safe-chunks.ts';+import { checkContextualRetrievalCoverage } from '../src/commands/doctor/checks/calibration.ts';+import { runImport } from '../src/commands/import.ts';+import { contentHashLegacy } from '../src/core/utils.ts';+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { resolveRepairScope, runRepair } from '../src/core/repair/core.ts';+import { __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts';+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { withEnv } from './helpers/with-env.ts';+import { testBackends } from './helpers/test-backends.ts';++const backends = testBackends();+const home = mkdtempSync(join(tmpdir(), 'gbrain-safe-chunks-'));+afterAll(() => rmSync(home, { recursive: true, force: true }));++const md = (body: string) => `---\ntitle: Synthetic note\ntype: note\nvisibility: world\n---\n\n${body}\n`;+const code = `export function verifyTurnstile(token: string) {\n const secret = process.env.TURNSTILE_SECRET_KEY;\n return secret + token;\n}\n`;++async function openPostgres(): Promise<{ engine: BrainEngine; close: () => Promise<void> }> {+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);+ return { engine: pg.engine, close: pg.close };+}++const pageState = async (engine: BrainEngine, sourceId: string, slug: string) => (await engine.executeRaw<{ chunker_version: number; revision: string; sealed: boolean; versions: number }>(+ `SELECT p.chunker_version, p.knowledge_revision::text AS revision, (p.text_projection_revision = p.knowledge_revision) AS sealed,+ (SELECT COUNT(*)::int FROM page_versions v WHERE v.page_id = p.id) AS versions+ FROM pages p WHERE p.source_id=$1 AND p.slug=$2`, [sourceId, slug]))[0];+const journal = async (engine: BrainEngine) => (await engine.executeRaw<{ requests: number; ids: string }>(+ `SELECT (SELECT COUNT(*)::int FROM persistence_requests) AS requests,+ COALESCE((SELECT lifetime_ids::text FROM persistence_counters WHERE key='brain'), '0') AS ids`))[0];++for (const kind of backends) {+ describe(`#5050/#5247 safe-chunk re-seal ${kind}`, () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;+ const sourceId = 'reseal-src';+ let meta: Record<string, unknown> = {};+ const ctx = (remote: boolean): OperationContext => ({ engine, config: { engine: engine.kind }, dryRun: false, remote, sourceId,+ logger: { info() {}, warn() {}, error() {} }, emitResponseMeta: (key: string, value: unknown) => { meta[key] = value; } }) as OperationContext;+ const degraded = () => ((meta.retrieval as { degraded?: Array<{ stage: string }> } | undefined)?.degraded ?? []).map(d => d.stage);+ const remoteSearch = async (query: string) => {+ meta = {};+ __resetPrivateVisibilityCacheForTests();+ return (await operationsByName.search.handler(ctx(true), { query, limit: 10 }) as SearchResult[]).map(r => r.slug);+ };++ beforeAll(async () => {+ if (kind === 'postgres') ({ engine, close } = await openPostgres());+ else {+ const pglite = new PGLiteEngine();+ await pglite.connect({}); await pglite.initSchema();+ engine = pglite; close = () => pglite.disconnect();+ }+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES ($1,$1)', [sourceId]);+ await engine.setConfig('search.mcp_keyword_only', 'true');+ await engine.setConfig('search.crag_escalation', 'false');+ }, 120_000);+ afterAll(async () => { await close(); });++ test('re-importing unchanged markdown below the fence re-seals it without a page write', async () => {+ const slug = 'people/zebra-keeper';+ const content = md('The keeper likes zebras and pottery.');+ expect((await importFromContent(engine, slug, content, { sourceId, noEmbed: true })).status).toBe('imported');+ await engine.executeRaw('UPDATE pages SET chunker_version=3 WHERE source_id=$1 AND slug=$2', [sourceId, slug]);+ expect(await remoteSearch('zebras')).toEqual([]);+ const before = await pageState(engine, sourceId, slug);+ expect((await importFromContent(engine, slug, content, { sourceId, noEmbed: true })).status).toBe('skipped');+ const after = await pageState(engine, sourceId, slug);+ expect(after.chunker_version).toBeGreaterThanOrEqual(SAFE_FENCE_CHUNKER_VERSION);+ expect(after.sealed).toBe(true);+ expect([after.revision, after.versions]).toEqual([before.revision, before.versions]);+ expect(await remoteSearch('zebras')).toEqual([slug]);+ expect(await journal(engine)).toEqual({ requests: 0, ids: '0' });+ });++ test('the pre-#3694 legacy content-hash branch re-seals too', async () => {+ const slug = 'people/legacy-hash-keeper';+ const content = md('The legacy keeper counts herons.');+ await importFromContent(engine, slug, content, { sourceId, noEmbed: true });+ const [page] = await engine.executeRaw<{ title: string; type: string; compiled_truth: string; timeline: string; frontmatter: Record<string, unknown> }>(+ 'SELECT title,type,compiled_truth,timeline,frontmatter FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, slug]);+ await engine.executeRaw('UPDATE pages SET chunker_version=3, content_hash=$3 WHERE source_id=$1 AND slug=$2',+ [sourceId, slug, contentHashLegacy(page as never)]);+ expect((await importFromContent(engine, slug, content, { sourceId, noEmbed: true })).status).toBe('skipped');+ expect((await pageState(engine, sourceId, slug)).chunker_version).toBeGreaterThanOrEqual(SAFE_FENCE_CHUNKER_VERSION);+ });++ test('re-importing an unchanged code file below the fence re-seals it, with or without --no-embed', async () => {+ for (const [path, noEmbed] of [['lib/turnstile-a.ts', true], ['lib/turnstile-b.ts', false]] as const) {+ const imported = await importCodeFile(engine, path, code, { sourceId, noEmbed: true });+ expect(imported.status).toBe('imported');+ await engine.executeRaw('UPDATE pages SET chunker_version=1 WHERE source_id=$1 AND slug=$2', [sourceId, imported.slug]);+ const before = await pageState(engine, sourceId, imported.slug);+ await importCodeFile(engine, path, code, { sourceId, noEmbed });+ const after = await pageState(engine, sourceId, imported.slug);+ expect(after.chunker_version).toBeGreaterThanOrEqual(SAFE_FENCE_CHUNKER_VERSION);+ expect([after.revision, after.versions]).toEqual([before.revision, before.versions]);+ }+ expect(await journal(engine)).toEqual({ requests: 0, ids: '0' });+ });++ test('a coordinated re-import of unchanged legacy content is a no-op that queues a projection-only re-seal', async () => {+ const slug = 'people/prepared-keeper';+ const content = md('The prepared keeper studies granite.');+ await importFromContent(engine, slug, content, { sourceId, noEmbed: true });+ await engine.executeRaw('UPDATE pages SET chunker_version=2 WHERE source_id=$1 AND slug=$2', [sourceId, slug]);+ let noop: boolean | undefined;+ let apply: ((tx: BrainEngine) => Promise<unknown>) | undefined;+ await importFromContent(engine, slug, content, { sourceId, noEmbed: true,+ prepare: async value => { noop = value.noop; apply = value.apply as never; return value.result; } });+ expect(noop).toBe(true);+ await engine.transaction(tx => apply!(tx));+ const jobs = await engine.executeRaw<{ reason: string }>('SELECT reason FROM page_projection_jobs WHERE slug=$1', [slug]);+ expect(jobs.map(j => j.reason)).toEqual(['safe_chunk_reseal']);+ expect(await rebuildPendingPageProjections(engine, 10)).toMatchObject({ rebuilt: 1 });+ expect((await pageState(engine, sourceId, slug)).chunker_version).toBeGreaterThanOrEqual(SAFE_FENCE_CHUNKER_VERSION);+ expect(await journal(engine)).toEqual({ requests: 0, ids: '0' });+ });++ test('a directory import (the sync --full path) reports re-sealed pages and the embedding work they left', async () => {+ const dir = mkdtempSync(join(home, `import-${kind}-`));+ writeFileSync(join(dir, 'walrus.md'), md('Walruses rest on sea ice.'));+ await withEnv({ GBRAIN_HOME: join(home, `import-home-${kind}`) }, async () => {+ const first = await runImport(engine, [dir, '--fresh', '--no-embed', '--json'], { sourceId });+ expect(first.imported).toBe(1);+ expect(first.resealed).toBeUndefined();+ await engine.executeRaw("UPDATE pages SET chunker_version=3 WHERE source_id=$1 AND slug='walrus'", [sourceId]);+ const second = await runImport(engine, [dir, '--fresh', '--no-embed', '--json'], { sourceId });+ expect(second).toMatchObject({ imported: 0, resealed: { pages: 1, pending_chunks: 1 } });+ });+ expect((await pageState(engine, sourceId, 'walrus')).chunker_version).toBeGreaterThanOrEqual(SAFE_FENCE_CHUNKER_VERSION);+ });++ test('doctor and safe_index_pending count legacy code pages; the hint fires on partial results', async () => {+ const imported = await importCodeFile(engine, 'lib/legacy-only.ts', code.replace('verifyTurnstile', 'legacyOnlyMarker'), { sourceId, noEmbed: true });+ await engine.executeRaw('UPDATE pages SET chunker_version=1 WHERE source_id=$1 AND slug=$2', [sourceId, imported.slug]);+ const check = await checkContextualRetrievalCoverage(engine, { sourceIds: [sourceId] });+ expect(check.message).toContain('1 page(s) below the safe-chunk index version');+ expect(check.message).toContain('gbrain repair safe-chunks');+ expect(await remoteSearch('legacyOnlyMarker')).toEqual([]);+ expect(degraded()).toContain('safe_index_pending');+ // A sealed page still matches, so the result is partial, not empty.+ const hits = await remoteSearch('zebras');+ expect(hits.length).toBeGreaterThan(0);+ expect(degraded()).toContain('safe_index_pending');+ await engine.executeRaw('DELETE FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, imported.slug]);+ await remoteSearch('zebras');+ expect(degraded()).not.toContain('safe_index_pending');+ });+ });++ describe(`gbrain repair safe-chunks ${kind}`, () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;+ beforeAll(async () => {+ if (kind === 'postgres') ({ engine, close } = await openPostgres());+ else {+ const pglite = new PGLiteEngine();+ await pglite.connect({}); await pglite.initSchema();+ engine = pglite; close = () => pglite.disconnect();+ }+ }, 120_000);+ afterAll(async () => { await disposePersistenceConsumer(engine); await close(); });++ const repairCtx = (sourceId: string) => ({ engine, sourceId, remote: false as const, config: { engine: engine.kind, embedding_disabled: true },+ dryRun: false, logger: { info() {}, warn() {}, error() {} } }) as never;++ test('previews, then re-seals legacy markdown and code pages on a managed brain with zero admissions; a rerun changes nothing', async () => {+ await withEnv({ GBRAIN_HOME: join(home, `managed-${kind}`) }, async () => {+ const sourceId = `repair-${randomUUID().slice(0, 8)}`;+ const root = join(home, `root-${kind}-${sourceId}`); mkdirSync(root, { recursive: true });+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);+ await claimWorktree(engine, sourceId, root);+ const ctx = repairCtx(sourceId);+ for (const slug of ['notes/a', 'notes/b']) {+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug, content: md(`Legacy body of ${slug}.`), request_id: randomUUID() } });+ }+ let codeSlug = '';+ await importCodeFile(engine, 'lib/legacy.ts', code, { sourceId, noEmbed: true, prepare: async value => {+ codeSlug = value.slug;+ await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => value.apply(tx)));+ return value.result;+ } });+ await engine.executeRaw('UPDATE pages SET chunker_version=1 WHERE source_id=$1', [sourceId]);+ const scope = await resolveRepairScope(engine, sourceId);+ const { safeChunksRepair, safeChunkUpgradeAdvisory } = await import('../src/core/repair/safe-chunks.ts');+ const advisory = await safeChunkUpgradeAdvisory(engine, true);+ expect(advisory).toContain('3 page(s) are below the safe-chunk index version');+ expect(advisory).toContain('gbrain repair safe-chunks --apply');+ const preview = await runRepair(ctx, safeChunksRepair, scope, { apply: false, sourceFlag: sourceId });+ expect(preview).toMatchObject({ kind: 'safe-chunks', mode: 'dry_run', affected: 3,+ cost: { lifetime_ids: 0, receipt_bytes: 0, embedding_pages: 3 }, apply_command: `gbrain repair safe-chunks --source ${sourceId} --apply` });+ expect(preview.sample).toEqual(expect.arrayContaining([`${sourceId}:notes/a`, `${sourceId}:${codeSlug}`]));+ const before = await journal(engine);+ const first = await runRepair(ctx, safeChunksRepair, scope, { apply: true, limit: 1, sourceFlag: sourceId });+ expect(first).toMatchObject({ applied: 1, complete: false });+ const rest = await runRepair(ctx, safeChunksRepair, scope, { apply: true, sourceFlag: sourceId });+ expect(rest).toMatchObject({ affected: 2, applied: 2, complete: true });+ expect(rest.resumed_from).not.toBeNull();+ expect(await journal(engine)).toEqual(before);+ const versions = await engine.executeRaw<{ v: number }>('SELECT chunker_version AS v FROM pages WHERE source_id=$1', [sourceId]);+ expect(versions.every(r => Number(r.v) >= SAFE_FENCE_CHUNKER_VERSION)).toBe(true);+ const again = await runRepair(ctx, safeChunksRepair, scope, { apply: true, sourceFlag: sourceId });+ expect(again).toMatchObject({ affected: 0, applied: 0, complete: true });+ expect(await safeChunkUpgradeAdvisory(engine, true)).toBeNull();++ // A provider failure after the re-seal keeps the re-seal and names the recovery command.+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug: 'notes/c', content: md('Legacy body of notes/c.'), request_id: randomUUID() } });+ await engine.executeRaw("UPDATE pages SET chunker_version=1 WHERE source_id=$1 AND slug='notes/c'", [sourceId]);+ const warnings: string[] = [];+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: { OPENAI_API_KEY: 'sk-fake' } });+ __setEmbedTransportForTests((async () => { throw new Error('synthetic provider outage'); }) as never);+ try {+ const failing = { ...(ctx as object), logger: { info() {}, warn: (m: string) => { warnings.push(m); }, error() {} } } as never;+ const embedded = await runRepair(failing, safeChunksRepair, scope, { apply: true, embed: true, sourceFlag: sourceId });+ expect(embedded).toMatchObject({ applied: 1, complete: true });+ } finally {+ __setEmbedTransportForTests(null);+ resetGateway();+ }+ expect(warnings.join('\n')).toContain(`gbrain embed --stale --source ${sourceId}`);+ expect((await pageState(engine, sourceId, 'notes/c')).chunker_version).toBeGreaterThanOrEqual(SAFE_FENCE_CHUNKER_VERSION);+ });+ }, 120_000);+ });+}diff --git a/test/search-safe-index-probe.test.ts b/test/search-safe-index-probe.test.tsindex 11c2efbfae..3e0d78a614 100644--- a/test/search-safe-index-probe.test.ts+++ b/test/search-safe-index-probe.test.ts@@ -2,11 +2,11 @@* #5004 (pre-landing review) — the `safe_index_pending` probe in* `src/core/ops/search.ts` (`hasUnsealedPagesInScope`) runs on EVERY empty* remote search/query. On a fully sealed brain it must be an index probe, not- * a walk of every markdown page: `NOT (COALESCE(chunker_version, 0) >= N)` is- * not sargable, so the partial btree `pages_chunker_version_idx` can only be- * scanned whole with the predicate as a post-scan Filter. `pages.chunker_version`- * is `SMALLINT NOT NULL DEFAULT 1` (cjk_wave migration), so the plain range- * `chunker_version < N` is the same set and lets the planner use an Index Cond.+ * a walk of every page: `NOT (COALESCE(chunker_version, 0) >= N)` is not+ * sargable. `pages.chunker_version` is `SMALLINT NOT NULL DEFAULT 1` (cjk_wave+ * migration), so the plain range `chunker_version < N` is the same set and+ * matches the partial `pages_safe_chunk_pending_idx`, which holds only unsealed+ * pages. #5247: the probe counts pages of every kind, not just markdown.** Pins both layers: the SQL text the probe issues, and the PGLite plan for it* (seq scans disabled so a non-sargable predicate cannot hide behind a small@@ -59,13 +59,14 @@ function recordingCtx(): OperationContext {}describe('safe_index_pending probe stays sargable (#5004)', () => {- test('an empty remote search issues a plain chunker_version range the partial index serves as an Index Cond', async () => {+ test('a remote search issues a plain chunker_version range over every page kind that the unsealed-only index serves', async () => {captured.length = 0;const rows = await operationsByName.search.handler(recordingCtx(), { query: 'nosuchtokenanywhere', limit: 5 });expect(rows).toEqual([]);- const probe = captured.find(c => c.sql.includes("page_kind = 'markdown'") && /LIMIT 1/.test(c.sql));+ const probe = captured.find(c => c.sql.includes(`p.chunker_version < ${SAFE_FENCE_CHUNKER_VERSION}`) && /LIMIT 1/.test(c.sql));expect(probe).toBeDefined();+ expect(probe!.sql).not.toContain('page_kind');expect(probe!.sql).not.toContain('COALESCE(p.chunker_version');expect(probe!.sql).toContain(`p.chunker_version < ${SAFE_FENCE_CHUNKER_VERSION}`);@@ -73,8 +74,8 @@ describe('safe_index_pending probe stays sargable (#5004)', () => {try {const plan = (await engine.executeRaw<Record<string, string>>(`EXPLAIN ${probe!.sql}`, probe!.params)).map(r => Object.values(r)[0]).join('\n');- expect(plan).toContain('Index Scan using pages_chunker_version_idx');- expect(plan).toContain(`Index Cond: (chunker_version < ${SAFE_FENCE_CHUNKER_VERSION})`);+ expect(plan).toContain('pages_safe_chunk_pending_idx');+ expect(plan).not.toContain('Seq Scan');} finally {await engine.executeRaw('RESET enable_seqscan');}diff --git a/test/shared-skills-export-projection.serial.test.ts b/test/shared-skills-export-projection.serial.test.tsindex c27035fabf..e0ebccac3f 100644--- a/test/shared-skills-export-projection.serial.test.ts+++ b/test/shared-skills-export-projection.serial.test.ts@@ -31,7 +31,8 @@ async function fixture(run: (ctx: OperationContext, root: string) => Promise<voiawait engine.putPage('notes/example', { type: 'note', title: 'Example', compiled_truth: body, timeline: '', frontmatter: { visibility: 'private' } }, { sourceId: 'default' });const page = (await engine.getPage('notes/example', { sourceId: 'default' }))!;const parsed = parseMarkdown(serializePageToMarkdown(page, []), 'notes/example.md');- await engine.transaction(tx => prepareCanonicalProjections(parsed, page.slug, 'default')(tx));+ const project = await prepareCanonicalProjections(engine, parsed, page.slug, 'default', null, 'editing');+ await engine.transaction(tx => project(tx));await run({ engine, config: { engine: databaseUrl ? 'postgres' : 'pglite', mcp: { publish_skills: false } }, sourceId: 'default', remote: false, dryRun: false,logger: { info() {}, warn() {}, error() {} } }, join(home, 'content'));} finally { await close(); rmSync(home, { recursive: true, force: true }); }@@ -102,7 +103,8 @@ test('an incomplete resolution cannot invent a resolver during export validationresolvedAt: '2026-01-01', resolvedQuality: 'correct', resolvedEvidence: 'Synthetic evidence without attribution' }]).trim();await ctx.engine.putPage('notes/incomplete', { type: 'note', title: 'Incomplete', compiled_truth: incomplete, timeline: '', frontmatter: {} }, { sourceId: 'default' });const page = (await ctx.engine.getPage('notes/incomplete', { sourceId: 'default' }))!;- await ctx.engine.transaction(tx => prepareCanonicalProjections(parseMarkdown(serializePageToMarkdown(page, []), 'notes/incomplete.md'), page.slug, 'default')(tx));+ const project = await prepareCanonicalProjections(ctx.engine, parseMarkdown(serializePageToMarkdown(page, []), 'notes/incomplete.md'), page.slug, 'default', null, 'editing');+ await ctx.engine.transaction(tx => project(tx));const before = await ctx.engine.executeRaw('SELECT * FROM takes ORDER BY id');const result = await exportDatabaseContent(ctx, { sourceId: 'default', root, confirmQuiesced: true, backup: 'operator_verified' });expect(result.status).toBe('conflict');diff --git a/test/shared-skills-writer-boundary.serial.test.ts b/test/shared-skills-writer-boundary.serial.test.tsindex bd1b305625..cd563676cb 100644--- a/test/shared-skills-writer-boundary.serial.test.ts+++ b/test/shared-skills-writer-boundary.serial.test.ts@@ -14,10 +14,11 @@ import { publishMutation } from '../src/core/persistence/coordinator.ts';import { managedSyncAuthority } from '../src/core/persistence/sync-authority.ts';import { prepareManagedSyncMutation, type SyncIntent } from '../src/core/persistence/sync-prepare.ts';import { sha256 } from '../src/core/persistence/digest.ts';+import { serializePageToMarkdown } from '../src/core/markdown.ts';import { importFromContent } from '../src/core/import-file.ts';import { activateSharedSkillPersistence } from '../src/core/persistence/skill-activation.ts';import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';-import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { disposePersistenceConsumer, writeResponse } from '../src/core/persistence/service.ts';import { adoptSharedSkillpack } from '../src/core/shared-skills/publication.ts';import { setSharedSkillPolicy } from '../src/core/shared-skills/policy.ts';import { assertKnowledgePublicationAllowed } from '../src/core/shared-skills/knowledge-guard.ts';@@ -42,6 +43,9 @@ import { saveState, SKILLPACK_STATE_SCHEMA_VERSION } from '../src/core/skillpackimport { packTarball, extractTarball } from '../src/core/skillpack/tarball.ts';import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';import { withEnv } from './helpers/with-env.ts';+import { testBackends } from './helpers/test-backends.ts';++const postgresUrl = testBackends().includes('postgres') ? process.env.DATABASE_URL : undefined;interface Fixture { engine: BrainEngine; ctx: OperationContext; root: string; scratch: string; incarnation: string; }const prose = '---\nname: alpha\ndescription: A synthetic shared skill\n---\n\nApproved instructions.\n';@@ -52,7 +56,7 @@ async function fixture(run: (f: Fixture) => Promise<void>) {const scratch = mkdtempSync(join(tmpdir(), 'gbrain-skill-writers-'));try {await withEnv({ GBRAIN_HOME: join(scratch, 'home'), DATABASE_URL: undefined }, async () => {- const isolated = await isolatedSharedSkillsEngine();+ const isolated = await isolatedSharedSkillsEngine(postgresUrl);const engine = isolated.engine;try {const root = join(scratch, 'brain'); mkdirSync(root);@@ -66,6 +70,8 @@ async function fixture(run: (f: Fixture) => Promise<void>) {['notes/path-alias', 'skills/alpha/SKILL.md', null],['notes/manifest-alias', 'skillpack.json', null],['notes/uri-alias', null, pathToFileURL(join(root, 'skills/alpha/references/guide.md')).href],+ ['notes/invalid-uri-alias', 'notes/invalid-uri-alias.md', 'file:///notes/%2F.md'],+ ['notes/relative-uri-alias', null, 'file://notes/relative-uri-alias.md'],]) {await engine.putPage(slug!, { title: 'Synthetic alias', type: 'note', compiled_truth: '', timeline: '', frontmatter: {} }, { sourceId: 'default' });await engine.executeRaw('UPDATE pages SET source_path=$1,source_uri=$2 WHERE source_id=$3 AND slug=$4', [sourcePath, sourceUri, 'default', slug]);@@ -73,7 +79,7 @@ async function fixture(run: (f: Fixture) => Promise<void>) {await claimWorktree(engine, 'default', root);await claimWorktree(engine, 'alias-source', aliasRoot);await activateSharedSkillPersistence(engine, { confirmQuiesced: true });- const ctx: OperationContext = { engine, config: { engine: 'pglite' }, remote: false, sourceId: 'default', dryRun: false,+ const ctx: OperationContext = { engine, config: { engine: engine.kind }, remote: false, sourceId: 'default', dryRun: false,logger: { info() {}, warn() {}, error() {} } };await engine.setConfig('mcp.publish_skills', 'true');await setSharedSkillPolicy(ctx, 'default', { version: 1, enabled: true, classes: ['prose', 'reference'], audiences: ['readers'], requirements: [], allow_follow: true }, null);@@ -119,6 +125,66 @@ test('registered source roots, aliases and symlinks deny page publication withouexpect(await canonicalState(f)).toEqual(before);}), 120_000);+test('unresolvable stored file aliases fail closed with a metadata diagnostic instead of skill publication advice', () => fixture(async f => {+ const before = await canonicalState(f);+ const row = { source_id: 'default', source_incarnation: f.incarnation, slug: 'notes/invalid-uri-alias' };+ for (const preparedFile of [undefined, { root: f.root, path: join(f.root, 'notes/invalid-uri-alias.md') }]) {+ await expect(assertKnowledgePublicationAllowed(f.engine, row, preparedFile)).rejects.toMatchObject({+ code: 'invalid_source_uri',+ detail: 'invalid_source_uri',+ message: 'The page has a stored file source_uri that cannot be resolved to a local filesystem path. Have the source owner inspect and repair the stored source_uri before retrying.',+ suggestion: expect.stringContaining(`inspect the stored source_uri of page ${row.slug} in source default`),+ });+ }+ expect(await canonicalState(f)).toEqual(before);+ const [page] = await f.engine.executeRaw<{ source_uri: string }>(+ 'SELECT source_uri FROM pages WHERE source_id=$1 AND slug=$2', ['default', row.slug]);+ expect(page.source_uri).toBe('file:///notes/%2F.md');+ const snapshot = await f.engine.readPageSnapshot(row.slug, { sourceId: 'default' });+ await expect(submitPageMutation(f.ctx, { operation: 'put_page', params: {+ slug: row.slug, content: note, request_id: randomUUID(), expected_revision: snapshot!.revision,+ } })).rejects.toMatchObject({ code: 'invalid_source_uri' });+ expect(await f.engine.readPageSnapshot(row.slug, { sourceId: 'default' })).toEqual(snapshot);+ expect(existsSync(join(f.root, 'notes/invalid-uri-alias.md'))).toBe(false);+ expect(await canonicalState(f)).toEqual(before);+ // The coordinator stores the message, but not OperationError.suggestion.+ // Verify that a queued failure retains both its classification and repair hint.+ await disposePersistenceConsumer(f.engine);+ const binding = (await getWorktreeBinding(f.engine, 'default'))!;+ const authority = await submissionAuthority(f.ctx, 'put_page', 'default', f.incarnation, row.slug);+ const accepted = await admitWrite(f.engine, { principal: authority.principal, operation: 'put_page', sourceId: 'default',+ sourceIncarnation: f.incarnation, slug: row.slug, requestId: randomUUID(), callerIntent: { slug: row.slug },+ intent: { slug: row.slug }, authority, worktreeId: binding.worktree_id, topologyGeneration: binding.topology_generation });+ const claimed = (await claimNextWrite(f.engine, localHostId()))!;+ expect(claimed.id).toBe(accepted.id);+ let applied = false;+ const result = await publishMutation(f.engine, claimed, { observedRevision: snapshot!.revision,+ file: { root: f.root, path: join(f.root, 'notes/invalid-uri-alias.md'), content: note },+ apply: async () => { applied = true; return {}; } }, localHostId());+ expect(result).toMatchObject({ state: 'failed', error_code: 'invalid_source_uri', recovery: null, publication_started: false });+ expect(result.error_message).toContain('inspect and repair the stored source_uri');+ expect(() => writeResponse(result)).toThrow(expect.objectContaining({ code: 'invalid_source_uri', writeError: 'invalid_source_uri' }));+ expect(applied).toBe(false);+ expect(existsSync(join(f.root, 'notes/invalid-uri-alias.md'))).toBe(false);+ expect(await f.engine.readPageSnapshot(row.slug, { sourceId: 'default' })).toEqual(snapshot);+ expect(await canonicalState(f)).toEqual(before);+}), 120_000);++test('a relative capture file URI names no local file and never blocks ordinary knowledge writes (#5622)', () => fixture(async f => {+ const row = { source_id: 'default', source_incarnation: f.incarnation, slug: 'notes/relative-uri-alias' };+ for (const preparedFile of [undefined, { root: f.root, path: join(f.root, 'notes/relative-uri-alias.md') }]) {+ await assertKnowledgePublicationAllowed(f.engine, row, preparedFile);+ }+ const snapshot = await f.engine.readPageSnapshot(row.slug, { sourceId: 'default' });+ mkdirSync(join(f.root, 'notes'), { recursive: true });+ writeFileSync(join(f.root, 'notes/relative-uri-alias.md'), serializePageToMarkdown(snapshot!.page, snapshot!.tags));+ const result = await submitPageMutation(f.ctx, { operation: 'put_page', params: {+ slug: row.slug, content: note, request_id: randomUUID(), expected_revision: snapshot!.revision,+ } });+ expect(result.state).toBe('committed');+ expect(readFileSync(join(f.root, 'notes/relative-uri-alias.md'), 'utf8')).toContain('Skill text is data.');+}), 120_000);+test('legacy skill writers refuse before partial copies, history, optimizer evaluation and auxiliary output sinks', () => fixture(async f => {const before = await canonicalState(f);const skillsDir = join(f.root, 'skills');diff --git a/test/storage-config.test.ts b/test/storage-config.test.tsindex d9d5ebed3d..8f5a2c5032 100644--- a/test/storage-config.test.ts+++ b/test/storage-config.test.ts@@ -10,6 +10,8 @@ import {loadStorageConfig,normalizeAndValidateStorageConfig,StorageConfigError,+ isDeclaredDbOnlySlug,+ hasUnresolvedDbOnlyDeclaration,__resetMissingStorageWarning,} from '../src/core/storage-config.ts';import type { StorageConfig } from '../src/core/storage-config.ts';@@ -126,6 +128,17 @@ describe('Storage Configuration', () => {expect(isSupabaseOnly('media/xerox/foo', noSlashConfig)).toBe(false);expect(isSupabaseOnly('media/x/tweet-1', noSlashConfig)).toBe(false);});++ test.each([+ ['conversations/sessions/a', ['conversations/'], true],+ ['conversations/sessions/a', ['Conversations/'], true],+ ['conversationsx/a', ['Conversations/'], false],+ ['atoms/a', ['conversations/'], false], // derive-phase defaults are not declared+ ['conversations/a', null, false],+ ] as const)('isDeclaredDbOnlySlug(%p, %p) is %p', (slug, dbOnly, expected) => {+ const config: StorageConfig | null = dbOnly ? { db_tracked: [], db_only: [...dbOnly] } : null;+ expect(isDeclaredDbOnlySlug(slug, config)).toBe(expected);+ });});});@@ -149,6 +162,23 @@ describe('loadStorageConfig — real-disk loader', () => {rmSync(tmp, { recursive: true, force: true });}+ test.each([+ ['flow-style db_only', 'storage:\n db_only: [conversations/]\n', true],+ ['flow-style deprecated supabase_only', 'storage:\n supabase_only: [conversations/]\n', true],+ ['db_only outside the storage section', 'db_only:\n - conversations/\n', true],+ ['literal empty db_only (accepted false positive)', 'storage:\n db_only: []\n', true],+ ['block-style db_only', 'storage:\n db_only:\n - conversations/\n', false],+ ['a comment that mentions db_only', '# db_only handling later\nstorage:\n db_tracked:\n - people/\n', false],+ ['no gbrain.yml', null, false],+ ] as const)('hasUnresolvedDbOnlyDeclaration: %s is %p', (_name, yml, expected) => {+ try {+ if (yml !== null) writeFileSync(join(tmp, 'gbrain.yml'), yml);+ expect(hasUnresolvedDbOnlyDeclaration(tmp, loadStorageConfig(tmp))).toBe(expected);+ } finally {+ cleanup();+ }+ });+test('returns null when repoPath is missing', () => {try {expect(loadStorageConfig(undefined)).toBeNull();diff --git a/test/subagent-handler.test.ts b/test/subagent-handler.test.tsindex d2d62dd22d..6aca96e9e7 100644--- a/test/subagent-handler.test.ts+++ b/test/subagent-handler.test.ts@@ -970,6 +970,39 @@ describe('write accounting (#4217)', () => {expect(result.pages_failed).toBe(0);});+ test('allow_clean_zero_writes: a clean finish after a completed read completes; without it the job dead-letters (#5540)', async () => {+ const searchTurn = {+ content: [{ type: 'tool_use', id: 'tu_s', name: 'brain_search', input: { value: 'themes' } }] as any,+ stop_reason: 'tool_use' as const,+ };+ const strict = makeSubagentHandler({+ engine, client: new FakeMessagesClient([searchTurn, endTurn]),+ toolRegistry: [makeEchoTool('brain_search'), makePutPageTool('ok')],+ });+ const strictCtx = await makeCtx({ prompt: 'find patterns', require_writes: true });+ await expect(strict(strictCtx)).rejects.toThrow('zero required put_page writes');++ const handler = makeSubagentHandler({+ engine, client: new FakeMessagesClient([searchTurn, endTurn]),+ toolRegistry: [makeEchoTool('brain_search'), makePutPageTool('ok')],+ });+ const ctx = await makeCtx({ prompt: 'find patterns', require_writes: true, allow_clean_zero_writes: true });+ const result = await handler(ctx);+ expect(result.stop_reason).toBe('end_turn');+ expect(result.pages_attempted).toBe(0);+ expect(result.pages_written).toBe(0);+ });++ test('allow_clean_zero_writes does not excuse a run whose only tool failed (#5540)', async () => {+ const client = new FakeMessagesClient([+ { content: [{ type: 'tool_use', id: 'tu_b2', name: 'broken', input: {} }] as any, stop_reason: 'tool_use' },+ endTurn,+ ]);+ const handler = makeSubagentHandler({ engine, client, toolRegistry: [makeThrowingTool('broken')] });+ const ctx = await makeCtx({ prompt: 'find patterns', require_writes: true, allow_clean_zero_writes: true });+ await expect(handler(ctx)).rejects.toThrow('zero required put_page writes');+ });+test('non-put_page tool failures do not count toward write accounting', async () => {const client = new FakeMessagesClient([{ content: [{ type: 'tool_use', id: 'tu_b', name: 'broken', input: {} }] as any, stop_reason: 'tool_use' },@@ -1044,6 +1077,73 @@ describe('oneshot mode dispatch (#4216)', () => {expect(await engine.getPage(SLUG_A)).not.toBeNull();});+ test('explicit oneshot skip under require_writes completes instead of dead-lettering (#5590)', async () => {+ const client = new FakeMessagesClient([]);+ const skip = JSON.stringify({ pages: [], skipped: true, skip_reason: 'verbatim paste of an existing page' });+ const handler = makeSubagentHandler({ engine, client, _chat: chatStub(skip) });+ const ctx = await makeCtx({+ prompt: 'synthesize', mode: 'oneshot', require_writes: true,+ allowed_slug_prefixes: PREFIXES, oneshot_slug_suffix: SUFFIX,+ });+ const result = await handler(ctx);+ expect(result.synth_mode_used).toBe('oneshot');+ expect(result.oneshot_skipped).toBe(true);+ expect(result.pages_attempted).toBe(0);+ expect(result.pages_written).toBe(0);+ expect(client.calls.length).toBe(0);+ });++ test('a oneshot skip replayed after its transcript persisted still completes without another model call (#5590)', async () => {+ const client = new FakeMessagesClient([]);+ const skip = JSON.stringify({ pages: [], skipped: true, skip_reason: 'already captured' });+ const handler = makeSubagentHandler({ engine, client, _chat: chatStub(skip) });+ const ctx = await makeCtx({+ prompt: 'synthesize', mode: 'oneshot', require_writes: true,+ allowed_slug_prefixes: PREFIXES, oneshot_slug_suffix: SUFFIX,+ });+ expect((await handler(ctx)).oneshot_skipped).toBe(true);++ let chatCalls = 0;+ const spy = (async (...args: any[]) => { chatCalls++; return chatStub(skip)(...args); }) as any;+ const replay = await makeSubagentHandler({ engine, client, _chat: spy })({ ...ctx, attempts_made: 1 });+ expect(replay.synth_mode_used).toBe('oneshot');+ expect(replay.oneshot_skipped).toBe(true);+ expect(replay.pages_attempted).toBe(0);+ expect(chatCalls).toBe(0);+ expect(client.calls.length).toBe(0);+ });++ test('an agentic-fallback transcript that merely looks like a skip still dead-letters on replay (#5590)', async () => {+ const client = new FakeMessagesClient([]);+ let chatCalls = 0;+ const spy = (async (...args: any[]) => { chatCalls++; return chatStub('{}')(...args); }) as any;+ const handler = makeSubagentHandler({ engine, client, _chat: spy });+ const ctx = await makeCtx({+ prompt: 'synthesize', mode: 'oneshot', require_writes: true,+ allowed_slug_prefixes: PREFIXES, oneshot_slug_suffix: SUFFIX,+ });+ await engine.executeRaw(+ `INSERT INTO subagent_messages (job_id, message_idx, role, content_blocks)+ VALUES ($1, 0, 'user', '[{"type":"text","text":"synthesize"}]'::jsonb),+ ($1, 1, 'assistant', $2::text::jsonb)`,+ [ctx.id, JSON.stringify([{ type: 'text', text: JSON.stringify({ pages: [], skipped: true }) }])],+ );+ await expect(handler({ ...ctx, attempts_made: 1 })).rejects.toThrow('zero required put_page writes');+ expect(chatCalls).toBe(0);+ });++ test('oneshot pages:[] without the skip flag still dead-letters when the fallback writes nothing (#5590)', async () => {+ const client = new FakeMessagesClient([+ { content: [{ type: 'text', text: 'nothing met the bar' }] as any, stop_reason: 'end_turn' },+ ]);+ const handler = makeSubagentHandler({ engine, client, _chat: chatStub(JSON.stringify({ pages: [], skipped: false })) });+ const ctx = await makeCtx({+ prompt: 'synthesize', mode: 'oneshot', require_writes: true,+ allowed_slug_prefixes: PREFIXES, oneshot_slug_suffix: SUFFIX,+ });+ await expect(handler(ctx)).rejects.toThrow('zero required put_page writes');+ });+test('invalid oneshot output falls back to the agentic loop IN THE SAME JOB', async () => {const client = new FakeMessagesClient([{ content: [{ type: 'text', text: 'agentic loop answered' }] as any, stop_reason: 'end_turn' },diff --git a/test/subagent-required-writes.test.ts b/test/subagent-required-writes.test.tsindex e459a0a234..e177f56f98 100644--- a/test/subagent-required-writes.test.ts+++ b/test/subagent-required-writes.test.ts@@ -10,11 +10,67 @@ const result: SubagentResult = {tokens: { in: 10, out: 5, cache_read: 0, cache_create: 0 },};-function ledger(rows: Array<{ status: string; error: string | null; output?: unknown }>): BrainEngine {- return { executeRaw: async () => rows } as unknown as BrainEngine;+function ledger(+ rows: Array<{ status: string; error: string | null; output?: unknown }>,+ completedTools: Array<{ id: number }> = [],+): BrainEngine {+ return {+ executeRaw: async (query: string) => query.includes("tool_name = 'brain_put_page'") ? rows : completedTools,+ } as unknown as BrainEngine;}describe('required-write postcondition (#5098)', () => {+ test('an explicit oneshot skip is a legitimate zero-write completion (#5590)', async () => {+ const skipped: SubagentResult = { ...result, synth_mode_used: 'oneshot', oneshot_skipped: true, written_refs: [] };+ const actual = await finalizeWriteAccounting(ledger([]), 1, skipped, { requireWrites: true });+ expect(actual.pages_attempted).toBe(0);+ expect(actual.pages_written).toBe(0);+ expect(actual.oneshot_skipped).toBe(true);+ });++ test('a skip marker without oneshot mode does not satisfy required writes (#5590)', async () => {+ const agentic: SubagentResult = { ...result, synth_mode_used: 'agentic', oneshot_skipped: true };+ await expect(finalizeWriteAccounting(ledger([]), 1, agentic, { requireWrites: true }))+ .rejects.toThrow('required put_page write');+ });++ test('a oneshot skip does not excuse attempted writes that all failed (#5590)', async () => {+ const skipped: SubagentResult = { ...result, synth_mode_used: 'oneshot', oneshot_skipped: true };+ await expect(finalizeWriteAccounting(ledger([{ status: 'failed', error: 'boom' }]), 1, skipped, { requireWrites: true }))+ .rejects.toThrow('all 1 put_page write(s) failed');+ });++ test('allowCleanZeroWrites completes a clean finish after a completed non-write tool (#5540)', async () => {+ const actual = await finalizeWriteAccounting(ledger([], [{ id: 1 }]), 1, result, {+ requireWrites: true,+ allowCleanZeroWrites: true,+ });+ expect(actual.stop_reason).toBe('end_turn');+ expect(actual.pages_attempted).toBe(0);+ expect(actual.pages_written).toBe(0);+ });++ test('allowCleanZeroWrites still dead-letters a clean finish with no completed tool (#5540)', async () => {+ await expect(finalizeWriteAccounting(ledger([]), 1, result, {+ requireWrites: true,+ allowCleanZeroWrites: true,+ })).rejects.toThrow('clean model finish does not satisfy require_writes');+ });++ test('allowCleanZeroWrites still dead-letters when every attempted write failed (#5540)', async () => {+ await expect(finalizeWriteAccounting(+ ledger([{ status: 'failed', error: 'database unavailable' }], [{ id: 1 }]), 1, result,+ { requireWrites: true, allowCleanZeroWrites: true },+ )).rejects.toThrow('all 1 put_page write(s) failed');+ });++ test('allowCleanZeroWrites still dead-letters a non-clean zero-write stop (#5540)', async () => {+ await expect(finalizeWriteAccounting(+ ledger([], [{ id: 1 }]), 1, { ...result, stop_reason: 'max_tokens' },+ { requireWrites: true, allowCleanZeroWrites: true },+ )).rejects.toThrow('did not finish cleanly');+ });+test('a clean prose-only finish cannot satisfy required writes', async () => {await expect(finalizeWriteAccounting(ledger([]), 1, result, { requireWrites: true })).rejects.toThrow('required put_page write');diff --git a/test/sweep.test.ts b/test/sweep.test.tsindex d7c57d829e..2582f26e7e 100644--- a/test/sweep.test.ts+++ b/test/sweep.test.ts@@ -470,6 +470,48 @@ describe('runMaintenanceSweep — corpus ingest [CX-P0.1, CX-P0.5]', () => {expect(r.skipped).toContainEqual({ reason: 'already_ingested', count: 1 });});+ test('a claude-cli self-capture is retired with a terminal sidecar and never extracted; a user session still is (#5413)', async () => {+ const claudeHome = mkdtempSync(join(tmpdir(), 'gbrain-sweep-claude-'));+ tmpDirs.push(claudeHome);+ const selfId = '11111111-2222-4333-8444-555555555555';+ const userId = '66666666-7777-4888-9999-000000000000';+ const selfProject = join(claudeHome, 'projects', '-tmp-gbrain-claude-cli-cwd-4242');+ const userProject = join(claudeHome, 'projects', '-home-user-app');+ mkdirSync(selfProject, { recursive: true });+ mkdirSync(userProject, { recursive: true });+ writeFileSync(join(selfProject, `${selfId}.jsonl`), '{"type":"user"}\n');+ writeFileSync(join(userProject, `${userId}.jsonl`), '{"type":"user"}\n');+ const selfFiles = [`${selfId}.txt`, `${selfId}.seg-aaaaaaaaaaaa.txt`, `${selfId}.wb-bbbbbbbbbbbbbbbbbbbbbbbb.txt`];+ for (const f of selfFiles) writeFileSync(join(corpusDir, f), 'User: <turn>extract facts from this page</turn>\n');+ writeFileSync(join(corpusDir, `${userId}.txt`), 'Alice committed to shipping the beta in March.\n');++ let chatCalls = 0;+ __setChatTransportForTests(async (): Promise<ChatResult> => {+ chatCalls += 1;+ return {+ text: JSON.stringify({ facts: [] }),+ blocks: [],+ stopReason: 'end',+ usage: { input_tokens: 1, output_tokens: 1, cache_read_tokens: 0, cache_creation_tokens: 0 },+ model: 'anthropic:test-stub',+ providerId: 'anthropic',+ };+ });++ const r1 = await withEnv({ CLAUDE_CONFIG_DIR: claudeHome }, () =>+ runMaintenanceSweep(engine, { sourceId: 'default', capabilities: KEYED }));+ expect(chatCalls).toBe(1);+ expect(r1.corpusIngested).toBe(1);+ expect(r1.skipped).toContainEqual({ reason: 'self_capture', count: 3 });+ for (const f of selfFiles) expect(existsSync(join(corpusDir, f + CORPUS_INGESTED_SUFFIX))).toBe(true);+ expect(existsSync(join(corpusDir, `${userId}.txt` + CORPUS_INGESTED_SUFFIX))).toBe(true);++ const r2 = await withEnv({ CLAUDE_CONFIG_DIR: claudeHome }, () =>+ runMaintenanceSweep(engine, { sourceId: 'default', capabilities: KEYED }));+ expect(chatCalls).toBe(1);+ expect(r2.corpusIngested).toBe(0);+ });+test('extraction_enabled=false spend gate skips without sidecars', async () => {await engine.setConfig('facts.extraction_enabled', 'false');try {diff --git a/test/tailscale.test.ts b/test/tailscale.test.tsindex 9ebafdf783..c557475476 100644--- a/test/tailscale.test.ts+++ b/test/tailscale.test.ts@@ -57,6 +57,21 @@ describe('parseTailscaleStatus', () => {expect(cap({ Capabilities: ['https://tailscale.com/cap/ssh'] })).toBe(false);expect(cap({ CapMap: {}, Capabilities: ['https://tailscale.com/cap/funnel'] })).toBe(true);});+ test('funnelCapable: current Tailscale CapMap forms (`funnel`, `…/cap/funnel-ports?ports=`) are Funnel-capable (#5599)', () => {+ const cap = (self: Record<string, unknown>) => parseTailscaleStatus(JSON.stringify({ ...STATUS_DOC, Self: { ...STATUS_DOC.Self, ...self } }))!.funnelCapable;+ // Tailscale 1.102.4 `Self` shape from the report: CapMap without the legacy URL key, Capabilities null.+ expect(cap({ Capabilities: null, CapMap: {+ 'default-auto-update': [], funnel: [], https: [],+ 'https://tailscale.com/cap/file-sharing': [],+ 'https://tailscale.com/cap/funnel-ports?ports=443,8443,10000': [],+ 'https://tailscale.com/cap/is-admin': [], 'https://tailscale.com/cap/is-owner': [], 'https://tailscale.com/cap/ssh': [],+ } })).toBe(true);+ expect(cap({ CapMap: { funnel: [] } })).toBe(true);+ expect(cap({ CapMap: { 'https://tailscale.com/cap/funnel-ports?ports=443': [] } })).toBe(true);+ expect(cap({ CapMap: { 'https://tailscale.com/cap/funnel-ports': [] } })).toBe(true);+ expect(cap({ Capabilities: ['funnel'] })).toBe(true);+ expect(cap({ CapMap: { 'https://tailscale.com/cap/funnel-portsx': [], funnelish: [], 'https://tailscale.com/cap/https': [] } })).toBe(false);+ });test('non-JSON / non-object output → null', () => {expect(parseTailscaleStatus('')).toBeNull();expect(parseTailscaleStatus('failed to connect to local Tailscale service')).toBeNull();diff --git a/test/timeline-materialize.test.ts b/test/timeline-materialize.test.tsnew file mode 100644index 0000000000..5e4e06ec8e--- /dev/null+++ b/test/timeline-materialize.test.ts@@ -0,0 +1,319 @@+/**+ * #5567 materialize + marker: database-only timeline rows are written back into+ * the page as marked bullets by writers that render from the database, and the+ * per-writer class decides who may remove a marked row.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync } 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 { importFromContent } from '../src/core/import-file.ts';+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { materializeTimeline, prepareCanonicalProjections, renderMaterializedBullet, type ProjectionWriter } from '../src/core/persistence/canonical-projections.ts';+import { parseTimelineEntries } from '../src/core/link-extraction.ts';+import { extractTimelineFromContent } from '../src/core/timeline-extract.ts';+import { sanitizeRemoteBody } from '../src/core/remote-body.ts';+import { materializedMarker } from '../src/core/timeline-marker.ts';+import { operationsByName } from '../src/core/operations.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { withEnv } from './helpers/with-env.ts';+import { testBackends } from './helpers/test-backends.ts';++const backends = testBackends();+const engines: BrainEngine[] = [];+const dataDir = mkdtempSync(join(tmpdir(), 'gbrain-materialize-'));+let closePostgres: (() => Promise<void>) | undefined;++beforeAll(async () => {+ if (backends.includes('pglite')) {+ const engine = new PGLiteEngine();+ await engine.connect({}); await engine.initSchema(); engines.push(engine);+ }+ if (backends.includes('postgres')) {+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);+ engines.push(pg.engine); closePostgres = pg.close;+ }+}, 120_000);++afterAll(async () => {+ for (const engine of engines) { await disposePersistenceConsumer(engine); if (engine.kind === 'pglite') await engine.disconnect(); }+ await closePostgres?.();+ rmSync(dataDir, { recursive: true, force: true });+});++type Row = { date: string; source: string; summary: string; detail: string };+interface Fixture { engine: BrainEngine; sourceId: string; root: string;+ put(slug: string, content: string, extra?: Record<string, unknown>): Promise<Record<string, unknown>>;+ revision(slug: string): Promise<string>; body(slug: string): Promise<string>; file(slug: string): string;+ legacy(slug: string, row: Omit<Row, 'detail'> & { detail?: string }): Promise<void>; timeline(slug: string): Promise<Row[]> }++async function fixture(run: (f: Fixture) => Promise<void>) {+ for (const engine of engines) {+ const dir = mkdtempSync(join(dataDir, 'case-'));+ const root = join(dir, 'brain'); mkdirSync(root);+ const sourceId = `materialize-${randomUUID().slice(0, 8)}`;+ const ctx = { engine, sourceId, remote: false as const, config: { engine: engine.kind, embedding_disabled: true },+ dryRun: false, logger: { info() {}, warn() {}, error() {} } };+ const f: Fixture = {+ engine, sourceId, root,+ put: (slug, content, extra = {}) => submitPageMutation(ctx, { operation: 'put_page', params: { slug, content, request_id: randomUUID(), ...extra } }),+ revision: async slug => (await engine.readPageSnapshot(slug, { sourceId }))!.revision,+ body: async slug => { const s = (await engine.readPageSnapshot(slug, { sourceId }))!; return [s.page.compiled_truth, s.page.timeline ?? ''].join('\n'); },+ file: slug => {+ const hit = [join(root, `${slug}.md`), join(root, '.sources', sourceId, `${slug}.md`)].find(existsSync);+ if (!hit) throw new Error(`no canonical file for ${slug}: ${readdirSync(root)}`);+ return readFileSync(hit, 'utf8');+ },+ legacy: async (slug, row) => { await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => tx.executeRaw(+ `INSERT INTO timeline_entries(page_id,date,source,summary,detail) SELECT id,$3::date,$4,$5,$6 FROM pages WHERE source_id=$1 AND slug=$2`,+ [sourceId, slug, row.date, row.source, row.summary, row.detail ?? '']))); },+ timeline: async slug => engine.executeRaw<Row>(`SELECT t.date::text AS date,t.source,t.summary,t.detail FROM timeline_entries t+ JOIN pages p ON p.id=t.page_id WHERE p.source_id=$1 AND p.slug=$2 AND t.event_page_id IS NULL ORDER BY t.date,t.summary`, [sourceId, slug]),+ };+ try {+ await withEnv({ GBRAIN_HOME: join(dir, 'home') }, async () => {+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);+ await claimWorktree(engine, sourceId, root);+ await run(f);+ });+ } finally {+ await disposePersistenceConsumer(engine);+ }+ }+}++const page = (body: string, timeline = '') =>+ `---\ntype: note\ntitle: Example project\n---\n${body}\n${timeline ? `\n## Timeline\n\n${timeline}\n` : ''}`;+const slug = 'projects/example';+const legacy = { date: '2026-07-01', source: 'legacy', summary: 'Kickoff held before write-through', detail: 'pre-write-through\n evidence' };+const normalized = { date: '2026-07-01', source: 'legacy', summary: 'Kickoff held before write-through', detail: 'pre-write-through evidence' };+const bullet = `${materializedMarker(normalized)}\n- **2026-07-01** | legacy — Kickoff held before write-through\n pre-write-through evidence`;++describe('#5567 database-only rows are materialized as marked bullets', () => {+ test('a put_page writes a legacy row back as a marked bullet with its normalized detail, in the file too', async () => {+ await fixture(async f => {+ await f.put(slug, page('First draft.', '- **2026-08-01** | markdown — Launch review'));+ await f.legacy(slug, legacy);+ await f.put(slug, page('Second draft.', '- **2026-08-01** | markdown — Launch review'), { expected_revision: await f.revision(slug) });+ expect(await f.body(slug)).toContain(`- **2026-08-01** | markdown — Launch review\n${bullet}`);+ expect(f.file(slug)).toContain(bullet);+ expect(await f.timeline(slug)).toEqual([normalized, { date: '2026-08-01', source: 'markdown', summary: 'Launch review', detail: '' }]);+ });+ });++ test('materializing history keeps the stored type of a body-only update', async () => {+ await fixture(async f => {+ await f.put(slug, page('Draft.'));+ await f.legacy(slug, legacy);+ await f.put(slug, '---\ntitle: Example project\n---\nBody-only update.\n', { force: true });+ expect((await f.engine.readPageSnapshot(slug, { sourceId: f.sourceId }))!.page.type).toBe('note');+ expect(await f.body(slug)).toContain(bullet);+ });+ });++ test('a second put of the rendered page and a forced re-put of the original body are byte-identical', async () => {+ await fixture(async f => {+ await f.put(slug, page('Draft.'));+ await f.legacy(slug, legacy);+ await f.put(slug, page('Draft.'), { force: true });+ const first = f.file(slug);+ const revision = await f.revision(slug);+ const again = await f.put(slug, first, { expected_revision: revision });+ expect(again.noop ?? again.status === 'skipped').toBeTruthy();+ expect(f.file(slug)).toBe(first);+ await f.put(slug, page('Draft.'), { force: true });+ expect(f.file(slug)).toBe(first);+ expect(await f.revision(slug)).toBe(revision);+ });+ });++ test('removing a marked bullet in a revision-bound put_page deletes its row', async () => {+ await fixture(async f => {+ await f.put(slug, page('Draft.'));+ await f.legacy(slug, legacy);+ await f.put(slug, page('Draft.'), { force: true });+ await f.put(slug, page('Draft without history.'), { expected_revision: await f.revision(slug) });+ expect(await f.timeline(slug)).toEqual([]);+ expect(await f.body(slug)).not.toContain('gbrain:materialized');+ });+ });++ test('a stale put_page without a revision keeps a marked row and renders it again', async () => {+ await fixture(async f => {+ await f.put(slug, page('Draft.'));+ await f.legacy(slug, legacy);+ await f.put(slug, page('Draft.'), { force: true });+ await f.put(slug, page('Stale copy.'), { force: true });+ expect(await f.timeline(slug)).toEqual([normalized]);+ expect(await f.body(slug)).toContain(bullet);+ });+ });++ test('deleting only the marker comment in an editing write keeps the row', async () => {+ await fixture(async f => {+ await f.put(slug, page('Draft.'));+ await f.legacy(slug, legacy);+ await f.put(slug, page('Draft.'), { force: true });+ const withoutMarker = f.file(slug).replace(`${materializedMarker(normalized)}\n`, '');+ await f.put(slug, withoutMarker, { expected_revision: await f.revision(slug) });+ expect(await f.timeline(slug)).toEqual([normalized]);+ expect(await f.body(slug)).not.toContain('gbrain:materialized');+ });+ });++ test('a hand-edited marked bullet is an ordinary edited bullet', async () => {+ await fixture(async f => {+ await f.put(slug, page('Draft.'));+ await f.legacy(slug, legacy);+ await f.put(slug, page('Draft.'), { force: true });+ const edited = f.file(slug).replace('Kickoff held before write-through', 'Kickoff held in person');+ await f.put(slug, edited, { expected_revision: await f.revision(slug) });+ expect((await f.timeline(slug)).map(r => r.summary)).toEqual(['Kickoff held in person']);+ await f.put(slug, page('Draft.'), { force: true });+ expect(await f.timeline(slug)).toEqual([]);+ });+ });++ test('a row whose normalized tuple already has a bullet is not duplicated', async () => {+ await fixture(async f => {+ await f.put(slug, page('Draft.', '- **2026-07-01** | legacy — Kickoff held before write-through'));+ await f.legacy(slug, { date: '2026-07-01', source: 'legacy', summary: 'Kickoff held before write-through ' });+ await f.put(slug, page('Edited.', '- **2026-07-01** | legacy — Kickoff held before write-through'), { force: true });+ expect(await f.body(slug)).not.toContain('gbrain:materialized');+ expect((await f.timeline(slug)).map(r => r.summary)).toEqual(['Kickoff held before write-through']);+ });+ });++ test('a source with internal whitespace materializes once and repeated saves converge', async () => {+ await fixture(async f => {+ await f.put(slug, page('Draft.'));+ await f.legacy(slug, { date: '2026-07-05', source: 'meeting notes', summary: 'Spaced source' });+ for (const body of ['Edited.', 'Edited again.', 'Edited once more.']) await f.put(slug, page(body), { force: true });+ expect((await f.body(slug)).match(/gbrain:materialized/g)?.length).toBe(1);+ expect(await f.timeline(slug)).toEqual([{ date: '2026-07-05', source: 'meeting notes', summary: 'Spaced source', detail: '' }]);+ });+ });++ test('backlink receipts, empty sources and delimiter-bearing sources are kept, never materialized', async () => {+ await fixture(async f => {+ await f.put(slug, page('Draft.'));+ const kept = [+ { date: '2026-07-02', source: 'markdown', summary: 'Referenced in [Acme](companies/acme-example.md)' },+ { date: '2026-07-03', source: '', summary: 'Example project' },+ { date: '2026-07-04', source: 'notes — call', summary: 'Delimiter in the source' },+ ];+ for (const row of kept) await f.legacy(slug, row);+ await f.put(slug, page('Edited.'), { force: true });+ expect(await f.body(slug)).not.toContain('gbrain:materialized');+ expect((await f.timeline(slug)).map(r => r.summary).sort()).toEqual(kept.map(r => r.summary).sort());+ });+ });++ test('a markdown rebuild keeps markers and their protection', async () => {+ await fixture(async f => {+ await f.put(slug, page('Draft.'));+ await f.legacy(slug, legacy);+ await f.put(slug, page('Draft.'), { force: true });+ const rendered = f.file(slug);+ await f.engine.transaction(tx => withCoordinatedWrite(tx, [f.sourceId], () => tx.executeRaw(+ `UPDATE pages SET compiled_truth='', timeline='' WHERE source_id=$1 AND slug=$2`, [f.sourceId, slug])));+ await f.engine.transaction(tx => withCoordinatedWrite(tx, [f.sourceId], () =>+ importFromContent(tx, slug, rendered, { sourceId: f.sourceId, noEmbed: true, forceRechunk: true })));+ expect(await f.body(slug)).toContain(bullet);+ await f.put(slug, page('Stale copy.'), { force: true });+ expect(await f.timeline(slug)).toEqual([normalized]);+ });+ });++ test('remote get_page keeps markers so a remote edit round-trips them; chunks never contain them', async () => {+ await fixture(async f => {+ await f.put(slug, page('Draft.'));+ await f.legacy(slug, legacy);+ await f.put(slug, page('Draft.'), { force: true });+ const remote = await operationsByName.get_page.handler({ engine: f.engine, config: { engine: f.engine.kind }, logger: { info() {}, warn() {}, error() {} },+ dryRun: false, remote: true, sourceId: f.sourceId } as never, { slug, include_content: true }) as { timeline: string; content?: string };+ expect(remote.timeline).toContain(materializedMarker(normalized));+ const chunks = await f.engine.executeRaw<{ chunk_text: string }>(`SELECT c.chunk_text FROM content_chunks c JOIN pages p ON p.id=c.page_id+ WHERE p.source_id=$1 AND p.slug=$2`, [f.sourceId, slug]);+ expect(chunks.length).toBeGreaterThan(0);+ expect(chunks.some(c => c.chunk_text.includes('Kickoff held'))).toBe(true);+ expect(chunks.some(c => c.chunk_text.includes('gbrain:materialized'))).toBe(false);+ });+ });+});++describe('#5567 per-writer classes for marked rows', () => {+ async function marked(f: Fixture) {+ await f.put(slug, page('Draft.'));+ await f.legacy(slug, legacy);+ await f.put(slug, page('Draft.'), { force: true });+ return f.engine.readPageSnapshot(slug, { sourceId: f.sourceId, includeDeleted: true });+ }+ const cases: Array<[ProjectionWriter, boolean, boolean]> = [+ // writer, renders the row back, keeps the row+ ['editing', false, false],+ ['file', false, false],+ ['preserving', true, true],+ ['immutable', false, true],+ ];+ for (const [writer, renders, keeps] of cases) {+ test(`${writer} writer that drops a marked bullet ${keeps ? 'keeps' : 'deletes'} the row${renders ? ' and renders it again' : ''}`, async () => {+ await fixture(async f => {+ const prior = await marked(f);+ const next = parseMarkdown(page('Regenerated body.'), slug);+ const carried = await materializeTimeline(f.engine, next, slug, prior, writer);+ expect(carried.materialized).toBe(renders ? 1 : 0);+ const project = await prepareCanonicalProjections(f.engine, { ...next, timeline: carried.timeline }, slug, f.sourceId, prior, writer);+ await f.engine.transaction(tx => withCoordinatedWrite(tx, [f.sourceId], () => project(tx)));+ expect(await f.timeline(slug)).toEqual(keeps ? [normalized] : []);+ });+ });+ }++ test('two consecutive connector-style regenerations keep a marked row and drop an unmarked bullet they stopped producing', async () => {+ await fixture(async f => {+ await f.put(slug, page('Draft.', '- **2026-08-01** | connector — Old item'));+ await f.legacy(slug, legacy);+ await f.put(slug, page('Draft.', '- **2026-08-01** | connector — Old item'), { force: true });+ for (const render of [page('Connector render.'), page('Connector render.')]) {+ await f.put(slug, render, { force: true });+ expect(await f.timeline(slug)).toEqual([normalized]);+ expect(await f.body(slug)).toContain(bullet);+ }+ });+ });+});++describe('#5567 marker parsing', () => {+ test('a marked bullet does not become detail of the preceding bullet, and the marker is not text anywhere', () => {+ const body = `- **2026-06-30** | markdown — Earlier bullet\n earlier detail\n${bullet}\n`;+ expect(parseTimelineEntries(body)).toEqual([+ { date: '2026-06-30', source: 'markdown', summary: 'Earlier bullet', detail: 'earlier detail' },+ { date: '2026-07-01', source: 'legacy', summary: 'Kickoff held before write-through', detail: 'pre-write-through evidence' },+ ]);+ expect(extractTimelineFromContent(body, slug).map(e => e.summary)).toEqual(['Earlier bullet', 'Kickoff held before write-through']);+ expect(sanitizeRemoteBody(body)).not.toContain('gbrain:materialized');+ expect(sanitizeRemoteBody(body, { keepMaterializedMarkers: true })).toContain(materializedMarker(normalized));+ });++ test('a materialized bullet after a dated header is not part of the header detail', () => {+ const body = `### 2026-06-01 — Planning\nHeader detail.\n${bullet}\n`;+ const header = extractTimelineFromContent(body, slug).find(e => e.summary === 'Planning');+ expect(header?.detail).toBe('Header detail.');+ });++ test('render then extract must return exactly the tuple', () => {+ expect(renderMaterializedBullet(legacy, slug)).toBe(bullet);+ expect(renderMaterializedBullet({ date: '2026-07-01', source: '', summary: 'x' }, slug)).toBeNull();+ expect(renderMaterializedBullet({ date: '2026-07-01', source: 'a — b', summary: 'x' }, slug)).toBeNull();+ expect(renderMaterializedBullet({ date: '2026-07-01', source: 'markdown', summary: 'Referenced in [X](x.md)' }, slug)).toBeNull();+ expect(renderMaterializedBullet({ date: '2026-07-01', source: 'notes', summary: 'x', detail: '**2026-07-02** | nested' }, slug)).toBeNull();+ });+});diff --git a/test/turn-context.test.ts b/test/turn-context.test.tsindex 19b187edbe..bdda941378 100644--- a/test/turn-context.test.ts+++ b/test/turn-context.test.ts@@ -216,6 +216,35 @@ describe('assembleTurnContext', () => {expect(r.text.startsWith(TURN_CONTEXT_ENVELOPE)).toBe(true);});+ test('hot facts already injected this session are not re-injected', async () => {+ // Every prompt used to repeat the whole digest; the repeats stay in the+ // transcript and are re-read on every later turn.+ await seedFact('WORLD-FACT standup moved to 9am', 'world');+ await seedFact('WORLD-FACT deploy freeze on friday', 'world');+ const first = await assembleTurnContext(engine, { sourceId: 'default', window: [] });+ expect(first.factsCount).toBe(2);++ __resetHotMemoryCacheForTests();+ await seedFact('WORLD-FACT new office opens in june', 'world');+ const next = await assembleTurnContext(engine, {+ sourceId: 'default',+ window: [{ role: 'user', text: 'no entities here, just vibes' }],+ priorContextText: first.text,+ });+ expect(next.factsCount).toBe(1);+ expect(next.text).toContain('WORLD-FACT new office opens in june');+ expect(next.text).not.toContain('standup moved to 9am');+ expect(next.text).not.toContain('deploy freeze on friday');+ });++ test('a changed confidence score does not make an injected fact new again', async () => {+ await seedFact('WORLD-FACT standup moved to 9am', 'world');+ const prior = `${TURN_CONTEXT_ENVELOPE}\n\n## Hot memory (recent facts)\n- WORLD-FACT standup moved to 9am [people/alice-example] (0.42)`;+ const r = await assembleTurnContext(engine, { sourceId: 'default', window: [], priorContextText: prior });+ expect(r.factsCount).toBe(0);+ expect(r.text).toBe('');+ });+test('nothing to inject → empty text, zero counts, no degradation', async () => {const r = await assembleTurnContext(engine, {sourceId: 'default',diff --git a/test/write-through.test.ts b/test/write-through.test.tsindex f88e9306ad..f2e9467abb 100644--- a/test/write-through.test.ts+++ b/test/write-through.test.ts@@ -446,13 +446,13 @@ describe('writePageThrough', () => {expect(fs.existsSync(path.join(sourceRoot, sourcePath))).toBe(false);});- test('[#4247] put-born page in a subdirectory-scoped local_path binds a Git-root-relative source_path', async () => {+ test('[#4247] put-born page in a subdirectory-scoped git-root source binds a Git-root-relative source_path', async () => {const gitRoot = path.join(tmpRoot, 'monorepo');fs.mkdirSync(path.join(gitRoot, '.git'), { recursive: true });const sourceRoot = path.join(gitRoot, 'public', 'changelog');fs.mkdirSync(sourceRoot, { recursive: true });await engine.executeRaw(- `INSERT INTO sources (id, name, local_path, config) VALUES ('changelog', 'Changelog', $1, '{}'::jsonb)`,+ `INSERT INTO sources (id, name, local_path, config) VALUES ('changelog', 'Changelog', $1, '{"slug_root_mode":"git-root"}'::jsonb)`,[sourceRoot],);const slug = 'posts/2026-08-24';@@ -467,9 +467,10 @@ describe('writePageThrough', () => {expect(res.written).toBe(true);expect(res.path).toBe(path.join(sourceRoot, 'posts', '2026-08-24.md'));- // Scoped syncs record source_path GIT-ROOT-relative (#774), and+ // Scoped git-root syncs record source_path GIT-ROOT-relative (#774), and// delete-reconcile keys on that exact form — a local_path-relative bind// here would desync reconcile and sweep the page while its file exists.+ // Source-root sources bind local_path-relative origins (#5610).const rows = await engine.executeRaw<{ source_path: string | null }>(`SELECT source_path FROM pages WHERE source_id = 'changelog' AND slug = $1`,[slug],