Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
v0.60.11.0 fix wave 3: connectors stop re-admitting, managed maintenance finishes, guided recovery after upgrade (#5747)
Garry Tanf8d1e3936d90
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex fab243c1a9..d89d7a3aac 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.60.10.0",+ "version": "0.60.11.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 8c2609afbc..80808ec6af 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.60.10.0",+ "version": "0.60.11.0","description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.","author": {"name": "Garry Tan",diff --git a/.github/workflows/macos-validation.yml b/.github/workflows/macos-validation.ymlnew file mode 100644index 0000000000..d815edcb3f--- /dev/null+++ b/.github/workflows/macos-validation.yml@@ -0,0 +1,85 @@+name: macOS 26 validation++# Native macOS 26 evidence for the Mac-specific persistence fixes. Not part of+# default PR CI (macOS minutes are scarce). Three triggers:+# - Nightly schedule.+# - Pull requests carrying the `macos-validation` label (scheduled and+# dispatched runs only use the default branch's workflow file, and the+# evidence is needed before a change merges).+# - Manual workflow_dispatch.+#+# Uses no secrets. Checks:+# #5604 device-identity re-stamp on real APFS (non-zero birth time, real+# inode); the device-number change itself stays simulated because a+# runner never reboots.+# #5449 PGLite checkpoint harness on a >= 2 GiB store, asserting the WAL bound.+# #5286 the published signed darwin-arm64 release binary: codesign --verify+# --strict and --version against the release tag.++on:+ schedule:+ - cron: '41 9 * * *' # 09:41 UTC daily, staggered from the other nightlies+ pull_request:+ types: [labeled, synchronize, reopened]+ workflow_dispatch:++permissions:+ contents: read++concurrency:+ group: macos-validation-${{ github.ref }}+ cancel-in-progress: true++jobs:+ macos-26:+ name: macOS 26 validation+ if: |+ github.event_name != 'pull_request' ||+ contains(github.event.pull_request.labels.*.name, 'macos-validation')+ runs-on: macos-26+ timeout-minutes: 90+ steps:+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4+ - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2+ with:+ bun-version: 1.3.13+ - run: bun install --frozen-lockfile --ignore-scripts+ - name: Runner identity+ run: |+ sw_vers+ uname -m+ echo "ImageOS=${ImageOS:-unknown} ImageVersion=${ImageVersion:-unknown}"+ - name: "#5604 device-identity re-stamp on real APFS"+ run: |+ probe="$(mktemp -d)"+ device="$(df "$probe" | tail -1 | awk '{print $1}')"+ personality="$(diskutil info "$device" | awk -F: '/File System Personality/ {gsub(/^ +/, "", $2); print $2}')"+ echo "temporary directory $probe is on $device ($personality)"+ case "$personality" in *APFS*) ;; *) echo "::error::expected APFS, found '$personality'"; exit 1 ;; esac+ PROBE="$probe" bun -e '+ const s = require("node:fs").statSync(process.env.PROBE, { bigint: true });+ console.log(JSON.stringify({ dev: String(s.dev), ino: String(s.ino), birthtime_ns: String(s.birthtimeNs) }));+ if (s.birthtimeNs === 0n || s.ino === 0n) { console.error("expected a real birth time and inode"); process.exit(1); }'+ bun test --timeout=60000 test/persistence-physical-root-device.test.ts test/connector-physical-root-device.test.ts+ - name: "#5449 PGLite checkpoint harness on a >= 2 GiB store"+ run: |+ bun scripts/pglite-checkpoint-harness/supervisor.ts --dir "$RUNNER_TEMP/pglite-5449" --fresh \+ --pages 2600 --page-kb 200 --min-store-gb 2 --stall-sec 600 --timeout-sec 3600+ - name: "#5449 harness result"+ if: always()+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4+ with:+ name: pglite-5449-result+ path: ${{ runner.temp }}/pglite-5449/result.json+ if-no-files-found: warn+ - name: "#5286 published signed release binary"+ run: |+ tag="$(curl -fsSI https://github.com/garrytan/gbrain/releases/latest | awk 'tolower($1)=="location:" {print $2}' | tr -d '\r' | sed 's#.*/tag/##')"+ echo "latest release: $tag"+ curl -fsSL -o gbrain-darwin-arm64 "https://github.com/garrytan/gbrain/releases/download/$tag/gbrain-darwin-arm64"+ shasum -a 256 gbrain-darwin-arm64+ codesign --verify --strict --verbose=2 gbrain-darwin-arm64+ chmod +x gbrain-darwin-arm64+ out="$(./gbrain-darwin-arm64 --version)"+ echo "binary reports: $out"+ case "$out" in *"${tag#v}"*) ;; *) echo "::error::binary version '$out' does not match release $tag"; exit 1 ;; esacdiff --git a/.github/workflows/native-locks.yml b/.github/workflows/native-locks.ymlindex 8dc0f5f9d5..4d95e8b1ee 100644--- a/.github/workflows/native-locks.yml+++ b/.github/workflows/native-locks.yml@@ -54,7 +54,7 @@ jobs:native:name: ${{ matrix.target }} / Bun ${{ matrix.bun }}- runs-on: ${{ fromJSON('{"linux-x64-glibc":"ubicloud-standard-4-ubuntu-2404","linux-arm64-glibc":"ubicloud-standard-4-arm-ubuntu-2404","darwin-arm64":"macos-15","darwin-x64":"macos-15-intel","win32-x64":"windows-2022","win32-arm64":"windows-11-arm"}')[matrix.target] }}+ runs-on: ${{ fromJSON('{"linux-x64-glibc":"ubicloud-standard-4-ubuntu-2404","linux-arm64-glibc":"ubicloud-standard-4-arm-ubuntu-2404","darwin-arm64":"macos-26","darwin-x64":"macos-26-intel","win32-x64":"windows-2022","win32-arm64":"windows-11-arm"}')[matrix.target] }}timeout-minutes: 15strategy:fail-fast: falsediff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 1a49011da3..69fdde8df7 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -74,7 +74,7 @@ jobs:strategy:matrix:include:- - os: macos-latest+ - os: macos-26target: bun-darwin-arm64artifact: gbrain-darwin-arm64- os: ubuntu-latestdiff --git a/.github/workflows/test.yml b/.github/workflows/test.ymlindex ba75c9ed5f..0e2273f4f1 100644--- a/.github/workflows/test.yml+++ b/.github/workflows/test.yml@@ -126,7 +126,7 @@ jobs:strategy:fail-fast: falsematrix:- os: [ubuntu-latest, macos-latest, windows-latest]+ os: [ubuntu-latest, macos-26, windows-latest]bun: ['1.3.11', '1.3.13']# Pull requests run the primary Bun version on every OS; pushes,# schedules and manual runs add the oldest supported version.diff --git a/AGENTS.md b/AGENTS.mdindex 5c30a4f344..1ce84761e8 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -95,9 +95,11 @@ writing or reviewing an operation, consult `src/core/operations.ts` for the cont`gbrain db-repair --yes` to apply safe fixes. All three are engine-free — theywork while the database is down. Full loop:[`docs/ENGINES.md`](./docs/ENGINES.md#engine-detection-and-access-repair).- Doctor residue (`timeline_history`, `derived_visibility`, unsealed pages):- preview `gbrain repair`, then `gbrain repair <kind> --apply` on the brain host- after the user agrees ([repair guide](./docs/guides/repair.md)). A refused+ Doctor residue (`timeline_history`, `derived_visibility`, `safe_index_pending`):+ preview `gbrain doctor --remediation-plan` (or `gbrain repair`), then, after the+ user agrees, `gbrain doctor --remediate --yes --include-repairs --max-usd <n>`+ or `gbrain repair <kind> --apply` on the brain host. After an upgrade, follow+ [recover after upgrading](./docs/guides/repair.md#recover-after-upgrading-to-this-release). A refusedwrite names its reason and recovery command([write refusal reasons](./docs/guides/write-refusals.md)).- **Migrate / upgrade:** `gbrain upgrade` (binary self-update + schema migrations + post-upgrade prompts),@@ -111,14 +113,22 @@ writing or reviewing an operation, consult `src/core/operations.ts` for the cont<dataset.jsonl>` runs against an isolated in-memory PGLiteper question — your `~/.gbrain` is never opened. Full guide:[`docs/eval-bench.md`](./docs/eval-bench.md).-- **Drive the brain to a target health score:** the one-command- loop. `gbrain doctor --remediation-plan --json` previews what would be- fixed; `gbrain doctor --remediate --yes --target-score 90 --max-usd 5`- walks a dependency-ordered plan, re-checking score between every step and- refusing to spend past the cost cap. Stale extraction uses source-scoped- database pages, including DB-only pages; it does not require a repository- sync first. Empty brains (no entity pages) or unconfigured embedding- keys hit a `max_reachable_score` ceiling and bail with what's missing.+- **Drive the brain to a target health score:** preview, then agree.+ `gbrain doctor --remediation-plan --json` previews job steps and the+ PROTECTED repair steps (each marked "requires user agreement", with its+ exact command); after the user agrees,+ `gbrain doctor --remediate --yes --include-repairs --target-score 90 --max-usd 5`+ runs the repairs (even when the score target is unreachable) and walks the+ dependency-ordered job plan, re-checking score between steps. The cap is+ cumulative across `--resume`; a paid step that would exceed it is not+ started while free steps still run. Without `--include-repairs`, repair+ steps are listed as skipped. `--json` classifies each finding `cleared`,+ `pending`, `consent_required`, `operator_required` or `unsupported`.+ Stale extraction uses source-scoped database pages, including DB-only+ pages; it does not require a repository sync first. Empty brains (no+ entity pages) or unconfigured embedding keys hit a `max_reachable_score`+ ceiling: job steps stop with what's missing, while included repair steps+ still run.Three phase handlers (synthesize / patterns / consolidate) arePROTECTED — only trusted local callers can submit them; MCP cannot.Reference: [`docs/architecture/topologies.md`](./docs/architecture/topologies.md).diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.mdindex d0a828c698..651f42a490 100644--- a/BOOTSTRAP_FOR_AGENTS.md+++ b/BOOTSTRAP_FOR_AGENTS.md@@ -1,4 +1,4 @@-<!-- gbrain-runbook-stamp: 0.60.10.0 -->+<!-- gbrain-runbook-stamp: 0.60.11.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 40dd21f332..0676367799 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,109 @@ 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.11.0] - 2026-09-30++**Managed brains stop re-writing the same pages every hour, every maintenance job finishes again, and after an upgrade doctor shows you each leftover problem with the exact fix.**++If you connect Gmail, Calendar, Contacts or GitHub to a managed brain, each connector used to forget where it stopped after every maintenance cycle. So every hour it walked its whole window again and spent a new permanent write ID and receipt on every unchanged page. Now it resumes where it stopped, skips pages that did not change, and keeps going when the owner is slow instead of giving up after one write.++On the same brains, a dozen maintenance steps still used a writer that managed brains refuse. Concept synthesis paid for the model call and then died, taking the rest of the nightly job with it. Every maintenance writer now goes through the coordinator, and one failing step no longer stops the steps after it.++After an upgrade, `gbrain post-upgrade` prints a preview banner, and `gbrain doctor --remediation-plan` lists every repair with its command. `gbrain doctor --remediate --yes --include-repairs --max-usd 2` applies the ones you agree to, under a spending cap.++| Managed brain, test fixtures on both engines | Before | After |+| --- | --- | --- |+| Page admissions on a quiet connector's second run | every window item | 0 |+| Connector runs that resume their cursor after a maintenance cycle | none | all |+| Global maintenance after `synthesize_concepts` is refused | job dies | later phases run, job reports the failure |+| Repairs listed by `doctor --remediation-plan` | none | every kind with work, each with its command |+| Commands from `gbrain post-upgrade` to a clean repair plan | not possible | 3 |+| Grandfathering 250 pages on a pushed repository, seconds per page (PGLite / Postgres) | 0.456 / 0.821 | 0.060 / 0.070 |++Things to watch: the first connector run after the upgrade may re-admit its window once (see below). A page you saved to an unbound Postgres source still refuses by default; the error now names both fixes.++### To take advantage of v0.60.11.0++`gbrain upgrade` should do this automatically. If it didn't, or if `gbrain doctor` warns about a partial migration:++1. **Upgrade hosts in this order, with autopilot paused on connector hosts.** Mixed versions refuse with typed errors instead of losing data, and this order keeps them away:+ ```bash+ gbrain autopilot pause --reason "upgrading to v0.60.11.0" # on each host that runs connector jobs+ gbrain upgrade # first: every consumer and worktree-owner host+ gbrain upgrade # then: the connector hosts+ gbrain doctor --remediation-plan # preview; ask the user before applying+ gbrain autopilot resume # on each host you paused+ gbrain sources status # verify+ ```+ If schema work did not complete, run `gbrain apply-migrations --yes --no-autopilot-install` on the brain host.+2. **Expect one connector re-walk, once.** Migration 176 moves each connector's cursor to its new key. A source whose newest cursor receipt was compacted re-walks its window once on its next run, and connector writes still queued from before the upgrade fail once with `connector_intent_outdated` (detail `pre_upgrade`, nothing to do) and are fetched again. The post-upgrade banner and `gbrain sources status` count those sources. This first spike is expected and is not the hourly churn this release fixes.+3. **Your agent reads `skills/migrations/v0.60.11.0.md` the next time you interact with it.** It previews the recovery plan and asks you before applying anything.+4. **Verify the outcome:**+ ```bash+ gbrain sources status --json # after the second run a quiet connector shows page_admissions: 0+ gbrain doctor --remediation-plan # no repair steps left once you applied the agreed ones+ gbrain sources writer status --json # writer versions per host+ ```+5. **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.++### Itemized changes++#### Connectors (#5686, #5470, #5600, #5601)++- **Stable connector identity.** The checkpoint key, the admission and publication change checks and the attachment-repair preview use the parsed connector settings minus credential-delivery fields. Cycle stamps and other bookkeeping in `sources.config` no longer restart a connector or fail its pending writes with `source_changed`.+- **Account pinning.** Each connector source pins the account its credential belongs to. Google checks it through every enabled service before importing; GitHub records the App installation, or the login under `scope: auto`. A different account refuses with `connector_account_changed` and two exact ways out.+- **Unchanged items take no admission.** Connector sync, managed `gbrain import`, `gbrain sync --working-tree` and company-profile sync run each item through its own publication preparation first and skip it when publishing would change nothing. Pages below the safe-chunk fence, pages whose search projection lags, deleted pages and changed pages are still published. An unchanged cursor is not saved again; freshness for `gbrain waiting` is stamped directly.+- **Accepted writes count as progress.** A connector keeps going when the owner is slow, waits at most 30 seconds in total per run, and records writes still pending; the next run resolves them first and retries failed ones by itself. `extract_atoms` reports a batch the owner accepted but has not published as pending, not failed, and dream no longer halts on it.+- **`gbrain sync --source <id> --reset-checkpoint`** re-walks one connector's window. Unchanged pages are not admitted again and the account pin is kept.+- **`gbrain sources status`** shows each connector's upgrade recovery state and its last run's admissions, skipped pages, pending writes and checkpoint admissions.+- **Mixed-version safety.** Connector writes use a new intent format. An older consumer refuses it with `unsupported_mutation_protocol` and the connector names the hosts to upgrade; an older connector's writes fail `connector_intent_outdated` and are fetched again after the upgrade.+- **Your notes on connector pages survive a re-walk.** A timeline entry you add to a connector page (`add_timeline_entry`) is kept when the connector renders the page again from the provider, and adding one to a database-only connector source stays database-only instead of claiming the source or refusing.++#### Maintenance writers on managed brains (#5484, #5280, #5523, #5405)++- **`synthesize_concepts`** publishes through the maintenance coordinator in the same order as before: private first, then the provenance edges, then promotion to world. The authority check runs before any model call.+- **A failing phase no longer kills maintenance.** A phase that throws is reported as a failed phase and later phases still run; the job still reports the failure and `gbrain dream` exits non-zero. Cancellation, a lost cycle lease and budget exhaustion still stop the job. A phase that fails after paid model calls is counted in doctor's `dream_paid_loop` check.+- **More writers go through the coordinator:** Life Chronicle events with their timeline row, the purge of deleted pages, `gbrain enrich` and `enrich_thin` (keeping facts and takes fences), the drift report and `grade_takes` auto-resolutions, the managed `extract` walk, `add_link` / `remove_link` as coordinated database-only writes (a manual link survives re-derivation), `gbrain bootstrap verify` cleanup, and the facts, phantom-redirect, open-loop and conversation-facts writers.+- **Every phase and mutating operation is classified** for managed brains, and a matrix test runs every phase once on a managed PGLite and Postgres brain.+- **Unbound Postgres sources (#5254).** Saving a page to a source with a checkout folder but no owner still refuses by default, but the error (`owner_unavailable`, detail `unbound_source`) names both fixes: bind with the printed `gbrain sources writer claim` command, or run `gbrain config set persistence.unbound_write database_only`. Migration 177 records those pages as database-only, so they stay that way after binding, and a publication racing a bind fails instead of committing. Doctor's `unbound_source` check is ok while the source is unbound and warns once it is bound; when a canonical file appears at such a page's path, `gbrain sources reconcile <source> <slug> --preview` shows both sides and `--apply` resolves it.++#### Embeddings and migrations (#5680, #4616, #5621, #5530, #5289)++- **Embedding migration budget (#5680).** Each provider request is charged at its maximum and settled to reported usage, once per attempt, summed across retries and splits. When `--max-cost-usd` is below the printed worst case, the migration stops before touching any vector and prints the command that covers it (`embedding_budget_below_worst_case`).+- **Degenerate vectors are refused per chunk (#4616).** A zero-norm, NaN or infinite vector fails only its own chunk with `embedding_zero_norm`; the page's other vectors are kept, on managed brains too, and the failure names `gbrain embed <slug>`. Empty inputs never reach the provider. `gbrain reindex --vectors` rebuilds vector indexes after a PGLite crash repair, and the repair notice names it.+- **Contextual retrieval mode (#5621).** `--no-embed` imports record their mode. Contributed by @woprrr (#5630). `gbrain repair contextual-mode` stamps existing pages exactly as a fresh import would and re-embeds only pages whose input changes.+- **Grandfathering groups its Git work (#5530).** The effect runner commits up to 100 ready single-file Git effects of a worktree together and pushes each root once per pass; a failed push leaves the group queued for the next pass.+- **`embed --stale --dry-run` matches the live run (#5289).** Chunks that only need a restamp are reported as `would_restamp`.++#### Recovery after an upgrade++- **Repairs are part of the remediation plan.** `gbrain doctor --remediation-plan` lists each `gbrain repair` kind with pending items (timeline, visibility, safe-chunks, contextual-mode, connector-checkpoints) as a protected step with its apply command, independent of `--target-score`. `--remediate --include-repairs` runs them in-process on the brain host under a cumulative, resumable `--max-usd` cap; free steps always run.+- **Finding classes and exit status.** `gbrain doctor --remediate --json` classifies every finding as `cleared`, `pending`, `consent_required`, `operator_required` or `unsupported`, and exits 0 when no automatically repairable finding is left.+- **Preview-only post-upgrade banner.** `gbrain post-upgrade` runs the recovery checks once and prints one `[AGENT] Relay this to your operator` block with each finding's count, the connector re-walk count and the preview command. It never prints `--yes` or `--apply`.+- **Remote doctor host-action lines.** Remote callers see one sanitized line per recovery check, never paths, row contents, SQL, account emails or installation ids; a check that cannot run says `Unknown:`.+- **New doctor checks.** `connector_checkpoints` (orphan connector cursor rows, cleared by `gbrain repair connector-checkpoints`), `unbound_source`, `safe_index_pending`, `self_capture` (#5413, with copy-paste quarantine commands) and `stale_embedding_effects` (#5629).+- **`gbrain repair` refuses unknown options,** and `--max-usd` points to the capped doctor route.+- **`gbrain autopilot pause` / `resume`.** A pause survives `gbrain upgrade` and `autopilot --install`; `resume` never clears a migration hold.+- **Writer admin lock (#5285).** `gbrain sources writer lock` / `unlock` set an opt-in lock under which writer claim, activate and transfer refuse with `writer_admin_locked`. Ordinary writes continue. It is not a security boundary.+- **Writer versions (migration 178).** Each write request records the version and host of the binary that admitted it and of the consumer that published it. Doctor's `writer_version` check warns about writers older than this release or v0.60.5.0 seen in the last 7 days. It observes; it does not enforce.+- **`writer_not_quiesced` names what blocks it (#5629).**+- **Managed-worktree fixes.** A `gbrain sources push` refused by the managed-worktree guard records the refusal (#5614), `writer claim` before activation returns `activation_required` naming what it fences (#5617), and autopilot skips sync for claimed sources awaiting activation (#5613). Contributed by Roma Cherepanov (@cheRoma).++Contributions: the no-op screen builds on #5581 by @tarush1989; the cycle-stamp diagnosis and test cases build on #5695 by @thebergerking91; the concept and chronicle publication approach comes from #5631 by @akinduroifedayo; `--no-embed` mode stamping is #5630 by Alexandre Mallet (@woprrr); the managed-worktree fixes are #5614, #5617 and #5613 by Roma Cherepanov (@cheRoma).++### For contributors++- `test/fix-wave-3-integration.test.ts` (with its Postgres arm in `test/e2e/fix-wave-3-integration.test.ts`) runs the twelve cross-lane checks, plus a chaos scenario with a delayed consumer and a provider outage, a timed recovery run (at most 3 operator commands, 5-minute ceiling) and the managed zero-norm check.+- `.github/workflows/macos-validation.yml` runs nightly, on dispatch and on pull requests labelled `macos-validation`, on a pinned `macos-26` runner with no secrets: APFS device-identity re-stamp, the PGLite checkpoint harness on a store of at least 2 GiB, and the signed release binary.+- The canonical-writer census counts direct `importFromContent` calls; `scripts/bench-grandfather-5530.ts` reproduces the grandfather numbers.+- The `fast-uri` override moves to 3.1.8 for a medium-severity advisory in 3.1.7.+## [0.60.10.0] - 2026-09-29**Local PGLite brains now commit writes about 3.7× faster, with the same durability.**diff --git a/INSTALL_FOR_AGENTS.md b/INSTALL_FOR_AGENTS.mdindex 2e7e4ab83c..b7a904bacd 100644--- a/INSTALL_FOR_AGENTS.md+++ b/INSTALL_FOR_AGENTS.md@@ -510,7 +510,9 @@ upgrade every process that writes to the brain, then follow the[v0.60.5.0 steps](skills/migrations/v0.60.5.0.md): one full `gbrain doctor`,then preview `gbrain repair` and apply only after the user agrees([repair guide](docs/guides/repair.md)). For v0.60.6.0, also follow the-[one-time timeline prune and slug-collision steps](skills/migrations/v0.60.6.0.md).+[one-time timeline prune and slug-collision steps](skills/migrations/v0.60.6.0.md). For v0.60.11.0, preview+`gbrain repair contextual-mode` and rebuild PGLite vector indexes after a crash+repair ([steps](skills/migrations/v0.60.11.0.md)).For v0.53.0.0, follow the[mechanical shared-skills migration](skills/migrations/v0.53.0.0.md) on the host,diff --git a/TODOS.md b/TODOS.mdindex ee403ce18f..56d41c3edd 100644--- a/TODOS.md+++ b/TODOS.md@@ -1,5 +1,58 @@# TODOS+## Fix wave 3 follow-ups (filed 2026-09-29, follow-up from v0.60.11.0)++### Recovery layer++- [ ] **P1 — Bounded replay window for lifetime request IDs (wave-2 CEO-E7).**+ **What:** every admitted write keeps a permanent request ID for replay protection, so the principal and brain lifetime-ID limits only move later (`persistence_capacity` warns at 80% and names a `gbrain config set` value). **Fix:** a bounded replay window with a documented horizon and an eviction rule that never replays a committed write twice; size it from the default of 600 admissions a day (about 417 days of headroom at the default limit). **Effort:** L. **Priority:** P1.+- [ ] **P1 — `gbrain sources writer deactivate` (#5455).**+ **What:** managed mode is a one-way door: the claim and activate runbook in `docs/architecture/topologies.md` tells operators to take a database backup because nothing turns activation off. **Fix:** a deliberate, state-bound deactivate with the same `--admin-intent` / `--expected-state` contract and quiescence checks, honoring the writer admin lock. **Effort:** M. **Priority:** P1.+- [ ] **P1 — Opt-in `min_writer_version` floor.**+ **What:** the `writer_version` doctor advisory only observes: a binary older than v0.60.5.0 can still delete database-only timeline rows. **Fix:** an opt-in floor enforced at admission and publication by the database (reusing the `writer_protocol_floor` trigger pattern), a binary version declaration older binaries lack, quiescence to enable it, and a floor that cannot be lowered. Eng estimate 1,500-3,000 changed lines against 800-1,500 for the advisory. **Effort:** L. **Priority:** P1.+- [ ] **P1 — #5629: reconcile or re-queue a stale queued embedding effect.**+ **What:** a committed write whose queued embedding effect is never claimed blocks shared-skill activation (`writer_not_quiesced` names it; doctor reports `stale_embedding_effects` as unsupported), and `retry-effects` refuses effects that have not failed. **Fix:** let the operator reconcile existing vectors or re-queue the effect under the owner, never silently drop the embedding obligation; then reclassify the doctor finding as repairable. **Effort:** M. **Priority:** P1.+- [ ] **P2 — #5522: write the reproduction first.** Plausible but unreproduced; no code until a failing repro exists. **Priority:** P2.+- [ ] **P2 — #5226 part 2.** Revisit only after part 1 is confirmed fixed with pacing on. **Priority:** P2.+- [ ] **P2 — Database remediation run record with a reservation ledger.**+ **What:** the remediation cap, consent and spend live in the local checkpoint (`~/.gbrain/remediation/<plan hash>.json`), which covers one host. **Fix:** a `remediation_runs` record plus per-attempt reservations that delegated workers enforce, so a cap holds across processes and hosts. This also closes two known gaps: the embedding effects that `timeline` and `visibility` repairs queue are charged at their pre-repair estimate but the persistence consumer does not enforce the cap per provider call, and a resumed safe-chunks embedding pass is scoped by source rather than by the exact re-sealed pages. **Effort:** L. **Priority:** P2.+- [ ] **P3 — Host-label registry for writer-version warnings.** The advisory names hosts by persistence host UUID because no hostname is recorded (`identity.ts` `host.json`). Record an operator-chosen label per host and show it beside the UUID. **Effort:** S. **Priority:** P3.+- [ ] **P3 — `source-paths` / `source-uris` repair kinds and the metadata-repair intent (dropped from W8).** Revisit when `invalid_source_uri` reports arrive; the manual step in `docs/guides/write-refusals.md` stands until then. **Priority:** P3.+- [ ] **P3 — Doctor check for unpushed managed commits by age (#5198 thread).** **Priority:** P3.+- [ ] **P3 — #3783 with #5691: query-side embedding prefixes behind a setting.** **Priority:** P3.+- [ ] **P3 — #5392 inert single-writer mode.** Recommended no: resolve through the #5198/#5254 family instead. Recorded so the decision is visible. **Priority:** P3.+- [ ] **P3 — Retire `safeChunkUpgradeAdvisory`.** Post-upgrade now reports `safe_index_pending` through the recovery banner; the function remains only for `test/safe-chunk-reseal.test.ts`. Move that assertion onto the doctor check and delete the function. **Effort:** S. **Priority:** P3.++### Connectors++- [ ] **P1 — Move the cycle stamps out of `sources.config`.**+ **What:** `runCycle` writes `last_source_cycle_at` / `last_full_cycle_at` into `sources.config` after every source cycle; that rotating blob was the root cause behind #5686. v0.60.11.0 keys connector identity on parsed settings instead, but nine files still read the stamps from the blob. **Fix:** dedicated columns or a cycle-state row, with a migration; community PR #5695 sketched one.+- [ ] **P2 — Per-source "admit even if unchanged" bypass for the #5470 no-op skip.**+ **What:** there is no way to force one connector, import or sync source to republish unchanged pages (for example after a renderer fix that keeps content hashes). **Fix:** a source-scoped, one-run flag that disables the kernel skip; `--reset-checkpoint` only re-walks.+- [ ] **P3 — Configurable connector pending-wait budget, clamped to the run's deadline.**+ **What:** the managed connector waits at most 30 s in total for accepted writes per run (`CONNECTOR_WAIT_BUDGET_MS`). **Fix:** a config key, clamped so it never exceeds the caller's job timeout.+- [ ] **P2 — Multi-source connector fan-out deadline (`stopped_on_wait_budget` across sources).**+ **What:** each connector run bounds its own waits and records `stopped_on_wait_budget`, but no in-process fan-out dispatches many connector sources against one shared deadline, so the plan's 50-source fan-out stop was not built. **Fix:** when such a fan-out exists (for example `sync --all` over connector sources), stop dispatching new sources at the deadline and report the rest.+- [ ] **P3 — Connector ingest waits on its whole pending set while the owner is delayed.**+ **What:** under a delayed consumer each run first waits on its recorded pending set and stops on the wait budget, so new upstream items are not admitted until the backlog drains (measured by `test/fix-wave-3-chaos.test.ts`). Nothing is lost; the items wait upstream. **Fix:** if time-to-searchable under sustained arrivals matters, admit new items up to the outstanding limit while the pending set resolves.+- [ ] **P3 — User timeline bullets on pages other preserving writers regenerate.**+ **What:** `add_timeline_entry` on a connector page now writes a materialized-marked bullet so the connector re-render keeps it (#5567). Other preserving writers that regenerate an ordinary page still treat an unmarked bullet their new body drops as removed. **Fix:** audit those writers and mark user-added bullets on the pages they own, with a regression per writer.+- [ ] **P2 — Facts and takes fences below the timeline sentinel on connector pages.**+ **What:** a connector re-render carries the page's facts and takes fences (so remembered facts are not expired), but only when the stored fences sit in the page body and pass the preservation check. A legacy page with a fence below the timeline sentinel, or an ambiguous fence, still loses those rows on re-render. **Fix:** move such fences above the sentinel in a repair, or refuse the connector publication for that page with a typed hold and a repair command.+- [ ] **P3 — Row-level ownership for fences in connector renders.**+ **What:** when the provider's own render carries a facts fence (for example a GitHub issue body), the provider owns the whole fence: upstream corrections win, and rows added on the brain to that fence are not carried. When the provider later drops its fence entirely, the stored fence is carried as brain-added. **Fix:** record which fence rows came from the provider so each side's rows follow its owner.+- [ ] **P3 — Resume a partially refused embedding without re-embedding its siblings.**+ **What:** after a #4616 refusal the page signature is cleared so `gbrain embed --stale` finds it; an explicit `retry-effects` then re-embeds the page's other chunks too, and `gbrain embed <slug>` stamps the signature only when it embeds every chunk in one run. **Fix:** judge completion from per-chunk provenance and stamp the page once the stored set is complete.+- [ ] **P3 — Record #4616 refusals inside embedding scans.**+ **What:** a withdrawal or source-scan embedding effect that meets a refused chunk moves on to its next page, so the effect can finish `committed` while that page's refused chunk has no vector (the page keeps no signature, so `gbrain embed --stale` still finds it). The generic parking path is built for Git and withdrawal targets: it would share the scan's embedding retry budget across pages, and `retry-effects` would mark a parked embedding scan complete. **Fix:** a scan-local refused-page list that resets the per-page attempt base and that `retry-effects` resolves before completing.++### Maintenance writers++- [ ] **P2 — Managed `writeSingleFact` keeps unresolved entity attribution.**+ **What:** on a managed brain a single fact for an entity with no page is stored database-only with `entity_slug` NULL (the response now reports that honestly), so the same claim for a second absent entity dedups against the first. The shared `managed_facts_entity` preparer accepts only the row's slug or NULL. **Fix:** an opt-in intent flag used only by `writeSingleFact`: `publishManagedFacts` keeps the resolver's fallback slug on `memory/unattributed` rows, and `prepareManagedFactsMutation` allows that slug on rows without a row number and passes it to `insertFact`, so dedup is per entity; add a test pinning the facts backstop's unchanged replay and dedup contract.+- [ ] **P3 — Release the reservation of other permanent embedding rejections.**+ **What:** the migration budget now refunds a provider token-limit rejection (it bills nothing), but the drain's per-chunk fan-out after another permanent 4xx (400/413/422) keeps the failed batch's maximum debit; the overshoot and exhaustion refusal bound it, but it can stop a migration early. **Fix:** map those unbilled rejections through the same `invokeAI` rejection mapper, with a test at exactly the printed cap.+## Test-audit follow-ups (filed 2026-09-29)Evidence for each item is in `docs/test-audit/2026-09-29/`.diff --git a/VERSION b/VERSIONindex 4d0449862b..11b69fff54 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-0.60.10.0+0.60.11.0diff --git a/bun.lock b/bun.lockindex 73fc5928f0..7d2add681e 100644--- a/bun.lock+++ b/bun.lock@@ -55,7 +55,7 @@"@ai-sdk/provider-utils": "4.0.33","@hono/node-server": "^2.0.5","body-parser": "^2.3.0",- "fast-uri": "3.1.7",+ "fast-uri": "3.1.8","fast-xml-builder": "^1.1.7","fast-xml-parser": "^5.7.0","form-data": "^4.0.6",@@ -405,7 +405,7 @@"fast-deep-equal": ["[email protected]", "", {}, "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="],- "fast-uri": ["[email protected]", "", {}, "sha512-dOvZVzjdZdz7phd9v6jCbwxrBW3fK6n8Rc0CtdmM4bumzMnxywBYhuph6J819RRw/ku+rLbelwfMunktuzVVHg=="],+ "fast-uri": ["[email protected]", "", {}, "sha512-GZMtZUTNRpOVIECoXwLNZS5xUGE+mVNbTB8h/7Rwh2TFWcBQiPzTgyZi05BF9UMZKkLJv8XBRJTlU7zg8+ZfMg=="],"fast-xml-builder": ["[email protected]", "", { "dependencies": { "path-expression-matcher": "^1.6.2", "xml-naming": "^0.3.0" } }, "sha512-F74cZEdCvuw9P41GAC3rod4X04jjWGM1JPEv/GWSqFTWLsdyMSBMBMlm9Hk3GLBgLBbdBNY8yee0pQh2RBVESQ=="],diff --git a/docs/ENGINES.md b/docs/ENGINES.mdindex 06c0a03a39..ccbe0dfef4 100644--- a/docs/ENGINES.md+++ b/docs/ENGINES.md@@ -270,9 +270,12 @@ version bump changes it.backs up `pg_wal/` + `pg_control` into a sibling`<dataDir>.wal-repair-backup-<ts>/` dir, resets the WAL in place(pg_resetwal semantics — data files preserved; transactions not- checkpointed before the corruption may be lost), and retries once. On- success it prints a loud stderr notice naming the backup and recommending- `gbrain doctor`. Safety bounds: repair only runs under a cleanly-acquired+ checkpointed before the corruption may be lost), and retries once. The+ reset does not rebuild indexes, so a page written just before the crash+ can be missing from vector search while keyword search still finds it.+ On success it prints a loud stderr notice naming the backup and the next+ commands: `gbrain reindex --vectors` (rebuilds every HNSW index from the+ stored vectors, no re-embedding) and then `gbrain doctor`. Safety bounds: repair only runs under a cleanly-acquireddata-dir lock (never after reaping another process's lock), skips for acooldown window after a failed attempt(`GBRAIN_PGLITE_WAL_REPAIR_COOLDOWN_SECONDS`, default 3600), reuses onediff --git a/docs/TESTING.md b/docs/TESTING.mdindex 2eecbc7b4d..d7a73deb6a 100644--- a/docs/TESTING.md+++ b/docs/TESTING.md@@ -521,8 +521,11 @@ the CI runner image supplies `setpriv`.`test/managed-maintenance.test.ts` and`test/helpers/maintenance-restart.ts` cover local synthesize/patterns/consolidation, restart replay, retired takes and semantic snapshots;-`test/managed-unsupported-preflight.serial.test.ts` checks unsupported bulk-lanes refuse before spend. These use synthetic provider/API transports, not+`test/managed-unsupported-preflight.serial.test.ts` checks that the managed+facts-family bulk lanes refuse an unaccepted writer before spend, and+`test/managed-facts-writers.test.ts` proves each of them (fence reconcile,+phantom redirect, fence writes, loops extraction, bulk conversation facts)+publishes through the coordinator on PGLite and Postgres. These use synthetic provider/API transports, notpaid model calls or production connectors. PGLite dream/job CLI with an activeowner is **not** proven delegated by the live fact-backfill IPC test.@@ -720,7 +723,7 @@ 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)+### PGLite checkpoint harness (outside PR CI)`scripts/pglite-checkpoint-harness/supervisor.ts` reproduces the large-storePGLite freeze. It spawns `worker.ts`, which imports 40 KB pages through@@ -740,6 +743,29 @@ bun scripts/pglite-checkpoint-harness/supervisor.ts --dir /tmp/h --fresh --pages--shared-buffers 16MB --max-wal-size 160MB --stall-sec 120 --expect-wedge # baseline check```+`--min-store-gb <n>` also fails a completed run whose data directory is+smaller than `n` GiB; the result reports the store size with and without WAL.+On macOS the supervisor samples worker CPU with `ps` instead of `/proc`.++### macOS 26 validation (`macos-validation`)++`.github/workflows/macos-validation.yml` runs on a GitHub-hosted `macos-26`+runner nightly, on manual dispatch, and on pull requests that carry the+`macos-validation` label. It uses no secrets and has a 90-minute cap. It checks+the device-identity re-stamp (#5604) on real APFS (the step first asserts an+APFS volume with a non-zero birth time and inode; the device-number change+itself stays simulated because a runner never reboots), runs the checkpoint+harness above on a store of at least 2 GiB with the WAL-bound assertion+(#5449), and verifies the latest published signed `darwin-arm64` release+binary with `codesign --verify --strict` and `--version` against its release+tag (#5286). Maintainers with triage or write access apply the label; an+outside contributor whose change touches macOS-specific persistence, locking+or release code asks for it in the pull request. Scheduled and dispatched runs+use the default branch's workflow file, so the label is the way to get this+evidence for a change before it merges. `test.yml`'s security matrix,+`release.yml`'s darwin build and `native-locks.yml`'s darwin cells pin+`macos-26` / `macos-26-intel` rather than `macos-latest`.+### Keeping CI partitions balancedRequired CI runs eight weighted unit workers, four serial workers with boundeddiff --git a/docs/architecture/canonical-writers.tsv b/docs/architecture/canonical-writers.tsvindex 624639f21f..7cae73563c 100644--- a/docs/architecture/canonical-writers.tsv+++ b/docs/architecture/canonical-writers.tsv@@ -4,15 +4,15 @@ 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/links-maintenance.ts 1 coordinator Managed extract --stale and post-sync extraction add only the coordinator's unrecorded canonical timeline tuples inside a revision-bound withCoordinatedWrite transaction that also replaces the page's derived links and stamps its watermark.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-conversation-facts.ts 4 coordinator On a managed brain the conversation fact rows, orphan cleanup and audit rows are database-only derived rows committed through writeDerivedFacts inside withCoordinatedWrite under the page key after a local-writer preflight that runs before provider work; unmanaged calls keep their direct engine writes behind the SQL guard.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.+src/commands/jobs.ts 0 coordinator The purge job runs purgeDeletedPagesCoordinated; remaining canonical writes live in delegated coordinated modules.src/commands/migrate-engine.ts 11 early_refusal Managed mode refuses this legacy entry point before its canonical filesystem/provider effects.src/commands/migrations/v0_13_1.ts 2 engine_guard Unmanaged metadata batches retain page guards and row locks; managed active Markdown pages route through the canonical grandfather publisher instead of direct SQL.src/commands/migrations/v0_32_2.ts 1 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.-src/commands/pages.ts 2 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.+src/commands/pages.ts 1 engine_guard The dry-run preview reads through the engine; the purge runs purgeDeletedPagesCoordinated, which is coordinated on managed brains.src/commands/reconcile-links.ts 2 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.src/commands/reindex-aliases.ts 1 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.src/commands/sources-set-path.ts 1 coordinator Managed rebind uses native exclusion, exact manifest verification and a retained source-incarnation receipt; unmanaged pointer repair remains explicit.@@ -23,54 +23,54 @@ src/core/atomic-write.ts 0 filesystem_guard Atomic page replacement checks the msrc/core/backfill-effective-date.ts 1 projection Derived indexing, retrieval telemetry, or source settings; canonical fields remain guarded by SQL triggers.src/core/background-work.ts 1 projection Derived indexing, retrieval telemetry, or source settings; canonical fields remain guarded by SQL triggers.src/core/backup/quarantine.ts 3 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.-src/core/bootstrap/verify.ts 4 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.+src/core/bootstrap/verify.ts 2 coordinator Probe writes use put_page; a managed brain purges probes through delete_page purge and deletes probe facts inside withCoordinatedWrite, while the unmanaged cleanup keeps the engine primitives behind the canonical table trigger.src/core/brain-repo-durability.ts 0 filesystem_guard Hardening checks the root; generated push/rebase helpers honor shared refusal markers.src/core/brain-writer.ts 0 filesystem_guard Frontmatter repair checks the managed root before backup or file replacement.src/core/calibration/undo-wave.ts 1 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.-src/core/chronicle/extract-events.ts 2 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.+src/core/chronicle/extract-events.ts 2 coordinator A managed brain publishes each event page and its depth timeline row through publishMaintenancePage after maintenancePreflight; the unmanaged putPage/upsertEventProjection pair stays behind the canonical table trigger.src/core/company-brain/admission.ts 1 coordinator Managed registration delegates to source lifecycle; the unmanaged insert runs under native topology locks and a principal/source-locked transaction that validates the approved plan, binds the schema and records the ingestion receipt atomically.-src/core/company-brain/demo.ts 1 isolated_eval Fictional source registration uses a new PGLiteEngine connected with an empty config, so writes remain in an isolated in-memory database that is disconnected after the demo; the configured brain is never opened.-src/core/company-brain/profile.ts 1 engine_guard Company-profile legacy deletes use withCompanyBrainSource to lock and validate source incarnation, path, receipt and policy; calls without that context retain engine guards, and managed sync routes to the coordinator before this legacy path.+src/core/company-brain/demo.ts 2 isolated_eval Fictional source registration uses a new PGLiteEngine connected with an empty config, so writes remain in an isolated in-memory database that is disconnected after the demo; the configured brain is never opened. Direct importFromContent calls without prepare refuse on managed brains before any write (assertUnmanagedCanonicalWriter).+src/core/company-brain/profile.ts 2 engine_guard Company-profile legacy deletes use withCompanyBrainSource to lock and validate source incarnation, path, receipt and policy; calls without that context retain engine guards, and managed sync routes to the coordinator before this legacy path. Direct importFromContent calls without prepare refuse on managed brains before any write (assertUnmanagedCanonicalWriter).src/core/company-brain/runtime.ts 1 projection Only source policy metadata advances under the company-source lock and brain/source row locks; the same transaction validates immutable approval and creates a receipt with source-incarnation and managed owner/topology fences, without source-file writes.-src/core/cycle/drift.ts 1 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.+src/core/cycle/drift.ts 1 coordinator A managed brain preflights maintenance authority before judge spend and publishes the report through publishMaintenancePage; the unmanaged putPage stays behind the canonical table trigger.src/core/cycle/extract-atoms.ts 3 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.-src/core/cycle/extract-facts.ts 6 early_refusal Managed legacy fence reconciliation refuses before providers; unmanaged reconciliation keys rows by fence row number under the page lock, updates matched rows in place, expires and detaches removed rows instead of deleting them, and expires fence-owned rows of soft-deleted pages.+src/core/cycle/extract-facts.ts 7 coordinator Managed and unmanaged reconciliation key rows by fence row number under the page lock, update matched rows in place, expire and detach removed rows instead of deleting them, and expire fence-owned rows of soft-deleted pages; on a managed brain each page transaction and the deleted-page expiry run inside withCoordinatedWrite (page key locked, body rechecked) after a local-writer preflight before any embedding call; the managed deleted-page expiry locks each candidate page key and rechecks its deletion before expiring its rows.src/core/cycle/extract-atoms-page-state.ts 1 engine_guard Atom completion updates and cardinality checks share one transaction; managed canonical SQL remains fenced and scan/failure bookkeeping is stored separately.src/core/cycle/extract-takes.ts 4 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication. Stale-row pruning deletes only takes whose rows left a cleanly parsed fence on a live page in the same source.-src/core/cycle/grade-takes.ts 1 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.+src/core/cycle/grade-takes.ts 1 coordinator A managed brain applies auto-resolutions through the coordinated takes_resolve page mutation; the unmanaged resolveTake stays behind the canonical table trigger.src/core/cycle/patterns.ts 0 coordinator Managed local patterns use admitted page operations and validate canonical outputs; the legacy reverse-file path runs only unmanaged.-src/core/cycle/phantom-redirect.ts 5 early_refusal Managed mode refuses this legacy entry point before its canonical filesystem/provider effects.+src/core/cycle/phantom-redirect.ts 3 coordinator Managed brains route the redirect to phantom-redirect-managed.ts (canonical merge and phantom delete as coordinated maintenance requests whose publication moves the rows); the legacy file-first path runs only unmanaged and its canonical SQL stays trigger-guarded.src/core/cycle/phases/consolidate.ts 5 coordinator Managed local consolidation publishes a take, semantic contributing facts and file in one guarded receipt transaction; legacy writes remain SQL-guarded.src/core/cycle/synthesize.ts 2 coordinator Managed summaries and provenance use prepared journal publication; legacy direct rows and reverse-file writes run only unmanaged.-src/core/cycle.ts 3 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.+src/core/cycle.ts 2 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.src/core/destructive-guard.ts 3 coordinator Managed source archive, restore and expiry purge use native exclusion and guarded topology transitions; remaining canonical maintenance keeps its engine guard.src/core/embedding-dim-check.ts 1 projection Derived indexing, retrieval telemetry, or source settings; canonical fields remain guarded by SQL triggers.src/core/embedding-invalidation.ts 2 projection Derived vector invalidation; signature restamping requires matching chunk context and a current text projection. Canonical fields remain guarded by SQL triggers.src/core/embedding-migration.ts 1 projection Derived indexing, retrieval telemetry, or source settings; canonical fields remain guarded by SQL triggers.src/core/engine-constants.ts 1 contract Engine contract or explanatory SQL references; execution is in guarded engine implementations.src/core/engine.ts 2 contract Engine contract or explanatory SQL references; execution is in guarded engine implementations.-src/core/enrichment-service.ts 3 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.+src/core/enrichment-service.ts 4 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication. Direct importFromContent calls without prepare refuse on managed brains before any write (assertUnmanagedCanonicalWriter).src/core/extract/receipt-writer.ts 1 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.src/core/extract-timeline-from-meetings.ts 1 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.src/core/facts/backstop.ts 3 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.-src/core/facts/fence-write.ts 2 filesystem_guard Source filesystem ownership is checked before editing canonical fact fences.+src/core/facts/fence-write.ts 2 coordinator Managed brains publish fence rows through the managed_facts_entity intent before any file or row write; unmanaged writes keep the source filesystem ownership check before editing canonical fact fences.src/core/facts/forget.ts 4 filesystem_guard Managed callers journal withdrawal; legacy filesystem helper and the supersession-only expiry require coordinated write.src/core/facts/withdrawal-schema.ts 1 schema Migration v174 DDL/backfill expires fact rows that match a folded withdrawal fingerprint; schema installation runs under coordinated activation, which quiesces canonical writers.src/core/facts/withdrawal.ts 2 coordinator Publication is transaction-scoped under admitted authority, source/page guards and revision checks.-src/core/facts/write-single.ts 2 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.+src/core/facts/write-single.ts 2 coordinator Managed brains publish the single fact through the managed_facts_entity intent before the legacy supersession or DB-only insert; those legacy writes run only unmanaged and stay trigger-guarded.src/core/git-remote.ts 0 filesystem_guard Clone, pull and rebase entry points check the durable root refusal registry.src/core/github-source.ts 3 coordinator Managed connector imports, deletion and checkpoints use prepared journal publication; unbound API sources explicitly persist in the database and bound sources retain canonical filesystem publication.src/core/google/google-source.ts 3 coordinator Managed connector imports, deletion and checkpoints use prepared journal publication; legacy materialization is confined to unmanaged sources.-src/core/google/loops-extract.ts 1 early_refusal Unsupported managed loop extraction refuses before model calls; unchanged unmanaged fact/fence writes remain guarded.-src/core/import-file.ts 17 coordinator Prepared import applies under journal publication and revision CAS; direct managed imports refuse early, legacy source-path repair follows revision validation inside a savepoint, and a moved file's page is renamed only on the direct (unmanaged) path. Frontmatter tag reconciliation deletes only import-owned tag rows inside the same guarded import transaction.+src/core/google/loops-extract.ts 1 coordinator Managed loop extraction checks the managed fact authority and owner before model calls and publishes its commitment fact through writeSingleFact's coordinator path; the provenance-tagged loop edge is not a guarded canonical table.+src/core/import-file.ts 19 coordinator Prepared import applies under journal publication and revision CAS; direct managed imports refuse early, legacy source-path repair follows revision validation inside a savepoint, and a moved file's page is renamed only on the direct (unmanaged) path. Frontmatter tag reconciliation deletes only import-owned tag rows inside the same guarded import transaction. Direct importFromContent calls without prepare refuse on managed brains before any write (assertUnmanagedCanonicalWriter).src/core/last-retrieved.ts 1 projection Derived indexing, retrieval telemetry, or source settings; canonical fields remain guarded by SQL triggers.src/core/migrate.ts 13 schema Schema installation and forward-reference DDL; coordinated activation quiesces canonical writers.-src/core/minions/handlers/ingest-capture.ts 1 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.+src/core/minions/handlers/ingest-capture.ts 3 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication. Direct importFromContent calls without prepare refuse on managed brains before any write (assertUnmanagedCanonicalWriter).src/core/onboard/checks.ts 2 projection Derived indexing, retrieval telemetry, or source settings; canonical fields remain guarded by SQL triggers.src/core/ops/extraction.ts 2 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.-src/core/ops/links.ts 2 early_refusal Managed mode refuses this legacy entry point before its canonical filesystem/provider effects.+src/core/ops/links.ts 3 coordinator Unmanaged add_link/remove_link keep the engine calls; a managed brain takes coordinatedManualLinkWrite, which checks durable write authority for the from page and commits the database-only edge inside a source-scoped withCoordinatedWrite transaction holding both endpoint page keys.src/core/ops/loops.ts 1 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.-src/core/ops/pages.ts 5 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.+src/core/ops/pages.ts 0 coordinator Page mutations delegate to persistence modules; purge_deleted_pages runs purgeDeletedPagesCoordinated.src/core/output/writer.ts 6 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.src/core/page-state/materialize.ts 1 coordinator Publication is transaction-scoped under admitted authority, source/page guards and revision checks.src/core/page-state/projection-schema.ts 1 schema Schema installation and forward-reference DDL; coordinated activation quiesces canonical writers.@@ -79,7 +79,7 @@ src/core/page-state/schema.ts 2 schema Schema installation and forward-referencesrc/core/page-state/tags.ts 3 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication. The frontmatter-claim and explicit-add inserts are two branches of one guarded statement.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 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/page-prepare.ts 10 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. Its importFromContent calls carry prepare and run inside the coordinator publication.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.@@ -105,10 +105,10 @@ src/core/takes-write.ts 8 filesystem_guard Managed operation routes through joursrc/core/think/index.ts 1 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.src/core/timeline-dedup-repair.ts 3 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.src/core/timeline-write-through.ts 2 filesystem_guard Managed semantic operation journals page changes; legacy atomic writes check root.-src/core/transcripts/ingest.ts 1 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.+src/core/transcripts/ingest.ts 2 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication. Direct importFromContent calls without prepare refuse on managed brains before any write (assertUnmanagedCanonicalWriter).src/core/workspace-push.ts 0 filesystem_guard The resolved git root is checked before staging, committing or pulling.src/core/write-through.ts 1 filesystem_guard Source filesystem lock and canonical page SQL guards reject legacy publication.-src/eval/brainbench/seed.ts 2 isolated_eval Explicit isolated evaluation database only; never opened against the active managed brain.+src/eval/brainbench/seed.ts 3 isolated_eval Explicit isolated evaluation database only; never opened against the active managed brain. Direct importFromContent calls without prepare refuse on managed brains before any write (assertUnmanagedCanonicalWriter).src/eval/chronicle/harness.ts 2 isolated_eval Explicit isolated evaluation database only; never opened against the active managed brain.src/eval/longmemeval/extract.ts 1 isolated_eval Explicit isolated evaluation database only; never opened against the active managed brain.src/commands/reinit-pglite.ts 0 filesystem_guard Managed datastore registry refuses destructive reinit even offline; unmanaged rename requires the stable native lock.@@ -117,13 +117,13 @@ src/commands/files.ts 0 filesystem_guard Attachment copying, redirection, restorsrc/commands/schema.ts 0 filesystem_guard Schema manifest scaffolding and forks check managed roots before creating files; separate config settings are control data.src/core/ingestion/sources/inbox-folder.ts 0 filesystem_guard Inbox archive moves refuse managed canonical input paths before emitting the event or moving source bytes.src/core/persistence/links-preparation.ts 2 coordinator Automatic graph projections publish inside canonical page transactions; delayed reconciliation locks all affected page keys and compares the originating revision.-src/core/persistence/sync-prepare.ts 5 coordinator Managed imports and deletes validate the recorded raw file hash plus enumerated page identity/revision; a managed rename moves the page with updateSlug and re-infers an implicit type inside the same journal publication after the renamed page's identity and revision are rechecked; the source-exclusive final checkpoint requires every selected receipt to be committed.-src/commands/enrich.ts 0 early_refusal Managed batch synthesis refuses before providers until its resume cursor retains prepared writes; legacy synthesis still carries a coherent revision and exposes pending request IDs.+src/core/persistence/sync-prepare.ts 7 coordinator Managed imports and deletes validate the recorded raw file hash plus enumerated page identity/revision; a managed rename moves the page with updateSlug and re-infers an implicit type inside the same journal publication after the renamed page's identity and revision are rechecked; the source-exclusive final checkpoint requires every selected receipt to be committed. Its importFromContent calls carry prepare and run inside the coordinator publication.+src/commands/enrich.ts 0 coordinator A managed brain preflights maintenance authority before any model spend and publishes each enriched page through publishMaintenancePage; unmanaged enrichment writes through the put_page operation.src/core/persistence/source-lifecycle.ts 6 coordinator Native affected roots precede topology, source, principal and receipt guards; every shared-root generation and old queued intent changes together.src/core/persistence/topology-recovery.ts 2 coordinator Verified directory-swap recovery checks source incarnation, current logical manifest and physical identity before topology commitment; permanent receipt IDs survive deletion.-src/core/persistence/connector-sync.ts 2 coordinator Connector freshness and source-scoped deletion commit through original/current authority, source and revision guards, canonical publication and checkpoint CAS.-src/core/persistence/prepared-maintenance.ts 2 coordinator Named local maintenance uses native owner publication; contributing semantic facts and take lifecycle are revalidated and committed together with canonical files and receipts.-src/core/persistence/facts-prepare.ts 2 coordinator Multi-entity fact publication rechecks original/current source authority, origin and target revisions, withdrawals and deduplication under coordinated page locks.+src/core/persistence/connector-sync.ts 4 coordinator Connector freshness and source-scoped deletion commit through original/current authority, source and revision guards, canonical publication and checkpoint CAS. A skipped unchanged checkpoint save stamps sources.last_sync_at/newest_content_at (never page content) inside withCoordinatedWrite, in a transaction that first asserts the connector sync lease, scoped to the source incarnation (#5686/#5470). Its importFromContent calls carry prepare and run inside the coordinator publication.+src/core/persistence/prepared-maintenance.ts 3 coordinator Named local maintenance uses native owner publication; contributing semantic facts and take lifecycle are revalidated and committed together with canonical files and receipts; a chronicle event page and its depth timeline projection commit in one publication.+src/core/persistence/facts-prepare.ts 3 coordinator Multi-entity fact publication rechecks original/current source authority, origin and target revisions, withdrawals and deduplication under coordinated page locks; a direct single-fact write (supersede intent) strikes the superseded fence row and expires and links the old fact in the same publication transaction.src/core/embed-facts.ts 1 projection Explicit bounded repair updates only fact embedding projections with selected-brain off-switch, invocation budget, source incarnation and fact-row version checks before atomic installation.src/core/shared-skills/knowledge-guard.ts 0 coordinator Page publication rejects registered skill namespaces and manifest paths using source incarnations, canonical roots and stored physical aliases; the coordinator rechecks before bytes and inside publication guards.src/core/skillpack/writer-guard.ts 0 filesystem_guard Legacy skill writers reuse durable managed-root and symlink-aware refusal; multiply linked sinks fail closed against out-of-root inode aliases, with put_skill and host-authorized adoption remedies.@@ -157,8 +157,20 @@ src/core/dry-fix.ts 0 filesystem_guard Doctor and check-resolvable repair preflisrc/core/skillpack/harness-bridge.ts 0 filesystem_guard Harness install, reference rewrite and ledger-owned removal preflight all destinations before effects; rewrite and deletion sinks recheck canonical refusal.src/core/shared-skills/setup.ts 1 engine_guard Trusted preactivation empty-source root binding uses an incarnation and null-path CAS; managed topology SQL remains guarded and skill bytes publish only through owner claim and bundle adoption.src/core/shared-skills/optimizer.ts 0 coordinator Shared optimization preserves the exact approved closure and original grants in private staging; only accepted body changes reach put_skill with the original revision and stable request UUID.-src/core/persistence/import-prepare.ts 1 coordinator The prepared local import updates source_path only inside canonical publication; owner, input and target hashes, source confinement and knowledge-versus-skill boundary revalidate before apply.+src/core/persistence/import-prepare.ts 2 coordinator The prepared local import updates source_path only inside canonical publication; owner, input and target hashes, source confinement and knowledge-versus-skill boundary revalidate before apply. Its importFromContent calls carry prepare and run inside the coordinator publication.src/core/persistence/grandfather.ts 2 coordinator Private migration intents preserve exact page/source/incarnation/revision identity and rollback snapshots; frontmatter/hash and existing text seals change only inside canonical file publication, without new embedding or fact-backstop effects.src/core/page-state/rename-alias.ts 8 engine_guard Rename aliases (slug_aliases) and moveSlugBindings (facts entity/fence slugs, page_aliases, withdrawal subjects) run inside the updateSlug transaction; the canonical table SQL trigger requires coordinator capability, so legacy calls fail before publication.src/core/timeline-extract.ts 1 engine_guard Retracting removed markdown timeline rows is canonical table SQL; the trigger requires coordinator capability, so legacy calls fail before canonical DB publication.src/core/persistence/connector-google-receipts.ts 1 coordinator Account and message-owned Gmail receipt metadata changes only under canonical source/page locks, identity/revision and file guards; guarded projection installation preserves withdrawal overlays without replaying bodies or extracting facts.+src/core/persistence/purge-deleted.ts 1 coordinator Unmanaged brains keep the engine bulk purge; a managed brain purges each expired tombstone through submitPageMutation delete_page purge bound to its revision.+src/core/persistence/unbound-source.ts 1 coordinator Stamps the durable unbound_source classification on a page inside the coordinator publication transaction that published it; the column is not a canonical content column.+src/core/cycle/synthesize-concepts.ts 2 coordinator A managed brain publishes concepts through publishMaintenancePage after maintenancePreflight; the unmanaged importFromContent path refuses on managed brains.+src/core/cycle/synthesize-verify.ts 2 early_refusal Legacy direct content import. Direct importFromContent calls without prepare refuse on managed brains before any write (assertUnmanagedCanonicalWriter).+src/core/persistence/reconcile-prepare.ts 3 coordinator Coordinated preparation module. Its importFromContent calls carry prepare and run inside the coordinator publication. The reconcile publication callback records the slug-derived source_path of a database-only page (the #5254 unbound collision) inside the admitted put_page transaction, after the pinned preimages and backup verify; it touches only the reconciled page and only while its source_path is still NULL. When the reconciled page gains a canonical origin, the same callback clears its #5254 unbound_source classification.+src/commands/brainstorm.ts 1 early_refusal Legacy direct content import. Direct importFromContent calls without prepare refuse on managed brains before any write (assertUnmanagedCanonicalWriter).+src/commands/eval-longmemeval.ts 1 early_refusal Legacy direct content import. Direct importFromContent calls without prepare refuse on managed brains before any write (assertUnmanagedCanonicalWriter).+src/commands/quarantine.ts 2 early_refusal Legacy direct content import. Direct importFromContent calls without prepare refuse on managed brains before any write (assertUnmanagedCanonicalWriter).+src/commands/reindex.ts 1 early_refusal Legacy direct content import. Direct importFromContent calls without prepare refuse on managed brains before any write (assertUnmanagedCanonicalWriter).+src/eval/brainbench/metrics/write-back.ts 1 isolated_eval Explicit isolated evaluation database only; never opened against the active managed brain.+src/eval/longmemeval/diagnostics.ts 1 isolated_eval Explicit isolated evaluation database only; never opened against the active managed brain.+src/core/persistence/effects.ts 1 coordinator The embedding effect clears only the page embedding signature, inside its claimed, source-guarded installation transaction, when #4616 refused a chunk, so embed --stale finds the page; no canonical content column changes.diff --git a/docs/architecture/key-files/canonical-reconciliation.md b/docs/architecture/key-files/canonical-reconciliation.mdindex 7ed6abd1d9..dce0963f6c 100644--- a/docs/architecture/key-files/canonical-reconciliation.md+++ b/docs/architecture/key-files/canonical-reconciliation.md@@ -2,8 +2,8 @@- `src/commands/sync-diagnostics.ts` + `src/core/persistence/{sync-run,verb-errors}.ts` — bounded source/slug/path/reason diagnostics derive from immutable managed-sync receipts, including when the local failure ledger is unavailable. Direct and resident-owner JSON carry the same receipt; human memory errors lead with the specific write reason without widening frozen v1 error codes. Pending requests retain their original UUID, terminal corrections require a new UUID, and neither retry nor line-ending diagnostics bypasses raw-byte or skip guards.-- `src/core/persistence/reconcile*.ts` — trusted-local exact-page reconciliation: loss-preserving semantic preview, explicit JSON Pointer choices, pinned identity/revision/raw-file/policy checks, durable private preimages and same-ID replay through the existing coordinator. Normal overwrite protection stays unchanged. The bounded audit reports source-scoped drift without repair or checkpoint changes. `src/commands/source-reconcile.ts` provides strict CLI parsing, private artifact I/O, brain routing and resident-owner delegation; the operations stay outside public MCP. Operator flow: `docs/guides/concurrent-writes.md`. Tests cover merge choices, both engines, grants, stale previews, read-only audit, and private files.+- `src/core/persistence/reconcile*.ts` — trusted-local exact-page reconciliation: loss-preserving semantic preview, explicit JSON Pointer choices, pinned identity/revision/raw-file/policy checks, durable private preimages and same-ID replay through the existing coordinator. Normal overwrite protection stays unchanged. The bounded audit reports source-scoped drift without repair or checkpoint changes. `src/commands/source-reconcile.ts` provides strict CLI parsing, private artifact I/O, brain routing and resident-owner delegation; the operations stay outside public MCP. Operator flow: `docs/guides/concurrent-writes.md`. Tests cover merge choices, both engines, grants, stale previews, read-only audit, and private files. A database-only page (no `source_path`, no `source_uri`; `isDatabaseOnlyPage` in `src/core/persistence/unbound-pages.ts`) is matched to the canonical file at its slug-derived path (`ReconcileState.origin: 'slug_derived'`), and apply records that path as its `source_path` (the #5254 unbound collision; `test/reconcile-unbound-collision.test.ts`).- `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. 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.+- `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. `admitCanonicalGrandfather` splits admission from `complete()` (wait, then settle the checkpoint exactly as the serial `grandfatherCanonicalPage` does); the migration admits a 50-page window before waiting, so the pages' Git effects coalesce (#5530). 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-1.md b/docs/architecture/key-files/commands-1.mdindex c38ae4adc3..a047c75db8 100644--- a/docs/architecture/key-files/commands-1.md+++ b/docs/architecture/key-files/commands-1.md@@ -15,6 +15,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/auth.ts` — token management. `gbrain auth create/list/revoke/test` for legacy bearer tokens (`create --scopes read,write` narrows a token via the `scopes TEXT[]` column with mint-time validation — a typo'd scope refuses loudly, never silently denies or widens; `list` shows id + scopes columns with grandfathered rows rendered honestly; `revoke --id <uuid>` revokes exactly one row since names are not unique, and bulk revoke-by-name says when it hit several; `permissions set-takes-holders` MERGES into the permissions JSONB via `COALESCE(permissions,'{}'::jsonb) || $2::jsonb` — a whole-object replace would silently wipe the `source_id` federation grant), plus `gbrain auth register-client` and `gbrain auth revoke-client <client_id>` for OAuth 2.1 client lifecycle. `revoke-client` runs an atomic `DELETE...RETURNING` on `oauth_clients`; FK `ON DELETE CASCADE` on `oauth_tokens.client_id` and `oauth_codes.client_id` purges every active token + auth code in one transaction; `process.exit(1)` on no-such-client (idempotent). Legacy tokens stored as SHA-256 hashes in `access_tokens`; OAuth clients in `oauth_clients`; legacy tokens with no scopes grant grandfather to `read+write+admin` on the OAuth HTTP server (no migration); scoped tokens are honored at exactly their grant. Every SQL site routes through `sqlQueryForEngine(engine)` from `src/core/sql-query.ts` (and `executeRawJsonb` for the takes-holders `permissions` JSONB column) so `gbrain auth` works against PGLite; the takes-holders write goes through `executeRawJsonb(engine, sql, [name, hash], [{takes_holders:[...]}])` which round-trips with `jsonb_typeof = 'object'`. `register-client` accepts `--source <id>` (write authority, scalar), `--federated-read <S1,S2,...>` (read scope, array), and `--token-ttl <seconds>` (per-client access-token TTL persisted to `oauth_clients.token_ttl`, bounds `TOKEN_TTL_MIN_SECONDS`=60 to `TOKEN_TTL_MAX_SECONDS`=7,776,000/90d) and prints the resolved `Write source` + `Federated reads`; clients without a `source_id` backfill to `'default'` via migration v60. The registration core is the exported `registerScopedClient(sql, engine, name, parsed, opts)` — exit-free, print-free, injected-handle (engine-bound callers like `agent register` pass the dispatcher's engine; a second `withConfiguredSql` engine self-deadlocks PGLite's single-writer lock), returns a `RegisteredClient` data object and throws on failure; the thin CLI wrapper owns exit/print. Its printer `formatRegisterClientOutput` is a BYTE-PINNED contract (connect.ts's `defaultRegisterOAuthClient` regex-scrapes `Client ID:`/`Client Secret:` from it in production) — pinned by `test/auth-register-client-output-pin.test.ts`. `preflightOauthClientColumns(sql)` probes `information_schema.columns` for the optional columns (`token_ttl`, `surface`, `federated_read`, `source_id`, `deleted_at`) so statement shapes are decided BEFORE any transaction — Postgres/PGLite abort the whole tx on any statement error (25P02) and SqlQuery has no savepoint seam, so "catch 42703 and continue" inside a tx is impossible; skipped optional writes surface as `RegisteredClient.skipped` with an apply-migrations hint. `gbrain auth clients [--usage] [--days N] [--json]` lists clients with scopes, per-client surface, write source (`source_id`), and federated reads (`federated_read`) — one projection-widened SELECT with a degrade ladder for pre-migration brains (drops the newest columns first, never errors); `--usage` joins per-client op-call counts via `src/core/mcp-usage.ts`. The bare `gbrain auth create <name>` form (no `--takes-holders`) mints a token via the exported pure `parseAuthCreateArgs(rest)`. Pinned by `test/auth-create-args.test.ts` + `test/auth-register-client-args.test.ts`.+- `src/commands/autopilot-pause.ts` — engine-free `gbrain autopilot pause [--reason <text>]` / `resume`: writes or removes the operator marker `autopilot-operator-paused` (`autopilotOperatorPauseMarkerPath` in `src/core/autopilot-paths.ts`, with `autopilotPaused()` and `autopilotPauseReason()`). The daemon loop and job workers honor it like the migration hold; `--install` (and so `gbrain upgrade`) clears only a leaked migration hold, and resume never clears a migration or restore hold. Test: `test/autopilot-operator-pause.test.ts`.- `src/commands/autopilot.ts` — `gbrain autopilot --install`: self-maintaining brain daemon (sync+extract+embed). Freshness sync jobs always send an explicit positive-polarity `pull` value derived from the source's parsed `remote_url`, so local-only sources skip pull and PGLite JSON-string configs behave like Postgres objects. Consumes `detectTini()` from `src/core/minions/spawn-helpers.ts`, resolved once at startup. Composes a `ChildWorkerSupervisor` instance for spawn-and-respawn with `--max-rss 2048` and soft `maxCrashes: 5`, preferring the current source/compiled CLI over PATH. The child worker performs private-queue recovery only after its driver/selected-child readiness and schema check; autopilot does not duplicate that recovery before spawn. A configuration-blocked child leaves the owning daemon alive and heartbeating but gates dispatch, worker restarts and engine work until explicit owner restart after repair. `--status --json` adds processing readiness, reason and runtime identities without replacing existing freshness/exit semantics; see [the owner-specific repair guide](../../guides/minions-fix.md). `onMaxCrashesExceeded` routes through autopilot's own `shutdown('max_crashes')` so the autopilot lockfile gets cleaned up. `shutdown()` drains via `childSupervisor.killChild('SIGTERM')` + `awaitChildExit(35_000)`. Pinned by `test/autopilot-fanout-wiring.test.ts` and `test/autopilot-supervisor-wiring.test.ts` (6 static-shape guards: composes ChildWorkerSupervisor not legacy names, `--max-rss 2048` in argv, `maxCrashes: 5` literal, shutdown-via-callback, no workerProc reference). tick body invokes `runNightlyQualityProbe` when `cfg.autopilot.nightly_quality_probe.enabled === true` (default OFF — opt-in to protect API spend). NO scheduler-side rate-limit check — `runNightlyQualityProbe`'s internal `shouldRunNightly` (reading the audit JSONL) is the single source of truth. Probe call wrapped in try/catch that logs via `logError` and does NOT bump `consecutiveErrors` (probe failure is informational, never crashes the loop). Default `max_usd` cap = 5. Pinned by `test/autopilot-nightly-probe-wiring.test.ts`. per-source `extract_atoms` auto-drain. Postgres-only block after the freshness fan-out: gated on `autopilot.auto_drain.enabled` (default true) AND `!packDeclaresPhase(engine,'extract_atoms')` (the silent-backlog condition) AND per-source `countExtractAtomsBacklog > threshold` (default 25) AND a daily cap `floor(max_usd_per_day / ~$0.30)`. Enumerates `loadAllSources`. Submits the PROTECTED `extract-atoms-drain` job (`{allowProtectedSubmit:true}`) with a UTC-day time-sloted idempotency key `autopilot-extract-atoms-drain:<src.id>:<utcDay>` (a static key would block the source after the first job completed). `src/core/minions/protected-names.ts` lists `extract-atoms-drain`; `src/commands/jobs.ts` registers the handler (thin wrapper over `runExtractAtomsDrainForSource`, `LockUnavailableError` → `{deferred:true}`; a `provider_failure` result throws `formatDrainProviderFailure(result)` — batches/remaining plus the drain's sanitized `last_error` — so the dead-lettered job's `error_text` names the cause, e.g. a missing provider key); `src/core/config.ts` carries the `autopilot.auto_drain.*` config keys + the `autopilot.` key prefix. Pinned by `test/extract-atoms-drain-handler.test.ts`, `test/autopilot-auto-drain-wiring.test.ts`. federated-brain co-existence + launchd hygiene. (1) `LOCK_PATH` resolves via `gbrainPath('autopilot.lock')` so it honors `GBRAIN_HOME` (two brains can run autopilot simultaneously without lock-stealing); lock file stores PID, startup checks `kill -0 <pid>` before refusing to start (a stale lock from a crashed process does not block). (2) exported `classifyReconnectError(err)` returns `'recoverable' | 'unrecoverable'`; unrecoverable causes `process.exit(0)` so launchd backs off instead of looping `config.database_url undefined`. (3) exported pure `generateLaunchdPlist(wrapperPath, home)` sets `ThrottleInterval=300` so launchd respects the exit-0 backoff. Pinned by `test/autopilot-lock-path.test.ts` + `test/autopilot-reconnect-classifier.test.ts`. targeted-submit loop instead of blanket `autopilot-cycle` dispatch. Each tick: cheap `engine.getHealth()` (single SQL count) + `computeRecommendations()`, then route by shape — `score >= 95 AND no plan AND <60min since last full` → sleep; `score >= 95 AND >=60min` → submit `autopilot-cycle` (60-min floor exercises phase-coupling invariants on healthy brains); `plan <= 3 steps AND est <5min` → submit individual handlers; `plan large OR score < 70` → submit full `autopilot-cycle`. The `gbrain-cycle` lock ensures targeted submissions and the full cycle can't run concurrently. `maxWaiting: 1` per submit closes the queue-fan-out vector. daemon env lane: `writeWrapperScript` additively sources `<gbrainDir>/env` (honors `GBRAIN_HOME`) after the shell profiles with a `set -a` wrap so dotenv-style `KEY=value` lines export too, and creates a fully-commented 0600 template on install (never overwritten, never chmod'd, never removed by uninstall; template excludes `GBRAIN_HOME` — the wrapper bakes it AFTER sourcing). Exported pure `chatBootWarning(chatAvailable, gbrainDir)` derives both remediation paths from the passed dir and prints via `console.log` at daemon boot (stdout is the autopilot.log sink on all four targets; stderr lands in the unsurfaced autopilot.err) using the bare global-model `isAvailable('chat')` probe on purpose (mirrors the bare-gated phases; facts extraction is model-aware and doctor owns it). Install is reload-safe so the warning's re-run-`--install` remediation is true: launchd unloads before load (bare load errors on a loaded agent), systemd `try-restart`s after `enable --now`, cron/container print a residual-process notice instead of auto-killing. Pinned by `test/autopilot-install.test.ts` (16 cases incl. real-bash wrapper execution). Once processing is configuration-blocked, `guardAutopilotEngine` refuses new engine calls (except disconnect), guards transaction callback engines, and rolls back a transaction whose callback finishes after the block; already committed work is not revoked. Pinned by `test/autopilot-transaction-fence.test.ts`.- `src/commands/backup.ts` — trusted local `gbrain backup status|check`: status may reuse a recent warning; check forces a bounded remote readback sweep. Enabled missing/locked/degraded evidence does not return an all-clear. Quiet and disabled modes retain explicit zero-exit behavior. JSON separates configured repos from fresh verified recoverable repos and describes committed-file-only recovery. Remote MCP doctor never invokes this local Git path; see `docs/operations/backup-check.md` and `test/backup-cli.serial.test.ts`.diff --git a/docs/architecture/key-files/commands-2.md b/docs/architecture/key-files/commands-2.mdindex 403a3dfceb..0be9ef21df 100644--- a/docs/architecture/key-files/commands-2.md+++ b/docs/architecture/key-files/commands-2.md@@ -6,6 +6,15 @@ 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/unbound-source.ts` — `unbound_source` (#5254) counts live pages with `pages.database_only_reason='unbound_source'` per source. While the source is unbound the count is ok and the message carries the filled `sources writer status`/`writer claim` bind command (database-only is the chosen mode); once the source has a binding it warns, because binding never materializes those pages into canonical files. Unreadable state warns. Registered on the `persistence_capacity` line in `doctor.ts`. Test: `test/e2e/unbound-source-postgres.test.ts`.++- `src/commands/doctor/wave-checks.ts` — `WAVE_CHECKS`, the table of managed-persistence wave checks (stable id, `resolution` `repair`/`operator`/`unsupported`, count-free remote `impact`, operator `instruction`, `count` for banners, `registration` inline-in-doctor.ts or from this table). `runWaveChecks` turns a throwing check into an `unknown` finding; `checkHealthUnknown` reads `details.health === 'unknown'`. `remoteWaveHandoff` returns one line per remotely offered check with `details.host_action` {`check_id`, `state` ok/action_required/unknown, `preview_command`} and no paths, rows, SQL, emails or installation ids. Consumers: doctor.ts, `report-remote.ts`, `remediate.ts`, `upgrade-banner.ts`. Tests: `test/recovery-layer.test.ts`, `test/e2e/recovery-layer.test.ts`.++- `src/commands/doctor/remediate.ts` — the `--remediation-plan` / `--remediate` CLI shell (re-exported from doctor.ts): per-step `command` (`gbrain jobs submit …` for job steps, `gbrain repair <kind> --apply` for repair steps), `combinedRemediateCommand`, `REMEDIATE_HELP`, `--include-repairs`/`--no-embed`/`--resume` handling, the resume command after budget exhaustion (repeats the recorded cap and consent), `classifyWaveFindings` (cleared / pending / consent_required / operator_required / unsupported, from wave checks run before and after) and `remediationExitStatus` (0 when no repairable finding remains and no step failed; 1 otherwise or on budget exhaustion; 2 when the target is unreachable with no repair step, or a resume is refused), set through `setCliExitVerdict`.++- `src/commands/doctor/upgrade-banner.ts` — `postUpgradeRecoveryBanner`: runs the wave checks once and returns one `[AGENT] Relay this to your operator` block (brain, per-finding count and resolution, the read-only `gbrain doctor --remediation-plan`, ask before applying), never an applying command; empty for a clean brain. `POST_UPGRADE_NOTES` lets other subsystems add lines. Test: `test/post-upgrade-banner.test.ts`.++- `src/commands/doctor/checks/{safe-index,self-capture,stale-embedding-effects}.ts` — `safe_index_pending` (BRAIN: re-sealable pages below the safe-chunk fence, names `gbrain repair safe-chunks`; kept code/image pages are informational), `self_capture` (BRAIN, #5413: corpus `.txt` files whose session id matches a gbrain claude-cli scratch transcript are classified, ones with no harness transcript left are unclassifiable; details carry a capped sample and copy-paste quarantine commands into `<corpus>.quarantine`; never moves or deletes), `stale_embedding_effects` (OPS, #5629: committed writes with a queued embedding effect untouched for an hour; names each effect with its inspect command; reported as unsupported). Unreadable state is warn with `details.health: 'unknown'`. `writer_version` (`checks/writer-version.ts`, owned by the persistence entry) is registered in the same table as operator-required. Tests: `test/doctor-self-capture.test.ts`, `test/recovery-layer.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`.diff --git a/docs/architecture/key-files/commands-3.md b/docs/architecture/key-files/commands-3.mdindex e3649db915..5a51c91e6e 100644--- a/docs/architecture/key-files/commands-3.md+++ b/docs/architecture/key-files/commands-3.md@@ -29,7 +29,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/export.ts` + `src/core/export-snapshot.ts` + `src/core/export-stage.ts` + `src/core/export-publish.ts` — local Markdown export collects source/page/canonical-withdrawal/tag/raw state in one export-scoped repeatable-read read-only transaction, using 256-key ID batches and private disk-backed SQLite staging. Primary-key page reads reuse the canonical withdrawal overlay without source-wide slug scans under stale planner statistics. Each 256-key batch groups by source and retains only one capacity-checked withdrawal ledger at a time; bodies with no literal `gbrain:facts:` marker skip normalization, while malformed/orphan markers still use canonical SQL fingerprinting. No engine defaults or shared migration iterators change. Explicit source selection is validated; restore-only selects one source and checks its recorded file path through the existing native path resolver. The manifest rejects unsafe paths, same/cross-source aliases, case/Unicode and file-prefix collisions before destination output, preserving the `<slug>.md` and `.raw/<name>.json` layout. Existing planned paths refuse rather than overwrite. The portable first-party native addon anchors no-follow directories and publishes leaves with atomic no-replace operations, retaining an exclusive persistent `.gbrain-export-status` marker; success requires flushed data and a final COMPLETE line. Unsupported native capabilities fail closed without a pathname fallback. A fresh destination is the retry path; unrelated files are never pruned. Fixed capacity/time limits fail visibly, never truncate. This is a historical snapshot, not a database backup or a sandbox against another same-user process renaming directories. See [safe export](../../storage-tiering.md#safe-export). Engine-free `export --help` documents scope, no-overwrite publication and incomplete-output recovery. Pinned by both-engine export safety/independent-roundtrip/snapshot/failure-release suites, the 100001-page scale fixture with staging bytes and full export SQL statement accounting, the native publication/compiled-wrapper suite, actual CLI help tests, and the PostgreSQL export E2E wrapper.-- `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-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`. On a managed brain the core runs `managedDerivedFactsPreflight` (local writer, active source) before any provider work, and every fact, orphan-cleanup and audit write commits through `writeDerivedFacts` inside the coordinator's source capability under the page key; the CLI no longer refuses up front and receipt pages are skipped. Tests: `test/managed-facts-writers.test.ts`, `test/managed-unsupported-preflight.serial.test.ts` (refusal before spend for an unaccepted writer).- `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 walk replaces each page's own markdown-derived links through `replacePageFileLinks` (the per-slug contract below; a file with no page row is skipped and not stamped); the db link walk and `extract --stale` replace through `replaceDerivedLinks`. Timeline rows are inserted in batches of 100 via `addTimelineEntriesBatch` (`ON CONFLICT DO NOTHING`; `created` counts real inserts) after every path — fs walk, db walk, per-slug, sync hooks, `--stale` — runs `retractRemovedTimelineEntries` for the page. `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 non-event rows whose (date, source, summary) any stored `page_versions` text of the page produced (under either timeline parser) and its current text no longer does; rows no version produced (enrichment, meeting fan-out, `--infer-dates` anchors) are kept, and the version scan only runs when the page holds a row the current text does not produce. `gbrain extract timeline --prune-orphans [--source-id] [--dry-run] [--json]` (`pruneTimelineOrphans`) runs that reconciliation over every page with timeline rows, without inserting — the one-time prune for rows orphaned while extraction was insert-only (managed brains retract each page's rows in a page-locked `withCoordinatedWrite` transaction; these rows are removals, so `gbrain repair timeline` / `timeline_history` exclude them; pinned in `test/persistence-managed-lifecycle.test.ts`); the read-only `timeline_orphans` doctor check (`src/commands/doctor/checks/timeline-orphans.ts`) samples 500 pages and points at it. Pinned by `test/timeline-reconcile-all-paths.test.ts`. `loadSlugAliasTargets` adds renamed pages' old slugs (`slug_aliases`) to `allSlugs` so links written before a rename resolve to the current slug. `extractLinksForSlugs` reads the requested files first, then loads page metadata only for those pages and their link endpoints (`fileLinkOwnership(engine, sourceId, { slugs })`); the unscoped whole-brain load happens only when a DB meeting or attendance origin needs `replaceFileLinks`. Both return `ExtractForSlugsResult { created, processed, errors? }`; `errors` names pages whose read or write failed, and sync reports them as `extract_error` (stderr line plus the `SyncResult` field) instead of swallowing them. `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`; on a managed brain it hands the sweep to `extractManagedStaleLinks` in `src/core/persistence/links-maintenance.ts` for every caller, CLI, cycle, jobs and maintain, and a live PGLite owner runs it through `src/commands/extract-stale-delegate.ts`) — 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 (`prepareAutomaticLinks`), the coordinator's unrecorded canonical timeline tuples (`unrecordedCanonicalTimeline`, 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`, `test/persistence-managed-lifecycle.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`.diff --git a/docs/architecture/key-files/commands-4.md b/docs/architecture/key-files/commands-4.mdindex 2ef335e105..38c3187baf 100644--- a/docs/architecture/key-files/commands-4.md+++ b/docs/architecture/key-files/commands-4.md@@ -19,7 +19,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/lint.ts` — Page quality linter (catches LLM artifacts, placeholder dates). `runLintCore(opts)` walks the tree ONCE; `--fix` applies fixes during that same scan and reports per-page results through the `onPageIssues(relPath, issues, fixedCount)` callback (issues = what remains after this run's fix attempt for the page; `fixedCount` = fixes actually applied), so the summary's auto-fixed count is the true count — a second scan run after fixing would see already-fixed files and report zero. `onScanStart` fires once with the collected page count for progress wiring. Pinned by `test/lint-fix-single-pass.test.ts`. On a durability-hardened brain (`isDurabilityHardened` on the target dir, or the page's directory for a single-file target) every non-dry-run `--fix` repair is committed path-limited via `commitWriteThroughFile` right after the `writeFileSync` — the same contract as put_page write-through, so the cycle, the `lint`/`lint-fix` minion handlers and the CLI never leave hardened repairs as uncommitted drift for the sync phase to flag (pinned by `test/cycle-lint-durability.test.ts`). Lint rules `huge-page` (flags pages exceeding `content_sanity.bytes_warn`) and `scraper-junk` (flags pages matching any junk pattern). Both reuse `assessContent()` from `src/core/content-sanity.ts` so lint, doctor, and ingest share one assessor. `lint.ts` lifts DB config when `~/.gbrain/` is reachable; falls back to file/env on CI. Pinned by `test/lint-content-sanity.test.ts`. with `src/commands/sources.ts`: `gbrain lint` has a `markup-heavy` rule (flags pages whose prose-vs-markup ratio exceeds `content_sanity.max_markup_ratio`, reusing `assessContentSanity` so lint/gate/scan share one assessor); pinned by `test/lint-content-sanity.test.ts`. `gbrain sources audit <id>` is disposition-aware: its dry-run disk scan reports would-quarantine / would-reject / would-flag counts driven by the effective `content_sanity.junk_disposition` + markup config, so an operator previews the gate's verdict before sync. The `content-sanity-audit` JSONL (`src/core/audit/content-sanity-audit.ts`) records the quarantine/flag dispositions.-- `src/commands/migrate-embeddings.ts` — `gbrain migrate embeddings --to <provider:model> [--dim N] [--dry-run] [--yes] [--json] [--no-embed] [--status] [--reranker auto|off|keep|<model>] [--retarget] [--batch-size N] [--pace[=mode]] [--ignore-env-override]` (alias: `gbrain retrieval-upgrade`). ONE shared orchestrator for CLI and the `migrate_embeddings` op: `planMigrationFlow` (plan + `verifyMigrationComplete` + env presence + un-merged file plane + brain/DB identity via `redactPgUrl` + concurrent-writer census + reranker plan + in-flight-other marker) and `executeMigrationFlow` (global `gbrain-embedding-migration` DbLock → retarget gate under it → all-source embed locks sorted with `includeArchived` → live embed probe → apply → reranker probe + switch → drain via `runEmbedCore({heldLocks, …})` so the migration never lock_skips itself, with a 5-min heartbeat whose refresh-false/3-errors ABORTS as `lock_lost` → reconcile → completion smoke check stamped into the marker → transactional complete; locks released in finally). The skip path exits 0 ONLY on `verify.complete` with no pending retarget decision and no pending reranker action (a resolved switch/disable runs as a config-only completion). `--status` is read-only/spend-free and never refuses on env (it REPORTS planes, key PRESENCE booleans only, censuses, markers verbatim incl. corrupt, the exact resume command, and the last completion + smoke-check outcome). `persistEmbeddingFileConfig` writes through `loadConfigFileOnly` (never persists env-sourced keys) and supports env-canonical no-file deployments (env pins target ⇒ proceed with notice). Exit codes: 0 completed/verified-no-work, 1 locked/refused/failed/incomplete (message names which; lock_skipped and lock_lost get their own copy), 2 non-TTY without `--yes`. Pinned by `test/migrate-embeddings-flow.serial.test.ts`, `test/migrate-embeddings-boundary.serial.test.ts`, `test/migrate-embeddings-hardening.serial.test.ts`. Migration guidance uses `renderCanonicalMigrationCommands` (`src/core/ai/defaults.ts`) to keep supported targets and dimensions consistent.+- `src/commands/migrate-embeddings.ts` — `gbrain migrate embeddings --to <provider:model> [--dim N] [--dry-run] [--yes] [--json] [--no-embed] [--status] [--reranker auto|off|keep|<model>] [--retarget] [--batch-size N] [--pace[=mode]] [--ignore-env-override]` (alias: `gbrain retrieval-upgrade`). ONE shared orchestrator for CLI and the `migrate_embeddings` op: `planMigrationFlow` (plan + `verifyMigrationComplete` + env presence + un-merged file plane + brain/DB identity via `redactPgUrl` + concurrent-writer census + reranker plan + in-flight-other marker) and `executeMigrationFlow` (global `gbrain-embedding-migration` DbLock → retarget gate under it → all-source embed locks sorted with `includeArchived` → worst-case authorization under the locks (a cap below it returns `refused_budget` / op `refused` with `embedding_budget_below_worst_case` before any provider call or invalidation) → live embed probe → apply → reranker probe + switch → drain via `runEmbedCore({heldLocks, …})` so the migration never lock_skips itself, with a 5-min heartbeat whose refresh-false/3-errors ABORTS as `lock_lost` → reconcile → completion smoke check stamped into the marker → transactional complete; locks released in finally). The skip path exits 0 ONLY on `verify.complete` with no pending retarget decision and no pending reranker action (a resolved switch/disable runs as a config-only completion). `--status` is read-only/spend-free and never refuses on env (it REPORTS planes, key PRESENCE booleans only, censuses, markers verbatim incl. corrupt, the exact resume command, and the last completion + smoke-check outcome). `persistEmbeddingFileConfig` writes through `loadConfigFileOnly` (never persists env-sourced keys) and supports env-canonical no-file deployments (env pins target ⇒ proceed with notice). Exit codes: 0 completed/verified-no-work, 1 locked/refused/failed/incomplete (message names which; lock_skipped and lock_lost get their own copy), 2 non-TTY without `--yes`. Pinned by `test/migrate-embeddings-flow.serial.test.ts`, `test/migrate-embeddings-boundary.serial.test.ts`, `test/migrate-embeddings-hardening.serial.test.ts`. Migration guidance uses `renderCanonicalMigrationCommands` (`src/core/ai/defaults.ts`) to keep supported targets and dimensions consistent.- `src/commands/migrate-engine.ts` — Bidirectional engine migration (`gbrain migrate --to supabase/pglite`). Copies the complete source catalog FIRST (`copyMigrationSources` — every `sources` row incl. archived rows and sync/routing metadata, `ON CONFLICT (id) DO UPDATE`, `default` ordered first) so every page write has a valid `pages.source_id` FK parent and the target preserves per-source behavior; pages copy afterward, tracked in the resume manifest by composite `(source_id, slug)` key. Link copy preserves each row's `to_source_id` (falling back to the origin source only for legacy rows without it), and failed-target filtering uses that same target composite key, so cross-source links migrate without being rebound to the origin source. The resume manifest is target-aware: `migrationTargetId(config)` hashes `(engine, locator)` (`database_url` for Postgres, resolved `database_path` for PGLite) and `manifestMatchesTarget` requires `schema_version === 2` plus a matching `target_id` — a legacy engine-only manifest, or one from a DIFFERENT target of the same engine kind, starts fresh instead of skipping "completed" pages the new target never received. After links, `copyMigrationFacts` carries the facts table verbatim (conversation facts have no markdown fence to re-sync from): source∩target column intersection via information_schema (older source schemas still copy), delete-and-recopy so every re-run converges to source truth, two-pass `superseded_by` restore (the self-FK points old→newer id, so id-ordered single-pass inserts would violate it), embeddings round-tripped as text into whichever physical type (`vector`/`halfvec`) the target column has with a NULL-embedding retry on per-row cast failure, and a `setval` bump so post-migration inserts don't collide with copied ids; fact-row failures block the config flip and force a non-zero exit, same contract as page failures. Takes are deliberately NOT copied (fence-canonical, keyed on target-reassigned `page_id`; the next extract cycle rebuilds them). `copyMigrationConfig` then copies EVERY DB-plane config row except the explicit engine-local denylist `MIGRATE_CONFIG_ENGINE_LOCAL_KEYS` (`engine`, `version` = target-owned schema ledger, `embedding_columns` + `search_embedding_column` = physical-column registry the copy doesn't materialize); skipped keys print in the end-of-run per-table copied-count summary, so nothing is dropped silently. Pinned by `test/migrate-engine-resume.test.ts` (manifest identity) + `test/e2e/migrate-engine-sources-postgres.test.ts` (source catalog lands before overlapping-slug pages, PGLite → real Postgres) + `test/e2e/multi-source-bug-class.test.ts` (cross-source links) + `test/migrate-engine-completeness.serial.test.ts` (facts chains/embeddings/sequence, config copy-all + denylist, summary). Legacy engine copies explicitly include stored unverified chunks and queue sanitized text rebuilding under the target revision; retrieval stays gated until rebuilt. Both source and target refuse any durable request history, withdrawal ledger, or ownership record before copying/clearing because this copier cannot preserve those identities.@@ -57,6 +57,8 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/reindex-multimodal.ts` — `gbrain reindex --multimodal [--limit N] [--dry-run] [--cost-estimate] [--no-embed] [--yes] [--json]`. Walks `content_chunks WHERE embedding_multimodal IS NULL`, batches via `embedMultimodalSafe` (partial-failure-aware), persists. Lock via `tryAcquireDbLock` (360min) so a concurrent autopilot embed phase can't race it. Cost prompt + Ctrl-C grace window in TTY. `GBRAIN_NO_REEMBED=1` bypass. Checkpoint at `~/.gbrain/reindex-multimodal-checkpoint.json` for resume. Auto-flip prompt at coverage=100% completion (TTY: interactive; non-TTY: stderr hint with a paste-ready command).+- `src/commands/reindex-vectors.ts` — `gbrain reindex --vectors [--dry-run] [--json]` (dispatched from cli.ts beside `--aliases`). Lists every HNSW index in the current schema from `pg_indexes` and runs `REINDEX INDEX` on each (`REINDEX INDEX CONCURRENTLY` on Postgres), rebuilding the ANN index from stored vectors with no re-embedding. The PGLite WAL-repair notice (`buildWalRepairNotice`) and `gbrain pglite-repair` name it, because a WAL reset does not rebuild indexes (#4616). Tests: `test/embedding-zero-norm-4616.serial.test.ts` on both engines.+- `src/commands/reindex-search-vector.ts` — `gbrain reindex-search-vector [--dry-run] [--yes] [--json]`. Escape hatch for changing `GBRAIN_FTS_LANGUAGE` after the `configurable_fts_language` migration has run (the migration shows applied and is skipped): recreates `update_page_search_vector` + `update_chunk_search_vector` with the configured language — bodies mirror the migration's and KEEP the `SET search_path = pg_catalog, public` hardening (CREATE OR REPLACE resets proconfig) — then backfills `pages` (UPDATE-to-self re-fires the trigger) and `content_chunks` (direct vector recompute) in id-keyset batches of `BACKFILL_BATCH_SIZE` (5000) via `UPDATE … WHERE id IN (SELECT … LIMIT n) RETURNING id`, streaming phases `reindex_search_vector.pages`/`.chunks` through the shared progress reporter (stderr). Confirmation gate: `--yes`, or an interactive TTY [y/N]; `--json` does NOT bypass the gate (non-TTY without `--yes` refuses with a ConfirmationRequired envelope, exit 2). Interrupted-run safety: stamps `fts.reindex_in_progress` (= target language, key exported as `FTS_REINDEX_MARKER_KEY` from `fts-language.ts`) in the config table BEFORE the autocommitted DDL and clears it only after both backfills return; each batch persists its keyset cursor under `backfill.fts_pages.last_id` / `backfill.fts_content_chunks.last_id` (the `checkpointKey` convention from `backfill-base.ts`), so a re-run with the same language resumes from the checkpoint and a different language resets it. Deliberately not one `engine.transaction()` (whole-run row locks on Postgres, zero banked progress on a hang). Idempotent. Pinned by `test/reindex-search-vector.serial.test.ts`.- `src/commands/init-mode-picker.ts` — install-time mode recommendation, downstream-input cost matrix, and mandatory operator choice. Mode summaries describe payload knobs only. Expansion follows the command (`query` on unless opted out; `search` and memory verbs off), not the chosen mode; provider charges and downstream prompt caching are disclosed separately from GBrain result caching.diff --git a/docs/architecture/key-files/commands-5.md b/docs/architecture/key-files/commands-5.mdindex 5647e4ad3c..1e394fb2f2 100644--- a/docs/architecture/key-files/commands-5.md+++ b/docs/architecture/key-files/commands-5.md@@ -3,8 +3,8 @@[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.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) `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`), `contextual-mode` (#5621 projection-only stamp of the import-time contextual retrieval mode on pages that have none; honors `--no-embed`) and `connector-checkpoints` (#5686 brain-wide cleanup of connector checkpoint rows no source can load); no kind previews every kind. Dry run unless `--apply` (no prompt; `--yes` refused). `parseRepairArgs` is strict: any unknown option or a second positional refuses `invalid_params` before anything runs, and `--max-usd`/`--max-cost` name the capped route `gbrain doctor --remediate --yes --include-repairs --max-usd <n>`. Help lines come from `REPAIR_REGISTRY`; `--json` adds `paid` per kind and `paid_kinds`. 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; `--no-embed` still stamps the mode of every page it re-chunks) 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 5ddc094362..6566ec5a3a 100644--- a/docs/architecture/key-files/core-ai.md+++ b/docs/architecture/key-files/core-ai.md@@ -11,6 +11,9 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/ai/dims.ts` — per-provider `providerOptions` resolver for embed-time dimension passthrough; the single source of truth for "which provider needs which knob to produce `vector(N)`". Exports `dimsProviderOptions(implementation, modelId, dims)` (called by `embed()` in `gateway.ts`), `VOYAGE_OUTPUT_DIMENSION_MODELS` (private const — the 7 hosted Voyage models that accept `output_dimension`: `voyage-4-large`, `voyage-4`, `voyage-4-lite`, `voyage-3-large`, `voyage-3.5`, `voyage-3.5-lite`, `voyage-code-3` — nano deliberately excluded), `VOYAGE_VALID_OUTPUT_DIMS = [256, 512, 1024, 2048] as const`, `supportsVoyageOutputDimension(modelId)`, `isValidVoyageOutputDim(dims)`. Voyage path uses the SDK-supported `dimensions` field (`{ openaiCompatible: { dimensions: N } }`), NOT Voyage's `output_dimension` wire-key — the `voyageCompatFetch` shim in `gateway.ts:541` translates `dimensions → output_dimension` before the HTTP body is built (the AI SDK's openai-compatible adapter doesn't recognize the wire-key, so sending it from here would be silently dropped and Voyage would return its default 1024-dim). Runtime guard: when a Voyage flexible-dim model is configured with `dims` outside `VOYAGE_VALID_OUTPUT_DIMS`, throws `AIConfigError` with a paste-ready `gbrain config set embedding_dimensions <256|512|1024|2048>` hint at the embed boundary (most common trigger: `embedding_model: voyage:voyage-4-large` without `embedding_dimensions`, retaining an incompatible 1536-dimensional setting from another provider). Every lookup in this module folds through the private `modelMatchKey` (trim + lowercase) so cased hub-form ids (`Qwen/Qwen3-Embedding-4B`) match the all-lowercase tables — the folded key is a MATCH key only, never sent to a provider (wire model ids are case-sensitive; error messages keep the original id so they stay paste-ready); the Qwen3-Embedding native-width table lives at module scope alongside the other dim tables. Consequence, deliberate: a cased Voyage/Perplexity config matches and fails loudly at init when its `dims` is invalid, rather than skipping validation and silently producing wrong-width vectors.+- `src/core/ai/embed-batch-plan.ts` — the embedding request plan shared by `embed()` and spend preflights: per-input truncation (`EMBED_MAX_CHARS`), the `max_batch_tokens` × safety-factor pre-split (`splitByTokenBudget`, re-exported by the gateway), the item cap (`capBatchItems`, `NO_BATCH_CAP_SUB_BATCH_ITEMS` for `no_batch_cap` recipes) and the per-request input ceiling a guard reserves (`embedRequestMaxInputTokens`: one token per UTF-8 byte, capped per text by a declared `max_input_tokens`, additive so any split or retry of the same texts stays inside it). `embedRequestCeilings(texts, model)` replays the plan for a model string without a gateway; `rerankRequestMaxInputTokens` is the rerank twin. Pinned by `test/embedding-migration-settle.serial.test.ts` and the adaptive-batch suites.+- `src/core/ai/embedding-guard.ts` — the embedding refusal contract (#4616). `degenerateEmbeddingReason` flags zero-norm (L2 norm below `EMBEDDING_NORM_EPSILON`), NaN and ±Inf vectors; `sendableEmbeddingInputs` keeps empty and whitespace-only inputs away from the provider; `screenEmbeddings` / `screenAlignedEmbeddings` put vectors back at their input positions and throw `EmbeddingZeroNormError` (an `AIConfigError`, `code: embedding_zero_norm`, docs `docs/guides/write-refusals.md#embedding_zero_norm`) carrying per-item `failures` and the usable `vectors` aligned with the input (null where refused). `mergeZeroNormErrors` re-aligns per-slice refusals. `suggestionFor(slug, sourceId?)` fills the `gbrain embed <slug>` recovery command. Consumers: `gateway.embed()` and both multimodal embedders, `embedding.ts:embedBatch` (later 100-input slices still run), `embed-retry.ts` (never retried; `embedBatchKeepingUsable` returns the partial result), `embed.ts:embedPageTexts` and markdown/code imports (usable vectors stored, refused chunks stay NULL and the page signature is not stamped). Tests: `test/embedding-zero-norm-4616.serial.test.ts` (+ Postgres wrapper).+- `src/core/ai/gateway.ts` — unified seam for every AI call. `embedQuery(text, opts?)` and `isAvailable(touchpoint, modelOverride?)` accept a model override so the resolved-column path embeds via the column's provider (Voyage / OpenAI) instead of the global default; the hybrid path passes `{embeddingModel: resolved.provider, dimensions: resolved.dimensions}` and the gateway resolves the matching recipe via `instantiateEmbedding()`. `isAvailable('embedding', 'voyage:voyage-3-large')` checks the override's recipe (not the default) so hybrid skips vector search only when the active column's provider is actually down. `voyageCompatFetch` adapts Voyage embedding requests and responses; `openAICompatAsymmetricFetch` threads explicit query/document input types for other compatible recipes through the SDK boundary. `gateway.rerank()` native HTTP path (no AI-SDK reranking abstraction): resolves the EFFECTIVE reranker as `input.model ?? getRerankerModel() ?? DEFAULT_RERANKER_MODEL` (imported from `ai/defaults.ts`; `voyage:rerank-2.5`), posts to the recipe's reranker path (`touchpoints.reranker.path`, default `/rerank`; supported recipes declare their path explicitly) with bearer auth — the request's top-N key is recipe-pluggable via `touchpoints.reranker.top_param` (default `top_n`; Voyage `top_k`) — and returns `RerankResult[]` sorted by relevance. `no_key` preflight: after `requireConfig()`, a recipe without a custom `resolveAuth` whose `auth_env.required` key is absent from `cfg.env` throws `RerankError('no_key')` BEFORE any HTTP — `noKeyOnce()` writes ONE `no_key` audit row per process per model without a stderr line, avoiding per-query noise. `auth` therefore means "key present but rejected" (HTTP 401/403). `RerankError.reason` classifier: `auth | no_key | rate_limit | network | timeout | payload_too_large | unknown`. 5s default timeout (search hot path). Pre-flight payload guard rejects bodies over `recipe.touchpoints.reranker.max_payload_bytes` with `reason: 'payload_too_large'`. `_rerankTransport` test seam mirrors `_embedTransport`. `embedQuery(text)` threads `inputType: 'query'` through `dimsProviderOptions()` (4-arg). `getRerankerModel()` returns only the EXPLICITLY configured model (callers need not pre-check availability — `rerank()` fails `no_key` itself; the sync readiness predicate for dashboards is `reranker-readiness.ts`) + `isAvailable('reranker')` branch; `configureGateway` + `reconfigureGatewayWithEngine` thread `reranker_model`; `applyResolveAuth` + `defaultResolveAuth` widen touchpoint param to include `'reranker'`. `embedMultimodalOpenAICompat()` routes recipes with `implementation: 'openai-compatible'` (LiteLLM, Anyscale, vLLM, Gemini multimodal via proxy) through the standard `/embeddings` endpoint with content arrays carrying `image_url` entries; the Voyage `/multimodalembeddings` path is unchanged (gateway selects by recipe `implementation` tag). Runtime dimension validation throws `AIConfigError` (with model id + observed + expected) before the vector reaches storage when the provider returns a width that doesn't match the recipe's `default_dims` or the brain's `embedding_dimensions`. Pinned by `test/openai-compat-multimodal.test.ts`. Module-scoped `_embedTransport` defaults to AI SDK `embedMany`, with `__setEmbedTransportForTests(fn)` test seam so tests drive `embed()` with a stubbed transport. `splitByTokenBudget` and `isTokenLimitError` exported `@internal` (pure functions reused by the test file). Module-level `_shrinkState: Map<recipeId, {factor, consecutiveSuccesses}>` halves the recipe's effective `safety_factor` on token-limit miss (floor 0.05) and heals back ×1.5 after `SHRINK_HEAL_AFTER=10` consecutive successes. `configureGateway()` walks every registered recipe at construction and emits a once-per-process stderr warning for any embedding touchpoint missing `max_batch_tokens` (excluding the canonical OpenAI fast-path). `resetGateway()` clears `_shrinkState`, the warned-set, and restores the real transport. `embedMultimodal()` reads `cfg.embedding_multimodal_model` first (falls back to `cfg.embedding_model`); after the recipe-level `supports_multimodal` fast-fail, validates the resolved model against `touchpoint.multimodal_models` when declared (closes the Voyage-text-only-into-multimodal-endpoint footgun before any HTTP call). `getMultimodalModel()` accessor mirrors `getEmbeddingModel` / `getChatModel`. Exported `VoyageResponseTooLargeError` tagged class: `voyageCompatFetch`'s two OOM-defense caps (Layer 1 Content-Length, Layer 2 per-embedding base64) throw it; the inbound response-rewriter's try/catch (which swallows parse failures so misshaped responses fall through to the SDK parser) checks `instanceof VoyageResponseTooLargeError` and rethrows so the cap is actually effective (`test/ai/gateway.test.ts` drives both layers through `embed()`). AI SDK v6 toolLoop compat (`gbrain skillopt` rollouts AND production background `subagent` jobs both route through `chat()` / `toolLoop`): in `chat()`, tool defs wrap the raw JSON Schema with the SDK's `jsonSchema()` helper (`inputSchema: jsonSchema(t.inputSchema)`) — v6's `asSchema()` treats a bare `{jsonSchema: ...}` object as a thunk and throws "schema is not a function"; exported pure `toModelMessages(messages: ChatMessage[]): unknown[]` converts gbrain's provider-neutral `ChatMessage[]` into v6 `ModelMessage[]` — tool results (pushed by `toolLoop` as `role:'user'` with bare-value tool-result blocks) become a dedicated `role:'tool'` message with structured `output:{type:'json'|'text'|'error-text', value}` parts; `null` output preserved as `{type:'json', value:null}` (not dropped); text/tool-call blocks pass through with v6 field names (`toolCallId`/`toolName`/`input`); applied at the `generateText` call (`messages: toModelMessages(opts.messages)`). The converter is load-bearing for the production subagent path, not just skillopt. Pinned by `test/gateway-model-messages.test.ts`. Companion: `src/core/skillopt/rollout.ts` builds tool schemas through the shared `paramDefToSchema` from `src/mcp/tool-defs.ts` (single source of truth, recursive on items/enum/default), never an inline converter. Provider-agnostic plumbing: `resolveNativeBaseUrl(provider, cfg)` normalizes a configured `ANTHROPIC_BASE_URL` / `OPENAI_BASE_URL` to carry the `/v1` suffix and is passed explicitly at every native `createAnthropic` / `createOpenAI` site (chat/expansion/embedding), so an env-injected bare host doesn't 404; returns `undefined` when unset so the SDK default is preserved (Google deferred until its native suffix is verified). `diagnoseEmbedding` fails closed with `user_provided_dims_unset` when a user-provided / zero-default recipe (litellm/llama-server) has no configured `embedding_dimensions`. `configureGateway` does not backfill `embedding_dimensions` (readers default it themselves), keeping the "no dims set" signal honest for that guard and the multimodal skip. `withBudgetTracker`: gateway-layer enforcement via `AsyncLocalStorage<BudgetTracker>`. `withBudgetTracker(tracker, fn)` installs the tracker on the module-internal store; every `gateway.chat / embed / rerank` call inside the scope auto-composes (reserve before, record in try/finally). Outside-scope calls are budget no-ops. Nested scopes restore the outer tracker on exit. `getCurrentBudgetTracker()` is the test seam. The chat path uses the pessimistic fallback on error paths; the embed path estimates input tokens from char count × recipe's `chars_per_token` because the AI SDK doesn't surface per-batch embed token usage; the rerank path estimates char count of query+docs. Pinned by 6 unit cases. `reconfigureGatewayWithEngine(engine)` (async, called from `cli.ts` after `engine.connect()`, before every command except `CLI_ONLY` no-DB commands) re-resolves expansion + chat defaults through `resolveModel()` so `models.tier.*` and `models.default` overrides apply to both. `DEFAULT_CHAT_MODEL` is `anthropic:claude-sonnet-4-6`. `ChatOpts.temperature` is threaded verbatim to the AI SDK `generateText` call (unset → the provider's default; the LongMemEval judge pins `0`, the official `evaluate_qa.py` setting). `ChatResult.responseModel` carries the model id the PROVIDER reported (`response.modelId`, e.g. a dated snapshot) when the SDK surfaced one and is absent otherwise, while `model` stays the requested `provider:modelId`; eval receipts pin the two side by side (`reader_model_snapshot`, `judge_model_snapshot`). `__setChatTransportForTests` mirrors `__setEmbedTransportForTests` so tests drive `chat()` with a stubbed transport. `toolLoop` per-turn permit hook: optional `acquireTurnPermit()` acquires a provider permit before EVERY round-trip and releases in finally; a lease-full throw propagates without consuming the turn (the subagent path wires it to the rate leases with provider-derived keys — Anthropic models share `anthropic:messages`, others get `<recipeId>:chat`). `ToolLoopStopReason` includes `'length'`: a zero-tool-call turn that hit the output cap propagates 'length' instead of folding into 'end', so truncation is never reported as a clean finish. Per-part provider state: `ChatBlock` variants carry optional `providerMetadata` captured from SDK parts in `chat()` and re-emitted as `providerOptions` on the rebuilt parts in `toModelMessages()` (attached only when present — metadata-free blocks stay byte-identical); this is the Gemini 3.x thoughtSignature echo. `isThinkingByDefaultModel(modelStr)` (exported) matches Claude 5-family ids behind any provider-prefix chain with a letters-only family segment (never `claude-3-5-*`); `isThinkingModel(modelStr)` (exported) is that regex OR the recipe's chat `thinking_by_default` capability (fail-closed: unknown/chat-less recipes are non-thinking) and drives `defaultMaxOutputTokens`'s 32k thinking headroom for chat()/toolLoop() callers that omit maxTokens (e.g. `gbrain skillopt` rollouts) and the subagent handler's `resolveMaxOutputTokens`; think/index.ts shares the regex and makes the same capability check. Pinned by `test/ai/gateway-thinking-headroom.test.ts`. `expand()` and `generateOcrText()` also record on the ambient tracker (they call generateObject/generateText directly and never pass through `chat()`'s `_recordBudget`): record-only, no reserve — a breach surfaces on the NEXT reserving call, matching `chat()`'s swallow of `BudgetExhausted` from `record()`. Successes record normalized SDK usage via `normalizeSdkUsage` (the ONE home for the v6/legacy usage shapes, used by chat's success path too; first FINITE field wins so a NaN v6 field can't shadow a real legacy value or poison the running total); failures record pessimistically under `gateway.expand.failed` / `gateway.ocr.failed` (a rejected attempt still billed provider tokens — one expand() can legitimately produce two records when the structured-output attempt fails and the text fallback runs). A recipe whose declared structured-output support is rejected at call time is remembered for the process lifetime (`_structuredOutputRejectedRecipes`) so the rejected attempt isn't re-paid on every call. OCR's input estimate is prompt text + a fixed per-image token constant, never base64 length (bytes are not tokens). `generateOcrText()` routes to `getImageOcrModel()` — `embedding_image_ocr_model` when set, else the expansion model — gated by `isAvailable('expansion', <ocr model>)` so a misconfigured OCR model (provider without an expansion touchpoint, or unkeyed) fails closed to `''` instead of silently OCRing with the expansion model; the accessor mirrors `getMultimodalModel()`, `configureGateway`/`buildGatewayConfig` thread the field, and an unconfigured gateway stays a silent `''` no-op. Pinned by `test/ai/ocr-model-routing.test.ts`. `__setGenerateObjectTransportForTests` mirrors the generateText seam. `ChatOpts.responseSchema` (`{ name, description?, schema }`) is honored ONLY when the resolved recipe is openai-compatible AND declares `supports_structured_outputs`: `chat()` attaches a tolerant `Output` spec (`jsonSchemaOutput` — carries the `{ type: 'json', schema, name }` responseFormat the provider turns into `response_format: json_schema`, and `parseCompleteOutput` hands the raw text back instead of throwing `NoObjectGeneratedError` the way `Output.object` does on unparseable text) to the generateText call, so `result.text`, stopReason mapping, budget recording and the caller's own parse + retry lane run unchanged; native / claude-cli lanes and undeclared openai-compatible recipes never see the field. A declared recipe whose backend REJECTS the schema at call time (`isStructuredOutputRejection` in `errors.ts`: a request-shaped 4xx naming `response_format` / `json_schema` / structured output — never a 5xx or an unrelated 400) gets ONE schemaless retry plus one warn line, and lands in `_structuredOutputRejectedRecipes` so later `chat()` and `expand()` calls skip the schema for the process lifetime instead of re-paying the rejection on every retry lane. + `test/core/budget/expand-records-budget.test.ts` + `test/ai/gateway-ocr-budget.test.ts` + `test/facts-extract-structured-output.test.ts` Tracker recording goes through `src/core/ai/budget-record.ts:recordOnTracker` (fail-open: a cap breach on `record()` surfaces on the next `reserve()`); every chat/toolLoop/expand/embed/rerank/OCR record site passes the requested model, `purpose` (optional on `ChatOpts` + toolLoop opts; skillopt sets `skillopt.optimizer|target|judge`, engine-internal calls leave it null), `failed` on failure paths, `countsAsCall: false` for expand's structured-output fallback attempt and `estimated` when tokens are char-estimated. `reconfigureGatewayWithEngine` records the expansion/chat `ResolveSource` (`file_config` for the servable config.json pin) in `src/core/ai/gateway-model-sources.ts`; its getters answer only while the gateway still routes to the recorded model, so a later reconfigure reads as unknown instead of stale provenance.- `src/core/ai/model-resolver.ts` — Recipe-touchpoint validator. `assertTouchpoint(recipe, touchpoint, modelId)` checks the PROVIDER's capability only (anthropic has no embedding touchpoint; voyage/ollama have no chat) and never gates on the model id. Recipe `models:` arrays are informational — default-model selection (`models[0]` for `--model <provider>` shorthand and env-ready pickers), guard-test fixtures for the repo's own hardcoded defaults, and `gbrain providers list` display — NOT a runtime allowlist, so frontier models newer than a recipe work without a recipe PR. A nonexistent id surfaces as the provider's own `model_not_found` at call time; `gbrain models doctor` live-probes the configured models for a pre-flight check. Exception: `gateway.rerank()` keeps its own model-list check because each listed reranker id maps to a known request/response wire shape. `embeddingDimsForModel` matches recipe `model_dims` keys exactly first, then case-insensitively with BOTH sides folded (configured ids arrive cased, and user-editable recipe tables can carry cased keys; without the fold a cased id would fall through to `default_dims` and `gbrain init` would build a wrong-width column), before falling back to `default_dims`.diff --git a/docs/architecture/key-files/core-cycle.md b/docs/architecture/key-files/core-cycle.mdindex 12061b2405..04a94fd446 100644--- a/docs/architecture/key-files/core-cycle.md+++ b/docs/architecture/key-files/core-cycle.md@@ -17,7 +17,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/cycle/extract-atoms.ts` — the extract_atoms lens phase: mines eligible pages into `atoms/<date>/<stem>-<hash>` pages. Eligibility reads source-incarnation/page/full-hash-keyed derived scan state; scan and failure markers do not mutate canonical frontmatter. Managed extraction checks source-wide local authority and owner readiness before provider work, admits outputs plus a completion request together, and replays retained output without another model call. Managed atom files keep provisional source hashes; only the source-incarnation/page/full-hash durable completion receipt excludes an item from discovery and backlog counts. Unmanaged atom completion flips and their cardinality check share a transaction after provenance links persist, so a partial match rolls back and stays retryable. An undated source dates its atoms by the source page's creation date (`undated` for transcripts), never the run date. After an unmanaged item completes, `retireStaleAtoms` soft-deletes that source's atoms from earlier extractions (other or provisional `source_hash`) that this extraction did not re-produce, so LLM-chosen titles that drift between extractions don't pile up. Atom identity: page-derived atoms fold the source-page slug into the slug hash (8 chars, NUL-separated) so two same-date pages emitting the same title get DISTINCT slugs; the source CONTENT hash is deliberately NOT folded (a reworded source still upserts rather than duping); transcript atoms keep the legacy title-only 6-char hash. `resolvePageAtomSlug` adopts a legacy-slug atom with a compatible binding in place on re-extraction (upgrade idempotency — no migration, no duplicate), while `assertAtomImportBinding` fail-closed refuses to reuse a slug bound to a DIFFERENT source locator. Both share `isCompatibleAtomBinding(frontmatter, sourcePageSlug)` — the ONE definition of compatible: bound to THIS source page, or carrying no `source_slug`/`source_path` at all (pre-binding-era adoption, not a clobber); a `source_path`-bound legacy transcript atom or a different `source_slug` is a different origin, and a non-atom page squatting on the slug is refused. `source_quote` is verified at extraction time against the exact `truncateUtf8` prompt prefix the model saw (`locateQuote` advances by full code points): located quotes persist original characters + [start,end) offsets + `source_quote_verified`; unlocatable quotes are dropped with the atom kept. Edges write before the completion flip; per-item drain failures stay typed (bounded, sanitized, reconcilable). Transcript items carry the same failure-count/tombstone machinery as pages, in the `extract_atoms_transcript_state` table (migration `extract_atoms_transcript_state_table`; keyed `(source_id, file_path, content_hash)` with the 16-char hash prefix, so an edit is a new row and re-eligibilizes): `recordItemFailureCount` counts a transcript's malformed output toward `MAX_DETERMINISTIC_FAILURES`, a zero-yield transcript tombstones immediately (the same zero-yield policy as pages), and `tombstonedTranscriptsForHashes` is the batch read-side gate mirroring `atomsExistingForHashes` (fail-open on error). Reported as `tombstoned_transcripts` (paths), separate from the page-slug `tombstoned_for_failures`. Malformed managed output requires a newly approved protected-job retry identity; publication retry reuses retained output and original/current grants.-- `src/core/cycle/extract-facts.ts` — source-scoped `## Facts` fence reconciliation. Rows are keyed by fence row number, never by claim text: a DB row whose `(row_num, claim)` is still in the fence keeps its id and has its other cells updated in place (ids from recall stay valid for forget; `source_session`, `created_at`, consolidation state and vectors survive), a row whose number left the fence or whose claim was rewritten is expired and detached (`row_num` NULL), never deleted, and only new row numbers insert. Duplicate ACTIVE rows with the same claim and source index once; a struck history row never collapses onto an active row with the same text, so a claim that reverts (NYC → SF → NYC) stays active. `superseded by #N` links resolve on every hop of a chain (`supersede-resolve.ts`; forgotten targets and cycles still resolve to NULL with a warning). Each run first expires (without detaching) the active fence-owned rows of soft-deleted pages in the source; restoring the page re-activates them on its next reconcile. Previously embedded fact rows and their text/provenance remain intact when a full valid replacement embedding batch is unavailable; old vectors are never transplanted to changed text/model. Restrictive fence changes still expire removed/withdrawn claims and tighten visibility before deferral. Provider cancellation within database writes rolls back rather than publishing half a replacement. Keyless initial fact insertion remains supported; conversation-origin facts without a fence are not wiped by fence reconciliation. Each page reconciles in isolation: a page whose writes the database rejects rolls back, is reported as `<slug>: FACTS_RECONCILE_FAILED: …` (counted in `pagesFailed`, booked as a halt in the rollup), and later pages still reconcile. `facts.superseded_by` is `ON DELETE SET NULL`. Tests: `test/e2e/fact-vector-repair-parity.test.ts`, `test/extract-facts-phase.test.ts`, `test/extract-facts-poison-page.test.ts`, `test/extract-facts-stable-identity.test.ts`. Managed legacy fence reconciliation refuses before any provider work; it is distinct from the restored coordinated `extract_facts` operation and durable page backstop.+- `src/core/cycle/extract-facts.ts` — source-scoped `## Facts` fence reconciliation. Rows are keyed by fence row number, never by claim text: a DB row whose `(row_num, claim)` is still in the fence keeps its id and has its other cells updated in place (ids from recall stay valid for forget; `source_session`, `created_at`, consolidation state and vectors survive), a row whose number left the fence or whose claim was rewritten is expired and detached (`row_num` NULL), never deleted, and only new row numbers insert. Duplicate ACTIVE rows with the same claim and source index once; a struck history row never collapses onto an active row with the same text, so a claim that reverts (NYC → SF → NYC) stays active. `superseded by #N` links resolve on every hop of a chain (`supersede-resolve.ts`; forgotten targets and cycles still resolve to NULL with a warning). Each run first expires (without detaching) the active fence-owned rows of soft-deleted pages in the source; restoring the page re-activates them on its next reconcile. Previously embedded fact rows and their text/provenance remain intact when a full valid replacement embedding batch is unavailable; old vectors are never transplanted to changed text/model. Restrictive fence changes still expire removed/withdrawn claims and tighten visibility before deferral. Provider cancellation within database writes rolls back rather than publishing half a replacement. Keyless initial fact insertion remains supported; conversation-origin facts without a fence are not wiped by fence reconciliation. Each page reconciles in isolation: a page whose writes the database rejects rolls back, is reported as `<slug>: FACTS_RECONCILE_FAILED: …` (counted in `pagesFailed`, booked as a halt in the rollup), and later pages still reconcile. `facts.superseded_by` is `ON DELETE SET NULL`. Tests: `test/e2e/fact-vector-repair-parity.test.ts`, `test/extract-facts-phase.test.ts`, `test/extract-facts-poison-page.test.ts`, `test/extract-facts-stable-identity.test.ts`. On a managed brain the same reconcile runs after `managedDerivedFactsPreflight` (local writer, active source, before any embedding call): each page transaction and the deleted-page expiry commit inside `withDerivedFactsWrite` (coordinator source capability, page key locked); the facts receipt page is skipped, the rollup is still booked. It is distinct from the coordinated `extract_facts` operation and durable page backstop. Tests: `test/managed-facts-writers.test.ts`.- `src/core/cycle/inline-drain.ts` — the dream cycle's private-queue drain. `runSubagentsInline(engine, queue, queueName, yieldDuringPhase?, handler?, lockMs?, concurrency?)` runs N independent `drainLoop`s (`dream.synthesize.inline_concurrency`, clamp [1,8], PGLite forced serial at the callsite) sharing the queue via the same SKIP-LOCKED claim fencing workers use — everything job-scoped (lockToken, abort, timeout timer, keepalive, renewTimer, outcome recording) stays loop-local. Pool hygiene: global housekeeping sweeps are leader-only (loop 0) while `promoteDelayed` runs in every loop; idle claim-poll backs off 1s→5s; a NON-retryable loop-level failure aborts siblings after their current child (a failing child is a job outcome, never a drain crash). Exit only when the queue holds no active/waiting/delayed child (a lease-full bounce's delayed backoff must not strand a child). Outcome routing mirrors the worker: `UnrecoverableError` → dead immediately; `RateLeaseUnavailableError` → `releaseLeaseFullJob` requeue without burning an attempt; timeout terminal. Handler invocation is wrapped in `withChatPhase('job:<name>')` (worker.ts parity) so each drained child's gateway spend is attributed to the CHILD — a bare `await handler(context)` inherits the caller's AsyncLocalStorage phase, and a cycle phase that wraps its own work (dream synthesize wraps `phase:synthesize`) would absorb every child's spend into the phase tag. `runDrainRenewalTick` (per-call AbortSignal + timeout + re-entrancy guard) and the null-safe nearest-rank `percentile()` telemetry helper are exported. Pinned by `test/cycle-synthesize-inline-concurrency.test.ts` (loop semantics) + `test/e2e/dream-synthesize-concurrency-postgres.test.ts` (real-Postgres exact-once + lease-ceiling).@@ -27,11 +27,12 @@ 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/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/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. Contained cycle-phase failures after paid model calls (`recordContainedPaidFailure`, `dream.breaker.contained_failures` config JSON, 24 h window, database clock) are counted under `dream:phase:<phase>:<source>` keys; the breaker never refuses those phases, doctor reports them and `gbrain dream reset-key` clears them. 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; a fuzzy hit needs a 0.1 margin over the runner-up) → `findPrefixCandidates` ambiguity check (a canonical that is not the single prefix candidate is ambiguous too) → `fenceDbDrift` bi-directional check → dry-run early exit → canonical file resolved through `resolvePageWriteTarget` (recorded `source_path`, own-`local_path` roots; only a brain with no configured root falls back to `brainDir`) → materialize canonical via `serializeMarkdown` if DB-only → append phantom fence rows to that file with `(claim, valid_from)` dedup-guard, numbering past both the file's and the DB's highest row number and rewriting `superseded by #N` to the new numbers → `engine.refreshPageBody` → move the phantom's fact withdrawals to the canonical subject → move every phantom fact row by id (a row takes its on-disk canonical row number unless the canonical index already holds it; history, duplicates and rows absent from the fence move expired and detached, never deleted) → move the phantom's links to the canonical page id (skipping duplicates and self-links) → `recordRenameAlias` (phantom → canonical in `slug_aliases`) → `engine.softDeletePage` + unlink. `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.+- `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; a fuzzy hit needs a 0.1 margin over the runner-up) → `findPrefixCandidates` ambiguity check (a canonical that is not the single prefix candidate is ambiguous too) → `fenceDbDrift` bi-directional check → dry-run early exit → canonical file resolved through `resolvePageWriteTarget` (recorded `source_path`, own-`local_path` roots; only a brain with no configured root falls back to `brainDir`) → materialize canonical via `serializeMarkdown` if DB-only → append phantom fence rows to that file with `(claim, valid_from)` dedup-guard, numbering past both the file's and the DB's highest row number and rewriting `superseded by #N` to the new numbers → `engine.refreshPageBody` → move the phantom's fact withdrawals to the canonical subject → move every phantom fact row by id (a row takes its on-disk canonical row number unless the canonical index already holds it; history, duplicates and rows absent from the fence move expired and detached, never deleted) → move the phantom's links to the canonical page id (skipping duplicates and self-links) → `recordRenameAlias` (phantom → canonical in `slug_aliases`) → `engine.softDeletePage` + unlink. `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. `mergePhantomFenceRows` (pure body merge), `movePhantomFacts` (row move inside the caller's transaction) and `mergePhantomLinks` are shared with `phantom-redirect-managed.ts`, which a managed brain uses instead of the file-first commit phase.+- `src/core/cycle/phantom-redirect-managed.ts` — managed-brain phantom redirect (#5280). After the same gates, `redirectManagedPhantom` runs `maintenancePreflight`, renders the canonical body with the phantom's fence rows appended and submits `managed_maintenance_phantom_merge` on the canonical page (keyed by its intent): `preparePhantomMerge` rechecks the phantom's id and revision, and its publication moves withdrawals, the phantom's fact rows by id, links and the rename alias in the canonical page's publication transaction. It then submits `managed_maintenance_phantom_delete` on the phantom, bound to the merged revision: `preparePhantomDelete` holds both page keys, moves any edge added to the phantom since the merge, defers if timeline rows appeared, then soft-deletes and removes the file. A missing canonical page or a changed phantom is reported as `drift`. Tests: `test/managed-facts-writers.test.ts`.- `src/core/cycle/phase-scope.ts` — the phase-scope taxonomy: `PHASE_SCOPE: Record<CyclePhase, 'source'|'mixed'|'global'>` maps each of the 23 phases (source: safe to parallelize per source; global: must serialize across the brain; mixed: brain-wide read + page write, so it stays in the default/global-maintenance lane until decomposed), plus `SOURCE_FRESHNESS_PHASES` — the deterministic, non-LLM subset (lint, backlinks, sync, extract, extract_facts, recompute_emotional_weight) that alone defines source freshness, so LLM-backed enrichment can never hold a freshness stamp hostage. cycle.ts re-exports both and derives the scheduling lists from them (see the cycle.ts entry). Consumed by `runCycle`'s `resolveCyclePhases` boundary, the autopilot fanout's per-source enqueue (`src/commands/autopilot-fanout.ts`), the jobs global-maintenance handler, and doctor's routing-federation phase-scope surface (`src/commands/doctor/checks/routing-federation.ts`). Pinned by `test/autopilot-global-maintenance.test.ts` (SOURCE ∪ MIXED ∪ GLOBAL == ALL_PHASES with no overlap; FRESHNESS ∪ BACKGROUND == SOURCE; resolveCyclePhases boundary semantics).@@ -48,3 +49,6 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `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`.+- `src/core/cycle/phase-containment.ts` — `timeContainedPhase` is the timer every `runCycle` phase runs under: a phase runner that throws returns a `fail` phase result carrying `{ class, code, message }` and `details.contained`, so later phases in the job still run while the report stays partial/failed (global freshness is not stamped; `gbrain dream` exits non-zero). Cancellation (an aborted cycle signal or `AbortError`), `LockStolenError` and `BudgetExhausted` are never contained. Successful `gateway.chat` calls inside the phase are counted through `withChatCallMeter` (`ai/chat-usage.ts`); a contained failure after at least one paid call is recorded under `dream:phase:<phase>:<source>` for `dream_paid_loop`. Tests: `test/cycle-phase-containment.test.ts`.+- `src/core/cycle/phase-table.ts` — `MANAGED_PHASE_TABLE` classifies every `ALL_PHASES` entry for managed brains as `writes` (publishes through the coordinator), `no_coordinated_write` (derived projections, side tables, audit-only) or `managed_skip`, each with its reason; `isManagedBrain` is what `runPhaseLint` uses to report issues without rewriting managed canonical files. The managed phase matrix test fails for an unclassified phase.+- `src/core/cycle/concept-publication.ts` — managed `synthesize_concepts` publication: `publishManagedConcept` publishes through `publishMaintenancePage` (a concept with a recorded `source_path` republishes to its file unless a `db_only` tier covers it; new concepts are database-only), and `composeConceptRepublication` keeps an existing concept's facts/takes fences, timeline, tags and other frontmatter, holding the concept (`concept_preservation_hold`) when a fence is duplicated, unbalanced, unparseable or below the timeline sentinel. `addManagedProvenanceLinks` commits the concept-provenance edges inside a coordinated transaction. The phase keeps the private-first, provenance, then promotion order; revision races are deferred and holds reported in the phase details. Tests: `test/managed-writers-w3.test.ts`.diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.mdindex 4d6523a937..bee691b631 100644--- a/docs/architecture/key-files/core-persistence.md+++ b/docs/architecture/key-files/core-persistence.md@@ -8,15 +8,25 @@ The page operations that submit through this layer are in [Core Services (2/3)](- `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/{admin-lock,blocking-effects,writer-versions}.ts` — `admin-lock.ts` owns the opt-in brain-level writer admin lock: reserved config key `persistence.writer_admin_lock` (`{locked, set_at, host_id, generation}`), written only by local `gbrain sources writer lock|unlock` under the `persistence_brain` row `FOR UPDATE`; lock refuses while a prepared transfer is unaccepted. `assertWriterAdminUnlocked` runs inside the claim, managed claim, activation, shared-skill activation and transfer prepare/accept transactions for every caller (share lock on the brain row) and refuses with `writer_admin_locked`; only the ordinary first-write auto-claim (`claimWorktree(..., { automatic: true })` from page and memory mutations) is exempt. Generic `config set`/`unset`/`unset --pattern` refuse the key; engine migration copies it. It is not a security boundary and older binaries ignore it. `blocking-effects.ts` lists queued, running or recovering effects (`listBlockingEffects`) and builds `writer_not_quiesced` suggestions naming the first blocking request or effect with `gbrain sources writer status <source> --json`. `writer-versions.ts` stamps admitter version/host at admission and consumer version/host/`published_at` only on committed publication (migration 178, cutoff `persistence_brain.writer_version_cutoff` on the database clock); replay and compaction keep stamps. `sources writer status` reports `admin_lock`, `local_host_id`, `blocking_effects` and `writer_versions`; `src/commands/doctor/checks/writer-version.ts` is the seven-day `writer_version` advisory. Tests: `test/persistence-writer-admin-lock.test.ts`, `test/persistence-writer-versions.test.ts`, `test/persistence-blocking-effects.test.ts`, `test/e2e/persistence-writer-{admin-lock,stamps}.test.ts`.+- `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/{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. `submitMaintenanceIntent` admits a maintenance request with its own intent kind keyed by the intent; `prepareMaintenanceMutation` also handles `managed_maintenance_phantom_merge` and `managed_maintenance_phantom_delete` (both delegated to `cycle/phantom-redirect-managed.ts`). `publishMaintenancePage` accepts an optional `eventProjection` (Life Chronicle): the event page and its depth-page timeline row commit in the same publication with the depth page key locked. Remote maintenance remains refused.+- `src/core/persistence/derived-facts.ts` — database-only fact rows derived from page text (fence reconcile, conversation facts): `managedDerivedFactsPreflight` (managed check, accepting persistence, local writer, active source; before provider spend), `withDerivedFactsWrite` (one transaction holding the coordinator source capability and the page keys, like derived links) and `writeDerivedFacts` (that on a managed brain, the caller's own engine call otherwise). No persistence request is admitted per row. 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. `unrecordedCanonicalTimeline` returns the body's canonical tuples with no stored row under the normalized key (managed `extract --stale` inserts only these), and `materializedHistoryRanges` locates marker lines whose hash matches the bullet after it, plus that bullet's indented detail (the dream verifier's history exemption). Tests: `test/canonical-projection-history.test.ts`, `test/timeline-materialize.test.ts` (PGLite and Postgres).+- `src/core/persistence/canonical-projections.ts` — installs the facts, takes and timeline projections of a canonical page body inside its publication transaction. Rows written by the conversation fact extractor (`cli:extract-conversation-facts*`) share the page coordinate without a fence and are never expired as rows that left it (#1928 parity with the extract_facts reconcile), so republishing a conversation keeps its extracted facts until their own replay replaces them. 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. `unrecordedCanonicalTimeline` returns the body's canonical tuples with no stored row under the normalized key (managed `extract --stale` inserts only these), and `materializedHistoryRanges` locates marker lines whose hash matches the bullet after it, plus that bullet's indented detail (the dream verifier's history exemption). 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/connector-sync.ts` — managed Google/GitHub API ingestion through source-scoped journaled `connector_v2_import`/`_delete`/`_checkpoint`/`_google_receipts` intents and `managed-connector` checkpoint CAS, not Git cursors. The checkpoint key, admission `configHash`, mid-sweep change check and publication `source_changed` check all use the parsed-config identity from `connector-identity.ts`, so cycle stamps in `sources.config` never rotate them. Unbound connectors use reviewed `connector_database` SQL-only authority; bound connectors retain canonical file publication with guarded root/hash/revision/epoch. Every managed run checks the credential's resolved account against the pin in the connector state row before reading its checkpoint (`assertAccount`), then applies a requested `--reset-checkpoint` (pending writes resolved first, pin kept). Each import or delete is first screened by running `prepareConnectorMutation` on an unadmitted request through the no-op kernel; unchanged items take no admission. An unchanged checkpoint save is skipped and, when it would have stamped freshness, `last_sync_at` is stamped directly inside a lease-asserted coordinated write. Accepted-pending writes are progress: a 30-second total wait budget (writes committing within one second are free), at most one in-flight write per page, outstanding writes kept under the principal's outstanding and intent-byte limits, and `ConnectorWaitBudgetStop` (a `write_pending` error) when the budget is spent. The checkpoint never advances past a pending page; the run records its pending set in the state row, and the next run resolves it first (committed dropped, failed retried automatically through the retry-pointer path without `--retry-failed`, unreached failures after a complete sweep dropped and counted). Retired `managed_connector_*` intents route to `prepareOutdatedConnectorMutation`, which fails them `connector_intent_outdated` (detail `pre_upgrade` before the v176 cutoff). Standalone entry, page reads and submissions authenticate the current source, local grant and canonical owner and settle retained worktree publications before deriving request identity. Explicit `--retry-failed` atomically admits a linked attempt and stores a per-base-request `managed-connector-retry` pointer. Durable connector cursors, retry pointers and state rows survive generic seven-day checkpoint GC. Tests: `test/persistence-connectors.test.ts`, `test/persistence-connector-retry.test.ts`, `test/connector-checkpoint-identity.test.ts`, `test/connector-wave3.test.ts` and `test/helpers/connector-restart.ts` on PGLite and disposable Postgres.+- `src/core/persistence/connector-identity.ts` — `connectorIdentity(kind, rawConfig, localPath)` returns the parsed connector config and a digest over every parsed leaf except credential-delivery fields (Google `access`/`tokenCommand`/`tokenEnv`; GitHub `tokenEnv` and `app` under `scope: repos`, `app.pemPath` always; under `scope: auto` the token env without an App and the App ids are identity). `services`/`repos` are sorted and de-duplicated; a parser leaf missing from `CONNECTOR_LEAF_RULES` joins the identity. Also `connectorCheckpointKey` and `isConnectorIntentKind`/`connectorIntentSql`, the one predicate for both intent namespaces. Test: `test/connector-identity.test.ts` enumerates every parser leaf.+- `src/core/persistence/connector-state.ts` — the per-source-incarnation `op='managed-connector-state'` row (fingerprint `digest({sourceId, incarnation})`, independent of the identity digest): account pin, pending set `{itemRef, requestId, baseRequestId, admittedAt}`, `upgrade_recovery` (`resumed`/`rewalking_once`/`none`) with `resumed_from`, `continuity_unverified` and last-run counts. `writeManagedConnectorState` checks the connector sync lease in the same statement. `connector-status.ts` renders it for `gbrain sources status` without the account.+- `src/core/persistence/connector-account.ts` — resolves the credential's account before any service runs: Google through Gmail profile, Calendar primary calendar or People `me` (first enabled service that answers; none refuses), GitHub App installation id from the minted token, or the `/user` login for token auth under `scope: auto`.+- `src/core/persistence/connector-errors.ts` — `connector_account_changed` with its two-exit hint, the retired-intent messages, and `receiptDeliveredHint`, which rebuilds `suggestion`/`detail`/`docs` for codes delivered through a stored receipt (the coordinator persists only code and message); `writeResponse` applies it.+- `src/core/persistence/noop-kernel.ts` — the #5470 no-op kernel. `inspectUnchanged` takes a preparer's `PreparedMutation` for an unadmitted `screeningRequest` and returns `contentUnchanged`, `projectionWorkRequired` (safe-chunk fence, text projection behind the knowledge revision, embedded page without a contextual mode), `metadataWorkRequired` (source path) and `observedRevision`; bound pages also need local file bytes equal to the serialized page. Callers run the preparer's own `validate` before counting a skip. Used by connector sync, `import-mutations.ts`, and `sync-run.ts` (working-tree and company-profile entries; renames and overlays always admit). Tests: `test/noop-kernel-paths.test.ts`, `test/connector-wave3.test.ts`.+- `src/core/persistence/accepted-pending.ts` — `acceptedPendingReceipt(error)`: the shared test for an accepted, not yet committed write, used by managed atom publication, extract_atoms, managed import and the connector budget.+- `src/core/persistence/connector-checkpoint-migration.ts` — migration 176 and orphan cleanup. The newest committed checkpoint receipt per source incarnation (found by slug, so a compacted one is still seen and re-walks) is copied to the stable key with `INSERT … ON CONFLICT DO NOTHING`; state rows are seeded; the cutoff is stored in `op_checkpoints` (`op=managed-connector-migration`, fingerprint `v2-cutoff`, excluded from the checkpoint purge). `orphanConnectorCheckpoints` keeps rows touched after the start, rows any registered source (archived included) can load, and rows referenced by a non-terminal request or a pending set; timestamps bind as text. `gbrain repair connector-checkpoints` (`src/core/repair/connector-checkpoints.ts`) and the `connector_checkpoints` doctor check reuse it with a 7-day floor. `connector-reset.ts` guards `gbrain sync --reset-checkpoint` to connector sources.- `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. A tick woken by a completed publication or a local admission claims the next write at once and runs root refresh plus recovery, expiry and topology scans at most once per poll interval; explicit, timer and idle-probe ticks always scan. Effects drain in batches of 20 without waiting for the next tick while full batches keep arriving; within a batch, git effects wait for their asynchronous durability probe (one per worktree root) after the other effects, and a single-file git effect in a repository without the durability hook acquires the worktree lock only to prove its root and records its outcome after releasing it. On PGLite, which has no autovacuum, the maintenance worker also runs `vacuumPersistenceQueues` (VACUUM ANALYZE of the queue tables) every minute or after 50 + 20% of the request table's rows in publications. 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`.@@ -32,7 +42,7 @@ The page operations that submit through this layer are in [Core Services (2/3)](- `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 keyed on the request's own forgotten fact (falling back to the whole source ledger only when that fact row is gone) while retaining each cursor; ambiguous or over-capacity legacy intent stays pending. Older workers must be quiesced before rollout. Independent mirror recovery reserves capacity before file effects, finishes forward without changing revision or receipt, and blocks only its worktree until reconciled. Git holds the native root lock, disables hooks, uses literal pathspecs and target-only commits, and pushes without pull/rebase. A 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/{effect-schema,effect-model,effect-journal,effect-recovery,effect-git,effects}.ts` — bounded postcommit outbox (migration 155). Canonical publication atomically queues Git and embedding work; withdrawals queue three versioned, bounded exact-page manifests with durable slug cursors. `effect-targets.ts` converts legacy source scans with complete bounded discovery keyed on the request's own forgotten fact (falling back to the whole source ledger only when that fact row is gone) while retaining each cursor; ambiguous or over-capacity legacy intent stays pending. Older workers must be quiesced before rollout. Independent mirror recovery reserves capacity before file effects, finishes forward without changing revision or receipt, and blocks only its worktree until reconciled. Git holds the native root lock, disables hooks, uses literal pathspecs and target-only commits, and pushes without pull/rebase. A claimed single-file Git effect brings up to 99 more ready single-file Git effects of its worktree (`claimCoalescedGitEffects`, same readiness, recovery and withdrawal-mirror ordering predicates, `SKIP LOCKED`); the runner validates each path under the worktree lock, makes one `commit --only` per group (`commitGitTargets`: one `ls-files`, `status`, `add` and `diff` for the group; untracked absent or ignored targets take the per-target refusal path) and pushes each root once at the end of the pass (`pushGitRoot`). A group shorter than 100 yields to publications still queued or running for its worktree (`retryEffect` with `publication_pending`, 250 ms apart) for at most 20 claims, so a serial producer publishes ahead and its Git work lands as one group; the v0.13.1 grandfather step admits a 50-page window (`admitCanonicalGrandfather`) before waiting for it. A path failure fails only its effect; a push failure leaves the group queued with `git_push_unavailable`, and the next pass finds nothing to commit and pushes once (#5530; tests: `persistence-git-coalescing-5530.slow.test.ts` + Postgres wrapper). A Git effect for a declared db_only page completes as skipped (`reason: db_only`), keeping its gitignored cache file out of Git. A Git or withdrawal target parks after five consecutive execution failures (`data.target_failures` for `data.failing_target`, reset when the target advances or a different target fails; shutdown cancellation, contention, dependency waits (including recovery-capacity waits) and transient database failures do not count): a scan records it in `data.parked` and moves on, a single-target effect or a failure outside any target parks the whole effect, and an effect with parked targets finishes as `failed`/`targets_parked`, never committed. 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.@@ -40,8 +50,12 @@ The page operations that submit through this layer are in [Core Services (2/3)](- `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/unbound-source.ts` — #5254 policy for a Postgres page write to a filesystem source (`local_path`, or `sync.repo_path` for `default`) with default write-through and no worktree binding. `submitPageMutation` refuses `owner_unavailable` with `detail: unbound_source`, a `docs` pointer to `write-refusals.md#unbound-sources-on-postgres`, and a hint naming the filled `sources writer status`/`writer claim ... --admin-intent writer_claim --expected-state <admin_state>` bind command (host path only for trusted local callers) and, for `put_page` to a page without `source_path`, `gbrain config set persistence.unbound_write database_only`. That key (`refuse` default, validated by `config set`; any other stored value refuses) lets such a `put_page` admit with `databaseOnlyReason: 'unbound_source'`. Publication rechecks inside its transaction, after `authorizeStoredRequest` share-locks the source row, that the source is still unbound and the page still has no `source_path` (else `owner_unavailable`/`unbound_source`, hint rebuilt from the persisted message by `writeResponse`), then stamps `pages.database_only_reason='unbound_source'` (migration 177). After binding, `prepareFileTarget` keeps a stamped page with no file database-only (receipt `write_through.skipped: unbound_source` with a warning) and managed sync refuses to import a file at its path (`source_changed`, diagnostic reason `unbound_source`). PGLite keeps auto-claiming. Tests: `test/e2e/unbound-source-postgres.test.ts`, `test/persistence-unbound-source.test.ts`.+- `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/persistence/manual-links.ts` — `coordinatedManualLinkWrite` makes `add_link` / `remove_link` coordinated database-only writes on a managed brain: it checks the caller's durable write authority for the `from` page (`submissionAuthority`, then `authorizeWrite` FOR SHARE inside the transaction), revalidates the source incarnation and commits the edge inside `withCoordinatedWrite` holding both endpoint page keys. Unmanaged brains keep the engine calls. Manual edges (`link_source` `manual` or a custom tag) survive re-derivation and republication because automatic reconciliation only replaces derived provenances. Tests: `test/managed-writers-w3.test.ts`.+- `src/core/persistence/purge-deleted.ts` — `purgeDeletedPagesCoordinated` backs the cycle `purge` phase, the purge job, `purge_deleted_pages` and `gbrain pages purge-deleted`. Unmanaged brains keep the engine bulk delete; a managed brain purges each tombstone older than the window (skipping archived sources, which the source lifecycle purges) through `delete_page` with `purge: true` bound to its revision. Revision races are deferred to the next run; any other failure is listed in `blocked` and sets `error`, which fails the purge phase. Tests: `test/managed-writers-w3.test.ts`.diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.mdindex 5f3214b2a6..430547bb16 100644--- a/docs/architecture/key-files/core-services-2.md+++ b/docs/architecture/key-files/core-services-2.md@@ -17,7 +17,8 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/facts/withdrawal.ts` + `withdrawal-schema.ts` + `withdrawal-discovery.ts` — durable withdrawal key is `(source_id, visibility, subject, SHA256(normalized claim))`. `subject` is the forgotten row's `entity_slug`; '*' (all subjects) covers subjectless facts and rows recorded before v169. A withdrawal matches when `subject = '*' OR subject = entity_slug`, so forgetting one entity's claim never touches the same claim about another entity. Fence rows belong to their page's entity: the import overlay, prepared-import check (`preserveWithdrawnFenceRows` / `assertPreparedFactWithdrawals`), snapshot overlay and Markdown export match on the page slug. `updateSlug` (both engines, via `moveSlugBindings`) and the phantom-redirect merge move subjects to the new slug (`MOVE_WITHDRAWAL_SUBJECT_SQL`), so rename and index recreation do not restore a claim. Normalization (`gbrain_fact_normalize`, mirrored in JS by `normalizeLoweredClaim`) folds case, whitespace and an explicit punctuation set, not meaning (migration v174); `+`, `#` and in-word dots are kept ("C++" ≠ "C"); pre-v174 ledger rows keep their exact `gbrain_fact_fingerprint_v1` hash and every ledger match checks both. v174 adds a folded row wherever a fact row still holds the claim text, expires facts that became matching, and builds `idx_facts_withdrawal_fingerprint` (the fingerprint inlines normalization: index builds use a restricted search_path). Discovery (`withdrawal-discovery.ts`) is keyed on claim, subject and fingerprint: SQL shortlists pages and chunks whose lowercased text contains every normalized token of the claim (necessary for any match; nothing is normalized in SQL), streams them by keyset, then verifies exactly; a subject-scoped claim reads only its entity's page plus provenance of that entity's facts. There is no source-inventory limit (#5674): refusals come from the matched set (>256 pages, reported with the count and sample slugs), the 10s scan budget, per-batch input limits or matching malformed evidence. Only an existing withdrawal covering the same subject skips discovery. Only affected page revisions/chunks are invalidated. The source row lock serializes withdrawal with the facts trigger; the trigger prevents insert/update from reactivating a matching claim. Import and snapshot overlays cover every complete legacy fence, including inactive rows; withdrawal markers precede preserved context and retain earlier expiry dates before hashing/chunking; malformed fences retain their existing diagnostics and the DB trigger still protects derived facts. `writeSingleFact` refuses an identical withdrawn claim for the resolved entity before embedding, using the protocol error envelope. `writeFactsToFence` rechecks each input under the page lock and drops claims withdrawn for the page's entity (reporting `withdrawnSkipped`), and the backstop skips them in phase 1, so a withdrawn claim is never appended to Markdown as an active row (audit B-10). TTL/supersession expiry creates no withdrawal; backfill trusts only explicit `forgotten:` markers; Markdown-only copies do not preserve DB-only withdrawals. Pinned by `test/facts-withdrawal-subject.test.ts`, `test/fact-withdrawal-normalized.test.ts`, `test/withdrawal-bounded-safety.test.ts` (both engines) and the Postgres scale gate `test/e2e/fact-withdrawal-scope-postgres.test.ts`.-- `src/core/facts/write-single.ts` — `writeSingleFact(fact, ctx)`: the zero-LLM single-fact seam behind `remember`. `runFactsPipeline` is extraction-first (LLM-gated) and cannot back a pre-formed fact; this reuses the pipeline's post-extraction stages directly: resolve → embedding-cosine dedup (same 0.95 threshold) → fence-first write with the same legacy DB-only fallbacks (thin-client, unparented, stub-guard). Supersession: deterministic rule — same entity_slug + same kind + similarity ≥ threshold + DIFFERENT text ⇒ the new fact supersedes (fence path: append new + `forgetFactInFence(old, { supersededBy })`, which strikes the old row with a page-local `#N` supersession reference and records no withdrawal, + superseded_by link; DB path: engine insertFact supersedeId). Pinned by `test/facts-supersede-not-withdrawal.test.ts`. Provenance lands on NewFact.source verbatim (no FactsBackstopCtx). No embedding provider ⇒ `degraded_dedup: true` (near-duplicates may insert — documented). `isNullLikeEntity(entity)` (exported) normalizes null-like entity tokens (`"null"`, `"undefined"`, `"none"`, `"n/a"`, `"nil"`, `"-"`, empty/whitespace) to ABSENT before resolution — applied here rather than only at the verb boundary so EVERY writeSingleFact caller gets the guard and the `resolved?.slug ?? entityRef` fallback can never adopt `"null"` as a slug.+- `src/core/facts/write-single.ts` — `writeSingleFact(fact, ctx)`: the zero-LLM single-fact seam behind `remember`. `runFactsPipeline` is extraction-first (LLM-gated) and cannot back a pre-formed fact; this reuses the pipeline's post-extraction stages directly: resolve → embedding-cosine dedup (same 0.95 threshold) → fence-first write with the same legacy DB-only fallbacks (thin-client, unparented, stub-guard). Supersession: deterministic rule — same entity_slug + same kind + similarity ≥ threshold + DIFFERENT text ⇒ the new fact supersedes (fence path: append new + `forgetFactInFence(old, { supersededBy })`, which strikes the old row with a page-local `#N` supersession reference and records no withdrawal, + superseded_by link; DB path: engine insertFact supersedeId). Pinned by `test/facts-supersede-not-withdrawal.test.ts`. Provenance lands on NewFact.source verbatim (no FactsBackstopCtx). No embedding provider ⇒ `degraded_dedup: true` (near-duplicates may insert — documented). `isNullLikeEntity(entity)` (exported) normalizes null-like entity tokens (`"null"`, `"undefined"`, `"none"`, `"n/a"`, `"nil"`, `"-"`, empty/whitespace) to ABSENT before resolution — applied here rather than only at the verb boundary so EVERY writeSingleFact caller gets the guard and the `resolved?.slug ?? entityRef` fallback can never adopt `"null"` as a slug. On a managed brain, after the withdrawal check and embedding, the fact publishes through `publishManagedEntityFacts` (`src/core/facts/managed-fact-write.ts`, the `managed_facts_entity` intent: fence row, index row and file together, dedup at publication, and the same-kind near-duplicate supersession rule via the intent's `supersede` flag, which strikes the old fence row and expires and links the old fact in the same transaction; an explicit per-fact context is kept; an entity without a live page lands database-only). `writeFactsToFence` (`fence-write.ts`) takes the same path on a managed brain, after dropping withdrawn claims.+- `src/core/facts/managed-fact-write.ts` — `publishManagedEntityFacts(engine, sourceId, entity, facts)` builds one managed facts session per visibility (request identity derived from the write, so a retried job replays its receipt), keeps a caller's vector only when it matches the brain's facts embedding signature, and returns ids in input order; `managedFactWritePreflight` runs the same session checks before a caller's model call.- `src/core/ops/` — the operations contract's module directory (the meat behind the `operations.ts` façade). `contract.ts` is the foundation contract: the error envelope (`ErrorCode`/`OperationError`/`verbError`), the shared param/logger/auth/context types, and the `Operation` interface — re-exported wholesale by the façade. `context.ts` carries the context validators + scope resolvers: the upload/slug/filename validators, the subagent and bound-client slug fences, and the source-scope resolution ladder (some internal helpers are exported only here and deliberately NOT re-exported from the façade — import those from `context.ts` directly). The remaining modules are one-per-op-domain (`pages.ts`, `search.ts`, `takes.ts`, `tags.ts`, `links.ts`, `timeline.ts`, `admin.ts`, `skills-catalog.ts`, `sync-status.ts`, `raw-data.ts`, `chunks.ts`, `ingest-log.ts`, `files.ts`, `jobs.ts`, `orphans.ts`, `calibration.ts`, `salience.ts`, `facts.ts`, `sources.ts`, `transcripts.ts`, `insights.ts`, `image.ts`, `extraction.ts`, `code-intel.ts`, `chronicle.ts`, `embedding-migration.ts`, `request-tools.ts`, `schema-packs.ts`, `skillopt.ts`), each exporting a `<domain>Operations` map that the façade spreads into the single `operations` export. Add a new op in the matching domain module — an existing domain needs no façade change; a brand-new domain module gets one spread line in `operations.ts`. `facadeExpansion` in `scripts/generate-flag-registry.ts` maps the façade to this whole directory so every module's `--flag` text stays on the command flag-scan surface.diff --git a/docs/architecture/key-files/core-utilities-1.md b/docs/architecture/key-files/core-utilities-1.mdindex bcf822f404..c45ed77433 100644--- a/docs/architecture/key-files/core-utilities-1.md+++ b/docs/architecture/key-files/core-utilities-1.md@@ -53,4 +53,5 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/preferences.ts` — preferences.json + the migration ledger (`migrations/completed.jsonl` append/read helpers; `appendCompletedMigration`, `loadCompletedMigrations`). Path resolution delegates to `config.ts:gbrainPath()`, so GBRAIN_HOME follows the ONE canonical convention: it is a PARENT dir and `.gbrain` is appended (`GBRAIN_HOME=/tmp/x` → `/tmp/x/.gbrain/migrations/...`). `copyForwardLegacyFile` migrates a legacy layout that placed these files directly under `$GBRAIN_HOME` once per file on first touch: atomic (temp + linkSync, EEXIST = concurrent winner), JSON-validated for prefs, chmod 0600, copy-not-move for binary rollback, once-per-process warning; a valid-but-uncopyable legacy file (read-only home) is READ IN PLACE so a transient failure can't drop a `minion_mode` opt-out or migration history. One-shot by design — mixed-version writers diverging post-snapshot is an accepted, documented limitation.-- `src/core/remediation-checkpoint.ts` — `doctor --remediate` checkpoint at `~/.gbrain/remediation/<plan_hash>.json`. `plan_hash = sha256(JSON.stringify(sorted recommendation ids)).slice(0,16)`. Schema-versioned, atomic `.tmp + rename`. `gbrain doctor --remediate --resume <plan_hash>` (no arg picks newest matching) loads it and skips completed steps. Mismatched plan_hash refuses with a paste-ready message. Cleared on clean completion. Pinned by 13 unit cases.+- `src/core/remediation-checkpoint.ts` — `doctor --remediate` checkpoint at `~/.gbrain/remediation/<plan_hash>.json`. `plan_hash = sha256(JSON.stringify(sorted recommendation ids)).slice(0,16)`. Schema-versioned, atomic `.tmp + rename`. `gbrain doctor --remediate --resume <plan_hash>` (no arg picks newest matching) loads it and skips completed steps. Mismatched plan_hash refuses with a paste-ready message. Cleared on clean completion. Optional resume-contract fields written by the doctor CLI: `brain_id` (a resume against another brain refuses), `max_usd` (reused by `--resume` without `--max-usd`), `include_repairs`, cumulative `spent_usd` and the original step `manifest` (`job_ids`, `repair_kinds`); a checkpoint without them keeps the legacy exact-plan-hash resume. Pinned by 13 unit cases plus `test/recovery-layer.test.ts`.+- `src/core/remediation/` — the doctor remediation library (`computeRemediationPlan`, `runRemediation`, shared by doctor, onboard and MCP `run_onboard`). `repairs.ts`: `planRepairSteps` previews every registered repair kind brain-wide and returns PROTECTED steps (`requires_user_agreement`, exact `command`, `paid`, `est_usd_cost`), independent of the score target; `runRepairSteps` applies them in-process for a trusted local caller only, refusing a paid step whose estimate exceeds the remaining cap before it starts and continuing with free steps; `effect` kinds reserve their estimate against the cap up front (the consumer embeds outside the tracker), and an `inline` step is marked `budget_exhausted` when the tracker fired even if a callee swallowed the throw. The plan hash includes the brain id so brains on one host never share a checkpoint file. `run.ts`: `opts.repairs` (doctor CLI only) plans the repair steps and runs them when `include` is set, even when the target is unreachable (job steps are skipped then); a remote `include` refuses `permission_denied`. The cap is cumulative (`spent_usd` from the checkpoint plus this run's tracker); a refused paid step ends the run budget-exhausted and saves the checkpoint. Callers that omit `repairs` keep the job-only behavior.diff --git a/docs/architecture/key-files/core-utilities-2.md b/docs/architecture/key-files/core-utilities-2.mdindex 5c13f8294a..f301ee923c 100644--- a/docs/architecture/key-files/core-utilities-2.md+++ b/docs/architecture/key-files/core-utilities-2.md@@ -3,7 +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/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` formats a pending-count line (the post-upgrade recovery banner reports `safe_index_pending` instead). `contextual-mode.ts`: a `publication: 'projection'` kind (#5621) that stamps `contextual_retrieval_mode` + `corpus_generation` on sealed live markdown pages with a NULL mode through `resolveImportContextualMode` (`src/core/import-contextual-mode.ts`, the resolver `importFromContent` also uses, strict source-row read), then under the page guard clears only vectors whose recorded embedding input the stamped convention no longer accepts (the #5553 rule) and re-embeds that page once unless `--no-embed`; unsealed pages are the `unsealed_projection` residual. `connector-checkpoints.ts`: a `publication: 'projection'` bookkeeping kind (#5686, `embeds: false`) that deletes connector checkpoint rows and retry pointers no registered source can load and that are older than 7 days, keeping rows a non-terminal request or recorded pending set references; brain-wide. `registry.ts`: `REPAIR_REGISTRY` (one entry per `REPAIR_KINDS` name in `--all` order: handler, help summary, `embeds` — `effect` when the publication's embedding effect re-embeds each page outside the run, `inline` when the kind embeds in-process and honors `--no-embed`, `none` for bookkeeping kinds — and the doctor `checks` it clears), `repairForCheck`, `repairApplyCommand` and `repairRunner`, the one trusted local runner that both `gbrain repair` and doctor remediation use; a new kind plugs in by adding its name to `REPAIR_KINDS` and one registry entry. Tests: `test/repair-command.test.ts`, `test/derived-visibility-repair.test.ts`, `test/safe-chunk-reseal.test.ts` (PGLite and Postgres), `test/repair-contextual-mode-5621.serial.test.ts` (PGLite and Postgres), `test/repair-flags.test.ts`.- `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()`.diff --git a/docs/architecture/key-files/files-and-sync-1.md b/docs/architecture/key-files/files-and-sync-1.mdindex f15454f895..27ff3d8cdd 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). 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` reconciles tags by provenance (`tags.tag_source`, migration v175): frontmatter tags go through `addTag(..., { tagSource: 'frontmatter' })`, and a row still marked 'frontmatter' whose tag left the frontmatter is deleted in the import transaction. Every other `addTag` stamps 'added' (add_tag, enrichment, the code importer) and is never import-deleted, so `gbrain reindex --markdown` keeps enrichment tags; legacy NULL rows are adopted only while the frontmatter still lists them; prepared (managed) imports keep add-only tags, matching the union their canonical file renders. Pinned by `test/reindex-preserve-tags.test.ts`, `test/import-frontmatter-tag-removal.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 OWN origin proves it moved (#5675): that origin is the `file://` path `importFromFile` records in `pages.source_uri` (never replacing non-file provenance), else the source's configured root (`local_path`, or the default source's legacy `sync.repo_path`). An origin that still exists moves only when it is this very file under another relative path (overlapping roots converge); a gone origin needs this file under that same root, and differing content also needs the same file name or title, so a missing path under another root, or a new note reusing a deleted note's template id, never renames a live page. `updateSlug` carries the row (page id, links, facts incl. `entity_slug`/`source_markdown_slug`, `page_aliases`, 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). An inline markdown re-import embeds only chunks whose embedding input changed: `planEmbeddingReuse` (keyed on chunk source + exact text) reuses a stored vector when the old index is sealed (`requireSafeChunks`), the page's `embedding_signature`, contextual mode, `corpus_generation` and (under the title wrapper) sanitized title are unchanged, and neither the old nor the new body holds protected fences; prepared, `--no-embed`, `--force-rechunk` and post-commit-embedding imports reuse nothing (`test/import-markdown-embedding-reuse.test.ts`). Offset-less frontmatter datetimes are read in the brain's `brain.timezone` (IANA, validated by `gbrain config set`; unset or invalid = UTC; the YAML parser tags naive timestamps with `NAIVE_DATETIME` so the wall-clock reading survives), while date-only values stay UTC calendar dates (`test/effective-date-brain-timezone.test.ts`). `effective_date` for an undated page falls back to `fallbackCreatedAt` (stored fallback date, else the earliest of the file's birth/modification time and — when `sync.git_first_commit_dates` is on — its git first-commit date via `fileTimes`, else now; `src/core/git-first-commit.ts` maps paths in one `git log --diff-filter=A` pass per `runImport`, skipping shallow clones; `test/effective-date-git-first-commit.test.ts`), 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). Every markdown import resolves and stamps `contextual_retrieval_mode` and `corpus_generation` with the canonical write, `--no-embed` included (#5621), so later embed passes reproduce the page's wrapping; a failed source-policy read fails the import unless the row or table is missing (`SourceRowNotFoundError`, `isUndefinedTableError`). 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` reconciles tags by provenance (`tags.tag_source`, migration v175): frontmatter tags go through `addTag(..., { tagSource: 'frontmatter' })`, and a row still marked 'frontmatter' whose tag left the frontmatter is deleted in the import transaction. Every other `addTag` stamps 'added' (add_tag, enrichment, the code importer) and is never import-deleted, so `gbrain reindex --markdown` keeps enrichment tags; legacy NULL rows are adopted only while the frontmatter still lists them; prepared (managed) imports keep add-only tags, matching the union their canonical file renders. Pinned by `test/reindex-preserve-tags.test.ts`, `test/import-frontmatter-tag-removal.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 OWN origin proves it moved (#5675): that origin is the `file://` path `importFromFile` records in `pages.source_uri` (never replacing non-file provenance), else the source's configured root (`local_path`, or the default source's legacy `sync.repo_path`). An origin that still exists moves only when it is this very file under another relative path (overlapping roots converge); a gone origin needs this file under that same root, and differing content also needs the same file name or title, so a missing path under another root, or a new note reusing a deleted note's template id, never renames a live page. `updateSlug` carries the row (page id, links, facts incl. `entity_slug`/`source_markdown_slug`, `page_aliases`, 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). An inline markdown re-import embeds only chunks whose embedding input changed: `planEmbeddingReuse` (keyed on chunk source + exact text) reuses a stored vector when the old index is sealed (`requireSafeChunks`), the page's `embedding_signature`, contextual mode, `corpus_generation` and (under the title wrapper) sanitized title are unchanged, and neither the old nor the new body holds protected fences; prepared, `--no-embed`, `--force-rechunk` and post-commit-embedding imports reuse nothing (`test/import-markdown-embedding-reuse.test.ts`). Offset-less frontmatter datetimes are read in the brain's `brain.timezone` (IANA, validated by `gbrain config set`; unset or invalid = UTC; the YAML parser tags naive timestamps with `NAIVE_DATETIME` so the wall-clock reading survives), while date-only values stay UTC calendar dates (`test/effective-date-brain-timezone.test.ts`). `effective_date` for an undated page falls back to `fallbackCreatedAt` (stored fallback date, else the earliest of the file's birth/modification time and — when `sync.git_first_commit_dates` is on — its git first-commit date via `fileTimes`, else now; `src/core/git-first-commit.ts` maps paths in one `git log --diff-filter=A` pass per `runImport`, skipping shallow clones; `test/effective-date-git-first-commit.test.ts`), 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/google-and-loops.md b/docs/architecture/key-files/google-and-loops.mdindex 325973b4f1..772548244d 100644--- a/docs/architecture/key-files/google-and-loops.md+++ b/docs/architecture/key-files/google-and-loops.md@@ -25,7 +25,7 @@ Historical Gmail repair selects explicit nested MIME metadata fields, excluding- `src/core/google/google-render.ts` — pure render functions (`{relPath, markdown}` out; no I/O, no engine): thread pages under `emails/YYYY/MM/` (type email), events under `calendar/YYYY/MM/` (type meeting), contacts under `people/` (type person). Gmail deep links are code-generated via the typed `emailCitation` scaffold, never LLM-composed. The noise/signature rules `recipes/email-to-brain.md` specifies as prose for agent-authored collectors are implemented here — keep the recipe and this module in sync. `isCalendarSystemMail({calendarMethod, subject})` gates BOTH loop detectors: the PRIMARY signal is a `calendarMethod` in the `CALENDAR_METHODS` allowlist (RFC 5546 — REQUEST, REPLY, CANCEL, PUBLISH, COUNTER, DECLINECOUNTER, REFRESH, ADD; case-insensitive); an empty or unrecognised method is NOT a stamp and falls to the subject fallback, which is anchored to the start of the subject, refuses any Re:/Fwd: prefix, and matches only Calendar's OWN localised headers (`Invitation:`, `Updated invitation:`, `Accepted:`, `Declined:`, `Tentative:`, `Canceled event:` + localised equivalents) — a generic word like `Notification:` is a human/vendor subject and never matches. `renderThreadPage` stamps `participants:` (every address on the thread) AND `senders:` (sorted unique message AUTHORS only — the list `loops mute sender` gates on, so muting one person cannot silence a whole group thread). Pinned by `test/google-render.test.ts`.- `src/core/google/google-source.ts` — the Google API source sweep. Unmanaged mode materializes Markdown under the source directory and imports through the standard chunks/aliases/links pipeline; managed mode uses journaled connector admission. Sweep order contacts → calendar → gmail: alias rows must exist before the loop detector resolves counterparties. Per-service independent cursors: contacts/calendar syncToken commits only after that service's fully-successful sweep (410 GONE drops the token and re-runs windowed); gmail delta rides history.list with an expired-history windowed fallback; the INITIAL backfill drains newest→oldest with a batch-committed floor cursor so a killed 50k-message backfill resumes at the floor instead of restarting, and the historyId anchor is captured BEFORE the backfill so the delta lane takes over with zero gap (overlap re-renders are idempotent). Emits the `sync.google_materialize` progress phase (docs/progress-events.md). Access resolves per source config: the vault (default), a token-printing command (`g_access: command` — gog/gcloud/gateway; identity entry synthesized, scope preflight trusts the configured services, send-as aliases fetched live best-effort), or a named env var (`g_access: env`). Secrets never land in `sources.config` (the command/env NAME is config; tokens are not). Honesty invariants: `last_sync_at` is gated on the GMAIL sweep's success (it feeds `gbrain waiting`'s trust-critical staleness gate, which protects loop freshness — a gmail sweep with real thread failures must not advance it); contacts/calendar failures mark the run `partial` but do not block the stamp, and a source without gmail in its services stamps unconditionally. A thread whose fetch fails on consecutive sweeps lands in the poison ledger and is skipped (steady-state runs honor the ledger; `--full` retries with a fresh one), so one bad thread can't wedge the sync while a poison-skip alone doesn't count as failure. Contact reconcile resolves by contact resourceName (DB lookup by contact id FIRST): deletion tombstones carry only `resourceName + deleted` (no names — slug derivation yields null) and a renamed contact derives a DIFFERENT slug, so both must land on the existing page by id, never by slug. The calendar sweep binds its sync token to its calendar: `sweepCalendar` compares `state.calendar_id` (legacy state without it is treated as primary's) with the configured `calendarId`; on a mismatch it logs `[google] calendar changed (<old> → <new>)`, discards the token and takes the windowed first-sync path (no `syncToken` on the wire), and a freshly banked token stores the calendar id beside it — pairing a re-pointed source with the previous calendar's cursor would import a foreign delta. Pages from the previous calendar are not reconciled on the switch (logged; a filed follow-up). `enqueueLoopsExtraction` enqueues EVERY eligible thread (newest first) under a waiting-depth budget `LOOPS_EXTRACT_ENQUEUE_CEILING − waiting` that counts only THIS source's waiting `loops_extract` jobs (`data->>'sourceId'`), so one account's stalled backlog cannot pin another source's budget at 0; overflow is a logged deferral (a deferred thread re-candidates when it changes) and a failed probe fails open. The budget probe counts PENDING rows — `status IN ('waiting','delayed','active')` — so a retry backlog parked in `delayed` during a flapping provider cannot stack past the ceiling. With no chat provider available (`isAvailable('chat')` false) the enqueue is skipped entirely and one stderr line per sweep names the reason and the count; pages still import and the threads re-candidate on their next touch or a `--full` sweep. Managed Google API sync uses journaled connector checkpoints; an unbound source is explicitly `connector_database`, while a bound source publishes canonical files. Identity-query storage failures do not become successful absence or advance the checkpoint. Unsupported Git/dry-run flags refuse before credentials/network; legacy materialization remains the unmanaged path.- `src/core/google/loop-detect.ts` — the zero-LLM thread-state machine: last substantive message inbound + user in To: + unanswered ≥24h → `unanswered_inbound`; last outbound + contains a question + unanswered ≥72h → `unanswered_outbound`; a reply closes the loop (`closed_by: reply_detected`). Precision IS the product: noise senders, list mail (List-Unsubscribe), CC-only delivery, FYI/forwards without a question, self-threads, and muted senders/threads never open loops — pinned by the labeled fixture corpus in `test/google-loop-detect.test.ts` (every false-positive class gets a fixture before its fix). Pure verdict function + a thin apply step called per touched thread from the sync; the apply step must never fail the sync.-- `src/core/google/loops-extract.ts` — the LLM half of the open-loop engine: ONE extractor per recent thread page projects each commitment into THREE substrates in the same pass — the `open_loops` row (dedup `commit:<sha8>`), a facts row via writeSingleFact (kind=commitment, fence-first, deduped; its id lands on `open_loops.fact_id` so entity cards / recall / context_pack see the commitment through existing read paths with zero new read code), and a typed edge thread-page → person-page (`owes_to` / `awaiting_reply_from`) for relational search. `extract_facts` never runs separately on google-source email pages. Guardrails: injection-hardened input, ALL-or-nothing parse barrier (a malformed model response writes NOTHING), a structural eligibility gate (`loopExtractionEligibility` — Gmail labels, `List-Unsubscribe`, calendar part, who wrote the message; no vendor lists) plus the per-source waiting-depth enqueue budget (`LOOPS_EXTRACT_ENQUEUE_CEILING`, a spend backstop — see `google-source.ts`), only the last `LOOPS_EXTRACT_WINDOW_DAYS` (30) of mail (the deep backfill is never extracted), kill switch `loops.extraction_enabled` (default ON for google sources). Suppressions gate the lane before any model/facts/edge write: a muted thread id, or a muted SENDER — `fm.from` ∪ `fm.senders`, every address that AUTHORED a message, so a muted counterparty who wrote earlier in the thread still suppresses — returns `reason: 'suppressed'`; recipients/CC never count (muting one person must not hide everyone else's commitments in a group thread, and an outside sender must not be able to dodge extraction by CC'ing a muted address). Pages without a `senders:` field fall back to `fm.from` alone until their next re-render. Eligibility computes the substantive (non-noise, non-calendar) message set FIRST and `owner_participated` requires the owner to have written a SUBSTANTIVE message — a pure-calendar thread the owner RSVP'd to stays `no_substantive_messages`. When the chat provider is unavailable, `runLoopsExtract` throws `LoopsExtractRetryableError` (reason `llm_unavailable`) rather than returning a skipped result: a completed no-work row would hold the revision-keyed idempotency slot forever, while a retried-then-dead row frees it so the same revision re-enqueues on the next sweep. Eligible managed loop-extraction jobs refuse with `writer_coordinator_required` before chat; disabled, missing-page and suppressed cases retain their existing no-work outcomes.+- `src/core/google/loops-extract.ts` — the LLM half of the open-loop engine: ONE extractor per recent thread page projects each commitment into THREE substrates in the same pass — the `open_loops` row (dedup `commit:<sha8>`), a facts row via writeSingleFact (kind=commitment, fence-first, deduped; its id lands on `open_loops.fact_id` so entity cards / recall / context_pack see the commitment through existing read paths with zero new read code), and a typed edge thread-page → person-page (`owes_to` / `awaiting_reply_from`) for relational search. `extract_facts` never runs separately on google-source email pages. Guardrails: injection-hardened input, ALL-or-nothing parse barrier (a malformed model response writes NOTHING), a structural eligibility gate (`loopExtractionEligibility` — Gmail labels, `List-Unsubscribe`, calendar part, who wrote the message; no vendor lists) plus the per-source waiting-depth enqueue budget (`LOOPS_EXTRACT_ENQUEUE_CEILING`, a spend backstop — see `google-source.ts`), only the last `LOOPS_EXTRACT_WINDOW_DAYS` (30) of mail (the deep backfill is never extracted), kill switch `loops.extraction_enabled` (default ON for google sources). Suppressions gate the lane before any model/facts/edge write: a muted thread id, or a muted SENDER — `fm.from` ∪ `fm.senders`, every address that AUTHORED a message, so a muted counterparty who wrote earlier in the thread still suppresses — returns `reason: 'suppressed'`; recipients/CC never count (muting one person must not hide everyone else's commitments in a group thread, and an outside sender must not be able to dodge extraction by CC'ing a muted address). Pages without a `senders:` field fall back to `fm.from` alone until their next re-render. Eligibility computes the substantive (non-noise, non-calendar) message set FIRST and `owner_participated` requires the owner to have written a SUBSTANTIVE message — a pure-calendar thread the owner RSVP'd to stays `no_substantive_messages`. When the chat provider is unavailable, `runLoopsExtract` throws `LoopsExtractRetryableError` (reason `llm_unavailable`) rather than returning a skipped result: a completed no-work row would hold the revision-keyed idempotency slot forever, while a retried-then-dead row frees it so the same revision re-enqueues on the next sweep. On a managed brain `managedFactWritePreflight` checks the managed fact authority and canonical owner before chat (an unaccepted writer refuses with `writer_coordinator_required`), and the commitment fact publishes through writeSingleFact's coordinator path; disabled, missing-page and suppressed cases retain their existing no-work outcomes.- `src/core/loops/loops-store.ts` — SQL accessors for the `open_loops` + `loop_suppressions` tables over `engine.executeRaw` with IDENTICAL SQL text on both engines (parity by construction, the sources-ops.ts pattern — no per-engine method twins). JSONB discipline: evidence binds through `$N::text::jsonb`, never a bare `::jsonb` cast over JSON.stringify. Loops close by state transition, never delete: reply-driven auto-close flips status to `done` and stamps `closed_by`, keeping the audit trail. The upsert's DO UPDATE carries a manual-close guard in its WHERE: a closed row (done/dropped/stale) only reopens on GENUINELY newer activity, so a routine sweep re-seeing the same thread never resurrects a hand-closed loop, and the staleness auto-close (`closed_by: 'staleness'`) is likewise guarded against the upsert's reopen. `removeSuppression(engine, sourceId, kind, value)` is the exact inverse of the mute write — deletes the one `(source_id, kind, value)` row with the same lower-casing, returns `{removed: boolean}` (false = was not muted, callers treat it as a no-op success), and never reopens loops: suppressions gate NEW detection only.- `src/core/ops/loops.ts` — the op surface: `open_loops` (read), `loops_close` (write), `loops_mute` (write). `open_loops` is deliberately NOT localOnly (hosted serves it over HTTP to the authenticated owner); instead it applies fail-closed evidence redaction for `ctx.remote !== false` — counts, counterparty, summary, due date only; verbatim quotes, Gmail deep links, and the injectable `text` digest are trusted-local only. The result carries the google sources' last-successful-sync ages + a `stale` flag (>24h) so callers can refuse stale-but-confident output on a trust-critical surface. Per-call scope params `source_id`/`all_sources` resolve through `resolveRequestedScope` (an MCP client bound to another source can reach the google source's loops; remote callers stay in-grant, out-of-grant `source_id` is denied); a scope with NO google source returns `no_google_sources: true` and the digest says the engine has nothing to read instead of a false "You are clean". Scope is fail-closed too: an UNSCOPED remote `open_loops` read is refused outright (the op must not rely on transports to enforce it — an unscoped remote read would span every source), and the write ops (`loops_close`, `loops_mute`, `loops_unmute`) require a single-source remote scope that matches the caller's grants — trusting a caller-supplied `source_id` for a remote write would let any remote client plant (or lift) suppression rows cross-source; `loops_unmute` reverses a suppression via `removeSuppression` and reports `{removed}` honestly.- `src/commands/google.ts` — `gbrain google connect|status|calendars|disconnect` (+ `setup` and `attachments` dispatch). Agent-first contract: every subcommand supports `--json` emitting `{ ok, status, next_action: { command?, user_message? }, error? }` (`calendars` adds `account` + `calendars[]` — id/summary/primary/accessRole — and carries the `sources add --calendar-id` template in `next_action.command`; it resolves a lone connected account, exits 2 when there are none or several without `--account`, and throws `not_connected` for an unknown `--account`); human copy the harness must relay verbatim is fenced in `[SHOW USER] ... [/SHOW USER]` blocks; secret intake is `--client-json <path|->` (preferred) / env `GOOGLE_CLIENT_ID`+`GOOGLE_CLIENT_SECRET` / TTY prompt, with raw argv flags accepted but documented last-resort; connect is an idempotent state machine (detects what exists, performs only the missing step — re-running is the documented fix for most errors). Credential commands are engine-free; `status` has a best-effort linked-sources listing, while `attachments backfill` requires the explicitly selected local managed brain. Funnel events append to `~/.gbrain/integrations/google/heartbeat.jsonl`; account addresses are hashed to a short non-reversible tag, never raw. The vault entry's `meta.scopes` records what Google ACTUALLY granted (the token response's `scope` — the consent screen lets users uncheck scopes; the requested set is only the fallback), which is what lets downstream preflights report `scope_missing` instead of opaque per-sweep 403s.diff --git a/docs/architecture/key-files/providers.md b/docs/architecture/key-files/providers.mdindex a32130920f..6283b6ea92 100644--- a/docs/architecture/key-files/providers.md+++ b/docs/architecture/key-files/providers.md@@ -5,7 +5,8 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/embedding-readiness.ts` — bounded source-aware recovery through canonical projection snapshots, queued intent, preparation and guarded installation. Global readiness remains archive-visible. Plain stale repair selects active sources for recovery and separately reports archived stranded work, so live pages can progress without pretending the whole brain completed. `countArchivedEmbeddingWork` classifies archived NULL vectors, non-NULL hash drift, signature work, contentful chunkless pages and, for migration, pending projections before authorization. Repair queues and snapshots require a live source under the existing source-before-page guard; unsupported pages remain blocked, never revision-stamped. The invalidation SQL additionally excludes unsealed projections.- `src/core/embedding-migration-retention.ts` — fail-closed retained-vector rebuildability check shared by migration preflight, direct apply, schema transition, pinned-column repair and invalidation/config transactions. Transaction-local SHARE locks freeze source/page/vector/withdrawal/config eligibility during the census and mutation. Sealed importer text chunks can be embedded and oversized chunks healed without regenerating their source projection; unsealed unsupported media still refuses. Width changes protect archived, skipped, deleted and unrebuildable retained page vectors; same-width checks match the shared false-stamp predicate, signature gate and current-space test. Archived pending work, including same-target content drift, metadata-only restamping, NULL vectors and chunkless pages, refuses before authorization or provider work; correct target-stamped archived vectors, including grandfathered NULL hashes, are retained controls. Companion retention checks follow actual schema/pinned-width changes and the same-target persisted migration marker; the guard returns the locked companion-clear decision consumed by the writer, ignoring a different target's completed-clear flag. Schema-only work leaves takes untouched. Existing fact eligibility and deliberate expiry/supersession/audit/withdrawal policy remain unchanged. Unknown registry, width or census fails closed. The source census includes archive state, but embed leases are not archive coordination. Synthetic two-engine regressions cover preservation refusals, real imported-image migration, same-target companion preservation, retarget/first-clear refusal and fail-closed metadata. Completion counts remain archive-visible; refusal never restores a source automatically.-- `src/core/embedding-migration-budget.ts` — finite authorization in the existing migration marker, conservatively debited under the acquired leases before each provider attempt with the existing BudgetTracker. Resume preserves uncertain dispatched liability; unknown prices or missing input bounds refuse. Marker corruption cannot erase a versioned authorization. Only an explicitly reauthorized legacy marker without authorization fields can be replaced.+- `src/core/embedding-migration-budget.ts` — finite authorization in the existing migration marker. Each provider attempt reserves its maximum input price under the acquired leases and a `FOR UPDATE` on the marker row, and records a pending entry keyed by attempt id; `settle(usage)` takes the same lock and replaces the reservation with the reported usage (refund or overshoot). Idempotent per (`authorization_generation`, attempt id): a repeated or stale-generation settle is a no-op, so a crash before settlement keeps the maximum. Missing usage keeps the maximum. Usage above the reservation debits actual, adds `overshoot_usd` and sets `halted`, which refuses further dispatch until an explicit `--max-cost-usd` renewal. `authorizeMigrationBudget(..., worstCase)` throws `MigrationBudgetRefusal` (`embedding_budget_below_worst_case`, with cap, worst case, retained debits, the filled `--max-cost-usd` command and the `write-refusals.md` anchor) before writing any state when the cap is below debits + worst case. Refusal copy prints the operator's cap, never a remainder. Resume preserves every debit; unknown prices or missing input bounds refuse. Marker corruption cannot erase a versioned authorization. Only an explicitly reauthorized legacy marker without authorization fields can be replaced.+- `src/core/embedding-migration-worst-case.ts` — `planMigrationWorstCase(engine, plan, { rerankerModel })`: Σ per-request maximum input from `embed-batch-plan.ts` over what the run sends (target probe, the drain's two probes, stale chunks per page (including content drift: a stored text hash that no longer matches) split by `healOversizedChunks` at the target chunk size over the complete page (a split re-indexes siblings, so every healed chunk of that page counts) and wrapped with `wrapChunkTextsForStoredMode`, the chunks projection recovery and the chunkless heal will create — replayed through `readProjectionSnapshot` + `preparePageProjection` at the current chunk size then the target-size heal, and directly at the target size, keeping the larger ceiling, replacing those pages' existing chunks — stale facts in 100-row per-source batches, three smoke-check queries, the reranker probe when switching), priced with operator overrides. `usd` is null only when the embedding model is unpriced; an unpriced reranker lands in `unpriced_models` and the embedding bound is still enforced. Owns the migration and reranker probe texts. Computed at plan time for the printed estimate and again under the migration locks for the refusal.- `src/core/facts/embedding-identity.ts` — active fact eligibility and stale model/text/width census shared by migration and fact repair. Legacy identity stays unknown. Both engine writers accept explicit `embedding_model` and compute the exact text hash; duplicate vector selection requires matching caller identity. `embed-facts.ts` installs under source-incarnation, row-version, withdrawal and configuration guards, retaining the outer migration invocation budget when nested.- `src/core/anthropic-pricing.ts` — bare-keyed Anthropic VIEW of `model-pricing.ts` (the `anthropic:` canonical entries with the prefix stripped). Kept distinct because many callers look up by bare Claude id and because `estimateMaxCostUsd(modelId, inTokens, maxOutTokens)` carries the null-on-miss contract the dream-cycle budget gate depends on (non-Anthropic ids return null; `BudgetMeter` tries `canonicalLookup` first and only falls back here, so it warns `BUDGET_METER_NO_PRICING` and runs unbounded only when canonical has no rates either). `estimateMaxCostUsd` routes bare/colon/slash ids through `splitProviderModelId`. Do NOT hand-edit prices here — the map is derived from canonical, so it cannot drift. `ANTHROPIC_PRICING` is consumed by `budget/budget-tracker.ts` and `cycle/budget-meter.ts`.@@ -19,7 +20,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `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.+- `src/core/embed-retry.ts` — embed retry/backoff primitives + the title-tier restamp helper. An `EmbeddingZeroNormError` (#4616) is never retried or classified transient; `embedBatchKeepingUsable` returns the usable vectors of a partially refused batch with the refusal, and still throws when nothing is usable. It stays 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.- `src/core/embed-skip.ts` — 5-site shared predicate for the soft-block embed-skip filter. Exports `shouldSkipEmbedding(frontmatter): boolean` (JS predicate for callers holding the page in memory), `EMBED_SKIP_SQL_FRAGMENT` (parameterized SQL clause shared by Postgres + PGLite via `executeRaw`), and `buildEmbedSkipMarker(reason: string)` (writes `frontmatter.embed_skip = {at: ISO_TIMESTAMP, reason}` so the JSONB shape stays uniform). The 5 sites: `embed.ts --stale`, `embed.ts --all`, the `embed-stale` Minion helper, plus both engines' `listStaleChunks` + `countStaleChunks`. Single source of truth so the filter cannot drift. Pinned by `test/embed-skip.test.ts` (cross-site invariant + JSONB shape).diff --git a/docs/architecture/managed-mutating-writers.tsv b/docs/architecture/managed-mutating-writers.tsvnew file mode 100644index 0000000000..633dbdaa52--- /dev/null+++ b/docs/architecture/managed-mutating-writers.tsv@@ -0,0 +1,73 @@+# Managed-brain census of mutating operations and CLI-only writers (fix wave 3).+# Every operation with `mutating: true` in the assembled registry needs a row; test/canonical-writer-inventory.test.ts enforces it.+# kind name class reason+# class: coordinator (publishes through the persistence coordinator), no_canonical_write (writes no guarded canonical table or file),+# early_refusal (refuses on a managed brain before any write), engine_guard (the managed writer trigger refuses its canonical write).+op remember coordinator submitRememberMutation admits a journaled page mutation.+op forget coordinator submitForgetMutation records a coordinated withdrawal.+op put_page coordinator submitPageMutation; unbound Postgres sources refuse unless persistence.unbound_write=database_only.+op delete_page coordinator submitPageMutation soft delete or trusted-local purge.+op restore_page coordinator submitPageMutation restores a recorded version.+op purge_deleted_pages coordinator purgeDeletedPagesCoordinated purges each expired tombstone through delete_page purge.+op capture coordinator submitPageMutation admits a journaled page mutation.+op cancel_write_request no_canonical_write Cancels a queued journal request; no canonical row changes.+op add_tag coordinator submitPageMutation admits a journaled page mutation.+op remove_tag coordinator submitPageMutation admits a journaled page mutation.+op add_link coordinator coordinatedManualLinkWrite: durable authority, withCoordinatedWrite, both endpoint page keys locked; database-only.+op remove_link coordinator coordinatedManualLinkWrite, same boundary as add_link.+op add_timeline_entry coordinator submitPageMutation admits a journaled page mutation.+op revert_version coordinator submitPageMutation admits a journaled page mutation.+op put_skill coordinator Shared-skill publication through the persistence journal.+op delete_skill coordinator Shared-skill publication through the persistence journal.+op set_skill_policy no_canonical_write Shared-skill policy row, epoch-guarded; no page content.+op prune_skill_revisions no_canonical_write Shared-skill revision retention only.+op retain_skill_revision no_canonical_write Shared-skill revision retention only.+op import_skill_proposal coordinator Imports a proposal through shared-skill publication.+op join_brain no_canonical_write Mount registration in local configuration.+op sync_brain_skills no_canonical_write Refreshes mounted skill copies outside the brain database.+op leave_brain no_canonical_write Mount removal in local configuration.+op sync_brain coordinator Managed sync admits each changed file through the coordinator.+op put_raw_data no_canonical_write raw_data side table; not guarded canonical content.+op log_ingest no_canonical_write ingest_log audit rows only.+op file_upload no_canonical_write File storage objects and their index rows, confined to the upload root.+op submit_job no_canonical_write Queues a minion job; its handler owns any write and its own boundary.+op cancel_job no_canonical_write Minion queue state only.+op retry_job no_canonical_write Minion queue state only.+op pause_job no_canonical_write Minion queue state only.+op resume_job no_canonical_write Minion queue state only.+op replay_job no_canonical_write Minion queue state only.+op send_job_message no_canonical_write Minion inbox rows only.+op submit_agent no_canonical_write Queues a subagent job; its tools write through put_page.+op think engine_guard Remote callers are read-only; a local --save persists through engine.putPage, which the managed writer trigger refuses on a managed brain.+op takes_add coordinator submitPageMutation takes intent.+op takes_update coordinator submitPageMutation takes intent.+op takes_resolve coordinator submitPageMutation takes intent.+op takes_supersede coordinator submitPageMutation takes intent.+op sources_add early_refusal Deliberate administrative refusal on managed brains; source topology changes through writer administration.+op sources_remove early_refusal Deliberate administrative refusal on managed brains; source topology changes through writer administration.+op request_tools no_canonical_write Persists the calling client's MCP tool surface on oauth_clients.+op connector_sync coordinator Managed connector sync admits pages and checkpoints through the coordinator.+op ontology_propose engine_guard mergeOntologyFact inserts into facts; the managed writer trigger refuses it on a managed brain.+op chronicle_backfill no_canonical_write Queues chronicle jobs; the chronicle extractor publishes through publishMaintenancePage.+op extract_entities early_refusal enrichment-service writes through direct importFromContent, which refuses on managed brains.+op extraction_review no_canonical_write Review queue state only.+op entity_identity_link no_canonical_write entity_identity side table.+op entity_identity_unlink no_canonical_write entity_identity side table.+op extract_facts coordinator The facts backstop publishes through the managed facts session on managed brains.+op forget_fact coordinator submitForgetMutation records a coordinated fact withdrawal.+op code_traversal_cache_clear no_canonical_write Derived traversal cache only.+op migrate_embeddings no_canonical_write Embedding projections under the migration budget; no canonical content.+op schema_apply_mutations no_canonical_write Schema-pack files outside the brain database.+op run_onboard no_canonical_write Runs remediation steps; each step keeps its own writer boundary.+op run_skillopt no_canonical_write Skill files and proposals outside the brain database.+op loops_close no_canonical_write open_loops state rows.+op loops_mute no_canonical_write Loop suppression rows.+op loops_unmute no_canonical_write Loop suppression rows.+cli src/commands/enrich.ts coordinator gbrain enrich preflights maintenance authority, then publishMaintenancePage per page.+cli src/commands/extract-conversation-facts.ts coordinator Bulk conversation facts commit through the coordinator capability after a derived-facts preflight.+cli src/commands/pages.ts coordinator gbrain pages purge-deleted runs purgeDeletedPagesCoordinated.+cli src/core/bootstrap/verify.ts coordinator gbrain bootstrap verify writes probes with put_page and purges them through delete_page purge.+cli src/core/google/loops-extract.ts coordinator Loop commitments publish through writeSingleFact's managed facts path.+cli src/core/facts/fence-write.ts coordinator Direct fence writes publish through publishManagedEntityFacts.+cli src/core/chronicle/extract-events.ts coordinator Chronicle events and their depth timeline rows publish through publishMaintenancePage.+cli src/core/persistence/purge-deleted.ts coordinator Shared purge used by the cycle, the purge job, the operation and the CLI.diff --git a/docs/architecture/topologies.md b/docs/architecture/topologies.mdindex 648369ff05..b40ecbbcc2 100644--- a/docs/architecture/topologies.md+++ b/docs/architecture/topologies.md@@ -485,6 +485,84 @@ parent, persistence home and stable lock/coordination directory together acrossrecreation. Storage preflight reports each location and can identify Linuxoverlay/tmpfs backing, but a mount shown as present is **not** attested durable.+### Claim and activate runbook++Managed mode cannot be turned off from the CLI (there is no deactivate command+yet, #5455), so treat activation as a one-way step. Take a database backup+first: for Postgres, `pg_dump` the brain database; for PGLite, stop every gbrain+process and copy the database directory.++Quiesce every writer on every host that uses this database before activating:++1. Stop `gbrain serve` (stdio and HTTP) on each host.+2. Pause autopilot on each host with `gbrain autopilot pause --reason "writer activation"`+ and confirm with `gbrain autopilot status`. The pause survives+ `gbrain upgrade` and `gbrain autopilot --install`; `gbrain autopilot resume`+ clears it afterwards.+3. Stop `gbrain jobs work` workers and supervisors that are not autopilot's.+4. Disable cron entries, Git hooks and harness hooks that run `gbrain sync`,+ `embed`, `extract`, `dream` or `import`.+5. Upgrade every remaining host to this release, even ones you only read from.++Then run the sequence, re-reading status between every step, because+`admin_state` rotates after every change and a stale value refuses with+`writer_admin_state_changed`:++```bash+gbrain sources writer status --brain host --json # note admin_state+gbrain sources writer claim default --brain host --path /absolute/canonical/source \+ --admin-intent writer_claim --expected-state <admin_state> --json+gbrain sources writer status --brain host --json # fresh admin_state+gbrain sources writer activate --brain host --confirm-quiesced --dry-run --json+gbrain sources writer activate --brain host --confirm-quiesced \+ --admin-intent writer_activate --expected-state <fresh admin_state> --json+```++After activation, managed sync requires `--no-pull` (Git pull/rebase needs an+explicit drained maintenance window) and refuses `--skip-failed` and+`--include-gitignored`; after fixing a failed item run+`gbrain sync --no-pull --retry-failed` with the same source and options. Resume+autopilot with `gbrain autopilot resume` and re-enable the hooks you stopped.++When activation refuses with `writer_not_quiesced` because of queued work, the+refusal names the blocking effect (effect id, kind, source, page and request id)+and the command that inspects it, `gbrain sources writer status <source> --json`.+A committed write whose queued embedding effect is never claimed cannot be+cleared by any command yet (`retry-effects` handles failed effects only);+`gbrain doctor` reports it as `stale_embedding_effects`.++### Writer admin lock++`gbrain sources writer lock` sets an opt-in, brain-level admin lock; while it+is set, writer claim, activate, transfer prepare and transfer accept refuse for+every caller with `writer_admin_locked`, whose hint tells an agent to stop and+ask the operator. Only these four administrative changes are blocked: ordinary+writes continue, including the automatic first-write claim on a PGLite brain.+There is no `--force`; the escape hatch is the local unlock. Remote callers can+neither lock nor unlock, and generic `gbrain config set`/`unset` (including+`--pattern`) refuse the reserved key `persistence.writer_admin_lock`. Dry runs+of the four operations refuse too. The lock guards against routine or accidental+agent administration; it is not a security boundary against a caller with the+same shell. Binaries older than this release do not consult it.+`gbrain sources writer status` shows `admin_lock` (whether it is set, when, and+by which host) and the selected brain.++To administer a locked brain, the operator runs, on the brain host:++```bash+gbrain sources writer unlock --brain host+gbrain sources writer status default --brain host --json # fresh admin_state+# ... the reviewed claim, activate or transfer commands above ...+gbrain sources writer lock --brain host+```++If administration fails midway, still run `gbrain sources writer lock` before+investigating, so no agent can retry the change meanwhile. `lock` refuses with+`writer_transfer_conflict` while a transfer is prepared but not accepted; finish+or abandon the transfer first. Shared-skill setup, which claims a checkout as+administration rather than as an ordinary first write, is refused while locked.+`lock` and `unlock` are idempotent and print the resulting state.+### Supported managed work and explicit repairOnce active, ordinary authorized local atom extraction, fact fences/backstop,@@ -549,14 +627,20 @@ consolidation uses a single source-scoped take/fact transaction. A retired orresolved matching take is skipped, not silently reopened. Only world-visiblefacts backed by live non-private evidence are eligible for public consolidation;this is no guarantee that private facts will be consolidated. Remote maintenance-authority is not added. Legacy fence reconciliation (`dream --phase-extract_facts`), bulk `extract-conversation-facts`,-`conversation_facts_backfill`, and `loops_extract` remain unsupported under-managed persistence, including preview paths that could spend. Their preflight-refuses with `writer_coordinator_required`; writer status and activation preview-list them in `unsupported_maintenance`. The restored `extract_facts` operation-and page backstop are separate from the legacy cycle fence reconciler. Do not-infer that every dream or job writer is restored from the named lanes above.+authority is not added. Fence reconciliation (`dream --phase extract_facts`,+including its expiry of deleted pages' facts), bulk `extract-conversation-facts`+and `conversation_facts_backfill` run on managed brains: their database-only+fact rows commit inside the coordinator's source capability under the page key,+like derived links, without a persistence request per page. The phantom redirect+publishes as two maintenance requests (`managed_maintenance_phantom_merge` on+the canonical page, which moves the phantom's rows by id, then+`managed_maintenance_phantom_delete` on the phantom). Direct fence writes,+`loops_extract` commitments and other `writeSingleFact` callers publish through+the `managed_facts_entity` intent. Each checks its local writer authority (and,+for file publication, the canonical owner) before model calls. Receipt pages+for these runs stay unmanaged-only. `unsupported_maintenance` in writer status+and activation preview is now empty. Do not infer that every dream or job+writer is restored from the named lanes above.Google and GitHub API sources route through managed connector checkpoints,not a Git cursor. A deliberately unbound API source uses revieweddiff --git a/docs/guides/embedding-migration.md b/docs/guides/embedding-migration.mdindex 5e5816fc85..ae695bff25 100644--- a/docs/guides/embedding-migration.md+++ b/docs/guides/embedding-migration.md@@ -74,10 +74,25 @@ even if a custom base URL still serves its old model.gate in [spend-controls](../operations/spend-controls.md)). Unlike the purecost gates there, `spend.posture=tokenmax` does **not** bypass this one:this gate guards both destructive work and bounded provider attempts.- `--yes` confirms the operation; it does not waive the cap. Retries retain- pre-dispatch debits, including requests with uncertain outcomes. Raising- the total cap explicitly authorizes more work. Unknown pricing or a- missing conservative provider input ceiling refuses before dispatch.+ `--yes` confirms the operation; it does not waive the cap. The plan prints a+ **worst-case authorization** beside the estimate: every planned provider+ request (probes, chunks per page, chunks that projection recovery will+ rebuild, fact batches, smoke-check queries) at its+ maximum input size, where a request's maximum is one token per UTF-8 byte+ of its texts. A cap below the worst case (plus any debits a resumed run+ already holds) refuses with `embedding_budget_below_worst_case` before any+ provider call or vector change; the refusal names your cap, the worst case+ and the exact `--max-cost-usd` value that covers it. Each attempt reserves+ its maximum, then settles to the provider's reported usage, so the unused+ headroom returns and retries and batch splits draw from it. A provider+ token-limit rejection bills nothing and releases its reservation, so the+ gateway's split of that batch fits inside the same worst case. A response+ without usage, or a crash before settlement, keeps the maximum debit.+ Usage above the reservation is debited, recorded as overshoot, and stops+ further dispatch until you re-run with `--max-cost-usd`. A reranker without+ a price is left out of the worst case with a warning; its probe refuses+ without dispatch and the switch is reported as failed. Raising the total+ cap explicitly authorizes more work. Unknown pricing refuses before dispatch.3. **Live probe.** After checking environment and embedding-enabled policy,one tiny embed against the TARGET provider before anyvector invalidation — validates the API key, model id, and dimension@@ -168,7 +183,7 @@ brain selection when inspecting status; do not blindly retry or reset the migrat| Failure | Action before retrying | Partial state to inspect || --- | --- | --- || `locked` | Check the existing holder; let it finish or deliberately stop it, then inspect status. | A previous holder may have committed progress or debits. |-| `refused` | Resolve the named environment mismatch or deliberately choose whether to resume or retarget. | An earlier migration and its authorization may still be live. |+| `refused` | Resolve the named environment mismatch or deliberately choose whether to resume or retarget. For `embedding_budget_below_worst_case`, re-run with the printed `--max-cost-usd` value or keep the current model. | An earlier migration and its authorization may still be live. The budget refusal itself changed nothing. || `probe_failed` (operation: `failed`) | Check provider configuration and the reported dimensions before authorizing another attempt. | An authorized probe debit may remain even when invalidation did not run. || `apply_failed` (operation: `failed`) | Inspect the specific blocker first. Restore an archived source with `gbrain sources restore <id>` only after owner approval; unsealed unsupported projections need their original importer. Resolve configuration, database, or ownership errors before retrying. | Canonical repairs, schema/config changes, vectors, and debits may have committed in earlier phases. || `retained_vectors_blocked` within `apply_failed` (operation: `failed`) | Inspect both the retained page-chunk/fact/take counts and the archived-page blocked-work count. Migration can lack an eligible rebuild path even when vectors are already missing. Preserve the data and obtain the owner's retention/recovery decision before retrying. | Refusal does not undo earlier committed progress or authorization debits. |@@ -212,10 +227,12 @@ of prior debits. The CLI does not infer that a failure means zero writes.`gbrain migrate embeddings --to openai:text-embedding-3-small --dim 1536 --reranker off --max-cost-usd 1 --yes --json`.The dollar amount is an operator-chosen total limit, not a price quote.A batch size is not a spending cap. The preview character-based cost is- an estimate; admission reserves conservative per-attempt token ceilings.+ an estimate; the cap must cover the printed worst-case authorization, and+ each attempt reserves its maximum input size before settling to reported usage.4. An incomplete or failed apply exits nonzero. Read `--status` beforerepeating the same command. Already-correct chunks/facts are not sent- again. A crash, timeout or provider refusal does not refund a debit.+ again. A crash, timeout or provider refusal without reported usage keeps+ that attempt's maximum debit.If the cap is exhausted, fix the underlying provider problem and explicitlyraise the **total** authorization to continue. Do not reset the marker.Projection recovery may have made durable progress even when migrationdiff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex 316c2b172c..d1aac99a26 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -2,8 +2,13 @@`gbrain doctor` finds some damage that it cannot fix on its own: timelinehistory that exists only in the database, derived pages without an explicit-visibility, and pages indexed before the safe-chunk fence. `gbrain repair`-fixes those three kinds. Every run is a preview unless you pass `--apply`.+visibility, pages indexed before the safe-chunk fence, pages imported+without a contextual retrieval mode, and connector checkpoint rows no source+can load. `gbrain repair` fixes those five kinds. Every run is a preview+unless you pass `--apply`.+`gbrain doctor --remediation-plan` lists the same kinds as repair steps, and+`gbrain doctor --remediate --yes --include-repairs` runs them under a budget+(see [Run repairs through doctor](#run-repairs-through-doctor)).**Say to your agent:** *"Doctor says some timeline history is only in thedatabase. Show me what `gbrain repair` would change, then apply it."* The@@ -38,7 +43,7 @@ timeline: 12 item(s) to repairit leaves alone (see [What each kind fixes](#what-each-kind-fixes)).- **Cost** is what an apply of the pending items would consume: one permanentrequest ID and 16 KiB of reserved receipt space per page for `timeline` and- `visibility`, and nothing for `safe-chunks`. When an embedding model is+ `visibility`, and nothing for `safe-chunks` or `contextual-mode`. When an embedding model isconfigured and priced, the line adds an estimated embedding cost in dollars.- **Capacity** shows the write-journal counters the run draws on and the 90%line where it stops (see [Capacity stop](#capacity-stop)).@@ -53,12 +58,16 @@ gbrain repair timeline --applygbrain repair visibility --applygbrain repair safe-chunks --applygbrain repair safe-chunks --apply --no-embed # re-seal text now, embed later+gbrain repair contextual-mode --applygbrain repair --all --apply # every kind in order````--apply` writes without a prompt, so review the preview first. With-`--apply` you must name a kind or pass `--all`; `--yes` is refused. `--all`-runs `timeline`, then `visibility`, then `safe-chunks`, and stops at the+`--apply` you must name a kind or pass `--all`; `--yes` is refused, and so is+any other option the table below does not list, including `--max-usd`: a+refused run changes nothing. To cap paid embedding work, run the repairs+through `gbrain doctor --remediate --yes --include-repairs --max-usd <n>`. `--all`+runs `timeline`, then `visibility`, then `safe-chunks`, then `contextual-mode`, then `connector-checkpoints`, and stops at thefirst kind that stops.Each item is re-checked against the page's current state just before it is@@ -71,10 +80,10 @@ left for the next run. Nothing is deleted.| --- | --- || `--apply` | Write the repair. Without it, only preview. || `--source <id>` | Limit the run to one active source. The default is every active (non-archived) source. An unknown or archived id is refused. |-| `--limit <n>` | Repair at most `n` items per kind in this run (a positive integer; with `--all`, up to `n` for each of the three kinds). Rerun the same command to continue. |-| `--no-embed` | `safe-chunks` only: re-seal chunk text and skip embedding. Run `gbrain embed --stale` later. |+| `--limit <n>` | Repair at most `n` items per kind in this run (a positive integer; with `--all`, up to `n` for each kind). Rerun the same command to continue. |+| `--no-embed` | `safe-chunks` and `contextual-mode`: skip the embedding provider. Run `gbrain embed --stale` later. `timeline` and `visibility` pages are re-embedded by their publication either way. || `--all` | Run every kind in order. |-| `--json` | Print `{ scope, mode, results[] }`, one result per kind with `affected`, `sample`, `residuals`, `cost`, `capacity`, `resumed_from`, `applied`, `skipped`, `complete`, `stopped` and `apply_command`. |+| `--json` | Print `{ scope, mode, results[], paid_kinds }`, one result per kind with `paid`, `affected`, `sample`, `residuals`, `cost`, `capacity`, `resumed_from`, `applied`, `skipped`, `complete`, `stopped` and `apply_command`. |The command exits 1 when a run stops early (capacity, a pending write, or aheld writer). A `--limit` batch that leaves work behind exits 0, so scripts@@ -86,7 +95,9 @@ should also check `results[].complete`.| --- | --- | --- | --- || `timeline` | `timeline_history` | Re-saves each page with its current body through a revision-bound `put_page`. The save writes each database-only timeline entry back into the page as a bullet preceded by `<!-- gbrain:materialized v1 <hash> -->`. | `kept_unrenderable_rows`: entries that would change if written as a bullet (for example an empty source). They stay in the database. || `visibility` | `derived_visibility` | Stamps an explicit `visibility` on extracted atoms and synthesized concepts. An atom takes its origin page's visibility; transcript atoms and atoms whose origin is gone become `private`; a concept takes the strictest visibility of its input atoms. A concept input found only through an atom's `concepts:` list counts as private. Atoms are repaired before concepts. It never loosens an explicit value: `private` stays `private`, and `world` can only become `private`. A missing value is stamped with the origin's value, which is `world` when the origin page is public. | `concepts_without_lineage`: concepts whose inputs cannot be found. They stay as they are, and remote readers already treat a missing visibility as private. `atoms_origin_gone_to_private` counts atoms made private because their origin page no longer exists. |-| `safe-chunks` | `contextual_retrieval_coverage` (`details.unsealed_pages`) | Rebuilds the chunks of markdown and code pages indexed before the safe-chunk fence, which remote and MCP search withhold. It rebuilds projections only: no page write, no new page version and no request ID. Vectors whose embedding input did not change are kept; the rest are embedded unless you pass `--no-embed` or no embedding model is configured. | `code_without_source_path`: code pages with no recorded file to re-chunk. `unsupported_page_kind`: other page kinds, such as images. Their importer re-seals them. |+| `connector-checkpoints` | `connector_checkpoints` | Deletes managed connector checkpoint rows and retry pointers that no registered connector source can load and that are older than 7 days. They accumulate after a content setting such as `g_history_days` changes, or when a connector host older than v0.60.11.0 runs during an upgrade. Cleanup only: it never copies or re-keys a checkpoint, takes no journal admission and runs brain-wide (`--source` does not narrow it). | Rows a queued or running connector write, or a connector's recorded pending set, still references. |+| `safe-chunks` | `safe_index_pending` (also `contextual_retrieval_coverage`, `details.unsealed_pages`) | Rebuilds the chunks of markdown and code pages indexed before the safe-chunk fence, which remote and MCP search withhold. It rebuilds projections only: no page write, no new page version and no request ID. Vectors whose embedding input did not change are kept; the rest are embedded unless you pass `--no-embed` or no embedding model is configured. | `code_without_source_path`: code pages with no recorded file to re-chunk. `unsupported_page_kind`: other page kinds, such as images. Their importer re-seals them. |+| `contextual-mode` | `contextual_retrieval_coverage` (pages with no recorded mode) | Stamps the contextual retrieval mode on markdown pages imported without one (for example by a large `--no-embed` sync or a connector source before this release), exactly as a fresh import of the page would: the page, source and brain settings decide, and the per-chunk synopsis tier lands at the free title tier. It rebuilds projections only: no page write, no new page version and no request ID. A page whose stored vectors already match the stamped convention keeps them and queues no re-embedding; a page whose embedding input changes has only those vectors cleared and is re-embedded once, unless you pass `--no-embed`. | `unsealed_projection`: pages whose chunks lag their text; `gbrain embed --stale` or `safe-chunks` seals them first, and the next run stamps them. `embed_skip`: pages marked to skip embedding keep their stored vectors and are not stamped. |Timeline rows that an earlier version of a page produced and its current textno longer has are removals, not history, so `timeline` neither counts nor@@ -98,6 +109,58 @@ A timeline repair can make pages gain marked bullets. That is the fix: thehistory is now visible in the page and survives later edits. Deleting a markedbullet in a save that passes the current `expected_revision` deletes its entry.+<a id="connector-checkpoints"></a>+### Connector checkpoints and the upgrade to v0.60.11.0++Managed Google and GitHub connector checkpoints are keyed on the parsed+connector settings minus credential-delivery fields, so the per-cycle+`last_source_cycle_at` stamp no longer makes every run start over. The+v0.60.11.0 migration copies each connector source's newest committed+checkpoint to the new key. A source whose newest checkpoint receipt was+compacted re-walks its window once; unchanged pages are not admitted again.++**Say to your agent:** *"Did my Gmail connector stop re-importing everything+every hour?"* The agent runs `gbrain sources status --json` and reads the+connector block below.++`gbrain sources status --json` adds a `connector` object to each Google or+GitHub source:++```json+"connector": {+ "upgrade_recovery": "resumed",+ "resumed_from": "2026-09-28 17:04:11.52+00",+ "account_pinned": true,+ "continuity_unverified": true,+ "pending": 0,+ "last_run": { "page_admissions": 0, "skipped_unchanged": 412, "pending": 0, "checkpoint_admissions": 1,+ "stopped_on_wait_budget": false, "dropped_upstream": 0, "finished_at": "2026-09-29T21:00:03.114Z" }+}+```++- `upgrade_recovery`: `resumed` (the migration copied a pre-upgrade checkpoint+ from `resumed_from`), `rewalking_once` (until the first post-upgrade run+ finishes) or `none`. Content selection since `resumed_from` is unverified;+ if you changed a content setting since then, re-walk once with+ `gbrain sync --source <id> --reset-checkpoint`.+- `account_pinned` / `continuity_unverified`: the account the credential+ resolved to is pinned on the first run. A migrated source is pinned on its+ first post-upgrade run, so continuity before the upgrade is unverified. The+ account itself is never printed here.+- `last_run`: page admissions, unchanged pages skipped without an admission,+ writes still pending, checkpoint admissions, whether the 30-second wait+ budget stopped the run, and items dropped because they were deleted+ upstream. A quiet source shows `page_admissions: 0`; a provider whose+ cursor changes every run (Calendar sync token, Gmail history id) shows one+ checkpoint admission per run.++`gbrain sync --source <id> --reset-checkpoint` discards that connector+source's checkpoint, including Google backfill state, after resolving its+pending writes, and re-walks the configured window once. Existing pages stay,+unchanged ones take no admission, and the account pin is kept. It refuses on a+Git-backed source and while the account differs+([`connector_account_changed`](write-refusals.md#connector-account-changed)).+## ResumeRuns are resumable. After each page commits, the position is saved under the@@ -125,7 +188,7 @@ STOPPED: Stopped before crossing 90% of brain lifetime_ids (...). Run: gbrain coRaise the limit on the brain host only if you agree, then rerun. Raised limitsare brain-wide; request IDs stay permanent replay protection. `safe-chunks`-takes no journal admission and never hits this stop. The limits and their+and `contextual-mode` take no journal admission and never hits this stop. The limits and theirdefaults are in [bounded admission and retention](concurrent-writes.md#bounded-admission-and-retention).## Where it runs@@ -149,7 +212,8 @@ every private page.```bashgbrain repair --json # every kind reports "affected": 0-gbrain doctor --json # timeline_history, derived_visibility, unsealed_pages+gbrain doctor --json # timeline_history, derived_visibility, safe_index_pending+gbrain doctor --remediation-plan # no repair steps left```Items the repair leaves alone can keep a doctor warning: concepts without@@ -157,8 +221,153 @@ lineage still count under `derived_visibility`, and code pages without asource path or unsupported page kinds still count as unsealed pages. Checkthe residual counters before treating a remaining warning as a failed repair.+## Run repairs through doctor++**Say to your agent:** *"Preview what doctor would fix after the upgrade, then+run the repairs I agree to with a $2 cap."*++`gbrain doctor --remediation-plan` previews two kinds of step. Job steps come+from the brain score and `--target-score`. Repair steps come from every+`gbrain repair` kind that has pending items, whatever the score target, and+each is marked `requires user agreement`. Every step prints the exact command+that applies it, and the plan ends with one combined command:++```text+Repair steps: 2 (requires user agreement; PROTECTED, run on this host only; independent of the score target)+ R1. timeline — 12 item(s) (free) [requires user agreement]+ apply: gbrain repair timeline --apply+ R2. safe-chunks — 40 item(s) (~$0.0031 embeddings) [requires user agreement]+ apply: gbrain repair safe-chunks --apply++Apply everything after the user agrees: gbrain doctor --remediate --yes --include-repairs --max-usd 0.01+Ask the user before applying any repair step.+```++`gbrain doctor --remediate --yes` runs job steps only. Repair steps run only+when you also pass `--include-repairs`, which records the user's agreement;+without it they are listed as `N repair steps skipped (user agreement required):+re-run with --include-repairs`. Repair steps are PROTECTED: they run in this+process on the brain host, and a remote caller cannot include them. They run+even when the score target is unreachable (a keyless brain often cannot reach+90); `--target-score` governs job steps only, and an included repair step runs+to completion.++`--max-usd <n>` is a cumulative cap across the run and every `--resume`. A paid+step (one that may queue embeddings) whose estimate exceeds what is left is not+started; the free steps still run, and the run then stops as budget-exhausted+with a resume command that repeats the cap and `--include-repairs`:++```text+Resume with:+ gbrain doctor --remediate --yes --include-repairs --max-usd 0 --resume 3f9c2a1b7d4e5f60+```++The checkpoint lives in `~/.gbrain/remediation/<plan hash>.json` on this host+and records the brain, the cap, the `--include-repairs` agreement, the spend so+far and the original steps. `--resume` without `--max-usd` reuses the recorded+cap and prints it; a higher `--max-usd` raises it. A resume only continues the+original steps: repair kinds or job steps found later need a fresh run and a+fresh agreement. A checkpoint recorded for another brain is refused.++When an embedding model is configured, every kind can spend. `timeline` and+`visibility` publish page writes whose embeddings the persistence consumer+computes afterwards, outside this run, so their estimate is charged against the+cap before they start; `--no-embed` does not change that. The consumer does+not see the cap, so for those kinds the cap bounds the estimate, not each+provider call, and the estimate counts the page as it is before the repair.+`safe-chunks` embeds in the run itself under the remaining cap and+`--no-embed` makes it free. When the budget runs out after pages are re-sealed,+the checkpoint keeps their sources and `--resume` finishes their embeddings+under the same cap; a run that leaves embeddings behind exits 1 and says to run+`gbrain embed --stale`.++With `--json`, the result adds `repairs[]` (one entry per repair step, with+`status` `completed`, `stopped`, `failed`, `budget_refused` or+`budget_exhausted`), `repairs_skipped[]`, `budget`, `repairs_completed`,+`healthy` and `findings[]`. Each finding has a `check_id`, a `message` and a+`class`:++| Class | Meaning |+| --- | --- |+| `cleared` | The finding was present before the run and is gone after it. |+| `pending` | A repairable finding remains: its step stopped, was refused by the budget, left items behind, or the check could not run. |+| `consent_required` | A repairable finding whose step was skipped for lack of `--include-repairs`; `command` applies it. |+| `operator_required` | Needs a named manual action on the brain host (`instruction`), for example raising a journal limit, retrying a parked effect, or quarantining self-captures. |+| `unsupported` | No command can clear it yet; it is reported so it is never hidden (a stale queued embedding effect). |++Exit status: `0` when no automatically repairable finding remains and no step+failed, even if operator-required or unsupported findings remain (they are+listed); `1` when a repairable finding remains, a step failed, or the budget+ran out; `2` when the score target is unreachable and there was no repair step+to run, or a resume was refused. `healthy` is true only when every wave check+is clean; `repairs_completed` counts the repair steps that finished.++## Recover after upgrading to this release++**Say to your agent:** *"We just upgraded gbrain. Check what needs repair and+walk me through it before changing anything."*++1. `gbrain post-upgrade` runs the recovery checks once and, when something+ needs attention, prints an `[AGENT] Relay this to your operator` banner with+ each finding's count. It never applies anything.+2. Preview: `gbrain doctor --remediation-plan`. Show the user the repair steps+ and their estimated cost, and ask before applying.+3. After the user agrees, apply with a budget:+ `gbrain doctor --remediate --yes --include-repairs --max-usd <n>`+ (the plan prints `<n>` filled in).+4. If it stops as budget-exhausted, ask the user again, then run the printed+ resume command (raise `--max-usd` only with their agreement).+5. Follow each `operator_required` instruction the run prints, and note the+ `unsupported` ones.+6. Verify: `gbrain doctor --remediation-plan` lists no repair steps.++Hosted and thin-client callers see the same checks in `gbrain remote doctor`+as one line each, for example+`timeline_history: ... host operator action required: on the brain host run gbrain doctor --remediation-plan`.+A line that says `Unknown:` means the check could not run; it is not a clean+result. Ask the brain host's operator to run the steps above.++## Quarantine self-captured corpus files++`gbrain doctor` reports `self_capture` when the dream session corpus+(`dream.synthesize.session_corpus_dir`) still holds files captured from+gbrain's own `claude-cli` sessions (#5413). Dream and the sweep already skip+the ones they can identify, but nothing removes them. The check never moves+or deletes files. It lists what it classified (a harness transcript under a+gbrain scratch project matches the file) and counts what it cannot decide (no+harness transcript is left for that session).++To quarantine the classified files on the brain host:++```bash+gbrain doctor --json > /tmp/gbrain-doctor.json+# Review the list first:+jq -r '.checks[] | select(.name=="self_capture") | .details.classified_sample[]' /tmp/gbrain-doctor.json+# Then run the exact commands doctor printed (one mkdir, one move per file, sidecars included):+jq -r '.checks[] | select(.name=="self_capture") | .details.quarantine_commands[]' /tmp/gbrain-doctor.json | sh+gbrain doctor --json | jq '.checks[] | select(.name=="self_capture") | .details'+```++The quarantine directory is a sibling of the corpus directory+(`<corpus>.quarantine`), so dream never reads it. Doctor prints at most 20 move+commands per run; rerun the sequence until `classified` reaches 0. Review the+`unclassifiable` files by hand; delete the quarantine directory only when you+are sure you do not need it.++## Stale queued embedding effects++`gbrain doctor` reports `stale_embedding_effects` when a committed write still+has a queued embedding effect an hour later that no consumer has claimed+(#5629). It blocks shared-skill activation with `writer_not_quiesced`, and the+refusal names the effect. Inspect it with+`gbrain sources writer status <source> --json`. Inspection cannot clear it:+`gbrain sources writer retry-effects` only handles failed effects, and the+path that reconciles or re-queues a stale queued effect (never silently+dropping it) is not built yet. Doctor remediation reports it as `unsupported`.+## Related- [Write refusal reasons](write-refusals.md) — what a refused write means and the recovery command- [Concurrent writes and durable receipts](concurrent-writes.md) — receipts, retries and capacity limits- [v0.60.5.0 upgrade steps](../../skills/migrations/v0.60.5.0.md) — the backup-first upgrade that introduced these repairs+- [Topologies: claim and activate runbook](../architecture/topologies.md#claim-and-activate-runbook) — quiescence checklist, the writer admin lockdiff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex bff531a11a..b2b215a030 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -38,11 +38,20 @@ of making a duplicate.| `file_database_drift` | `source_changed` | The page's canonical file and its database copy disagree, usually because the file was edited outside a coordinated write. Neither copy was overwritten. A file with no `type:` line keeps the stored type, and titles compare trimmed, so those alone no longer cause this. | `gbrain sources reconcile <source> <slug> --brain <brain> --preview`, review the preview, resolve it, then `--apply <resolved-preview-file> --request-id <new uuid>`. Retry the original write with a **new** request ID. See [repair a file/database disagreement](concurrent-writes.md#repair-a-filedatabase-disagreement). || `ambiguous_source_path` | `page_identity_changed` | A source registered at a Git subfolder `<sub>` has a page whose stored path `<sub>/<file>` could mean either `<file>` in the source directory (the older Git-root spelling) or `<sub>/<file>` inside a folder of the source that repeats its name, and both files exist. Sync refuses instead of guessing. See [sources in a Git subfolder](multi-source-brains.md#sources-in-a-git-subfolder). | Rename or move one of the two files, commit, then `gbrain sync --source <source> --no-pull --retry-failed`. || `physical_root_device_changed` | `recovery_required` | The checkout's filesystem device number changed while everything else matches, which macOS can do after a reboot. When the owner token, brain, worktree, root, inode and a non-zero birth time all match and the caller can verify database ownership, the write path re-stamps ownership by itself and the write proceeds. This refusal means the automatic re-stamp could not be verified; the suggestion says why. | Do a deliberate self-transfer: `gbrain sources writer status <source>` (note `admin_state`), then `gbrain sources writer transfer prepare <source> --self-transfer --admin-intent writer_transfer_prepare --expected-state <admin_state>`, then `gbrain sources writer transfer accept <source> --path <root> --expected-epoch <epoch> --manifest <digest from prepare> --self-transfer --admin-intent writer_transfer_accept --expected-state <fresh admin_state>`. Retry the original write with the **same** request ID. Never delete ownership marker files. |+| <a id="embedding_budget_below_worst_case"></a>`embedding_budget_below_worst_case` | `embedding_budget_below_worst_case` | `gbrain migrate embeddings` (or the local `migrate_embeddings` operation) was given a `--max-cost-usd` cap below the migration's worst-case authorization: every planned provider request at its maximum input size, plus any debits a resumed run already holds. The run stopped before any provider request, re-chunk or vector invalidation, so nothing changed. The message and JSON carry `cap_usd`, `worst_case_usd`, `debited_usd` and `required_cap_usd`. | Re-run with the value the `suggestion` names, for example `gbrain migrate embeddings --to <provider:model> --dim <N> --max-cost-usd <required_cap_usd> --yes` (operation: `max_cost_usd`). Preview first with `--dry-run`, which prints the worst-case authorization beside the estimate. Requests settle to reported usage, so actual spend is usually far below the cap. See [embedding migration](embedding-migration.md). || `cursor_processing_options_conflict` | `invalid_params` | An unfinished sync's processing options (`--no-embed`, `--no-extract`, `--no-schema-pack`) conflict with this run, or the cursor predates saved options and has none. When options are saved, a run that omits those flags, including autopilot and `sync` jobs, adopts them. | When the message prints a resume command (`gbrain sync --source <source> --no-pull` plus the saved flags), run it or drop the conflicting flag. When it reports no saved options, resolve pending requests first, then rediscover with `gbrain sync --source <source> --no-pull --retry-failed` and the processing flags you want. || `take_row_collision` | `take_row_collision` | A save adds a takes-table row whose row number already belongs to a different take that exists only in the database. The save stops instead of overwriting that take. | Renumber the new takes row, or add the existing take to the page's takes table, then save with the current `expected_revision` and a **new** request ID (the content changed). || `invalid_source_uri` | `invalid_source_uri` | The brain has shared skillpacks, and the page's stored `source_uri` is a `file:` URI that cannot be turned into a local path, so gbrain cannot prove the write stays outside a skillpack. Shared-skill protection stays on. | The source owner inspects the page's stored `source_uri` on the brain host and replaces it with an absolute file URI or clears it; there is no dedicated command yet. Retry with a **new** request ID. || `queue_capacity` | `queue_capacity` | Admission would exceed a write-journal limit. Existing requests keep their place; nothing is evicted. For the cumulative limits (lifetime request IDs and receipt bytes), `detail` names the limit, for example `principal_lifetime_ids`. | For a cumulative limit, run the printed `gbrain config set persistence.limits.<limit> <value>` (sized for about one more year at the current rate), then retry with the **same** request ID. For outstanding-request, queued-byte or recovery-byte limits, let outstanding requests finish and check `gbrain sources writer status`. See [bounded admission and retention](concurrent-writes.md#bounded-admission-and-retention). |+| <a id="connector-account-changed"></a>`account_changed`, `account_unresolved` | `connector_account_changed` | A managed Google or GitHub connector's credential resolves to a different account than the one pinned for the source (Google email, GitHub App installation or login), or to no account at all. Google checks every enabled service before any service runs. Nothing was imported. No reset flag authorizes an account change. | The suggestion gives two branches with real values. (A) Restore the credential for the pinned account (the configured `g_token_env`, `g_token_command`, vault credential, `gh_token_env` or GitHub App key), then `gbrain sync --source <source>`. (B) For a deliberate change, add a new source for the new account (`gbrain google setup --account <email>`, or `gbrain sources add <new-id> --kind github … --app-install <id>`), then `gbrain sources archive <source>`; existing pages stay under the old source. |+| <a id="connector-intent-outdated"></a>`pre_upgrade` | `connector_intent_outdated` | A connector write was admitted in the intent format retired in v0.60.11.0. With detail `pre_upgrade` it was admitted before this brain's upgrade; otherwise a connector host older than v0.60.11.0 admitted it. The consumer recovers any file publication in progress first, then fails the request. | `pre_upgrade`: nothing to do; the item is fetched again on the next `gbrain sync --source <source>` under a new request ID. Otherwise: `gbrain upgrade` on the host that runs connector jobs, then `gbrain sync --source <source>`. |+| <a id="unsupported-mutation-protocol"></a>`consumer_upgrade_required` | `unsupported_mutation_protocol` | A v0.60.11.0 connector sent a `connector_v2_*` write to a persistence consumer older than v0.60.11.0, which does not know the format. Other `permission_denied` refusals on connector receipts are never relabeled as upgrades. | `gbrain upgrade` on every consumer and worktree-owner host, then `gbrain sync --source <source>`. Upgrade those hosts before connector hosts. |+| `unbound_source` | `owner_unavailable` | On Postgres, a page write went to a source that has a checkout path but no canonical owner. It is refused by default because another host may own the files. The same reason appears when the source was bound, or the page gained a canonical file, after a database-only write was accepted, and (as a `source_changed` sync failure) when a canonical file appears at the path of a page written while the source was unbound. | Bind the source (`gbrain sources writer status <source> --json`, then `gbrain sources writer claim <source> --path <checkout> --admin-intent writer_claim --expected-state <admin_state>`), or opt in with `gbrain config set persistence.unbound_write database_only`. See [unbound sources on Postgres](#unbound-sources-on-postgres). |+| <a id="embedding_zero_norm"></a>`zero_norm`, `non_finite` or `empty_input` | `embedding_zero_norm` | The embedding provider returned a vector with no direction (all zeros, NaN or infinity) for a chunk, or the chunk text was empty. A vector index silently skips such a row, so gbrain refuses to store it. Only that chunk is refused: the page text and every other chunk's vector are saved, and the page is left for `gbrain embed --stale`. It is never retried as a rate limit or network error. | Inspect the named page's chunk text (empty, whitespace- or symbol-only chunks are the usual cause) or the embedding provider, fix it, then run `gbrain embed <slug>` (add `--source <source>` for a non-default source). If normal text also returns zero vectors, the provider or model is broken; check it with `gbrain doctor`. || `targets_parked` (doctor: `parked_effects`) | effect `error_code` | A Git backup or withdrawal target failed five times in a row and was set aside so the other pages keep committing. The page write itself committed; its Git backup or withdrawal is incomplete. Contention, dependency waits, shutdown and transient database errors never count toward the five. | `gbrain sources writer status <source>`, fix the cause it names, preview with `gbrain sources writer retry-effects <source> --request-id <id> --dry-run`, then run it without `--dry-run`. Each run grants one more attempt per parked target; a target that fails again parks again. |+| <a id="writer_admin_locked"></a>`writer_admin_locked` | `writer_admin_locked` | The operator set the brain's writer admin lock (`gbrain sources writer lock`), so writer claim, activate, transfer prepare and transfer accept refuse for every caller. Ordinary writes are not affected. | Agents: stop and ask the operator; do not unlock it yourself. The operator runs, on the brain host, `gbrain sources writer unlock`, re-reads `gbrain sources writer status <source> --json`, administers, then `gbrain sources writer lock` again. See the [writer admin lock](../architecture/topologies.md#writer-admin-lock). |+| <a id="writer_not_quiesced"></a>`writer_not_quiesced` | `writer_not_quiesced` | Activation found an older writer, a legacy lock, or queued, running or recovering work. When work blocks it, the message names the blocking effect id, kind, source, page and request id. | Stop the writers named in the [claim and activate runbook](../architecture/topologies.md#claim-and-activate-runbook), inspect the named work with `gbrain sources writer status <source> --json`, let it finish, then retry. A committed write whose queued embedding effect is never claimed cannot be cleared by a command yet; see [stale queued embedding effects](repair.md#stale-queued-embedding-effects). |+| unknown option (repair) | `invalid_params` | `gbrain repair` refuses any option it does not list, so a mistyped flag or `--max-usd` never runs a repair silently without it. | Fix the option (`gbrain repair --help`). To cap paid repair work, run `gbrain doctor --remediate --yes --include-repairs --max-usd <n>`. |`gbrain doctor` reports parked targets as the `parked_effects` check with theexact `retry-effects` command per request. It reports `persistence_capacity`@@ -50,6 +59,52 @@ when lifetime request IDs or receipt bytes reach 80% of a limit, with the`gbrain config set` value to use; outstanding-request, queued-byte andrecovery-byte limits can refuse writes without that warning.+## Unbound sources on Postgres++A source with a checkout path (`local_path`, or `sync.repo_path` for the+`default` source) normally publishes every page write to a markdown file in+that checkout, through the source's canonical owner. PGLite claims that owner+automatically on the first write. Postgres does not, because several hosts can+share one Postgres brain and only one of them may own the files. Until someone+binds the source, `put_page`, `capture` and `delete_page` to it refuse with+`owner_unavailable` and `detail: unbound_source`. The suggestion names both+ways out with the real source filled in:++1. **Bind the source** on the host that holds the checkout. Run+ `gbrain sources writer status <source> --json` and note `admin_state`, then+ `gbrain sources writer claim <source> --path <checkout> --admin-intent writer_claim --expected-state <admin_state>`.+ If an operator has locked writer administration, ask them to unlock it+ first. Read [topologies](../architecture/topologies.md) before claiming a+ source that other hosts write to.+2. **Allow database-only writes** with+ `gbrain config set persistence.unbound_write database_only` (the default is+ `refuse`; no other value is accepted, and the key can only be set on the+ brain host). A `put_page` to a new page, or to a page that is already+ database-only, then writes to the database only. Its result says+ `write_through: { written: false, skipped: "unbound_source" }` with a+ warning. Pages written this way stay database-only: binding the source+ later does not materialize them into canonical files, later writes keep+ them database-only, and sync never deletes or overwrites them.++The opt-in never applies to a page that came from a canonical file (it has a+stored source path). An edit there could be lost on the owner's next sync, so+it keeps refusing with only the bind option. `capture` and `delete_page` also+keep refusing.++If the source is bound after a database-only write was accepted but before it+was published, the write fails with the same reason and nothing is written;+read the page again and resubmit with a new request ID. If a canonical file+appears at the path of a database-only page after binding, sync stops for that+file with `source_changed` and reason `unbound_source`; neither copy is+overwritten and the database page stays served. Rename or remove the file,+commit, and sync again.++`gbrain doctor` reports the `unbound_source` check: the number of such pages+per source. While the source is unbound it is `ok` and prints the bind command;+after binding it warns, because those pages sit outside the canonical files.+There is no command yet that turns them into files; to move one, save its+content under a new slug and delete the database-only page.+## Related- [Concurrent writes and durable receipts](concurrent-writes.md) — receipt states, retries, capacity limitsdiff --git a/llms-full.txt b/llms-full.txtindex 8daeebd46d..fd711fc493 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -1726,9 +1726,11 @@ writing or reviewing an operation, consult `src/core/operations.ts` for the cont`gbrain db-repair --yes` to apply safe fixes. All three are engine-free — theywork while the database is down. Full loop:[`docs/ENGINES.md`](./docs/ENGINES.md#engine-detection-and-access-repair).- Doctor residue (`timeline_history`, `derived_visibility`, unsealed pages):- preview `gbrain repair`, then `gbrain repair <kind> --apply` on the brain host- after the user agrees ([repair guide](./docs/guides/repair.md)). A refused+ Doctor residue (`timeline_history`, `derived_visibility`, `safe_index_pending`):+ preview `gbrain doctor --remediation-plan` (or `gbrain repair`), then, after the+ user agrees, `gbrain doctor --remediate --yes --include-repairs --max-usd <n>`+ or `gbrain repair <kind> --apply` on the brain host. After an upgrade, follow+ [recover after upgrading](./docs/guides/repair.md#recover-after-upgrading-to-this-release). A refusedwrite names its reason and recovery command([write refusal reasons](./docs/guides/write-refusals.md)).- **Migrate / upgrade:** `gbrain upgrade` (binary self-update + schema migrations + post-upgrade prompts),@@ -1742,14 +1744,22 @@ writing or reviewing an operation, consult `src/core/operations.ts` for the cont<dataset.jsonl>` runs against an isolated in-memory PGLiteper question — your `~/.gbrain` is never opened. Full guide:[`docs/eval-bench.md`](./docs/eval-bench.md).-- **Drive the brain to a target health score:** the one-command- loop. `gbrain doctor --remediation-plan --json` previews what would be- fixed; `gbrain doctor --remediate --yes --target-score 90 --max-usd 5`- walks a dependency-ordered plan, re-checking score between every step and- refusing to spend past the cost cap. Stale extraction uses source-scoped- database pages, including DB-only pages; it does not require a repository- sync first. Empty brains (no entity pages) or unconfigured embedding- keys hit a `max_reachable_score` ceiling and bail with what's missing.+- **Drive the brain to a target health score:** preview, then agree.+ `gbrain doctor --remediation-plan --json` previews job steps and the+ PROTECTED repair steps (each marked "requires user agreement", with its+ exact command); after the user agrees,+ `gbrain doctor --remediate --yes --include-repairs --target-score 90 --max-usd 5`+ runs the repairs (even when the score target is unreachable) and walks the+ dependency-ordered job plan, re-checking score between steps. The cap is+ cumulative across `--resume`; a paid step that would exceed it is not+ started while free steps still run. Without `--include-repairs`, repair+ steps are listed as skipped. `--json` classifies each finding `cleared`,+ `pending`, `consent_required`, `operator_required` or `unsupported`.+ Stale extraction uses source-scoped database pages, including DB-only+ pages; it does not require a repository sync first. Empty brains (no+ entity pages) or unconfigured embedding keys hit a `max_reachable_score`+ ceiling: job steps stop with what's missing, while included repair steps+ still run.Three phase handlers (synthesize / patterns / consolidate) arePROTECTED — only trusted local callers can submit them; MCP cannot.Reference: [`docs/architecture/topologies.md`](./docs/architecture/topologies.md).@@ -2872,7 +2882,9 @@ upgrade every process that writes to the brain, then follow the[v0.60.5.0 steps](skills/migrations/v0.60.5.0.md): one full `gbrain doctor`,then preview `gbrain repair` and apply only after the user agrees([repair guide](docs/guides/repair.md)). For v0.60.6.0, also follow the-[one-time timeline prune and slug-collision steps](skills/migrations/v0.60.6.0.md).+[one-time timeline prune and slug-collision steps](skills/migrations/v0.60.6.0.md). For v0.60.11.0, preview+`gbrain repair contextual-mode` and rebuild PGLite vector indexes after a crash+repair ([steps](skills/migrations/v0.60.11.0.md)).For v0.53.0.0, follow the[mechanical shared-skills migration](skills/migrations/v0.53.0.0.md) on the host,@@ -3924,9 +3936,12 @@ version bump changes it.backs up `pg_wal/` + `pg_control` into a sibling`<dataDir>.wal-repair-backup-<ts>/` dir, resets the WAL in place(pg_resetwal semantics — data files preserved; transactions not- checkpointed before the corruption may be lost), and retries once. On- success it prints a loud stderr notice naming the backup and recommending- `gbrain doctor`. Safety bounds: repair only runs under a cleanly-acquired+ checkpointed before the corruption may be lost), and retries once. The+ reset does not rebuild indexes, so a page written just before the crash+ can be missing from vector search while keyword search still finds it.+ On success it prints a loud stderr notice naming the backup and the next+ commands: `gbrain reindex --vectors` (rebuilds every HNSW index from the+ stored vectors, no re-embedding) and then `gbrain doctor`. Safety bounds: repair only runs under a cleanly-acquireddata-dir lock (never after reaping another process's lock), skips for acooldown window after a failed attempt(`GBRAIN_PGLITE_WAL_REPAIR_COOLDOWN_SECONDS`, default 3600), reuses one@@ -8360,8 +8375,13 @@ Source: https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/rep`gbrain doctor` finds some damage that it cannot fix on its own: timelinehistory that exists only in the database, derived pages without an explicit-visibility, and pages indexed before the safe-chunk fence. `gbrain repair`-fixes those three kinds. Every run is a preview unless you pass `--apply`.+visibility, pages indexed before the safe-chunk fence, pages imported+without a contextual retrieval mode, and connector checkpoint rows no source+can load. `gbrain repair` fixes those five kinds. Every run is a preview+unless you pass `--apply`.+`gbrain doctor --remediation-plan` lists the same kinds as repair steps, and+`gbrain doctor --remediate --yes --include-repairs` runs them under a budget+(see [Run repairs through doctor](#run-repairs-through-doctor)).**Say to your agent:** *"Doctor says some timeline history is only in thedatabase. Show me what `gbrain repair` would change, then apply it."* The@@ -8396,7 +8416,7 @@ timeline: 12 item(s) to repairit leaves alone (see [What each kind fixes](#what-each-kind-fixes)).- **Cost** is what an apply of the pending items would consume: one permanentrequest ID and 16 KiB of reserved receipt space per page for `timeline` and- `visibility`, and nothing for `safe-chunks`. When an embedding model is+ `visibility`, and nothing for `safe-chunks` or `contextual-mode`. When an embedding model isconfigured and priced, the line adds an estimated embedding cost in dollars.- **Capacity** shows the write-journal counters the run draws on and the 90%line where it stops (see [Capacity stop](#capacity-stop)).@@ -8411,12 +8431,16 @@ gbrain repair timeline --applygbrain repair visibility --applygbrain repair safe-chunks --applygbrain repair safe-chunks --apply --no-embed # re-seal text now, embed later+gbrain repair contextual-mode --applygbrain repair --all --apply # every kind in order````--apply` writes without a prompt, so review the preview first. With-`--apply` you must name a kind or pass `--all`; `--yes` is refused. `--all`-runs `timeline`, then `visibility`, then `safe-chunks`, and stops at the+`--apply` you must name a kind or pass `--all`; `--yes` is refused, and so is+any other option the table below does not list, including `--max-usd`: a+refused run changes nothing. To cap paid embedding work, run the repairs+through `gbrain doctor --remediate --yes --include-repairs --max-usd <n>`. `--all`+runs `timeline`, then `visibility`, then `safe-chunks`, then `contextual-mode`, then `connector-checkpoints`, and stops at thefirst kind that stops.Each item is re-checked against the page's current state just before it is@@ -8429,10 +8453,10 @@ left for the next run. Nothing is deleted.| --- | --- || `--apply` | Write the repair. Without it, only preview. || `--source <id>` | Limit the run to one active source. The default is every active (non-archived) source. An unknown or archived id is refused. |-| `--limit <n>` | Repair at most `n` items per kind in this run (a positive integer; with `--all`, up to `n` for each of the three kinds). Rerun the same command to continue. |-| `--no-embed` | `safe-chunks` only: re-seal chunk text and skip embedding. Run `gbrain embed --stale` later. |+| `--limit <n>` | Repair at most `n` items per kind in this run (a positive integer; with `--all`, up to `n` for each kind). Rerun the same command to continue. |+| `--no-embed` | `safe-chunks` and `contextual-mode`: skip the embedding provider. Run `gbrain embed --stale` later. `timeline` and `visibility` pages are re-embedded by their publication either way. || `--all` | Run every kind in order. |-| `--json` | Print `{ scope, mode, results[] }`, one result per kind with `affected`, `sample`, `residuals`, `cost`, `capacity`, `resumed_from`, `applied`, `skipped`, `complete`, `stopped` and `apply_command`. |+| `--json` | Print `{ scope, mode, results[], paid_kinds }`, one result per kind with `paid`, `affected`, `sample`, `residuals`, `cost`, `capacity`, `resumed_from`, `applied`, `skipped`, `complete`, `stopped` and `apply_command`. |The command exits 1 when a run stops early (capacity, a pending write, or aheld writer). A `--limit` batch that leaves work behind exits 0, so scripts@@ -8444,7 +8468,9 @@ should also check `results[].complete`.| --- | --- | --- | --- || `timeline` | `timeline_history` | Re-saves each page with its current body through a revision-bound `put_page`. The save writes each database-only timeline entry back into the page as a bullet preceded by `<!-- gbrain:materialized v1 <hash> -->`. | `kept_unrenderable_rows`: entries that would change if written as a bullet (for example an empty source). They stay in the database. || `visibility` | `derived_visibility` | Stamps an explicit `visibility` on extracted atoms and synthesized concepts. An atom takes its origin page's visibility; transcript atoms and atoms whose origin is gone become `private`; a concept takes the strictest visibility of its input atoms. A concept input found only through an atom's `concepts:` list counts as private. Atoms are repaired before concepts. It never loosens an explicit value: `private` stays `private`, and `world` can only become `private`. A missing value is stamped with the origin's value, which is `world` when the origin page is public. | `concepts_without_lineage`: concepts whose inputs cannot be found. They stay as they are, and remote readers already treat a missing visibility as private. `atoms_origin_gone_to_private` counts atoms made private because their origin page no longer exists. |-| `safe-chunks` | `contextual_retrieval_coverage` (`details.unsealed_pages`) | Rebuilds the chunks of markdown and code pages indexed before the safe-chunk fence, which remote and MCP search withhold. It rebuilds projections only: no page write, no new page version and no request ID. Vectors whose embedding input did not change are kept; the rest are embedded unless you pass `--no-embed` or no embedding model is configured. | `code_without_source_path`: code pages with no recorded file to re-chunk. `unsupported_page_kind`: other page kinds, such as images. Their importer re-seals them. |+| `connector-checkpoints` | `connector_checkpoints` | Deletes managed connector checkpoint rows and retry pointers that no registered connector source can load and that are older than 7 days. They accumulate after a content setting such as `g_history_days` changes, or when a connector host older than v0.60.11.0 runs during an upgrade. Cleanup only: it never copies or re-keys a checkpoint, takes no journal admission and runs brain-wide (`--source` does not narrow it). | Rows a queued or running connector write, or a connector's recorded pending set, still references. |+| `safe-chunks` | `safe_index_pending` (also `contextual_retrieval_coverage`, `details.unsealed_pages`) | Rebuilds the chunks of markdown and code pages indexed before the safe-chunk fence, which remote and MCP search withhold. It rebuilds projections only: no page write, no new page version and no request ID. Vectors whose embedding input did not change are kept; the rest are embedded unless you pass `--no-embed` or no embedding model is configured. | `code_without_source_path`: code pages with no recorded file to re-chunk. `unsupported_page_kind`: other page kinds, such as images. Their importer re-seals them. |+| `contextual-mode` | `contextual_retrieval_coverage` (pages with no recorded mode) | Stamps the contextual retrieval mode on markdown pages imported without one (for example by a large `--no-embed` sync or a connector source before this release), exactly as a fresh import of the page would: the page, source and brain settings decide, and the per-chunk synopsis tier lands at the free title tier. It rebuilds projections only: no page write, no new page version and no request ID. A page whose stored vectors already match the stamped convention keeps them and queues no re-embedding; a page whose embedding input changes has only those vectors cleared and is re-embedded once, unless you pass `--no-embed`. | `unsealed_projection`: pages whose chunks lag their text; `gbrain embed --stale` or `safe-chunks` seals them first, and the next run stamps them. `embed_skip`: pages marked to skip embedding keep their stored vectors and are not stamped. |Timeline rows that an earlier version of a page produced and its current textno longer has are removals, not history, so `timeline` neither counts nor@@ -8456,6 +8482,58 @@ A timeline repair can make pages gain marked bullets. That is the fix: thehistory is now visible in the page and survives later edits. Deleting a markedbullet in a save that passes the current `expected_revision` deletes its entry.+<a id="connector-checkpoints"></a>+### Connector checkpoints and the upgrade to v0.60.11.0++Managed Google and GitHub connector checkpoints are keyed on the parsed+connector settings minus credential-delivery fields, so the per-cycle+`last_source_cycle_at` stamp no longer makes every run start over. The+v0.60.11.0 migration copies each connector source's newest committed+checkpoint to the new key. A source whose newest checkpoint receipt was+compacted re-walks its window once; unchanged pages are not admitted again.++**Say to your agent:** *"Did my Gmail connector stop re-importing everything+every hour?"* The agent runs `gbrain sources status --json` and reads the+connector block below.++`gbrain sources status --json` adds a `connector` object to each Google or+GitHub source:++```json+"connector": {+ "upgrade_recovery": "resumed",+ "resumed_from": "2026-09-28 17:04:11.52+00",+ "account_pinned": true,+ "continuity_unverified": true,+ "pending": 0,+ "last_run": { "page_admissions": 0, "skipped_unchanged": 412, "pending": 0, "checkpoint_admissions": 1,+ "stopped_on_wait_budget": false, "dropped_upstream": 0, "finished_at": "2026-09-29T21:00:03.114Z" }+}+```++- `upgrade_recovery`: `resumed` (the migration copied a pre-upgrade checkpoint+ from `resumed_from`), `rewalking_once` (until the first post-upgrade run+ finishes) or `none`. Content selection since `resumed_from` is unverified;+ if you changed a content setting since then, re-walk once with+ `gbrain sync --source <id> --reset-checkpoint`.+- `account_pinned` / `continuity_unverified`: the account the credential+ resolved to is pinned on the first run. A migrated source is pinned on its+ first post-upgrade run, so continuity before the upgrade is unverified. The+ account itself is never printed here.+- `last_run`: page admissions, unchanged pages skipped without an admission,+ writes still pending, checkpoint admissions, whether the 30-second wait+ budget stopped the run, and items dropped because they were deleted+ upstream. A quiet source shows `page_admissions: 0`; a provider whose+ cursor changes every run (Calendar sync token, Gmail history id) shows one+ checkpoint admission per run.++`gbrain sync --source <id> --reset-checkpoint` discards that connector+source's checkpoint, including Google backfill state, after resolving its+pending writes, and re-walks the configured window once. Existing pages stay,+unchanged ones take no admission, and the account pin is kept. It refuses on a+Git-backed source and while the account differs+([`connector_account_changed`](write-refusals.md#connector-account-changed)).+## ResumeRuns are resumable. After each page commits, the position is saved under the@@ -8483,7 +8561,7 @@ STOPPED: Stopped before crossing 90% of brain lifetime_ids (...). Run: gbrain coRaise the limit on the brain host only if you agree, then rerun. Raised limitsare brain-wide; request IDs stay permanent replay protection. `safe-chunks`-takes no journal admission and never hits this stop. The limits and their+and `contextual-mode` take no journal admission and never hits this stop. The limits and theirdefaults are in [bounded admission and retention](concurrent-writes.md#bounded-admission-and-retention).## Where it runs@@ -8507,7 +8585,8 @@ every private page.```bashgbrain repair --json # every kind reports "affected": 0-gbrain doctor --json # timeline_history, derived_visibility, unsealed_pages+gbrain doctor --json # timeline_history, derived_visibility, safe_index_pending+gbrain doctor --remediation-plan # no repair steps left```Items the repair leaves alone can keep a doctor warning: concepts without@@ -8515,11 +8594,156 @@ lineage still count under `derived_visibility`, and code pages without asource path or unsupported page kinds still count as unsealed pages. Checkthe residual counters before treating a remaining warning as a failed repair.+## Run repairs through doctor++**Say to your agent:** *"Preview what doctor would fix after the upgrade, then+run the repairs I agree to with a $2 cap."*++`gbrain doctor --remediation-plan` previews two kinds of step. Job steps come+from the brain score and `--target-score`. Repair steps come from every+`gbrain repair` kind that has pending items, whatever the score target, and+each is marked `requires user agreement`. Every step prints the exact command+that applies it, and the plan ends with one combined command:++```text+Repair steps: 2 (requires user agreement; PROTECTED, run on this host only; independent of the score target)+ R1. timeline — 12 item(s) (free) [requires user agreement]+ apply: gbrain repair timeline --apply+ R2. safe-chunks — 40 item(s) (~$0.0031 embeddings) [requires user agreement]+ apply: gbrain repair safe-chunks --apply++Apply everything after the user agrees: gbrain doctor --remediate --yes --include-repairs --max-usd 0.01+Ask the user before applying any repair step.+```++`gbrain doctor --remediate --yes` runs job steps only. Repair steps run only+when you also pass `--include-repairs`, which records the user's agreement;+without it they are listed as `N repair steps skipped (user agreement required):+re-run with --include-repairs`. Repair steps are PROTECTED: they run in this+process on the brain host, and a remote caller cannot include them. They run+even when the score target is unreachable (a keyless brain often cannot reach+90); `--target-score` governs job steps only, and an included repair step runs+to completion.++`--max-usd <n>` is a cumulative cap across the run and every `--resume`. A paid+step (one that may queue embeddings) whose estimate exceeds what is left is not+started; the free steps still run, and the run then stops as budget-exhausted+with a resume command that repeats the cap and `--include-repairs`:++```text+Resume with:+ gbrain doctor --remediate --yes --include-repairs --max-usd 0 --resume 3f9c2a1b7d4e5f60+```++The checkpoint lives in `~/.gbrain/remediation/<plan hash>.json` on this host+and records the brain, the cap, the `--include-repairs` agreement, the spend so+far and the original steps. `--resume` without `--max-usd` reuses the recorded+cap and prints it; a higher `--max-usd` raises it. A resume only continues the+original steps: repair kinds or job steps found later need a fresh run and a+fresh agreement. A checkpoint recorded for another brain is refused.++When an embedding model is configured, every kind can spend. `timeline` and+`visibility` publish page writes whose embeddings the persistence consumer+computes afterwards, outside this run, so their estimate is charged against the+cap before they start; `--no-embed` does not change that. The consumer does+not see the cap, so for those kinds the cap bounds the estimate, not each+provider call, and the estimate counts the page as it is before the repair.+`safe-chunks` embeds in the run itself under the remaining cap and+`--no-embed` makes it free. When the budget runs out after pages are re-sealed,+the checkpoint keeps their sources and `--resume` finishes their embeddings+under the same cap; a run that leaves embeddings behind exits 1 and says to run+`gbrain embed --stale`.++With `--json`, the result adds `repairs[]` (one entry per repair step, with+`status` `completed`, `stopped`, `failed`, `budget_refused` or+`budget_exhausted`), `repairs_skipped[]`, `budget`, `repairs_completed`,+`healthy` and `findings[]`. Each finding has a `check_id`, a `message` and a+`class`:++| Class | Meaning |+| --- | --- |+| `cleared` | The finding was present before the run and is gone after it. |+| `pending` | A repairable finding remains: its step stopped, was refused by the budget, left items behind, or the check could not run. |+| `consent_required` | A repairable finding whose step was skipped for lack of `--include-repairs`; `command` applies it. |+| `operator_required` | Needs a named manual action on the brain host (`instruction`), for example raising a journal limit, retrying a parked effect, or quarantining self-captures. |+| `unsupported` | No command can clear it yet; it is reported so it is never hidden (a stale queued embedding effect). |++Exit status: `0` when no automatically repairable finding remains and no step+failed, even if operator-required or unsupported findings remain (they are+listed); `1` when a repairable finding remains, a step failed, or the budget+ran out; `2` when the score target is unreachable and there was no repair step+to run, or a resume was refused. `healthy` is true only when every wave check+is clean; `repairs_completed` counts the repair steps that finished.++## Recover after upgrading to this release++**Say to your agent:** *"We just upgraded gbrain. Check what needs repair and+walk me through it before changing anything."*++1. `gbrain post-upgrade` runs the recovery checks once and, when something+ needs attention, prints an `[AGENT] Relay this to your operator` banner with+ each finding's count. It never applies anything.+2. Preview: `gbrain doctor --remediation-plan`. Show the user the repair steps+ and their estimated cost, and ask before applying.+3. After the user agrees, apply with a budget:+ `gbrain doctor --remediate --yes --include-repairs --max-usd <n>`+ (the plan prints `<n>` filled in).+4. If it stops as budget-exhausted, ask the user again, then run the printed+ resume command (raise `--max-usd` only with their agreement).+5. Follow each `operator_required` instruction the run prints, and note the+ `unsupported` ones.+6. Verify: `gbrain doctor --remediation-plan` lists no repair steps.++Hosted and thin-client callers see the same checks in `gbrain remote doctor`+as one line each, for example+`timeline_history: ... host operator action required: on the brain host run gbrain doctor --remediation-plan`.+A line that says `Unknown:` means the check could not run; it is not a clean+result. Ask the brain host's operator to run the steps above.++## Quarantine self-captured corpus files++`gbrain doctor` reports `self_capture` when the dream session corpus+(`dream.synthesize.session_corpus_dir`) still holds files captured from+gbrain's own `claude-cli` sessions (#5413). Dream and the sweep already skip+the ones they can identify, but nothing removes them. The check never moves+or deletes files. It lists what it classified (a harness transcript under a+gbrain scratch project matches the file) and counts what it cannot decide (no+harness transcript is left for that session).++To quarantine the classified files on the brain host:++```bash+gbrain doctor --json > /tmp/gbrain-doctor.json+# Review the list first:+jq -r '.checks[] | select(.name=="self_capture") | .details.classified_sample[]' /tmp/gbrain-doctor.json+# Then run the exact commands doctor printed (one mkdir, one move per file, sidecars included):+jq -r '.checks[] | select(.name=="self_capture") | .details.quarantine_commands[]' /tmp/gbrain-doctor.json | sh+gbrain doctor --json | jq '.checks[] | select(.name=="self_capture") | .details'+```++The quarantine directory is a sibling of the corpus directory+(`<corpus>.quarantine`), so dream never reads it. Doctor prints at most 20 move+commands per run; rerun the sequence until `classified` reaches 0. Review the+`unclassifiable` files by hand; delete the quarantine directory only when you+are sure you do not need it.++## Stale queued embedding effects++`gbrain doctor` reports `stale_embedding_effects` when a committed write still+has a queued embedding effect an hour later that no consumer has claimed+(#5629). It blocks shared-skill activation with `writer_not_quiesced`, and the+refusal names the effect. Inspect it with+`gbrain sources writer status <source> --json`. Inspection cannot clear it:+`gbrain sources writer retry-effects` only handles failed effects, and the+path that reconciles or re-queues a stale queued effect (never silently+dropping it) is not built yet. Doctor remediation reports it as `unsupported`.+## Related- [Write refusal reasons](write-refusals.md) — what a refused write means and the recovery command- [Concurrent writes and durable receipts](concurrent-writes.md) — receipts, retries and capacity limits- [v0.60.5.0 upgrade steps](../../skills/migrations/v0.60.5.0.md) — the backup-first upgrade that introduced these repairs+- [Topologies: claim and activate runbook](../architecture/topologies.md#claim-and-activate-runbook) — quiescence checklist, the writer admin lock---@@ -8567,11 +8791,20 @@ of making a duplicate.| `file_database_drift` | `source_changed` | The page's canonical file and its database copy disagree, usually because the file was edited outside a coordinated write. Neither copy was overwritten. A file with no `type:` line keeps the stored type, and titles compare trimmed, so those alone no longer cause this. | `gbrain sources reconcile <source> <slug> --brain <brain> --preview`, review the preview, resolve it, then `--apply <resolved-preview-file> --request-id <new uuid>`. Retry the original write with a **new** request ID. See [repair a file/database disagreement](concurrent-writes.md#repair-a-filedatabase-disagreement). || `ambiguous_source_path` | `page_identity_changed` | A source registered at a Git subfolder `<sub>` has a page whose stored path `<sub>/<file>` could mean either `<file>` in the source directory (the older Git-root spelling) or `<sub>/<file>` inside a folder of the source that repeats its name, and both files exist. Sync refuses instead of guessing. See [sources in a Git subfolder](multi-source-brains.md#sources-in-a-git-subfolder). | Rename or move one of the two files, commit, then `gbrain sync --source <source> --no-pull --retry-failed`. || `physical_root_device_changed` | `recovery_required` | The checkout's filesystem device number changed while everything else matches, which macOS can do after a reboot. When the owner token, brain, worktree, root, inode and a non-zero birth time all match and the caller can verify database ownership, the write path re-stamps ownership by itself and the write proceeds. This refusal means the automatic re-stamp could not be verified; the suggestion says why. | Do a deliberate self-transfer: `gbrain sources writer status <source>` (note `admin_state`), then `gbrain sources writer transfer prepare <source> --self-transfer --admin-intent writer_transfer_prepare --expected-state <admin_state>`, then `gbrain sources writer transfer accept <source> --path <root> --expected-epoch <epoch> --manifest <digest from prepare> --self-transfer --admin-intent writer_transfer_accept --expected-state <fresh admin_state>`. Retry the original write with the **same** request ID. Never delete ownership marker files. |+| <a id="embedding_budget_below_worst_case"></a>`embedding_budget_below_worst_case` | `embedding_budget_below_worst_case` | `gbrain migrate embeddings` (or the local `migrate_embeddings` operation) was given a `--max-cost-usd` cap below the migration's worst-case authorization: every planned provider request at its maximum input size, plus any debits a resumed run already holds. The run stopped before any provider request, re-chunk or vector invalidation, so nothing changed. The message and JSON carry `cap_usd`, `worst_case_usd`, `debited_usd` and `required_cap_usd`. | Re-run with the value the `suggestion` names, for example `gbrain migrate embeddings --to <provider:model> --dim <N> --max-cost-usd <required_cap_usd> --yes` (operation: `max_cost_usd`). Preview first with `--dry-run`, which prints the worst-case authorization beside the estimate. Requests settle to reported usage, so actual spend is usually far below the cap. See [embedding migration](embedding-migration.md). || `cursor_processing_options_conflict` | `invalid_params` | An unfinished sync's processing options (`--no-embed`, `--no-extract`, `--no-schema-pack`) conflict with this run, or the cursor predates saved options and has none. When options are saved, a run that omits those flags, including autopilot and `sync` jobs, adopts them. | When the message prints a resume command (`gbrain sync --source <source> --no-pull` plus the saved flags), run it or drop the conflicting flag. When it reports no saved options, resolve pending requests first, then rediscover with `gbrain sync --source <source> --no-pull --retry-failed` and the processing flags you want. || `take_row_collision` | `take_row_collision` | A save adds a takes-table row whose row number already belongs to a different take that exists only in the database. The save stops instead of overwriting that take. | Renumber the new takes row, or add the existing take to the page's takes table, then save with the current `expected_revision` and a **new** request ID (the content changed). || `invalid_source_uri` | `invalid_source_uri` | The brain has shared skillpacks, and the page's stored `source_uri` is a `file:` URI that cannot be turned into a local path, so gbrain cannot prove the write stays outside a skillpack. Shared-skill protection stays on. | The source owner inspects the page's stored `source_uri` on the brain host and replaces it with an absolute file URI or clears it; there is no dedicated command yet. Retry with a **new** request ID. || `queue_capacity` | `queue_capacity` | Admission would exceed a write-journal limit. Existing requests keep their place; nothing is evicted. For the cumulative limits (lifetime request IDs and receipt bytes), `detail` names the limit, for example `principal_lifetime_ids`. | For a cumulative limit, run the printed `gbrain config set persistence.limits.<limit> <value>` (sized for about one more year at the current rate), then retry with the **same** request ID. For outstanding-request, queued-byte or recovery-byte limits, let outstanding requests finish and check `gbrain sources writer status`. See [bounded admission and retention](concurrent-writes.md#bounded-admission-and-retention). |+| <a id="connector-account-changed"></a>`account_changed`, `account_unresolved` | `connector_account_changed` | A managed Google or GitHub connector's credential resolves to a different account than the one pinned for the source (Google email, GitHub App installation or login), or to no account at all. Google checks every enabled service before any service runs. Nothing was imported. No reset flag authorizes an account change. | The suggestion gives two branches with real values. (A) Restore the credential for the pinned account (the configured `g_token_env`, `g_token_command`, vault credential, `gh_token_env` or GitHub App key), then `gbrain sync --source <source>`. (B) For a deliberate change, add a new source for the new account (`gbrain google setup --account <email>`, or `gbrain sources add <new-id> --kind github … --app-install <id>`), then `gbrain sources archive <source>`; existing pages stay under the old source. |+| <a id="connector-intent-outdated"></a>`pre_upgrade` | `connector_intent_outdated` | A connector write was admitted in the intent format retired in v0.60.11.0. With detail `pre_upgrade` it was admitted before this brain's upgrade; otherwise a connector host older than v0.60.11.0 admitted it. The consumer recovers any file publication in progress first, then fails the request. | `pre_upgrade`: nothing to do; the item is fetched again on the next `gbrain sync --source <source>` under a new request ID. Otherwise: `gbrain upgrade` on the host that runs connector jobs, then `gbrain sync --source <source>`. |+| <a id="unsupported-mutation-protocol"></a>`consumer_upgrade_required` | `unsupported_mutation_protocol` | A v0.60.11.0 connector sent a `connector_v2_*` write to a persistence consumer older than v0.60.11.0, which does not know the format. Other `permission_denied` refusals on connector receipts are never relabeled as upgrades. | `gbrain upgrade` on every consumer and worktree-owner host, then `gbrain sync --source <source>`. Upgrade those hosts before connector hosts. |+| `unbound_source` | `owner_unavailable` | On Postgres, a page write went to a source that has a checkout path but no canonical owner. It is refused by default because another host may own the files. The same reason appears when the source was bound, or the page gained a canonical file, after a database-only write was accepted, and (as a `source_changed` sync failure) when a canonical file appears at the path of a page written while the source was unbound. | Bind the source (`gbrain sources writer status <source> --json`, then `gbrain sources writer claim <source> --path <checkout> --admin-intent writer_claim --expected-state <admin_state>`), or opt in with `gbrain config set persistence.unbound_write database_only`. See [unbound sources on Postgres](#unbound-sources-on-postgres). |+| <a id="embedding_zero_norm"></a>`zero_norm`, `non_finite` or `empty_input` | `embedding_zero_norm` | The embedding provider returned a vector with no direction (all zeros, NaN or infinity) for a chunk, or the chunk text was empty. A vector index silently skips such a row, so gbrain refuses to store it. Only that chunk is refused: the page text and every other chunk's vector are saved, and the page is left for `gbrain embed --stale`. It is never retried as a rate limit or network error. | Inspect the named page's chunk text (empty, whitespace- or symbol-only chunks are the usual cause) or the embedding provider, fix it, then run `gbrain embed <slug>` (add `--source <source>` for a non-default source). If normal text also returns zero vectors, the provider or model is broken; check it with `gbrain doctor`. || `targets_parked` (doctor: `parked_effects`) | effect `error_code` | A Git backup or withdrawal target failed five times in a row and was set aside so the other pages keep committing. The page write itself committed; its Git backup or withdrawal is incomplete. Contention, dependency waits, shutdown and transient database errors never count toward the five. | `gbrain sources writer status <source>`, fix the cause it names, preview with `gbrain sources writer retry-effects <source> --request-id <id> --dry-run`, then run it without `--dry-run`. Each run grants one more attempt per parked target; a target that fails again parks again. |+| <a id="writer_admin_locked"></a>`writer_admin_locked` | `writer_admin_locked` | The operator set the brain's writer admin lock (`gbrain sources writer lock`), so writer claim, activate, transfer prepare and transfer accept refuse for every caller. Ordinary writes are not affected. | Agents: stop and ask the operator; do not unlock it yourself. The operator runs, on the brain host, `gbrain sources writer unlock`, re-reads `gbrain sources writer status <source> --json`, administers, then `gbrain sources writer lock` again. See the [writer admin lock](../architecture/topologies.md#writer-admin-lock). |+| <a id="writer_not_quiesced"></a>`writer_not_quiesced` | `writer_not_quiesced` | Activation found an older writer, a legacy lock, or queued, running or recovering work. When work blocks it, the message names the blocking effect id, kind, source, page and request id. | Stop the writers named in the [claim and activate runbook](../architecture/topologies.md#claim-and-activate-runbook), inspect the named work with `gbrain sources writer status <source> --json`, let it finish, then retry. A committed write whose queued embedding effect is never claimed cannot be cleared by a command yet; see [stale queued embedding effects](repair.md#stale-queued-embedding-effects). |+| unknown option (repair) | `invalid_params` | `gbrain repair` refuses any option it does not list, so a mistyped flag or `--max-usd` never runs a repair silently without it. | Fix the option (`gbrain repair --help`). To cap paid repair work, run `gbrain doctor --remediate --yes --include-repairs --max-usd <n>`. |`gbrain doctor` reports parked targets as the `parked_effects` check with theexact `retry-effects` command per request. It reports `persistence_capacity`@@ -8579,6 +8812,52 @@ when lifetime request IDs or receipt bytes reach 80% of a limit, with the`gbrain config set` value to use; outstanding-request, queued-byte andrecovery-byte limits can refuse writes without that warning.+## Unbound sources on Postgres++A source with a checkout path (`local_path`, or `sync.repo_path` for the+`default` source) normally publishes every page write to a markdown file in+that checkout, through the source's canonical owner. PGLite claims that owner+automatically on the first write. Postgres does not, because several hosts can+share one Postgres brain and only one of them may own the files. Until someone+binds the source, `put_page`, `capture` and `delete_page` to it refuse with+`owner_unavailable` and `detail: unbound_source`. The suggestion names both+ways out with the real source filled in:++1. **Bind the source** on the host that holds the checkout. Run+ `gbrain sources writer status <source> --json` and note `admin_state`, then+ `gbrain sources writer claim <source> --path <checkout> --admin-intent writer_claim --expected-state <admin_state>`.+ If an operator has locked writer administration, ask them to unlock it+ first. Read [topologies](../architecture/topologies.md) before claiming a+ source that other hosts write to.+2. **Allow database-only writes** with+ `gbrain config set persistence.unbound_write database_only` (the default is+ `refuse`; no other value is accepted, and the key can only be set on the+ brain host). A `put_page` to a new page, or to a page that is already+ database-only, then writes to the database only. Its result says+ `write_through: { written: false, skipped: "unbound_source" }` with a+ warning. Pages written this way stay database-only: binding the source+ later does not materialize them into canonical files, later writes keep+ them database-only, and sync never deletes or overwrites them.++The opt-in never applies to a page that came from a canonical file (it has a+stored source path). An edit there could be lost on the owner's next sync, so+it keeps refusing with only the bind option. `capture` and `delete_page` also+keep refusing.++If the source is bound after a database-only write was accepted but before it+was published, the write fails with the same reason and nothing is written;+read the page again and resubmit with a new request ID. If a canonical file+appears at the path of a database-only page after binding, sync stops for that+file with `source_changed` and reason `unbound_source`; neither copy is+overwritten and the database page stays served. Rename or remove the file,+commit, and sync again.++`gbrain doctor` reports the `unbound_source` check: the number of such pages+per source. While the source is unbound it is `ok` and prints the bind command;+after binding it warns, because those pages sit outside the canonical files.+There is no command yet that turns them into files; to move one, save its+content under a new slug and delete the database-only page.+## Related- [Concurrent writes and durable receipts](concurrent-writes.md) — receipt states, retries, capacity limitsdiff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex 816af9a0f3..328c16dbfd 100644--- a/openclaw.plugin.json+++ b/openclaw.plugin.json@@ -1,7 +1,7 @@{"id": "gbrain-context-engine","name": "gbrain",- "version": "0.60.10.0",+ "version": "0.60.11.0","description": "Personal knowledge brain with Postgres + pgvector hybrid search","family": "bundle-plugin","kind": "context-engine",diff --git a/package.json b/package.jsonindex 55332bf4f9..5fd610084b 100644--- a/package.json+++ b/package.json@@ -191,11 +191,11 @@"bun": ">=1.3.11"},"license": "MIT",- "version": "0.60.10.0",+ "version": "0.60.11.0","overrides": {"@ai-sdk/provider-utils": "4.0.33","@hono/node-server": "^2.0.5",- "fast-uri": "3.1.7",+ "fast-uri": "3.1.8","body-parser": "^2.3.0","fast-xml-builder": "^1.1.7","fast-xml-parser": "^5.7.0",diff --git a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json b/plugin-variants/gbrain-coding/.claude-plugin/plugin.jsonindex d8908b3d6c..a58e967dad 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.60.10.0",+ "version": "0.60.11.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 5eeccc79b5..a7f8857468 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.60.10.0",+ "version": "0.60.11.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 038045eafa..b85a6ed521 100644--- a/plugin-variants/gbrain-coding/README.md+++ b/plugin-variants/gbrain-coding/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.60.10.0 -->+<!-- gbrain-plugin-tree-stamp: 0.60.11.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-coding/skills/maintain/SKILL.md b/plugin-variants/gbrain-coding/skills/maintain/SKILL.mdindex 9e306da0e9..c2ec71d8fa 100644--- a/plugin-variants/gbrain-coding/skills/maintain/SKILL.md+++ b/plugin-variants/gbrain-coding/skills/maintain/SKILL.md@@ -69,24 +69,35 @@ ineligible for local writer administration.### Autonomous path (v0.36.4.0) — when you want to reach a target score-If the user asks "get my brain to 90/100" or "fix what's broken", prefer the-one-command loop over walking each dimension by hand:+If the user asks "get my brain to 90/100" or "fix what's broken", preview first+and ask before applying anything:```bash-gbrain doctor --remediation-plan --json # preview what would run-gbrain doctor --remediate --yes --target-score 90 --max-usd 5+gbrain doctor --remediation-plan --json # preview: job steps + repair steps+# Show the user the repair steps (each "requires user agreement") and the cost.+# Only after the user agrees:+gbrain doctor --remediate --yes --include-repairs --target-score 90 --max-usd 5```-`--remediation-plan` prints a dependency-ordered list (sync before extract,-embed after consolidate, etc.) with per-step `est_seconds` and `est_usd_cost`.-`--remediate` walks the plan, submitting each step as a Minion job, re-checking-score between every step. `--max-usd N` is a hard cost cap — submission refuses-when the plan would exceed the cap (prevents synthesize loops from burning-Anthropic credits unattended).+`--remediation-plan` prints a dependency-ordered list of job steps (sync before+extract, embed after consolidate, etc.) with per-step `est_seconds` and+`est_usd_cost`, and, independent of the score target, the PROTECTED repair steps+for every `gbrain repair` kind with pending items. Each step carries the exact+command that applies it, and the plan ends with one combined command.+`--remediate` runs the repair steps only with `--include-repairs` (the user's+agreement; without it they are listed as skipped), then walks the job plan,+submitting each step as a Minion job and re-checking score between steps.+`--max-usd N` is a cumulative cost cap across the run and every `--resume`: a+paid step that would exceed it is not started, free steps still run, and the run+stops with a resume command that keeps the cap and the agreement.When the target score is unreachable for the brain (empty brain with no entitypages → `graph_coverage` caps at 70; unconfigured embedding key → caps at 60),-the command bails with a list of what's missing rather than looping.+job steps stop with a list of what's missing rather than looping; included repair+steps still run. `--json` classifies each finding `cleared`, `pending`,+`consent_required`, `operator_required` (follow its instruction) or+`unsupported` (report it; nothing clears it yet). After an upgrade, follow the+recipe in `docs/guides/repair.md#recover-after-upgrading-to-this-release`.Use the per-dimension walk below (Phase 2 onward) when:- The user explicitly asks for a dimension-by-dimension auditdiff --git a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json b/plugin-variants/gbrain-daily/.claude-plugin/plugin.jsonindex 28cea1795a..e7ac70e595 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.60.10.0",+ "version": "0.60.11.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 5257a7debf..1bc6b59f5a 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.60.10.0",+ "version": "0.60.11.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 79de8b31f2..2544010ee6 100644--- a/plugin-variants/gbrain-daily/README.md+++ b/plugin-variants/gbrain-daily/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.60.10.0 -->+<!-- gbrain-plugin-tree-stamp: 0.60.11.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 21d29a2fbd..a9da338047 100644--- a/plugin/README.md+++ b/plugin/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.60.10.0 -->+<!-- gbrain-plugin-tree-stamp: 0.60.11.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/plugin/skills/maintain/SKILL.md b/plugin/skills/maintain/SKILL.mdindex 9e306da0e9..c2ec71d8fa 100644--- a/plugin/skills/maintain/SKILL.md+++ b/plugin/skills/maintain/SKILL.md@@ -69,24 +69,35 @@ ineligible for local writer administration.### Autonomous path (v0.36.4.0) — when you want to reach a target score-If the user asks "get my brain to 90/100" or "fix what's broken", prefer the-one-command loop over walking each dimension by hand:+If the user asks "get my brain to 90/100" or "fix what's broken", preview first+and ask before applying anything:```bash-gbrain doctor --remediation-plan --json # preview what would run-gbrain doctor --remediate --yes --target-score 90 --max-usd 5+gbrain doctor --remediation-plan --json # preview: job steps + repair steps+# Show the user the repair steps (each "requires user agreement") and the cost.+# Only after the user agrees:+gbrain doctor --remediate --yes --include-repairs --target-score 90 --max-usd 5```-`--remediation-plan` prints a dependency-ordered list (sync before extract,-embed after consolidate, etc.) with per-step `est_seconds` and `est_usd_cost`.-`--remediate` walks the plan, submitting each step as a Minion job, re-checking-score between every step. `--max-usd N` is a hard cost cap — submission refuses-when the plan would exceed the cap (prevents synthesize loops from burning-Anthropic credits unattended).+`--remediation-plan` prints a dependency-ordered list of job steps (sync before+extract, embed after consolidate, etc.) with per-step `est_seconds` and+`est_usd_cost`, and, independent of the score target, the PROTECTED repair steps+for every `gbrain repair` kind with pending items. Each step carries the exact+command that applies it, and the plan ends with one combined command.+`--remediate` runs the repair steps only with `--include-repairs` (the user's+agreement; without it they are listed as skipped), then walks the job plan,+submitting each step as a Minion job and re-checking score between steps.+`--max-usd N` is a cumulative cost cap across the run and every `--resume`: a+paid step that would exceed it is not started, free steps still run, and the run+stops with a resume command that keeps the cap and the agreement.When the target score is unreachable for the brain (empty brain with no entitypages → `graph_coverage` caps at 70; unconfigured embedding key → caps at 60),-the command bails with a list of what's missing rather than looping.+job steps stop with a list of what's missing rather than looping; included repair+steps still run. `--json` classifies each finding `cleared`, `pending`,+`consent_required`, `operator_required` (follow its instruction) or+`unsupported` (report it; nothing clears it yet). After an upgrade, follow the+recipe in `docs/guides/repair.md#recover-after-upgrading-to-this-release`.Use the per-dimension walk below (Phase 2 onward) when:- The user explicitly asks for a dimension-by-dimension auditdiff --git a/scripts/bench-grandfather-5530.ts b/scripts/bench-grandfather-5530.tsnew file mode 100644index 0000000000..073d074489--- /dev/null+++ b/scripts/bench-grandfather-5530.ts@@ -0,0 +1,109 @@+#!/usr/bin/env bun+/**+ * #5530 benchmark: wall time per page for the v0.13.1 managed grandfather+ * step on a durability-hardened canonical repository that tracks a local+ * bare remote. Every page is its own admitted put_page; the measurement+ * covers admission, publication and the page's Git commit and push.+ *+ * bun scripts/bench-grandfather-5530.ts [--pages 250] [--postgres <url>] [--no-harden] [--no-push] [--json]+ *+ * --no-harden skips the durability hook, so Git effects record without running+ * git: the difference between the two runs is the Git share of the step.+ * --no-push unsets the branch upstream, so effects commit but never push.+ *+ * Isolated: a temporary GBRAIN_HOME, an in-memory PGLite brain (or a fresh+ * database on the given test Postgres server) and a local bare remote. It+ * never opens an operator brain and never reaches the network.+ */+import { chmodSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { randomUUID } from 'node:crypto';++function arg(name: string): string | undefined {+ const at = process.argv.indexOf(name);+ return at >= 0 ? process.argv[at + 1] : undefined;+}+const pages = Number(arg('--pages') ?? 250);+const databaseUrl = arg('--postgres');+const json = process.argv.includes('--json');+const harden = !process.argv.includes('--no-harden');+const push = !process.argv.includes('--no-push');++function git(root: string, ...args: string[]): string {+ const result = Bun.spawnSync(['git', '-C', root, ...args]);+ if (result.exitCode) throw new Error(`git ${args.join(' ')}: ${result.stderr.toString()}`);+ return result.stdout.toString();+}++const home = realpathSync.native(mkdtempSync(join(tmpdir(), 'gbrain-bench-5530-')));+process.env.GBRAIN_HOME = home;+delete process.env.DATABASE_URL;+delete process.env.GBRAIN_DATABASE_URL;++const { phaseCGrandfather } = await import('../src/commands/migrations/v0_13_1.ts');+const { claimWorktree } = await import('../src/core/persistence/ownership.ts');+const { activateSharedSkillPersistence } = await import('../src/core/persistence/skill-activation.ts');+const { submitPageMutation } = await import('../src/core/persistence/page-mutations.ts');+const { disposePersistenceConsumer } = await import('../src/core/persistence/service.ts');+const { PGLiteEngine } = await import('../src/core/pglite-engine.ts');+const { runPersistenceEffects } = await import('../src/core/persistence/effects.ts');+const { localHostId } = await import('../src/core/persistence/identity.ts');++const root = join(home, 'content'), remote = join(home, 'remote.git');+mkdirSync(root); mkdirSync(remote);+git(root, 'init', '-q', '-b', 'main');+git(root, 'config', 'user.name', 'Example Writer');+git(root, 'config', 'user.email', '[email protected]');+writeFileSync(join(root, 'README.md'), 'Benchmark\n');+git(root, 'add', 'README.md'); git(root, 'commit', '-q', '-m', 'Initial');+git(remote, 'init', '-q', '--bare');+git(root, 'remote', 'add', 'origin', remote); git(root, 'push', '-q', '-u', 'origin', 'main');++let engine: import('../src/core/engine.ts').BrainEngine, close: () => Promise<void>;+if (databaseUrl) {+ const { isolatedPersistencePostgres } = await import('../test/helpers/persistence-postgres.ts');+ ({ engine, close } = await isolatedPersistencePostgres(databaseUrl));+} else {+ const pglite = new PGLiteEngine(); await pglite.connect({}); await pglite.initSchema();+ engine = pglite; close = () => pglite.disconnect();+}+try {+ await engine.executeRaw("UPDATE sources SET local_path=$1 WHERE id='default'", [root]);+ await claimWorktree(engine, 'default', root);+ await activateSharedSkillPersistence(engine, { confirmQuiesced: true });+ const ctx = { engine, config: { engine: engine.kind, embedding_disabled: true }, sourceId: 'default',+ remote: false, dryRun: false, logger: { info() {}, warn() {}, error() {} } } as never;+ // Seed before hardening, so the seed writes skip Git and only the step under test commits and pushes.+ for (let i = 0; i < pages; i++) {+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug: `notes/page-${String(i).padStart(4, '0')}`, request_id: randomUUID(),+ content: `---\ntype: note\ntitle: Page ${i}\n---\n\nBenchmark page ${i}.\n` } });+ }+ await disposePersistenceConsumer(engine);+ git(root, 'add', '-A'); git(root, 'commit', '-q', '-m', 'Seed'); git(root, 'push', '-q');+ if (harden) {+ 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);+ }+ if (!push) git(root, 'branch', '--unset-upstream');+ const commitsBefore = Number(git(root, 'rev-list', '--count', 'HEAD').trim());+ const started = performance.now();+ const result = await phaseCGrandfather(engine, { yes: true, dryRun: false, noAutopilotInstall: true } as never);+ const stepSeconds = (performance.now() - started) / 1000;+ await disposePersistenceConsumer(engine);+ // Git work the step left queued still has to run before the pages are backed up.+ await engine.executeRaw("UPDATE persistence_effects SET next_attempt_at=now() WHERE state='queued'").catch(() => undefined);+ while (await runPersistenceEffects(engine, ctx.config as never, { hostId: localHostId(), limit: 20 }) > 0);+ const seconds = (performance.now() - started) / 1000;+ const commits = Number(git(root, 'rev-list', '--count', 'HEAD').trim()) - commitsBefore;+ const remoteHead = git(remote, 'rev-parse', 'main').trim() === git(root, 'rev-parse', 'HEAD').trim();+ const report = { engine: engine.kind, pages, hardened: harden, push, touched: result.detail.touched, failed: result.detail.failed, failures: result.detail.failures.slice(0, 3),+ step_seconds: Number(stepSeconds.toFixed(2)), seconds: Number(seconds.toFixed(2)), seconds_per_page: Number((seconds / pages).toFixed(3)), commits, remote_matches_head: push ? remoteHead : null,+ platform: `${process.platform}-${process.arch}`, bun: Bun.version };+ console.log(json ? JSON.stringify(report) : Object.entries(report).map(([k, v]) => `${k}: ${v}`).join('\n'));+} finally {+ await disposePersistenceConsumer(engine);+ await close();+ rmSync(home, { recursive: true, force: true });+}diff --git a/scripts/e2e-test-map.ts b/scripts/e2e-test-map.tsindex 08bc1f4d3c..cb388c3690 100644--- a/scripts/e2e-test-map.ts+++ b/scripts/e2e-test-map.ts@@ -111,7 +111,8 @@ export const E2E_TEST_MAP: Record<string, string[]> = {"test/e2e/openclaw-plugin-load-real.test.ts",],// dream.ts is a thin alias over runCycle in cycle.ts.- "src/core/cycle.ts": ["test/e2e/cycle.test.ts", "test/e2e/dream.test.ts"],+ "src/core/cycle.ts": ["test/e2e/cycle.test.ts", "test/e2e/dream.test.ts", "test/e2e/managed-phase-matrix.test.ts"],+ "src/core/cycle/phase-*.ts": ["test/e2e/managed-phase-matrix.test.ts"],// Multi-source sync writes share the per-source bookmark anchor."src/core/sync.ts": ["test/e2e/sync.test.ts", "test/e2e/multi-source.test.ts", "test/e2e/sync-reconcile-postgres.test.ts", "test/e2e/sync-lock-overlap-postgres.test.ts"],// F7: real SIGKILL mid-sync on live Postgres — checkpoint banking@@ -157,11 +158,14 @@ export const E2E_TEST_MAP: Record<string, string[]> = {],// #3390: runSchemaTransition's DDL path + the stale predicates behave// differently on real pgvector than on PGLite.- "src/core/embedding-migration*.ts": ["test/e2e/migrate-embeddings-postgres.test.ts", "test/e2e/embedding-recovery-parity.test.ts", "test/e2e/memory-safety-wave-postgres.test.ts", ...MIGRATION_WAVE_TESTS],+ "src/core/embedding-migration*.ts": ["test/e2e/migrate-embeddings-postgres.test.ts", "test/e2e/embedding-recovery-parity.test.ts", "test/e2e/memory-safety-wave-postgres.test.ts", "test/e2e/embedding-migration-settle-postgres.test.ts", ...MIGRATION_WAVE_TESTS],+ // #5680: the per-request ceilings the migration reserves and settles under FOR UPDATE.+ "src/core/ai/embed-batch-plan.ts": ["test/e2e/embedding-migration-settle-postgres.test.ts"],"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", "test/e2e/w5-persistence-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", "test/e2e/managed-phase-matrix.test.ts"],+ "src/commands/lint.ts": ["test/e2e/managed-phase-matrix.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",@@ -197,6 +201,7 @@ export const E2E_TEST_MAP: Record<string, string[]> = {"src/core/db-lock.ts": ["test/e2e/db-lock-acquisition-token.test.ts", "test/e2e/sync-lock-overlap-postgres.test.ts", "test/e2e/managed-connector-fencing.test.ts", "test/e2e/managed-connector-recovery.test.ts"],"src/core/lease-schema.ts": ["test/e2e/db-lock-acquisition-token.test.ts"],"src/core/persistence/**": [+ "test/e2e/fix-wave-3-integration.test.ts","test/e2e/persistence-http-liveness.test.ts","test/e2e/persistence-phase-liveness.test.ts","test/e2e/persistence-idle-pool.test.ts",@@ -207,6 +212,8 @@ export const E2E_TEST_MAP: Record<string, string[]> = {"test/e2e/persistence-chaos.test.ts","test/e2e/persistence-runtime-matrix.test.ts","test/e2e/persistence-admin-intent.test.ts",+ "test/e2e/persistence-writer-admin-lock.test.ts",+ "test/e2e/persistence-writer-stamps.test.ts","test/e2e/persistence-recovery.test.ts","test/e2e/managed-sync-failures.test.ts","test/e2e/managed-connector-routing.test.ts",@@ -221,6 +228,10 @@ export const E2E_TEST_MAP: Record<string, string[]> = {"test/e2e/managed-atom-regressions.test.ts","test/e2e/managed-atom-compaction.test.ts","test/e2e/managed-maintenance.test.ts",+ "test/e2e/managed-writers-w3.test.ts",+ "test/e2e/managed-facts-writers.test.ts",+ "test/e2e/unbound-source-postgres.test.ts",+ "test/e2e/managed-phase-matrix.test.ts","test/e2e/managed-synthesis-postprocess.test.ts","test/e2e/persistence-embedding-effects.test.ts","test/e2e/withdrawal-bounded-safety-postgres.test.ts",@@ -229,6 +240,7 @@ export const E2E_TEST_MAP: Record<string, string[]> = {"test/e2e/reconcile-crash.test.ts","test/e2e/reconcile-crash-unactivated.test.ts","test/e2e/reconcile-pgbouncer.test.ts",+ "test/e2e/reconcile-unbound-collision.test.ts","test/e2e/persistence-skill-bundles-postgres.test.ts","test/e2e/shared-skills-transports.test.ts","test/e2e/canonical-projection-history.test.ts",@@ -239,14 +251,27 @@ export const E2E_TEST_MAP: Record<string, string[]> = {"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/repair/**": ["test/e2e/repair-command.test.ts", "test/e2e/derived-visibility-repair.test.ts", "test/e2e/safe-chunk-reseal.test.ts", "test/e2e/recovery-layer.test.ts", "test/e2e/repair-contextual-mode-5621-postgres.test.ts", "test/e2e/fix-wave-3-integration.test.ts"],+ "src/core/remediation/**": ["test/e2e/recovery-layer.test.ts"],+ "src/core/remediation-checkpoint.ts": ["test/e2e/recovery-layer.test.ts"],+ "src/commands/repair.ts": ["test/e2e/repair-command.test.ts", "test/e2e/repair-contextual-mode-5621-postgres.test.ts"],+ "src/core/import-contextual-mode.ts": ["test/e2e/repair-contextual-mode-5621-postgres.test.ts"],+ "src/core/ai/embedding-guard.ts": ["test/e2e/embedding-zero-norm-4616-postgres.test.ts"],+ "src/commands/reindex-vectors.ts": ["test/e2e/embedding-zero-norm-4616-postgres.test.ts"],+ "src/core/embedding-invalidation.ts": ["test/e2e/embed-stale-dry-run-restamp-5289-postgres.test.ts"],+ "src/core/persistence/effect-git.ts": ["test/e2e/persistence-git-coalescing-5530-postgres.test.ts"],+ "src/core/persistence/effect-journal.ts": ["test/e2e/persistence-git-coalescing-5530-postgres.test.ts"],+ "src/core/persistence/grandfather.ts": ["test/e2e/persistence-git-coalescing-5530-postgres.test.ts", "test/e2e/grandfather-projection-postgres.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"],+ "src/core/cycle/synthesize*.ts": ["test/e2e/managed-maintenance.test.ts", "test/e2e/managed-synthesis-postprocess.test.ts", "test/e2e/managed-writers-w3.test.ts"],+ "src/core/cycle/concept-publication.ts": ["test/e2e/managed-writers-w3.test.ts"],+ "src/core/chronicle/extract-events.ts": ["test/e2e/managed-writers-w3.test.ts"],+ "src/commands/enrich.ts": ["test/e2e/managed-writers-w3.test.ts"],+ "src/core/ops/links.ts": ["test/e2e/managed-writers-w3.test.ts"],"src/core/cycle/extract-atoms-page-state.ts": ["test/e2e/extract-atoms-page-state.test.ts", "test/e2e/reconcile-crash.test.ts", "test/e2e/reconcile-crash-unactivated.test.ts", "test/e2e/reconcile-pgbouncer.test.ts"],- "src/commands/migrations/v0_13_1.ts": ["test/e2e/grandfather-projection-postgres.test.ts"],+ "src/commands/migrations/v0_13_1.ts": ["test/e2e/grandfather-projection-postgres.test.ts", "test/e2e/persistence-git-coalescing-5530-postgres.test.ts"],"src/core/pool-budget.ts": ["test/e2e/persistence-runtime-matrix.test.ts"],"src/core/connection-manager.ts": ["test/e2e/persistence-runtime-matrix.test.ts", "test/e2e/pgbouncer-teardown.test.ts"],"src/core/postgres-engine.ts": [@@ -383,7 +408,7 @@ export const E2E_TEST_MAP: Record<string, string[]> = {"src/commands/autopilot.ts": ["test/e2e/autopilot-linux-lifecycle.serial.test.ts", "test/e2e/worker-readiness-cli.test.ts"],"src/commands/doctor.ts": ["test/e2e/doctor-progress.test.ts"],// Doctor check modules peeled from doctor.ts feed the same e2e surface.- "src/commands/doctor/**": ["test/e2e/doctor-progress.test.ts"],+ "src/commands/doctor/**": ["test/e2e/doctor-progress.test.ts", "test/e2e/recovery-layer.test.ts", "test/e2e/fix-wave-3-integration.test.ts"],// Knowledge graph layer feeds graph-quality."src/core/link-extraction.ts": ["test/e2e/graph-quality.test.ts", "test/e2e/attendance-retrieval-postgres.test.ts"],"src/core/attendance-repair.ts": ["test/e2e/attendance-repair-postgres.test.ts"],@@ -434,9 +459,24 @@ export const E2E_TEST_MAP: Record<string, string[]> = {"src/core/google/attachment-receipts.ts": ["test/e2e/google-attachments-postgres.test.ts"],"src/core/google/attachment-backfill.ts": ["test/e2e/google-attachments-postgres.test.ts"],"src/core/persistence/connector-google-receipts.ts": ["test/e2e/google-attachments-postgres.test.ts"],+ // Fix wave 3 lane A: connector identity, account pin, no-op kernel, pending set and migration 176.+ "src/core/persistence/connector-sync.ts": ["test/e2e/connector-wave3.test.ts"],+ "src/core/persistence/connector-identity.ts": ["test/e2e/connector-wave3.test.ts"],+ "src/core/persistence/connector-state.ts": ["test/e2e/connector-wave3.test.ts"],+ "src/core/persistence/connector-account.ts": ["test/e2e/connector-wave3.test.ts"],+ "src/core/persistence/connector-errors.ts": ["test/e2e/connector-wave3.test.ts"],+ "src/core/persistence/connector-status.ts": ["test/e2e/connector-wave3.test.ts"],+ "src/core/persistence/connector-reset.ts": ["test/e2e/connector-wave3.test.ts"],+ "src/core/persistence/connector-checkpoint-migration.ts": ["test/e2e/connector-wave3.test.ts"],+ "src/core/persistence/noop-kernel.ts": ["test/e2e/connector-wave3.test.ts"],+ "src/core/persistence/import-mutations.ts": ["test/e2e/connector-wave3.test.ts"],+ "src/core/persistence/sync-run.ts": ["test/e2e/connector-wave3.test.ts"],+ "src/core/persistence/sync-prepare.ts": ["test/e2e/connector-wave3.test.ts"],+ "src/core/persistence/accepted-pending.ts": ["test/e2e/connector-wave3.test.ts"],"src/commands/google-attachments.ts": ["test/e2e/google-attachments-postgres.test.ts"],"src/core/backup/**": ["test/e2e/backup-coverage-parity.test.ts"],"src/commands/backup.ts": ["test/e2e/backup-coverage-parity.test.ts"],"src/commands/doctor/checks/backup-coverage.ts": ["test/e2e/backup-coverage-parity.test.ts"],"src/commands/doctor/checks/sync-failures.ts": ["test/e2e/managed-sync-failures.test.ts"],+ "src/commands/doctor/checks/writer-version.ts": ["test/e2e/persistence-writer-stamps.test.ts"],};diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex a00298ebae..da81c9c51b 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -3,24 +3,24 @@# 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 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; +1 managed extract --stale delegation to a live PGLite owner-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 4609 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 ceiling; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +6 at the merge-src/commands/embed.ts 2171 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 failures; +2 fw3: embed --stale --images dispatch (sweep lives in core/embed-stale-images.ts)+src/cli.ts 4137 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; +1 managed extract --stale delegation to a live PGLite owner; +1 fix wave 3 integration: lane C and lane D command-dispatch additions composed at the merge+src/commands/autopilot.ts 2733 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; +4 fix wave 3 Lane D: pause/resume positional aliases, help row and dispatch (body in autopilot-pause.ts); +3 #5198 (PR #5613): activation-pending skip in the freshness dispatch loop (logic lives in sync-policy.ts)+src/commands/doctor.ts 4340 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 ceiling; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +6 at the merge; lowered to 4340: fix wave 3 Lane D moved --remediation-plan/--remediate into doctor/remediate.ts (-272) and registers wave checks through doctor/wave-checks.ts (+3)+src/commands/embed.ts 2182 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 failures; +2 fw3: embed --stale --images dispatch (sweep lives in core/embed-stale-images.ts); +5 #5289: dry run reports restamp-only chunks apart from chunks to embed (count lives in core/embedding-invalidation.ts); +6 #4616: keep a partially refused batch in embedPageTexts and name the recovery command in failure samples (guard lives in core/ai/embedding-guard.ts)src/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 2608 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; +5 fw3 derived-sync: timeline --prune-orphans CLI (#4649) and full-walk page link replacement; +13 fw3 A16/A15: sync link hook reads scoped page metadata and reports per-page extraction errors; +1 fw3 managed-lifecycle: extract --stale dispatches managed brains to the coordinator-safe path; +4 fw3 integration: managed brains refuse the direct timeline orphan prune; +26 #5609: managed extract --stale publishes links, canonical timeline and watermark per page in one coordinated transaction; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +4 at the merge-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/extract.ts 2615 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; +5 fw3 derived-sync: timeline --prune-orphans CLI (#4649) and full-walk page link replacement; +13 fw3 A16/A15: sync link hook reads scoped page metadata and reports per-page extraction errors; +1 fw3 managed-lifecycle: extract --stale dispatches managed brains to the coordinator-safe path; +4 fw3 integration: managed brains refuse the direct timeline orphan prune; +26 #5609: managed extract --stale publishes links, canonical timeline and watermark per page in one coordinated transaction; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +4 at the merge; +6 fix wave 3 lane B: a managed brain routes the extract phase file walk through extractManagedStaleLinks instead of the refused raw timeline batch, keeping the extract.links_fs progress phase+src/commands/jobs.ts 3266 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; +4 fix wave 3 #5405: the purge job reports coordinated purge blocks and fails on a coordinated purge failuresrc/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 hint-src/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 6016 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 managed sync result fields and notes line (slug collisions, derived links; printing lives in sync-diagnostics.ts); +11 fw3 A15: post-sync extraction failures logged and returned as extract_error; fw3 integration: derived-sync +11 and managed-lifecycle +3 compose (5995 + 14); +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; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +7 at the merge+src/core/ai/gateway.ts 4335 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; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner+src/commands/sync.ts 6022 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 managed sync result fields and notes line (slug collisions, derived links; printing lives in sync-diagnostics.ts); +11 fw3 A15: post-sync extraction failures logged and returned as extract_error; fw3 integration: derived-sync +11 and managed-lifecycle +3 compose (5995 + 14); +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; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +7 at the merge; +6 fix wave 3 lane A: --reset-checkpoint flag, SyncOpts field and help (connector-source guard lives in persistence/connector-reset.ts)src/core/cycle.ts 3217 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; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the mergesrc/core/cycle/synthesize.ts 3317 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; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge-src/core/cycle/extract-atoms.ts 1792 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; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge+src/core/cycle/extract-atoms.ts 1798 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; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts)src/core/engine.ts 2667 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; +2 fw3 A14: addTag tagSource provenance contract-src/core/import-file.ts 2283 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; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +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 count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge-src/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 ingestion+src/core/import-file.ts 2230 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; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +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 count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode)+src/core/migrate.ts 723 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 ingestion; +1 fix wave 3 lane A: static import of the v176 connector-checkpoint handler (engine-live paths use static imports)src/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 6184 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); +10 fw3-search: traversal walk row cap + (page, depth) dedupe (parity twin), source_boosts opt; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +8 at the merge; +9: PGLite statement-cache attach and release, savepoint-aware page guards (helpers live in pglite-statements.ts and page-state/guards.ts)+src/core/pglite-engine.ts 6186 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); +10 fw3-search: traversal walk row cap + (page, depth) dedupe (parity twin), source_boosts opt; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +8 at the merge; +9: PGLite statement-cache attach and release, savepoint-aware page guards (helpers live in pglite-statements.ts and page-state/guards.ts); +2 #4616: WAL-repair notice says indexes are not rebuilt and names gbrain reindex --vectorssrc/core/postgres-engine.ts 5590 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 lines; +8 fw3-search: traversal walk row cap + (page, depth) dedupe (parity twin), source_boosts opt; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the mergesrc/core/search/hybrid.ts 3125 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; lowered fw3-search: alias hop peeled to search/alias-hop.ts; +5 fw3-search: general title-mention boost skips concept intent and relational questions; fix wave 3 x fix wave 2 (v0.60.5.0) composition: -90 at the merge (hybrid.ts: alias hop lives in search/alias-hop.ts)src/core/types.ts 2086 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; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge@@ -30,10 +30,10 @@ src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connesrc/core/minions/handlers/subagent.ts 1918 ratchet merged: master v131 settle rework + dream-wave C5 peel + C6 accounting + C7 lease heartbeats/lost-lease aborts + C9 oneshot dispatch + adversarial fix batches; grown by #4078 subagent-loop capability fix; +6 lines (reasoning-item replay: adaptContentBlocksToChatBlocks handles 'reasoning' blocks); +3 wave G #4514: Anthropic-via-OpenRouter allowed on the subagent loop; +36 lines (code review, same PR): isPromptTooLongError walks a bounded .cause chain so it still matches post-normalizeAIError() wrapping, plus extractPromptTooLongDetail so the dead-lettered job's error carries the matched provider detail instead of the generic normalizeAIError() wrapper text; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; #5105: +13 call-site wiring to shared tool-write-identity helper across fresh and replay dispatchsrc/commands/bootstrap.ts 2115 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness); +5 for the harnessDetect test seam (bulk lives in core/bootstrap/harness.ts); +23 for the contract subcommand dispatcher glue (#4105 absorb — bulk lives in core/bootstrap/contract.ts); +codex hooks-consent gate + mcp+hooks receipt registration + uninstall arm; +42 ambient-writeback WP8: interview-time SURFACE_MULTIUSER audience apply (pre-init ordering) + applyDeclaredAudienceFromInterview; +3 #4897 harness usage clause documenting --source ID semanticssrc/core/minions/worker.ts 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 retry-src/commands/sources.ts 1993 ratchet grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules; canonical reconciliation: +5 engine-free sibling-command dispatch and help row, implementation remains in source-reconcile.ts+src/commands/sources.ts 1997 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; +4 fix wave 3 lane A: sources status connector recovery state and run counts (view lives in persistence/connector-status.ts)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 detail-src/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 revalidation-src/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/core/embedding-migration.ts 1515 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 revalidation; +2 #5680: authorization_generation field and its carry-forward on same-target re-apply (settle idempotency)+src/core/github-source.ts 1530 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; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refreshsrc/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 1795 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 wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the mergediff --git a/scripts/pglite-checkpoint-harness/supervisor.ts b/scripts/pglite-checkpoint-harness/supervisor.tsindex 8d351bd4f3..fba1a5914f 100644--- a/scripts/pglite-checkpoint-harness/supervisor.ts+++ b/scripts/pglite-checkpoint-harness/supervisor.ts@@ -5,16 +5,17 @@// 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+// /proc (from `ps` on macOS), 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.+// largest single transaction, or when --min-store-gb is set and the final+// data directory is smaller than that many GiB.//// 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 { execFileSync, 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';@@ -33,6 +34,7 @@ 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 minStoreGb = Number(arg('min-store-gb', '0'));const dataDir = join(dir, 'brain.pglite');const progressPath = join(dir, 'progress.ndjson');@@ -47,6 +49,13 @@ function dirBytes(path: string): number {}function cpuTicks(pid: number): number | null {try {+ if (process.platform !== 'linux') {+ // `ps` reports cumulative CPU as [[dd-]hh:]mm:ss.ss; convert to 1/100 s ticks.+ const time = execFileSync('ps', ['-o', 'time=', '-p', String(pid)], { encoding: 'utf8' }).trim();+ const [days, clock] = time.includes('-') ? time.split('-') as [string, string] : ['0', time];+ const seconds = clock.split(':').reduce((total, part) => total * 60 + Number(part), 0) + Number(days) * 86400;+ return Number.isFinite(seconds) ? Math.round(seconds * 100) : null;+ }const fields = readFileSync(`/proc/${pid}/stat`, 'utf8').split(') ')[1]!.split(' ');return Number(fields[11]) + Number(fields[12]);} catch { return null; }@@ -144,10 +153,13 @@ for (let k = 0; k < committed.length; k++) {}const walBound = guardThresholdBytes + maxTransactionWal;const walWithinBound = maxSinceRedo <= walBound;+const storeBytes = dirBytes(dataDir);+const storeLargeEnough = storeBytes >= minStoreGb * 2 ** 30;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) };+ store_bytes: storeBytes, store_bytes_without_wal: storeBytes - dirBytes(join(dataDir, 'pg_wal')), min_store_gb: minStoreGb,+ store_large_enough: storeLargeEnough, platform: `${process.platform}-${process.arch}`, 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);+process.exit(verdict.verdict === 'completed' && walWithinBound && storeLargeEnough ? 0 : 1);diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsvindex 59ec53d361..090274f397 100644--- a/scripts/structural-suites.tsv+++ b/scripts/structural-suites.tsv@@ -14,7 +14,7 @@ test/auto-link-targeted-probe-2544.test.ts #2544 — auto-link behavior throughtest/autopilot-auto-drain-wiring.test.ts autopilot auto-drain wiring 8 readFileSynctest/autopilot-cycle-failure-classification.test.ts autopilot cycle-failure classification — only 'failed' trips the circuit breaker 2 readFileSynctest/autopilot-cycle-failure-classification.test.ts runPhaseOrphans ratio threshold — no more absolute count > 20 3 readFileSync-test/autopilot-fanout-wiring.test.ts autopilot.ts ↔ dispatchPerSource wiring 16 readFileSync+test/autopilot-fanout-wiring.test.ts autopilot.ts ↔ dispatchPerSource wiring 17 readFileSynctest/autopilot-install.test.ts autopilot install — reload-safety (#2608) 1 readFileSynctest/autopilot-install.test.ts autopilot showStatus — wrapper-path detection 1 readFileSynctest/autopilot-install.test.ts autopilot wiring: chat-unavailable boot warning (#2608) 1 readFileSync@@ -45,7 +45,7 @@ test/brain-score-breakdown.test.ts linkable scope — archive pages do not dragtest/brainstorm-timeout.test.ts orchestrator entry-point wrap (CV11 single-point classification) 2 bun-filetest/build-llms.test.ts CLAUDE.md restructure content contracts 5 readFileSynctest/build-llms.test.ts build-llms generator 7 readFileSync-test/canonical-writer-inventory.test.ts (file-level) 2 readFileSync+test/canonical-writer-inventory.test.ts (file-level) 4 readFileSynctest/chat-key-plane.test.ts #3944 both planner surfaces share the helper (source guard) 2 readFileSynctest/check-bootstrap-guards.test.ts check-grok-pin.sh 9 readFileSynctest/check-bootstrap-guards.test.ts check-opencode-pin.sh 6 readFileSync@@ -212,6 +212,7 @@ test/pg-access-classify.test.ts marker contract (skill↔binary lockstep, the UPtest/pglite-engine.test.ts PGLiteEngine: v0.13.1 error-wrap on connect() (#223) 1 readFileSynctest/pglite-repair-command.serial.test.ts gbrain pglite-repair — interactive confirm wiring (#4318 residual) 1 readFileSynctest/pglite-wal-repair.serial.test.ts WAL auto-repair — real-brain regression (#223/#1670/#2575) 6 readFileSync+test/post-upgrade-banner.test.ts post-upgrade recovery banner 3 readFileSynctest/postgres-driver-vendor.test.ts vendored Postgres driver packaging 3 readFileSynctest/postgres-engine.test.ts postgres-engine / search date filtering 1 readFileSynctest/postgres-engine.test.ts postgres-engine / search path timeout isolation 7 readFileSync@@ -235,7 +236,7 @@ test/scripts/ci-local-rendering.test.ts ci-local execution coverage 3 readFileSytest/scripts/ci-local-rendering.test.ts local test configuration through run-e2e 2 readFileSynctest/scripts/ci-local-rendering.test.ts required PgBouncer execution through run-e2e 1 readFileSynctest/scripts/ci-pr-scope.test.ts pull-request CI scope 7 readFileSync-test/scripts/ci-runner-routing.test.ts CI runner routing 5 readFileSync+test/scripts/ci-runner-routing.test.ts CI runner routing 6 readFileSynctest/scripts/classify-tests.test.ts classify-tests detectors 20 bun-file,doctor-source-helper,exec-scan,readFileSynctest/scripts/coverage-diff-gate.test.ts exemptions 3 readFileSynctest/scripts/data-safety-native-workflow.test.ts data-safety native CI coverage 12 readFileSyncdiff --git a/skills/maintain/SKILL.md b/skills/maintain/SKILL.mdindex 9e306da0e9..c2ec71d8fa 100644--- a/skills/maintain/SKILL.md+++ b/skills/maintain/SKILL.md@@ -69,24 +69,35 @@ ineligible for local writer administration.### Autonomous path (v0.36.4.0) — when you want to reach a target score-If the user asks "get my brain to 90/100" or "fix what's broken", prefer the-one-command loop over walking each dimension by hand:+If the user asks "get my brain to 90/100" or "fix what's broken", preview first+and ask before applying anything:```bash-gbrain doctor --remediation-plan --json # preview what would run-gbrain doctor --remediate --yes --target-score 90 --max-usd 5+gbrain doctor --remediation-plan --json # preview: job steps + repair steps+# Show the user the repair steps (each "requires user agreement") and the cost.+# Only after the user agrees:+gbrain doctor --remediate --yes --include-repairs --target-score 90 --max-usd 5```-`--remediation-plan` prints a dependency-ordered list (sync before extract,-embed after consolidate, etc.) with per-step `est_seconds` and `est_usd_cost`.-`--remediate` walks the plan, submitting each step as a Minion job, re-checking-score between every step. `--max-usd N` is a hard cost cap — submission refuses-when the plan would exceed the cap (prevents synthesize loops from burning-Anthropic credits unattended).+`--remediation-plan` prints a dependency-ordered list of job steps (sync before+extract, embed after consolidate, etc.) with per-step `est_seconds` and+`est_usd_cost`, and, independent of the score target, the PROTECTED repair steps+for every `gbrain repair` kind with pending items. Each step carries the exact+command that applies it, and the plan ends with one combined command.+`--remediate` runs the repair steps only with `--include-repairs` (the user's+agreement; without it they are listed as skipped), then walks the job plan,+submitting each step as a Minion job and re-checking score between steps.+`--max-usd N` is a cumulative cost cap across the run and every `--resume`: a+paid step that would exceed it is not started, free steps still run, and the run+stops with a resume command that keeps the cap and the agreement.When the target score is unreachable for the brain (empty brain with no entitypages → `graph_coverage` caps at 70; unconfigured embedding key → caps at 60),-the command bails with a list of what's missing rather than looping.+job steps stop with a list of what's missing rather than looping; included repair+steps still run. `--json` classifies each finding `cleared`, `pending`,+`consent_required`, `operator_required` (follow its instruction) or+`unsupported` (report it; nothing clears it yet). After an upgrade, follow the+recipe in `docs/guides/repair.md#recover-after-upgrading-to-this-release`.Use the per-dimension walk below (Phase 2 onward) when:- The user explicitly asks for a dimension-by-dimension auditdiff --git a/skills/migrations/v0.60.11.0.md b/skills/migrations/v0.60.11.0.mdnew file mode 100644index 0000000000..f56399e9cf--- /dev/null+++ b/skills/migrations/v0.60.11.0.md@@ -0,0 +1,144 @@+# Upgrade to v0.60.11.0: resume connectors, finish managed maintenance, then preview and apply the agreed repairs++This release makes managed Google and GitHub connectors resume their saved+cursor and skip unchanged pages, moves the remaining maintenance writers on+managed brains onto the persistence coordinator, refuses degenerate embedding+vectors per chunk, and wires every `gbrain repair` kind into doctor's+remediation plan with a preview-only banner after `gbrain post-upgrade`.++Three migrations run automatically. None deletes a page, a receipt or a write+ID, holds a long transaction or starts a background service, and a rerun+changes nothing:++- **176** (handler) copies each connector source's newest committed checkpoint+ to its stable key, marks a source whose newest checkpoint receipt was+ compacted to re-walk once, and removes checkpoint rows no source can load.+- **177** adds `pages.database_only_reason` (nullable) for pages saved+ database-only to an unbound Postgres source.+- **178** adds five nullable writer-version columns to `persistence_requests`+ and records its cutoff with the database clock.++Never apply a repair, raise a limit, lock, unlock or resume on the user's+behalf without asking. Every step below that changes the brain needs the+user's agreement first.++1. **Upgrade hosts in order, with autopilot paused.** List with the user every+ host that uses this brain. On each host that runs connector jobs, pause+ autopilot first; upgrade the hosts that run the persistence consumer or own+ a worktree before the connector hosts; then resume:++ ```bash+ gbrain autopilot pause --reason "upgrading to v0.60.11.0" # each connector host+ gbrain upgrade # consumer and worktree-owner hosts first+ gbrain upgrade # then connector hosts+ gbrain doctor --remediation-plan # step 4+ gbrain autopilot resume # each host you paused+ gbrain sources status # verify (step 3)+ ```++ The pause survives `gbrain upgrade`. Mixed versions refuse with typed errors+ instead of losing data: a new connector talking to an old consumer fails+ `unsupported_mutation_protocol` and names the consumer upgrade; an old+ connector talking to a new consumer fails `connector_intent_outdated`. If+ schema work did not complete, run+ `gbrain apply-migrations --yes --no-autopilot-install` on the brain host.++2. **Tell the user to expect one connector re-walk, once.** Connector writes+ queued before the upgrade fail once with `connector_intent_outdated` (detail+ `pre_upgrade`, no action needed) and are fetched again on the next run. A+ source the migration marked to re-walk re-admits its window once. This+ first spike is expected and is not the hourly churn this release fixes. The+ post-upgrade banner prints the count as `connector_rewalk`.++3. **Verify connectors with `gbrain sources status --json`.** Each connector+ source has a `connector` block ([shape](../../docs/guides/repair.md#connector-checkpoints)).+ After the second run, a quiet source shows `last_run.page_admissions: 0`.+ - For each source the migration printed+ `resumed from pre-upgrade checkpoint of <time>` (kept as `resumed_from`):+ if the user changed a content setting such as `g_history_days` since+ then, run `gbrain sync --source <id> --reset-checkpoint`. Unchanged pages+ are not admitted again.+ - Each connector source pins the account its credential resolves to on its+ first run. If a run refuses `connector_account_changed`, relay its two+ branches: restore the credential for the pinned account, or add a new+ source for the new account and archive the old one. No reset flag changes+ the account.++4. **Relay the post-upgrade banner, then preview the recovery plan and ask.**+ When `gbrain post-upgrade` prints an `[AGENT] Relay this to your operator`+ block, show it to the user as-is. It lists each finding and its count and+ never applies anything. Then:++ ```bash+ gbrain doctor --remediation-plan+ ```++ Show the user the repair steps (each marked "requires user agreement"),+ their estimated cost, and the combined command at the end. The kinds are+ `timeline`, `visibility`, `safe-chunks`, `contextual-mode` (stamps the+ contextual retrieval mode on pages imported without one; may re-embed a+ page whose input changes) and `connector-checkpoints` (removes orphan+ connector cursor rows; free). Ask which to apply and what spending cap they+ accept.++5. **Apply only what the user agreed to**, with their cap:++ ```bash+ gbrain doctor --remediate --yes --include-repairs --max-usd <n>+ ```++ Pass `--no-embed` if they want no paid embeddings (then `gbrain embed+ --stale` later). If the run stops as budget-exhausted, ask again before+ running the printed resume command; the cap is cumulative across resumes.++6. **Report what is left.** The run prints each remaining finding with its+ class. For `operator_required`, relay the instruction (for example the+ #5413 quarantine commands in `docs/guides/repair.md#quarantine-self-captured-corpus-files`,+ `gbrain upgrade` on a host that `writer_version` names, or the reset command+ `dream_paid_loop` prints). For `unsupported`, tell the user it is known and+ cannot be cleared yet.++7. **Postgres sources with a checkout folder but no owner.** Saving a page+ there still refuses by default, with `owner_unavailable` and detail+ `unbound_source`. Ask the user which fix they want; do not pick for them:+ - bind the source: `gbrain sources writer status <source> --json`, then+ the printed `gbrain sources writer claim <source> --path <path>+ --admin-intent writer_claim --expected-state <admin_state>`; or+ - allow database-only saves:+ `gbrain config set persistence.unbound_write database_only`. Pages saved+ this way stay database-only after the source is bound.++ `gbrain doctor` reports `unbound_source`: ok while the source is unbound, a+ warning once it is bound. When a canonical file later appears at such a+ page's path, preview both sides with+ `gbrain sources reconcile <source> <slug> --brain <brain> --preview` and+ apply only the resolution the user chose.++8. **Tell the user what else changes.**+ - Global maintenance keeps running when one phase fails; the run is+ reported as partial and `gbrain dream` exits non-zero. Concept synthesis,+ chronicle extraction, the purge of deleted pages, enrichment,+ `add_link` / `remove_link`, bootstrap verify and the facts writers now+ work on managed brains.+ - An embedding provider that returns an all-zero or broken vector for a+ chunk now gets that chunk refused with `embedding_zero_norm`; the page+ keeps its text and every other vector, and the failure names+ `gbrain embed <slug>`.+ - `gbrain migrate embeddings --max-cost-usd <n>` stops with+ `embedding_budget_below_worst_case` before changing anything when the cap+ is below the printed worst case. Rerun only with the user's agreement.+ - If the user saw "gbrain repaired this brain's PGLite WAL in place", run+ `gbrain reindex --vectors` (free; nothing is re-embedded).++9. **Verify.**++ ```bash+ gbrain doctor --remediation-plan # no repair steps left+ gbrain sources status --json # quiet connectors: page_admissions 0+ gbrain sources writer status --json # writer versions per host+ ```++Optional, only if the user asks: `gbrain sources writer lock` stops agents+from claiming, activating or transferring writers on this brain until the+operator runs `gbrain sources writer unlock`. See the writer admin lock in+`docs/architecture/topologies.md`.diff --git a/skills/skills.lock.json b/skills/skills.lock.jsonindex 904102e379..c1180a2763 100644--- a/skills/skills.lock.json+++ b/skills/skills.lock.json@@ -92,7 +92,7 @@"idea-lineage/SKILL.md": "bbf37781d93b71ddc7909ecc5ab635872c874fb8591995dbf88b45ffeac6b1de","idea-lineage/routing-eval.jsonl": "ee2e00704b9accb7dd58bb8f126a3bc04a2c40be499180fa505dbf6d5061cd41","ingest/SKILL.md": "dc40ecc0072806fb8c7bb6ab9cf1f103842e05653eb55d67632d7e3ffc4dd7d2",- "maintain/SKILL.md": "74244af50a4faf3d3b2f16250cae0d01c2911fa50d2fca1a02f936f9dc2a21d6",+ "maintain/SKILL.md": "1bd23d13dd9804b97fbc75e13161f1a654fb2dde98d17a10e73bf3170cf8034e","manifest.json": "357aa185d380f0a357cb15cd513317e290cbc5fcf5ca4e3860b0e829fdcbf1e4","mcp-access/SKILL.md": "d96d0720d3f15f442e2f87803354206795f04ae114869a2cf608aa5c9955585d","measure-before-you-fix/SKILL.md": "1fd3b40ab65cbd08f50dea16107701859165469be3c85c57d779c7b4bbf92db8",@@ -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.11.0.md": "ad3086df4eceff272f08bf16d674be404b97963292729b280f44268c583f77c5","migrations/v0.60.5.0.md": "0d3ee19359a2740de08ac9ec388ddc15e7c72d663afe33832e1e54170528acab","migrations/v0.60.6.0.md": "1cbfca2c899e1348acbd61f0baa4c8e723b5283ff868c710c74e116c0cb6726e","migrations/v0.7.0.md": "97c2740445a10b1c5c7123c17dbd625fa27a94095b85d27c2b278da756c4c59a",diff --git a/src/cli.ts b/src/cli.tsindex 8cc015f9af..aa64437cba 100755--- a/src/cli.ts+++ b/src/cli.ts@@ -2968,6 +2968,7 @@ async function handleCliOnly(command: string, args: string[]) {args = resolveAutopilotPositionals(args);if (args.includes('--uninstall')) { uninstallDaemon(); return; }if (args.includes('--status')) { runAutopilotStatus(args); return; }+ if (args.includes('--pause') || args.includes('--resume')) { (await import('./commands/autopilot-pause.ts')).runAutopilotPauseCommand(args); return; }}// Thin-client `think` dispatch: runThinkCli already routes through@@ -3290,6 +3291,10 @@ async function handleCliOnly(command: string, args: string[]) {}break;}+ if (args.includes('--vectors')) {+ await (await import('./commands/reindex-vectors.ts')).runReindexVectors(engine, args); // #4616+ break;+ }if (args.includes('--aliases')) {// T8 — backfill the free-text alias layer (page_aliases) for existing// pages whose frontmatter `aliases:` predate the import-time projection.diff --git a/src/commands/autopilot-fanout.ts b/src/commands/autopilot-fanout.tsindex e0fddff8c7..366b080db8 100644--- a/src/commands/autopilot-fanout.ts+++ b/src/commands/autopilot-fanout.ts@@ -38,6 +38,7 @@ import type { MinionQueue } from '../core/minions/queue.ts';import { SOURCE_FRESHNESS_PHASES, MAINTENANCE_PHASES, LAST_GLOBAL_AT_KEY } from '../core/cycle.ts';import { sourceConfigHasRemoteUrl, sourceLocalPathSkipWarning } from '../core/sources-load.ts';import { isSyncDisabledConfig } from '../core/sync-policy.ts';+import { loadActivationPendingSourceIds, skipActivationPendingSync } from '../core/sync-policy.ts';import { AUTOPILOT_FULL_CYCLE_FLOOR_MINUTES } from './autopilot-remediation-policy.ts';// #2194 fix #2: failure cooldown. A source whose autopilot-cycle keeps@@ -502,6 +503,9 @@ export async function dispatchPerSource(}}+ // #5198: claimed-but-not-activated sources refuse sync until activation.+ const activationPending = await loadActivationPendingSourceIds(engine);+const dispatched: string[] = [];const coalesced: string[] = [];for (const src of dispatch) {@@ -510,7 +514,12 @@ export async function dispatchPerSource(// sync. It still gets its lint/backlinks/extract cycle and freshness// stamp; only the sync phase (and the pull that feeds it) is dropped —// normalizeQueuedSourcePhases passes a freshness subset through as-is.- const syncDisabled = isSyncDisabledConfig(src.config);+ // #5198: a claimed source awaiting activation is treated the same way,+ // so its cycle does not fail on a sync that is refused by contract.+ const pendingActivation = skipActivationPendingSync(+ activationPending, src.id, 'fanout_sync_skipped', opts.jsonMode === true, opts.jsonMode ? emit : log,+ );+ const syncDisabled = isSyncDisabledConfig(src.config) || pendingActivation;const shouldPull = sourceConfigHasRemoteUrl(src.config) && !syncDisabled;const job = await queue.add('autopilot-cycle',diff --git a/src/commands/autopilot-pause.ts b/src/commands/autopilot-pause.tsnew file mode 100644index 0000000000..4283923f84--- /dev/null+++ b/src/commands/autopilot-pause.ts@@ -0,0 +1,48 @@+/**+ * `gbrain autopilot pause [--reason <text>]` and `gbrain autopilot resume`:+ * the operator's own hold on this host's autopilot daemon and job workers.+ * Engine-free (a live PGLite daemon holds the database lock). The pause is+ * its own marker, so `gbrain upgrade` and `gbrain autopilot --install` keep it,+ * and resume clears only it — never a migration or backup-restore hold.+ */+import { mkdirSync, readFileSync, unlinkSync, writeFileSync } from 'fs';+import { dirname } from 'path';+import { hostname } from 'os';+import { autopilotOperatorPauseMarkerPath, autopilotPausedMarkerPath } from '../core/autopilot-paths.ts';++function read(path: string): string | null {+ try { return readFileSync(path, 'utf-8').trim(); } catch { return null; }+}++export function runAutopilotPauseCommand(args: string[]): void {+ const json = args.includes('--json');+ const operator = autopilotOperatorPauseMarkerPath();+ const at = args.indexOf('--reason');+ const reason = at >= 0 ? args[at + 1] : undefined;+ if (at >= 0 && (!reason || reason.startsWith('--'))) { console.error('--reason requires a value.'); process.exit(2); }+ let action: string;+ if (args.includes('--pause')) {+ const existing = read(operator);+ if (existing === null || reason !== undefined) {+ mkdirSync(dirname(operator), { recursive: true });+ writeFileSync(operator, `operator pause since ${new Date().toISOString()} on ${hostname()}: ${reason ?? 'no reason given'}\n`, { mode: 0o600 });+ }+ action = existing === null ? 'paused' : 'already_paused';+ } else {+ try { unlinkSync(operator); action = 'resumed'; } catch { action = 'not_paused'; }+ }+ const operatorPause = read(operator);+ const hold = read(autopilotPausedMarkerPath());+ if (json) {+ console.log(JSON.stringify({ action, operator_pause: operatorPause, other_hold: hold, paused: operatorPause !== null || hold !== null }));+ return;+ }+ if (action === 'paused' || action === 'already_paused') {+ console.log(`Autopilot ${action === 'paused' ? 'paused' : 'is already paused'} on this host: ${operatorPause}`);+ console.log('The daemon skips cycles and workers stop claiming jobs at their next poll; an in-flight job finishes.');+ console.log('`gbrain upgrade` and `gbrain autopilot --install` keep this pause. Resume with: gbrain autopilot resume');+ } else {+ console.log(action === 'resumed' ? 'Operator pause cleared; autopilot resumes at its next poll.' : 'No operator pause was set on this host.');+ }+ if (hold !== null) console.log(`Another hold is still present and was not touched (it clears when its operation finishes): ${hold}`);+}diff --git a/src/commands/autopilot.ts b/src/commands/autopilot.tsindex cedae7d1fc..97c0887aca 100644--- a/src/commands/autopilot.ts+++ b/src/commands/autopilot.ts@@ -49,6 +49,7 @@ import { inspectLock } from '../core/db-lock.ts';import { registerCleanup } from '../core/process-cleanup.ts';import { loadAllSources, sourceConfigHasRemoteUrl, sourceLocalPathSkipWarning, relativeSourceLocalPathSkipWarning } from '../core/sources-load.ts';import { isSyncDisabledConfig } from '../core/sync-policy.ts';+import { loadActivationPendingSourceIds, skipActivationPendingSync } from '../core/sync-policy.ts';import { resolveAutopilotDispatchTimeoutMs } from './autopilot-timeout.ts';import {autopilotRemediationIdempotencyKey,@@ -63,6 +64,8 @@ import {autopilotLockPath,autopilotDisabledMarkerPath,autopilotPausedMarkerPath,+ autopilotPaused,+ autopilotPauseReason,autopilotDisableStrikesPath,autopilotLaunchdLabel,markerHolderAlive,@@ -515,7 +518,7 @@ async function attemptAutopilotSelfUpgrade(}/** Flags that consume the following argv token as their value (#1525). */-const AUTOPILOT_VALUE_FLAGS = new Set(['--repo', '--interval', '--target']);+const AUTOPILOT_VALUE_FLAGS = new Set(['--repo', '--interval', '--target', '--reason']);/** Positional spellings → their canonical flags. A Map (not a plain object)* so prototype-chain words like `constructor` stay unknown positionals. */@@ -523,6 +526,8 @@ const AUTOPILOT_POSITIONAL_ALIASES = new Map<string, string>([['status', '--status'],['install', '--install'],['uninstall', '--uninstall'],+ ['pause', '--pause'],+ ['resume', '--resume'],['help', '--help'],]);@@ -554,7 +559,7 @@ export function resolveAutopilotPositionals(args: string[]): string[] {}if (a === 'start') continue; // daemon start is the default actionconsole.error(- `Unknown autopilot argument '${a}'. Expected one of: status, install, uninstall, start, help.\n` ++ `Unknown autopilot argument '${a}'. Expected one of: status, install, uninstall, pause, resume, start, help.\n` +`Run 'gbrain autopilot --help' for usage.`,);process.exit(2);@@ -598,7 +603,8 @@ export async function runAutopilot(engine: BrainEngine, args: string[]) {'Usage: gbrain autopilot [--repo <path>] [--interval N] [--json] [--no-worker]\n' +' gbrain autopilot --install [--repo <path>]\n' +' gbrain autopilot --uninstall\n' +- ' gbrain autopilot --status [--json]\n\n' ++ ' gbrain autopilot --status [--json]\n' ++ ' gbrain autopilot pause [--reason <text>] | resume (operator hold; upgrade and --install keep it)\n\n' +'Self-maintaining brain daemon. Runs the full maintenance cycle\n' +'(lint + backlinks + sync + extract + embed + orphans) on an interval.\n\n' +'For a one-shot cron-triggered cycle, see `gbrain dream`.',@@ -618,6 +624,7 @@ export async function runAutopilot(engine: BrainEngine, args: string[]) {runAutopilotStatus(args);return;}+ if (args.includes('--pause') || args.includes('--resume')) return (await import('./autopilot-pause.ts')).runAutopilotPauseCommand(args);const repoPath = parseArg(args, '--repo') || await engine.getConfig('sync.repo_path');// Same NaN guard as the status path: a typo'd interval would otherwise@@ -945,7 +952,7 @@ export async function runAutopilot(engine: BrainEngine, args: string[]) {// heartbeat so a paused daemon still reads as alive, and BEFORE any DB// work so a cross-engine migration is not racing our writes into an// engine that is about to stop being the configured one.- if (existsSync(autopilotPausedMarkerPath())) {+ if (autopilotPaused()) {// Self-heal an orphan: a migrate-owned marker whose recorded pid is dead// was leaked by a killed migration (SIGKILL, power loss — anything its// own cleanup could not catch). Nothing else ever deletes it, and an@@ -960,7 +967,8 @@ export async function runAutopilot(engine: BrainEngine, args: string[]) {if (orphaned) {console.log('[autopilot] clearing an orphaned pause marker (its migrate process is dead); resuming.');try { unlinkSync(autopilotPausedMarkerPath()); } catch { /* already gone */ }- } else {+ }+ if (autopilotPaused()) {if (!pausedAnnounced) {console.log('[autopilot] paused (autopilot-paused marker present) — skipping cycles until it clears.');pausedAnnounced = true;@@ -1128,6 +1136,7 @@ export async function runAutopilot(engine: BrainEngine, args: string[]) {const { isFederatedV2Enabled } = await import('../core/feature-flags.ts');if (await isFederatedV2Enabled(engine)) {const sources = await loadAllSources(engine);+ const activationPending = await loadActivationPendingSourceIds(engine);const intervalMs = baseInterval * 1000;const now = Date.now();for (const src of sources) {@@ -1136,6 +1145,7 @@ export async function runAutopilot(engine: BrainEngine, args: string[]) {// sync (this loop, the full-cycle fan-out, `sync --all`); an// explicit `gbrain sync --source <id>` is unaffected.if (isSyncDisabledConfig(src.config)) continue;+ if (skipActivationPendingSync(activationPending, src.id, 'freshness_sync_skipped', jsonMode, (l) => process.stderr.write(l + '\n'))) continue; // #5198// A local_path this machine cannot use — relative (#3696: cwd is// launchd's, not the registering shell's) or absent on disk and// not a managed clone sync can re-create — would sync a phantom@@ -2653,10 +2663,7 @@ function showStatus(json: boolean, intervalSeconds: number) {disabledReason = readFileSync(autopilotDisabledMarkerPath(), 'utf-8').trim() || null;} catch { /* not self-disabled */ }- let pausedReason: string | null = null;- try {- pausedReason = readFileSync(autopilotPausedMarkerPath(), 'utf-8').trim() || 'pause marker present (no reason recorded)';- } catch { /* not paused */ }+ const pausedReason = autopilotPauseReason();let heartbeatAgeSeconds: number | null = null;try {@@ -2689,8 +2696,8 @@ function showStatus(json: boolean, intervalSeconds: number) {break;case 'paused':console.log(`Autopilot: PAUSED — ${report.paused_reason}`);- console.log(' A pause marker is parked at ' + autopilotPausedMarkerPath() + '.');- console.log(' Normal while `gbrain migrate` runs. A marker orphaned by a dead migration');+ if (report.paused_reason?.startsWith('operator pause')) { console.log(' Operator pause on this host. Resume with: gbrain autopilot resume'); break; }+ console.log(' A pause marker is parked at ' + autopilotPausedMarkerPath() + '. Normal while `gbrain migrate` runs. A marker orphaned by a dead migration');console.log(' clears itself on the daemon\'s next poll; only remove it by hand if the');console.log(' pid it names is dead and no daemon is running to clean it up.');break;diff --git a/src/commands/config.ts b/src/commands/config.tsindex 7e386eeb7c..199a95a464 100644--- a/src/commands/config.ts+++ b/src/commands/config.ts@@ -10,6 +10,7 @@ import {} from '../core/search/embedding-column.ts';import { redactPgUrl } from '../core/url-redact.ts';+import { WRITER_ADMIN_LOCK_KEY } from '../core/persistence/admin-contract.ts';// v0.36.x #892: sensitive config-key allowlist. The `show` path used a// loose `.includes('key')` check that also redacts (works); the `set` path@@ -221,6 +222,17 @@ export async function tryRunConfigEngineFree(args: string[]): Promise<boolean> {export async function runConfig(engine: BrainEngine, args: string[]) {const action = args[0];+ // The writer admin lock is reserved for `gbrain sources writer lock|unlock`; --force is no escape.+ if (action === 'set' || action === 'unset') {+ const patternAt = action === 'unset' ? args.indexOf('--pattern') : -1;+ const target = patternAt >= 0 ? args[patternAt + 1] : args.filter(a => a !== '--raw')[1];+ if (target && (patternAt >= 0 ? WRITER_ADMIN_LOCK_KEY.startsWith(target) : target === WRITER_ADMIN_LOCK_KEY)) {+ console.error(`[config] ${WRITER_ADMIN_LOCK_KEY} is reserved: only \`gbrain sources writer lock\` and \`gbrain sources writer unlock\` on the brain host change it.`);+ console.error(`[config] ${patternAt >= 0 ? `The pattern "${target}" covers that key. Nothing was deleted.` : 'Nothing was written.'}`);+ process.exit(1);+ }+ }+if (action === 'show') {const config = loadConfig();if (!config) {@@ -843,6 +855,13 @@ export async function runConfig(engine: BrainEngine, args: string[]) {catch (error) { console.error(`[config] ${(error as Error).message}`); process.exit(1); }}+ // #5254: an unknown value would silently keep refusing unbound writes.+ const { UNBOUND_WRITE_KEY, parseUnboundWriteValue } = await import('../core/persistence/unbound-source.ts');+ if (key === UNBOUND_WRITE_KEY) {+ try { parseUnboundWriteValue(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 b6c5461dbd..2a33cc99be 100644--- a/src/commands/doctor.ts+++ b/src/commands/doctor.ts@@ -2689,6 +2689,9 @@ export async function buildChecks(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));+ // Wave checks registered in doctor/wave-checks.ts rather than inline here.+ const { runWaveChecks } = await import('./doctor/wave-checks.ts');+ for (const finding of await runWaveChecks(engine, { only: 'wave', sourceIds: orphanRatioSourceId ? [orphanRatioSourceId] : undefined })) checks.push(finding.check);}// 10. Integrity sample scan (v0.13 knowledge runtime).@@ -4332,278 +4335,6 @@ async function runLocksCheck(engine: BrainEngine | null, jsonOutput: boolean): Pprocess.exit(1);}-// ============================================================-// v0.36+ brain-health-100 wave: --remediation-plan + --remediate-//-// Plan: ~/.claude/plans/system-instruction-you-are-working-fluttering-ocean.md-// Decisions: D1 (per-job re-eval), D3 (sequential submit),-// D5 (depends_on cascade on failure), D7 (scoped recheck),-// D9 (content-hash idempotency), D13 (three-state classification),-// D14 (stable remediation_id), +A (cost-budget gate).-// ============================================================+// --remediation-plan + --remediate live in doctor/remediate.ts (re-exported for import-site stability).+export { runRemediationPlan, renderRemediationPlanLines, runRemediate } from './doctor/remediate.ts';-/**- * CLI wrapper around computeRemediationPlan (src/core/remediation/plan.ts).- *- * v0.41.18.0 (A1, codex finding #2): library extracted so onboard +- * MCP run_onboard can compose against a stable shape. This wrapper- * stays as the CLI surface only — argv parsing + human render. JSON- * mode emits the library's stable envelope verbatim.- *- * Read-only — never enqueues, never mutates.- */-export async function runRemediationPlan(- engine: BrainEngine,- args: string[],-): Promise<void> {- const { computeRemediationPlan } = await import('../core/remediation/index.ts');-- const targetScore = parseIntFlag(args, '--target-score') ?? 90;- const jsonOutput = args.includes('--json');-- const plan = await computeRemediationPlan(engine, { targetScore });-- if (jsonOutput) {- console.log(JSON.stringify(plan, null, 2));- return;- }-- for (const line of renderRemediationPlanLines(plan, targetScore)) {- console.log(line);- }-}--/**- * Human-render the remediation plan into a sequence of console lines.- * Exported for unit-test access — `runRemediationPlan` consumes it- * verbatim and only adds the JSON-mode short-circuit.- *- * Gating the "at target" line on `brain_score_current >= targetScore`- * is load-bearing: when the plan is empty AND the target is unreachable,- * the prior shape printed both "Target unreachable: …" and "Brain is at- * target" back-to-back, which contradicted itself and hid the real next- * step (manual prereq config to lift `max_reachable_score`).- */-export function renderRemediationPlanLines(- plan: RemediationPlanShape,- targetScore: number,-): string[] {- const lines: string[] = [];- lines.push(`Brain score: ${plan.brain_score_current}/100 → target ${targetScore}`);- if (plan.target_unreachable) {- lines.push(`Target unreachable: max with autonomous remediation is ${plan.max_reachable_score}/100.`);- }- if (plan.plan.length === 0) {- if (plan.brain_score_current >= targetScore) {- lines.push('No remediations needed. Brain is at target.');- }- // When brain_score < targetScore and plan is empty, the unreachable- // line (if applicable) is the user-facing explanation; the blocked-- // checks block below surfaces the manual gap. Don't follow with a- // misleading "at target" claim.- } else {- lines.push(`Plan: ${plan.plan.length} step(s), est ${plan.est_total_seconds}s, est $${plan.est_total_usd_cost.toFixed(2)}`);- for (const step of plan.plan) {- const protectedMark = step.protected ? ' [PROTECTED]' : '';- const costMark = step.est_usd_cost ? ` ($${step.est_usd_cost.toFixed(2)})` : '';- lines.push(` ${step.step}. [${step.severity}] ${step.job}${protectedMark} — ${step.rationale}${costMark}`);- }- }- if (plan.blocked.length > 0) {- lines.push(`\nBlocked checks (prereq missing):`);- for (const b of plan.blocked) {- lines.push(` - ${b.check}: ${b.reason}`);- }- }- return lines;-}--interface RemediationPlanShape {- brain_score_current: number;- target_unreachable: boolean;- max_reachable_score: number;- plan: Array<{- step: number;- severity: string;- job: string;- protected?: boolean;- est_usd_cost?: number;- rationale: string;- }>;- est_total_seconds: number;- est_total_usd_cost: number;- blocked: Array<{ check: string; reason: string }>;-}--/**- * CLI wrapper around runRemediation (src/core/remediation/run.ts).- *- * v0.41.18.0 (A1, codex finding #2): orchestrator extracted into the- * remediation library. This wrapper stays as the CLI surface only —- * argv parsing + interactive TTY confirmation + human/JSON render via- * RemediationHooks.- *- * Default behavior: submit-and-wait per step. --dry-run skips submission.- * --max-usd N refuses if est_total_usd_cost > N. --max-jobs N caps the- * inner loop. --resume [plan_hash] loads checkpoint and continues.- *- * PGLite path: synchronous in-process execution (no durable queue).- */-export async function runRemediate(- engine: BrainEngine,- args: string[],-): Promise<void> {- const targetScore = parseIntFlag(args, '--target-score') ?? 90;- const maxJobs = parseIntFlag(args, '--max-jobs') ?? Infinity;- // A4 amended: --max-cost is an alias for --max-usd. Both spellings are- // documented as the cron-safety guard. Either threads through to the- // pre-flight estimate refusal AND, via withBudgetTracker, the mid-run- // BudgetExhausted hard-throw.- const maxUsdRaw = parseFloatFlag(args, '--max-usd') ?? parseFloatFlag(args, '--max-cost');- const maxUsd = maxUsdRaw === null ? undefined : maxUsdRaw;- const dryRun = args.includes('--dry-run');- const skipConfirm = args.includes('--yes');- const jsonOutput = args.includes('--json');- // A4 amended: --resume <plan_hash?> loads the checkpoint for the active- // (engine,target) and continues from the next step. With no value, the- // most recent checkpoint for the active engine is loaded.- const resumeFlagIdx = args.indexOf('--resume');- const resumeMode = resumeFlagIdx !== -1;- const resumeArg = resumeMode ? args[resumeFlagIdx + 1] : undefined;- const resumePlanHash = resumeArg && !resumeArg.startsWith('--') ? resumeArg : undefined;-- const { runRemediation, computeRemediationPlan } =- await import('../core/remediation/index.ts');-- // TTY confirmation gate (stays in CLI; library doesn't render).- // Compute the plan once for the confirmation prompt, then hand off- // to the library for the actual run. The library re-computes its- // own plan internally — we accept the second computation cost for- // a cleaner CLI/library separation.- if (!skipConfirm && !dryRun && process.stdout.isTTY && !resumeMode) {- const plan = await computeRemediationPlan(engine, { targetScore });- if (plan.target_unreachable) {- console.error(- `[remediate] target ${targetScore} unreachable; max autonomous = ${plan.max_reachable_score}/100. ` +- `Configure missing prereqs (see --remediation-plan blocked output) or lower --target-score.`,- );- process.exit(2);- }- if (plan.plan.length === 0) {- console.log(`Brain at score ${plan.brain_score_current}/100, target ${targetScore}. Nothing to do.`);- return;- }- if (maxUsd !== undefined && plan.est_total_usd_cost > maxUsd) {- console.error(- `[remediate] est cost $${plan.est_total_usd_cost.toFixed(2)} exceeds --max-usd $${maxUsd.toFixed(2)}. Aborting.`,- );- process.exit(2);- }- console.log(`About to submit ${plan.plan.length} job(s), est ${plan.est_total_seconds}s, est $${plan.est_total_usd_cost.toFixed(2)}`);- console.log('Pass --yes to proceed (cron-friendly).');- process.exit(1);- }-- if (engine.kind === 'pglite') {- console.error('[remediate] PGLite engine: running inline (no durable queue).');- }-- const result = await runRemediation(- engine,- {- targetScore,- maxJobs,- maxUsd,- dryRun,- resume: resumeMode,- resumePlanHash,- },- {- onTargetUnreachable: (target, ceiling) => {- console.error(- `[remediate] target ${target} unreachable; max autonomous = ${ceiling}/100. ` +- `Configure missing prereqs (see --remediation-plan blocked output) or lower --target-score.`,- );- },- onNothingToDo: (score, target) => {- console.log(`Brain at score ${score}/100, target ${target}. Nothing to do.`);- },- onBudgetRefused: (estCost, cap) => {- console.error(- `[remediate] est cost $${estCost.toFixed(2)} exceeds --max-usd $${cap.toFixed(2)}. Aborting.`,- );- },- onResumeMissed: (planHash, requested) => {- console.error(- `[remediate --resume] no matching checkpoint found ` +- `(plan_hash=${planHash}${requested ? `; requested=${requested}` : ''}). ` +- `Run without --resume to start fresh.`,- );- },- onResumeLoaded: (planHash, completed, remaining) => {- console.error(- `[remediate --resume] resuming plan_hash=${planHash}: ${completed} step(s) completed, ${remaining} remaining.`,- );- },- onBudgetExhausted: (planHash, snapshot) => {- console.error(- `\n[remediate] BudgetExhausted (${snapshot.reason}): spent $${snapshot.spent.toFixed(4)} > cap $${snapshot.cap.toFixed(2)}.\n` +- `Checkpoint saved. Resume with:\n` +- ` gbrain doctor --remediate --resume ${planHash}\n`,- );- },- },- );-- // CLI surfaces — target unreachable / resume missed already emitted via hooks.- // Library returns synthetic result with target_unreachable populated; exit 2.- if (result.target_unreachable) process.exit(2);-- if (dryRun && result.submitted.length > 0) {- console.log(`[remediate --dry-run] Would submit ${result.submitted.length} jobs:`);- for (const s of result.submitted) console.log(` - ${s.id}`);- return;- }-- if (jsonOutput) {- console.log(JSON.stringify(result, null, 2));- } else if (result.submitted.length > 0) {- console.log(`\nBrain score: ${result.brain_score_initial} → ${result.brain_score_final} (target ${targetScore})`);- // #3626: split the count honestly — a step that deduped onto an in-flight- // job did not submit new work; a rotated re-run did.- const coalesced = result.submitted.filter((s) => s.coalesced).length;- const rotated = result.submitted.filter((s) => s.deduped_job_id !== undefined).length;- const notes = [- ...(rotated > 0 ? [`${rotated} re-ran under a rotated key (prior terminal row held it)`] : []),- ...(coalesced > 0 ? [`${coalesced} coalesced onto in-flight job(s)`] : []),- ];- console.log(- `Submitted: ${result.submitted.length - coalesced} job(s)${notes.length > 0 ? ` (${notes.join('; ')})` : ''}, ${result.aborted_count} aborted/failed`,- );- }-- const anyFailed = result.submitted.some(- (s) => s.status !== 'completed' && s.status !== 'submitted' && s.status !== 'dry_run',- );- if (result.budget_exhausted || anyFailed) process.exit(1);-}--// v0.41.18.0 (A1, codex finding #2): loadRecommendationContext moved to-// src/core/remediation/context.ts so onboard + MCP run_onboard compose-// the same context. The CLI surfaces (runRemediationPlan / runRemediate-// above) now call computeRemediationPlan + runRemediation from the-// library, which builds the context internally.--function parseIntFlag(args: string[], flag: string): number | null {- const i = args.indexOf(flag);- if (i === -1 || i === args.length - 1) return null;- const v = parseInt(args[i + 1] ?? '', 10);- return isNaN(v) ? null : v;-}--function parseFloatFlag(args: string[], flag: string): number | null {- const i = args.indexOf(flag);- if (i === -1 || i === args.length - 1) return null;- const v = parseFloat(args[i + 1] ?? '');- return isNaN(v) ? null : v;-}diff --git a/src/commands/doctor/checks/calibration.ts b/src/commands/doctor/checks/calibration.tsindex 1a6ecc601a..57506a3662 100644--- a/src/commands/doctor/checks/calibration.ts+++ b/src/commands/doctor/checks/calibration.ts@@ -40,7 +40,7 @@ import type { Check } from '../../doctor.ts';* to be re-embedded for the wrapper to apply. Paste-ready fix:* `gbrain reindex --markdown`.* 2. Pages with contextual_retrieval_mode IS NULL — never evaluated- * against the CR ladder. Same fix as (1).+ * against the CR ladder. Fix: `gbrain repair contextual-mode` (#5621).* 3. Synopsis-failure events in the audit JSONL over the last 7 days* — surfaces refusals + page-level fallbacks. >5% refusal rate* warns; otherwise reported as informational.@@ -98,7 +98,7 @@ export async function checkContextualRetrievalCoverage(}const needsReindex = chunkerDrift > 0 || modeNull > 0;- const details = { unsealed_pages: unsealed, unsealed_code_pages: unsealedCode, count: 'exact', repair: 'safe-chunks' };+ const details = { unsealed_pages: unsealed, unsealed_code_pages: unsealedCode, mode_null_pages: modeNull, count: 'exact', repair: 'safe-chunks', mode_repair: 'contextual-mode' };if (!needsReindex && unsealed === 0 && failureSummaryLine === '') {return {name: 'contextual_retrieval_coverage',@@ -119,7 +119,8 @@ export async function checkContextualRetrievalCoverage(parts.push(`${modeNull} page(s) never evaluated against CR ladder`);}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.` : '');+ + (modeNull > 0 ? ' Preview the mode stamp (#5621): gbrain repair contextual-mode — apply: gbrain repair contextual-mode --apply.' : '')+ + (chunkerDrift > 0 ? ` Run \`gbrain reindex --markdown\` to align.` : '');return {name: 'contextual_retrieval_coverage',status: needsReindex || unsealed > 0 ? 'warn' : 'ok',diff --git a/src/commands/doctor/checks/connector-checkpoints.ts b/src/commands/doctor/checks/connector-checkpoints.tsnew file mode 100644index 0000000000..5a28040cf6--- /dev/null+++ b/src/commands/doctor/checks/connector-checkpoints.ts@@ -0,0 +1,31 @@+import type { BrainEngine } from '../../../core/engine.ts';+import type { Check } from '../../doctor.ts';+import { orphanConnectorCheckpoints } from '../../../core/persistence/connector-checkpoint-migration.ts';+import { ORPHAN_CHECKPOINT_MIN_AGE_DAYS } from '../../../core/repair/connector-checkpoints.ts';++const LIMIT = 1000;++/**+ * #5686: connector checkpoint rows and retry pointers that no registered+ * connector source can load, older than 7 days. The 7-day checkpoint purge+ * never removes them, so they accumulate after a content-config change or an+ * old binary running during an upgrade. Counts only; names the repair.+ */+export async function checkConnectorCheckpoints(engine: BrainEngine): Promise<Check> {+ try {+ const rows = await orphanConnectorCheckpoints(engine, { minAgeDays: ORPHAN_CHECKPOINT_MIN_AGE_DAYS, limit: LIMIT + 1 });+ const truncated = rows.length > LIMIT;+ const counted = rows.slice(0, LIMIT);+ const checkpoints = counted.filter(row => row.op === 'managed-connector').length;+ const retries = counted.length - checkpoints;+ const details = { count: counted.length, checkpoints, retries, truncated, repair: 'connector-checkpoints', docs: 'docs/guides/repair.md#connector-checkpoints' };+ if (!counted.length) return { name: 'connector_checkpoints', status: 'ok', message: 'No orphan connector checkpoint rows older than 7 days.', details };+ return { name: 'connector_checkpoints', status: 'warn', details,+ message: `${counted.length}${truncated ? '+' : ''} connector checkpoint row(s) no source can load (${checkpoints} checkpoint(s), ${retries} retry pointer(s)), older than 7 days. `+ + 'Preview on the brain host: gbrain repair connector-checkpoints — then apply after the user agrees: gbrain repair connector-checkpoints --apply' };+ } catch (error) {+ return { name: 'connector_checkpoints', status: 'warn',+ message: `Connector checkpoint rows could not be inspected: ${error instanceof Error ? error.message : String(error)}. Health is unknown.`,+ details: { count: 0, truncated: true } };+ }+}diff --git a/src/commands/doctor/checks/derived-visibility.ts b/src/commands/doctor/checks/derived-visibility.tsindex 0956a979db..84551cbc75 100644--- a/src/commands/doctor/checks/derived-visibility.ts+++ b/src/commands/doctor/checks/derived-visibility.ts@@ -37,6 +37,6 @@ export async function derivedVisibilityCheck(engine: BrainEngine, sourceId?: str+ `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 } };+ details: { count: 'lower_bound', truncated: true, health: 'unknown' } };}}diff --git a/src/commands/doctor/checks/dream-breaker.ts b/src/commands/doctor/checks/dream-breaker.tsindex d9bbf59470..90e5905af4 100644--- a/src/commands/doctor/checks/dream-breaker.ts+++ b/src/commands/doctor/checks/dream-breaker.ts@@ -5,7 +5,7 @@* 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 { countDeadDreamSubmissions, dreamBreakerResetCommand, loadDreamBreakerThreshold, DREAM_BREAKER_CONFIG_KEY, DREAM_PHASE_KEY_PREFIX } from '../../../core/cycle/dream-breaker.ts';import type { Check } from '../../doctor.ts';export async function dreamPaidLoopCheck(engine: BrainEngine): Promise<Check> {@@ -14,7 +14,8 @@ export async function dreamPaidLoopCheck(engine: BrainEngine): Promise<Check> {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 })) };+ keys: looping.map(row => ({ key_prefix: row.base_key.startsWith('dream:patterns:') ? 'dream:patterns:'+ : row.base_key.startsWith(DREAM_PHASE_KEY_PREFIX) ? DREAM_PHASE_KEY_PREFIX : '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 };}@@ -22,6 +23,8 @@ export async function dreamPaidLoopCheck(engine: BrainEngine): Promise<Check> {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)}.`;+ const phaseNote = looping.some(row => row.base_key.startsWith(DREAM_PHASE_KEY_PREFIX))+ ? ` ${DREAM_PHASE_KEY_PREFIX}* keys count cycle phases that failed after paid model calls; the cycle keeps running them, so fix the cause first.` : '';return { name: 'dream_paid_loop', status: 'warn',- message: `${looping.length} dream key(s) died ${limit}+ times in 24h: ${shown}. ${action}`, details };+ message: `${looping.length} dream key(s) died ${limit}+ times in 24h: ${shown}. ${action}${phaseNote}`, details };}diff --git a/src/commands/doctor/checks/parked-effects.ts b/src/commands/doctor/checks/parked-effects.tsindex 181f4541f6..986b9ba478 100644--- a/src/commands/doctor/checks/parked-effects.ts+++ b/src/commands/doctor/checks/parked-effects.ts@@ -9,12 +9,14 @@ const SAMPLE = 20;* 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> {+export async function checkParkedEffects(engine: BrainEngine, sourceIds?: string[]): Promise<Check> {try {- const [{ count }] = await engine.executeRaw<{ count: number }>(`SELECT COUNT(*)::int AS count FROM persistence_effects WHERE data ? 'parked'`);+ const scoped = sourceIds ? ' AND e.source_id=ANY($1::text[])' : '';+ const params = sourceIds ? [sourceIds] : [];+ const [{ count }] = await engine.executeRaw<{ count: number }>(`SELECT COUNT(*)::int AS count FROM persistence_effects e WHERE e.data ? 'parked'${scoped}`, params);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}`);+ JOIN persistence_requests r ON r.id=e.request_id WHERE e.data ? 'parked'${scoped} ORDER BY e.id LIMIT ${SAMPLE}`, params);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 };@@ -27,6 +29,6 @@ export async function checkParkedEffects(engine: BrainEngine): Promise<Check> {} 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 } };+ details: { exact: false, inspected: 0, truncated: true, health: 'unknown' } };}}diff --git a/src/commands/doctor/checks/persistence-capacity.ts b/src/commands/doctor/checks/persistence-capacity.tsindex de6249cf5d..01358d1d4b 100644--- a/src/commands/doctor/checks/persistence-capacity.ts+++ b/src/commands/doctor/checks/persistence-capacity.ts@@ -34,6 +34,6 @@ export async function checkPersistenceCapacity(engine: BrainEngine): Promise<Che} 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 } };+ details: { exact: false, inspected: 0, truncated: true, health: 'unknown' } };}}diff --git a/src/commands/doctor/checks/safe-index.ts b/src/commands/doctor/checks/safe-index.tsnew file mode 100644index 0000000000..e7ab5bbb27--- /dev/null+++ b/src/commands/doctor/checks/safe-index.ts@@ -0,0 +1,31 @@+/**+ * safe_index_pending doctor check (#5050, #5247): pages chunked before the+ * safe-chunk fence, whose chunks remote/MCP search withholds until they are+ * re-sealed. Counts the pages `gbrain repair safe-chunks` can re-seal and,+ * separately, the ones it keeps (code without a source path, image pages).+ * One indexed aggregate; counts are exact.+ */+import type { BrainEngine } from '../../../core/engine.ts';+import type { Check } from '../../doctor.ts';+import { SAFE_FENCE_CHUNKER_VERSION } from '../../../core/search/safe-chunks.ts';++export async function safeIndexPendingCheck(engine: BrainEngine, sourceIds?: string[]): Promise<Check> {+ const name = 'safe_index_pending';+ try {+ const [row] = await engine.executeRaw<{ rebuildable: number; kept: number }>(`SELECT+ COUNT(*) FILTER (WHERE p.page_kind='markdown' OR (p.page_kind='code' AND COALESCE(p.frontmatter->>'file',p.source_path) IS NOT NULL))::int AS rebuildable,+ COUNT(*) FILTER (WHERE NOT (p.page_kind='markdown' OR (p.page_kind='code' AND COALESCE(p.frontmatter->>'file',p.source_path) IS NOT NULL)))::int AS kept+ FROM pages p JOIN sources s ON s.id=p.source_id AND s.archived IS NOT TRUE+ WHERE p.deleted_at IS NULL AND p.chunker_version < ${SAFE_FENCE_CHUNKER_VERSION} ${sourceIds ? 'AND p.source_id=ANY($1::text[])' : ''}`,+ sourceIds ? [sourceIds] : []);+ const rebuildable = Number(row?.rebuildable ?? 0), kept = Number(row?.kept ?? 0);+ const details = { pages_pending: rebuildable, kept_pages: kept, count: 'exact', truncated: false, repair: 'safe-chunks' };+ const keptNote = kept ? ` ${kept} other page(s) cannot be re-sealed here (code without a recorded source path, or image pages) and are left for their importer.` : '';+ if (rebuildable === 0) return { name, status: 'ok', details, message: `Every re-sealable page is at the safe-chunk index version.${keptNote}` };+ return { name, status: 'warn', details, message: `${rebuildable} page(s) are below the safe-chunk index version, so remote/MCP search withholds their chunks. `+ + `Preview: gbrain repair safe-chunks — apply: gbrain repair safe-chunks --apply.${keptNote}` };+ } catch (error) {+ return { name, status: 'warn', message: `Safe-chunk index state could not be read: ${error instanceof Error ? error.message : String(error)}. Health is unknown.`,+ details: { count: 'unknown', truncated: true, health: 'unknown' } };+ }+}diff --git a/src/commands/doctor/checks/self-capture.ts b/src/commands/doctor/checks/self-capture.tsnew file mode 100644index 0000000000..d6d7865bd8--- /dev/null+++ b/src/commands/doctor/checks/self-capture.ts@@ -0,0 +1,93 @@+/**+ * self_capture doctor check (#5413): corpus files captured from gbrain's own+ * claude-cli sessions before the session-end hook refused them. Dream+ * discovery and the sweep already skip every self-capture they can identify;+ * this check counts what is still sitting in the session corpus so the+ * operator can quarantine it by hand. It never moves or deletes anything.+ *+ * Classified: the file's session id matches a harness transcript under a+ * gbrain claude-cli scratch project. Unclassifiable: no harness transcript+ * exists for the session any more (Claude Code pruned it), so whether it is+ * a self-capture cannot be decided from this host. Best-effort: both counts+ * read the local filesystem of the brain host.+ */+import { readdirSync } from 'node:fs';+import { basename, dirname, join, relative } from 'node:path';+import type { BrainEngine } from '../../../core/engine.ts';+import type { Check } from '../../doctor.ts';+import { claudeCliSelfSessionIds } from '../../../core/ai/providers/claude-cli-scratch.ts';+import { claudeProjectsDir } from '../../../core/bootstrap/host-specs.ts';+import { corpusFileSessionId } from '../../../core/context/corpus-segments.ts';+import { pruneDir } from '../../../core/sync.ts';++const SAMPLE = 20;+const CORPUS_KEY = 'dream.synthesize.session_corpus_dir';++function harnessSessionIds(projectsRoot: string): Set<string> {+ const ids = new Set<string>();+ let projects: string[];+ try { projects = readdirSync(projectsRoot); } catch { return ids; }+ for (const project of projects) {+ 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;+}++/** Every `.txt` under the corpus (dream discovery's pruning), and whether any directory could not be read. */+function corpusTextFiles(root: string): { files: string[]; unreadable: number } {+ const files: string[] = [];+ let unreadable = 0;+ const walk = (dir: string, top: boolean) => {+ let entries: import('node:fs').Dirent[];+ try { entries = readdirSync(dir, { withFileTypes: true }); }+ catch (error) { if (top) throw error; unreadable++; return; }+ for (const entry of entries) {+ const full = join(dir, entry.name);+ if (entry.isDirectory()) { if (pruneDir(entry.name, dir)) walk(full, false); }+ else if (entry.isFile() && entry.name.endsWith('.txt')) files.push(full);+ }+ };+ walk(root, true);+ return { files: files.sort(), unreadable };+}++const quote = (path: string) => `'${path.replaceAll("'", "'\\''")}'`;++export async function selfCaptureCheck(engine: BrainEngine, opts: { projectsRoot?: string; corpusDir?: string } = {}): Promise<Check> {+ const name = 'self_capture';+ try {+ const corpusDir = opts.corpusDir ?? await engine.getConfig(CORPUS_KEY);+ if (!corpusDir) return { name, status: 'ok', message: 'No session corpus is configured; nothing to classify.', details: { classified: 0, unclassifiable: 0, count: 'exact', truncated: false } };+ // An unreadable corpus root throws (unknown health); unreadable subdirectories make the counts a lower bound.+ const { files, unreadable } = corpusTextFiles(corpusDir);+ const projectsRoot = opts.projectsRoot ?? claudeProjectsDir();+ const selfIds = claudeCliSelfSessionIds(projectsRoot);+ const known = harnessSessionIds(projectsRoot);+ const classified: string[] = [], unclassifiable: string[] = [];+ for (const file of files) {+ const session = corpusFileSessionId(basename(file));+ if (selfIds.has(session)) classified.push(file);+ else if (!known.has(session)) unclassifiable.push(file);+ }+ const quarantineDir = join(dirname(corpusDir), `${basename(corpusDir)}.quarantine`);+ const destinations = classified.slice(0, SAMPLE).map(file => ({ file, dir: join(quarantineDir, dirname(relative(corpusDir, file))) }));+ const commands = [`mkdir -p ${[...new Set([quarantineDir, ...destinations.map(d => d.dir)])].map(quote).join(' ')}`,+ ...destinations.map(({ file, dir }) => `for f in ${quote(file)}*; do mv -n -- "$f" ${quote(dir)}/; done`)];+ const details = { classified: classified.length, unclassifiable: unclassifiable.length, corpus_files: files.length, unreadable_dirs: unreadable,+ count: unreadable ? 'lower_bound' : 'exact', truncated: classified.length > SAMPLE, ...(unreadable ? { health: 'unknown' } : {}),+ corpus_dir: corpusDir, quarantine_dir: quarantineDir, classified_sample: classified.slice(0, SAMPLE).map(file => relative(corpusDir, file)),+ quarantine_commands: commands, docs: 'docs/guides/repair.md#quarantine-self-captured-corpus-files' };+ const unknownNote = unclassifiable.length ? ` ${unclassifiable.length} corpus file(s) have no harness transcript left, so whether they are self-captures cannot be decided here; review them by hand.` : '';+ if (unreadable) return { name, status: 'warn', details, message: `${unreadable} session corpus director${unreadable === 1 ? 'y' : 'ies'} could not be read, so self-capture health is unknown `+ + `(at least ${classified.length} identified self-capture(s)). Fix the directory permissions on the brain host and rerun gbrain doctor.${unknownNote}` };+ if (!classified.length) return { name, status: 'ok', details, message: `No identified gbrain self-capture remains in the session corpus.${unknownNote}` };+ return { name, status: 'warn', details, message: `${classified.length} session corpus file(s) were captured from gbrain's own claude-cli sessions (#5413). `+ + `Dream and the sweep skip them, but they stay in the corpus until you move them. Nothing was moved or deleted. Quarantine them on the brain host: `+ + `${commands.slice(0, 3).join(' && ')}${classified.length > 2 ? ' … (full list: gbrain doctor --json, check self_capture; recipe: docs/guides/repair.md#quarantine-self-captured-corpus-files)' : ''}.${unknownNote}` };+ } catch (error) {+ return { name, status: 'warn', message: `Self-capture scan could not run: ${error instanceof Error ? error.message : String(error)}. Health is unknown.`,+ details: { count: 'unknown', truncated: true, health: 'unknown' } };+ }+}diff --git a/src/commands/doctor/checks/stale-embedding-effects.ts b/src/commands/doctor/checks/stale-embedding-effects.tsnew file mode 100644index 0000000000..70c650e81e--- /dev/null+++ b/src/commands/doctor/checks/stale-embedding-effects.ts@@ -0,0 +1,36 @@+/**+ * stale_embedding_effects doctor check (#5629): a queued embedding effect+ * whose write request already committed, still unclaimed an hour later. It+ * blocks shared-skill activation (`writer_not_quiesced`) and no command can+ * clear it yet: `retry-effects` refuses effects that have not failed, and the+ * reconcile-or-re-queue path is deferred. The check names each effect so an+ * operator can inspect it; inspection cannot clear it.+ */+import type { BrainEngine } from '../../../core/engine.ts';+import type { Check } from '../../doctor.ts';++const SAMPLE = 10;++export async function staleEmbeddingEffectsCheck(engine: BrainEngine, sourceIds?: string[]): Promise<Check> {+ const name = 'stale_embedding_effects';+ try {+ const where = `e.kind='embedding' AND e.state='queued' AND r.state='committed' AND e.updated_at < now() - interval '1 hour'+ ${sourceIds ? 'AND r.source_id=ANY($1::text[])' : ''}`;+ const params = sourceIds ? [sourceIds] : [];+ const [{ count }] = await engine.executeRaw<{ count: number }>(`SELECT COUNT(*)::int AS count FROM persistence_effects e+ JOIN persistence_requests r ON r.id=e.request_id WHERE ${where}`, params);+ const rows = await engine.executeRaw<{ effect_id: string; source_id: string; slug: string | null; request_id: string; updated_at: string }>(+ `SELECT e.id::text AS effect_id,r.source_id,r.slug,r.request_id::text AS request_id,e.updated_at::text AS updated_at FROM persistence_effects e+ JOIN persistence_requests r ON r.id=e.request_id WHERE ${where} ORDER BY e.id LIMIT ${SAMPLE}`, params);+ const effects = rows.map(row => ({ ...row, kind: 'embedding', inspect: `gbrain sources writer status ${row.source_id} --json` }));+ const details = { stale_effects: Number(count), count: 'exact', truncated: Number(count) > rows.length, effects,+ resolution: 'unsupported', docs: 'docs/guides/repair.md#stale-queued-embedding-effects' };+ if (!Number(count)) return { name, status: 'ok', details, message: 'No committed write has a queued embedding effect older than an hour.' };+ return { name, status: 'warn', details, message: `${count} committed write(s) still have a queued embedding effect after an hour; it blocks shared-skill activation `+ + `(writer_not_quiesced). No command clears it yet (retry-effects refuses effects that have not failed), and inspection cannot clear it. Inspect: `+ + `${effects.map(e => `effect ${e.effect_id} (${e.source_id}:${e.slug ?? '(no page)'}, request ${e.request_id}): ${e.inspect}`).join(' | ')}` };+ } catch (error) {+ return { name, status: 'warn', message: `Queued embedding effects could not be read: ${error instanceof Error ? error.message : String(error)}. Health is unknown.`,+ details: { count: 'unknown', truncated: true, health: 'unknown' } };+ }+}diff --git a/src/commands/doctor/checks/timeline-history.ts b/src/commands/doctor/checks/timeline-history.tsindex 6bf369c534..bbad108925 100644--- a/src/commands/doctor/checks/timeline-history.ts+++ b/src/commands/doctor/checks/timeline-history.ts@@ -39,6 +39,6 @@ export async function timelineHistoryCheck(engine: BrainEngine, sourceId?: strin: `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 } };+ details: { count: 'lower_bound', truncated: true, health: 'unknown' } };}}diff --git a/src/commands/doctor/checks/unbound-source.ts b/src/commands/doctor/checks/unbound-source.tsnew file mode 100644index 0000000000..7f5305f6fd--- /dev/null+++ b/src/commands/doctor/checks/unbound-source.ts@@ -0,0 +1,41 @@+import type { BrainEngine } from '../../../core/engine.ts';+import type { Check } from '../../doctor.ts';+import { unboundBindCommand } from '../../../core/persistence/unbound-source.ts';++/**+ * #5254: pages written database-only while their filesystem source had no+ * canonical owner (`persistence.unbound_write=database_only`). While the source+ * stays unbound that is the chosen mode, so the count reports ok with the bind+ * command; once the source is bound those pages sit outside its canonical+ * files and are never materialized automatically, so it warns.+ */+export async function checkUnboundSource(engine: BrainEngine): Promise<Check> {+ try {+ const rows = await engine.executeRaw<{ source_id: string; pages: number; bound: boolean; local_path: string | null }>(+ `SELECT p.source_id,COUNT(*)::int AS pages,+ EXISTS(SELECT 1 FROM persistence_source_bindings b WHERE b.source_id=p.source_id) AS bound,+ COALESCE((SELECT s.local_path FROM sources s WHERE s.id=p.source_id),+ CASE WHEN p.source_id='default' THEN (SELECT c.value FROM config c WHERE c.key='sync.repo_path') END) AS local_path+ FROM pages p WHERE p.database_only_reason='unbound_source' AND p.deleted_at IS NULL+ GROUP BY p.source_id ORDER BY p.source_id`);+ const sources = rows.map(row => ({ source_id: row.source_id, pages: row.pages, bound: row.bound }));+ const total = rows.reduce((sum, row) => sum + row.pages, 0);+ if (!total) return { name: 'unbound_source', status: 'ok', message: 'No page was written database-only to an unbound source.', details: { total, sources } };+ const bound = rows.filter(row => row.bound);+ const unbound = rows.filter(row => !row.bound);+ const counts = (list: typeof rows) => list.map(row => `${row.source_id}: ${row.pages}`).join(', ');+ const unboundText = unbound.length ? `${counts(unbound)} written database-only because the source has no canonical owner `+ + `(persistence.unbound_write=database_only). To give a source a canonical owner, ${unbound.map(row => unboundBindCommand(row.source_id, row.local_path)).join('; ')}. `+ + 'Pages already written stay database-only.' : '';+ if (!bound.length) return { name: 'unbound_source', status: 'ok', message: unboundText, details: { total, sources } };+ return { name: 'unbound_source', status: 'warn', details: { total, sources },+ message: `${counts(bound)} page(s) written database-only while the source was unbound now sit outside canonical files: `+ + 'binding does not materialize them, so they are not in the checkout, its Git history or file backups. '+ + 'There is no bulk materialization command; when a canonical file already exists at a page\'s slug path, preview both sides with '+ + 'gbrain sources reconcile <source> <slug> --brain <brain> --preview and apply the agreed resolution. Otherwise save its content under a new slug and delete the database-only page.'+ + (unboundText ? ` ${unboundText}` : '') };+ } catch (error) {+ return { name: 'unbound_source', status: 'warn', details: { total: null, sources: [] },+ message: `Unbound-source pages could not be counted: ${error instanceof Error ? error.message : String(error)}. Health is unknown.` };+ }+}diff --git a/src/commands/doctor/checks/writer-version.ts b/src/commands/doctor/checks/writer-version.tsnew file mode 100644index 0000000000..4149560165--- /dev/null+++ b/src/commands/doctor/checks/writer-version.ts@@ -0,0 +1,38 @@+import type { BrainEngine } from '../../../core/engine.ts';+import type { Check } from '../../doctor.ts';+import { recentWriterVersions, WRITER_VERSION_FLOOR, writerVersionBelowFloor } from '../../../core/persistence/writer-versions.ts';++const WINDOW_DAYS = 7;+const SAMPLE = 20;++/**+ * Writer-version advisory: committed requests from the last seven days whose admitting or publishing+ * binary predates v0.60.5.0 or this release (no stamp). Observation, not prevention; older writers are+ * not blocked. Pending requests never count, and only requests admitted or published after migration 178+ * are expected to carry stamps.+ */+export async function writerVersionCheck(engine: BrainEngine): Promise<Check> {+ try {+ const [brain] = await engine.executeRaw<{ cutoff: unknown }>('SELECT writer_version_cutoff AS cutoff FROM persistence_brain WHERE singleton=1');+ if (!brain?.cutoff) throw new Error('the writer-version migration cutoff is not recorded');+ const observed = await recentWriterVersions(engine, WINDOW_DAYS);+ const flagged = observed.filter(row => writerVersionBelowFloor(row.version));+ const hosts = flagged.slice(0, SAMPLE).map(row => ({ host_id: row.host_id, principal: row.principal, role: row.role,+ [`${row.role}_version`]: row.version_label, last_seen: row.last_seen, requests: row.requests }));+ const count = flagged.reduce((sum, row) => sum + row.requests, 0);+ const details = { count, truncated: flagged.length > SAMPLE, hosts, window_days: WINDOW_DAYS, floor: WRITER_VERSION_FLOOR,+ observed: observed.slice(0, SAMPLE).map(row => ({ host_id: row.host_id, principal: row.principal, role: row.role, version: row.version_label, last_seen: row.last_seen })) };+ if (!flagged.length) return { name: 'writer_version', status: 'ok', details,+ message: `Every writer that admitted or published a request in the last ${WINDOW_DAYS} days is v${WRITER_VERSION_FLOOR} or newer.` };+ const listed = hosts.map(host => `host ${host.host_id ?? 'unknown (not recorded)'} (principal ${host.principal}) ${host.role} ${host[`${host.role}_version`]}, last seen ${host.last_seen}`);+ return { name: 'writer_version', status: 'warn', details,+ message: `${count} committed request(s) in the last ${WINDOW_DAYS} days were admitted or published by a writer older than v${WRITER_VERSION_FLOOR} or by an unstamped binary: `+ + `${listed.join('; ')}${flagged.length > SAMPLE ? ` (first ${SAMPLE} of ${flagged.length} shown)` : ''}. `+ + `A writer older than v${WRITER_VERSION_FLOOR} may still delete database-only timeline rows. Run \`gbrain upgrade\` on that host. `+ + 'This is an observation, not prevention: older writers are not blocked.' };+ } catch (error) {+ return { name: 'writer_version', status: 'warn',+ message: `Writer versions could not be read: ${error instanceof Error ? error.message : String(error)}. Health is unknown.`,+ details: { count: 'unknown', truncated: true, hosts: [] } };+ }+}diff --git a/src/commands/doctor/remediate.ts b/src/commands/doctor/remediate.tsnew file mode 100644index 0000000000..ede47ed361--- /dev/null+++ b/src/commands/doctor/remediate.ts@@ -0,0 +1,327 @@+/**+ * `gbrain doctor --remediation-plan` and `gbrain doctor --remediate`: the CLI+ * shell around the remediation library (src/core/remediation/). doctor.ts+ * re-exports these so import sites are unchanged.+ *+ * The plan lists job steps (driven by the brain score target) and, separately+ * and independent of the target, PROTECTED repair steps for every registered+ * `gbrain repair` kind with pending items. Each step prints the exact command+ * that applies it, plus one combined command. `--remediate --yes` runs repair+ * steps only with `--include-repairs` (the user's agreement). The `--max-usd`+ * cap is cumulative across the original run and every `--resume`; the cap,+ * consent and step manifest live in the local remediation checkpoint.+ *+ * After a run, every wave check is classified (cleared, pending,+ * consent_required, operator_required, unsupported). Exit status: 0 when no+ * automatically repairable finding remains and no step failed, even if+ * operator-required or unsupported findings remain (they are listed); 1+ * otherwise and on budget exhaustion; 2 when the target is unreachable and+ * there is no repair step to run, or a resume is refused.+ */+import type { BrainEngine } from '../../core/engine.ts';+import { setCliExitVerdict } from '../../core/cli-force-exit.ts';+import type { RemediationPlan, RemediationResult } from '../../core/remediation/types.ts';+import type { RepairPlanStep } from '../../core/remediation/repairs.ts';+import { runWaveChecks, waveRepairKind, type WaveFinding } from './wave-checks.ts';++export const REMEDIATE_HELP = `Usage: gbrain doctor --remediation-plan [--target-score <n>] [--no-embed] [--json]+ gbrain doctor --remediate [--yes] [--include-repairs] [--max-usd <n>] [--target-score <n>]+ [--max-jobs <n>] [--no-embed] [--dry-run] [--resume [<plan_hash>]] [--json]++--remediation-plan previews job steps (driven by the brain score target) and,+independent of the target, PROTECTED repair steps for every \`gbrain repair\`+kind with pending items. Each step prints the exact command that applies it,+plus one combined command. Read-only.++--remediate runs job steps; with --include-repairs it also runs the repair+steps (the user's agreement; local brain host only). Without it, repair steps+are listed as skipped.+ --max-usd <n> Cumulative USD cap across the run and every --resume. A paid+ step that would exceed it is not started; free steps still+ run, then the run stops as budget-exhausted with a resume+ command. --resume without --max-usd reuses the recorded cap.+ --target-score <n> Governs job steps only; included repair steps always run to+ completion.+ --no-embed Repair steps re-seal or stamp text only (no paid embeddings).+ --json Findings classified cleared, pending, consent_required,+ operator_required and unsupported.++Exit status: 0 when no automatically repairable finding remains and no step+failed (operator-required and unsupported findings are listed but do not fail+the run); 1 otherwise and on budget exhaustion; 2 when the target is unreachable+and no repair step runs, or a resume is refused.+Recipe: docs/guides/repair.md#recover-after-upgrading-to-this-release`;++function parseIntFlag(args: string[], flag: string): number | null {+ const i = args.indexOf(flag);+ if (i === -1 || i === args.length - 1) return null;+ const v = parseInt(args[i + 1] ?? '', 10);+ return isNaN(v) ? null : v;+}++function parseFloatFlag(args: string[], flag: string): number | null {+ const i = args.indexOf(flag);+ if (i === -1 || i === args.length - 1) return null;+ const v = parseFloat(args[i + 1] ?? '');+ return isNaN(v) ? null : v;+}++const shellQuote = (text: string) => `'${text.replaceAll("'", "'\\''")}'`;++/** The exact command that runs one job step on its own. */+export function jobStepCommand(step: { job: string; params?: Record<string, unknown> }): string {+ return `gbrain jobs submit ${step.job}${step.params && Object.keys(step.params).length ? ` --params ${shellQuote(JSON.stringify(step.params))}` : ''} --follow`;+}++/** `gbrain doctor --remediate --yes --include-repairs --max-usd <n>`, filled from the plan's estimates. */+export function combinedRemediateCommand(plan: Pick<RemediationPlanShape, 'est_total_usd_cost' | 'repair_steps'>, targetScore = 90): string {+ const repairs = plan.repair_steps ?? [];+ const unknown = repairs.some(step => step.paid && step.est_usd_cost === null);+ const total = plan.est_total_usd_cost + repairs.reduce((sum, step) => sum + (step.est_usd_cost ?? 0), 0);+ const cap = unknown ? '<n>' : String(Math.ceil(total * 100) / 100);+ return `gbrain doctor --remediate --yes${repairs.length ? ' --include-repairs' : ''} --max-usd ${cap}${targetScore !== 90 ? ` --target-score ${targetScore}` : ''}`;+}++/**+ * CLI wrapper around computeRemediationPlan. Read-only — never enqueues,+ * never mutates. JSON adds a `command` per job step, the repair steps and+ * the combined command to the library's stable envelope.+ */+export async function runRemediationPlan(engine: BrainEngine, args: string[]): Promise<void> {+ if (args.includes('--help') || args.includes('-h')) { console.log(REMEDIATE_HELP); return; }+ const { computeRemediationPlan } = await import('../../core/remediation/index.ts');+ const targetScore = parseIntFlag(args, '--target-score') ?? 90;+ const plan = await computeRemediationPlan(engine, { targetScore, repairs: { noEmbed: args.includes('--no-embed') } });+ if (args.includes('--json')) {+ console.log(JSON.stringify({ ...plan, plan: plan.plan.map(step => ({ ...step, command: jobStepCommand(step) })),+ combined_command: combinedRemediateCommand(plan, targetScore) }, null, 2));+ return;+ }+ for (const line of renderRemediationPlanLines(plan, targetScore)) console.log(line);+}++interface RemediationPlanShape {+ brain_score_current: number;+ target_unreachable: boolean;+ max_reachable_score: number;+ plan: Array<{+ step: number;+ severity: string;+ job: string;+ params?: Record<string, unknown>;+ protected?: boolean;+ est_usd_cost?: number;+ rationale: string;+ }>;+ est_total_seconds: number;+ est_total_usd_cost: number;+ blocked: Array<{ check: string; reason: string }>;+ repair_steps?: RepairPlanStep[];+}++/**+ * Human-render the remediation plan. "Brain is at target" prints only when+ * the score is at target AND no repair step is pending, so an unreachable+ * target never reads as "nothing to do".+ */+export function renderRemediationPlanLines(plan: RemediationPlanShape, targetScore: number): string[] {+ const lines: string[] = [];+ const repairs = plan.repair_steps ?? [];+ lines.push(`Brain score: ${plan.brain_score_current}/100 → target ${targetScore}`);+ if (plan.target_unreachable) {+ lines.push(`Target unreachable: max with autonomous remediation is ${plan.max_reachable_score}/100.`);+ }+ if (plan.plan.length === 0) {+ if (plan.brain_score_current >= targetScore && repairs.length === 0) {+ lines.push('No remediations needed. Brain is at target.');+ }+ } else {+ lines.push(`Plan: ${plan.plan.length} step(s), est ${plan.est_total_seconds}s, est $${plan.est_total_usd_cost.toFixed(2)}`);+ for (const step of plan.plan) {+ const protectedMark = step.protected ? ' [PROTECTED]' : '';+ const costMark = step.est_usd_cost ? ` ($${step.est_usd_cost.toFixed(2)})` : '';+ lines.push(` ${step.step}. [${step.severity}] ${step.job}${protectedMark} — ${step.rationale}${costMark}`);+ lines.push(` run: ${jobStepCommand(step)}`);+ }+ }+ if (repairs.length > 0) {+ lines.push(`\nRepair steps: ${repairs.length} (requires user agreement; PROTECTED, run on this host only; independent of the score target)`);+ for (const step of repairs) {+ const cost = step.paid ? (step.est_usd_cost === null ? ' (paid embeddings, price unknown)' : ` (~$${step.est_usd_cost.toFixed(4)} embeddings)`) : ' (free)';+ lines.push(` R${step.step}. ${step.kind} — ${step.affected} item(s)${cost} [requires user agreement]`);+ lines.push(` apply: ${step.command}`);+ }+ }+ if (plan.plan.length > 0 || repairs.length > 0) {+ lines.push(`\nApply everything${repairs.length ? ' after the user agrees' : ''}: ${combinedRemediateCommand(plan, targetScore)}`);+ if (repairs.length) lines.push('Ask the user before applying any repair step.');+ }+ if (plan.blocked.length > 0) {+ lines.push(`\nBlocked checks (prereq missing):`);+ for (const b of plan.blocked) lines.push(` - ${b.check}: ${b.reason}`);+ }+ return lines;+}++export type FindingClass = 'cleared' | 'pending' | 'consent_required' | 'operator_required' | 'unsupported';++export interface RemediationFinding {+ check_id: string;+ class: FindingClass;+ message: string;+ repair_kind?: string;+ command?: string;+ instruction?: string;+}++/**+ * Classify every wave check that reported a finding before or after the run.+ * A repairable finding the run did not clear is `pending` (the step stopped,+ * was refused by the budget, or items remain) or `consent_required` (the step+ * was skipped for lack of --include-repairs). A check that could not run is+ * `pending`: its state is unknown, never assumed clean.+ */+export function classifyWaveFindings(before: WaveFinding[], after: WaveFinding[], result: Pick<RemediationResult, 'repairs' | 'repairs_skipped'>): RemediationFinding[] {+ const findings: RemediationFinding[] = [];+ for (const now of after) {+ const was = before.find(b => b.spec.id === now.spec.id);+ const kind = waveRepairKind(now.spec);+ if (now.state === 'ok') {+ if (was && was.state !== 'ok') findings.push({ check_id: now.spec.id, class: 'cleared', message: now.check.message, ...(kind ? { repair_kind: kind } : {}) });+ continue;+ }+ const base = { check_id: now.spec.id, message: now.check.message };+ if (now.state === 'unknown') { findings.push({ ...base, class: 'pending', instruction: 'The check could not run; rerun gbrain doctor on the brain host.' }); continue; }+ if (now.spec.resolution === 'operator') { findings.push({ ...base, class: 'operator_required', instruction: now.spec.instruction }); continue; }+ if (now.spec.resolution === 'unsupported') { findings.push({ ...base, class: 'unsupported', instruction: now.spec.instruction }); continue; }+ const skipped = result.repairs_skipped?.find(step => step.kind === kind);+ findings.push({ ...base, class: skipped ? 'consent_required' : 'pending', ...(kind ? { repair_kind: kind } : {}),+ ...(skipped ? { command: skipped.command } : kind ? { command: `gbrain repair ${kind} --apply` } : {}) });+ }+ return findings;+}++export function remediationExitStatus(result: RemediationResult, findings: RemediationFinding[]): number {+ if (result.resume_refused) return 2;+ if (result.budget_exhausted) return 1;+ const jobFailed = result.submitted.some(s => s.status !== 'completed' && s.status !== 'submitted' && s.status !== 'dry_run');+ // A stopped step (capacity, pending write, unfinished embeddings) left work behind.+ const repairFailed = (result.repairs ?? []).some(r => r.status === 'failed' || r.status === 'stopped');+ if (jobFailed || repairFailed) return 1;+ if (findings.some(f => f.class === 'pending' || f.class === 'consent_required')) return 1;+ if (result.target_unreachable) return 2;+ return 0;+}++/**+ * CLI wrapper around runRemediation. Default: submit-and-wait per job step,+ * in-process repair steps with --include-repairs. --dry-run skips submission.+ */+export async function runRemediate(engine: BrainEngine, args: string[]): Promise<void> {+ if (args.includes('--help') || args.includes('-h')) { console.log(REMEDIATE_HELP); return; }+ const targetScore = parseIntFlag(args, '--target-score') ?? 90;+ const maxJobs = parseIntFlag(args, '--max-jobs') ?? Infinity;+ // --max-cost is an alias for --max-usd; both feed the pre-flight refusal+ // and, via withBudgetTracker, the mid-run BudgetExhausted hard stop.+ const maxUsdRaw = parseFloatFlag(args, '--max-usd') ?? parseFloatFlag(args, '--max-cost');+ const maxUsd = maxUsdRaw === null ? undefined : maxUsdRaw;+ const dryRun = args.includes('--dry-run');+ const skipConfirm = args.includes('--yes');+ const jsonOutput = args.includes('--json');+ const includeRepairs = args.includes('--include-repairs');+ const noEmbed = args.includes('--no-embed');+ const resumeFlagIdx = args.indexOf('--resume');+ const resumeMode = resumeFlagIdx !== -1;+ const resumeArg = resumeMode ? args[resumeFlagIdx + 1] : undefined;+ const resumePlanHash = resumeArg && !resumeArg.startsWith('--') ? resumeArg : undefined;+ const log = (line: string) => (jsonOutput ? console.error : console.log)(line);++ const { runRemediation, computeRemediationPlan } = await import('../../core/remediation/index.ts');++ // TTY confirmation gate (stays in CLI; library doesn't render).+ if (!skipConfirm && !dryRun && process.stdout.isTTY && !resumeMode) {+ const plan = await computeRemediationPlan(engine, { targetScore, repairs: { noEmbed } });+ const repairs = plan.repair_steps ?? [];+ if (plan.target_unreachable && !(includeRepairs && repairs.length)) {+ console.error(`[remediate] target ${targetScore} unreachable; max autonomous = ${plan.max_reachable_score}/100. `+ + `Configure missing prereqs (see --remediation-plan blocked output) or lower --target-score.`);+ process.exit(2);+ }+ if (plan.plan.length === 0 && repairs.length === 0) {+ console.log(`Brain at score ${plan.brain_score_current}/100, target ${targetScore}. Nothing to do.`);+ return;+ }+ console.log(`About to submit ${plan.plan.length} job(s), est ${plan.est_total_seconds}s, est $${plan.est_total_usd_cost.toFixed(2)}`+ + (repairs.length ? `, and ${includeRepairs ? 'run' : 'skip (no --include-repairs)'} ${repairs.length} repair step(s)` : ''));+ console.log('Pass --yes to proceed (cron-friendly).');+ process.exit(1);+ }++ if (engine.kind === 'pglite') console.error('[remediate] PGLite engine: running inline (no durable queue).');+ const before = dryRun ? [] : await runWaveChecks(engine);++ const result = await runRemediation(engine,+ { targetScore, maxJobs, maxUsd, dryRun, resume: resumeMode, resumePlanHash, repairs: { include: includeRepairs, remote: false, noEmbed } },+ {+ onTargetUnreachable: (target, ceiling) => {+ console.error(`[remediate] target ${target} unreachable; max autonomous = ${ceiling}/100. `+ + (includeRepairs ? 'Job steps are skipped; repair steps still run.' : 'Configure missing prereqs (see --remediation-plan blocked output) or lower --target-score.'));+ },+ onNothingToDo: (score, target) => log(`Brain at score ${score}/100, target ${target}. Nothing to do.`),+ onBudgetRefused: (estCost, cap) => console.error(`[remediate] est job cost $${estCost.toFixed(2)} exceeds the remaining --max-usd $${cap.toFixed(2)}. Job steps not started.`),+ onResumeMissed: (planHash, requested) => console.error(`[remediate --resume] no matching checkpoint found `+ + `(plan_hash=${planHash}${requested ? `; requested=${requested}` : ''}). Run without --resume to start fresh.`),+ onResumeBrainMismatch: (planHash, cpBrain, brain) => console.error(`[remediate --resume] checkpoint ${planHash} belongs to brain ${cpBrain}, `+ + `but the selected brain is ${brain}. Refusing to resume; select that brain with --brain, or run without --resume.`),+ onResumeCap: (cap, spent) => console.error(`[remediate --resume] cumulative cap ${cap === null ? 'none' : `$${cap.toFixed(2)}`} `+ + `(recorded in the checkpoint unless --max-usd was given); $${spent.toFixed(4)} already spent.`),+ onResumeLoaded: (planHash, completed, remaining) => console.error(`[remediate --resume] resuming plan_hash=${planHash}: ${completed} step(s) completed, ${remaining} remaining.`),+ onRepairStepEnd: (step, r) => log(` repair ${step.kind}: ${r.status}${r.applied ? `, applied ${r.applied}` : ''}${r.message ? ` — ${r.message}` : ''}`),+ onBudgetExhausted: (_planHash, snapshot) => console.error(`\n[remediate] Budget exhausted (${snapshot.reason}): spent $${snapshot.spent.toFixed(4)} `+ + `of the cumulative cap $${snapshot.cap.toFixed(2)}. Checkpoint saved (cap, consent and remaining steps).`),+ });++ if (result.budget_exhausted) {+ const cap = result.budget?.max_usd ?? result.budget_exhausted.cap;+ console.error(`Resume with:\n gbrain doctor --remediate --yes${result.budget?.include_repairs ? ' --include-repairs' : ''}`+ + `${cap !== null && cap !== undefined ? ` --max-usd ${cap}` : ''} --resume ${result.budget_exhausted.plan_hash}\n`+ + '(the cap is cumulative: spend from this run counts against it)');+ }++ const after = dryRun ? [] : await runWaveChecks(engine);+ const findings = classifyWaveFindings(before, after, result);+ const exitStatus = dryRun ? (result.target_unreachable ? 2 : 0) : remediationExitStatus(result, findings);+ const repairsCompleted = (result.repairs ?? []).filter(r => r.status === 'completed').length;+ const healthy = !dryRun && after.every(f => f.state === 'ok');++ if (jsonOutput) {+ console.log(JSON.stringify({ ...result, findings, repairs_completed: repairsCompleted, healthy, exit_status: exitStatus }, null, 2));+ } else {+ if (dryRun && result.submitted.length > 0) {+ console.log(`[remediate --dry-run] Would run ${result.submitted.length} step(s):`);+ for (const s of result.submitted) console.log(` - ${s.id}`);+ } else if (result.submitted.length > 0) {+ console.log(`\nBrain score: ${result.brain_score_initial} → ${result.brain_score_final} (target ${targetScore})`);+ // #3626: a step that deduped onto an in-flight job did not submit new work; a rotated re-run did.+ const coalesced = result.submitted.filter((s) => s.coalesced).length;+ const rotated = result.submitted.filter((s) => s.deduped_job_id !== undefined).length;+ const notes = [+ ...(rotated > 0 ? [`${rotated} re-ran under a rotated key (prior terminal row held it)`] : []),+ ...(coalesced > 0 ? [`${coalesced} coalesced onto in-flight job(s)`] : []),+ ];+ console.log(`Submitted: ${result.submitted.length - coalesced} job(s)${notes.length > 0 ? ` (${notes.join('; ')})` : ''}, ${result.aborted_count} aborted/failed`);+ }+ if (result.repairs?.length) console.log(`Repair steps completed: ${repairsCompleted} of ${result.repairs.length}`);+ const skipped = result.repairs_skipped ?? [];+ if (skipped.length) {+ console.log(`${skipped.length} repair step${skipped.length === 1 ? '' : 's'} skipped (user agreement required): re-run with --include-repairs`);+ for (const step of skipped) console.log(` - ${step.kind}: ${step.affected} item(s); ${step.command}`);+ }+ for (const f of findings.filter(f => f.class !== 'cleared')) {+ console.log(`[${f.class}] ${f.check_id}: ${f.instruction ?? f.command ?? f.message}`);+ }+ const cleared = findings.filter(f => f.class === 'cleared').map(f => f.check_id);+ if (cleared.length) console.log(`Cleared: ${cleared.join(', ')}`);+ }+ setCliExitVerdict(exitStatus);+}diff --git a/src/commands/doctor/report-remote.ts b/src/commands/doctor/report-remote.tsindex 8097e7dc28..8367b16551 100644--- a/src/commands/doctor/report-remote.ts+++ b/src/commands/doctor/report-remote.ts@@ -474,5 +474,11 @@ export async function doctorReportRemote(// File-plane only (no engine) — works on thin clients too.checks.push(checkSelfUpgradeHealth());+ // 14. Wave checks as sanitized host-action lines (doctor/wave-checks.ts):+ // stable check id, a count-free impact summary and the on-host preview+ // command; a check that could not run reports unknown, never ok.+ const { remoteWaveHandoff } = await import('./wave-checks.ts');+ checks.push(...await remoteWaveHandoff(engine, opts.sourceIds));+return computeDoctorReport(checks);}diff --git a/src/commands/doctor/upgrade-banner.ts b/src/commands/doctor/upgrade-banner.tsnew file mode 100644index 0000000000..917c4cbadb--- /dev/null+++ b/src/commands/doctor/upgrade-banner.ts@@ -0,0 +1,44 @@+/**+ * The `gbrain post-upgrade` recovery banner (fix wave 3, Lane D). Runs every+ * wave check once (the full checks, not `doctor --fast`) and, when any has a+ * finding, prints one `[AGENT] Relay this to your operator` block naming the+ * selected brain, the count per finding, the read-only preview command and+ * the instruction to ask the user before applying anything. It never prints+ * an applying command (`--yes`, `--apply`): applying is the user's decision.+ * A clean brain prints nothing.+ */+import type { BrainEngine } from '../../core/engine.ts';+import { runWaveChecks } from './wave-checks.ts';+import { readConnectorSourceStatuses } from '../../core/persistence/connector-status.ts';++/** #5686: connector sources that re-walk their window once, or resumed from a pre-upgrade checkpoint. */+async function connectorRewalkNote(engine: BrainEngine): Promise<string | null> {+ const statuses = [...(await readConnectorSourceStatuses(engine)).values()];+ const rewalking = statuses.filter(status => status.upgrade_recovery === 'rewalking_once').length;+ const resumed = statuses.filter(status => status.upgrade_recovery === 'resumed').length;+ if (!rewalking && !resumed) return null;+ return `connector_rewalk: ${rewalking} connector source(s) re-walk their window once on the next run (a one-time admission spike, not new churn)`+ + `${resumed ? `; ${resumed} resumed from a pre-upgrade checkpoint` : ''}. Check with: gbrain sources status`;+}++/**+ * Extra banner lines contributed by other subsystems (for example the count+ * of connector sources that will re-walk once after a checkpoint migration).+ * Each returns null when it has nothing to say.+ */+export const POST_UPGRADE_NOTES: Array<(engine: BrainEngine) => Promise<string | null>> = [connectorRewalkNote];++export async function postUpgradeRecoveryBanner(engine: BrainEngine, brainLabel: string): Promise<string[]> {+ const findings = (await runWaveChecks(engine)).filter(f => f.state !== 'ok');+ const notes = (await Promise.all(POST_UPGRADE_NOTES.map(note => note(engine).catch(() => null)))).filter((n): n is string => !!n);+ if (!findings.length && !notes.length) return [];+ const lines = ['', `[AGENT] Relay this to your operator: brain ${brainLabel} has residual state to review after the upgrade.`];+ for (const { spec, check, state } of findings) {+ const how = spec.resolution === 'repair' ? 'repairable after the user agrees' : spec.resolution === 'operator' ? 'needs an operator action' : 'reported only; no command clears it yet';+ lines.push(state === 'unknown' ? `[AGENT] ${spec.id}: could not be checked (health unknown)` : `[AGENT] ${spec.id}: ${spec.count(check.details ?? {})} (${how})`);+ }+ for (const note of notes) lines.push(`[AGENT] ${note}`);+ lines.push('[AGENT] Preview (read-only): gbrain doctor --remediation-plan');+ lines.push('[AGENT] Ask the user before applying any repair; the plan prints the exact commands. Recipe: docs/guides/repair.md#recover-after-upgrading-to-this-release');+ return lines;+}diff --git a/src/commands/doctor/wave-checks.ts b/src/commands/doctor/wave-checks.tsnew file mode 100644index 0000000000..98b481b595--- /dev/null+++ b/src/commands/doctor/wave-checks.ts@@ -0,0 +1,172 @@+/**+ * Wave checks: the doctor checks that report residual state from the managed+ * persistence waves, each with a stable id and a declared resolution. One+ * table feeds four consumers so they can never disagree:+ *+ * - the local doctor (checks registered here rather than inline in doctor.ts),+ * - the remote doctor's sanitized host-action lines (report-remote.ts),+ * - `gbrain doctor --remediate` finding classification,+ * - the `gbrain post-upgrade` banner.+ *+ * `resolution` says how a non-ok finding clears: `repair` (a registered+ * `gbrain repair` kind names this check in its `checks`), `operator` (a named+ * manual action on the brain host), or `unsupported` (no command can clear it+ * yet; it is reported, never hidden). Add a check by appending one entry.+ */+import type { BrainEngine } from '../../core/engine.ts';+import type { Check } from '../doctor.ts';+import { repairForCheck } from '../../core/repair/registry.ts';++export type WaveResolution = 'repair' | 'operator' | 'unsupported';++export interface WaveScope {+ /** Remote source scope; undefined means brain-wide (local trusted callers). */+ sourceIds?: string[];+}++export interface WaveCheckSpec {+ id: string;+ resolution: WaveResolution;+ /** Count-free, path-free impact line safe for remote callers. */+ impact: string;+ /** The named instruction for an operator-required or unsupported finding. */+ instruction?: string;+ /** Where the local doctor runs it: inline in doctor.ts, or from this table. */+ registration: 'doctor.ts' | 'wave';+ /** Reason the check is not offered to remote callers, if any. */+ hostOnly?: string;+ /** Items behind a finding, read from the check's details (host-side banners only). */+ count(details: Record<string, any>): number;+ run(engine: BrainEngine, scope: WaveScope): Promise<Check>;+}++/** Checks that take one optional source id: run once brain-wide, or once per scoped source and merged. */+async function perSource(scope: WaveScope, run: (sourceId?: string) => Promise<Check>): Promise<Check> {+ if (!scope.sourceIds) return run();+ const checks = await Promise.all(scope.sourceIds.map(id => run(id)));+ const worst = checks.find(c => c.status === 'fail') ?? checks.find(c => c.status === 'warn') ?? checks[0];+ return worst ?? { name: '', status: 'ok', message: '' };+}++export const WAVE_CHECKS: readonly WaveCheckSpec[] = [+ {+ id: 'timeline_history', resolution: 'repair', registration: 'doctor.ts',+ count: d => Number(d.materializable_rows ?? 0),+ impact: 'Some timeline rows exist only in the database and are missing from their pages',+ run: async (engine, scope) => { const { timelineHistoryCheck } = await import('./checks/timeline-history.ts'); return perSource(scope, id => timelineHistoryCheck(engine, id)); },+ },+ {+ id: 'derived_visibility', resolution: 'repair', registration: 'doctor.ts',+ count: d => Number(d.unstamped_atoms ?? 0) + Number(d.unstamped_concepts ?? 0) + Number(d.looser_atoms ?? 0) + Number(d.looser_concepts ?? 0),+ impact: 'Some derived pages have no explicit visibility or are stored looser than their origin',+ run: async (engine, scope) => { const { derivedVisibilityCheck } = await import('./checks/derived-visibility.ts'); return perSource(scope, id => derivedVisibilityCheck(engine, id)); },+ },+ {+ id: 'safe_index_pending', resolution: 'repair', registration: 'wave',+ count: d => Number(d.pages_pending ?? 0),+ impact: 'Some pages are below the safe-chunk index version and are withheld from remote search',+ run: async (engine, scope) => (await import('./checks/safe-index.ts')).safeIndexPendingCheck(engine, scope.sourceIds),+ },+ {+ id: 'connector_checkpoints', resolution: 'repair', registration: 'wave',+ count: d => Number(d.count ?? 0),+ impact: 'Some connector checkpoint rows can no longer be loaded by any connector source',+ run: async engine => (await import('./checks/connector-checkpoints.ts')).checkConnectorCheckpoints(engine),+ },+ {+ id: 'unbound_source', resolution: 'operator', registration: 'wave',+ count: d => (d.sources ?? []).filter((source: { bound?: boolean }) => source.bound).reduce((sum: number, source: { pages?: number }) => sum + Number(source.pages ?? 0), 0),+ impact: 'Some pages written database-only while their source was unbound now sit outside canonical files',+ instruction: 'Keep them database-only, or for a page whose slug already has a canonical file preview both sides with `gbrain sources reconcile <source> <slug> --brain <brain> --preview` and apply the agreed resolution (docs/guides/write-refusals.md#unbound-sources-on-postgres).',+ run: async engine => (await import('./checks/unbound-source.ts')).checkUnboundSource(engine),+ },+ {+ id: 'persistence_capacity', resolution: 'operator', registration: 'doctor.ts',+ count: d => (d.resources ?? []).length,+ impact: 'A cumulative managed-write limit is at or above 80%',+ instruction: 'Raise the named journal limit with the `gbrain config set` command doctor prints, on the brain host.',+ run: async engine => (await import('./checks/persistence-capacity.ts')).checkPersistenceCapacity(engine),+ },+ {+ id: 'parked_effects', resolution: 'operator', registration: 'doctor.ts',+ count: d => Number(d.parked_effects ?? 0),+ impact: 'Some Git or withdrawal effects are parked after repeated failures',+ instruction: 'Fix the cause, then run the `gbrain sources writer retry-effects <source> --request-id <id>` command doctor prints (preview with --dry-run first).',+ run: async (engine, scope) => (await import('./checks/parked-effects.ts')).checkParkedEffects(engine, scope.sourceIds),+ },+ {+ id: 'dream_paid_loop', resolution: 'operator', registration: 'doctor.ts',+ count: d => (d.keys ?? []).length,+ impact: 'A dream synthesis key keeps dying and was paid for on each attempt',+ instruction: 'Fix the cause, then reset the breaker with the command doctor prints.',+ run: async engine => (await import('./checks/dream-breaker.ts')).dreamPaidLoopCheck(engine),+ },+ {+ id: 'writer_version', resolution: 'operator', registration: 'wave',+ impact: 'A writer older than this release admitted or published a recent write',+ instruction: 'Run `gbrain upgrade` on each host doctor names (by host UUID), then restart its gbrain processes; an older writer may still delete database-only timeline rows.',+ count: d => Number(d.count ?? 0),+ run: async engine => (await import('./checks/writer-version.ts')).writerVersionCheck(engine),+ },+ {+ id: 'self_capture', resolution: 'operator', registration: 'wave',+ count: d => Number(d.classified ?? 0),+ impact: 'The session corpus still holds files captured from gbrain\'s own model sessions',+ instruction: 'Quarantine the listed corpus files by hand with the commands in docs/guides/repair.md#quarantine-self-captured-corpus-files; nothing is deleted automatically.',+ run: async engine => (await import('./checks/self-capture.ts')).selfCaptureCheck(engine),+ },+ {+ id: 'stale_embedding_effects', resolution: 'unsupported', registration: 'wave',+ count: d => Number(d.stale_effects ?? 0),+ impact: 'A committed write still has a queued embedding effect that no command can clear yet',+ instruction: 'Inspect it with `gbrain sources writer status <source> --json`; inspection cannot clear it (see docs/guides/repair.md#stale-queued-embedding-effects).',+ run: async (engine, scope) => (await import('./checks/stale-embedding-effects.ts')).staleEmbeddingEffectsCheck(engine, scope.sourceIds),+ },+];++/** A check that could not run reports unknown, never ok. */+export function checkHealthUnknown(check: Check): boolean {+ return check.details?.health === 'unknown' || check.details?.count === 'unknown';+}++export interface WaveFinding { spec: WaveCheckSpec; check: Check; state: 'ok' | 'finding' | 'unknown' }++/** Run wave checks; a throwing check becomes an unknown finding instead of aborting the rest. */+export async function runWaveChecks(engine: BrainEngine, opts: WaveScope & { only?: WaveCheckSpec['registration']; remote?: boolean } = {}): Promise<WaveFinding[]> {+ const specs = WAVE_CHECKS.filter(spec => (!opts.only || spec.registration === opts.only) && (!opts.remote || !spec.hostOnly));+ const findings: WaveFinding[] = [];+ for (const spec of specs) {+ let check: Check;+ try { check = await spec.run(engine, { sourceIds: opts.sourceIds }); }+ catch (error) {+ check = { name: spec.id, status: 'warn', message: `${spec.id} could not run: ${error instanceof Error ? error.message : String(error)}. Health is unknown.`,+ details: { health: 'unknown' } };+ }+ check = { ...check, name: spec.id };+ findings.push({ spec, check, state: checkHealthUnknown(check) ? 'unknown' : check.status === 'ok' ? 'ok' : 'finding' });+ }+ return findings;+}++/** The repair kind that clears a wave finding, when its resolution is `repair`. */+export function waveRepairKind(spec: WaveCheckSpec) {+ return spec.resolution === 'repair' ? repairForCheck(spec.id)?.kind : undefined;+}++export const REMOTE_HOST_ACTION = 'host operator action required: on the brain host run `gbrain doctor --remediation-plan`';++/**+ * Remote doctor lines: one per remotely offered wave check, with a stable id,+ * the count-free impact summary and the on-host preview command. No host+ * paths, row contents, SQL, account emails or installation ids.+ */+export async function remoteWaveHandoff(engine: BrainEngine, sourceIds?: string[]): Promise<Check[]> {+ const findings = await runWaveChecks(engine, { sourceIds, remote: true });+ return findings.map(({ spec, state }) => {+ const host_action = { check_id: spec.id, state: state === 'finding' ? 'action_required' : state, preview_command: 'gbrain doctor --remediation-plan' };+ if (state === 'ok') return { name: spec.id, status: 'ok' as const, message: 'No host action needed.', details: { host_action } };+ if (state === 'unknown') return { name: spec.id, status: 'warn' as const, details: { host_action },+ message: `Unknown: this check could not run for the remote caller; ${REMOTE_HOST_ACTION}.` };+ return { name: spec.id, status: 'warn' as const, details: { host_action }, message: `${spec.impact}; ${REMOTE_HOST_ACTION}.` };+ });+}diff --git a/src/commands/dream.ts b/src/commands/dream.tsindex 07c27b1d33..25bb5009fe 100644--- a/src/commands/dream.ts+++ b/src/commands/dream.ts@@ -864,8 +864,9 @@ export async function runDream(engine: BrainEngine | null, args: string[]): Prom}// Exit non-zero when the cycle failed overall (helps cron spot real problems).- // 'partial' is not a failure — it means some phase warned but the cycle ran.- if (report.status === 'failed') {+ // 'partial' is not a failure — it means some phase warned but the cycle ran —+ // except when a phase threw and was contained so later phases could run.+ if (report.status === 'failed' || report.phases.some(p => p.details?.contained === true)) {process.exit(1);}diff --git a/src/commands/embed.ts b/src/commands/embed.tsindex 7911422a7f..cb8a222a1f 100644--- a/src/commands/embed.ts+++ b/src/commands/embed.ts@@ -20,7 +20,7 @@ import {import { createProgress, type ProgressReporter } from '../core/progress.ts';import { getCliOptions, cliOptsToProgressOptions } from '../core/cli-options.ts';import { assertEmbeddingEnabled } from '../core/embedding-dim-check.ts';-import { invalidateStaleSignatureEmbeddingsGuarded } from '../core/embedding-invalidation.ts';+import { countRestampOnlyChunks, invalidateStaleSignatureEmbeddingsGuarded } from '../core/embedding-invalidation.ts';import { loadConfig, type GBrainConfig } from '../core/config.ts';import { slog, serr } from '../core/console-prefix.ts';import { filterOutEmbedSkipped } from '../core/embed-skip.ts';@@ -36,10 +36,12 @@ import {import { tryAcquireDbLock, type DbLockHandle } from '../core/db-lock.ts';import { embedBackfillLockId } from '../core/embed-backfill-lock.ts';import { AITransientError } from '../core/ai/errors.ts';+import { isEmbeddingZeroNormError } from '../core/ai/embedding-guard.ts';import { wrapChunkTextsForStoredMode } from '../core/embedding-context.ts';import {restampIfDemotedToTitleTier,embedBatchWithBackoff,+ embedBatchKeepingUsable,isEmbedRetriableError,isTransientNetworkEmbedError,type EmbedBatchWithBackoffOpts,@@ -84,7 +86,8 @@ const EMBED_UNAVAILABLE_MESSAGE = 'Page or source is unavailable or changed; nofunction recordFailure(result: EmbedResult, chunkCount: number, slug: string, e: unknown): void {result.failures += chunkCount;if (result.failure_samples.length < FAILURE_SAMPLE_CAP) {- result.failure_samples.push(`${slug}: ${e instanceof Error ? e.message : String(e)}`);+ const fix = isEmbeddingZeroNormError(e) ? ` ${e.suggestionFor(slug)}` : '';+ result.failure_samples.push(`${slug}: ${e instanceof Error ? e.message : String(e)}${fix}`);}}@@ -257,6 +260,8 @@ export interface EmbedResult {skipped: number;/** Chunks that would be embedded if not for dryRun (0 in non-dryRun). */would_embed: number;+ /** #5289 dryRun: signature-stale chunks whose current-space vectors are only restamped. */+ would_restamp?: number;/** Total chunks considered across all processed pages. */total_chunks: number;/** Number of pages processed (whether or not they had stale chunks). */@@ -1766,7 +1771,10 @@ async function embedAllStale(}if (dryRun) {- result.would_embed += staleCount;+ // #5289: current-space vectors on a drifted page are restamped, not re-embedded.+ const restamp = signature ? await countRestampOnlyChunks(engine, { signature, sourceId, includeNullSignature: includeNullSig }) : 0;+ result.would_embed += staleCount - restamp;+ result.would_restamp = restamp;result.total_chunks += staleCount;// No progress event: a dry run reads a count and processes zero pages, so// there is no page total to report. The previous synthetic onProgress(1,1,0)@@ -1781,7 +1789,7 @@ async function embedAllStale(const chunklessNote = result.chunkless_pages_healed > 0? `, including ${result.chunkless_pages_healed} chunkless page(s)`: '';- slog(`[dry-run] Would embed ${result.would_embed} stale chunks${chunklessNote}`);+ slog(`[dry-run] Would embed ${result.would_embed} stale chunks${chunklessNote}${restamp ? `; ${restamp} chunk(s) keep their vectors and are only restamped` : ''}`);}return;}@@ -2140,9 +2148,12 @@ async function embedPageTexts(opts: EmbedBatchWithBackoffOpts = {},): Promise<{ embeddings: (Float32Array | null)[]; failed: number; firstError?: unknown }> {try {- return { embeddings: await embedBatchWithBackoff(texts, opts), failed: 0 };+ // #4616: the gateway already isolated degenerate items; keep the rest.+ const { vectors, refused } = await embedBatchKeepingUsable(texts, opts);+ return { embeddings: vectors, failed: refused?.failures.length ?? 0, firstError: refused };} catch (e: unknown) {if (opts.abortSignal?.aborted) throw e; // shutdown, not a chunk problem+ if (isEmbeddingZeroNormError(e)) throw e; // nothing usable: fanning out would re-send the same inputsif (texts.length <= 1) throw e; // nothing to isolate// #3374 — network-transient exhaustion isn't chunk-specific either:// fanning out during an outage multiplies failing calls per page.diff --git a/src/commands/enrich.ts b/src/commands/enrich.tsindex 9e6b8df173..d2e32c9011 100644--- a/src/commands/enrich.ts+++ b/src/commands/enrich.ts@@ -33,7 +33,8 @@ import { randomUUID } from 'node:crypto';import type { BrainEngine } from '../core/engine.ts';import type { EnrichCandidate, PageType } from '../core/types.ts';import { operations, OperationError } from '../core/operations.ts';-import { assertUnmanagedCanonicalWriter } from '../core/persistence/maintenance.ts';+import { maintenancePreflight, publishMaintenancePage, type MaintenanceAuthority } from '../core/persistence/prepared-maintenance.ts';+import { preserveCanonicalFences } from '../core/cycle/concept-publication.ts';import type { WriteReceipt } from '../core/persistence/types.ts';import type { OperationContext } from '../core/operations.ts';import { configureGatewayIfUninitialized, isAvailable, chat, getChatModel, withBudgetTracker } from '../core/ai/gateway.ts';@@ -340,6 +341,8 @@ interface EnrichOneCtx {done: Set<string>;signal?: AbortSignal;config: ReturnType<typeof loadConfig>;+ /** Managed brains publish through the maintenance coordinator (#5280); null when unmanaged. */+ maintenance: MaintenanceAuthority | null;}async function enrichOne(ctx: EnrichOneCtx, candidate: EnrichCandidate): Promise<void> {@@ -439,12 +442,20 @@ async function enrichOneLocked(ctx: EnrichOneCtx, candidate: EnrichCandidate): Penriched_at: new Date().toISOString(),enriched_by: ENRICHED_BY,};- const content = serializeMarkdown(newFrontmatter, parsed.body, page.timeline ?? '', {+ // The model owns the prose only: the page's facts/takes fences are carried+ // over verbatim so publication never expires fence facts or deletes takes.+ const content = serializeMarkdown(newFrontmatter, preserveCanonicalFences(page, parsed.body), page.timeline ?? '', {type: page.type,title: page.title,tags,});+ if (ctx.maintenance) {+ await publishMaintenancePage(engine, ctx.maintenance, slug, content, { expectedRevision: snapshot.revision });+ ctx.result.pages_enriched++;+ ctx.done.add(completedKey(sourceId, slug));+ return;+ }const putPageOp = operations.find((o) => o.name === 'put_page');if (!putPageOp) throw new Error('put_page operation missing (gbrain build issue)');const opCtx: OperationContext = {@@ -475,7 +486,6 @@ export async function runEnrichCore(signal?: AbortSignal,): Promise<EnrichResult> {if (!opts.sourceId) throw new Error('runEnrichCore: opts.sourceId is required');- if (!opts.dryRun) await assertUnmanagedCanonicalWriter(engine, 'enrich');const result: EnrichResult = {candidates_considered: 0,@@ -544,6 +554,9 @@ export async function runEnrichCore(// permanent instead of decaying (the intended retry channel; --force is// the immediate one).if (pending.length === 0) return result;+ // #5280: a managed brain publishes through the maintenance coordinator; the+ // preflight refuses a missing canonical owner before any model spend.+ const maintenance = opts.dryRun ? null : await maintenancePreflight(engine, opts.sourceId);const body = async () => {const oneCtx: EnrichOneCtx = {@@ -557,6 +570,7 @@ export async function runEnrichCore(done,signal,config,+ maintenance,};let lastFlush = 0;diff --git a/src/commands/extract-conversation-facts.ts b/src/commands/extract-conversation-facts.tsindex 78a8a719db..cb9d6aad2e 100644--- a/src/commands/extract-conversation-facts.ts+++ b/src/commands/extract-conversation-facts.ts@@ -73,7 +73,8 @@ import {type ExtractedFact,} from '../core/facts/extract.ts';import { configureGatewayIfUninitialized, isAvailable, withBudgetTracker } from '../core/ai/gateway.ts';-import { assertUnmanagedCanonicalWriter } from '../core/persistence/maintenance.ts';+import { managedDerivedFactsPreflight, writeDerivedFacts } from '../core/persistence/derived-facts.ts';+import { managedPersistenceEnabled } from '../core/persistence/ownership.ts';import { BudgetTracker, BudgetExhausted, loadPricingOverrides } from '../core/budget/budget-tracker.ts';import { listSources } from '../core/sources-ops.ts';import {@@ -698,7 +699,7 @@ async function deleteOrphanFactsForPage(): Promise<number> {// A cleanup failure is authoritative: callers must not write a terminal or// non-extractable marker while facts from an older snapshot may remain.- const rows = await engine.executeRaw<{ count: string }>(+ const rows = await writeDerivedFacts(engine, sourceId, slug, db => db.executeRaw<{ count: string }>(`WITH del AS (DELETE FROM factsWHERE source_id = $1@@ -708,7 +709,7 @@ async function deleteOrphanFactsForPage()SELECT COUNT(*)::text AS count FROM del`,[sourceId, slug],- );+ ));const n = parseInt(rows[0]?.count ?? '0', 10);return Number.isFinite(n) ? n : 0;}@@ -1162,7 +1163,7 @@ async function processPage(context:fact.context ?? `from ${page.slug} segment ${seg.startIso}..${seg.endIso}`,}));- const ins = await state.engine.insertFacts(rows, { source_id: state.sourceId }); // gbrain-allow-direct-insert: canonical bulk extraction path for conversation pages — fences-as-system-of-record doesn't apply because conversations don't carry `## Facts` fences (the chat-log shape is the source-of-truth)+ const ins = await writeDerivedFacts(state.engine, state.sourceId, page.slug, db => db.insertFacts(rows, { source_id: state.sourceId })); // gbrain-allow-direct-insert: canonical bulk extraction path for conversation pages — fences-as-system-of-record doesn't apply because conversations don't carry `## Facts` fences (the chat-log shape is the source-of-truth)pageInsertedTotal += ins.inserted;state.result.facts_inserted += ins.inserted;}@@ -1242,7 +1243,7 @@ async function writeTerminalAuditRow(row_num: rowNum,source_markdown_slug: slug,};- await engine.insertFacts([fact], { source_id: sourceId }); // gbrain-allow-direct-insert: page-level TERMINAL audit row (Codex C7 / E16) marks extraction completion in the durable facts table — there's no fence equivalent because this is internal audit state, not user-facing knowledge+ await writeDerivedFacts(engine, sourceId, slug, db => db.insertFacts([fact], { source_id: sourceId })); // gbrain-allow-direct-insert: page-level TERMINAL audit row (Codex C7 / E16) marks extraction completion in the durable facts table — there's no fence equivalent because this is internal audit state, not user-facing knowledge}/**@@ -1279,7 +1280,7 @@ async function writeNonExtractableAuditRow(row_num: rowNum,source_markdown_slug: slug,};- await engine.insertFacts([fact], { source_id: sourceId }); // gbrain-allow-direct-insert: durable non-extractable audit outcome prevents repeated scans while remaining distinct from successful extraction+ await writeDerivedFacts(engine, sourceId, slug, db => db.insertFacts([fact], { source_id: sourceId })); // gbrain-allow-direct-insert: durable non-extractable audit outcome prevents repeated scans while remaining distinct from successful extraction}export async function runExtractConversationFactsCore(@@ -1291,7 +1292,7 @@ export async function runExtractConversationFactsCore(if (!sourceId) {throw new Error('runExtractConversationFactsCore: opts.sourceId is required');}- await assertUnmanagedCanonicalWriter(engine, 'bulk conversation fact extraction');+ await managedDerivedFactsPreflight(engine, sourceId);const result: ExtractConversationFactsResult = {pages_considered: 0,@@ -1676,8 +1677,8 @@ async function writeRunReceiptAndRollup(// receipt slug. shortRunId() truncates to 8 chars.const runId = `ecf-${Date.now().toString(36)}-${sourceId.slice(0, 4)}`;- // Receipt write: only when the run actually inserted facts.- if (result.facts_inserted > 0) {+ // Receipt write: only when the run actually inserted facts (receipt pages are unmanaged-only, like extract_atoms).+ if (result.facts_inserted > 0 && !await managedPersistenceEnabled(engine)) {try {await writeReceipt(engine, {kind: 'facts.conversation',@@ -1915,7 +1916,6 @@ export async function runExtractConversationFacts(console.log(HELP);return;}- await assertUnmanagedCanonicalWriter(engine, 'bulk conversation fact extraction');// --background path.const backgrounded = await maybeBackground({diff --git a/src/commands/extract.ts b/src/commands/extract.tsindex 857783a1c9..61a9c5a2b2 100644--- a/src/commands/extract.ts+++ b/src/commands/extract.ts@@ -734,6 +734,16 @@ export async function runExtractCore(engine: BrainEngine, opts: ExtractOpts): Pr);const workers = workersResolved.workers;+ // Managed brains: the file walk's raw timeline batch is refused by the+ // writer guard, so links, missing canonical timeline rows and the watermark+ // publish on the one managed path (the same one sync and `extract --stale` run).+ if (!dryRun && opts.mode === 'all' && opts.slugs?.length !== 0 && await managedPersistenceEnabled(engine)) {+ const { extractManagedStaleLinks } = await import('../core/persistence/links-maintenance.ts');+ const progress = createProgress(cliOptsToProgressOptions(getCliOptions())); progress.start('extract.links_fs', opts.slugs?.length);+ const r = await extractManagedStaleLinks(engine, { sourceId: opts.sourceId, slugs: opts.slugs, signal: opts.signal, maxPages: opts.slugs?.length });+ progress.finish(); return { links_created: r.created, timeline_entries_created: r.timeline, pages_processed: r.pages };+ }+// Incremental path: if specific slugs provided, only extract from those files.// This is the cycle path — sync tells us what changed, we only re-extract those.if (opts.slugs !== undefined) {diff --git a/src/commands/google-attachments.ts b/src/commands/google-attachments.tsindex 6a599f9fa4..105aa95842 100644--- a/src/commands/google-attachments.ts+++ b/src/commands/google-attachments.ts@@ -11,7 +11,7 @@ import { isValidSourceId } from '../core/source-id.ts';import { parseGoogleSourceConfig, runGoogleAttachmentBackfill } from '../core/google/google-source.ts';import type { FetchImpl } from '../core/google/google-clients.ts';import { managedSyncAuthority } from '../core/persistence/sync-authority.ts';-import { connectorCheckpointKey } from '../core/persistence/connector-sync.ts';+import { connectorCheckpointKey, connectorIdentity } from '../core/persistence/connector-identity.ts';import type { GoogleSourceState } from '../core/google/types.ts';import { isCredentialError } from '../core/creds/errors.ts';@@ -81,7 +81,7 @@ export async function runGoogleAttachments(args: string[], connected?: BrainEngiconst [count] = await engine.executeRaw<{ count: string }>(`SELECT count(*)::text AS count FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND frontmatter->>'thread_id' IS NOT NULL`, [parsed.sourceId]);const [checkpoint] = await engine.executeRaw<{ completed_keys: Array<{ state: GoogleSourceState }> }>("SELECT completed_keys FROM op_checkpoints WHERE op='managed-connector' AND fingerprint=$1",- [connectorCheckpointKey(parsed.sourceId, source.incarnation, 'google', source.config)]);+ [connectorCheckpointKey(parsed.sourceId, source.incarnation, connectorIdentity('google', source.config, source.local_path))]);return { status: 'preview' as const, complete: false, imported_thread_pages: Number(count.count), account: cfg.account, writes: 'none',historical_inspection: checkpoint?.completed_keys[0]?.state?.gmail_attachment_backfill ?? { status: 'not_inspected' } };}diff --git a/src/commands/import.ts b/src/commands/import.tsindex 4246727cf9..87b21e0c27 100644--- a/src/commands/import.ts+++ b/src/commands/import.ts@@ -34,6 +34,7 @@ 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 { acceptedPendingReceipt } from '../core/persistence/accepted-pending.ts';import { estimateCostFromChars, lookupEmbeddingPrice } from '../core/embedding-pricing.ts';import { getEmbeddingModel } from '../core/ai/gateway.ts';@@ -706,16 +707,19 @@ export async function runImport(if (e !== signal.reason && !(e instanceof Error && e.name === 'AbortError')) throw e;return;}- const msg = e instanceof Error ? e.message : String(e);- const { count, sample } = recordImportFailure(errorCounts, errorSamples, msg);- if (count <= 5) {- console.error(` Warning: skipped ${relativePath}: ${msg}`);- } else if (count === 6) {- console.error(` (suppressing further "${sample.slice(0, 60)}..." errors)`);+ // #5600: an accepted managed import still publishing is not a failure; the next run resumes its request.+ if (acceptedPendingReceipt(e)) { skipped++; console.error(` Pending: ${relativePath} was accepted and is still publishing; rerun to confirm it.`); } else {+ const msg = e instanceof Error ? e.message : String(e);+ const { count, sample } = recordImportFailure(errorCounts, errorSamples, msg);+ if (count <= 5) {+ console.error(` Warning: skipped ${relativePath}: ${msg}`);+ } else if (count === 6) {+ console.error(` (suppressing further "${sample.slice(0, 60)}..." errors)`);+ }+ errors++;+ skipped++;+ failures.push({ path: importRelPath, error: msg });}- errors++;- skipped++;- failures.push({ path: importRelPath, error: msg });}processed++;tickProgress();diff --git a/src/commands/jobs.ts b/src/commands/jobs.tsindex 22329a5aeb..504dde3c6b 100644--- a/src/commands/jobs.ts+++ b/src/commands/jobs.ts@@ -3012,10 +3012,12 @@ export async function registerBuiltinHandlers(const olderThanHours = typeof job.data.olderThanHours === 'number' ? job.data.olderThanHours : 72;const dryRun = !!job.data.dryRun;let pagesPurged = 0;+ let pagesBlocked: Array<{ source_id: string; slug: string; reason: string }> = [];+ let pagesError: string | undefined;let sourcesPurged: string[] = [];if (scope === 'pages' || scope === 'all') {- const result = await engine.purgeDeletedPages(olderThanHours);- pagesPurged = result.count;+ const result = await (await import('../core/persistence/purge-deleted.ts')).purgeDeletedPagesCoordinated(engine, olderThanHours);+ pagesPurged = result.count; pagesBlocked = result.blocked; pagesError = result.error?.message;}let sourcesBlocked: Array<{ id: string; reason: string }> = [];if (scope === 'sources' || scope === 'all') {@@ -3027,7 +3029,9 @@ export async function registerBuiltinHandlers(// GC stale op_checkpoints rows (folded scope item +C from review).const { purgeStaleCheckpoints } = await import('../core/op-checkpoint.ts');const checkpointsPurged = await purgeStaleCheckpoints(engine, 7);- return { pagesPurged, sourcesPurged, sourcesBlocked, checkpointsPurged, dryRun };+ // #5405: a coordinated purge failure fails the job after the other purges ran.+ if (pagesError) throw new Error(pagesError);+ return { pagesPurged, pagesBlocked, sourcesPurged, sourcesBlocked, checkpointsPurged, dryRun };});// Phase-wrapper handlers — each delegates to runCycle({ phases: [name] }).diff --git a/src/commands/lint.ts b/src/commands/lint.tsindex 63b7b7ffd5..ca0f6dd422 100644--- a/src/commands/lint.ts+++ b/src/commands/lint.ts@@ -536,7 +536,7 @@ export async function runLintCore(opts: LintOpts): Promise<LintResult> {throw new Error(`Not found: ${opts.target}`);}- if (opts.engine && !hasSourceFilesystemLock(opts.target)) {+ if (opts.engine && opts.fix && !opts.dryRun && !hasSourceFilesystemLock(opts.target)) {return withSourceFilesystemLock(opts.engine, opts.target, () => runLintCore(opts), { signal: opts.signal });}diff --git a/src/commands/migrate-embeddings.ts b/src/commands/migrate-embeddings.tsindex 8e96f98d3b..c4dc4ad24a 100644--- a/src/commands/migrate-embeddings.ts+++ b/src/commands/migrate-embeddings.ts@@ -36,7 +36,8 @@ import { prepareEmbeddingProjections } from '../core/embedding-readiness.ts';import { assertRetainedEmbeddingRebuildability } from '../core/embedding-migration-retention.ts';import { embedStaleFacts } from '../core/embed-facts.ts';import { countStaleFactEmbeddings } from '../core/facts/embedding-identity.ts';-import { authorizeMigrationBudget, assertMigrationLeases } from '../core/embedding-migration-budget.ts';+import { authorizeMigrationBudget, assertMigrationLeases, ceilCents, MigrationBudgetRefusal, type MigrationBudgetRefusalDetails, type MigrationWorstCase } from '../core/embedding-migration-budget.ts';+import { planMigrationWorstCase, MIGRATION_PROBE_TEXT, RERANKER_PROBE } from '../core/embedding-migration-worst-case.ts';import { withAIInvocationGuard } from '../core/ai/invocation-guard.ts';/**@@ -69,7 +70,8 @@ Flags:declared width; required when the recipe declares none.--dry-run Plan + cost estimate only; change nothing.--yes Skip the confirm prompt (required non-interactively).- --max-cost-usd <USD> Total durable authorization; retries retain debits. Raise explicitly to renew.+ --max-cost-usd <USD> Total durable authorization; must cover the printed worst case (or the run+ refuses before any change). Requests settle to reported usage; raise to renew.--json Machine-readable envelope on stdout.--no-embed Apply schema + config + invalidation, but skip there-embed pass. Inspect --status, then rerun this migration@@ -112,7 +114,7 @@ function renderPlan(ctx: MigrationPlanContext): string {lines.push(` From: ${plan.from_model} (${plan.from_dims}d${plan.column_dims !== null && plan.column_dims !== plan.from_dims ? `; column is actually ${plan.column_dims}d` : ''})`);lines.push(` To: ${plan.to_model} (${plan.to_dims}d)`);lines.push(` Work: ${plan.chunks_to_embed} chunks, ${plan.facts_to_embed ?? 0} active facts; ${plan.blocked_projection_pages ?? 0} projection-blocked pages.`);- lines.push(' Paid authorization: --max-cost-usd is a durable total cap, conservatively debited before each attempt; unknown prices refuse.');+ lines.push(' Paid authorization: --max-cost-usd is a durable total cap; each attempt reserves its maximum input size and settles to reported usage; unknown prices refuse.');// DB-reality census: what pages say they were embedded with (env can lie// about From; the census cannot).if (plan.signature_census.length > 0) {@@ -172,6 +174,17 @@ function renderPlan(ctx: MigrationPlanContext): string {? ` Estimated cost: $${plan.est_cost_usd.toFixed(2)} (${plan.total_chars} chars at the ${plan.to_model} rate)`: ` Estimated cost: unknown — no pricing entry for ${plan.to_model}. Check the provider's pricing before proceeding.`,);+ const worst = plan.worst_case_authorization;+ lines.push(worst.usd === null+ ? ` Worst-case authorization: unknown (${worst.requests} request(s); no price for ${plan.to_model}); paid dispatch refuses until priced.`+ : ` Worst-case authorization: $${ceilCents(worst.usd).toFixed(2)} (${worst.requests} request(s) at maximum input size; retries and batch splits settle from the same headroom).`);+ const unpricedReranker = worst.unpriced_models.filter(m => m !== plan.to_model);+ if (worst.usd !== null && unpricedReranker.length) {+ lines.push(` WARNING: reranker ${unpricedReranker.join(', ')} has no price; its probe refuses without dispatch and the switch is reported as failed. The worst case above covers embeddings only.`);+ }+ if (worst.usd !== null && worst.prior_debited_usd > 0) {+ lines.push(` Prior debits: $${worst.prior_debited_usd.toFixed(4)} retained; --max-cost-usd must be at least $${ceilCents(worst.usd + worst.prior_debited_usd).toFixed(2)}.`);+ }if (plan.resuming) {lines.push(' Resuming: a prior migration to this target was interrupted; continuing it.');}@@ -273,7 +286,7 @@ export async function probeTargetProvider(): Promise<{ ok: true } | { ok: false; message: string }> {try {const { embed } = await import('../core/ai/gateway.ts');- const vecs = await embed(['gbrain embedding migration probe'], {+ const vecs = await embed([MIGRATION_PROBE_TEXT], {embeddingModel: toModel,dimensions: toDims,});@@ -306,8 +319,8 @@ export async function probeTargetReranker(try {const { rerank } = await import('../core/ai/gateway.ts');const results = await rerank({- query: 'gbrain reranker migration probe',- documents: ['gbrain reranker migration probe document a', 'gbrain reranker migration probe document b'],+ query: RERANKER_PROBE.query,+ documents: [...RERANKER_PROBE.documents],model,timeoutMs: 8000,});@@ -411,8 +424,11 @@ export interface RerankerOutcome {suggestion?: string | null;}+/** The plan plus its worst-case authorization (#5680) and the same target's retained debits. */+export type MigrationPlan = EmbeddingMigrationPlan & { worst_case_authorization: MigrationWorstCase & { prior_debited_usd: number } };+export interface MigrationPlanContext {- plan: EmbeddingMigrationPlan;+ plan: MigrationPlan;verify: MigrationVerify;envPresence: ReturnType<typeof detectEnvPresence>;/** env is set AND exactly pins the target (the notice-and-proceed case). */@@ -435,6 +451,7 @@ export type MigrationFlowResult =| { status: 'refused_env'; warning: EnvOverrideWarning }| { status: 'probe_failed'; message: string }| { status: 'apply_failed'; reason: string }+ | { status: 'refused_budget'; refusal: MigrationBudgetRefusalDetails }| {status: 'applied_no_embed';invalidated: number; cache_cleared: number;@@ -515,6 +532,8 @@ export async function planMigrationFlow(// Reranker companion decision (D8) — throws a paste-ready message on an// invalid explicit --reranker value BEFORE anything destructive can run.const rerankerPlan = await resolveRerankerPlan(engine, plan.from_model, plan.to_model, opts.reranker);+ const worstCase = await planMigrationWorstCase(engine, plan, { rerankerModel: rerankerPlan.action.kind === 'switch' ? rerankerPlan.action.to : undefined });+ const priorDebitedUsd = marker.state && !inflightOther ? marker.state.budget?.debited_usd ?? 0 : 0;// Brain/DB identity (round-1 C1): make wrong-brain routing visible in every// transcript. Redacted — never print a raw connection string.@@ -551,7 +570,8 @@ export async function planMigrationFlow(if (col && col !== 'embedding') customSearchColumn = col;} catch { /* informational */ }- return { plan, verify, envPresence, envMatchesTarget, inflightOther, rerankerPlan, identity, concurrentWriters, customSearchColumn };+ return { plan: { ...plan, worst_case_authorization: { ...worstCase, prior_debited_usd: priorDebitedUsd } },+ verify, envPresence, envMatchesTarget, inflightOther, rerankerPlan, identity, concurrentWriters, customSearchColumn };}/**@@ -658,8 +678,15 @@ export async function executeMigrationFlow(return { status: 'apply_failed', reason: 'Embedding is disabled or its policy is invalid; no provider requests or migration invalidation performed. Review the selected brain embedding configuration before retrying.' };}await engine.transaction(async tx => { await assertOwned(tx); await assertRetainedEmbeddingRebuildability(tx, plan.to_dims, plan.to_model, plan); });- const debit = await authorizeMigrationBudget(engine, plan, opts.maxCostUsd, heldLocks,- ctx.rerankerPlan.action.kind === 'switch' ? ctx.rerankerPlan.action.to : undefined);+ const rerankerModel = ctx.rerankerPlan.action.kind === 'switch' ? ctx.rerankerPlan.action.to : undefined;+ let debit: Awaited<ReturnType<typeof authorizeMigrationBudget>>;+ try {+ debit = await authorizeMigrationBudget(engine, plan, opts.maxCostUsd, heldLocks, rerankerModel,+ await planMigrationWorstCase(engine, plan, { rerankerModel }));+ } catch (error) {+ if (error instanceof MigrationBudgetRefusal) return { status: 'refused_budget', refusal: error.details };+ throw error;+ }return await withAIInvocationGuard(async call => {await assertOwned();const permit = await debit(call);@@ -1045,7 +1072,7 @@ export async function runMigrateEmbeddings(// Refusals normalize to the op-envelope shape ({status:'refused', reason})// in their own cases below; everything else gets the generic envelope.- if (flags.json && result.status !== 'refused_env' && result.status !== 'refused_retarget') {+ if (flags.json && result.status !== 'refused_env' && result.status !== 'refused_retarget' && result.status !== 'refused_budget') {console.log(JSON.stringify({ ...result, plan,...(result.status !== 'completed' && result.status !== 'applied_no_embed' && { recovery: EMBEDDING_MIGRATION_RECOVERY }),}, null, 2));@@ -1081,6 +1108,15 @@ export async function runMigrateEmbeddings(exit(1);break;}+ case 'refused_budget': {+ if (flags.json) {+ console.log(JSON.stringify({ status: 'refused', reason: result.refusal.error, ...result.refusal, plan, recovery: EMBEDDING_MIGRATION_RECOVERY }, null, 2));+ }+ serr(result.refusal.message);+ serr(` Docs: ${result.refusal.docs}`);+ exit(1);+ break;+ }case 'probe_failed': {serr(result.message);exit(1);diff --git a/src/commands/migrations/v0_13_1.ts b/src/commands/migrations/v0_13_1.tsindex 6b4c1194df..486b45c50f 100644--- a/src/commands/migrations/v0_13_1.ts+++ b/src/commands/migrations/v0_13_1.ts@@ -43,7 +43,7 @@ import { loadConfig, toEngineConfig, gbrainPath } from '../../core/config.ts';import { createEngine } from '../../core/engine-factory.ts';import type { BrainEngine } from '../../core/engine.ts';import { managedPersistenceEnabled } from '../../core/persistence/ownership.ts';-import { grandfatherCanonicalPage } from '../../core/persistence/grandfather.ts';+import { admitCanonicalGrandfather } from '../../core/persistence/grandfather.ts';import { OperationError } from '../../core/ops/contract.ts';// Bug 3 — ledger writes moved to the runner (apply-migrations.ts).@@ -107,6 +107,9 @@ const GRANDFATHER_WHERE =// (same rationale as engine-constants.ts DELETE_BATCH_SIZE).const CHUNK_SIZE = 1000;+// Grandfather writes admitted before the step waits for them (#5530).+const GRANDFATHER_WINDOW = 50;+/** A page this run grandfathered and the revision its write produced. */export interface GrandfatheredPage { id: number; revision: string | null; }@@ -157,19 +160,31 @@ export async function phaseCGrandfather(const selected = await engine.executeRaw<{ id: number; slug: string; source_id: string; source_incarnation: string }>('SELECT p.id,p.slug,p.source_id,s.incarnation AS source_incarnation FROM pages p JOIN sources s ON s.id=p.source_id WHERE p.id=ANY($1::int[]) AND NOT s.archived ORDER BY p.id', [chunk]);gf.skipped += chunk.length - selected.length;- for (const page of selected) {- try {- const outcome = await grandfatherCanonicalPage(engine, page, snapshot => appendRollbackBatch([snapshot]));- if (outcome.status === 'touched') {+ const fail = (page: { id: number }, error: unknown) => {+ gf.failed++;+ const reason = error instanceof OperationError+ ? `${error.code}${error.writeRequest ? ` request_id=${error.writeRequest.request_id}` : ''}`+ : error instanceof Error ? error.message : String(error);+ gf.failures.push(`page#${page.id}: ${reason}`.slice(0, 120));+ };+ // #5530: admit a bounded window before waiting (below the principal's+ // outstanding-request limit), so the pages' Git effects are ready+ // together and the effect runner commits and pushes them as groups.+ for (let w = 0; w < selected.length; w += GRANDFATHER_WINDOW) {+ const admitted: { page: typeof selected[number]; complete: () => Promise<{ revision: string | null }> }[] = [];+ for (const page of selected.slice(w, w + GRANDFATHER_WINDOW)) {+ try {+ const outcome = await admitCanonicalGrandfather(engine, page, snapshot => appendRollbackBatch([snapshot]));+ if (outcome.status === 'skipped') gf.skipped++;+ else admitted.push({ page, complete: outcome.complete });+ } catch (error) { fail(page, error); }+ }+ for (const { page, complete } of admitted) {+ try {+ const outcome = await complete();gf.touched++;gf.grandfathered.push({ id: page.id, revision: outcome.revision });- } else gf.skipped++;- } catch (error) {- gf.failed++;- const reason = error instanceof OperationError- ? `${error.code}${error.writeRequest ? ` request_id=${error.writeRequest.request_id}` : ''}`- : error instanceof Error ? error.message : String(error);- gf.failures.push(`page#${page.id}: ${reason}`.slice(0, 120));+ } catch (error) { fail(page, error); }}}continue;diff --git a/src/commands/pages.ts b/src/commands/pages.tsindex ca2fe24ee9..72a27212d3 100644--- a/src/commands/pages.ts+++ b/src/commands/pages.ts@@ -7,6 +7,8 @@* page_links, chunk_relations via existing FKs.*/import type { BrainEngine } from '../core/engine.ts';+import { purgeDeletedPagesCoordinated } from '../core/persistence/purge-deleted.ts';+import { setCliExitVerdict } from '../core/cli-force-exit.ts';const SOFT_DELETE_TTL_HOURS_DEFAULT = 72;@@ -44,11 +46,15 @@ async function runPurgeDeleted(engine: BrainEngine, args: string[]): Promise<voireturn;}- const result = await engine.purgeDeletedPages(olderThanHours);+ const result = await purgeDeletedPagesCoordinated(engine, olderThanHours);if (json) {- console.log(JSON.stringify({ older_than_hours: olderThanHours, count: result.count, slugs: result.slugs }, null, 2));+ console.log(JSON.stringify({ older_than_hours: olderThanHours, count: result.count, slugs: result.slugs,+ ...(result.blocked.length ? { blocked: result.blocked } : {}) }, null, 2));+ if (result.error) setCliExitVerdict(1);return;}+ for (const b of result.blocked) console.error(`Not purged: ${b.source_id}/${b.slug}: ${b.reason}`);+ if (result.error) setCliExitVerdict(1);if (result.count === 0) {console.log(`No pages to purge (older than ${olderThanHours}h).`);} else {diff --git a/src/commands/persistence-admin.ts b/src/commands/persistence-admin.tsindex ad7290a18c..a593f56fca 100644--- a/src/commands/persistence-admin.ts+++ b/src/commands/persistence-admin.ts@@ -20,6 +20,8 @@ export const WRITER_HELP = `Usage:gbrain sources writer activate --confirm-quiesced [--cleanup-dead-local-locks] [--shared-skills] [administration options] [--dry-run] [--json]gbrain sources writer transfer prepare <source> [--self-transfer] [administration options] [--dry-run] [--json]gbrain sources writer transfer accept <source> --path <worktree-root> --expected-epoch <n> --manifest <sha256> [--self-transfer] [administration options] [--dry-run] [--json]+ gbrain sources writer lock [--json]+ gbrain sources writer unlock [--json]Inspect status first. Routine diagnosis, doctor --fix, startup, and maintenancemust not change ownership or activate managed persistence. Read the operator@@ -31,7 +33,9 @@ Explicit noninteractive administration is supported. Stale state is rejected.Use --brain <id> to select a database. Prepare drains the current owner and recordsan exact manifest; accept requires that epoch and matching bytes on the successor.Before activation, upgrade and stop older writers on every host, claim every-filesystem source, and inspect/release remaining legacy locks. --confirm-quiesced+filesystem source, and inspect/release remaining legacy locks. A claim alone+fences legacy sync, sources push and lint --fix for that checkout; claim output+says so while persistence is not activated. --confirm-quiescedattests quiescence but does not grant administration intent. --dry-run never enables.Self-transfer is opt-in on both phases and only repairs this host's recordedcanonical root; it never relocates a checkout. Inspect status again after prepare.@@ -45,7 +49,16 @@ previews parked targets with --dry-run and otherwise authorizes one more attemptper parked target (a target that fails again parks again). For embeddings itreconciles existing complete vectors or authorizes one additional bounded retrycycle 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.`;+It never changes ownership or activation and needs no topology admin-intent.+lock sets an opt-in, brain-level writer admin lock (config key persistence.writer_admin_lock)+and unlock clears it; both are local-only, idempotent and print the resulting state.+While locked, writer claim, activate and transfer (prepare and accept) are refused with+writer_admin_locked for every caller; ordinary writes continue. lock refuses while a transfer+is prepared and not yet accepted. There is no --force: the escape hatch is the local unlock+(operator workflow: unlock, administer, lock). The lock guards against routine or accidental+agent administration; it is not a security boundary against a caller with the same shell.+Binaries older than this release do not consult the lock. status shows admin_lock,+local_host_id, blocking effects and the latest admitter/consumer versions per host.`;export const LOCAL_WRITER_HELP = `Usage:gbrain auth local-writer list [--limit <1-1000>] [--before <uuid>] [--json]@@ -103,11 +116,13 @@ export function parsePersistenceAdminArgs(group: Group, args: string[]): {else if (verb === 'retry-effects') operation = 'writer_retry_effects';else if (verb === 'claim') operation = 'writer_claim';else if (verb === 'activate') operation = 'writer_activate';+ else if (verb === 'lock') operation = 'writer_lock';+ else if (verb === 'unlock') operation = 'writer_unlock';else if (verb === 'transfer') {const phase = positional.shift();if (phase !== 'prepare' && phase !== 'accept') throw new OperationError('invalid_params', 'Transfer requires prepare or accept.');operation = phase === 'prepare' ? 'writer_transfer_prepare' : 'writer_transfer_accept';- } else throw new OperationError('invalid_params', 'Writer administration requires status, retry-effects, claim, activate, or transfer.');+ } else throw new OperationError('invalid_params', 'Writer administration requires status, retry-effects, claim, activate, transfer, lock, or unlock.');const source = positional.shift();if (source !== undefined) {if (params.source_id !== undefined) throw new OperationError('invalid_params', 'Specify the source once.');@@ -149,6 +164,7 @@ export async function runPersistenceAdminCli(group: Group, args: string[], conneresult = await runPersistenceAdministration(connected ?? owned!, parsed.operation, parsed.params, config,brainId === 'host' ? 'owner' : 'mounted_database');}+ if (['writer_status', 'writer_lock', 'writer_unlock'].includes(parsed.operation)) result = { selected_brain: brainId, ...(result as Record<string, unknown>) };await writeStdoutFinal(JSON.stringify(result, bigintToStringReplacer, 2) + '\n');} catch (error) {if (!await reportPersistenceCliError(error, args.includes('--json'))) {diff --git a/src/commands/pglite-repair.ts b/src/commands/pglite-repair.tsindex 27df5e0895..abc5f1fd13 100644--- a/src/commands/pglite-repair.ts+++ b/src/commands/pglite-repair.ts@@ -72,7 +72,8 @@ The default gbrain engine (PGLite) can fail to open after an unclean shutdown(commonly a macOS-upgrade reboot) with "RuntimeError: Aborted()". The cause istorn WAL/checkpoint state on disk, not a macOS WASM bug. This command resetsthe WAL in place (pg_resetwal semantics): data files are preserved;-transactions not checkpointed before the corruption may be lost. The+transactions not checkpointed before the corruption may be lost, and indexes+are not rebuilt, so run \`gbrain reindex --vectors\` afterwards. Thepre-repair pg_wal + pg_control are kept in a sibling backup directory.Usage:@@ -315,14 +316,15 @@ export async function runPgliteRepair(args: string[]): Promise<number> {wal_seg_size: receipt.walSegSize,repaired_at: receipt.repairedAt,backups_on_disk: listRepairBackups(dataDir),+ next_command: 'gbrain reindex --vectors',}));} else {console.log('WAL reset complete.');console.log(` Data dir: ${receipt.dataDir}`);console.log(` Backup: ${receipt.backupPath}${receipt.reusedEpisodeBackup ? ' (reused this episode’s existing backup)' : ''}`);console.log(` Reset segment: ${receipt.resetSegment} (timeline ${receipt.timelineId}, ${receipt.walSegSize / (1024 * 1024)}MB segments)`);- console.log(' Data files were preserved; un-checkpointed transactions may be lost.');- console.log(' Next: run any gbrain command to reopen the brain, then `gbrain doctor`.');+ console.log(' Un-checkpointed transactions may be lost, and indexes are not rebuilt.');+ console.log(' Next: rebuild the vector indexes with `gbrain reindex --vectors` (it reopens the brain), then run `gbrain doctor`.');}return 0;} finally {diff --git a/src/commands/reindex-vectors.ts b/src/commands/reindex-vectors.tsnew file mode 100644index 0000000000..0ad6ce4c40--- /dev/null+++ b/src/commands/reindex-vectors.ts@@ -0,0 +1,40 @@+/**+ * `gbrain reindex --vectors [--dry-run] [--json]` — rebuild every HNSW vector+ * index in the brain from the stored vectors.+ *+ * #4616: a PGLite WAL reset (auto-repair or `gbrain pglite-repair`) resets the+ * log in place but never rebuilds indexes, so an HNSW index can miss rows+ * written just before the crash. Those pages stay reachable by `gbrain get`+ * and keyword search while vector search never returns them. Rebuilding the+ * index from the table is the fix; no vector is re-embedded and nothing is+ * paid. Postgres rebuilds concurrently so reads and writes continue.+ */+import type { BrainEngine } from '../core/engine.ts';+import { quoteIdentifier } from '../core/search/embedding-column.ts';++export const REINDEX_VECTORS_COMMAND = 'gbrain reindex --vectors';++export interface ReindexVectorsResult {+ indexes: { table: string; index: string }[];+ rebuilt: number;+ dry_run: boolean;+}++export async function runReindexVectors(engine: BrainEngine, args: string[]): Promise<ReindexVectorsResult> {+ const dryRun = args.includes('--dry-run');+ const indexes = (await engine.executeRaw<{ table: string; index: string }>(+ `SELECT tablename AS table, indexname AS index FROM pg_indexes+ WHERE schemaname = current_schema() AND indexdef ~* 'USING hnsw' ORDER BY tablename, indexname`));+ let rebuilt = 0;+ for (const { table, index } of dryRun ? [] : indexes) {+ if (!args.includes('--json')) process.stderr.write(`[reindex] rebuilding ${table}.${index}\n`);+ await engine.executeRaw(`REINDEX INDEX ${engine.kind === 'postgres' ? 'CONCURRENTLY ' : ''}${quoteIdentifier(index)}`);+ rebuilt++;+ }+ const result = { indexes, rebuilt, dry_run: dryRun };+ if (args.includes('--json')) console.log(JSON.stringify(result));+ else console.log(dryRun+ ? `reindex --vectors: would rebuild ${indexes.length} vector index(es): ${indexes.map(i => i.index).join(', ') || '(none)'}`+ : `reindex --vectors: rebuilt ${rebuilt} vector index(es)`);+ return result;+}diff --git a/src/commands/reindex.ts b/src/commands/reindex.tsindex fcd1a00d69..7803a74c4b 100644--- a/src/commands/reindex.ts+++ b/src/commands/reindex.ts@@ -82,6 +82,7 @@ USAGEgbrain reindex --markdown [--type PAGE_TYPE] [--limit N] [--dry-run] [--no-embed] [--json] [--repo PATH]gbrain reindex --multimodal [--limit N] [--workers N] [--dry-run] [--cost-estimate] [--no-embed] [--yes] [--json]gbrain reindex --aliases [--limit N] [--dry-run] [--json] [--source <id>]+ gbrain reindex --vectors [--dry-run] [--json]TARGETS (exactly one required)--markdown Re-chunk markdown pages whose chunker_version lags the@@ -91,6 +92,8 @@ TARGETS (exactly one required)embedding pipeline (Voyage batches).--aliases Backfill the free-text alias layer (page_aliases) forpages whose frontmatter aliases predate the projection.+ --vectors Rebuild every HNSW vector index from the stored vectors+ (no re-embedding, no cost). Run after a PGLite WAL repair.OPTIONS--type <t> --markdown only: restrict to one page typediff --git a/src/commands/repair.ts b/src/commands/repair.tsindex 95851e50ff..18f8aafa36 100644--- a/src/commands/repair.ts+++ b/src/commands/repair.ts@@ -8,15 +8,21 @@* 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';+import { OperationError } from '../core/ops/contract.ts';+import { REPAIR_KINDS, resolveRepairScope, runRepair, type RepairKind, type RepairResult } from '../core/repair/core.ts';+import { REPAIR_REGISTRY, repairMaySpend, repairRunner, repairSpec } from '../core/repair/registry.ts';-const HANDLERS: Record<RepairKind, RepairHandler> = { timeline: timelineRepair, visibility: visibilityRepair, 'safe-chunks': safeChunksRepair };+function wrap(text: string, indent: number, width = 80): string {+ const lines: string[] = [];+ let line = '';+ for (const word of text.split(' ')) {+ if (line && indent + line.length + 1 + word.length > width) { lines.push(line); line = word; }+ else line = line ? `${line} ${word}` : word;+ }+ if (line) lines.push(line);+ return lines.join(`\n${' '.repeat(indent)}`);+}export const REPAIR_HELP = `Usage: gbrain repair [<kind>] [--apply] [--source <id>] [--limit <n>] [--no-embed] [--json]gbrain repair --all [--apply] [--source <id>] [--json]@@ -24,32 +30,58 @@ export const REPAIR_HELP = `Usage: gbrain repair [<kind>] [--apply] [--source <iRepair 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.+${REPAIR_REGISTRY.map(spec => ` ${spec.kind.length < 13 ? spec.kind.padEnd(12) : `${spec.kind}\n${' '.repeat(14)}`} ${wrap(spec.summary, 15)}`).join('\n')}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.+ --no-embed safe-chunks, contextual-mode: no provider call; embed later with gbrain embed --stale.--all Run every kind in order (${REPAIR_KINDS.join(', ')}).--json Machine-readable output with a stable shape.+Any other option is refused. There is no --max-usd here: to cap paid embedding+work, run the repairs through gbrain doctor --remediate --yes --include-repairs --max-usd <n>.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;+const BOOLEAN_FLAGS = new Set(['--apply', '--all', '--json', '--no-embed']);+const VALUE_FLAGS = new Set(['--source', '--limit']);++interface RepairArgs { kind?: string; apply: boolean; all: boolean; json: boolean; noEmbed: boolean; source?: string; limit?: string }++/** Strict parse: every flag is known, value flags carry a value, at most one kind. */+export function parseRepairArgs(args: string[]): RepairArgs {+ const parsed: RepairArgs = { apply: false, all: false, json: false, noEmbed: false };+ const positional: string[] = [];+ for (let i = 0; i < args.length; i++) {+ const token = args[i]!;+ if (!token.startsWith('-')) { positional.push(token); continue; }+ const equal = token.indexOf('=');+ const flag = equal < 0 ? token : token.slice(0, equal);+ if (flag === '--yes') throw new OperationError('invalid_params', '`--yes` is not accepted by gbrain repair; pass --apply to write.');+ if (flag === '--max-usd' || flag === '--max-cost') {+ const cap = equal < 0 ? args[i + 1] : token.slice(equal + 1);+ throw new OperationError('invalid_params', `${flag} is not a gbrain repair option; the repair did not run.`,+ `To cap paid repair work, run: gbrain doctor --remediate --yes --include-repairs --max-usd ${cap && !cap.startsWith('-') ? cap : '<n>'}`);+ }+ if (BOOLEAN_FLAGS.has(flag)) {+ if (equal >= 0) throw new OperationError('invalid_params', `${flag} does not accept a value.`);+ if (flag === '--apply') parsed.apply = true;+ else if (flag === '--all') parsed.all = true;+ else if (flag === '--json') parsed.json = true;+ else parsed.noEmbed = true;+ continue;+ }+ if (!VALUE_FLAGS.has(flag)) throw new OperationError('invalid_params', `Unknown option ${flag} for gbrain repair.`, 'Run gbrain repair --help for the accepted options.');+ const value = equal >= 0 ? token.slice(equal + 1) : args[++i];+ if (!value || value.startsWith('--')) throw new OperationError('invalid_params', `${flag} requires a value.`);+ if (flag === '--source') parsed.source = value;+ else parsed.limit = value;+ }+ if (positional.length > 1) throw new OperationError('invalid_params', `Unexpected argument '${positional[1]}'; gbrain repair takes at most one kind.`,+ `Kinds: ${REPAIR_KINDS.join(', ')}.`);+ parsed.kind = positional[0];+ return parsed;}function human(result: RepairResult): string {@@ -69,39 +101,31 @@ function human(result: RepairResult): string {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 { kind, apply, all, json, noEmbed, source, limit: limitText } = parseRepairArgs(args);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.');+ if (kind && all) throw new OperationError('invalid_params', 'Pass either a kind or --all, not both.');+ if (!kind && apply && !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[] = [];+ const runner = await repairRunner(engine, { apply, noEmbed });+ const results: Array<RepairResult & { paid: boolean }> = [];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);+ const result = await runner.run(k, scope, { limit, sourceFlag: source });+ results.push({ ...result, paid: repairMaySpend(repairSpec(k), noEmbed) });if (result.stopped) break;}+ const paidKinds = results.filter(r => r.paid).map(r => r.kind);if (json) {- console.log(JSON.stringify({ scope, mode: apply ? 'apply' : 'dry_run', results }, null, 2));+ console.log(JSON.stringify({ scope, mode: apply ? 'apply' : 'dry_run', results, paid_kinds: paidKinds }, 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 (!apply && paidKinds.length) console.log(`Kinds that may queue paid embeddings: ${paidKinds.join(', ')} (pass --no-embed to skip; `+ + 'page-write kinds are re-embedded by their publication either way; cap spend with gbrain doctor --remediate --yes --include-repairs --max-usd <n>).');}if (results.some(r => r.stopped)) setCliExitVerdict(1);}diff --git a/src/commands/source-reconcile.ts b/src/commands/source-reconcile.tsindex b159c45444..3a2f10be57 100644--- a/src/commands/source-reconcile.ts+++ b/src/commands/source-reconcile.ts@@ -28,7 +28,10 @@ export const RECONCILE_HELP = `Usage:gbrain sources reconcile <source> <slug> --brain <id> --backups [--limit <1-100>] [--after <request-uuid>] [--json]gbrain sources reconcile <source> <slug> --brain <id> --remove-backup <exact-reference> [--json]-Preview is the default and never changes canonical content. --out creates a new+Preview is the default and never changes canonical content. A database-only+page (no recorded origin, for example one written while the source was unbound)+is previewed against the canonical file at its slug path; apply records that+file as the page's origin. --out creates a newprivate file outside canonical worktrees; it never replaces an existing file.Resolve conflicts with JSON-Pointer decisions and inspect the resolved previewbefore applying. Apply preserves both originals and uses the current canonicaldiff --git a/src/commands/sources.ts b/src/commands/sources.tsindex 36b8499817..a9ee0c2715 100644--- a/src/commands/sources.ts+++ b/src/commands/sources.ts@@ -1235,12 +1235,14 @@ async function runStatus(engine: BrainEngine, args: string[]): Promise<void> {}),);+ const connectors = await (await import('../core/persistence/connector-status.ts')).readConnectorSourceStatuses(engine);if (json) {const enriched = metrics.map((m) => ({...m,sync_running: syncRunning.has(m.source_id),sync_holder: syncRunning.get(m.source_id) ?? null,...(ingestion.get(m.source_id) ? { ingestion: ingestion.get(m.source_id) } : {}),+ ...(connectors.get(m.source_id) ? { connector: connectors.get(m.source_id) } : {}),}));console.log(JSON.stringify({ schema_version: 1, sources: enriched }, null, 2));return;@@ -1278,6 +1280,8 @@ async function runStatus(engine: BrainEngine, args: string[]): Promise<void> {console.log(` ${m.source_id.padEnd(20)} ${lag.padEnd(8)} ${embed.padEnd(7)} ${backfill.padEnd(9)} ${fails.padEnd(6)} ${queue.padEnd(6)} ${pages.padStart(8)} ${sync}`);}console.log('');+ const { connectorStatusLines } = await import('../core/persistence/connector-status.ts');+ for (const [sourceId, status] of connectors) for (const line of connectorStatusLines(sourceId, status)) console.log(line);for (const m of metrics) {const warns: string[] = [];if (!m.local_path) warns.push('no local_path');diff --git a/src/commands/sync.ts b/src/commands/sync.tsindex 0e70a643c9..7d16e36263 100644--- a/src/commands/sync.ts+++ b/src/commands/sync.ts@@ -352,6 +352,8 @@ export interface SyncOpts {skipFailed?: boolean;/** Bug 9 — re-attempt unacknowledged failures explicitly (CLI --retry-failed). */retryFailed?: boolean;+ /** Managed connector sources: discard the connector checkpoint and re-walk the window once (CLI --reset-checkpoint). */+ resetCheckpoint?: boolean;/*** v0.41.37.0 #1569 — skip loading the active schema pack during sync. When set,* `loadActivePack` is not called, so no user-supplied pack page-type regex@@ -629,8 +631,10 @@ See also:// runBreakLock, buildPartialResult) was peeled to src/core/sync-lock.ts// (pure move). Re-exported so existing importers keep working.export { SyncLockBusyError, runBreakLock } from '../core/sync-lock.ts';+import { assertResetCheckpointSource } from '../core/persistence/connector-reset.ts';async function runConnectorSync(engine: BrainEngine, opts: SyncOpts, managed: boolean): Promise<SyncResult | null> {+ if (opts.resetCheckpoint) await assertResetCheckpointSource(engine, opts.sourceId);if (!opts.sourceId && !opts.githubItem) return null;const sourceId = opts.sourceId ?? 'default';const [source] = await engine.executeRaw<{ local_path: string | null; config: unknown }>(@@ -4608,6 +4612,8 @@ Options:--skip-failed Acknowledge previously-recorded sync failures sothe bookmark can advance past unparseable files.--retry-failed Re-attempt previously-failed files; clear on success.+ --reset-checkpoint Connector source only: re-walk its window once from an empty+ checkpoint; unchanged pages are not admitted again.--watch Re-sync continuously on an interval.--interval N Watch-mode interval in seconds (default 60).--no-pull Skip 'git pull' before the sync (useful for tests).@@ -4667,7 +4673,7 @@ See also:let noEmbed = resolveNoEmbed(args, loadConfig());const noExtract = args.includes('--no-extract'); // v0.42.7 #1696const skipFailed = args.includes('--skip-failed');- const retryFailed = args.includes('--retry-failed');+ const retryFailed = args.includes('--retry-failed'), resetCheckpoint = args.includes('--reset-checkpoint');const noSchemaPack = args.includes('--no-schema-pack'); // v0.41.37.0 #1569const explicitProcessing = ([['--no-embed', 'noEmbed'], ['--no-extract', 'noExtract'], ['--no-schema-pack', 'noSchemaPack']] as const).filter(([flag]) => args.includes(flag)).map(([, key]) => key);@@ -5373,7 +5379,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, explicitProcessing, includeGitignored, workingTree, sourceId,+ repoPath, dryRun, full, noPull, noEmbed, noExtract, skipFailed, retryFailed, resetCheckpoint, 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 5ea14b0d93..bc6276b10c 100644--- a/src/commands/upgrade.ts+++ b/src/commands/upgrade.ts@@ -644,7 +644,6 @@ export async function runPostUpgrade(args: string[] = []): Promise<void> {// A managed brain refuses the markdown reindex; name its drain instead.try {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');@@ -657,13 +656,21 @@ export async function runPostUpgrade(args: string[] = []): Promise<void> {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}`);console.warn('Run `gbrain reindex --markdown` manually when ready.');}++ // Fix wave 3: run the wave checks once (full, not --fast) and relay a+ // preview-only recovery banner; applying stays the user's decision.+ try {+ const { postUpgradeRecoveryBanner } = await import('./doctor/upgrade-banner.ts');+ const [brain] = await engine.executeRaw<{ brain_id: string }>('SELECT brain_id FROM persistence_brain WHERE singleton=1').catch(() => []);+ for (const line of await postUpgradeRecoveryBanner(engine, `host (${engine.kind}${brain ? `, id ${brain.brain_id}` : ''})`)) console.log(line);+ } catch (be) {+ console.warn(`\nRecovery checks skipped: ${be instanceof Error ? be.message : String(be)}. Run \`gbrain doctor --remediation-plan\` to preview.`);+ }} finally {try { await engine.disconnect(); } catch { /* best-effort */ }}diff --git a/src/core/ai/chat-usage.ts b/src/core/ai/chat-usage.tsindex c3399b4e68..12f8028808 100644--- a/src/core/ai/chat-usage.ts+++ b/src/core/ai/chat-usage.ts@@ -60,6 +60,15 @@ export function currentChatPhase(): string | null {return __chatPhaseStore.getStore() ?? null;}+/** Successful chat calls counted for one cycle phase (phase containment, dream_paid_loop). */+export interface ChatCallMeter { calls: number }+const __chatMeterStore = new AsyncLocalStorage<ChatCallMeter>();++/** Run `fn` counting every successful gateway.chat() inside it on `meter`. */+export function withChatCallMeter<T>(meter: ChatCallMeter, fn: () => T): T {+ return __chatMeterStore.run(meter, fn);+}+/*** #4480: sink REGISTRY (stack), not a last-wins scalar. A multi-engine* process (migrate-engine source+target, doctor probes, tests) used to lose@@ -131,6 +140,8 @@ export function recordChatUsage(input: {cache_write_tokens?: number;};}): void {+ const meter = __chatMeterStore.getStore();+ if (meter) meter.calls++;const sink = _sinks.length > 0 ? _sinks[_sinks.length - 1]!.sink : null;if (!sink) return;try {diff --git a/src/core/ai/embed-batch-plan.ts b/src/core/ai/embed-batch-plan.tsnew file mode 100644index 0000000000..2fdca2efbc--- /dev/null+++ b/src/core/ai/embed-batch-plan.ts@@ -0,0 +1,138 @@+/**+ * The embedding request plan shared by `embed()` and every caller that must+ * predict it before spending (#5680: the migration worst-case authorization).+ * One home for per-input truncation, the token-budget pre-split, the hard item+ * cap, and the per-request input ceiling a guard reserves before dispatch.+ */+import type { Recipe } from './types.ts';+import { resolveRecipe } from './model-resolver.ts';+import { truncateUtf8 } from '../text-safe.ts';+import { sendableEmbeddingInputs } from './embedding-guard.ts';++/** Per-input character cap applied before any embedding request. */+export const EMBED_MAX_CHARS = 8000;+/** Default chars-per-token when a recipe omits it. Matches OpenAI tiktoken on English. */+export const DEFAULT_CHARS_PER_TOKEN = 4;+/** Default safety factor when a recipe omits it. */+export const DEFAULT_SAFETY_FACTOR = 0.8;++/**+ * #3875: default per-call item cap for `no_batch_cap` recipes (Ollama,+ * LiteLLM proxy). These recipes declare no static token/item cap because the+ * backend's capacity is user-launched — but the per-SDK-call+ * AI_EMBED_TIMEOUT_MS (60s default) then bounded a whole FILE's chunks in one+ * request. A slow local model (CPU Ollama) embedding a large file timed out+ * deterministically and every retry re-sent the same oversized batch. Capping+ * items per sub-batch makes the 60s timeout a per-BATCH budget: 16 chunks per+ * call finishes comfortably even on CPU-bound local models, and a genuinely+ * wedged provider still surfaces the timeout loudly on the first sub-batch.+ * An explicit `max_batch_items` on the recipe always wins over this default.+ *+ * @internal exported for tests; not part of the public gateway API.+ */+export const NO_BATCH_CAP_SUB_BATCH_ITEMS = 16;++export function truncateEmbedInputs(texts: ReadonlyArray<string | null | undefined>): string[] {+ return texts.map(t => truncateUtf8(t ?? '', EMBED_MAX_CHARS));+}++/**+ * Split texts into sub-batches that stay under the provided budget. Pure;+ * no module state. Exported for the adaptive-embed-batch test suite.+ *+ * @param texts - The texts to partition. Each text counts as+ * `Math.ceil(text.length / charsPerToken)` tokens for budget purposes.+ * @param budgetTokens - The token ceiling for each sub-batch. Caller is+ * responsible for applying any safety-factor shrink before passing in.+ * @param charsPerToken - Provider-specific character density. Defaults to+ * `DEFAULT_CHARS_PER_TOKEN` (4) when omitted, matching OpenAI tiktoken.+ *+ * @internal exported for tests; not part of the public gateway API.+ */+export function splitByTokenBudget(+ texts: string[],+ budgetTokens: number,+ charsPerToken: number = DEFAULT_CHARS_PER_TOKEN,+): string[][] {+ const ratio = charsPerToken > 0 ? charsPerToken : DEFAULT_CHARS_PER_TOKEN;+ const batches: string[][] = [];+ let current: string[] = [];+ let currentTokens = 0;++ for (const text of texts) {+ const estTokens = Math.ceil(text.length / ratio);+ if (current.length > 0 && currentTokens + estTokens > budgetTokens) {+ batches.push(current);+ current = [];+ currentTokens = 0;+ }+ current.push(text);+ currentTokens += estTokens;+ }+ if (current.length > 0) batches.push(current);++ return batches;+}++/**+ * Split a batch into sub-batches of at most `maxItems` inputs. Enforces a+ * hard COUNT cap that the token-budget split can't (many tiny inputs fit+ * under any token budget). Used for endpoints like llama.cpp's llama-server+ * that reject requests exceeding their launch batch size.+ *+ * @internal exported for tests; not part of the public gateway API.+ */+export function capBatchItems(texts: string[], maxItems: number): string[][] {+ if (maxItems <= 0 || texts.length <= maxItems) return [texts];+ const batches: string[][] = [];+ for (let i = 0; i < texts.length; i += maxItems) {+ batches.push(texts.slice(i, i + maxItems));+ }+ return batches;+}++/**+ * The provider requests `embed()` dispatches for already-truncated texts.+ * Pre-split is gated on `max_batch_tokens` (or the operator's+ * GBRAIN_EMBED_MAX_BATCH_TOKENS cap, #3622, for recipes that ship without+ * one); recipes without either ride one request. The hard COUNT cap+ * (e.g. llama-server's 32) then re-splits any oversized batch, and+ * `no_batch_cap` recipes default to NO_BATCH_CAP_SUB_BATCH_ITEMS (#3875).+ */+export function planEmbedRequests(texts: string[], recipe: Recipe, safetyFactor: number, envMaxBatchTokens?: number): string[][] {+ const embedding = recipe.touchpoints?.embedding;+ const maxBatchTokens = embedding?.max_batch_tokens ?? envMaxBatchTokens;+ const tokenBatches = maxBatchTokens+ ? splitByTokenBudget(texts, Math.floor(maxBatchTokens * safetyFactor), embedding?.chars_per_token ?? DEFAULT_CHARS_PER_TOKEN)+ : [texts];+ const maxBatchItems = embedding?.max_batch_items ?? (embedding?.no_batch_cap === true ? NO_BATCH_CAP_SUB_BATCH_ITEMS : undefined);+ return maxBatchItems ? tokenBatches.flatMap(b => capBatchItems(b, maxBatchItems)) : tokenBatches;+}++/**+ * #5680: the most input tokens one request can bill. Every token covers at+ * least one UTF-8 byte of its input, and a declared per-input limit caps each+ * text, so the ceiling follows the request's own texts instead of the+ * recipe's whole batch cap. Additive, so it bounds any later split or retry+ * of the same texts.+ */+export function embedRequestMaxInputTokens(texts: string[], recipe: Recipe, modelId: string): number {+ const perInput = recipe.touchpoints?.embedding?.max_input_tokens?.[modelId] ?? Infinity;+ return texts.reduce((sum, text) => sum + Math.min(Math.max(1, Buffer.byteLength(text, 'utf8')), perInput), 0);+}++/** Per-request input ceilings `embed()` would reserve for these texts on `modelStr`, at the declared safety factor (empty inputs are never sent, #4616). */+export function embedRequestCeilings(texts: ReadonlyArray<string>, modelStr: string, envMaxBatchTokens?: number): number[] {+ const { parsed, recipe } = resolveRecipe(modelStr);+ const safety = recipe.touchpoints?.embedding?.safety_factor ?? DEFAULT_SAFETY_FACTOR;+ const truncated = truncateEmbedInputs(texts);+ const sent = sendableEmbeddingInputs(truncated);+ if (!sent.length) return [];+ return planEmbedRequests(sent.map(i => truncated[i]!), recipe, safety, envMaxBatchTokens)+ .map(batch => embedRequestMaxInputTokens(batch, recipe, parsed.modelId));+}++/** The most input tokens one rerank request can bill: the query is sent beside every document. */+export function rerankRequestMaxInputTokens(query: string, documents: ReadonlyArray<string>): number {+ return documents.reduce((sum, document) => sum + Buffer.byteLength(query, 'utf8') + Buffer.byteLength(document, 'utf8'), 0);+}diff --git a/src/core/ai/embedding-guard.ts b/src/core/ai/embedding-guard.tsnew file mode 100644index 0000000000..f1379fdedd--- /dev/null+++ b/src/core/ai/embedding-guard.ts@@ -0,0 +1,107 @@+/**+ * #4616: the embedding gateway never hands back a vector that an ANN index+ * cannot serve. A zero-norm, NaN or ±Inf vector has no cosine direction, so+ * HNSW silently skips its row: `gbrain get` and keyword search find the chunk+ * while vector search never returns it. Empty inputs are refused before the+ * provider call.+ *+ * The refusal is terminal per item: the other inputs of the same call keep+ * their (already paid) vectors, carried on the error aligned with the input,+ * so a caller that can store a partial result stores it and leaves only the+ * degenerate chunks unembedded. A caller that cannot simply fails the call,+ * and nothing degenerate is ever written.+ */+import { AIConfigError } from './errors.ts';++export const EMBEDDING_ZERO_NORM = 'embedding_zero_norm';+export const EMBEDDING_ZERO_NORM_DOCS = 'docs/guides/write-refusals.md#embedding_zero_norm';+/** Real embeddings have norms near 1; below this the direction is noise. */+export const EMBEDDING_NORM_EPSILON = 1e-6;++export type DegenerateEmbeddingReason = 'empty_input' | 'zero_norm' | 'non_finite';++export function degenerateEmbeddingReason(vector: ArrayLike<number>): DegenerateEmbeddingReason | null {+ let sum = 0;+ for (let i = 0; i < vector.length; i++) {+ const value = vector[i]!;+ if (!Number.isFinite(value)) return 'non_finite';+ sum += value * value;+ }+ return Math.sqrt(sum) < EMBEDDING_NORM_EPSILON ? 'zero_norm' : null;+}++export class EmbeddingZeroNormError extends AIConfigError {+ readonly code = EMBEDDING_ZERO_NORM;+ readonly docs = EMBEDDING_ZERO_NORM_DOCS;++ constructor(+ readonly failures: { index: number; reason: DegenerateEmbeddingReason }[],+ readonly vectors: (Float32Array | null)[],+ readonly model: string,+ ) {+ const reasons = [...new Set(failures.map(f => f.reason))].join(', ');+ super(+ `${EMBEDDING_ZERO_NORM}: the embedding provider ${model} gave no usable vector for ${failures.length === 1 ? 'one input' : 'some inputs'} (${reasons}); ` ++ `those inputs were not indexed and the rest of the batch was kept.`,+ 'Inspect the affected chunk text (empty, whitespace- or symbol-only chunks are the usual cause) or the provider, then re-embed the page with `gbrain embed <slug>`.',+ );+ this.name = 'EmbeddingZeroNormError';+ }++ /** The recovery command filled with the page the failed chunks belong to. */+ suggestionFor(slug: string, sourceId?: string): string {+ const source = sourceId && sourceId !== 'default' ? ` --source ${sourceId}` : '';+ return `Inspect the chunk text of ${slug} (empty, whitespace- or symbol-only chunks are the usual cause) or the embedding provider, ` ++ `then run \`gbrain embed ${slug}${source}\`. See ${EMBEDDING_ZERO_NORM_DOCS}.`;+ }+}++export function isEmbeddingZeroNormError(error: unknown): error is EmbeddingZeroNormError {+ return error instanceof EmbeddingZeroNormError;+}++/**+ * Merge per-slice refusals of one logical call into a single error whose+ * vectors and indices are aligned with the caller's full input.+ */+export function mergeZeroNormErrors(total: number, slices: { offset: number; vectors: Float32Array[] | null; error?: EmbeddingZeroNormError }[],+ model: string): EmbeddingZeroNormError | null {+ if (!slices.some(s => s.error)) return null;+ const vectors: (Float32Array | null)[] = new Array(total).fill(null);+ const failures: EmbeddingZeroNormError['failures'] = [];+ for (const slice of slices) {+ const source = slice.error?.vectors ?? slice.vectors ?? [];+ source.forEach((v, i) => { vectors[slice.offset + i] = v; });+ for (const f of slice.error?.failures ?? []) failures.push({ index: slice.offset + f.index, reason: f.reason });+ }+ return new EmbeddingZeroNormError(failures, vectors, model);+}++/** Indexes of inputs worth sending: empty and whitespace-only inputs never reach the provider. */+export function sendableEmbeddingInputs(texts: string[]): number[] {+ return texts.flatMap((text, i) => (text.trim() ? [i] : []));+}++/**+ * Place the provider's vectors (one per sent input) back at their input+ * positions and refuse every empty or degenerate item. Returns the full+ * aligned result when every item is usable.+ */+export function screenEmbeddings(texts: string[], sent: number[], vectors: Float32Array[], model: string): Float32Array[] {+ const out: (Float32Array | null)[] = new Array(texts.length).fill(null);+ sent.forEach((index, j) => { out[index] = vectors[j] ?? null; });+ return screenAlignedEmbeddings(out, model);+}++/** Refuse every missing (empty input) or degenerate vector of an input-aligned result. */+export function screenAlignedEmbeddings(out: (Float32Array | null)[], model: string): Float32Array[] {+ const failures: EmbeddingZeroNormError['failures'] = [];+ out.forEach((vector, index) => {+ const reason = vector ? degenerateEmbeddingReason(vector) : 'empty_input';+ if (!reason) return;+ failures.push({ index, reason });+ out[index] = null;+ });+ if (failures.length) throw new EmbeddingZeroNormError(failures, out, model);+ return out as Float32Array[];+}diff --git a/src/core/ai/gateway.ts b/src/core/ai/gateway.tsindex 7dbb6a5e09..a382c925c1 100644--- a/src/core/ai/gateway.ts+++ b/src/core/ai/gateway.ts@@ -31,7 +31,8 @@ import { createAnthropic } from '@ai-sdk/anthropic';import { createOpenAICompatible } from '@ai-sdk/openai-compatible';import { z } from 'zod';-import { truncateUtf8 } from '../text-safe.ts';+import { DEFAULT_CHARS_PER_TOKEN, DEFAULT_SAFETY_FACTOR, embedRequestMaxInputTokens, planEmbedRequests, rerankRequestMaxInputTokens, truncateEmbedInputs } from './embed-batch-plan.ts';+export { splitByTokenBudget, capBatchItems, NO_BATCH_CAP_SUB_BATCH_ITEMS } from './embed-batch-plan.ts';import { BudgetTracker, type BudgetKind } from '../budget/budget-tracker.ts';import { failedCallUsage, recordOnTracker } from './budget-record.ts';import type {@@ -57,6 +58,7 @@ import type { BrainEngine } from '../engine.ts';import { dimsProviderOptions } from './dims.ts';import { hasAnthropicKey, stashGatewayAnthropicKeyFromEnv } from './anthropic-key.ts';import { AIConfigError, AITransientError, isStructuredOutputRejection, normalizeAIError } from './errors.ts';+import { isEmbeddingZeroNormError, screenAlignedEmbeddings, screenEmbeddings, sendableEmbeddingInputs } from './embedding-guard.ts';import { getProviderCapabilities } from './capabilities.ts';import { runGuardrails, hasGuardrails, type GuardrailHook } from '../guardrails.ts';import { loadConfig } from '../config.ts';@@ -103,7 +105,6 @@ function withDefaultTimeout(caller: AbortSignal | undefined, timeoutMs: number):return caller ? AbortSignal.any([caller, timeout]) : timeout;}-const MAX_CHARS = 8000;export { DEFAULT_EMBEDDING_MODEL, DEFAULT_EMBEDDING_DIMENSIONS } from './defaults.ts';import {DEFAULT_EMBEDDING_MODEL,@@ -197,10 +198,6 @@ const _shrinkState = new Map<string, ShrinkEntry>();const SHRINK_FLOOR = 0.05;/** Successful batches needed before the factor heals back toward recipe default. */const SHRINK_HEAL_AFTER = 10;-/** Default chars-per-token when a recipe omits it. Matches OpenAI tiktoken on English. */-const DEFAULT_CHARS_PER_TOKEN = 4;-/** Default safety factor when a recipe omits it. */-const DEFAULT_SAFETY_FACTOR = 0.8;/*** v0.31.8 (D2 + D10): hard ceiling on Voyage response size, sized as@@ -1461,30 +1458,14 @@ function instantiateEmbedding(recipe: Recipe, modelId: string, cfg: AIGatewayConconst MIN_SUB_BATCH = 1;/**- * #3875: default per-call item cap for `no_batch_cap` recipes (Ollama,- * LiteLLM proxy). These recipes declare no static token/item cap because the- * backend's capacity is user-launched — but the per-SDK-call- * AI_EMBED_TIMEOUT_MS (60s default) then bounded a whole FILE's chunks in one- * request. A slow local model (CPU Ollama) embedding a large file timed out- * deterministically and every retry re-sent the same oversized batch. Capping- * items per sub-batch makes the 60s timeout a per-BATCH budget: 16 chunks per- * call finishes comfortably even on CPU-bound local models, and a genuinely- * wedged provider still surfaces the timeout loudly on the first sub-batch.- * An explicit `max_batch_items` on the recipe always wins over this default.- *- * @internal exported for tests; not part of the public gateway API.- */-export const NO_BATCH_CAP_SUB_BATCH_ITEMS = 16;--/**- * Embed many texts. Truncates to MAX_CHARS, then dispatches based on whether+ * Embed many texts. Truncates to EMBED_MAX_CHARS, then dispatches based on whether* the recipe declares a per-batch token budget.** Flow:* ```* embed(texts)* ├─ resolve recipe + model- * ├─ truncate each text to MAX_CHARS (8000)+ * ├─ truncate each text to EMBED_MAX_CHARS (8000)* ├─ read recipe.touchpoints.embedding.{max_batch_tokens, chars_per_token, safety_factor}* │* ├─ if max_batch_tokens declared (Voyage path):@@ -1564,7 +1545,7 @@ export async function embed(texts: string[], opts?: EmbedOpts): Promise<Float32Aconst resolveTarget = opts?.embeddingModel ?? getEmbeddingModel();const tracker = __budgetStore.getStore() ?? null;const { model, recipe, modelId } = await resolveEmbeddingProvider(resolveTarget);- const truncated = texts.map(t => truncateUtf8(t ?? '', MAX_CHARS));+ const truncated = truncateEmbedInputs(texts);// Reserve up front for the worst-case batch token count. Embeddings have// no output rate, so maxOutputTokens=0. record() at the end uses the@@ -1594,43 +1575,14 @@ export async function embed(texts: string[], opts?: EmbedOpts): Promise<Float32A);const expected = effectiveDims;- const embedding = recipe.touchpoints?.embedding;// GBRAIN_EMBED_MAX_BATCH_TOKENS (#3622): operator-declared cap for recipes- // that ship without one (ollama/llama-server/litellm declare no_batch_cap- // because real capacity depends on the operator's local server). Without- // any cap, a page's entire chunk set goes out as ONE request — on a serial- // local server that can outlive the embed timeout and starve the queue.- // Recipe-declared caps always win; invalid values are ignored. Read from- // the configure-time env snapshot (Codex C3), never process.env at call- // time — buildGatewayConfig folds the operator's process env into it.+ // that ship without one. Read from the configure-time env snapshot (Codex+ // C3), never process.env at call time; invalid values are ignored.const envCapRaw = parseInt(cfg.env?.GBRAIN_EMBED_MAX_BATCH_TOKENS ?? '', 10);const envCap = Number.isFinite(envCapRaw) && envCapRaw > 0 ? envCapRaw : undefined;- const maxBatchTokens = embedding?.max_batch_tokens ?? envCap;- const charsPerToken = embedding?.chars_per_token ?? DEFAULT_CHARS_PER_TOKEN;-- // Pre-split is gated on max_batch_tokens. Recipes without it (e.g. OpenAI)- // ride the fast path: one embedMany call, no recursion safety net.- const tokenBatches = maxBatchTokens- ? splitByTokenBudget(truncated, Math.floor(maxBatchTokens * effectiveSafetyFactor(recipe)), charsPerToken)- : [truncated];-- // Hard COUNT cap (e.g. llama-server's "maximum allowed batch size 32").- // Token budget can't bound item count, so re-split any oversized batch.- //- // #3875: recipes that declare `no_batch_cap` (Ollama, LiteLLM proxy) have- // NO static token cap AND no item cap, so a large file used to ride to the- // provider as ONE request — and the 60s AI_EMBED_TIMEOUT_MS (per SDK call)- // became a per-FILE budget. A slow local model embedding hundreds of chunks- // hit the timeout deterministically, and no amount of retrying could ever- // succeed. Default those recipes to a conservative item cap so the per-call- // timeout bounds a fixed amount of work; an explicit max_batch_items still- // wins.- const maxBatchItems =- embedding?.max_batch_items ??- (embedding?.no_batch_cap === true ? NO_BATCH_CAP_SUB_BATCH_ITEMS : undefined);- const batches = maxBatchItems- ? tokenBatches.flatMap(b => capBatchItems(b, maxBatchItems))- : tokenBatches;+ // #4616: empty inputs never reach the provider; screenEmbeddings refuses them per item.+ const sent = sendableEmbeddingInputs(truncated);+ const batches = sent.length ? planEmbedRequests(sent.map(i => truncated[i]!), recipe, effectiveSafetyFactor(recipe), envCap) : [];const allEmbeddings: Float32Array[] = [];let _embedThrew = false;@@ -1639,7 +1591,7 @@ export async function embed(texts: string[], opts?: EmbedOpts): Promise<Float32Aconst result = await embedSubBatch(batch, model, providerOpts, expected, recipe, modelId, opts);allEmbeddings.push(...result);}- return allEmbeddings;+ return screenEmbeddings(truncated, sent, allEmbeddings, `${recipe.id}:${modelId}`);} catch (err) {_embedThrew = true;throw err;@@ -1666,61 +1618,6 @@ export async function embed(texts: string[], opts?: EmbedOpts): Promise<Float32A}}-/**- * Split texts into sub-batches that stay under the provided budget. Pure;- * no module state. Exported for the adaptive-embed-batch test suite.- *- * @param texts - The texts to partition. Each text counts as- * `Math.ceil(text.length / charsPerToken)` tokens for budget purposes.- * @param budgetTokens - The token ceiling for each sub-batch. Caller is- * responsible for applying any safety-factor shrink before passing in.- * @param charsPerToken - Provider-specific character density. Defaults to- * `DEFAULT_CHARS_PER_TOKEN` (4) when omitted, matching OpenAI tiktoken.- *- * @internal exported for tests; not part of the public gateway API.- */-export function splitByTokenBudget(- texts: string[],- budgetTokens: number,- charsPerToken: number = DEFAULT_CHARS_PER_TOKEN,-): string[][] {- const ratio = charsPerToken > 0 ? charsPerToken : DEFAULT_CHARS_PER_TOKEN;- const batches: string[][] = [];- let current: string[] = [];- let currentTokens = 0;-- for (const text of texts) {- const estTokens = Math.ceil(text.length / ratio);- if (current.length > 0 && currentTokens + estTokens > budgetTokens) {- batches.push(current);- current = [];- currentTokens = 0;- }- current.push(text);- currentTokens += estTokens;- }- if (current.length > 0) batches.push(current);-- return batches;-}--/**- * Split a batch into sub-batches of at most `maxItems` inputs. Enforces a- * hard COUNT cap that the token-budget split can't (many tiny inputs fit- * under any token budget). Used for endpoints like llama.cpp's llama-server- * that reject requests exceeding their launch batch size.- *- * @internal exported for tests; not part of the public gateway API.- */-export function capBatchItems(texts: string[], maxItems: number): string[][] {- if (maxItems <= 0 || texts.length <= maxItems) return [texts];- const batches: string[][] = [];- for (let i = 0; i < texts.length; i += maxItems) {- batches.push(texts.slice(i, i + maxItems));- }- return batches;-}-/*** Returns true if the error looks like a provider batch-token-limit error.*@@ -1801,10 +1698,7 @@ async function embedSubBatch(): Promise<Float32Array[]> {try {const callTransport = () => invokeAI({ operation: 'gateway.embed', kind: 'embedding', model: `${recipe.id}:${modelId}`,- maxInputTokens: recipe.touchpoints.embedding?.max_batch_tokens- ?? (recipe.touchpoints.embedding?.max_input_tokens?.[modelId] !== undefined- ? recipe.touchpoints.embedding.max_input_tokens[modelId]! * texts.length : undefined),- maxOutputTokens: 0 }, () => _embedTransport({+ maxInputTokens: embedRequestMaxInputTokens(texts, recipe, modelId), maxOutputTokens: 0 }, () => _embedTransport({model,values: texts,providerOptions: providerOpts,@@ -1814,7 +1708,7 @@ async function embedSubBatch(// deadline) — shorter wins.abortSignal: withDefaultTimeout(opts?.abortSignal, AI_EMBED_TIMEOUT_MS),...(hasAIInvocationGuard() ? { maxRetries: 0 } : opts?.maxRetries !== undefined ? { maxRetries: opts.maxRetries } : {}),- }), sdkInvocationUsage);+ }), sdkInvocationUsage, err => isTokenLimitError(err) ? { inputTokens: 0, outputTokens: 0 } : null);// Carry the threaded input_type across the SDK boundary via// __embedInputTypeStore (the adapter strips it from providerOptions —// see the store's doc comment). Populated only when dimsProviderOptions@@ -2057,7 +1951,7 @@ export async function embedMultimodal(}}- return allEmbeddings;+ return screenAlignedEmbeddings(allEmbeddings, `${recipe.id}:${parsed.modelId}`);}// Documentation pointer: callers must size-check before calling. Voyage caps@@ -2218,7 +2112,7 @@ async function embedMultimodalOpenAICompat(allEmbeddings.push(new Float32Array(row.embedding));}- return allEmbeddings;+ return screenAlignedEmbeddings(allEmbeddings, `${recipe.id}:${modelId}`);}// ---- v0.36 cross-modal wave: query-side multimodal embedding + safe variant ----@@ -2313,6 +2207,10 @@ export async function embedMultimodalSafe(} catch (err) {if (isAIInvocationPolicyError(err)) throw err;lastError = err instanceof Error ? err : new Error(String(err));+ if (isEmbeddingZeroNormError(err)) {+ err.vectors.forEach((v, i) => { if (v) embeddings[startIdx + i] = v; else failedIndices.push(startIdx + i); });+ return;+ }// AIConfigError = permanent misconfig. Retrying smaller won't help.if (lastError instanceof AIConfigError) {for (let i = 0; i < items.length; i++) failedIndices.push(startIdx + i);@@ -4361,8 +4259,7 @@ export async function rerank(input: RerankInput): Promise<RerankResult[]> {};try {const transport: RerankTransport = _rerankTransport ?? ((u, init) => fetch(u, init));- const maxInputTokens = input.documents.reduce((sum, document) =>- sum + Buffer.byteLength(input.query, 'utf8') + Buffer.byteLength(document, 'utf8'), 0);+ const maxInputTokens = rerankRequestMaxInputTokens(input.query, input.documents);const resp = await invokeAI({ operation: 'gateway.rerank', kind: 'rerank', model: modelStr, maxInputTokens }, () => transport(url, {method: 'POST',headers,diff --git a/src/core/ai/invocation-guard.ts b/src/core/ai/invocation-guard.tsindex 2142a74747..e46708344f 100644--- a/src/core/ai/invocation-guard.ts+++ b/src/core/ai/invocation-guard.ts@@ -45,8 +45,13 @@ export function withAIInvocationPreflight<T>(preflight: (call: AIInvocation) =>}export function hasAIInvocationGuard(): boolean { return guards.getStore() !== undefined; }-/** One provider attempt. No guessed usage, no release on an ambiguous failure. */-export async function invokeAI<T>(call: AIInvocation, run: () => Promise<T>, usage: (result: T) => AIInvocationUsage | null | Promise<AIInvocationUsage | null>): Promise<T> {+/**+ * One provider attempt. No guessed usage, no release on an ambiguous failure:+ * a failed attempt settles null (keep the maximum) unless `rejected` proves the+ * provider refused the request unbilled.+ */+export async function invokeAI<T>(call: AIInvocation, run: () => Promise<T>, usage: (result: T) => AIInvocationUsage | null | Promise<AIInvocationUsage | null>,+ rejected?: (error: unknown) => AIInvocationUsage | null): Promise<T> {const guard = guards.getStore();if (!guard) return run();let permit: AIInvocationPermit;@@ -57,7 +62,7 @@ export async function invokeAI<T>(call: AIInvocation, run: () => Promise<T>, usa}let result: T;try { result = await run(); }- catch (error) { await permit.settle(null); throw error; }+ catch (error) { await permit.settle(rejected?.(error) ?? null); throw error; }let measured: AIInvocationUsage | null;try { measured = await usage(result); }catch (error) { await permit.settle(null); throw error; }diff --git a/src/core/autopilot-paths.ts b/src/core/autopilot-paths.tsindex 7c923320d1..035d90c635 100644--- a/src/core/autopilot-paths.ts+++ b/src/core/autopilot-paths.ts@@ -1,7 +1,7 @@/*** Filesystem coordination points for the autopilot daemon.*- * A LEAF module (imports only `path` + `config`) so other commands can read the+ * A LEAF module (imports only node builtins + `config`) so other commands can read the* daemon's state files WITHOUT importing `src/commands/autopilot.ts`.** Why that matters concretely: the CLI flag-registry generator follows a@@ -20,6 +20,7 @@* because that is where the daemon itself writes; a `GBRAIN_HOME` install* otherwise has readers looking in a different directory than the writer.*/+import { existsSync, readFileSync } from 'fs';import { join } from 'path';import { gbrainPath } from './config.ts';@@ -113,3 +114,26 @@ export function markerHolderAlive(body: string): 'alive' | 'dead' | 'unknown' {return (e as NodeJS.ErrnoException)?.code === 'ESRCH' ? 'dead' : 'alive';}}++/**+ * The operator's own pause (the autopilot pause subcommand), kept apart from+ * the migration/restore hold above: installing autopilot and upgrading gbrain+ * clear a leaked migration hold but never this marker, and resuming clears+ * only this marker, never a live migration's hold.+ */+export function autopilotOperatorPauseMarkerPath(): string {+ return join(gbrainPath(), 'autopilot-operator-paused');+}++/** True while either pause marker is present; the daemon and workers do no new work. */+export function autopilotPaused(): boolean {+ return existsSync(autopilotOperatorPauseMarkerPath()) || existsSync(autopilotPausedMarkerPath());+}++/** The recorded reason for the active pause (the operator pause first), or null. */+export function autopilotPauseReason(): string | null {+ for (const path of [autopilotOperatorPauseMarkerPath(), autopilotPausedMarkerPath()]) {+ try { return readFileSync(path, 'utf-8').trim() || 'pause marker present (no reason recorded)'; } catch { /* not present */ }+ }+ return null;+}diff --git a/src/core/bootstrap/verify.ts b/src/core/bootstrap/verify.tsindex 245e45b192..5c8024a758 100644--- a/src/core/bootstrap/verify.ts+++ b/src/core/bootstrap/verify.ts@@ -27,9 +27,11 @@* keeping the last 5 snapshots. `bootstrap status` + doctor read them.*/-import { assertUnmanagedCanonicalWriter } from '../persistence/maintenance.ts';+import { managedPersistenceEnabled } from '../persistence/ownership.ts';+import { submitPageMutation } from '../persistence/page-mutations.ts';+import { withCoordinatedWrite } from '../persistence/context.ts';import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';-import { createHash } from 'node:crypto';+import { createHash, randomUUID } from 'node:crypto';import { execFileSync } from 'node:child_process';import { join } from 'node:path';@@ -177,12 +179,32 @@ deterministic edge to extract.* local caller and the probe is not user content), reconciled probe facts,* and write-through files under brain/. Best-effort, never throws. */async function sweepProbeLeftovers(engine: BrainEngine, ws: string, sourceId: string): Promise<void> {+ await removeProbes(engine, ws, sourceId);+}++/**+ * Hard-delete both probe pages, their files and their fence facts; returns one+ * warning per page that could not be removed. An unmanaged brain uses the+ * engine primitives. A managed brain (#5280) purges each probe through the+ * coordinator (`delete_page --purge`, bound to its revision, which also removes+ * its canonical file) and removes the probe facts in a coordinated transaction.+ */+async function removeProbes(engine: BrainEngine, ws: string, sourceId: string): Promise<string[]> {+ const warnings: string[] = [];+ const managed = await managedPersistenceEnabled(engine);for (const slug of [VERIFY_PROBE_SLUG, VERIFY_PROBE_ENTITY_SLUG]) {try {- await engine.deletePage(slug, { sourceId });- } catch {- /* absent / engine without hard delete — soft path below still applies */+ if (managed) {+ const snapshot = await engine.readPageSnapshot(slug, { sourceId, includeDeleted: true });+ if (snapshot) await submitPageMutation(localCtx(engine, sourceId), { operation: 'delete_page', params: {+ slug, source_id: sourceId, purge: true, expected_revision: snapshot.revision, request_id: randomUUID() } });+ } else {+ await engine.deletePage(slug, { sourceId });+ }+ } catch (e) {+ warnings.push(`${slug}: ${(e as Error).message}`);}+ if (managed) continue;try {rmSync(join(ws, 'brain', `${slug}.md`), { force: true });} catch {@@ -194,13 +216,14 @@ async function sweepProbeLeftovers(engine: BrainEngine, ws: string, sourceId: st// v51 fence column source_markdown_slug), NEVER a `fact LIKE %token%`// substring match — a user fact that merely mentions the token string// must survive verify's cleanup [G13].- await engine.executeRaw(- `DELETE FROM facts WHERE source_id = $1 AND source_markdown_slug IN ($2, $3)`,- [sourceId, VERIFY_PROBE_SLUG, VERIFY_PROBE_ENTITY_SLUG],- );+ const sql = `DELETE FROM facts WHERE source_id = $1 AND source_markdown_slug IN ($2, $3)`;+ const params = [sourceId, VERIFY_PROBE_SLUG, VERIFY_PROBE_ENTITY_SLUG];+ if (managed) await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => tx.executeRaw(sql, params)));+ else await engine.executeRaw(sql, params);} catch {/* facts table may not exist on a pre-migration brain — doctor_green names that */}+ return warnings;}// ---------------------------------------------------------------------------@@ -846,29 +869,7 @@ async function runRoundtrip(// pages until the 72h purge) — using it here left two probe tombstones in// the user's brain after every verify run, visible to include_deleted// readers and pinned as residue by the Postgres e2e cleanup assertion.- const deleteWarnings: string[] = [];- for (const slug of [VERIFY_PROBE_SLUG, VERIFY_PROBE_ENTITY_SLUG]) {- try {- await engine.deletePage(slug, { sourceId });- } catch (e) {- deleteWarnings.push(`${slug}: ${(e as Error).message}`);- }- try {- rmSync(join(ws, 'brain', `${slug}.md`), { force: true });- } catch {- /* best effort */- }- }- try {- // Exact-identity delete (see sweepProbeLeftovers): only facts whose fence- // lives on a probe page, never a token substring match over user facts.- await engine.executeRaw(- `DELETE FROM facts WHERE source_id = $1 AND source_markdown_slug IN ($2, $3)`,- [sourceId, VERIFY_PROBE_SLUG, VERIFY_PROBE_ENTITY_SLUG],- );- } catch {- /* best effort */- }+ const deleteWarnings = await removeProbes(engine, ws, sourceId);if (deleteWarnings.length > 0) {checks.push({ id: 'probe_cleanup', ok: false, warn: true, detail: `probe deletion incomplete: ${deleteWarnings.join('; ')}` });}@@ -1100,7 +1101,6 @@ export async function verifyWorkspace(ws: string,opts: VerifyOpts = {},): Promise<VerifyReport> {- await assertUnmanagedCanonicalWriter(engine, 'bootstrap verify');let sourceId = opts.sourceId ?? 'workspace';const gbrainHomeDir = opts.gbrainHomeDir ?? resolveGbrainHome();const caps = opts.capabilities ?? detectCapabilities();diff --git a/src/core/chronicle/extract-events.ts b/src/core/chronicle/extract-events.tsindex e430b0ef17..9ed25daca1 100644--- a/src/core/chronicle/extract-events.ts+++ b/src/core/chronicle/extract-events.ts@@ -10,6 +10,8 @@// configured it returns zero events (auto-emit is a no-op, never an error).import type { BrainEngine } from '../engine.ts';import { computeContentHash } from '../ingestion/types.ts';+import { maintenancePreflight, publishMaintenancePage } from '../persistence/prepared-maintenance.ts';+import { serializeMarkdown } from '../markdown.ts';export interface ChronicleEventProposal {when: string; // ISO datetime or YYYY-MM-DD@@ -123,6 +125,9 @@ export async function runChronicleExtract(: typeof fm.date === 'string' ? fm.date: null;const attendees = collectAttendees(fm);+ // #5523: a managed brain refuses the legacy putPage/projection writers.+ // Claim maintenance authority before judge spend; null when unmanaged.+ const maintenance = await maintenancePreflight(engine, sourceId);const judge = opts.judge ?? defaultJudge(engine);let result: ChronicleJudgeResult;@@ -157,18 +162,27 @@ export async function runChronicleExtract(const day = isoDay(when, tz);const hash = computeContentHash(`${who.join(',')}|${ev.what}|${opts.slug}`).slice(0, 8);const eventSlug = `life/events/${day}-${hash}`;+ const title = ev.what.slice(0, 120);+ const compiledTruth = `${ev.what} — see [[${opts.slug}]].`;+ const event = { when, who, what: ev.what, where: ev.where ?? null, kind: normalizeKind(ev.kind), depth: opts.slug };+ if (maintenance) {+ // Database-only: life/events/ is derived machine output. event_date feeds+ // the importer's effective_date, matching the legacy column.+ const snapshot = await engine.readPageSnapshot(eventSlug, { sourceId, includeDeleted: true });+ if (snapshot?.page.deleted_at) continue; // an operator deleted this event; never resurrect it+ await publishMaintenancePage(engine, maintenance, eventSlug,+ serializeMarkdown({ event, event_date: when, captured_via: 'life-chronicle:auto' }, compiledTruth, '',+ { type: 'event', title, tags: [] }),+ { expectedRevision: snapshot?.revision ?? null, file: false,+ eventProjection: { depth_slug: opts.slug, date: day, summary: ev.what } });+ written++;+ continue;+ }await engine.putPage(eventSlug, {type: 'event',- title: ev.what.slice(0, 120),- compiled_truth: `${ev.what} — see [[${opts.slug}]].`,- frontmatter: {- type: 'event',- event: {- when, who, what: ev.what, where: ev.where ?? null,- kind: normalizeKind(ev.kind), depth: opts.slug,- },- captured_via: 'life-chronicle:auto',- },+ title,+ compiled_truth: compiledTruth,+ frontmatter: { type: 'event', event, captured_via: 'life-chronicle:auto' },effective_date: safeDate(when),}, { sourceId });await engine.upsertEventProjection({diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 233c0732aa..3f77f8d9c2 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -18,8 +18,8 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'agent': ['--allow-old-serve', '--brain', '--detach', '--fanout-manifest', '--federated-read', '--flags', '--follow', '--harness', '--help', '--http', '--json', '--max-turns', '--mcp-only', '--model', '--no-follow', '--path', '--port', '--preset', '--reissue', '--scopes', '--show-token', '--since', '--source', '--subagent-def', '--surface', '--timeout-ms', '--token-ttl', '--tools', '--url', '--word', '--yes'],'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', '--stale', '--status', '--swap-only', '--target', '--uninstall', '--user', '--version', '--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', '--force', '--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', '--pause', '--phase', '--reason', '--refresh-cache', '--remediation-plan', '--repo', '--resume', '--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'],@@ -32,29 +32,29 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'capture': ['--access', '--asof', '--background', '--bound-slug-prefixes', '--brain', '--date', '--days', '--depth', '--entities', '--expected-revision', '--explain', '--file', '--follow', '--force', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--mcp-only', '--mode', '--multimodal', '--once', '--page', '--path', '--progress-interval', '--progress-json', '--quiet', '--request-id', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--stdin', '--surface', '--timeout', '--trusted-extraction', '--type', '--types', '--url', '--what', '--where', '--who', '--yes'],'check-backlinks': ['--background', '--brain', '--dir', '--dry-run', '--explain', '--follow', '--help', '--json', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout'],'check-resolvable': ['--brain', '--dry-run', '--fix', '--help', '--json', '--skills-dir', '--source', '--strict', '--verbose'],- 'check-update': ['--brain', '--ff-only', '--help', '--json', '--markdown', '--migrate-only', '--no-autopilot-install', '--non-interactive', '--refresh-cache', '--source', '--swap-only', '--version', '--yes'],+ 'check-update': ['--brain', '--ff-only', '--help', '--json', '--markdown', '--migrate-only', '--no-autopilot-install', '--non-interactive', '--refresh-cache', '--remediation-plan', '--source', '--swap-only', '--version', '--yes'],'claw-test': ['--agent', '--brain', '--dir', '--force-retry', '--format', '--help', '--json', '--keep-tempdir', '--list-agents', '--live', '--local', '--locks', '--message', '--no-embed', '--no-embedding', '--output-format', '--pglite', '--progress-json', '--run-id', '--scenario', '--skip-verify', '--source', '--version', '--yes'],'code-callees': ['--all-sources', '--brain', '--force', '--help', '--json', '--lang', '--limit', '--no-embed', '--no-json', '--source'],'code-callers': ['--all-sources', '--brain', '--force', '--help', '--json', '--lang', '--limit', '--no-embed', '--no-json', '--source'],'code-def': ['--all-sources', '--brain', '--force', '--help', '--json', '--lang', '--limit', '--no-embed', '--no-json', '--source'],'code-refs': ['--all-sources', '--brain', '--force', '--help', '--json', '--lang', '--limit', '--no-embed', '--no-json', '--source'],'compile-context': ['--brain', '--budget', '--check', '--help', '--include', '--json', '--out', '--source', '--stdout', '--target'],- 'config': ['--background', '--brain', '--coverage-override', '--db-url', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--help', '--json', '--markdown', '--path', '--pattern', '--pglite', '--progress-interval', '--progress-json', '--quiet', '--raw', '--session', '--source', '--timeout', '--to', '--url', '--yes'],+ 'config': ['--admin-intent', '--background', '--brain', '--coverage-override', '--db-url', '--embedding-dimensions', '--embedding-model', '--expected-state', '--explain', '--follow', '--force', '--help', '--json', '--markdown', '--path', '--pattern', '--pglite', '--progress-interval', '--progress-json', '--quiet', '--raw', '--session', '--source', '--timeout', '--to', '--url', '--yes'],'connect': ['--agent', '--auto', '--bearer-token-env-var', '--bind', '--brain', '--client-id', '--client-secret', '--credentials-file', '--env', '--force', '--grant-types', '--harness', '--header', '--help', '--http', '--install', '--issuer-url', '--json', '--mcp-only', '--mcp-url', '--name', '--oauth', '--oauth-client-id', '--oauth-client-secret', '--public-url', '--pure', '--register', '--remove', '--root', '--scope', '--scopes', '--show-token', '--source', '--status', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--url', '--version', '--yes'],'connectors': ['--all', '--background', '--brain', '--cookie', '--dry-run', '--embed', '--explain', '--follow', '--force', '--full', '--help', '--install', '--json', '--limit', '--no-browser', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--token', '--try-oauth', '--window-days'],'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', '--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', '--exclude-standard', '--explain', '--fast', '--federated-read', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--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', '--log-noop', '--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', '--prune-orphans', '--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'],+ 'doctor': ['--abbrev-ref', '--abort', '--admin-intent', '--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', '--exclude-standard', '--expected-state', '--explain', '--fast', '--federated-read', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--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', '--include-repairs', '--index-audit', '--init', '--install', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--link-source', '--link-type', '--local', '--locks', '--log-noop', '--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', '--preview', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--prune-orphans', '--pure', '--push-only', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--refresh', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--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', '--vectors', '--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', '--images', '--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', '--show-toplevel', '--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'],+ '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', '--vectors', '--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': ['--admin-intent', '--after-slug', '--apply-preview', '--background', '--backup-verified', '--brain', '--break-lock', '--by-mention', '--catch-up', '--checkpoint', '--concurrency', '--confirm', '--db-url', '--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', '--prune-orphans', '--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'],+ 'extract-conversation-facts': ['--admin-intent', '--background', '--brain', '--concurrency', '--confirm-destructive', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--help', '--json', '--limit', '--manifest', '--max-cost', '--max-cost-usd', '--max-runtime', '--no-embedding', '--override-disabled', '--path', '--pglite', '--progress-interval', '--progress-json', '--quiet', '--segment-limit', '--self-transfer', '--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', '--images', '--include-frontmatter', '--include-null-signature', '--infer-dates', '--json', '--kind', '--ner', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--path', '--priority', '--prune-orphans', '--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'],'forget': ['--brain', '--help', '--json', '--reason', '--request-id', '--source'],@@ -68,11 +68,11 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'init': ['--all', '--allow-create-db', '--allow-docker', '--brain', '--break-lock', '--chat-model', '--check', '--content-root', '--db-only', '--dim', '--embedding-dimensions', '--embedding-model', '--entity', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-expand', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--path', '--pglite', '--prefer-postgres', '--probe', '--provenance', '--quiet', '--schema-pack', '--scopes', '--show-toplevel', '--skip-embed-check', '--source', '--stale', '--status', '--supabase', '--surface', '--to', '--touchpoint', '--url', '--version', '--yes'],'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],'integrity': ['--auto', '--backend', '--background', '--brain', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--supabase', '--timeout', '--type', '--url'],- 'jobs': ['--abbrev-ref', '--access', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--cli-path', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--cost-estimate', '--date', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--explain', '--facts', '--file', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--hard-deadline', '--health-interval', '--help', '--http', '--idempotency-key', '--ids', '--image', '--images', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--limit', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--no-worker', '--now', '--older-than', '--once', '--order', '--others', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--phase', '--pid-file', '--priority', '--prune-orphans', '--queue', '--quiet', '--rebuild', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--repo', '--resume', '--retry-failed', '--review-lower', '--segment-limit', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--stats', '--status', '--strategy', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--trusted-extraction', '--type', '--types', '--uninstall', '--url', '--user', '--verbose', '--verify', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],+ 'jobs': ['--abbrev-ref', '--access', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--cli-path', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--cost-estimate', '--date', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--explain', '--facts', '--file', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--hard-deadline', '--health-interval', '--help', '--http', '--idempotency-key', '--ids', '--image', '--images', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--limit', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--no-worker', '--now', '--older-than', '--once', '--order', '--others', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--pause', '--phase', '--pid-file', '--priority', '--prune-orphans', '--queue', '--quiet', '--reason', '--rebuild', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--repo', '--reset-checkpoint', '--resume', '--retry-failed', '--review-lower', '--segment-limit', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--stats', '--status', '--strategy', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--trusted-extraction', '--type', '--types', '--uninstall', '--url', '--user', '--vectors', '--verbose', '--verify', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],'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', '--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', '--prune-orphans', '--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'],+ 'maintain': ['--all', '--apply', '--background', '--brain', '--break-lock', '--by-mention', '--catch-up', '--concurrency', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--explain', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--from-meetings', '--full', '--harness', '--help', '--http', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--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', '--preview', '--probe-pglite', '--prune-orphans', '--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', '--images', '--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'],@@ -81,45 +81,45 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'onboard': ['--access', '--asof', '--auto', '--bound-slug-prefixes', '--brain', '--check', '--date', '--days', '--entities', '--explain', '--file', '--from-pages', '--full', '--help', '--history', '--http', '--image', '--json', '--kind', '--limit', '--max-usd', '--mode', '--multimodal', '--once', '--page', '--params', '--path', '--remediate', '--remediation-plan', '--resume', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--surface', '--target-score', '--trusted-extraction', '--types', '--url', '--yes'],'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', '--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'],+ 'pglite-repair': ['--brain', '--break-lock', '--dry-run', '--help', '--json', '--path', '--source', '--vectors', '--yes'],+ 'post-upgrade': ['--acknowledge-no-backup', '--admin-intent', '--all', '--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', '--pause', '--quiet', '--reason', '--remediation-plan', '--repo', '--require-db', '--resume', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--status', '--swap-only', '--target', '--uninstall', '--user', '--vectors', '--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'],'quarantine': ['--apply', '--brain', '--force', '--force-rechunk', '--help', '--include-flagged', '--json', '--limit', '--no-embed', '--source', '--source-id', '--stale'],'recall': ['--access', '--as-context', '--asof', '--background', '--bound-slug-prefixes', '--brain', '--budget-policy', '--budget-tokens', '--date', '--days', '--entities', '--explain', '--file', '--follow', '--full', '--grep', '--help', '--http', '--image', '--include-expired', '--json', '--kind', '--limit', '--mcp-only', '--mode', '--multimodal', '--once', '--page', '--path', '--pending', '--progress-interval', '--progress-json', '--query', '--quiet', '--reason', '--request-id', '--rollup', '--session', '--session-id', '--since', '--since-last-run', '--slug', '--slugs', '--source', '--source-id', '--stats', '--supersessions', '--surface', '--timeout', '--today', '--trusted-extraction', '--types', '--url', '--watch', '--yes'],'reconcile-links': ['--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout'],- 'reindex': ['--aliases', '--background', '--brain', '--concurrency', '--cost-estimate', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--force-rechunk', '--help', '--json', '--limit', '--markdown', '--multimodal', '--no-embed', '--no-embedding', '--pglite', '--progress-interval', '--progress-json', '--quiet', '--repo', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--type', '--workers', '--yes'],+ 'reindex': ['--aliases', '--background', '--brain', '--concurrency', '--cost-estimate', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--force-rechunk', '--help', '--json', '--limit', '--markdown', '--multimodal', '--no-embed', '--no-embedding', '--pglite', '--progress-interval', '--progress-json', '--quiet', '--repo', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--type', '--vectors', '--workers', '--yes'],'reindex-code': ['--background', '--brain', '--break-lock', '--concurrency', '--db-url', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--help', '--json', '--max-cost', '--max-cost-usd', '--max-runtime', '--no-embed', '--path', '--progress-interval', '--progress-json', '--quiet', '--source', '--status', '--timeout', '--workers', '--yes'],'reindex-frontmatter': ['--brain', '--concurrency', '--dry-run', '--force', '--help', '--json', '--slug-prefix', '--source', '--workers', '--yes'],'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'],+ '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', '--reset-checkpoint', '--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': ['--all', '--apply', '--brain', '--help', '--include-repairs', '--json', '--limit', '--max-cost', '--max-usd', '--no-embed', '--remediate', '--source', '--stale', '--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'],+ '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', '--reset-checkpoint', '--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'],'resolvers': ['--backend', '--brain', '--cost', '--help', '--json', '--source'],'retrieval-upgrade': ['--all', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--max-cost-usd', '--no-embed', '--non-interactive', '--pace', '--pace-max-concurrency', '--priority', '--progress-interval', '--progress-json', '--quiet', '--reranker', '--retarget', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--yes'],'routing-eval': ['--brain', '--help', '--json', '--llm', '--skills-dir', '--source'],'salience': ['--brain', '--days', '--help', '--json', '--kind', '--limit', '--mcp-only', '--slug-prefix', '--source'],'schema': ['--alias', '--apply', '--as-filing-rules', '--brain', '--dims', '--expert', '--expert-routing', '--extractable', '--force', '--help', '--inverse', '--json', '--kind', '--pack', '--page-type', '--prefix', '--primitive', '--schema-pack', '--since', '--source', '--source-id', '--target-type', '--to', '--with-db'],- 'self-upgrade': ['--brain', '--check-only', '--ff-only', '--force', '--help', '--json', '--markdown', '--migrate-only', '--no-autopilot-install', '--non-interactive', '--refresh-cache', '--source', '--swap-only', '--version', '--yes'],+ 'self-upgrade': ['--brain', '--check-only', '--ff-only', '--force', '--help', '--json', '--markdown', '--migrate-only', '--no-autopilot-install', '--non-interactive', '--refresh-cache', '--remediation-plan', '--source', '--swap-only', '--version', '--yes'],'serve': ['--bind', '--brain', '--enable-dcr', '--enable-dcr-insecure', '--help', '--http', '--json', '--log-full-params', '--oauth-request', '--port', '--print-admin-token', '--public-url', '--source', '--source-guard', '--stdio-idle-timeout', '--suppress-bootstrap-token', '--surface', '--token-ttl', '--url', '--yes'],'skillify': ['--brain', '--description', '--dry-run', '--force', '--help', '--json', '--mutating', '--recent', '--skills-dir', '--source', '--strict', '--triggers', '--writes-pages', '--writes-to'],'skillopt': ['--all', '--allow-mutate-bundled', '--background', '--batch-size', '--benchmark', '--bootstrap-from-routing', '--bootstrap-from-skill', '--bootstrap-reviewed', '--bootstrap-tasks', '--brain', '--brain-wide-max-cost-usd', '--dry-run', '--epochs', '--follow', '--force', '--held-out', '--help', '--json', '--judge-model', '--lr', '--lr-schedule', '--max-cost-usd', '--max-runtime-min', '--models-strict', '--no-max-cost', '--no-mutate', '--optimizer-model', '--patch', '--reflect-max-tokens', '--resume', '--rewrite', '--skills-dir', '--source', '--split', '--status', '--target-model', '--target-models'],'skillpack': ['--all', '--apply-clean-hunks', '--author', '--auto', '--brain', '--dest', '--dry-run', '--env', '--exit-code', '--fast', '--fix', '--force-unlock', '--format', '--from', '--full', '--harness', '--help', '--homepage', '--json', '--license', '--list', '--minimal', '--name-only', '--no-cache', '--no-lint', '--note', '--out', '--overwrite-local', '--persona', '--pure', '--push', '--quick', '--quiet', '--refresh', '--repo', '--schema-pack', '--scope', '--short', '--since', '--skill', '--skills', '--skills-dir', '--skip-doctor', '--source', '--strict', '--stub', '--supabase', '--target', '--tier', '--trust', '--url', '--verify', '--workspace', '--yes'],'skillpack-check': ['--background', '--brain', '--explain', '--fast', '--follow', '--help', '--json', '--list', '--progress-interval', '--progress-json', '--quiet', '--source', '--strict', '--timeout', '--yes'],'smoke-test': ['--brain', '--help', '--json', '--source'],- 'sources': ['--abbrev-ref', '--abort', '--access', '--account', '--admin-intent', '--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'],- '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'],+ 'sources': ['--abbrev-ref', '--abort', '--access', '--account', '--admin-intent', '--after', '--all', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--budget-usd-per-day', '--cached', '--calendar-id', '--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', '--reset-checkpoint', '--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'],+ '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', '--reset-checkpoint', '--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', '--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', '--images', '--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', '--prune-orphans', '--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'],+ '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', '--images', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--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', '--preview', '--priority', '--probe-pglite', '--progress-interval', '--progress-json', '--prune-orphans', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--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', '--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'],+ 'upgrade': ['--acknowledge-no-backup', '--admin-intent', '--all', '--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', '--pause', '--quiet', '--reason', '--remediation-plan', '--repo', '--require-db', '--resume', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--status', '--swap-only', '--target', '--uninstall', '--user', '--vectors', '--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/config.ts b/src/core/config.tsindex 46f9c6764e..e1cab36bd8 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -1606,7 +1606,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = ['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',+ 'persistence.receipt_retention_days', 'persistence.unbound_write', // #5254: persistence/unbound-source.ts];/**diff --git a/src/core/contextual-retrieval-service.ts b/src/core/contextual-retrieval-service.tsindex 9a8813dbad..0162bc6fe3 100644--- a/src/core/contextual-retrieval-service.ts+++ b/src/core/contextual-retrieval-service.ts@@ -722,8 +722,11 @@ function readSourceTextWithFallback(page: Page, chunks: ChunkInput[]): string {* the import path (#3885: stored `sources set-cr-mode` must apply on* capture/reindex, not just the Minion backfill) and the conversation-parser* body reader (#3911: relative raw_transcript resolves against the OWNING- * source's local_path). Throws when the source id is unknown.+ * source's local_path). Throws SourceRowNotFoundError when the source id is+ * unknown, so callers can tell a missing row from a failed read.*/+export class SourceRowNotFoundError extends Error {}+export async function loadSourceRow(engine: BrainEngine, sourceId: string): Promise<SourceRow> {const rows = await engine.executeRaw<SourceRow>(`SELECT id, name, local_path, last_commit, last_sync_at, config, created_at,@@ -731,8 +734,9 @@ export async function loadSourceRow(engine: BrainEngine, sourceId: string): PromFROM sources WHERE id = $1`,[sourceId],);- if (rows.length === 0) {- throw new Error(`Source not found: ${sourceId}`);+ // A missing result set (unit-test engine doubles) reads as no row.+ if (!rows?.length) {+ throw new SourceRowNotFoundError(`Source not found: ${sourceId}`);}return rows[0];}diff --git a/src/core/cycle.ts b/src/core/cycle.tsindex 8cf1b797c6..5d6f5a77ab 100644--- a/src/core/cycle.ts+++ b/src/core/cycle.ts@@ -50,6 +50,8 @@ import type { BrainEngine } from './engine.ts';import { createProgress, type ProgressReporter } from './progress.ts';import { getCliOptions, cliOptsToProgressOptions } from './cli-options.ts';import { tryAcquireDbLock, reapDeadHolderLocks, LockStolenError, type DbLockHandle } from './db-lock.ts';+import { timeContainedPhase } from './cycle/phase-containment.ts';+import { isManagedBrain } from './cycle/phase-table.ts';import { assertValidSourceId } from './source-id.ts';import { PHASE_SCOPE, SOURCE_FRESHNESS_PHASES, type PhaseScope } from './cycle/phase-scope.ts';import { assertEmbedNotStalled } from './embed-stall.ts';@@ -1007,12 +1009,6 @@ function makeErrorFromException(e: unknown, fallbackClass = 'InternalError'): Ph};}-async function timePhase<T>(fn: () => Promise<T>): Promise<{ result: T; duration_ms: number }> {- const start = performance.now();- const result = await fn();- return { result, duration_ms: Math.round(performance.now() - start) };-}-async function safeYield(hook?: () => Promise<void>) {if (!hook) return;try {@@ -1053,7 +1049,7 @@ export async function runPhaseLint(brainDir: string, dryRun: boolean, engine?: B// competing module-style engine that nulls the shared db singleton// mid-cycle (which broke every phase after lint with a misleading// "connect() has not been called").- const result = await runLintCore({ target: brainDir, fix: true, dryRun, engine: engine ?? undefined, signal });+ const result = await runLintCore({ target: brainDir, fix: !(engine && await isManagedBrain(engine)), dryRun, engine: engine ?? undefined, signal });const issues = result.total_issues ?? 0;const fixed = result.total_fixed ?? 0;const remaining = Math.max(0, issues - fixed);@@ -1719,12 +1715,12 @@ async function runPhasePurge(engine: BrainEngine, dryRun: boolean): Promise<Phasdetails: { dry_run: true, purged_sources_count: 0, purged_pages_count: 0, purged_orphan_clones_count: 0 },};}- const { purgeExpiredSources } = await import('./destructive-guard.ts');+ const [{ purgeExpiredSources }, { purgeDeletedPagesCoordinated }] = await Promise.all([import('./destructive-guard.ts'), import('./persistence/purge-deleted.ts')]);// gbrain#4115: {purged, blocked} — a RESTRICT-FK-held source (revoked// oauth_client, v64) is reported and skipped instead of aborting the sweep.const purgeResult = await purgeExpiredSources(engine);const purgedSources = purgeResult.purged;- const purgedPages = await engine.purgeDeletedPages(SOFT_DELETE_TTL_HOURS_FOR_PURGE);+ const purgedPages = await purgeDeletedPagesCoordinated(engine, SOFT_DELETE_TTL_HOURS_FOR_PURGE); // #5405: coordinated on managed brainsconst purgedClones = await purgeOrphanClones(SOFT_DELETE_TTL_HOURS_FOR_PURGE);// v0.36+ folded scope item +C: GC stale op_checkpoints rows.// 7-day TTL is deliberately generous; any reasonable long-running op@@ -1769,7 +1765,7 @@ async function runPhasePurge(engine: BrainEngine, dryRun: boolean): Promise<Phas}return {phase: 'purge',- status: 'ok',+ status: purgedPages.error ? 'fail' : 'ok', error: purgedPages.error,duration_ms: 0,summary:`purged ${purgedSources.length} source(s)` +@@ -1782,7 +1778,7 @@ async function runPhasePurge(engine: BrainEngine, dryRun: boolean): Promise<Phasdetails: {purged_sources_count: purgedSources.length,purged_sources_blocked: purgeResult.blocked,- purged_pages_count: purgedPages.count,+ purged_pages_count: purgedPages.count, purged_pages_blocked: purgedPages.blocked, purged_pages_deferred: purgedPages.deferred,purged_orphan_clones_count: purgedClones.count,purged_orphan_clone_names: purgedClones.names,purged_sources: purgedSources,@@ -2115,7 +2111,9 @@ export async function runCycle(// stop the WAIT while the phase unwinds cooperatively; extract_atoms and// synthesize_concepts still can't carry one (W6). Steal-free cycles behave// byte-identically to timePhase.- const racedTimePhase = <T,>(fn: () => Promise<T>) => raceStolen(timePhase(fn));+ // Phase containment (#5484): a failing phase returns a `fail` result so later phases run; abort, lease loss and budget exhaustion still stop the job.+ const timePhase = <T extends PhaseResult,>(fn: () => Promise<T>, phase: CyclePhase) => timeContainedPhase({ engine, sourceId: cycleSourceId ?? 'default', signal: cycleSignal }, phase, fn);+ const racedTimePhase = <T extends PhaseResult,>(fn: () => Promise<T>, phase: CyclePhase) => raceStolen(timePhase(fn, phase));// #1972: reap dead-holder sync/cycle locks at cycle start — before the sync// phase needs them — so a crashed sync's stranded lock self-heals THIS tick@@ -2163,7 +2161,7 @@ export async function runCycle(phaseResults.push(skipNoBrainDir('lint'));} else {progress.start('cycle.lint');- const { result, duration_ms } = await timePhase(() => runPhaseLint(brainDir, dryRun, engine, cycleSignal));+ const { result, duration_ms } = await timePhase(() => runPhaseLint(brainDir, dryRun, engine, cycleSignal), 'lint');result.duration_ms = duration_ms;phaseResults.push(result);progress.finish();@@ -2178,7 +2176,7 @@ export async function runCycle(phaseResults.push(skipNoBrainDir('backlinks'));} else {progress.start('cycle.backlinks');- const { result, duration_ms } = await timePhase(() => runPhaseBacklinks(brainDir, dryRun));+ const { result, duration_ms } = await timePhase(() => runPhaseBacklinks(brainDir, dryRun), 'backlinks');result.duration_ms = duration_ms;phaseResults.push(result);progress.finish();@@ -2218,7 +2216,7 @@ export async function runCycle(// sync checkpoints its progress, holds its own per-source lock (the// successor's sync phase skips with lock-busy), and its stall// watchdog bounds the dangling import. Signal threading lands in W6.- const { result, duration_ms } = await racedTimePhase(() => runPhaseSync(engine, brainDir, dryRun, pull, phases.includes('extract')));+ const { result, duration_ms } = await racedTimePhase(() => runPhaseSync(engine, brainDir, dryRun, pull, phases.includes('extract')), 'sync');result.duration_ms = duration_ms;// Capture changed slugs for incremental extract.syncPagesAffected = (result as SyncPhaseResult).pagesAffected;@@ -2269,7 +2267,7 @@ export async function runCycle(// timeout domain — clamped via the patterns.ts childBudget template).deadlineAtMs: opts.deadlineAtMs ?? null,privateQueueOwnerJobId: opts.privateQueueOwnerJobId ?? null,- }));+ }), 'synthesize');result.duration_ms = duration_ms;phaseResults.push(result);// v0.29: capture synthesize-written slugs so the recompute_emotional_weight@@ -2300,7 +2298,7 @@ export async function runCycle(// If sync didn't run (phases exclude it) or failed, syncPagesAffected// is undefined → extract falls back to full walk (safe default).progress.start('cycle.extract');- const { result, duration_ms } = await timePhase(() => runPhaseExtract(engine, brainDir, dryRun, syncPagesAffected, cycleSignal, cycleSourceId));+ const { result, duration_ms } = await timePhase(() => runPhaseExtract(engine, brainDir, dryRun, syncPagesAffected, cycleSignal, cycleSourceId), 'extract');result.duration_ms = duration_ms;phaseResults.push(result);progress.finish();@@ -2349,7 +2347,7 @@ export async function runCycle(const syncRanButFailed = syncAttempted && syncPagesAffected === undefined;const xfSlugs = syncRanButFailed ? [] : syncPagesAffected;const { result, duration_ms } = await timePhase(() =>- runPhaseExtractFacts(engine, brainDir, xfSourceId, dryRun, xfSlugs, cycleSignal));+ runPhaseExtractFacts(engine, brainDir, xfSourceId, dryRun, xfSlugs, cycleSignal), 'extract_facts');result.duration_ms = duration_ms;phaseResults.push(result);progress.finish();@@ -2416,7 +2414,7 @@ export async function runCycle(// v0.41.19.0 (T4): pass same reporter (not a child — cycle.ts// owns start/finish; phase only ticks).progress,- }));+ }), 'extract_atoms');result.duration_ms = duration_ms;phaseResults.push(result);progress.finish();@@ -2441,7 +2439,7 @@ export async function runCycle(});} else {progress.start('cycle.resolve_symbol_edges');- const { result, duration_ms } = await timePhase(() => runPhaseResolveSymbolEdges(engine, dryRun));+ const { result, duration_ms } = await timePhase(() => runPhaseResolveSymbolEdges(engine, dryRun), 'resolve_symbol_edges');result.duration_ms = duration_ms;phaseResults.push(result);progress.finish();@@ -2488,7 +2486,7 @@ export async function runCycle(sourceId: cycleSourceId,// #4077: same cooperative-cancellation threading as synthesize.signal: cycleSignal,- }));+ }), 'patterns');result.duration_ms = duration_ms;phaseResults.push(result);progress.finish();@@ -2537,7 +2535,7 @@ export async function runCycle(yieldDuringPhase: buildYieldDuringPhase(lock, opts.yieldDuringPhase, onStolen),// v0.41.19.0 (T4): pass same reporter (not a child).progress,- }));+ }), 'synthesize_concepts');result.duration_ms = duration_ms;phaseResults.push(result);progress.finish();@@ -2582,7 +2580,7 @@ export async function runCycle(signal: cycleSignal,yieldDuringPhase: buildYieldDuringPhase(lock, opts.yieldDuringPhase, onStolen),onProgress: () => progress.tick(),- }),+ }), 'recompute_emotional_weight',);result.duration_ms = duration_ms;phaseResults.push(result);@@ -2616,7 +2614,7 @@ export async function runCycle(// always-undefined — hook, so long phases never refreshed).yieldDuringPhase: buildYieldDuringPhase(lock, opts.yieldDuringPhase, onStolen),signal: cycleSignal,- }));+ }), 'consolidate');result.duration_ms = duration_ms;phaseResults.push(result);progress.finish();@@ -2661,7 +2659,7 @@ export async function runCycle(// #4102: `once` bypasses the cycle.propose_takes.enabled off switch// for `gbrain dream --phase propose_takes --once` (same semantics as// conversation_facts_backfill / enrich_thin above).- const { result, duration_ms } = await timePhase(() => runPhaseProposeTakes(calibrationCtx, { dryRun, repoPath: brainDir ?? undefined, deadlineAtMs: opts.deadlineAtMs ?? null, once: opts.onceForPhase === 'propose_takes' }) as Promise<PhaseResult>);+ const { result, duration_ms } = await timePhase(() => runPhaseProposeTakes(calibrationCtx, { dryRun, repoPath: brainDir ?? undefined, deadlineAtMs: opts.deadlineAtMs ?? null, once: opts.onceForPhase === 'propose_takes' }) as Promise<PhaseResult>, 'propose_takes');result.duration_ms = duration_ms;phaseResults.push(result);progress.finish();@@ -2672,7 +2670,7 @@ export async function runCycle(checkAborted(cycleSignal);progress.start('cycle.grade_takes');const { runPhaseGradeTakes } = await import('./cycle/grade-takes.ts');- const { result, duration_ms } = await timePhase(() => runPhaseGradeTakes(calibrationCtx, { dryRun, deadlineAtMs: opts.deadlineAtMs ?? null }) as Promise<PhaseResult>);+ const { result, duration_ms } = await timePhase(() => runPhaseGradeTakes(calibrationCtx, { dryRun, deadlineAtMs: opts.deadlineAtMs ?? null }) as Promise<PhaseResult>, 'grade_takes');result.duration_ms = duration_ms;phaseResults.push(result);progress.finish();@@ -2683,7 +2681,7 @@ export async function runCycle(checkAborted(cycleSignal);progress.start('cycle.calibration_profile');const { runPhaseCalibrationProfile } = await import('./cycle/calibration-profile.ts');- const { result, duration_ms } = await timePhase(() => runPhaseCalibrationProfile(calibrationCtx, { dryRun, deadlineAtMs: opts.deadlineAtMs ?? null }) as Promise<PhaseResult>);+ const { result, duration_ms } = await timePhase(() => runPhaseCalibrationProfile(calibrationCtx, { dryRun, deadlineAtMs: opts.deadlineAtMs ?? null }) as Promise<PhaseResult>, 'calibration_profile');result.duration_ms = duration_ms;phaseResults.push(result);progress.finish();@@ -2740,7 +2738,7 @@ export async function runCycle(summary: r.detail,details: { ...(r.totals ?? {}) },};- });+ }, 'drift');result.duration_ms = duration_ms;phaseResults.push(result);progress.finish();@@ -2773,7 +2771,7 @@ export async function runCycle(dryRun,signal: cycleSignal,once: opts.onceForPhase === 'conversation_facts_backfill',- }),+ }), 'conversation_facts_backfill',);result.duration_ms = duration_ms;phaseResults.push(result);@@ -2805,7 +2803,7 @@ export async function runCycle(dryRun,signal: cycleSignal,once: opts.onceForPhase === 'enrich_thin',- }),+ }), 'enrich_thin',);result.duration_ms = duration_ms;phaseResults.push(result);@@ -2838,7 +2836,7 @@ export async function runCycle(dryRun,once: opts.onceForPhase === 'skillopt',...(cycleSignal ? { signal: cycleSignal } : {}),- }),+ }), 'skillopt',);result.duration_ms = duration_ms;phaseResults.push(result as never);@@ -2860,7 +2858,7 @@ export async function runCycle(});} else {progress.start('cycle.embed');- const { result, duration_ms } = await timePhase(() => runPhaseEmbed(engine, dryRun, cycleSignal));+ const { result, duration_ms } = await timePhase(() => runPhaseEmbed(engine, dryRun, cycleSignal), 'embed');result.duration_ms = duration_ms;phaseResults.push(result);progress.finish();@@ -2881,7 +2879,7 @@ export async function runCycle(});} else {progress.start('cycle.orphans');- const { result, duration_ms } = await timePhase(() => runPhaseOrphans(engine, orphansSourceId));+ const { result, duration_ms } = await timePhase(() => runPhaseOrphans(engine, orphansSourceId), 'orphans');result.duration_ms = duration_ms;phaseResults.push(result);progress.finish();@@ -2918,7 +2916,7 @@ export async function runCycle(summary: r.skipped ? `skipped: ${r.reason ?? 'unknown'}` : `${r.suggestions_emitted} suggestions emitted`,details: { ...r },};- });+ }, 'schema-suggest');result.duration_ms = duration_ms;phaseResults.push(result);} catch (e) {@@ -2951,7 +2949,7 @@ export async function runCycle(});} else {progress.start('cycle.purge');- const { result, duration_ms } = await timePhase(() => runPhasePurge(engine, dryRun));+ const { result, duration_ms } = await timePhase(() => runPhasePurge(engine, dryRun), 'purge');result.duration_ms = duration_ms;phaseResults.push(result);progress.finish();diff --git a/src/core/cycle/concept-publication.ts b/src/core/cycle/concept-publication.tsnew file mode 100644index 0000000000..70d02fdef6--- /dev/null+++ b/src/core/cycle/concept-publication.ts@@ -0,0 +1,135 @@+/**+ * Managed publication of `synthesize_concepts` output (#5484).+ *+ * On a managed brain the phase publishes each concept page through the+ * maintenance coordinator (`publishMaintenancePage`) instead of the legacy+ * `importFromContent` writer, which a managed brain refuses. The caller keeps+ * the #5525 order: publish private, bank provenance edges, then promote.+ */+import type { BrainEngine, LinkBatchInput } from '../engine.ts';+import type { Page } from '../types.ts';+import { serializeMarkdown, parseMarkdown } from '../markdown.ts';+import { FACTS_FENCE_BEGIN, FACTS_FENCE_END, parseFactsFence, replaceOrInsertFactsFence, stripFactsFence } from '../facts-fence.ts';+import { TAKES_FENCE_BEGIN, TAKES_FENCE_END, parseTakesFence, stripTakesFence } from '../takes-fence.ts';+import { isDbOnly, loadStorageConfig } from '../storage-config.ts';+import { publishMaintenancePage, type MaintenanceAuthority } from '../persistence/prepared-maintenance.ts';+import { withCoordinatedWrite } from '../persistence/context.ts';++/** Error code for a concept held because republication could lose canonical material. */+export const CONCEPT_PRESERVATION_CODE = 'concept_preservation_hold';+/** Codes that mean the page moved under a concurrent writer; the next run retries. */+export const CONCEPT_DEFERRAL_CODES = new Set(['revision_conflict', 'page_identity_changed']);+/** Codes that hold a concept until an operator imports or repairs its page. */+export const CONCEPT_HOLD_CODES = new Set(['source_changed', CONCEPT_PRESERVATION_CODE]);++function conceptHoldError(message: string): Error { return Object.assign(new Error(message), { code: CONCEPT_PRESERVATION_CODE }); }++/**+ * Publish one concept page through the maintenance coordinator. A concept+ * keeps the storage shape it already has: a row with a recorded source file is+ * republished to that file (a database-only update would leave the file stale+ * for the next sync to resurrect); new concepts and file-less rows stay+ * database-only, which is what the legacy writer produced. A declared+ * `db_only` storage tier always wins.+ */+export async function publishManagedConcept(engine: BrainEngine, authority: MaintenanceAuthority,+ slug: string, synthesized: Record<string, unknown>, narrative: string, expectedRevision: string | null, brainDir?: string): Promise<string | null> {+ const snapshot = await engine.readPageSnapshot(slug, { sourceId: authority.writer.sourceId, includeDeleted: true });+ // The narrative was synthesized from the revision read before the model call+ // (or the previous publication's result); an intervening edit wins.+ if ((snapshot?.revision ?? null) !== expectedRevision) {+ throw Object.assign(new Error('The concept page changed during synthesis.'), { code: 'revision_conflict' });+ }+ let dbOnly = !snapshot?.page.source_path;+ if (!dbOnly) {+ try {+ const storage = loadStorageConfig(brainDir);+ dbOnly = storage !== null && isDbOnly(slug, storage);+ } catch {+ // Unreadable gbrain.yml: keep the recorded file; sync reports the config.+ }+ }+ const title = slug.split('/').pop()!.replace(/-/g, ' ');+ const markdown = snapshot && !snapshot.page.deleted_at+ ? composeConceptRepublication(snapshot.page, snapshot.tags, synthesized, narrative)+ : serializeMarkdown(synthesized, narrative, '', { type: 'concept', title, tags: [] });+ const receipt = await publishMaintenancePage(engine, authority, slug, markdown,+ { expectedRevision: snapshot?.revision ?? null, file: !dbOnly });+ return typeof receipt.revision === 'string' ? receipt.revision : null;+}++/** Provenance edges inside a coordinated transaction scoped to the concept's source. */+export async function addManagedProvenanceLinks(engine: BrainEngine, sourceId: string, links: LinkBatchInput[]): Promise<number> {+ return engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () =>+ tx.addLinksBatch(links, { auditSite: 'cycle.synthesize_concepts.provenance' }))); // gbrain-allow-direct-insert: concept-provenance edges derived from the synthesis itself, inside the coordinated transaction+}++/**+ * The synthesized narrative is the only part of a concept page this phase+ * owns. Republishing an existing concept keeps everything else the page+ * already carries: its `## Facts` / `## Takes` fences (the system of record+ * for those rows; dropping them would expire every fact and delete every take+ * on publication), its timeline, its tags, and any frontmatter keys the+ * synthesis does not set.+ */+export function composeConceptRepublication(page: Pick<Page, 'type' | 'title' | 'compiled_truth' | 'timeline' | 'frontmatter'>,+ tags: string[], synthesized: Record<string, unknown>, narrative: string): string {+ const compiled = preserveCanonicalFences(page, narrative);+ const { type: _type, title: _title, tags: _tags, ...kept } = (page.frontmatter ?? {}) as Record<string, unknown>;+ return serializeMarkdown({ ...kept, ...synthesized }, compiled, (page.timeline ?? '').trim(),+ { type: page.type ?? 'concept', title: page.title, tags });+}++/**+ * Carry a page's existing `## Facts` / `## Takes` fences into a replacement+ * body written by a model or a synthesis phase, which owns only the prose. Any+ * fence in the replacement is dropped and the original blocks are inserted+ * verbatim, so publication neither expires fence facts nor deletes takes.+ * Throws a hold (`concept_preservation_hold`) when the original fences are+ * ambiguous or the result would not carry exactly the original rows.+ */+export function preserveCanonicalFences(page: Pick<Page, 'compiled_truth' | 'timeline'>, replacement: string): string {+ const hold = conceptPreservationHold(page);+ if (hold) throw conceptHoldError(hold);+ const body = page.compiled_truth ?? '';+ let compiled = stripTakesFence(stripFactsFence(replacement)).trim();+ const facts = fenceBlock(body, FACTS_FENCE_BEGIN, FACTS_FENCE_END);+ if (facts) compiled = replaceOrInsertFactsFence(compiled, facts).trimEnd();+ const takes = fenceBlock(body, TAKES_FENCE_BEGIN, TAKES_FENCE_END);+ if (takes) compiled = `${compiled}\n\n## Takes\n\n${takes}`;+ const out = parseMarkdown(serializeMarkdown({}, compiled, (page.timeline ?? '').trim(), { type: 'note', title: 'x', tags: [] }), 'page');+ if (JSON.stringify(canonicalRows(out.compiled_truth)) !== JSON.stringify(canonicalRows(body))+ || (out.timeline ?? '').trim() !== (page.timeline ?? '').trim()) {+ throw conceptHoldError('CONCEPT_REPUBLICATION_LOSSY: composed page would not preserve the existing fences or timeline');+ }+ return compiled;+}++function canonicalRows(body: string): { facts: unknown[]; takes: unknown[] } {+ return { facts: parseFactsFence(body).facts, takes: parseTakesFence(body).takes };+}++/**+ * Why an existing concept page cannot be republished losslessly, or null.+ * Each fence must occur at most once, be balanced, parse without warnings and+ * sit above the timeline sentinel; anything else holds the concept untouched.+ */+export function conceptPreservationHold(page: Pick<Page, 'compiled_truth' | 'timeline'>): string | null {+ const body = page.compiled_truth ?? '';+ const timeline = page.timeline ?? '';+ for (const [name, begin, end] of [['FACTS', FACTS_FENCE_BEGIN, FACTS_FENCE_END], ['TAKES', TAKES_FENCE_BEGIN, TAKES_FENCE_END]] as const) {+ if (timeline.includes(begin) || timeline.includes(end)) return `CONCEPT_${name}_FENCE_BELOW_SENTINEL: a ${name.toLowerCase()} fence marker sits in the timeline`;+ const begins = body.split(begin).length - 1, ends = body.split(end).length - 1;+ if (begins > 1 || ends > 1) return `CONCEPT_${name}_FENCE_DUPLICATE: more than one ${name.toLowerCase()} fence`;+ if (begins !== ends) return `CONCEPT_${name}_FENCE_UNBALANCED: ${name.toLowerCase()} fence begin/end markers do not pair`;+ }+ const warnings = [...parseFactsFence(body).warnings, ...parseTakesFence(body).warnings];+ return warnings.length ? `CONCEPT_FENCE_UNPARSEABLE: ${warnings[0]}` : null;+}++function fenceBlock(body: string, begin: string, end: string): string | null {+ const start = body.indexOf(begin);+ if (start === -1) return null;+ const stop = body.indexOf(end, start + begin.length);+ return stop === -1 ? null : body.slice(start, stop + end.length);+}diff --git a/src/core/cycle/conversation-facts-backfill.ts b/src/core/cycle/conversation-facts-backfill.tsindex c4d9d22ac2..7765504596 100644--- a/src/core/cycle/conversation-facts-backfill.ts+++ b/src/core/cycle/conversation-facts-backfill.ts@@ -49,7 +49,6 @@ import {loadPricingOverrides,} from '../budget/budget-tracker.ts';import { withBudgetTracker } from '../ai/gateway.ts';-import { assertUnmanagedCanonicalWriter } from '../persistence/maintenance.ts';import { listSources } from '../sources-ops.ts';import {runExtractConversationFactsCore,@@ -191,7 +190,6 @@ export async function runPhaseConversationFactsBackfill();}- await assertUnmanagedCanonicalWriter(engine, 'conversation fact backfill');const startedAt = Date.now();const maxTotalWalltimeMs = cfg.maxTotalWalltimeMin * 60_000;const maxWalltimeMs = cfg.maxWalltimeMin * 60_000;diff --git a/src/core/cycle/dream-breaker.ts b/src/core/cycle/dream-breaker.tsindex 527a28ec97..9588932962 100644--- a/src/core/cycle/dream-breaker.ts+++ b/src/core/cycle/dream-breaker.ts@@ -16,8 +16,12 @@import type { BrainEngine } from '../engine.ts';export const DREAM_BREAKER_KEY_PREFIXES = ['dream:synth-v2:', 'dream:patterns:'] as const;+/** Base-key prefix of a contained cycle-phase failure after paid model calls. */+export const DREAM_PHASE_KEY_PREFIX = 'dream:phase:';export const DREAM_BREAKER_CONFIG_KEY = 'dream.breaker.max_dead_submissions';export const DREAM_BREAKER_RESETS_KEY = 'dream.breaker.resets';+/** Contained paid phase failures: `{ [base key]: ISO finish times }`, pruned to the 24 h window. */+export const DREAM_BREAKER_CONTAINED_KEY = 'dream.breaker.contained_failures';export const DEFAULT_MAX_DEAD_SUBMISSIONS = 3;export interface DeadDreamSubmissions { base_key: string; dead_submissions: number; last_dead_at: string }@@ -56,7 +60,7 @@ async function loadResets(engine: BrainEngine): Promise<Record<string, string>>*/export async function countDeadDreamSubmissions(engine: BrainEngine): Promise<DeadDreamSubmissions[]> {const resets = await loadResets(engine);- return engine.executeRaw<DeadDreamSubmissions>(+ const dead = await 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@@ -71,6 +75,50 @@ export async function countDeadDreamSubmissions(engine: BrainEngine): Promise<DeORDER BY dead_submissions DESC, base_key`,[DREAM_BREAKER_KEY_PREFIXES[0], DREAM_BREAKER_KEY_PREFIXES[1], JSON.stringify(resets)],);+ const cutoff = Date.now() - 24 * 3_600_000;+ for (const [baseKey, times] of Object.entries(await loadContained(engine))) {+ const after = Math.max(cutoff, Date.parse(resets[baseKey] ?? '') || -Infinity);+ const counted = times.filter(at => Date.parse(at) > after).sort();+ if (counted.length) dead.push({ base_key: baseKey, dead_submissions: counted.length, last_dead_at: counted.at(-1)! });+ }+ return dead.sort((a, b) => b.dead_submissions - a.dead_submissions || a.base_key.localeCompare(b.base_key));+}++async function loadContained(engine: BrainEngine): Promise<Record<string, string[]>> {+ const raw = await engine.getConfig(DREAM_BREAKER_CONTAINED_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).flatMap(([key, times]) => Array.isArray(times)+ ? [[key, times.filter((at): at is string => typeof at === 'string' && Number.isFinite(Date.parse(at)))]] : []));+ } catch { return {}; }+}++/**+ * Record a cycle phase whose failure was contained after it made paid model+ * calls (#5484 containment), so doctor's dream_paid_loop sees a phase that+ * keeps paying and failing even though its job no longer dies. The update is+ * serialized on the config row and drops entries older than the window.+ */+export async function recordContainedPaidFailure(engine: BrainEngine, phase: string, sourceId: string): Promise<void> {+ const baseKey = `${DREAM_PHASE_KEY_PREFIX}${phase}:${sourceId}`;+ await engine.transaction(async tx => {+ await tx.executeRaw("INSERT INTO config (key, value) VALUES ($1, '{}') ON CONFLICT (key) DO NOTHING", [DREAM_BREAKER_CONTAINED_KEY]);+ const [row] = await tx.executeRaw<{ value: string; now: string }>(+ `SELECT value, to_char(now() AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') AS now FROM config WHERE key=$1 FOR UPDATE`,+ [DREAM_BREAKER_CONTAINED_KEY]);+ let current: Record<string, unknown> = {};+ try { const parsed = JSON.parse(row?.value ?? '{}'); if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) current = parsed; } catch { /* rewrite a corrupt value */ }+ const cutoff = Date.parse(row!.now) - 24 * 3_600_000;+ const next: Record<string, string[]> = {};+ for (const [key, times] of Object.entries(current)) {+ const kept = Array.isArray(times) ? times.filter((at): at is string => typeof at === 'string' && Date.parse(at) > cutoff) : [];+ if (kept.length) next[key] = kept;+ }+ next[baseKey] = [...next[baseKey] ?? [], row!.now].slice(-50);+ await tx.executeRaw('UPDATE config SET value=$2 WHERE key=$1', [DREAM_BREAKER_CONTAINED_KEY, JSON.stringify(next)]);+ });}export interface DreamBreaker { threshold: number; tripped: Map<string, number> }diff --git a/src/core/cycle/drift.ts b/src/core/cycle/drift.tsindex 16ad8b3649..be4eecd1d7 100644--- a/src/core/cycle/drift.ts+++ b/src/core/cycle/drift.ts@@ -28,6 +28,8 @@ import { resolveSynthMaxOutputTokens } from './synthesize-concepts.ts';import { resolveCycleDate, shiftCalendarDate } from './cycle-date.ts';import { resolveModel } from '../model-config.ts';import type { DreamPhaseResult } from './auto-think.ts';+import { maintenancePreflight, publishMaintenancePage } from '../persistence/prepared-maintenance.ts';+import { serializeMarkdown } from '../markdown.ts';export interface DriftPhaseOpts {brainDir?: string;@@ -310,6 +312,10 @@ export async function runPhaseDrift(};}+ // #5280: a managed brain publishes the report through the maintenance+ // coordinator; the preflight refuses a missing canonical owner before any+ // judge spend. Null on an unmanaged brain.+ const maintenance = await maintenancePreflight(engine, 'default');const modelId = await resolveModel(engine, {configKey: 'models.drift',deprecatedConfigKey: 'dream.drift.model',@@ -358,11 +364,17 @@ export async function runPhaseDrift(// Report-only v1: the report page is the ONLY write this phase makes.// Lands in the default source (brain-global artifact, same-day re-runs// upsert the same slug).- await engine.putPage(reportSlug, {- type: 'report',- title: `Drift report ${cycleDate}`,- compiled_truth: buildReportBody(judged, config, modelId),- });+ if (maintenance) {+ const snapshot = await engine.readPageSnapshot(reportSlug, { sourceId: 'default' });+ await publishMaintenancePage(engine, maintenance, reportSlug, serializeMarkdown({}, buildReportBody(judged, config, modelId), '',+ { type: 'report', title: `Drift report ${cycleDate}`, tags: [] }), { expectedRevision: snapshot?.revision ?? null, file: false });+ } else {+ await engine.putPage(reportSlug, {+ type: 'report',+ title: `Drift report ${cycleDate}`,+ compiled_truth: buildReportBody(judged, config, modelId),+ });+ }}const detail =diff --git a/src/core/cycle/extract-atoms.ts b/src/core/cycle/extract-atoms.tsindex a317a3c2cc..911a1b9743 100644--- a/src/core/cycle/extract-atoms.ts+++ b/src/core/cycle/extract-atoms.ts@@ -83,6 +83,7 @@ import { managedAtomSession, readAtomOrigin, resumeManagedAtoms, publishManagedAimport { effectiveVisibility } from '../search/private-visibility.ts';import { OperationError } from '../ops/contract.ts';import type { WriteReceipt } from '../persistence/types.ts';+import { acceptedPendingReceipt } from '../persistence/accepted-pending.ts';import { AtomPageStateError, completeAtomReceipts, readAtomPageIdentity, writeAtomPageState, type AtomPageInput } from './extract-atoms-page-state.ts';const DEFAULT_BUDGET_USD = 0.3;@@ -991,6 +992,7 @@ export async function runPhaseExtractAtoms(// EXCEPT the ones TRANSIENT_EXTRACT_ERROR_RE + the rate_limit abort class// say are "retryable, never counted" — see that regex's doc comment.let hardFailureCount = 0;+ let writesPending = 0; // #5601: accepted atom batches still publishing (progress, not failures)async function stampAtomsScanHash(item: AtomPageInput): Promise<void> {await writeAtomPageState(engine, sourceId, item, 'complete');@@ -1300,7 +1302,9 @@ export async function runPhaseExtractAtoms(// the deterministic slugs make the retry converge.if (managed && origin) {for (const atom of managedAtoms) atom.links = provenanceLinks.filter(link => link.to_slug === atom.slug);- writeRequests.push(...await publishManagedAtoms(engine, managed, origin, managedAtoms));+ const published = await publishManagedAtoms(engine, managed, origin, managedAtoms);+ writeRequests.push(...published);+ if (published.some(receipt => receipt.state !== 'committed')) writesPending++;totalAtomsExtracted += managedAtoms.length;} else {if (provenanceLinks.length > 0) {@@ -1330,6 +1334,7 @@ export async function runPhaseExtractAtoms(opts.progress?.tick(1, `${totalAtomsExtracted} atoms / ${duplicatesSkipped} skipped`);} catch (err) {if (err instanceof OperationError && err.writeRequest) writeRequests.push(err.writeRequest);+ if (acceptedPendingReceipt(err)) { writesPending++; continue; }if (err instanceof BudgetExhausted) {budgetExhausted = true;if (item.kind === 'transcript') transcriptsSkipped++;@@ -1439,6 +1444,7 @@ export async function runPhaseExtractAtoms(pages_total: pages.length,pages_skipped_budget: pagesSkipped,duplicates_skipped: duplicatesSkipped,+ write_pending: writesPending,failures,...(managed ? { write_requests: writeRequests } : {}),...(abortedGlobalError ? { aborted_global_error: abortedGlobalError } : {}),diff --git a/src/core/cycle/extract-facts.ts b/src/core/cycle/extract-facts.tsindex 347639bee1..30bbb5db75 100644--- a/src/core/cycle/extract-facts.ts+++ b/src/core/cycle/extract-facts.ts@@ -55,7 +55,7 @@import { existsSync, readFileSync } from 'node:fs';import type { BrainEngine } from '../engine.ts';-import { assertUnmanagedCanonicalWriter } from '../persistence/maintenance.ts';+import { managedDerivedFactsPreflight, withDerivedFactsWrite } from '../persistence/derived-facts.ts';import {resolveSupersededByRow,supersessionChainOf,@@ -438,8 +438,12 @@ export async function runExtractFacts(engine: BrainEngine,opts: ExtractFactsOpts = {},): Promise<ExtractFactsResult> {- await assertUnmanagedCanonicalWriter(engine, 'legacy fact-fence reconciliation');const sourceId = opts.sourceId ?? 'default';+ // Managed brains reconcile the same way, but each database write commits+ // inside the coordinator's source capability under the page key.+ const managed = await managedDerivedFactsPreflight(engine, sourceId);+ const transact = <T>(slugs: string[], fn: (tx: BrainEngine) => Promise<T>): Promise<T> =>+ managed ? withDerivedFactsWrite(engine, sourceId, slugs, fn) : engine.transaction(fn);const result: ExtractFactsResult = {pagesScanned: 0,pagesWithFacts: 0,@@ -601,7 +605,7 @@ export async function runExtractFacts(// forgotten claims expired). Rows of a page that simply has no DB row yet// (a fence write ahead of sync) are untouched.if (!opts.dryRun) {- const expired = await engine.executeRaw<{ id: number }>(+ const expireDeleted = (db: BrainEngine) => db.executeRaw<{ id: number }>(`UPDATE facts f SET expired_at = now()WHERE f.source_id = $1 AND f.row_num IS NOT NULL AND f.expired_at IS NULLAND EXISTS (SELECT 1 FROM pages p@@ -610,6 +614,9 @@ export async function runExtractFacts(RETURNING f.id`,[sourceId],);+ // Managed: one page at a time under its key, so a concurrent restore is+ // either seen as restored or waited for, never expired underneath it.+ const expired = managed ? await expireDeletedPagesManaged(engine, sourceId, transact) : await expireDeleted(engine);result.factsExpiredForDeletedPages = expired.length;}@@ -812,7 +819,7 @@ export async function runExtractFacts(const apply = async () => {try {- return await engine.transaction(async tx => {+ return await transact([slug], async tx => {opts.signal?.throwIfAborted();const current = await tx.getPage(slug, { sourceId });if (!current || current.compiled_truth !== page.compiled_truth || current.timeline !== page.timeline) return null;@@ -898,7 +905,8 @@ export async function runExtractFacts(// v0.42 Wave B3: receipt + rollup. extract_facts is deterministic// (fence reconcile, no LLM cost); receipt only when facts were// actually inserted; rollup always fires.- if (!opts.dryRun && result.factsInserted > 0) {+ // Receipt pages are unmanaged-only, like extract_atoms'; the rollup below still books the run.+ if (!opts.dryRun && !managed && result.factsInserted > 0) {const runId = `efacts-${Date.now().toString(36)}-${sourceId.slice(0, 4)}`;try {await writeReceipt(engine, {@@ -931,3 +939,24 @@ export async function runExtractFacts(return result;}++async function expireDeletedPagesManaged(engine: BrainEngine, sourceId: string,+ transact: <T>(slugs: string[], fn: (tx: BrainEngine) => Promise<T>) => Promise<T>): Promise<Array<{ id: number }>> {+ const pages = await engine.executeRaw<{ slug: string }>(+ `SELECT DISTINCT f.source_markdown_slug AS slug FROM facts f+ WHERE f.source_id = $1 AND f.row_num IS NOT NULL AND f.expired_at IS NULL+ AND EXISTS (SELECT 1 FROM pages p WHERE p.source_id = f.source_id AND p.slug = f.source_markdown_slug AND p.deleted_at IS NOT NULL)`,+ [sourceId],+ );+ const expired: Array<{ id: number }> = [];+ for (const { slug } of pages) {+ expired.push(...await transact([slug], tx => tx.executeRaw<{ id: number }>(+ `UPDATE facts f SET expired_at = now()+ WHERE f.source_id = $1 AND f.source_markdown_slug = $2 AND f.row_num IS NOT NULL AND f.expired_at IS NULL+ AND EXISTS (SELECT 1 FROM pages p WHERE p.source_id = $1 AND p.slug = $2 AND p.deleted_at IS NOT NULL)+ RETURNING f.id`,+ [sourceId, slug],+ )));+ }+ return expired;+}diff --git a/src/core/cycle/grade-takes.ts b/src/core/cycle/grade-takes.tsindex 9387ecd94d..0e44d0289d 100644--- a/src/core/cycle/grade-takes.ts+++ b/src/core/cycle/grade-takes.ts@@ -45,6 +45,9 @@ import { GBrainError } from '../types.ts';import type { OperationContext } from '../operations.ts';import type { BrainEngine, Take, TakeResolution } from '../engine.ts';import type { PhaseStatus, CyclePhase } from '../cycle.ts';+import { managedPersistenceEnabled } from '../persistence/ownership.ts';+import { parseTakesFence } from '../takes-fence.ts';+import { submitPageMutation } from '../persistence/page-mutations.ts';/*** Bump when the judge prompt or the JSON output shape changes. Old verdicts@@ -585,6 +588,9 @@ class GradeTakesPhase extends BaseCyclePhase {opts.reporter.start('grade_takes.takes' as never, takes.length);}+ // #5280: a managed brain refuses the raw takes update; resolutions go+ // through the coordinated, markdown-canonical takes_resolve mutation.+ const managed = await managedPersistenceEnabled(engine);const now = new Date();for (const take of takes) {// Phase deadline check (gbrain#4168). Break, not throw: verdicts@@ -781,7 +787,28 @@ class GradeTakesPhase extends BaseCyclePhase {// Apply to canonical takes if eligible.if (shouldApply && resolution) {try {- await engine.resolveTake(take.page_id, take.row_num, resolution);+ if (managed) {+ // Resolve the judged take by page identity, not the cached slug: a+ // rename during judging must not redirect the resolution to another page.+ const [page] = await engine.executeRaw<{ slug: string; source_id: string }>(+ `SELECT p.slug, p.source_id FROM pages p JOIN takes t ON t.page_id=p.id+ WHERE p.id=$1 AND p.deleted_at IS NULL AND t.row_num=$2 AND t.claim=$3`, [take.page_id, take.row_num, take.claim]);+ if (!page) throw new Error('the judged take moved or changed during grading; it is graded again next run');+ const snapshot = await engine.readPageSnapshot(page.slug, { sourceId: page.source_id });+ // The resolution publishes against this exact revision, so the judged+ // claim must be the row this revision's fence holds.+ const fenced = snapshot ? parseTakesFence(snapshot.page.compiled_truth ?? '').takes.find(t => t.rowNum === take.row_num) : undefined;+ if (!snapshot || snapshot.page.id !== take.page_id || fenced?.claim !== take.claim) {+ throw new Error('the judged page changed during grading; it is graded again next run');+ }+ await submitPageMutation({ engine, config: { engine: engine.kind } as never, remote: false, sourceId: page.source_id,+ dryRun: false, logger: { info() {}, warn() {}, error() {} } }, { operation: 'takes_resolve', params: {+ slug: page.slug, source_id: page.source_id, expected_revision: snapshot.revision, row_num: take.row_num, quality: resolution.quality,+ evidence: resolution.source, resolved_by: resolution.resolvedBy,+ request_id: createHash('sha256').update(`grade_takes:${take.id}:${recordedSig}:${snapshot.revision}`).digest('hex').replace(/^(.{8})(.{4}).(.{3}).(.{3})(.{12}).*/, '$1-$2-4$3-a$4-$5') } });+ } else {+ await engine.resolveTake(take.page_id, take.row_num, resolution);+ }result.auto_applied += 1;// T11 / E4 — gstack-learnings coupling on incorrect / partial@@ -814,6 +841,11 @@ class GradeTakesPhase extends BaseCyclePhase {} catch (err) {const msg = err instanceof Error ? err.message : String(err);result.warnings.push(`auto-apply failed on take ${take.id}: ${msg}`);+ // Managed: drop the cached verdict so the next run grades the take+ // again instead of skipping it as already applied.+ if (managed) await engine.executeRaw(`DELETE FROM take_grade_cache+ WHERE take_id=$1 AND prompt_version=$2 AND judge_model_id=$3 AND evidence_signature=$4`,+ [take.id, promptVersion, recordedJudgeModelId, recordedSig]);}}diff --git a/src/core/cycle/phantom-redirect-managed.ts b/src/core/cycle/phantom-redirect-managed.tsnew file mode 100644index 0000000000..a0e0c466a9--- /dev/null+++ b/src/core/cycle/phantom-redirect-managed.ts@@ -0,0 +1,119 @@+/**+ * Phantom redirect on a managed brain (#5280). The legacy handler edits the+ * canonical file, moves rows, soft-deletes the phantom and unlinks its file+ * outside coordination. Here the same lossless merge is two maintenance+ * requests through the coordinator:+ *+ * 1. `managed_maintenance_phantom_merge` on the canonical page publishes+ * the canonical body with the phantom's fence rows appended and, in the+ * same transaction, moves withdrawals, the phantom's fact rows (by id, to+ * the row numbers written to the fence), its links and the rename alias.+ * 2. `managed_maintenance_phantom_delete` on the phantom soft-deletes it and+ * removes its canonical file, moving any edge added since the merge.+ *+ * Both requests are keyed by their intents, so a retry after a crash between+ * them replays the merge and completes the delete.+ */+import type { BrainEngine } from '../engine.ts';+import type { GBrainConfig } from '../config.ts';+import type { Page } from '../types.ts';+import type { PreparedMutation } from '../persistence/coordinator.ts';+import type { WriteRequest } from '../persistence/model.ts';+import { OperationError } from '../ops/contract.ts';+import { parseFactsFence } from '../facts-fence.ts';+import { serializePageToMarkdown } from '../markdown.ts';+import { logPhantomEvent } from '../facts/phantom-audit.ts';+import { MOVE_WITHDRAWAL_SUBJECT_SQL } from '../facts/withdrawal-schema.ts';+import { recordRenameAlias } from '../page-state/rename-alias.ts';+import { preparePageMutation } from '../persistence/page-prepare.ts';+import { maintenancePreflight, submitMaintenanceIntent } from '../persistence/prepared-maintenance.ts';+import { mergePhantomFenceRows, mergePhantomLinks, movePhantomFacts, phantomHasResidue, type RedirectResult } from './phantom-redirect.ts';++export async function redirectManagedPhantom(engine: BrainEngine, page: Page, canonical: string, sourceId: string): Promise<RedirectResult> {+ const authority = (await maintenancePreflight(engine, sourceId))!;+ const drift = (reason: string): RedirectResult => {+ logPhantomEvent({ phantom_slug: page.slug, outcome: 'drift', source_id: sourceId, reason });+ return { outcome: 'drift', canonical };+ };+ const target = await engine.readPageSnapshot(canonical, { sourceId });+ if (!target) return drift('canonical page unavailable on a managed brain');+ const phantom = await engine.readPageSnapshot(page.slug, { sourceId });+ // Eligibility, merge and delete all bind to this one snapshot revision.+ if (!phantom || phantom.page.id !== page.id || phantom.page.compiled_truth !== page.compiled_truth+ || await phantomHasResidue(engine, phantom.page)) return drift('phantom page changed');++ const [dbMax] = await engine.executeRaw<{ n: number | string | null }>(+ 'SELECT MAX(row_num) AS n FROM facts WHERE source_id = $1 AND source_markdown_slug = $2', [sourceId, canonical]);+ const merged = mergePhantomFenceRows(target.page.compiled_truth, parseFactsFence(page.compiled_truth ?? '').facts, Number(dbMax?.n ?? 0));+ if (merged.body !== null && parseFactsFence(merged.body).warnings.length > 0) return drift('rendered fence failed re-parse');+ const outcome = await submitMaintenanceIntent(engine, authority, canonical, {+ kind: 'managed_maintenance_phantom_merge', expected_revision: target.revision,+ content: serializePageToMarkdown({ ...target.page, compiled_truth: merged.body ?? target.page.compiled_truth }, target.tags),+ phantom_slug: page.slug, phantom_page_id: page.id, phantom_revision: phantom.revision, row_map: [...merged.renumber],+ });++ // The delete is bound to the revision that was merged: an edit committed+ // since then never reached the canonical page, so the next run remerges it.+ const current = await engine.readPageSnapshot(page.slug, { sourceId });+ if (current?.page.id === page.id) {+ if (current.revision !== phantom.revision) return drift('phantom page edited after its merge; delete deferred to the next run');+ await submitMaintenanceIntent(engine, authority, page.slug, { kind: 'managed_maintenance_phantom_delete',+ expected_revision: phantom.revision, canonical_slug: canonical });+ }+ logPhantomEvent({ phantom_slug: page.slug, canonical_slug: canonical, outcome: 'redirected',+ fact_count: Number(outcome.facts_moved ?? 0), source_id: sourceId });+ return { outcome: 'redirected', canonical };+}++/** Preparer for `managed_maintenance_phantom_merge`: the canonical page publication plus the phantom's row moves. */+export async function preparePhantomMerge(engine: BrainEngine, row: WriteRequest, config: GBrainConfig): Promise<PreparedMutation> {+ const p = row.intent!;+ const phantomSlug = String(p.phantom_slug);+ const phantomId = Number(p.phantom_page_id);+ const rowMap = new Map((p.row_map as Array<[number, number]>).map(([from, to]) => [Number(from), Number(to)]));+ const phantomUnchanged = async (db: BrainEngine) => {+ const phantom = await db.readPageSnapshot(phantomSlug, { sourceId: row.source_id });+ if (!phantom || phantom.page.id !== phantomId || phantom.revision !== p.phantom_revision || await phantomHasResidue(db, phantom.page)) {+ throw new OperationError('revision_conflict', 'The phantom page changed before its redirect.');+ }+ };+ await phantomUnchanged(engine);+ const page = await preparePageMutation(engine, row, config);+ return { ...page, additionalPageKeys: [...(page.additionalPageKeys ?? []), { sourceId: row.source_id, slug: phantomSlug }],+ validate: async tx => { await page.validate?.(tx); await phantomUnchanged(tx); },+ apply: async tx => {+ // Withdrawals move first so the trigger honors them as the rows take the+ // canonical subject; moved rows then match the published fence rows.+ await tx.executeRaw(MOVE_WITHDRAWAL_SUBJECT_SQL, [row.source_id, phantomSlug, row.slug]);+ const moved = await movePhantomFacts(tx, row.source_id, phantomSlug, row.slug, rowMap);+ const outcome = await page.apply(tx);+ await mergePhantomLinks(tx, phantomId, Number(row.page_id));+ await recordRenameAlias(tx, row.source_id, phantomSlug, row.slug);+ return { ...outcome, facts_moved: moved };+ } };+}++/**+ * Preparer for `managed_maintenance_phantom_delete`: the phantom's soft delete+ * and file removal, holding the canonical key too. Edges added to the phantom+ * after the merge (they advance no revision) move in the same transaction;+ * timeline rows added since then defer the delete.+ */+export async function preparePhantomDelete(engine: BrainEngine, row: WriteRequest, config: GBrainConfig): Promise<PreparedMutation> {+ const canonicalSlug = String(row.intent!.canonical_slug);+ const noTimeline = async (db: BrainEngine) => {+ if ((await db.executeRaw('SELECT 1 FROM timeline_entries WHERE page_id=$1 LIMIT 1', [row.page_id])).length) {+ throw new OperationError('revision_conflict', 'The phantom gained timeline rows after its merge.');+ }+ };+ await noTimeline(engine);+ const page = await preparePageMutation(engine, { ...row, operation: 'delete_page' }, config);+ return { ...page, additionalPageKeys: [...(page.additionalPageKeys ?? []), { sourceId: row.source_id, slug: canonicalSlug }],+ validate: async tx => { await page.validate?.(tx); await noTimeline(tx); },+ apply: async tx => {+ const canonical = await tx.readPageSnapshot(canonicalSlug, { sourceId: row.source_id });+ if (!canonical) throw new OperationError('page_not_found', 'The redirect target disappeared before the phantom delete.');+ await mergePhantomLinks(tx, Number(row.page_id), canonical.page.id);+ return page.apply(tx);+ } };+}diff --git a/src/core/cycle/phantom-redirect.ts b/src/core/cycle/phantom-redirect.tsindex 189be43f88..893b8f2c35 100644--- a/src/core/cycle/phantom-redirect.ts+++ b/src/core/cycle/phantom-redirect.ts@@ -1,4 +1,3 @@-import { assertUnmanagedCanonicalWriter } from '../persistence/maintenance.ts';/*** v0.35.5 — phantom-page redirect pass.*@@ -59,6 +58,7 @@ import { logPhantomEvent, type PhantomOutcome } from '../facts/phantom-audit.ts'import { MOVE_WITHDRAWAL_SUBJECT_SQL } from '../facts/withdrawal-schema.ts';import { resolvePageWriteTarget } from '../write-through.ts';import { recordRenameAlias } from '../page-state/rename-alias.ts';+import { managedPersistenceEnabled } from '../persistence/ownership.ts';/** Tagged-union outcome of a single phantom-redirect attempt. */export type RedirectOutcome =@@ -220,9 +220,35 @@ function appendPhantomFenceRowsToCanonical(phantomFacts: ParsedFact[],dbMaxRowNum: number,): Map<number, number> {+ if (phantomFacts.length === 0) return new Map<number, number>();+ const { body: newBody, renumber } = mergePhantomFenceRows(fs.readFileSync(canonicalPath, 'utf-8'), phantomFacts, dbMaxRowNum);+ if (newBody === null) return renumber;++ // Atomic write: .tmp first, parse-validate, rename.+ const tmpPath = `${canonicalPath}.tmp`;+ fs.writeFileSync(tmpPath, newBody, 'utf-8');+ const reparsed = parseFactsFence(newBody);+ if (reparsed.warnings.length > 0) {+ // Leave .tmp as quarantine evidence; do NOT rename.+ throw new Error(+ `phantom-redirect: rendered fence failed re-parse: ${reparsed.warnings.join('; ')}`,+ );+ }+ fs.renameSync(tmpPath, canonicalPath);+ return renumber;+}++/**+ * The canonical body with the phantom's rows appended (null when every row+ * dedups onto an existing canonical row) and the phantom -> canonical row+ * number map. Shared by the file writer above and the managed redirect.+ */+export function mergePhantomFenceRows(+ body: string,+ phantomFacts: ParsedFact[],+ dbMaxRowNum: number,+): { body: string | null; renumber: Map<number, number> } {const renumber = new Map<number, number>();- if (phantomFacts.length === 0) return renumber;- const body = fs.readFileSync(canonicalPath, 'utf-8');const { facts: existingFacts } = parseFactsFence(body);// Dedup key combines claim + valid_from. We deliberately do NOT include@@ -247,7 +273,7 @@ function appendPhantomFenceRowsToCanonical(nextRowNum += 1;}- if (pending.length === 0) return renumber;+ if (pending.length === 0) return { body: null, renumber };const merged: ParsedFact[] = [...existingFacts, ...pending.map((f) => {const target = f.supersededBy === undefined ? undefined : renumber.get(f.supersededBy);@@ -257,20 +283,7 @@ function appendPhantomFenceRowsToCanonical(// Shared placement rule (#4756): replace in place, else insert ABOVE the// timeline sentinel — never a blind EOF append below `## Timeline`.- const newBody = replaceOrInsertFactsFence(body, renderFactsTable(merged));-- // Atomic write: .tmp first, parse-validate, rename.- const tmpPath = `${canonicalPath}.tmp`;- fs.writeFileSync(tmpPath, newBody, 'utf-8');- const reparsed = parseFactsFence(newBody);- if (reparsed.warnings.length > 0) {- // Leave .tmp as quarantine evidence; do NOT rename.- throw new Error(- `phantom-redirect: rendered fence failed re-parse: ${reparsed.warnings.join('; ')}`,- );- }- fs.renameSync(tmpPath, canonicalPath);- return renumber;+ return { body: replaceOrInsertFactsFence(body, renderFactsTable(merged)), renumber };}/**@@ -289,32 +302,41 @@ async function migratePhantomFacts(canonicalSlug: string,rowMap: ReadonlyMap<number, number>,): Promise<number> {- return engine.transaction(async (tx) => {- const rows = await tx.executeRaw<{ id: number; row_num: number | null }>(- 'SELECT id, row_num FROM facts WHERE source_id = $1 AND source_markdown_slug = $2',- [sourceId, phantomSlug],- );- const taken = new Set((await tx.executeRaw<{ row_num: number }>(- 'SELECT row_num FROM facts WHERE source_id = $1 AND source_markdown_slug = $2 AND row_num IS NOT NULL',- [sourceId, canonicalSlug],- )).map(r => Number(r.row_num)));- let moved = 0;- for (const row of rows) {- const mapped = row.row_num == null ? undefined : rowMap.get(Number(row.row_num));- const target = mapped !== undefined && !taken.has(mapped) ? mapped : undefined;- if (target !== undefined) {- taken.add(target);- moved += 1;- }- await tx.executeRaw(- `UPDATE facts SET entity_slug = $3, source_markdown_slug = $3, row_num = $4::integer,- expired_at = CASE WHEN $4::integer IS NULL THEN COALESCE(expired_at, now()) ELSE expired_at END- WHERE id = $1 AND source_id = $2`,- [row.id, sourceId, canonicalSlug, target ?? null],- );+ return engine.transaction(tx => movePhantomFacts(tx, sourceId, phantomSlug, canonicalSlug, rowMap));+}++/** The body of migratePhantomFacts inside the caller's transaction. */+export async function movePhantomFacts(+ tx: BrainEngine,+ sourceId: string,+ phantomSlug: string,+ canonicalSlug: string,+ rowMap: ReadonlyMap<number, number>,+): Promise<number> {+ const rows = await tx.executeRaw<{ id: number; row_num: number | null }>(+ 'SELECT id, row_num FROM facts WHERE source_id = $1 AND source_markdown_slug = $2',+ [sourceId, phantomSlug],+ );+ const taken = new Set((await tx.executeRaw<{ row_num: number }>(+ 'SELECT row_num FROM facts WHERE source_id = $1 AND source_markdown_slug = $2 AND row_num IS NOT NULL',+ [sourceId, canonicalSlug],+ )).map(r => Number(r.row_num)));+ let moved = 0;+ for (const row of rows) {+ const mapped = row.row_num == null ? undefined : rowMap.get(Number(row.row_num));+ const target = mapped !== undefined && !taken.has(mapped) ? mapped : undefined;+ if (target !== undefined) {+ taken.add(target);+ moved += 1;}- return moved;- });+ await tx.executeRaw(+ `UPDATE facts SET entity_slug = $3, source_markdown_slug = $3, row_num = $4::integer,+ expired_at = CASE WHEN $4::integer IS NULL THEN COALESCE(expired_at, now()) ELSE expired_at END+ WHERE id = $1 AND source_id = $2`,+ [row.id, sourceId, canonicalSlug, target ?? null],+ );+ }+ return moved;}/**@@ -323,7 +345,7 @@ async function migratePhantomFacts(* already carries, or one that would become a self-link, stays on the* soft-deleted phantom.*/-async function mergePhantomLinks(engine: BrainEngine, phantomId: number, canonicalId: number): Promise<void> {+export async function mergePhantomLinks(engine: BrainEngine, phantomId: number, canonicalId: number): Promise<void> {await engine.executeRaw(`UPDATE links l SET to_page_id = $2WHERE l.to_page_id = $1 AND l.from_page_id <> $2@@ -432,6 +454,15 @@ async function materializeCanonicalToDisk(/** Frontmatter a bare phantom stub may carry; any other key is residue. */const PHANTOM_STUB_FRONTMATTER = new Set(['title', 'type', 'tags']);+/** Anything a redirect would lose: body beyond the fence, timeline text or rows, custom frontmatter. */+export async function phantomHasResidue(engine: BrainEngine, page: Page): Promise<boolean> {+ const residue = stripFenceAndFrontmatterAndLeadingH1(page.compiled_truth ?? '')+ + (page.timeline ?? '').trim()+ + Object.keys(page.frontmatter ?? {}).filter(key => !PHANTOM_STUB_FRONTMATTER.has(key)).join(',');+ if (residue.length > 0) return true;+ return (await engine.executeRaw('SELECT 1 FROM timeline_entries WHERE page_id=$1 LIMIT 1', [page.id])).length > 0;+}+/*** Single-phantom redirect. Caller (the pass) is responsible for the* outer lock + the audit-log cap.@@ -451,12 +482,7 @@ export async function tryRedirectPhantom(// a facts fence. Only fence rows migrate, so anything else the page holds// (timeline text or rows, custom frontmatter) is residue that a redirect// would delete.- const residue = stripFenceAndFrontmatterAndLeadingH1(page.compiled_truth ?? '')- + (page.timeline ?? '').trim()- + Object.keys(page.frontmatter ?? {}).filter(key => !PHANTOM_STUB_FRONTMATTER.has(key)).join(',');- const timelineRows = residue.length > 0 ? [] : await engine.executeRaw(- 'SELECT 1 FROM timeline_entries WHERE page_id=$1 LIMIT 1', [page.id]);- if (residue.length > 0 || timelineRows.length > 0) {+ if (await phantomHasResidue(engine, page)) {logPhantomEvent({phantom_slug: page.slug,outcome: 'not_phantom_has_residue',@@ -503,7 +529,10 @@ export async function tryRedirectPhantom(// D10: dry-run preview — no FS / DB / audit writes.if (dryRun) return { outcome: 'redirected', canonical };- await assertUnmanagedCanonicalWriter(engine, 'phantom canonical redirect');+ if (await managedPersistenceEnabled(engine)) {+ const { redirectManagedPhantom } = await import('./phantom-redirect-managed.ts');+ return redirectManagedPhantom(engine, page, canonical, sourceId);+ }// ─── Commit phase (codex #3/#4/#6/#7) ─────────────────────────────// The canonical file is the page's file of record (recorded source_path,diff --git a/src/core/cycle/phase-containment.ts b/src/core/cycle/phase-containment.tsnew file mode 100644index 0000000000..285639c234--- /dev/null+++ b/src/core/cycle/phase-containment.ts@@ -0,0 +1,68 @@+/**+ * Cycle phase containment (fix wave 3, CEO E2 / Eng E-D15).+ *+ * A phase whose runner throws (for example a managed-brain refusal) returns a+ * `fail` phase result carrying the typed error, so later phases in the same+ * job still run; the job's status still reports the failure. Containment+ * never swallows cancellation, a lost cycle lease or budget exhaustion: those+ * stop the job exactly as before. A contained failure after paid model calls+ * is recorded for doctor's dream_paid_loop check.+ */+import type { BrainEngine } from '../engine.ts';+import type { CyclePhase, PhaseResult } from '../cycle.ts';+import { LockStolenError } from '../db-lock.ts';+import { BudgetExhausted } from '../budget/budget-tracker.ts';+import { withChatCallMeter } from '../ai/chat-usage.ts';+import { recordContainedPaidFailure } from './dream-breaker.ts';++/** Errors that must stop the whole job instead of failing one phase. */+export function isUncontainedPhaseError(error: unknown, signal?: AbortSignal): boolean {+ if (signal?.aborted) return true;+ if (error instanceof LockStolenError || error instanceof BudgetExhausted) return true;+ const name = (error as { name?: unknown } | null)?.name;+ return name === 'AbortError' || name === 'LockStolenError' || name === 'BudgetExhausted';+}++export interface PhaseContainment {+ engine: BrainEngine | null;+ sourceId: string;+ signal?: AbortSignal;+}++/**+ * Time one phase runner and contain its failure. Returns the same+ * `{ result, duration_ms }` shape as the plain timer.+ */+export async function timeContainedPhase<T extends PhaseResult>(containment: PhaseContainment, phase: CyclePhase,+ fn: () => Promise<T>): Promise<{ result: T | PhaseResult; duration_ms: number }> {+ const start = performance.now();+ const meter = { calls: 0 };+ try {+ const result = await withChatCallMeter(meter, fn);+ return { result, duration_ms: Math.round(performance.now() - start) };+ } catch (error) {+ if (isUncontainedPhaseError(error, containment.signal)) throw error;+ const err = error instanceof Error ? error : new Error(String(error));+ const rawCode = (err as { code?: unknown }).code;+ const code = typeof rawCode === 'string' ? rawCode : 'UNKNOWN';+ let paidLoopRecorded = false;+ if (meter.calls > 0 && containment.engine) {+ try { await recordContainedPaidFailure(containment.engine, phase, containment.sourceId); paidLoopRecorded = true; }+ catch (recordError) {+ console.warn(`[cycle] could not record the contained ${phase} failure for dream_paid_loop: ${recordError instanceof Error ? recordError.message : String(recordError)}`);+ }+ }+ console.error(`[cycle] phase '${phase}' failed and was contained; later phases still run: ${err.message}`);+ return {+ result: {+ phase,+ status: 'fail',+ duration_ms: 0,+ summary: `${phase} failed: ${err.message.slice(0, 200)}`,+ details: { contained: true, paid_model_calls: meter.calls, paid_loop_recorded: paidLoopRecorded },+ error: { class: err.name || 'Error', code, message: err.message.slice(0, 200) },+ },+ duration_ms: Math.round(performance.now() - start),+ };+ }+}diff --git a/src/core/cycle/phase-table.ts b/src/core/cycle/phase-table.tsnew file mode 100644index 0000000000..a7af374662--- /dev/null+++ b/src/core/cycle/phase-table.ts@@ -0,0 +1,50 @@+/**+ * Managed-brain phase table (fix wave 3, CEO managed-brain phase matrix /+ * Eng E-D15). Every phase in `ALL_PHASES` is classified by what it does on a+ * managed brain (persistence enabled):+ *+ * - `writes`: publishes canonical rows or files through the coordinator.+ * - `no_coordinated_write`: writes nothing coordinated by design (derived+ * projections, side tables, reports outside the brain), with the reason.+ * - `managed_skip`: deliberately skipped on managed brains, with the reason+ * the cycle report shows.+ *+ * `test/managed-phase-matrix.test.ts` fails for a phase missing here and runs+ * each classified phase once on a managed PGLite and Postgres brain.+ */+import type { BrainEngine } from '../engine.ts';+import type { CyclePhase } from '../cycle.ts';+import { managedPersistenceEnabled } from '../persistence/ownership.ts';++export type ManagedPhaseClass = 'writes' | 'no_coordinated_write' | 'managed_skip';+export interface ManagedPhaseEntry { class: ManagedPhaseClass; reason: string }++export const MANAGED_PHASE_TABLE: Readonly<Record<CyclePhase, ManagedPhaseEntry>> = {+ lint: { class: 'no_coordinated_write', reason: 'On a managed brain lint reports issues and skips its file fixes; canonical markdown changes go through page mutations.' },+ backlinks: { class: 'no_coordinated_write', reason: 'Audit-only: counts missing back-links and never writes files.' },+ sync: { class: 'writes', reason: 'Managed sync admits each changed file through the coordinator.' },+ synthesize: { class: 'writes', reason: 'Dream synthesis publishes pages through the maintenance coordinator.' },+ extract: { class: 'writes', reason: 'Derived links and unrecorded timeline rows commit inside revision-bound coordinated transactions.' },+ extract_facts: { class: 'writes', reason: 'Fence facts are re-projected through coordinated maintenance writes.' },+ extract_atoms: { class: 'writes', reason: 'Atom pages publish through the maintenance coordinator.' },+ resolve_symbol_edges: { class: 'no_coordinated_write', reason: 'Resolves code-edge metadata on chunks, a derived projection outside the canonical tables.' },+ patterns: { class: 'writes', reason: 'Pattern pages publish through the maintenance coordinator.' },+ synthesize_concepts: { class: 'writes', reason: 'Concept pages publish through publishMaintenancePage: private first, provenance, then promotion.' },+ recompute_emotional_weight: { class: 'no_coordinated_write', reason: 'Writes the derived emotional_weight column, which the canonical writer guard does not cover.' },+ consolidate: { class: 'writes', reason: 'Consolidated takes, facts and pages commit through the maintenance coordinator.' },+ propose_takes: { class: 'no_coordinated_write', reason: 'Writes the take_proposals review queue; managed brains skip the legacy receipt page.' },+ grade_takes: { class: 'no_coordinated_write', reason: 'The cycle runs it with auto-resolve off, so it only caches verdicts in take_grade_cache; opt-in auto-applied resolutions go through the coordinated takes_resolve mutation.' },+ calibration_profile: { class: 'no_coordinated_write', reason: 'Writes the calibration_profiles side table only.' },+ drift: { class: 'writes', reason: 'The drift report page publishes through the maintenance coordinator.' },+ conversation_facts_backfill: { class: 'writes', reason: 'Backfilled conversation facts publish through coordinated writes.' },+ enrich_thin: { class: 'writes', reason: 'Enriched pages publish through the maintenance coordinator.' },+ skillopt: { class: 'no_coordinated_write', reason: 'Writes skill files and proposals outside the brain database.' },+ embed: { class: 'no_coordinated_write', reason: 'Embeddings are a physical projection the canonical writer guard does not cover.' },+ orphans: { class: 'no_coordinated_write', reason: 'Read-only orphan report.' },+ 'schema-suggest': { class: 'no_coordinated_write', reason: 'Writes schema suggestions outside the canonical tables.' },+ purge: { class: 'writes', reason: 'Expired tombstones are purged one by one through coordinated delete_page purges.' },+};++export async function isManagedBrain(engine: BrainEngine): Promise<boolean> {+ return managedPersistenceEnabled(engine);+}diff --git a/src/core/cycle/propose-takes.ts b/src/core/cycle/propose-takes.tsindex ae8f0a492f..e1ca215296 100644--- a/src/core/cycle/propose-takes.ts+++ b/src/core/cycle/propose-takes.ts@@ -44,6 +44,7 @@ import { chat as gatewayChat, getChatModel, probeChatModel } from '../ai/gatewayimport { createGlobalLlmHaltTracker, haltedClassOf, type GlobalLlmErrorClass } from '../ai/errors.ts';import { normalizeModelId } from '../model-id.ts';import { writeReceipt } from '../extract/receipt-writer.ts';+import { managedPersistenceEnabled } from '../persistence/ownership.ts';import { upsertExtractRollup, classifyRunStop } from '../extract/rollup-writer.ts';import { GBrainError } from '../types.ts';import { isConfigTruthy } from '../config.ts';@@ -998,7 +999,9 @@ class ProposeTakesPhase extends BaseCyclePhase {// v0.42 Wave B3: receipt + rollup for propose_takes. Source-scoped// via the read scope. Receipt only when proposals actually written.const sourceIdForReceipt = scope.sourceId ?? 'default';- if (result.proposals_inserted > 0) {+ // Managed brains skip the receipt page (a legacy putPage the coordinator+ // refuses), like extract_atoms and synthesize_concepts; the rollup stays.+ if (result.proposals_inserted > 0 && !await managedPersistenceEnabled(engine)) {try {await writeReceipt(engine, {kind: 'takes.proposed',diff --git a/src/core/cycle/synthesize-concepts.ts b/src/core/cycle/synthesize-concepts.tsindex 10be63e4ca..8a9b80f09d 100644--- a/src/core/cycle/synthesize-concepts.ts+++ b/src/core/cycle/synthesize-concepts.ts@@ -39,6 +39,8 @@ import { createHash } from 'node:crypto';import { slugifySegment } from '../sync.ts';import { validatePageSlug } from '../ops/context.ts';import { privatePagesFilterFragment, strictestVisibility, type Visibility } from '../search/private-visibility.ts';+import { maintenancePreflight } from '../persistence/prepared-maintenance.ts';+import { addManagedProvenanceLinks, CONCEPT_DEFERRAL_CODES, CONCEPT_HOLD_CODES, publishManagedConcept } from './concept-publication.ts';const DEFAULT_BUDGET_USD = 1.5;// Canonical-miss policy — mirrors skillopt/preflight.ts's lookupPrice:@@ -287,6 +289,15 @@ export async function runPhaseSynthesizeConcepts(fallback: 'sonnet',});const synthMaxOutputTokens = resolveSynthMaxOutputTokens(synthModel);+ // #5484: a managed brain refuses the legacy importFromContent writer. Claim+ // maintenance authority before any model spend so a missing canonical owner+ // fails fast; null on an unmanaged brain.+ const maintenance = opts.dryRun ? null : await maintenancePreflight(engine, opts.sourceId ?? 'default', opts.brainDir);+ // Managed publication outcomes, kept out of `failures` (LLM fallback). A+ // deferred concept moved under a concurrent writer and is retried next run;+ // a held concept cannot be republished without losing canonical material.+ const publicationDeferred: Array<{ concept: string; reason: string }> = [];+ const publicationHeld: Array<{ concept: string; reason: string }> = [];const skippedHumanOwned: string[] = [];const skippedUnchanged: string[] = [];const keptExistingNarrative: string[] = [];@@ -294,7 +305,8 @@ export async function runPhaseSynthesizeConcepts(const conceptSlug = `concepts/${group.conceptSlug}`;// A concept page this phase did not write belongs to a human (or another// writer). Check before any spend; never replace its body.- const existing = await engine.getPage(conceptSlug, { sourceId: opts.sourceId ?? 'default' });+ const existingSnapshot = await engine.readPageSnapshot(conceptSlug, { sourceId: opts.sourceId ?? 'default' });+ const existing = existingSnapshot?.page ?? null;if (existing && !String(existing.frontmatter?.synthesized_by ?? '').startsWith('synthesize_concepts')) {skippedHumanOwned.push(conceptSlug);continue;@@ -403,28 +415,48 @@ export async function runPhaseSynthesizeConcepts(// the page is chunked (+ embedded when a provider is configured) —// mirrors put_page's isAvailable('embedding') → noEmbed gate.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,- member_hash: memberHash,- synthesized_at: synthesizedAt,- synthesized_by: 'synthesize_concepts-v0.41',- visibility: pageVisibility,- },- narrative,- '',- { type: 'concept', title: title.replace(/-/g, ' '), tags: [] },- ), {- noEmbed: !isAvailable('embedding'),- // #4416: target the cycle's resolved source, not the 'default' literal.- sourceId: opts.sourceId,+ const synthesized = (pageVisibility: Visibility) => ({+ tier: group.tier,+ mention_count: group.atomTitles.length,+ composite_score: group.atomTitles.length,+ synthesis_mode: synthesisMode,+ member_hash: memberHash,+ synthesized_at: synthesizedAt,+ synthesized_by: 'synthesize_concepts-v0.41',+ visibility: pageVisibility,});+ // Each managed publication is bound to the revision the narrative was+ // synthesized from, then to the previous publication's result.+ let conceptRevision = existingSnapshot?.revision ?? null;+ const publish = async (pageVisibility: Visibility): Promise<void> => {+ if (maintenance) {+ conceptRevision = await publishManagedConcept(engine, maintenance, conceptSlug, synthesized(pageVisibility), narrative,+ conceptRevision, opts.brainDir);+ return;+ }+ await importFromContent(engine, conceptSlug, serializeMarkdown(synthesized(pageVisibility), narrative, '',+ { type: 'concept', title: title.replace(/-/g, ' '), tags: [] }), {+ noEmbed: !isAvailable('embedding'),+ // #4416: target the cycle's resolved source, not the 'default' literal.+ sourceId: opts.sourceId,+ });+ };+ // A managed publication that lost a revision race or would lose canonical+ // material is recorded and skipped; any other error stops the phase.+ const publishOrRecord = async (pageVisibility: Visibility): Promise<boolean> => {+ try { await publish(pageVisibility); return true; } catch (err) {+ const code = (err as { code?: unknown }).code;+ if (!maintenance || typeof code !== 'string') throw err;+ const reason = `${code}: ${(err as Error).message}`;+ if (CONCEPT_DEFERRAL_CODES.has(code)) publicationDeferred.push({ concept: group.conceptSlug, reason });+ else if (CONCEPT_HOLD_CODES.has(code)) publicationHeld.push({ concept: group.conceptSlug, reason });+ else throw err;+ return false;+ }+ };// #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');+ if (!await publishOrRecord('private')) continue;// #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@@ -439,7 +471,8 @@ export async function runPhaseSynthesizeConcepts({ from_slug: atomSlug, to_slug: conceptSlug, link_type: 'synthesizes', link_source: 'concept-provenance', context: 'concept synthesized from this atom', from_source_id: src, to_source_id: src },]);try {- const inserted = await engine.addLinksBatch(provenanceLinks, { auditSite: 'cycle.synthesize_concepts.provenance' }); // gbrain-allow-direct-insert: concept-provenance edges derived from the synthesis itself (no markdown body to reconcile from)+ const inserted = maintenance ? await addManagedProvenanceLinks(engine, src, provenanceLinks)+ : await engine.addLinksBatch(provenanceLinks, { auditSite: 'cycle.synthesize_concepts.provenance' }); // gbrain-allow-direct-insert: concept-provenance edges derived from the synthesis itself (no markdown body to reconcile from)// Zero rows back with edges requested means every member atom fell// out of the batch JOIN (not in this source) — unless a prior run// already banked them (ON CONFLICT DO NOTHING also returns 0). A@@ -462,7 +495,7 @@ export async function runPhaseSynthesizeConcepts(JOIN pages c ON c.id=l.from_page_id JOIN pages a ON a.id=l.to_page_idWHERE 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');+ if (Number(linked) === members.length && !await publishOrRecord('world')) continue;}}conceptsWritten++;@@ -480,7 +513,9 @@ export async function runPhaseSynthesizeConcepts(// survives only as the fallback for legacy unscoped callers. Receipt only// fires when concepts were actually written; rollup always fires so doctor// sees the phase ran.- if (!opts.dryRun && conceptsWritten > 0) {+ // Managed brains skip the receipt page (a legacy putPage), like extract_atoms;+ // the rollup row below still records the run for doctor.+ if (!opts.dryRun && !maintenance && conceptsWritten > 0) {const runId = `concepts-${Date.now().toString(36)}`;try {await writeReceipt(engine, {@@ -507,14 +542,14 @@ export async function runPhaseSynthesizeConcepts(kind: 'concepts',source_id: opts.sourceId ?? 'default',cost_delta: estimatedSpendUsd,- round_completed_delta: failures.length === 0 ? 1 : 0,+ round_completed_delta: failures.length === 0 && publicationDeferred.length === 0 && publicationHeld.length === 0 ? 1 : 0,halt_delta: failures.length > 0 ? 1 : 0,});}return {phase: 'synthesize_concepts',- status: failures.length > 0 || linkWarnings.length > 0 ? 'warn' : 'ok',+ status: failures.length > 0 || linkWarnings.length > 0 || publicationDeferred.length > 0 || publicationHeld.length > 0 ? 'warn' : 'ok',duration_ms: 0,summary:`synthesize_concepts: ${conceptsWritten} concepts ` +@@ -523,7 +558,9 @@ export async function runPhaseSynthesizeConcepts((linkWarnings.length > 0 ? ` (${linkWarnings.length} provenance-link warning(s))` : '') +(skippedHumanOwned.length > 0 ? ` (${skippedHumanOwned.length} human-owned page(s) left untouched)` : '') +(skippedUnchanged.length > 0 ? ` (${skippedUnchanged.length} unchanged)` : '') +- (keptExistingNarrative.length > 0 ? ` (${keptExistingNarrative.length} existing narrative(s) kept)` : ''),+ (keptExistingNarrative.length > 0 ? ` (${keptExistingNarrative.length} existing narrative(s) kept)` : '') ++ (publicationDeferred.length > 0 ? ` (${publicationDeferred.length} publication(s) deferred: page changed, retried next run)` : '') ++ (publicationHeld.length > 0 ? ` (${publicationHeld.length} publication(s) held: existing page needs import/repair)` : ''),details: {concepts_written: conceptsWritten,tier_counts: tierCounts,@@ -535,6 +572,8 @@ export async function runPhaseSynthesizeConcepts(skipped_human_owned: skippedHumanOwned,skipped_unchanged: skippedUnchanged,kept_existing_narrative: keptExistingNarrative,+ publication_deferred: publicationDeferred,+ publication_held: publicationHeld,...(abortedGlobalError ? { aborted_global_error: abortedGlobalError } : {}),estimated_spend_usd: estimatedSpendUsd,budget_usd: budgetCap,diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex 794f6ad492..6a45415103 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -57,7 +57,10 @@ export type CheckCategory = 'brain' | 'skill' | 'ops' | 'meta';export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set(['abandoned_threads','atom_provenance_drift',+ 'connector_checkpoints','derived_visibility',+ 'safe_index_pending',+ 'self_capture','brain_score','calibration_freshness','child_table_orphans',@@ -132,6 +135,8 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set(['timeline_coverage','timeline_orphans','timeline_history',+ // #5254 — pages written database-only to a source with no canonical owner.+ 'unbound_source','undeclared_db_only_pages','unified_multimodal_coverage','unverified_extractions',@@ -195,6 +200,8 @@ export const OPS_CHECK_NAMES: ReadonlySet<string> = new Set(['oauth_confidential_client_health','orphan_clones','persistence_capacity',+ 'stale_embedding_effects',+ 'writer_version','pgbouncer_prepare','pglite_data_dir',// db-availability loop: engine-fit + repair-recurrence signals.diff --git a/src/core/embed-retry.ts b/src/core/embed-retry.tsindex ca0e2baeff..3e81f3973d 100644--- a/src/core/embed-retry.ts+++ b/src/core/embed-retry.ts@@ -13,6 +13,7 @@*/import { embedBatch } from './embedding.ts';+import { isEmbeddingZeroNormError, type EmbeddingZeroNormError } from './ai/embedding-guard.ts';import { serr } from './console-prefix.ts';import { noteEmbedApiResponse } from './embed-stall.ts';import { titleTierCorpusGeneration } from './contextual-retrieval-service.ts';@@ -251,6 +252,21 @@ export async function embedBatchWithBackoff(return embedBatch(texts);}+/**+ * #4616: embedBatchWithBackoff that keeps a partially refused batch. Usable+ * vectors come back aligned with `texts` (null where the gateway refused an+ * item) together with the refusal; a batch with nothing usable still throws.+ */+export async function embedBatchKeepingUsable(texts: string[], opts: EmbedBatchWithBackoffOpts = {}):+ Promise<{ vectors: (Float32Array | null)[]; refused?: EmbeddingZeroNormError }> {+ try {+ return { vectors: await embedBatchWithBackoff(texts, opts) };+ } catch (e) {+ if (!isEmbeddingZeroNormError(e) || e.failures.length === texts.length) throw e;+ return { vectors: e.vectors, refused: e };+ }+}+/*** Retriable embed errors: 429 rate limits plus transient gateway overload* (502/503/504). Shared by embedBatchWithBackoff (retry decision) and@@ -259,6 +275,7 @@ export async function embedBatchWithBackoff(* providers whose wrappers strip `cause.status`.*/export function isEmbedRetriableError(e: unknown): boolean {+ if (isEmbeddingZeroNormError(e)) return false; // #4616: terminal per item, never retriedconst msg = e instanceof Error ? e.message : String(e);return (detect429FromCause(e) ||@@ -298,6 +315,7 @@ export function transientBackoffMs(attempt: number, rng: () => number = Math.ran* @internal exported for unit tests.*/export function isTransientNetworkEmbedError(e: unknown): boolean {+ if (isEmbeddingZeroNormError(e)) return false;const TRANSIENT_CODES = /^(DNS_ETIMEOUT|ETIMEOUT|ETIMEDOUT|ESOCKETTIMEDOUT|ECONNRESET|EPIPE|ECONNABORTED|EAI_AGAIN|UND_ERR_CONNECT_TIMEOUT|UND_ERR_HEADERS_TIMEOUT|UND_ERR_BODY_TIMEOUT|UND_ERR_SOCKET)$/;let cur: unknown = e;for (let depth = 0; depth < 5 && cur !== undefined && cur !== null; depth++) {diff --git a/src/core/embedding-input-limit.ts b/src/core/embedding-input-limit.tsindex 21f77b5b4b..be887ae28c 100644--- a/src/core/embedding-input-limit.ts+++ b/src/core/embedding-input-limit.ts@@ -62,12 +62,12 @@ export function maxInputTokensForModel(recipe: Recipe, modelId: string): number}/**- * Effective chunk-token cap for the active embedding model. See module doc.+ * Effective chunk-token cap for the active embedding model (or `model`). See module doc.* Never exceeds DEFAULT_MAX_CHUNK_TOKENS (existing downstream sizing —* tsvector limits, context assembly — calibrates to it) and never goes below* MIN_CHUNK_TOKENS.*/-export function resolveMaxChunkTokens(env: Record<string, string | undefined> = process.env): number {+export function resolveMaxChunkTokens(env: Record<string, string | undefined> = process.env, model?: string): number {const raw = env.GBRAIN_MAX_CHUNK_TOKENS;if (raw !== undefined && raw.trim() !== '') {const n = Number(raw);@@ -84,7 +84,7 @@ export function resolveMaxChunkTokens(env: Record<string, string | undefined> =}}try {- const { parsed, recipe } = resolveRecipe(getEmbeddingModel());+ const { parsed, recipe } = resolveRecipe(model ?? getEmbeddingModel());const declared = maxInputTokensForModel(recipe, parsed.modelId);if (declared !== undefined) {return Math.min(diff --git a/src/core/embedding-invalidation.ts b/src/core/embedding-invalidation.tsindex bf7bdf4485..6a8f12afa4 100644--- a/src/core/embedding-invalidation.ts+++ b/src/core/embedding-invalidation.ts@@ -154,6 +154,32 @@ export async function clearFalseStampedSignatures(});}+/**+ * #5289: chunks the widened stale predicate counts that the live run only+ * restamps. Their vectors are already in the target space (model, text hash+ * and width match), so invalidation keeps them and never re-embeds them; an+ * honest dry run subtracts them from its "would embed" figure.+ */+export async function countRestampOnlyChunks(+ engine: Pick<BrainEngine, 'executeRaw'>,+ opts: { signature: string; sourceId?: string; includeNullSignature?: boolean },+): Promise<number> {+ const colId = quoteIdentifier((await resolveActiveEmbeddingColumnFromEngine(engine, { fallbackToLegacy: true })).name);+ const { model, dims } = splitEmbeddingSignature(opts.signature);+ const sigClause = opts.includeNullSignature+ ? '(p.embedding_signature IS NULL OR p.embedding_signature <> $1)'+ : 'p.embedding_signature IS NOT NULL AND p.embedding_signature <> $1';+ const rows = await engine.executeRaw<{ count: number | string }>(+ `SELECT count(*)::int AS count FROM content_chunks cc JOIN pages p ON p.id = cc.page_id+ WHERE p.deleted_at IS NULL AND ${sigClause}+ AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')+ AND ($4::text IS NULL OR p.source_id = $4)+ AND ${currentSpaceChunkPredicate(colId, 2, 3)}`,+ [opts.signature, model, dims, opts.sourceId ?? null],+ );+ return Number(rows[0]?.count ?? 0);+}+export async function invalidateStaleSignatureEmbeddingsGuarded(engine: BrainEngine,opts: { signature: string; sourceId?: string; includeNullSignature?: boolean },diff --git a/src/core/embedding-migration-budget.ts b/src/core/embedding-migration-budget.tsindex 2f002dda01..c0c1edaa13 100644--- a/src/core/embedding-migration-budget.ts+++ b/src/core/embedding-migration-budget.ts@@ -1,9 +1,49 @@+import { randomUUID } from 'node:crypto';import type { BrainEngine } from './engine.ts';-import { BudgetTracker, loadPricingOverrides } from './budget/budget-tracker.ts';-import type { AIInvocation, AIInvocationPermit } from './ai/invocation-guard.ts';+import { loadPricingOverrides } from './budget/budget-tracker.ts';+import { reservationCostUsd, usageCostUsd, type BudgetKind } from './budget/reservation-cost.ts';+import type { AIInvocation, AIInvocationPermit, AIInvocationUsage } from './ai/invocation-guard.ts';import { MIGRATION_STATE_KEY, readMigrationState, type EmbeddingMigrationPlan, type MigrationState } from './embedding-migration.ts';import type { DbLockHandle } from './db-lock.ts';+export const EMBEDDING_BUDGET_BELOW_WORST_CASE = 'embedding_budget_below_worst_case';+export const EMBEDDING_BUDGET_REFUSAL_DOCS = 'https://github.com/garrytan/gbrain/blob/master/docs/guides/write-refusals.md#embedding_budget_below_worst_case';+const USD_EPSILON = 1e-9;++/** Σ maximum input over the planned requests, from the same batcher the run dispatches through. `usd` is null only when the embedding model is unpriced. */+export interface MigrationWorstCase { requests: number; input_tokens: number; usd: number | null; unpriced_models: string[] }++export interface MigrationBudgetRefusalDetails {+ error: typeof EMBEDDING_BUDGET_BELOW_WORST_CASE;+ message: string;+ cap_usd: number;+ worst_case_usd: number;+ debited_usd: number;+ required_cap_usd: number;+ suggestion: string;+ docs: string;+}++/** Whole cents, rounded up, so a printed amount is always enough to authorize what it describes. */+export function ceilCents(usd: number): number {+ return usd <= 0 ? 0 : Math.ceil(usd * 100 - USD_EPSILON) / 100;+}++export class MigrationBudgetRefusal extends Error {+ readonly details: MigrationBudgetRefusalDetails;+ constructor(plan: EmbeddingMigrationPlan, cap: number, worst: number, debited: number) {+ const required = ceilCents(worst + debited);+ const suggestion = `gbrain migrate embeddings --to ${plan.to_model} --dim ${plan.to_dims} --max-cost-usd ${required.toFixed(2)} --yes`;+ const message = `Migration refused before any change (${EMBEDDING_BUDGET_BELOW_WORST_CASE}): the cap is $${cap} (--max-cost-usd), `+ + `but the worst-case authorization is $${ceilCents(worst).toFixed(2)}${debited > 0 ? ` on top of $${debited.toFixed(4)} already debited` : ''}. `+ + `No provider request was sent and no vector was dropped. Raise the cap to at least $${required.toFixed(2)}: ${suggestion}`;+ super(message);+ this.name = 'MigrationBudgetRefusal';+ this.details = { error: EMBEDDING_BUDGET_BELOW_WORST_CASE, message, cap_usd: cap, worst_case_usd: worst, debited_usd: debited,+ required_cap_usd: required, suggestion, docs: EMBEDDING_BUDGET_REFUSAL_DOCS };+ }+}+export async function assertMigrationLeases(engine: BrainEngine, locks: DbLockHandle[]) {if (!locks.length) return;const owned = await engine.executeRaw<{ id: string; token: string }>(`SELECT id,acquisition_token::text AS token@@ -13,7 +53,30 @@ export async function assertMigrationLeases(engine: BrainEngine, locks: DbLockHa}}-export async function authorizeMigrationBudget(engine: BrainEngine, plan: EmbeddingMigrationPlan, maxCostUsd?: number, locks: DbLockHandle[] = [], rerankerModel?: string) {+type MigrationBudget = NonNullable<MigrationState['budget']>;++function budgetIsValid(budget: MigrationBudget): boolean {+ return Number.isFinite(budget.max_cost_usd) && budget.max_cost_usd >= 0 && Number.isFinite(budget.debited_usd)+ && budget.debited_usd >= 0 && Number.isSafeInteger(budget.requests) && budget.requests >= 0+ && (budget.pending === undefined || (typeof budget.pending === 'object' && budget.pending !== null+ && Object.values(budget.pending).every(n => Number.isFinite(n) && n >= 0)))+ && (budget.overshoot_usd === undefined || Number.isFinite(budget.overshoot_usd) && budget.overshoot_usd >= 0);+}++async function lockMigrationState(tx: BrainEngine): Promise<MigrationState | null> {+ await tx.executeRaw('SELECT key FROM config WHERE key=$1 FOR UPDATE', [MIGRATION_STATE_KEY]);+ return (await readMigrationState(tx)).state;+}++/**+ * Durable migration authorization. Each provider attempt reserves its maximum+ * input size under the migration state row lock and settles, under the same+ * lock, to the provider's reported usage (#5680). A missing usage report or a+ * crash before settlement keeps the maximum; usage above the reservation+ * debits actual, records the overshoot and stops further dispatch. When a+ * worst case is supplied, a cap below it refuses before any state changes.+ */+export async function authorizeMigrationBudget(engine: BrainEngine, plan: EmbeddingMigrationPlan, maxCostUsd?: number, locks: DbLockHandle[] = [], rerankerModel?: string, worstCase?: MigrationWorstCase) {const prior = await readMigrationState(engine);if (prior.corrupt) {let legacy = false;@@ -31,14 +94,17 @@ export async function authorizeMigrationBudget(engine: BrainEngine, plan: Embedd};const old = state.budget;if (state.authorization_version && !old) throw new Error('Migration authorization is missing; automatic renewal refused');- if (old && (!Number.isFinite(old.max_cost_usd) || old.max_cost_usd < 0 || !Number.isFinite(old.debited_usd)- || old.debited_usd < 0 || !Number.isSafeInteger(old.requests) || old.requests < 0)) {- throw new Error('Migration authorization is corrupt; no request dispatched');- }+ if (old && !budgetIsValid(old)) throw new Error('Migration authorization is corrupt; no request dispatched');if (maxCostUsd !== undefined && (!Number.isFinite(maxCostUsd) || maxCostUsd < 0)) throw new Error('--max-cost-usd must be finite and nonnegative');if (!old && maxCostUsd === undefined) throw new Error('Paid work requires explicit --max-cost-usd. Preview with --dry-run; resume retains spent authorization.');- state.budget = { max_cost_usd: maxCostUsd ?? old!.max_cost_usd, debited_usd: old?.debited_usd ?? 0, requests: old?.requests ?? 0 };+ const cap = maxCostUsd ?? old!.max_cost_usd;+ const debited = old?.debited_usd ?? 0;+ if (worstCase?.usd != null && cap + USD_EPSILON < debited + worstCase.usd) throw new MigrationBudgetRefusal(plan, cap, worstCase.usd, debited);+ state.budget = old ? { ...old, max_cost_usd: cap } : { max_cost_usd: cap, debited_usd: 0, requests: 0 };+ if (maxCostUsd !== undefined) delete state.budget.halted;state.authorization_version = 1;+ const generation = (state.authorization_generation ?? 0) + 1;+ state.authorization_generation = generation;if (!same && prior.state) {state.retargeted_at = state.started_at;state.superseded = [...prior.state.superseded ?? [], { to_model: prior.state.to_model, to_dims: prior.state.to_dims, started_at: prior.state.started_at }];@@ -48,26 +114,59 @@ export async function authorizeMigrationBudget(engine: BrainEngine, plan: Embeddawait tx.setConfig(MIGRATION_STATE_KEY, JSON.stringify(state));});const pricingOverrides = await loadPricingOverrides(engine);+ const ownsBudget = (current: MigrationState | null): current is MigrationState & { budget: MigrationBudget } =>+ !!current?.budget && current.to_model === plan.to_model && current.to_dims === plan.to_dims+ && current.authorization_generation === generation;++ const settle = async (attempt: string, call: AIInvocation, kind: BudgetKind, usage: AIInvocationUsage | null) => {+ await engine.transaction(async tx => {+ const current = await lockMigrationState(tx);+ if (!ownsBudget(current) || !budgetIsValid(current.budget)) return;+ const reserved = current.budget.pending?.[attempt];+ if (reserved === undefined) return;+ const billable = usage && usage.inputTokens + (usage.cacheReadTokens ?? 0) + (usage.cacheWriteTokens ?? 0);+ const actual = usage ? usageCostUsd(call.model, billable!, usage.outputTokens, kind, pricingOverrides) : null;+ const { [attempt]: _settled, ...pending } = current.budget.pending!;+ current.budget.pending = pending;+ if (!Object.keys(pending).length) delete current.budget.pending;+ if (actual !== null && Number.isFinite(actual) && actual >= 0) {+ current.budget.debited_usd = Math.max(0, current.budget.debited_usd + actual - reserved);+ if (actual > reserved + USD_EPSILON) {+ current.budget.overshoot_usd = (current.budget.overshoot_usd ?? 0) + actual - reserved;+ current.budget.halted = true;+ }+ }+ await tx.setConfig(MIGRATION_STATE_KEY, JSON.stringify(current));+ });+ };+return async (call: AIInvocation): Promise<AIInvocationPermit> => {if (call.kind !== 'embedding' && call.kind !== 'rerank') throw new Error('Migration permits embedding and reranker probes only');if (call.model !== (call.kind === 'embedding' ? plan.to_model : rerankerModel)) throw new Error('Provider model differs from the authorized migration plan; no request dispatched');if (!Number.isSafeInteger(call.maxInputTokens) || call.maxInputTokens! <= 0) throw new Error('Provider request has no conservative input ceiling; no request dispatched');+ const kind: BudgetKind = call.kind === 'embedding' ? 'embed' : 'rerank';+ const reserved = reservationCostUsd(call.model, kind, call.maxInputTokens!, 0, pricingOverrides);+ if (reserved === null) {+ throw new Error(`Migration authorization cannot price ${call.model} (${kind}); no request dispatched. Declare an operator rate with gbrain config set pricing.overrides '{"${call.model}": <usd-per-1M-tokens>}'.`);+ }+ const attempt = randomUUID();await engine.transaction(async tx => {await assertMigrationLeases(tx, locks);- await tx.executeRaw('SELECT key FROM config WHERE key=$1 FOR UPDATE', [MIGRATION_STATE_KEY]);- const current = (await readMigrationState(tx)).state;- if (!current?.budget || current.to_model !== plan.to_model || current.to_dims !== plan.to_dims) throw new Error('Migration authorization changed; no request dispatched');- if (![current.budget.max_cost_usd, current.budget.debited_usd].every(n => Number.isFinite(n) && n >= 0)- || !Number.isSafeInteger(current.budget.requests) || current.budget.requests < 0) throw new Error('Migration authorization is corrupt; no request dispatched');- const tracker = new BudgetTracker({ label: 'embedding-migration', maxCostUsd: Math.max(0, current.budget.max_cost_usd-current.budget.debited_usd), pricingOverrides });- const estimate = { modelId: call.model, kind: call.kind === 'embedding' ? 'embed' as const : 'rerank' as const,- estimatedInputTokens: call.maxInputTokens!, maxOutputTokens: 0 };- tracker.reserve(estimate);- tracker.record({ modelId: call.model, kind: estimate.kind, inputTokens: call.maxInputTokens!, outputTokens: 0 });- current.budget.debited_usd += tracker.totalSpent;- current.budget.requests++;+ const current = await lockMigrationState(tx);+ if (!ownsBudget(current)) throw new Error('Migration authorization changed; no request dispatched');+ const budget = current.budget;+ if (!budgetIsValid(budget)) throw new Error('Migration authorization is corrupt; no request dispatched');+ if (budget.halted) {+ throw new Error(`Migration dispatch stopped: provider usage exceeded its reservation by $${(budget.overshoot_usd ?? 0).toFixed(6)} (recorded as overshoot). No request dispatched. Inspect gbrain migrate embeddings --status, then re-run with --max-cost-usd to renew dispatch.`);+ }+ if (budget.debited_usd + reserved > budget.max_cost_usd + USD_EPSILON) {+ throw new Error(`Migration authorization exhausted: this request needs up to $${reserved.toFixed(6)} at its maximum input size, but $${budget.debited_usd.toFixed(6)} of the $${budget.max_cost_usd} cap (--max-cost-usd) is already debited. No request dispatched. Raise --max-cost-usd to renew; prior debits remain.`);+ }+ budget.debited_usd += reserved;+ budget.requests++;+ budget.pending = { ...budget.pending, [attempt]: reserved };await tx.setConfig(MIGRATION_STATE_KEY, JSON.stringify(current));});- return { settle: async () => {} };+ return { settle: usage => settle(attempt, call, kind, usage) };};}diff --git a/src/core/embedding-migration-worst-case.ts b/src/core/embedding-migration-worst-case.tsnew file mode 100644index 0000000000..4e80dab162--- /dev/null+++ b/src/core/embedding-migration-worst-case.ts@@ -0,0 +1,172 @@+/**+ * #5680: the worst-case authorization of an embedding migration — the sum of+ * each planned provider request's maximum input, computed with the gateway's+ * own request plan (embed-batch-plan.ts) over the texts the run will send:+ * the provider probes, every stale chunk grouped per page, split as the+ * drain's oversize heal splits it (a split re-indexes the whole page, so every+ * healed chunk of that page is counted) and wrapped as the drain wraps it, the+ * chunks projection recovery and the chunkless heal will create (replayed+ * through the same projection preparation at the current chunk size then the+ * drain's target-size heal, and directly at the target size, keeping the+ * larger), every stale fact in the fact backfill's batches, the+ * completion smoke-check queries, and the reranker probe when the run+ * switches rerankers. Stale chunks include the drain's content drift (a+ * stored text hash that no longer matches the chunk text). The per-request+ * ceiling is additive over texts, and a provider token-limit rejection settles+ * unbilled, so the gateway's split of the same texts settles from the+ * parent's headroom.+ * An unpriced reranker is left out of `usd` and listed in `unpriced_models`:+ * its probe refuses without dispatch and the switch is reported as failed,+ * while the known embedding bound is still enforced.+ */+import type { BrainEngine } from './engine.ts';+import { embedRequestCeilings, rerankRequestMaxInputTokens } from './ai/embed-batch-plan.ts';+import { wrapChunkTextsForStoredMode } from './embedding-context.ts';+import type { ChunkInput, CRMode } from './types.ts';+import { readContentChunksEmbeddingDim } from './embedding-dim-check.ts';+import { falseStampPageWhere } from './embedding-invalidation.ts';+import { resolveActiveEmbeddingColumnFromEngine, quoteIdentifier } from './search/embedding-column.ts';+import { eligibleFactEmbedding, staleFactEmbedding } from './facts/embedding-identity.ts';+import { AUDIT_ROW_SOURCES } from './facts/audit-sources.ts';+import { EMBED_PROBE_TEXT } from './embed-stale.ts';+import { healOversizedChunks } from './embed-oversize-heal.ts';+import { resolveMaxChunkTokens } from './embedding-input-limit.ts';+import { preparePageProjection, readProjectionSnapshot } from './page-state/projections.ts';+import { QUARANTINE_FILTER_FRAGMENT } from './quarantine.ts';+import { loadPricingOverrides } from './budget/budget-tracker.ts';+import { usageCostUsd } from './budget/reservation-cost.ts';+import type { EmbeddingMigrationPlan } from './embedding-migration.ts';+import type { MigrationWorstCase } from './embedding-migration-budget.ts';++export const MIGRATION_PROBE_TEXT = 'gbrain embedding migration probe';+export const RERANKER_PROBE = {+ query: 'gbrain reranker migration probe',+ documents: ['gbrain reranker migration probe document a', 'gbrain reranker migration probe document b'],+} as const;+/** The drain's projection-readiness probe and its signature-drift probe. */+const DRAIN_PROBES = 2;+/** verifySearchRoundTrip embeds up to 3 sample queries of at most 160 UTF-16 units (≤ 3 UTF-8 bytes each). */+const SMOKE_QUERIES = 3;+const SMOKE_QUERY_MAX_TOKENS = 160 * 3;+/** embedStaleFacts' default batch size. */+const FACT_BATCH = 100;+const SCAN_PAGE = 2000;++interface ChunkRow { page_id: number; chunk_index: number; chunk_text: string; chunk_source: string | null; title: string | null; contextual_retrieval_mode: CRMode | null; stale: boolean }+interface FactRow { id: string; source_id: string; fact: string }+interface ChunkSizes { current: number; target: number }++/** Pages whose chunks are (re)built before embedding: unsealed projections, and contentful pages with no chunks. */+const REPROJECTED_PAGE = `(p.text_projection_revision IS DISTINCT FROM p.knowledge_revision+ OR ((p.compiled_truth <> '' OR p.timeline <> '') AND ${QUARANTINE_FILTER_FRAGMENT}+ AND NOT EXISTS (SELECT 1 FROM content_chunks c WHERE c.page_id=p.id)))`;++/** The drain's whole-page oversize split; it reads only text, source and token count, which the planner's rows carry. */+const healAtTarget = (chunks: ReadonlyArray<Pick<ChunkInput, 'chunk_index' | 'chunk_text'> & { chunk_source?: string | null }>, sizes: ChunkSizes) =>+ healOversizedChunks(chunks as unknown as Parameters<typeof healOversizedChunks>[0], sizes.target);++async function eachReprojectedPage(engine: BrainEngine, sizes: ChunkSizes, weigh: (texts: string[]) => number, visit: (texts: string[]) => void): Promise<void> {+ let after = 0;+ for (;;) {+ const rows = await engine.executeRaw<{ id: number; slug: string; source_id: string }>(`SELECT p.id, p.slug, p.source_id+ FROM pages p JOIN sources s ON s.id=p.source_id+ WHERE NOT s.archived AND p.deleted_at IS NULL AND NOT (COALESCE(p.frontmatter,'{}'::jsonb) ? 'embed_skip')+ AND ${REPROJECTED_PAGE} AND p.id > $1+ ORDER BY p.id LIMIT ${SCAN_PAGE}`, [after]);+ for (const row of rows) {+ const candidates: string[][] = [];+ for (const limit of new Set([sizes.current, sizes.target])) {+ const prepared = await readProjectionSnapshot(engine, row.slug, row.source_id, { allowUnsealed: true, maxChunkTokens: limit });+ if (!prepared) continue;+ try { candidates.push(wrapChunkTextsForStoredMode(prepared.snapshot.page, healAtTarget((await preparePageProjection(prepared)).chunks, sizes).chunks)); }+ catch { continue; }+ }+ if (candidates.length) visit(candidates.reduce((a, b) => weigh(b) > weigh(a) ? b : a));+ }+ if (rows.length < SCAN_PAGE) break;+ after = rows[rows.length - 1].id;+ }+}++async function eachStalePage(engine: BrainEngine, plan: EmbeddingMigrationPlan, sizes: ChunkSizes, visit: (texts: string[]) => void): Promise<void> {+ const column = (await readContentChunksEmbeddingDim(engine)).exists+ ? quoteIdentifier((await resolveActiveEmbeddingColumnFromEngine(engine, { fallbackToLegacy: true })).name)+ : null;+ const staleChunk = (c: string) => column === null ? 'true' : `(${c}.${column} IS NULL OR p.embedding_signature IS NULL OR p.embedding_signature <> $1+ OR (${c}.embedded_text_hash IS NOT NULL AND ${c}.embedded_text_hash <> md5(${c}.chunk_text))+ OR (${c}.${column} IS NOT NULL AND ${falseStampPageWhere(column, 1, 2)}))`;+ const livePage = column === null ? 'true' : `p.deleted_at IS NULL AND NOT (COALESCE(p.frontmatter,'{}'::jsonb) ? 'embed_skip')`;+ let page: ChunkRow[] = [];+ const flush = () => {+ if (!page.length) return;+ const healed = healAtTarget(page, sizes);+ visit(wrapChunkTextsForStoredMode(page[0], healed.changed ? healed.chunks : page.filter(row => row.stale)));+ page = [];+ };+ let after = { page: 0, chunk: -1 };+ for (;;) {+ const rows = await engine.executeRaw<ChunkRow>(`SELECT cc.page_id, cc.chunk_index, cc.chunk_text, cc.chunk_source,+ p.title, p.contextual_retrieval_mode, ${staleChunk('cc')} AS stale+ FROM content_chunks cc JOIN pages p ON p.id=cc.page_id+ WHERE ($1::text IS NOT NULL AND $2::text IS NOT NULL) AND ${livePage} AND NOT ${REPROJECTED_PAGE}+ AND EXISTS (SELECT 1 FROM content_chunks cs WHERE cs.page_id=p.id AND ${staleChunk('cs')})+ AND (cc.page_id > $3 OR (cc.page_id = $3 AND cc.chunk_index > $4))+ ORDER BY cc.page_id, cc.chunk_index LIMIT ${SCAN_PAGE}`,+ [`${plan.to_model}:${plan.to_dims}`, plan.to_model, after.page, after.chunk]);+ for (const row of rows) {+ if (page.length && page[0].page_id !== row.page_id) flush();+ page.push(row);+ }+ if (rows.length < SCAN_PAGE) break;+ after = { page: rows[rows.length - 1].page_id, chunk: rows[rows.length - 1].chunk_index };+ }+ flush();+}++async function eachStaleFactBatch(engine: BrainEngine, plan: EmbeddingMigrationPlan, visit: (texts: string[]) => void): Promise<void> {+ let batch: FactRow[] = [];+ const flush = () => { if (batch.length) visit(batch.map(row => row.fact)); batch = []; };+ let after = { source: '', id: '0' };+ for (;;) {+ const rows = await engine.executeRaw<FactRow>(`SELECT f.id::text AS id, f.source_id, f.fact FROM facts f+ WHERE ($1::text IS NULL OR f.source_id=$1) AND ${eligibleFactEmbedding} AND ${staleFactEmbedding}+ AND (f.source_id > $5 OR (f.source_id = $5 AND f.id > $6::bigint))+ ORDER BY f.source_id, f.id LIMIT ${SCAN_PAGE}`,+ [null, [...AUDIT_ROW_SOURCES], plan.to_model, plan.to_dims, after.source, after.id]);+ for (const row of rows) {+ if (batch.length && (batch[0].source_id !== row.source_id || batch.length === FACT_BATCH)) flush();+ batch.push(row);+ }+ if (rows.length < SCAN_PAGE) break;+ after = { source: rows[rows.length - 1].source_id, id: rows[rows.length - 1].id };+ }+ flush();+}++export async function planMigrationWorstCase(engine: BrainEngine, plan: EmbeddingMigrationPlan, opts: { rerankerModel?: string } = {}): Promise<MigrationWorstCase> {+ const envCap = Number.parseInt(process.env.GBRAIN_EMBED_MAX_BATCH_TOKENS ?? '', 10);+ const ceilings: number[] = [];+ const ceilingsOf = (texts: string[]) => texts.length+ ? embedRequestCeilings(texts, plan.to_model, Number.isFinite(envCap) && envCap > 0 ? envCap : undefined) : [];+ const add = (texts: string[]) => { ceilings.push(...ceilingsOf(texts)); };+ add([MIGRATION_PROBE_TEXT]);+ for (let i = 0; i < DRAIN_PROBES; i++) add([EMBED_PROBE_TEXT]);+ for (let i = 0; i < SMOKE_QUERIES; i++) ceilings.push(SMOKE_QUERY_MAX_TOKENS);+ const target = resolveMaxChunkTokens(process.env, plan.to_model);+ const sizes = { current: resolveMaxChunkTokens(), target };+ await eachStalePage(engine, plan, sizes, add);+ await eachReprojectedPage(engine, sizes, texts => ceilingsOf(texts).reduce((sum, n) => sum + n, 0), add);+ await eachStaleFactBatch(engine, plan, add);+ const embedTokens = ceilings.reduce((sum, n) => sum + n, 0);+ const rerankTokens = opts.rerankerModel ? rerankRequestMaxInputTokens(RERANKER_PROBE.query, RERANKER_PROBE.documents) : 0;+ const overrides = await loadPricingOverrides(engine);+ const embedUsd = usageCostUsd(plan.to_model, embedTokens, 0, 'embed', overrides);+ const rerankUsd = opts.rerankerModel ? usageCostUsd(opts.rerankerModel, rerankTokens, 0, 'rerank', overrides) : 0;+ const unpriced = [...(embedUsd === null ? [plan.to_model] : []), ...(rerankUsd === null ? [opts.rerankerModel!] : [])];+ return {+ requests: ceilings.length + (opts.rerankerModel ? 1 : 0),+ input_tokens: embedTokens + rerankTokens,+ usd: embedUsd === null ? null : embedUsd + (rerankUsd ?? 0),+ unpriced_models: unpriced,+ };+}diff --git a/src/core/embedding-migration.ts b/src/core/embedding-migration.tsindex 98d8c349e1..be0b5d235a 100644--- a/src/core/embedding-migration.ts+++ b/src/core/embedding-migration.ts@@ -325,7 +325,8 @@ export const MIGRATION_COMPLETED_KEY = 'embedding_migration.completed';export interface MigrationState {authorization_version?: 1;- budget?: { max_cost_usd: number; debited_usd: number; requests: number };+ authorization_generation?: number;+ budget?: { max_cost_usd: number; debited_usd: number; requests: number; generation?: number; pending?: Record<string, number>; overshoot_usd?: number; halted?: boolean };/** Marker schema version. Absent = v1 (pre-hardening). */version?: 2;companion_vectors_invalidated?: boolean;@@ -1171,6 +1172,7 @@ export async function applyEmbeddingMigration(state.companion_vectors_invalidated = prior.state.companion_vectors_invalidated;state.budget = prior.state.budget;state.authorization_version = prior.state.authorization_version;+ state.authorization_generation = prior.state.authorization_generation;if (prior.state.retargeted_at) state.retargeted_at = prior.state.retargeted_at;if (prior.state.superseded) state.superseded = prior.state.superseded;} else if (prior.state) {diff --git a/src/core/embedding.ts b/src/core/embedding.tsindex c8eb48656e..656f66a1ef 100644--- a/src/core/embedding.ts+++ b/src/core/embedding.ts@@ -13,6 +13,7 @@ import {getEmbeddingDimensions as gatewayGetDims,} from './ai/gateway.ts';import { lookupEmbeddingPrice } from './embedding-pricing.ts';+import { isEmbeddingZeroNormError, mergeZeroNormErrors, type EmbeddingZeroNormError } from './ai/embedding-guard.ts';// v0.27.1: re-export multimodal embedding so callers can pull both text and// image embedding APIs from `src/core/embedding`. import-image-file consumes@@ -91,14 +92,22 @@ export async function embedBatch(if (texts.length <= BATCH_SIZE && !options.onBatchComplete) {return gatewayEmbed(texts, gwOpts);}- const results: Float32Array[] = [];+ // #4616: a degenerate vector fails only its item; later slices still run and+ // the merged refusal carries every usable vector aligned with `texts`.+ const slices: { offset: number; vectors: Float32Array[] | null; error?: EmbeddingZeroNormError }[] = [];for (let i = 0; i < texts.length; i += BATCH_SIZE) {const slice = texts.slice(i, i + BATCH_SIZE);- const out = await gatewayEmbed(slice, gwOpts);- results.push(...out);- options.onBatchComplete?.(results.length, texts.length);+ try {+ slices.push({ offset: i, vectors: await gatewayEmbed(slice, gwOpts) });+ } catch (error) {+ if (!isEmbeddingZeroNormError(error)) throw error;+ slices.push({ offset: i, vectors: null, error });+ }+ options.onBatchComplete?.(Math.min(i + BATCH_SIZE, texts.length), texts.length);}- return results;+ const refused = mergeZeroNormErrors(texts.length, slices, slices.find(s => s.error)?.error?.model ?? '');+ if (refused) throw refused;+ return slices.flatMap(s => s.vectors ?? []);}/** Currently-configured embedding model (short form without provider prefix). */diff --git a/src/core/facts/fence-write.ts b/src/core/facts/fence-write.tsindex 087eb7a7c0..312ff53779 100644--- a/src/core/facts/fence-write.ts+++ b/src/core/facts/fence-write.ts@@ -53,7 +53,7 @@ import { contentHash } from '../utils.ts';import { extractFactsFromFenceText } from './extract-from-fence.ts';import { logStubGuardEvent } from './stub-guard-audit.ts';import { isFactWithdrawn } from './withdrawal.ts';-import { assertUnmanagedCanonicalWriter } from '../persistence/maintenance.ts';+import { managedPersistenceEnabled } from '../persistence/ownership.ts';/** Resolved source binding for the entity page. */export interface FenceTarget {@@ -285,7 +285,19 @@ export async function writeFactsToFence(target: FenceTarget,facts: FenceInputFact[],): Promise<FenceWriteResult> {- await assertUnmanagedCanonicalWriter(engine, 'direct facts fence write');+ if (await managedPersistenceEnabled(engine)) {+ // The coordinator owns the canonical file on a managed brain: publish the+ // fence rows through its fact intent instead of editing the file here.+ const kept: FenceInputFact[] = [];+ for (const f of facts) {+ if (!await isFactWithdrawn(engine, target.sourceId, f.visibility, f.fact, target.slug)) kept.push(f);+ }+ const withdrawnSkipped = facts.length - kept.length ? { withdrawnSkipped: facts.length - kept.length } : {};+ if (!kept.length) return { inserted: 0, ids: [], ...withdrawnSkipped };+ const { publishManagedEntityFacts } = await import('./managed-fact-write.ts');+ const { inserted, ids } = await publishManagedEntityFacts(engine, target.sourceId, target.slug, kept);+ return { inserted, ids, ...withdrawnSkipped };+ }if (target.localPath === null) {return { inserted: 0, ids: [], legacyFallback: true };}diff --git a/src/core/facts/managed-fact-write.ts b/src/core/facts/managed-fact-write.tsnew file mode 100644index 0000000000..18659d4c46--- /dev/null+++ b/src/core/facts/managed-fact-write.ts@@ -0,0 +1,53 @@+import type { BrainEngine } from '../engine.ts';+import type { FactsBackstopCtx } from './backstop.ts';+import type { FenceInputFact } from './fence-write.ts';+import type { ExtractedFact } from './extract.ts';+import { managedPersistenceEnabled } from '../persistence/ownership.ts';+import { prepareManagedFactsSession, publishManagedFacts, resolveManagedFactsEmbedding, resumeManagedFacts } from '../persistence/facts-maintenance.ts';++function factsContext(engine: BrainEngine, sourceId: string, requestIntent: Record<string, unknown>, sessionId: string | null = null): FactsBackstopCtx {+ return { engine, sourceId, sessionId, source: 'mcp:extract_facts', remote: false, requestIntent };+}++/** Validates managed fact authority and ownership before a caller spends on a model. No-op when unmanaged. */+export async function managedFactWritePreflight(engine: BrainEngine, sourceId: string): Promise<void> {+ if (!await managedPersistenceEnabled(engine)) return;+ await prepareManagedFactsSession(factsContext(engine, sourceId, { preflight: 'managed_fact_write' }), { turnText: '' });+}++/**+ * Managed brains append entity facts through the coordinator's fact intent+ * (managed_facts_entity): the fence row, its index row and the canonical file+ * publish together, deduplicated and withdrawal-checked at publication. An+ * entity with no live page lands database-only, like the legacy stub guard.+ * The request identity derives from the write itself, so a retried job+ * replays its receipt. Returned ids follow input order.+ */+export async function publishManagedEntityFacts(engine: BrainEngine, sourceId: string, entity: string | null,+ facts: FenceInputFact[], options: { supersede?: boolean } = {}): Promise<{ inserted: number; duplicate: number; superseded: number; ids: number[] }> {+ const out = { inserted: 0, duplicate: 0, superseded: 0, ids: new Array<number>(facts.length) };+ for (const visibility of ['private', 'world'] as const) {+ const positions = facts.flatMap((fact, i) => fact.visibility === visibility ? [i] : []);+ if (!positions.length) continue;+ const group = positions.map(i => facts[i]);+ const ctx = factsContext(engine, sourceId, { writer: 'fence_write', entity, visibility, supersede: options.supersede === true,+ facts: group.map(f => [f.fact, f.kind, f.source, f.notability, f.confidence ?? 1, f.validFrom?.toISOString() ?? null,+ f.validUntil?.toISOString() ?? null, f.sessionId, f.context ?? null]) }, group[0].sessionId);+ const session = (await prepareManagedFactsSession(ctx, { turnText: '' }))!;+ let result = await resumeManagedFacts(engine, session);+ if (!result) {+ const signature = await resolveManagedFactsEmbedding(engine, session.config);+ session.embedding = signature;+ const extracted: ExtractedFact[] = group.map(f => ({ fact: f.fact, kind: f.kind, entity_slug: entity, visibility,+ notability: f.notability, source: f.source, context: f.context ?? null, confidence: f.confidence ?? 1,+ valid_from: f.validFrom, valid_until: f.validUntil ?? null, source_session: f.sessionId,+ embedding: signature && f.embedding_model === signature.model && f.embedding?.length === signature.dimensions ? f.embedding : null }));+ result = await publishManagedFacts(engine, session, ctx, extracted, visibility, undefined, { supersede: options.supersede, explicitContext: true });+ }+ out.inserted += result.inserted;+ out.duplicate += result.duplicate;+ out.superseded += result.superseded;+ positions.forEach((position, i) => { out.ids[position] = result!.fact_ids[i]; });+ }+ return out;+}diff --git a/src/core/facts/write-single.ts b/src/core/facts/write-single.tsindex a290dafe7b..c76dba294b 100644--- a/src/core/facts/write-single.ts+++ b/src/core/facts/write-single.ts@@ -76,8 +76,8 @@ export async function writeSingleFact(sourceId: string,input: SingleFactInput,): Promise<SingleFactResult> {- const { assertCoordinatedWrite } = await import('../persistence/context.ts');- await assertCoordinatedWrite(engine, sourceId);+ const { managedPersistenceEnabled } = await import('../persistence/ownership.ts');+ const managed = await managedPersistenceEnabled(engine);const { resolveEntitySlugWithSource } = await import('../entities/resolve.ts');const { cosineSimilarity } = await import('./classify.ts');@@ -125,6 +125,18 @@ export async function writeSingleFact(degradedDedup = true;}+ if (managed) {+ // The coordinator's fact intent owns dedup, supersession, the fence row and+ // the file on a managed brain; the legacy direct writes stay unmanaged.+ const { publishManagedEntityFacts } = await import('./managed-fact-write.ts');+ const written = await publishManagedEntityFacts(engine, sourceId, resolvedSlug, [{ fact: factText, kind, notability: 'medium',+ source: input.provenance, visibility, confidence: input.confidence ?? 1.0, validFrom: new Date(), validUntil,+ embedding, embedding_model: embeddingModel, sessionId: input.sessionId ?? null }], { supersede: true });+ const [stored] = await engine.executeRaw<{ entity_slug: string | null }>('SELECT entity_slug FROM facts WHERE id=$1', [written.ids[0]]);+ return { id: written.ids[0], status: written.superseded ? 'superseded' : written.inserted ? 'inserted' : 'duplicate', entity_slug: stored?.entity_slug ?? null,+ valid_until: validUntil, degraded_dedup: degradedDedup };+ }+// Dedup + supersession decision (same candidates + threshold as the pipeline).let supersedeId: number | null = null;if (resolvedSlug && embedding) {diff --git a/src/core/github-source-config.ts b/src/core/github-source-config.tsnew file mode 100644index 0000000000..f2ce9753f2--- /dev/null+++ b/src/core/github-source-config.ts@@ -0,0 +1,54 @@+/** Parse a GitHub connector source's `sources.config`. Dependency-light so migrations and the connector identity can import it. */+import type { GitHubSourceConfig, GitHubAppConfig } from './github-source.ts';++/** True for "owner/name" with no dot segments, slashes, or empty parts. */+export function isValidRepoName(repo: string): boolean {+ if (repo.length === 0 || repo.length > 200) return false;+ if (repo.startsWith('/') || repo.endsWith('/')) return false;+ const parts = repo.split('/');+ if (parts.length !== 2) return false;+ return parts.every((p) => p.length > 0 && p !== '.' && p !== '..' && /^[\w.-]+$/.test(p));+}++export function parseGitHubSourceConfig(+ config: Record<string, unknown>,+ fallbackDir: string,+): GitHubSourceConfig {+ const tokenEnv =+ typeof config.gh_token_env === 'string' && config.gh_token_env.length > 0+ ? config.gh_token_env+ : 'GH_TOKEN';+ const app: GitHubAppConfig | null =+ typeof config.gh_app_id === 'number' &&+ Number.isInteger(config.gh_app_id) &&+ typeof config.gh_app_pem_path === 'string' &&+ config.gh_app_pem_path.length > 0+ ? {+ appId: config.gh_app_id,+ pemPath: config.gh_app_pem_path,+ installId:+ typeof config.gh_app_install_id === 'number' &&+ Number.isInteger(config.gh_app_install_id) &&+ config.gh_app_install_id > 0+ ? config.gh_app_install_id+ : undefined,+ }+ : null;+ // gh_handle / gh_involvement are reserved config keys: tolerated when+ // present but ignored (the involvement expansion is not implemented).+ const scope = config.gh_scope === 'repos' ? 'repos' : 'auto';+ // Repo names are case-insensitive on GitHub; everything downstream (page+ // paths, state file, webhook matching, slugs) keys on the lowercase form.+ const repos =+ typeof config.gh_repos === 'string'+ ? config.gh_repos+ .split(',')+ .map((s) => s.trim().toLowerCase())+ .filter(isValidRepoName)+ : [];+ const dir =+ typeof config.gh_dir === 'string' && config.gh_dir.length > 0+ ? config.gh_dir+ : fallbackDir;+ return { tokenEnv, app, scope, repos, dir };+}diff --git a/src/core/github-source.ts b/src/core/github-source.tsindex 3d3a1e3f89..bf73cd7691 100644--- a/src/core/github-source.ts+++ b/src/core/github-source.ts@@ -1,4 +1,7 @@-import { withConnectorSync, rethrowConnectorWriteError, type ManagedConnectorSync } from './persistence/connector-sync.ts';+import { withConnectorSync, rethrowConnectorWriteError, pendingConnectorResult, type ManagedConnectorSync } from './persistence/connector-sync.ts';+import { resolveGitHubAccount } from './persistence/connector-account.ts';+import { isValidRepoName } from './github-source-config.ts';+export { isValidRepoName, parseGitHubSourceConfig } from './github-source-config.ts';import { slugifyPath } from './sync.ts';/*** github-source — GitHub issues/PR sync for the `github` source kind.@@ -95,58 +98,6 @@ export function isGitHubSourceConfig(config: Record<string, unknown>): boolean {return config.kind === GH_KIND;}-/** True for "owner/name" with no dot segments, slashes, or empty parts. */-export function isValidRepoName(repo: string): boolean {- if (repo.length === 0 || repo.length > 200) return false;- if (repo.startsWith('/') || repo.endsWith('/')) return false;- const parts = repo.split('/');- if (parts.length !== 2) return false;- return parts.every((p) => p.length > 0 && p !== '.' && p !== '..' && /^[\w.-]+$/.test(p));-}--export function parseGitHubSourceConfig(- config: Record<string, unknown>,- fallbackDir: string,-): GitHubSourceConfig {- const tokenEnv =- typeof config.gh_token_env === 'string' && config.gh_token_env.length > 0- ? config.gh_token_env- : 'GH_TOKEN';- const app: GitHubAppConfig | null =- typeof config.gh_app_id === 'number' &&- Number.isInteger(config.gh_app_id) &&- typeof config.gh_app_pem_path === 'string' &&- config.gh_app_pem_path.length > 0- ? {- appId: config.gh_app_id,- pemPath: config.gh_app_pem_path,- installId:- typeof config.gh_app_install_id === 'number' &&- Number.isInteger(config.gh_app_install_id) &&- config.gh_app_install_id > 0- ? config.gh_app_install_id- : undefined,- }- : null;- // gh_handle / gh_involvement are reserved config keys: tolerated when- // present but ignored (the involvement expansion is not implemented).- const scope = config.gh_scope === 'repos' ? 'repos' : 'auto';- // Repo names are case-insensitive on GitHub; everything downstream (page- // paths, state file, webhook matching, slugs) keys on the lowercase form.- const repos =- typeof config.gh_repos === 'string'- ? config.gh_repos- .split(',')- .map((s) => s.trim().toLowerCase())- .filter(isValidRepoName)- : [];- const dir =- typeof config.gh_dir === 'string' && config.gh_dir.length > 0- ? config.gh_dir- : fallbackDir;- return { tokenEnv, app, scope, repos, dir };-}-export function gitHubStateFile(dir: string): string {return join(dir, '.github-source.json');}@@ -207,6 +158,7 @@ function b64url(input: string): string {interface MintedInstallationToken {token: string;expiresAt: number; // epoch ms+ installationId: number;}/**@@ -247,12 +199,13 @@ export async function mintAppInstallationToken(});if (!res.ok) throw new Error(`GitHub App access_tokens HTTP ${res.status}`);const body = (await res.json()) as { token: string; expires_at: string };- return { token: body.token, expiresAt: Date.parse(body.expires_at) };+ return { token: body.token, expiresAt: Date.parse(body.expires_at), installationId: installId };}/** Caches a minted installation token and refreshes it before expiry. */export class AppTokenProvider implements GitHubTokenProvider {private cached: MintedInstallationToken | null = null;+ get installationId(): number | null { return this.cached?.installationId ?? null; }constructor(private readonly app: GitHubAppConfig,@@ -264,8 +217,9 @@ export class AppTokenProvider implements GitHubTokenProvider {return this.refresh();}+ // A refresh re-mints for the installation first resolved (and pinned), never a newly discovered one.async refresh(): Promise<string> {- this.cached = await mintAppInstallationToken(this.app, this.fetchImpl);+ this.cached = await mintAppInstallationToken({ ...this.app, installId: this.app.installId ?? this.cached?.installationId }, this.fetchImpl);return this.cached.token;}}@@ -1189,7 +1143,7 @@ export async function runGitHubSync(fetchImpl?: FetchImpl,): Promise<import('../commands/sync.ts').SyncResult> {return withConnectorSync(engine, sourceId, 'github', cfg, opts,- (managed, options) => runGitHubSyncInner(engine, sourceId, cfg, options, managed, fetchImpl));+ (managed, options) => runGitHubSyncInner(engine, sourceId, cfg, options, managed, fetchImpl), pendingConnectorResult);}async function runGitHubSyncInner(engine: BrainEngine, sourceId: string, cfg: GitHubSourceConfig, opts: SyncOpts,@@ -1203,9 +1157,9 @@ async function runGitHubSyncInner(engine: BrainEngine, sourceId: string, cfg: Gi`GitHub source "${sourceId}" has no token. Set ${cfg.tokenEnv} in the environment or configure a GitHub App (gh_app_id + gh_app_pem_path).`,);}- const client = cfg.app- ? new GitHubClient(new AppTokenProvider(cfg.app, fetchImpl ?? fetch), fetchImpl)- : new GitHubClient(process.env[cfg.tokenEnv] ?? '', fetchImpl);+ const appTokens = cfg.app ? new AppTokenProvider(cfg.app, fetchImpl ?? fetch) : null;+ const client = new GitHubClient(appTokens ?? process.env[cfg.tokenEnv] ?? '', fetchImpl);+ if (managed) await managed.assertAccount(await resolveGitHubAccount(cfg, client, appTokens, opts.signal)); // #5686 installation/login pinconst deps: GitHubSyncDeps = { engine, sourceId, cfg, opts, client, managed };const summary: GitHubSyncSummary = {status: 'synced',diff --git a/src/core/google/attachment-backfill.ts b/src/core/google/attachment-backfill.tsindex dd80707208..efe1d5b72a 100644--- a/src/core/google/attachment-backfill.ts+++ b/src/core/google/attachment-backfill.ts@@ -34,6 +34,7 @@ export async function runGoogleAttachmentBackfill(engine: BrainEngine, sourceId:if (profile.emailAddress?.toLowerCase() !== cfg.account) {throw new OperationError('source_changed', 'The Gmail credential belongs to a different account. No metadata was changed.');}+ await managed.assertAccount({ kind: 'google', email: cfg.account });const state = managed.state<GoogleSourceState>({ gmail_history_id: null, gmail_backfill_floor_ms: null,gmail_backfill_done: false, gmail_newest_ms: null, calendar_sync_token: null, contacts_sync_token: null, last_full_at: null });return backfillGmailAttachments(engine, managed, gmail, state, cfg.account, opts.limit, options.signal);diff --git a/src/core/google/google-source.ts b/src/core/google/google-source.tsindex bd7b0062b4..718488446d 100644--- a/src/core/google/google-source.ts+++ b/src/core/google/google-source.ts@@ -1,4 +1,5 @@-import { withConnectorSync, rethrowConnectorWriteError, type ManagedConnectorSync } from '../persistence/connector-sync.ts';+import { withConnectorSync, rethrowConnectorWriteError, pendingConnectorResult, type ManagedConnectorSync } from '../persistence/connector-sync.ts';+import { resolveGoogleAccount } from '../persistence/connector-account.ts';/*** google-source — Gmail/Calendar/Contacts sync for the `google` source kind.*@@ -64,6 +65,8 @@ import { LOOPS_EXTRACT_WINDOW_DAYS, loopExtractionEligibility } from './loops-exexport type { GoogleSourceConfig } from './types.ts';export { runGoogleAttachmentBackfill } from './attachment-backfill.ts';+export { parseGoogleSourceConfig } from './source-config.ts';+import { parseGoogleSourceConfig } from './source-config.ts';// ── Config ───────────────────────────────────────────────────────────────────@@ -73,49 +76,6 @@ export function isGoogleSourceConfig(config: Record<string, unknown>): boolean {return config.kind === G_KIND;}-export function parseGoogleSourceConfig(- config: Record<string, unknown>,- fallbackDir: string,-): GoogleSourceConfig {- const account =- typeof config.g_account === 'string' ? config.g_account.trim().toLowerCase() : '';- const services =- typeof config.g_services === 'string'- ? (config.g_services- .split(',')- .map((s) => s.trim().toLowerCase())- .filter((s): s is GoogleService => (ALL_GOOGLE_SERVICES as string[]).includes(s)))- : [...ALL_GOOGLE_SERVICES];- const historyDays =- typeof config.g_history_days === 'number' &&- Number.isFinite(config.g_history_days) &&- config.g_history_days > 0- ? Math.min(3650, Math.floor(config.g_history_days))- : 90;- const calendarId =- typeof config.g_calendar_id === 'string' && config.g_calendar_id.trim().length > 0- ? config.g_calendar_id.trim()- : DEFAULT_CALENDAR_ID;- const dir =- typeof config.g_dir === 'string' && config.g_dir.length > 0 ? config.g_dir : fallbackDir;- const access =- config.g_access === 'command' || config.g_access === 'env' ? config.g_access : 'vault';- return {- account,- services: services.length > 0 ? services : [...ALL_GOOGLE_SERVICES],- historyDays,- calendarId,- dir,- access,- ...(typeof config.g_token_command === 'string' && config.g_token_command.trim()- ? { tokenCommand: config.g_token_command }- : {}),- ...(typeof config.g_token_env === 'string' && config.g_token_env.trim()- ? { tokenEnv: config.g_token_env }- : {}),- };-}-// ── State ────────────────────────────────────────────────────────────────────export function googleStateFile(dir: string): string {@@ -1004,7 +964,7 @@ export async function runGoogleSync(vaultOverride?: CredentialVault,): Promise<SyncResult> {return withConnectorSync(engine, sourceId, 'google', cfg, opts,- (managed, options) => runGoogleSyncInner(engine, sourceId, cfg, options, managed, fetchImpl, vaultOverride));+ (managed, options) => runGoogleSyncInner(engine, sourceId, cfg, options, managed, fetchImpl, vaultOverride), pendingConnectorResult);}async function runGoogleSyncInner(engine: BrainEngine, sourceId: string, cfg: GoogleSourceConfig, opts: SyncOpts,@@ -1102,6 +1062,11 @@ async function runGoogleSyncInner(engine: BrainEngine, sourceId: string, cfg: Golog(new CredentialError('scope_missing', undefined, `services without grant: ${missingServices.join(', ')}`).toHuman());}const activeServices = grantedScopes.length > 0 ? grantedServices : cfg.services;+ // #5686: every enabled service reads as the pinned account; checked before any service runs.+ if (managed) {+ const email = await resolveGoogleAccount({ gmail, calendar, people }, activeServices, opts.signal);+ await managed.assertAccount(email ? { kind: 'google', email } : null);+ }const state = managed ? managed.state(emptyState()) : readGoogleState(cfg.dir);const firstRun = !state.gmail_backfill_done && state.gmail_history_id === null;diff --git a/src/core/google/loops-extract.ts b/src/core/google/loops-extract.tsindex a4dba21577..94dba40b6f 100644--- a/src/core/google/loops-extract.ts+++ b/src/core/google/loops-extract.ts@@ -25,7 +25,7 @@*/import type { BrainEngine } from '../engine.ts';-import { assertUnmanagedCanonicalWriter } from '../persistence/maintenance.ts';+import { managedFactWritePreflight } from '../facts/managed-fact-write.ts';import { loadSuppressions, upsertOpenLoop, type LoopType } from '../loops/loops-store.ts';import { isCalendarSystemMail, isNoiseSender, sha8 } from './google-render.ts';import { bareAddress, type GmailMessageMeta, type GmailThreadData } from './types.ts';@@ -323,7 +323,9 @@ export async function runLoopsExtract(return { ...empty, reason: 'suppressed' };}- await assertUnmanagedCanonicalWriter(engine, 'Google loop extraction');+ // Managed brains publish the commitment fact through the coordinator; its+ // authority and canonical owner are checked here, before the model call.+ await managedFactWritePreflight(engine, payload.sourceId);const { isAvailable, chat } = await import('../ai/gateway.ts');// Keyless install / provider outage: NOT a skip. The sweep already refuses to// enqueue while chat is unavailable; a job that reaches here mid-outage mustdiff --git a/src/core/google/source-config.ts b/src/core/google/source-config.tsnew file mode 100644index 0000000000..8a8b2383a3--- /dev/null+++ b/src/core/google/source-config.ts@@ -0,0 +1,45 @@+/** Parse a Google connector source's `sources.config`. Dependency-light so migrations and the connector identity can import it. */+import { ALL_GOOGLE_SERVICES, DEFAULT_CALENDAR_ID, type GoogleService, type GoogleSourceConfig } from './types.ts';++export function parseGoogleSourceConfig(+ config: Record<string, unknown>,+ fallbackDir: string,+): GoogleSourceConfig {+ const account =+ typeof config.g_account === 'string' ? config.g_account.trim().toLowerCase() : '';+ const services =+ typeof config.g_services === 'string'+ ? (config.g_services+ .split(',')+ .map((s) => s.trim().toLowerCase())+ .filter((s): s is GoogleService => (ALL_GOOGLE_SERVICES as string[]).includes(s)))+ : [...ALL_GOOGLE_SERVICES];+ const historyDays =+ typeof config.g_history_days === 'number' &&+ Number.isFinite(config.g_history_days) &&+ config.g_history_days > 0+ ? Math.min(3650, Math.floor(config.g_history_days))+ : 90;+ const calendarId =+ typeof config.g_calendar_id === 'string' && config.g_calendar_id.trim().length > 0+ ? config.g_calendar_id.trim()+ : DEFAULT_CALENDAR_ID;+ const dir =+ typeof config.g_dir === 'string' && config.g_dir.length > 0 ? config.g_dir : fallbackDir;+ const access =+ config.g_access === 'command' || config.g_access === 'env' ? config.g_access : 'vault';+ return {+ account,+ services: services.length > 0 ? services : [...ALL_GOOGLE_SERVICES],+ historyDays,+ calendarId,+ dir,+ access,+ ...(typeof config.g_token_command === 'string' && config.g_token_command.trim()+ ? { tokenCommand: config.g_token_command }+ : {}),+ ...(typeof config.g_token_env === 'string' && config.g_token_env.trim()+ ? { tokenEnv: config.g_token_env }+ : {}),+ };+}diff --git a/src/core/import-contextual-mode.ts b/src/core/import-contextual-mode.tsnew file mode 100644index 0000000000..638814744f--- /dev/null+++ b/src/core/import-contextual-mode.ts@@ -0,0 +1,38 @@+/**+ * The contextual-retrieval convention a markdown import records with its+ * canonical write (#5621): the page/source/global override chain, with the+ * per-chunk synopsis tier demoted to the free title tier (the synopsis tier+ * is the Minion backfill's job), plus the corpus generation that tier embeds+ * under. Shared by `importFromContent` and `gbrain repair contextual-mode`,+ * so an existing page is stamped exactly as a fresh import would stamp it.+ *+ * `strict` (coordinated writes and repairs) fails on any source-row read+ * error. Otherwise only a missing row ('default' not seeded on a fresh brain)+ * or a missing sources table keeps the host-trust defaults; any other failed+ * read fails, because falling back would stamp the wrong source's convention.+ */+import type { BrainEngine } from './engine.ts';+import { resolveContextualRetrievalMode } from './contextual-retrieval-resolver.ts';+import { loadSearchModeConfig, resolveSearchMode } from './search/mode.ts';+import { isUndefinedTableError } from './utils.ts';+import { computeCorpusGeneration, loadSourceRow, SourceRowNotFoundError } from './contextual-retrieval-service.ts';+import { DEFAULT_SYNOPSIS_MODEL } from './page-summary.ts';++export async function resolveImportContextualMode(engine: BrainEngine, sourceId: string, frontmatter: Record<string, unknown> | null | undefined,+ strict: boolean): Promise<{ mode: 'none' | 'title'; corpusGeneration: string | null }> {+ const knobs = resolveSearchMode(await loadSearchModeConfig(engine));+ let source: { id: string; contextual_retrieval_mode?: string | null; trust_frontmatter_overrides?: boolean } =+ { id: sourceId, contextual_retrieval_mode: null, trust_frontmatter_overrides: false };+ try {+ const row = await loadSourceRow(engine, sourceId);+ source = { id: row.id, contextual_retrieval_mode: row.contextual_retrieval_mode ?? null, trust_frontmatter_overrides: row.trust_frontmatter_overrides === true };+ } catch (error) {+ if (strict || !(error instanceof SourceRowNotFoundError || isUndefinedTableError(error))) throw error;+ }+ const resolution = resolveContextualRetrievalMode({ pageFrontmatter: frontmatter ?? {}, source,+ globalMode: knobs.contextual_retrieval, killSwitchDisabled: knobs.contextual_retrieval_disabled });+ const effectiveCRMode = resolution.mode === 'per_chunk_synopsis' ? 'title' : resolution.mode;+ const mode = effectiveCRMode === 'none' ? 'none' : 'title';+ // The inline path never uses per_chunk_synopsis, so the doc-cap field stays out of the hash.+ return { mode, corpusGeneration: mode === 'none' ? null : computeCorpusGeneration({ crMode: mode, synopsisModel: DEFAULT_SYNOPSIS_MODEL }) };+}diff --git a/src/core/import-file.ts b/src/core/import-file.tsindex fc63015c00..1e990f18d0 100644--- a/src/core/import-file.ts+++ b/src/core/import-file.ts@@ -26,13 +26,13 @@ import { embedMultimodal, currentEmbeddingSignature } from './embedding.ts';// transient network backoff) instead of bare embedBatch, so one socket blip// mid-sync no longer aborts the whole file import. Same core→commands edge// precedent as embed-stale.ts.-import { embedBatchWithBackoff } from './embed-retry.ts';+import { embedBatchKeepingUsable, embedBatchWithBackoff } from './embed-retry.ts';+import { isEmbeddingZeroNormError, type EmbeddingZeroNormError } from './ai/embedding-guard.ts';import { slugifyPath, slugifyCodePath, isCodeFilePath, hasMalformedPathSegment } from './sync.ts';import type { ChunkInput, Page, PageInput, PageType } from './types.ts';import { computeEffectiveDate, fallbackCreatedAt, isValidTimeZone } from './effective-date.ts';import { MARKDOWN_CHUNKER_VERSION } from './chunkers/recursive.ts';import { logSlugFallback } from './audit-slug-fallback.ts';-import { resolveContextualRetrievalMode } from './contextual-retrieval-resolver.ts';import { assessContentSanity, ContentSanityBlockError } from './content-sanity.ts';import { loadOperatorLiterals } from './content-sanity-literals.ts';import { logContentSanityAssessment } from './audit/content-sanity-audit.ts';@@ -50,12 +50,10 @@ import {modeRequiresWrapper,wrapChunkForEmbedding,} from './embedding-context.ts';-import { loadSearchModeConfig, resolveSearchMode } from './search/mode.ts';import { normalizeAliasList } from './search/alias-normalize.ts';-import { isUndefinedTableError, warnOncePerProcess, validateSlug, contentHash, contentHashLegacy, ATOMS_SCAN_HASH_KEY } from './utils.ts';+import { warnOncePerProcess, validateSlug, contentHash, contentHashLegacy, ATOMS_SCAN_HASH_KEY } from './utils.ts';import { decorateEmbeddingDimError } from './embedding-dim-check.ts';-import { computeCorpusGeneration, loadSourceRow } from './contextual-retrieval-service.ts';-import { DEFAULT_SYNOPSIS_MODEL } from './page-summary.ts';+import { resolveImportContextualMode } from './import-contextual-mode.ts';import { runGuardrails } from './guardrails.ts';import { parseFactsFence, renderFactsTable, restoreHiddenFactRows, factsGapWarning, replaceOrInsertFactsFence } from './facts-fence.ts';@@ -785,72 +783,12 @@ export async function importFromContent(// and defers per-chunk synopsis to the Minion-driven sweep).// - Stored chunk_text stays canonical; only the embedding input is wrapped.// - Code chunks (chunk_source='fenced_code') bypass wrapping per D20-T4.- // Coordinated imports publish text now and embed through the durable outbox.- // Capture their wrapping convention before publication, even though no- // provider runs here. Plain legacy --no-embed imports retain their behavior.- const prepareEmbeddingContext = !opts.noEmbed || opts.prepare !== undefined;- let effectiveCRMode: 'none' | 'title' | 'per_chunk_synopsis' = 'none';- if (prepareEmbeddingContext) {- const searchInput = await loadSearchModeConfig(engine);- const knobs = resolveSearchMode(searchInput);- // #3885: load the REAL source row so a stored `gbrain sources- // set-cr-mode <id> <mode>` (and the mount trust flag) applies on the- // inline import path — capture + reindex --markdown — not just the- // Minion backfill. The prior hardcoded stub (contextual_retrieval_mode:- // null / trust_frontmatter_overrides: false) silently ignored the- // per-source override. Unknown source id / pre-sources-table brains- // keep the stub (host-trust defaults).- let sourceRow: {- id: string;- contextual_retrieval_mode?: string | null;- trust_frontmatter_overrides?: boolean;- } = {- id: sourceId ?? 'default',- contextual_retrieval_mode: null,- trust_frontmatter_overrides: false,- };- try {- const row = await loadSourceRow(engine, sourceId ?? 'default');- sourceRow = {- id: row.id,- contextual_retrieval_mode: row.contextual_retrieval_mode ?? null,- trust_frontmatter_overrides: row.trust_frontmatter_overrides === true,- };- } catch (error) {- // Accepted coordinated writes must retry a failed policy read; falling- // back here could commit a different source's wrapping convention.- if (opts.prepare) throw error;- // Source row missing ('default' not seeded on a fresh brain) — the- // stub stands, matching pre-#3885 behavior.- }- const resolution = resolveContextualRetrievalMode({- pageFrontmatter: parsed.frontmatter,- source: sourceRow,- globalMode: knobs.contextual_retrieval,- killSwitchDisabled: knobs.contextual_retrieval_disabled,- });- // Inline path: title-tier wrap is free. per_chunk_synopsis is too- // expensive for the inline import path; the page lands at the- // title tier on disk and the Minion-driven contextual reindex- // upgrades it later when the user accepts the cost prompt.- effectiveCRMode = resolution.mode === 'per_chunk_synopsis' ? 'title' : resolution.mode;- }-- // v0.40.3.0: corpus_generation hash for D27 P1-5 cache invalidation.- // Record the selected wrapper generation for inline or deferred embedding;- // 'none' writes NULL. The separate embedding signature certifies vectors.- const corpusGeneration =- effectiveCRMode === 'none' || !prepareEmbeddingContext- ? null- : computeCorpusGeneration({- crMode: effectiveCRMode,- synopsisModel: DEFAULT_SYNOPSIS_MODEL,- // Inline import-file path never uses per_chunk_synopsis (refuses- // upstream); pass undefined so the doc-cap field stays out of- // the hash here. Per_chunk_synopsis runs through the Minion- // backfill handler which threads SYNOPSIS_DOC_MAX_CHARS through- // the service layer.- });+ // Every markdown import records its wrapping convention with the canonical+ // write, --no-embed included (#5621): later embed passes reproduce the stored+ // mode, so an unstamped page would stay unwrapped. No provider runs here.+ // #3885: the real source row applies (a stored `sources set-cr-mode`); the+ // inline path demotes per_chunk_synopsis to the free title tier.+ const { mode: effectiveCRMode, corpusGeneration } = await resolveImportContextualMode(engine, sourceId ?? 'default', parsed.frontmatter, opts.prepare !== undefined);// A13: an edit re-embeds only chunks whose embedding input changed. A stored// vector is reused for a chunk with the same source and text when its@@ -883,6 +821,7 @@ export async function importFromContent(}}+ let embeddingPartial: EmbeddingZeroNormError | undefined;const embedChunks = async () => {const pending = chunks.map((_, i) => i).filter(i => !reused.has(i));if (opts.noEmbed || pending.length === 0) return;@@ -891,9 +830,12 @@ export async function importFromContent(? buildContextualPrefix(parsed.title, null): null;const wrappedTexts = pending.map(i => prefix ? wrapChunkForEmbedding(chunks[i].chunk_text, prefix, chunks[i].chunk_source) : chunks[i].chunk_text);- const embeddings = await embedBatchWithBackoff(wrappedTexts);+ // #4616: store the usable vectors; refused chunks stay NULL for embed --stale.+ const { vectors: embeddings, refused } = await embedBatchKeepingUsable(wrappedTexts);+ embeddingPartial = refused;pending.forEach((i, j) => {- chunks[i].embedding = embeddings[j];+ if (!embeddings[j]) return;+ chunks[i].embedding = embeddings[j]!;// token_count tracks the wrapped string length so cost reporting// reflects what we actually sent to the embedder.chunks[i].token_count = Math.ceil(wrappedTexts[j].length / 4);@@ -907,6 +849,10 @@ export async function importFromContent(if (!opts.onPostCommitEmbedding) {try {await embedChunks();+ if (embeddingPartial) {+ embeddingDeferred = true;+ process.stderr.write(`[import] ${slug}: ${embeddingPartial.message} ${embeddingPartial.suggestionFor(slug, sourceId)}\n`);+ }} catch (err) {embeddingDeferred = true;chunks.forEach((c, i) => { if (!reused.has(i)) { c.embedding = undefined; c.token_count = undefined; } });@@ -974,17 +920,16 @@ export async function importFromContent(// v0.40.3.0: stamp the contextual retrieval state columns alongside// the page write. updatePageContextualRetrievalState is a narrow// UPDATE that runs after putPage's INSERT/UPDATE so the row exists.- // Prepared imports bind this convention to the new canonical revision;- // their deferred embedder reproduces it and installs only under CAS.+ // Deferred embedders reproduce it: the prepared outbox installs only+ // under CAS, and --no-embed drains read it back. Every chunk row is+ // replaced below, so no older vector survives under this stamp.// This stamp certifies no vector: embedding_signature stays deferred.- if (prepareEmbeddingContext) {- await tx.updatePageContextualRetrievalState(- slug,- sourceId ?? 'default',- effectiveCRMode,- corpusGeneration,- );- }+ await tx.updatePageContextualRetrievalState(+ slug,+ sourceId ?? 'default',+ effectiveCRMode,+ corpusGeneration,+ );// Tag reconciliation (A14): frontmatter tags carry tag_source='frontmatter'.// A frontmatter-owned row whose tag left the frontmatter is deleted; rows@@ -1108,7 +1053,7 @@ export async function importFromContent(if (!persistedProjection) return { status: 'superseded' };const signature = currentEmbeddingSignature();await embedChunks();- const installed = await installPageEmbeddings(engine, persistedProjection, chunks, signature ?? undefined);+ const installed = await installPageEmbeddings(engine, persistedProjection, chunks, embeddingPartial ? undefined : signature ?? undefined);return { status: installed ? 'embedded' : 'superseded' };} catch {return { status: 'failed', error: 'Page content was saved, but embedding failed. Check the embedding provider and database on the brain host, then run gbrain embed --stale --source <source-id>.' };@@ -1534,6 +1479,8 @@ export async function importCodeFile(}} catch (e: unknown) {codeEmbeddingFailed = true;+ // #4616: keep the usable vectors of a partially refused batch.+ if (isEmbeddingZeroNormError(e)) needsEmbedIndexes.forEach((i, j) => { if (e.vectors[j]) chunks[i]!.embedding = e.vectors[j]!; });console.warn(`[gbrain] embedding failed for code file ${slug}: ${e instanceof Error ? e.message : String(e)}`);}}diff --git a/src/core/migrate.ts b/src/core/migrate.tsindex 9a8f995d62..26c2cd0fe0 100644--- a/src/core/migrate.ts+++ b/src/core/migrate.ts@@ -24,6 +24,7 @@ import { FACT_WITHDRAWAL_SCHEMA_SQL, FACT_WITHDRAWAL_BACKFILL_SQL, FACT_WITHDRAWimport { repairLegacyClientGrants } from './grants/migration.ts';import { PROJECTION_STATISTICS_SQL, verifyProjectionStatistics } from './search/projection-statistics.ts';import { SHARED_SKILLS_SCHEMA_SQL } from './shared-skills/schema-all.ts';+import { migrateConnectorCheckpoints } from './persistence/connector-checkpoint-migration.ts';/*** When true, per-migration explanatory notices (e.g. the v123/v124 "here is@@ -6777,6 +6778,52 @@ CREATE TRIGGER minion_queue_protocol BEFORE INSERT OR UPDATE ON minion_jobsidempotent: true,sql: `ALTER TABLE tags ADD COLUMN IF NOT EXISTS tag_source TEXT;`,},+ {+ // #5686: connector checkpoints were keyed on the raw sources.config, which+ // the cycle stamp rewrites after every run. Re-key each source's newest+ // committed checkpoint receipt to the stable parsed-config identity, seed+ // its connector state row (resumed or re-walking once), record the cutoff+ // that classifies retired-format connector intents, and remove orphan+ // checkpoint rows. Handler-only, statement-at-a-time, rerun-safe.+ version: 176, name: 'connector_checkpoint_stable_identity', idempotent: true, sql: '',+ handler: async engine => { await migrateConnectorCheckpoints(engine); },+ },+ {+ // #5254: a page written database-only while its filesystem source had no+ // canonical owner (persistence.unbound_write=database_only) is stamped+ // 'unbound_source', so writes and sync after binding keep it database-only+ // instead of materializing or overwriting it. Nullable, no backfill (no+ // earlier binary could write such a page), no index (read per page; the+ // doctor count scans only non-NULL rows; bootstrap-coverage: column-only).+ // Keep in sync with src/schema.sql (regenerate schema-embedded.ts via+ // build:schema) and src/core/pglite-schema.ts.+ version: 177,+ name: 'pages_database_only_reason',+ idempotent: true,+ sql: `ALTER TABLE pages ADD COLUMN IF NOT EXISTS database_only_reason TEXT;`,+ },+ {+ // Writer-version stamps: each request records the binary version and host+ // that admitted it and the ones that published it, so doctor's+ // writer_version advisory can name an older writer still on the brain.+ // Nullable and never backfilled (a past writer cannot be proven). The+ // cutoff is the database clock at migration time: only requests admitted+ // or published after it are expected to carry stamps. persistence_requests+ // and persistence_brain are migration-created on PGLite and no index+ // references these columns (bootstrap-coverage: column-only exemptions).+ version: 178,+ name: 'persistence_writer_version_stamps',+ idempotent: true,+ sql: `+ ALTER TABLE persistence_requests ADD COLUMN IF NOT EXISTS admitter_version text;+ ALTER TABLE persistence_requests ADD COLUMN IF NOT EXISTS admitter_host_id uuid;+ ALTER TABLE persistence_requests ADD COLUMN IF NOT EXISTS consumer_version text;+ ALTER TABLE persistence_requests ADD COLUMN IF NOT EXISTS consumer_host_id uuid;+ ALTER TABLE persistence_requests ADD COLUMN IF NOT EXISTS published_at timestamptz;+ ALTER TABLE persistence_brain ADD COLUMN IF NOT EXISTS writer_version_cutoff timestamptz;+ UPDATE persistence_brain SET writer_version_cutoff=now() WHERE writer_version_cutoff IS NULL;+ `,+ },];export const LATEST_VERSION = MIGRATIONS.length > 0diff --git a/src/core/minions/supervisor.ts b/src/core/minions/supervisor.tsindex c29f245389..f6395187ba 100644--- a/src/core/minions/supervisor.ts+++ b/src/core/minions/supervisor.ts@@ -48,7 +48,7 @@ import { hostname } from 'os';import type { BrainEngine } from '../engine.ts';import { tryAcquireDbLock, waitForDbLockTakeover, inspectLock, isLockHolderLive, type DbLockHandle } from '../db-lock.ts';import { currentBrainId, readWorkers } from './worker-registry.ts';-import { autopilotPausedMarkerPath } from '../autopilot-paths.ts';+import { autopilotOperatorPauseMarkerPath, autopilotPaused } from '../autopilot-paths.ts';import { resolveEnvNumber } from '../env-number.ts';export type SupervisorEvent =@@ -426,13 +426,15 @@ async function probeQueueStateInner(}const workerAlive = supervisorLive || registeredWorker || sig.activeHealthy > 0;- const paused = existsSync(autopilotPausedMarkerPath());+ const paused = autopilotPaused();// Same operator knob the doctor's queue_health depth check reads.const threshold = resolveEnvNumber('GBRAIN_QUEUE_WAITING_THRESHOLD', 10);const warnings: string[] = [];if (paused) {- warnings.push('system paused for migration — job will not start until the pause clears');+ warnings.push(existsSync(autopilotOperatorPauseMarkerPath())+ ? 'system paused by the operator (gbrain autopilot resume clears it) — job will not start until the pause clears'+ : 'system paused for migration — job will not start until the pause clears');}if (!workerAlive) {warnings.push(diff --git a/src/core/minions/worker.ts b/src/core/minions/worker.tsindex 322aa45c8c..97295b8e28 100644--- a/src/core/minions/worker.ts+++ b/src/core/minions/worker.ts@@ -13,7 +13,7 @@ import { assertNoUnreviewedJobs, authorizeJobExecution, withSubmissionAuthority*/import { existsSync } from 'fs';-import { autopilotPausedMarkerPath } from '../autopilot-paths.ts';+import { autopilotOperatorPauseMarkerPath, autopilotPausedMarkerPath } from '../autopilot-paths.ts';import type { BrainEngine } from '../engine.ts';import type {MinionJob, MinionJobContext, MinionHandler, MinionWorkerOpts,@@ -827,7 +827,7 @@ export class MinionWorker extends EventEmitter {// the CLAIM here extends that fence to queued jobs (an already// in-flight job finishes and is waited on by the migrate drain).// Checked at claim time only: one existsSync per poll tick.- if (existsSync(autopilotPausedMarkerPath())) {+ if (existsSync(autopilotPausedMarkerPath()) || existsSync(autopilotOperatorPauseMarkerPath())) {if (!this.pausedByMarkerAnnounced) {console.log('[worker] pause marker present — not claiming new jobs until it clears.');this.pausedByMarkerAnnounced = true;@@ -891,7 +891,7 @@ export class MinionWorker extends EventEmitter {// after migrate's drain probe counted zero active jobs. A job// claimed into that window is released back (delayed, un-run)// instead of executed; the poll loop then parks on the marker.- if (existsSync(autopilotPausedMarkerPath())) {+ if (existsSync(autopilotPausedMarkerPath()) || existsSync(autopilotOperatorPauseMarkerPath())) {console.log(`[worker] pause marker appeared after claim — releasing ${job.name} (id=${job.id}) un-run.`);await this.releaseClaimForPause(job, lockToken);this.executions.delete(lockToken);diff --git a/src/core/op-checkpoint.ts b/src/core/op-checkpoint.tsindex bd5d8b3269..9ef9c491d4 100644--- a/src/core/op-checkpoint.ts+++ b/src/core/op-checkpoint.ts@@ -498,7 +498,7 @@ export async function purgeStaleCheckpoints(`WITH deleted AS (DELETE FROM op_checkpointsWHERE updated_at < now() - ($1 || ' days')::interval- AND op NOT IN ('managed-atoms','managed-connector','managed-connector-retry')+ AND op NOT IN ('managed-atoms','managed-connector','managed-connector-retry','managed-connector-state','managed-connector-migration')AND NOT (op='managed-sync' AND (COALESCE(completed_keys->0->>'done','false')<>'true' OR EXISTS (SELECT 1 FROM op_checkpoints f WHERE f.op='managed-sync-failure' AND f.fingerprint=op_checkpoints.fingerprint)))AND op<>'managed-sync-failure'diff --git a/src/core/ops/contract.ts b/src/core/ops/contract.tsindex ed6cf4bfe8..c543b341b4 100644--- a/src/core/ops/contract.ts+++ b/src/core/ops/contract.ts@@ -45,6 +45,7 @@ export type ErrorCode =| 'provenance_required' // remember: provenance missing or empty| 'unavailable' // a required dependency cannot serve (no API key, gateway down, model refusal)| 'budget_unsatisfiable' // RESERVED in v1 — schema-listed, never returned+ | 'embedding_budget_below_worst_case' // #5680: migration cap below its worst-case authorization; refused before any change// eslint-disable-next-line @typescript-eslint/ban-types| (string & {}); // OPEN union for forward-compat (eE7 / D13)diff --git a/src/core/ops/embedding-migration.ts b/src/core/ops/embedding-migration.tsindex f6f127949f..9acd51c73a 100644--- a/src/core/ops/embedding-migration.ts+++ b/src/core/ops/embedding-migration.ts@@ -22,7 +22,7 @@ const migrate_embeddings: Operation = {dim: { type: 'number', description: "Target dimensions. Defaults to the provider recipe's declared width; required when the recipe declares none." },dry_run: { type: 'boolean', description: 'Plan + cost estimate only; change nothing.' },yes: { type: 'boolean', description: 'Confirm the re-embed spend + destructive schema change. Required for a live run.' },- max_cost_usd: { type: 'number', description: 'Finite total paid authorization. Required for new work; resume preserves all conservative pre-dispatch debits. Increase explicitly to renew.' },+ max_cost_usd: { type: 'number', description: 'Finite total paid authorization. Required for new work and must cover plan.worst_case_authorization (else refused with embedding_budget_below_worst_case before any change); requests settle to reported usage, resume preserves debits. Increase explicitly to renew.' },retarget: { type: 'boolean', description: 'Abandon a DIFFERENT in-flight migration target and start this one (the abandoned target is recorded in the marker history).' },reranker: { type: 'string', description: 'Reranker companion action: auto (default), off, keep, or an explicit provider:model (e.g. voyage:rerank-2.5). Reranker config lives on the DB plane.' },},@@ -86,6 +86,9 @@ const migrate_embeddings: Operation = {if (result.status === 'refused_env') {return { status: 'refused', reason: 'env_override', warning: result.warning, plan, recovery };}+ if (result.status === 'refused_budget') {+ return { status: 'refused', reason: result.refusal.error, ...result.refusal, plan, recovery };+ }if (result.status === 'refused_retarget') {return {status: 'refused',diff --git a/src/core/ops/links.ts b/src/core/ops/links.tsindex 41cf65da25..9d09529b3f 100644--- a/src/core/ops/links.ts+++ b/src/core/ops/links.ts@@ -1,4 +1,4 @@-import { assertUnmanagedCanonicalWriter } from '../persistence/maintenance.ts';+import { coordinatedManualLinkWrite } from '../persistence/manual-links.ts';/*** Links + graph operation cluster — pure move from operations.ts (v0.46.x* tranche 1). MANAGED_LINK_SOURCES stays exported (test suite + operations.ts@@ -76,7 +76,6 @@ const add_link: Operation = {}}if (ctx.dryRun) return { dry_run: true, action: 'add_link', from: p.from, to: p.to };- await assertUnmanagedCanonicalWriter(ctx.engine, 'add_link');// v114 (#1941): default omitted provenance to 'manual' (NOT the engine's// 'markdown' default) so hand/tool-created CLI edges are honestly manual,// and forbid forging the reconciliation-managed built-ins.@@ -97,7 +96,11 @@ const add_link: Operation = {await requireWritablePage(ctx, p.from as string, 'add_link', 'from');await requireWritablePage(ctx, p.to as string, 'add_link', 'to');try {- await ctx.engine.addLink( // gbrain-allow-direct-insert: add_link MCP op is the explicit canonical surface for manual link creation; auto-link reconciliation runs separately via auto_link post-hook+ // #5280: a managed brain takes the coordinated database-only path.+ const managed = await coordinatedManualLinkWrite(ctx, 'add_link', p.from as string, p.to as string, (engine, sourceId) =>+ engine.addLink(p.from as string, p.to as string, (p.context as string) || '', linkType, linkSource, undefined, undefined, // gbrain-allow-direct-insert: coordinated manual link inside withCoordinatedWrite+ { fromSourceId: sourceId, toSourceId: sourceId, originSourceId: sourceId }));+ if (!managed) await ctx.engine.addLink( // gbrain-allow-direct-insert: add_link MCP op is the explicit canonical surface for manual link creation; auto-link reconciliation runs separately via auto_link post-hookp.from as string, p.to as string,(p.context as string) || '', linkType,linkSource, undefined, undefined,@@ -130,19 +133,22 @@ const remove_link: Operation = {handler: async (ctx, p) => {enforceClientSlugFence(ctx, p.from as string, 'remove_link');if (ctx.dryRun) return { dry_run: true, action: 'remove_link', from: p.from, to: p.to };- await assertUnmanagedCanonicalWriter(ctx.engine, 'remove_link');const linkOpts = ctx.sourceId? { fromSourceId: ctx.sourceId, toSourceId: ctx.sourceId }: undefined;- // #4527: report how many edges actually died — an unconditional- // `{ status: 'ok' }` made a zero-match delete (typo'd slug, wrong- // link_type, already removed) indistinguishable from a real removal.- const removed = await ctx.engine.removeLink(+ const remove = (engine: typeof ctx.engine, opts: typeof linkOpts) => engine.removeLink(p.from as string, p.to as string,(p.link_type as string) || undefined,(p.link_source as string) || undefined,- linkOpts,+ opts,);+ // #4527: report how many edges actually died — an unconditional+ // `{ status: 'ok' }` made a zero-match delete (typo'd slug, wrong+ // link_type, already removed) indistinguishable from a real removal.+ // #5280: a managed brain takes the coordinated database-only path.+ const managed = await coordinatedManualLinkWrite(ctx, 'remove_link', p.from as string, p.to as string,+ (engine, sourceId) => remove(engine, { fromSourceId: sourceId, toSourceId: sourceId }));+ const removed = managed ? managed.value : await remove(ctx.engine, linkOpts);return { status: 'ok', removed };},cliHints: { name: 'unlink', aliases: ['link-rm'], positional: ['from', 'to'] },diff --git a/src/core/ops/pages.ts b/src/core/ops/pages.tsindex 0cbd089934..a74a29c5ea 100644--- a/src/core/ops/pages.ts+++ b/src/core/ops/pages.ts@@ -413,8 +413,8 @@ const purge_deleted_pages: Operation = {handler: async (ctx, p) => {const olderThanHours = (p.older_than_hours as number | undefined) ?? 72;if (ctx.dryRun) return { dry_run: true, action: 'purge_deleted_pages', older_than_hours: olderThanHours };- const result = await ctx.engine.purgeDeletedPages(olderThanHours);- return { status: 'purged', count: result.count, slugs: result.slugs };+ const result = await (await import('../persistence/purge-deleted.ts')).purgeDeletedPagesCoordinated(ctx.engine, olderThanHours);+ return { status: result.failed ? 'partial' : 'purged', count: result.count, slugs: result.slugs, ...(result.blocked.length ? { blocked: result.blocked } : {}) };},cliHints: { name: 'purge-deleted' },};diff --git a/src/core/ops/persistence.ts b/src/core/ops/persistence.tsindex 8966854691..5bc3d949a6 100644--- a/src/core/ops/persistence.ts+++ b/src/core/ops/persistence.ts@@ -92,11 +92,15 @@ async function visible(ctx: OperationContext, row: WriteRequest): Promise<booleaasync function publicReceipt(ctx: OperationContext, row: WriteRequest, facts?: WriteHealthFacts): Promise<Record<string, unknown>> {const { receiptFor } = await import('../persistence/journal.ts');const { publicEffectsForRequest } = await import('../persistence/effect-journal.ts');+ const { receiptDeliveredHint } = await import('../persistence/connector-errors.ts');return {...publicWriteReceipt(receiptFor(row, facts)),operation: row.operation, source_id: row.source_id, slug: row.slug,...(isWriteErrorCode(row.error_code) ? { write_error: row.error_code } : {}),- effects: await publicEffectsForRequest(ctx.engine, row.id),+ effects: (await publicEffectsForRequest(ctx.engine, row.id)).map(effect => {+ const hint = effect.reason ? receiptDeliveredHint({ error_code: effect.reason, source_id: row.source_id, slug: row.slug }) : null;+ return hint ? { ...effect, suggestion: hint.suggestion, docs: hint.docs } : effect;+ }),};}diff --git a/src/core/persistence/accepted-pending.ts b/src/core/persistence/accepted-pending.tsnew file mode 100644index 0000000000..8ef846aed5--- /dev/null+++ b/src/core/persistence/accepted-pending.ts@@ -0,0 +1,13 @@+/**+ * #5600/#5601: an accepted write that has not committed yet is progress, not+ * a failure. It keeps its request identity and publishes later; the caller+ * records it and moves on, and a rerun resumes the same request. Shared by+ * connector sync, managed import and managed atom publication.+ */+import { OperationError } from '../ops/contract.ts';+import { isTerminalWriteState, type WriteReceipt } from './types.ts';++export function acceptedPendingReceipt(error: unknown): WriteReceipt | null {+ if (!(error instanceof OperationError) || error.code !== 'write_pending' || !error.writeRequest) return null;+ return isTerminalWriteState(error.writeRequest.state) ? null : error.writeRequest;+}diff --git a/src/core/persistence/activation.ts b/src/core/persistence/activation.tsindex 37dd01843a..4471c03539 100644--- a/src/core/persistence/activation.ts+++ b/src/core/persistence/activation.ts@@ -7,6 +7,8 @@ import { localHostId, existingLocalHostId, persistenceHome, registerLocalWriterimport { nativeLockCapability, tryAcquireNativeLock, type NativeLockHandle } from './native-lock.ts';import { managedFilesystemDatastorePath, refreshManagedFilesystemRoots } from './filesystem-guard.ts';import { assertWriterAdminState, WRITER_INSPECTION_HINT } from './admin-intent.ts';+import { assertWriterAdminUnlocked } from './admin-lock.ts';+import { notQuiescedError } from './blocking-effects.ts';import { inspectLegacyWriterLocks } from './legacy-locks.ts';import { deleteLockRowExact } from '../db-lock.ts';@@ -101,6 +103,7 @@ export async function activatePersistence(engine: BrainEngine, opts: { confirmQuawait tx.executeRaw("SELECT set_config('lock_timeout','2000ms',true),set_config('synchronous_commit','on',true)");await assertWriterAdminState(tx, opts.expectedState);const [current] = await tx.executeRaw<{ enabled: boolean }>('SELECT enabled FROM persistence_brain WHERE singleton=1 FOR UPDATE');+ await assertWriterAdminUnlocked(tx);if (current?.enabled) return { enabled: true, activated: false, filesystem_sources: initial.length, native_lock: native };const currentSources = await configuredSources(tx, true);const bindings = await validatedBindings(tx, currentSources, hostId, true);@@ -116,7 +119,7 @@ export async function activatePersistence(engine: BrainEngine, opts: { confirmQuconst legacyLocks = await inspectLegacyWriterLocks(tx);if (legacyLocks.some(row => !opts.cleanupDeadLocalLocks || row.liveness !== 'dead_eligible')) throw quiescence();if ((await tx.executeRaw(`SELECT id FROM persistence_requests WHERE state IN ('queued','running','recovering') OR recovery IS NOT NULL LIMIT 1`)).length- || (await tx.executeRaw('SELECT id FROM persistence_effects WHERE recovery IS NOT NULL LIMIT 1')).length) throw quiescence();+ || (await tx.executeRaw('SELECT id FROM persistence_effects WHERE recovery IS NOT NULL LIMIT 1')).length) throw await notQuiescedError(tx, quiescence().message, { queuedEffects: false });if (opts.dryRun) return { enabled: false, activated: false, filesystem_sources: bindings.length, native_lock: native, legacy_locks: legacyLocks, drift_audit: driftAudit };for (const row of legacyLocks) {if (!(await deleteLockRowExact(tx, row.id, row.holder_pid, row.acquisition_token)).deleted) throw quiescence();diff --git a/src/core/persistence/admin-contract.ts b/src/core/persistence/admin-contract.tsindex 727515e895..d4c66306c8 100644--- a/src/core/persistence/admin-contract.ts+++ b/src/core/persistence/admin-contract.ts@@ -1,6 +1,9 @@/** Local administration is deliberately absent from the public operation registry. */+/** Reserved brain-level config key set only by `gbrain sources writer lock|unlock`; generic config writes refuse it. */+export const WRITER_ADMIN_LOCK_KEY = 'persistence.writer_admin_lock';export const PERSISTENCE_ADMIN_OPERATIONS = ['writer_status', 'writer_sync', 'writer_extract_stale', 'writer_reindex_code', 'writer_retry_effects', 'writer_embed_facts', 'writer_claim', 'writer_activate', 'writer_transfer_prepare', 'writer_transfer_accept',+ 'writer_lock', 'writer_unlock','local_writer_list', 'local_writer_register', 'local_writer_revoke','source_lifecycle', 'source_add', 'company_brain_preview', 'company_brain_connect', 'company_brain_resume','writer_reconcile_preview', 'writer_reconcile_apply', 'writer_reconcile_audit', 'writer_reconcile_backups',diff --git a/src/core/persistence/admin-lock.ts b/src/core/persistence/admin-lock.tsnew file mode 100644index 0000000000..ced4ae2d27--- /dev/null+++ b/src/core/persistence/admin-lock.ts@@ -0,0 +1,68 @@+/** Opt-in brain-level lock on writer claim, activation and transfer (#5285). Not a security boundary. */+import type { BrainEngine } from '../engine.ts';+import { OperationError } from '../ops/contract.ts';+import { WRITER_ADMIN_LOCK_KEY } from './admin-contract.ts';+import { existingLocalHostId, localHostId } from './identity.ts';+import type { SqlEngine } from './model.ts';++export { WRITER_ADMIN_LOCK_KEY };+export interface WriterAdminLock { locked: boolean; set_at: string | null; host_id: string | null; generation: number; }+export const WRITER_ADMIN_LOCKED_DOCS = 'docs/guides/write-refusals.md#writer_admin_locked';+export const WRITER_ADMIN_LOCKED_SUGGESTION = 'Stop. The operator locked writer administration on this brain. Do not retry or work around this refusal; '+ + 'ask the operator to review and perform the claim, activation or transfer. Ordinary page and memory writes continue. '+ + `See ${WRITER_ADMIN_LOCKED_DOCS}.`;++function parseLock(value: string | null | undefined): WriterAdminLock {+ const unlocked: WriterAdminLock = { locked: false, set_at: null, host_id: null, generation: 0 };+ if (!value) return unlocked;+ let parsed: Partial<WriterAdminLock>;+ try { parsed = JSON.parse(value) as Partial<WriterAdminLock>; }+ catch { return { ...unlocked, locked: true }; }+ // Anything but an explicit false stays locked: an unreadable row never unlocks administration.+ return { locked: parsed?.locked !== false, set_at: typeof parsed?.set_at === 'string' ? parsed.set_at : null,+ host_id: typeof parsed?.host_id === 'string' ? parsed.host_id : null,+ generation: Number.isSafeInteger(parsed?.generation) ? parsed.generation! : 0 };+}++export async function readWriterAdminLock(engine: SqlEngine): Promise<WriterAdminLock> {+ const [row] = await engine.executeRaw<{ value: string }>('SELECT value FROM config WHERE key=$1', [WRITER_ADMIN_LOCK_KEY]);+ return parseLock(row?.value);+}++/**+ * Runs inside claim, activation and transfer transactions for every caller, reviewed or internal.+ * FOR SHARE serializes with lock/unlock (FOR UPDATE) without blocking admission, which also shares this row.+ */+export async function assertWriterAdminUnlocked(tx: SqlEngine): Promise<void> {+ await tx.executeRaw('SELECT singleton FROM persistence_brain WHERE singleton=1 FOR SHARE');+ const lock = await readWriterAdminLock(tx);+ if (!lock.locked) return;+ throw new OperationError('writer_admin_locked',+ `Writer administration is locked on this brain (${WRITER_ADMIN_LOCK_KEY}${lock.set_at ? `, set ${lock.set_at}` : ''}${lock.host_id ? ` by host ${lock.host_id}` : ''}); `+ + 'writer claim, activate and transfer are refused.', WRITER_ADMIN_LOCKED_SUGGESTION, WRITER_ADMIN_LOCKED_DOCS);+}++/** Transaction body for `sources writer lock|unlock`; idempotent, serialized on the persistence_brain row. */+export async function writeWriterAdminLock(tx: SqlEngine, locked: boolean): Promise<{ admin_lock: WriterAdminLock; changed: boolean }> {+ await tx.executeRaw("SELECT set_config('synchronous_commit','on',true)");+ await tx.executeRaw('SELECT singleton FROM persistence_brain WHERE singleton=1 FOR UPDATE');+ const current = await readWriterAdminLock(tx);+ if (current.locked === locked) return { admin_lock: current, changed: false };+ if (locked) {+ const pending = await tx.executeRaw<{ id: string }>(`SELECT w.id FROM persistence_worktrees w+ WHERE w.state='draining' AND w.manifest IS NOT NULL ORDER BY w.id LIMIT 1`);+ if (pending.length) throw new OperationError('writer_transfer_conflict',+ `A writer transfer is prepared and not yet accepted (worktree ${pending[0].id}); the lock was not set.`,+ 'Finish the prepared transfer with gbrain sources writer transfer accept, inspect gbrain sources writer status --json, then lock.');+ }+ const [now] = await tx.executeRaw<{ at: string }>(`SELECT to_char(now() AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') AS at`);+ const next: WriterAdminLock = { locked, set_at: now.at, host_id: localHostId(), generation: current.generation + 1 };+ await tx.executeRaw(`INSERT INTO config(key,value) VALUES($1,$2) ON CONFLICT(key) DO UPDATE SET value=EXCLUDED.value`,+ [WRITER_ADMIN_LOCK_KEY, JSON.stringify(next)]);+ return { admin_lock: next, changed: true };+}++export async function setWriterAdminLock(engine: BrainEngine, locked: boolean): Promise<{ admin_lock: WriterAdminLock; changed: boolean; local_host_id: string | null }> {+ const result = await engine.transaction(tx => writeWriterAdminLock(tx, locked));+ return { ...result, local_host_id: existingLocalHostId() };+}diff --git a/src/core/persistence/administration.ts b/src/core/persistence/administration.tsindex 5d6250def4..e4562bb3bd 100644--- a/src/core/persistence/administration.ts+++ b/src/core/persistence/administration.ts@@ -14,6 +14,9 @@ import type { PersistenceAdminOperation } from './admin-contract.ts';import { operationScopesAllowed } from '../scope.ts';import { assertWriterAdminState, requireWriterAdminIntent, writerAdminState, WRITER_INSPECTION_HINT } from './admin-intent.ts';import { writerOnboardingPreflight } from './onboarding.ts';+import { assertWriterAdminUnlocked, readWriterAdminLock, setWriterAdminLock } from './admin-lock.ts';+import { listBlockingEffects } from './blocking-effects.ts';+import { listWriterVersions } from './writer-versions.ts';const invalid = (message: string) => new OperationError('invalid_params', message);function source(value: unknown): string {@@ -62,6 +65,12 @@ async function registrationGrant(engine: BrainEngine, params: Record<string, unkreturn { sourceIds, scopes, operations, slugPrefixes };}+/** Shown by `writer claim` (and its dry run) while persistence is not activated. */+export const CLAIM_BEFORE_ACTIVATION_NOTICE = 'Persistence is not activated. After this claim, gbrain sync refuses this source with '+ + 'writer_coordinator_required until activation, and legacy file writers in its checkout (sources push, lint --fix and other '+ + 'file-writing maintenance) refuse while the checkout is managed. Stop older writers, review gbrain sources writer status, '+ + 'then activate deliberately.';+export async function runPersistenceAdministration(engine: BrainEngine, operation: PersistenceAdminOperation,params: Record<string, unknown>, config?: GBrainConfig, embeddingRetryPolicy: 'owner' | 'mounted_database' = 'owner'): Promise<Record<string, unknown>> {if (operation === 'writer_reconcile_preview') return (await import('./reconcile.ts')).runReconcilePreview(engine, params);@@ -82,6 +91,12 @@ export async function runPersistenceAdministration(engine: BrainEngine, operatioreturn { ...await runtime.connectCompanyBrain(engine, input) };}if (currentVerifiedLocalWriter()?.remote) throw new OperationError('permission_denied', 'Writer administration requires a trusted local CLI caller.');+ if (operation === 'writer_lock' || operation === 'writer_unlock') {+ keys(params, []);+ return { ...await setWriterAdminLock(engine, operation === 'writer_lock') };+ }+ // Early refusal before any native lock or preview; the checks inside each transaction stay authoritative.+ if (['writer_claim', 'writer_activate', 'writer_transfer_prepare', 'writer_transfer_accept'].includes(operation)) await assertWriterAdminUnlocked(engine);if (operation === 'writer_sync') return (await import('./sync-administration.ts')).runAuthenticatedSyncSlice(engine, params);if (operation === 'writer_extract_stale') {keys(params, ['source_id', 'dry_run']);@@ -149,15 +164,23 @@ export async function runPersistenceAdministration(engine: BrainEngine, operatioconst onboarding = await writerOnboardingPreflight(engine, params.source_id as string | undefined);const [sharedSkills] = await engine.executeRaw<{ writer_protocol_floor: number; skill_bundles_enabled: boolean }>('SELECT writer_protocol_floor,skill_bundles_enabled FROM persistence_brain WHERE singleton=1');+ const adminLock = await readWriterAdminLock(engine);+ const blockingEffects = await listBlockingEffects(engine, { sourceId: params.source_id as string | undefined, limit: 20 });+ const writerVersions = await listWriterVersions(engine);await assertWriterAdminState(engine, adminState, false);- return { ...diagnostics, host_id: existingLocalHostId(), bindings, admin_state: adminState, onboarding, shared_skills: sharedSkills, ...(native ? { native_lock: native } : {}) };+ return { ...diagnostics, host_id: existingLocalHostId(), local_host_id: existingLocalHostId(), bindings, admin_state: adminState,+ admin_lock: { locked: adminLock.locked, set_at: adminLock.set_at, host_id: adminLock.host_id }, blocking_effects: blockingEffects,+ writer_versions: writerVersions, onboarding, shared_skills: sharedSkills, ...(native ? { native_lock: native } : {}) };}if (operation === 'writer_claim') {keys(params, ['source_id', 'path', 'dry_run', 'admin_intent', 'expected_state']);const sourceId = source(params.source_id), root = path(params.path);- if (params.dry_run) return { dry_run: true, action: operation, source_id: sourceId, path: root, current: await getWorktreeBinding(engine, sourceId, existingLocalHostId()) };+ // #5198: say at claim time what the claim retires, before and after the fact.+ const [brain] = await engine.executeRaw<{ enabled: boolean }>('SELECT enabled FROM persistence_brain WHERE singleton=1');+ const notice = brain?.enabled ? {} : { activation_required: CLAIM_BEFORE_ACTIVATION_NOTICE };+ if (params.dry_run) return { dry_run: true, action: operation, source_id: sourceId, path: root, current: await getWorktreeBinding(engine, sourceId, existingLocalHostId()), ...notice };const expectedState = await requireWriterAdminIntent(engine, operation, params);- return { claimed: true, binding: await claimWorktree(engine, sourceId, root, undefined, expectedState) };+ return { claimed: true, binding: await claimWorktree(engine, sourceId, root, undefined, expectedState), ...notice };}if (operation === 'writer_activate') {keys(params, ['confirm_quiesced', 'dry_run', 'shared_skills', 'admin_intent', 'expected_state', 'cleanup_dead_local_locks']);diff --git a/src/core/persistence/atom-maintenance.ts b/src/core/persistence/atom-maintenance.tsindex baeb980b50..2c2f48ff00 100644--- a/src/core/persistence/atom-maintenance.ts+++ b/src/core/persistence/atom-maintenance.ts@@ -2,6 +2,7 @@ import { readFileSync } from 'node:fs';import type { BrainEngine, LinkBatchInput } from '../engine.ts';import type { GBrainConfig } from '../config.ts';import type { OperationContext } from '../ops/contract.ts';+import { acceptedPendingReceipt } from './accepted-pending.ts';import { OperationError } from '../ops/contract.ts';import { currentSubmissionAuthority } from '../minions/submission-authority.ts';import { authorizeStoredRequest, authorizeWrite, submissionAuthority } from './authority.ts';@@ -226,7 +227,14 @@ export async function publishManagedAtoms(engine: BrainEngine, session: ManagedAconst receipts: WriteReceipt[] = [];for (const row of rows) {const finished = await waitForWrite(engine, row, session.config);- writeResponse(finished);+ try { writeResponse(finished); }+ catch (error) {+ // #5601: an accepted batch still publishing is progress; its deterministic request ids resume it next run.+ const pending = acceptedPendingReceipt(error);+ if (!pending) throw error;+ receipts.push(pending);+ continue;+ }receipts.push(receiptFor(finished));}return receipts;diff --git a/src/core/persistence/blocking-effects.ts b/src/core/persistence/blocking-effects.tsnew file mode 100644index 0000000000..fb78d6ef0a--- /dev/null+++ b/src/core/persistence/blocking-effects.ts@@ -0,0 +1,42 @@+/** Names the queued, running or recovering work that keeps a brain from quiescing (#5629). Read-only. */+import { OperationError } from '../ops/contract.ts';+import { WRITER_INSPECTION_HINT } from './admin-intent.ts';+import type { SqlEngine } from './model.ts';++export interface BlockingEffect {+ effect_id: string; kind: string; state: string; recovering: boolean; source_id: string; slug: string;+ request_id: string; attempts: number; next_attempt_at: string | Date | null; inspect: string;+}++const inspect = (sourceId: string) => `gbrain sources writer status ${sourceId} --json`;++/** Effects in state queued or running, or holding a recovery record, oldest first. */+export async function listBlockingEffects(engine: SqlEngine, opts: { sourceId?: string; limit?: number; recoveringOnly?: boolean } = {}): Promise<BlockingEffect[]> {+ const limit = Math.max(1, Math.min(opts.limit ?? 20, 1000));+ const rows = await engine.executeRaw<Omit<BlockingEffect, 'inspect'>>(`SELECT e.id::text AS effect_id,e.kind,e.state,(e.recovery IS NOT NULL) AS recovering,+ COALESCE(e.source_id,r.source_id) AS source_id,r.slug,r.request_id::text AS request_id,e.attempts,e.next_attempt_at+ FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id+ WHERE (e.recovery IS NOT NULL OR (NOT $3::boolean AND e.state IN ('queued','running')))+ AND ($1::text IS NULL OR COALESCE(e.source_id,r.source_id)=$1)+ ORDER BY e.id LIMIT $2`, [opts.sourceId ?? null, limit, opts.recoveringOnly === true]);+ return rows.map(row => ({ ...row, attempts: Number(row.attempts), inspect: inspect(row.source_id) }));+}++export function blockingEffectHint(effect: BlockingEffect): string {+ return `${WRITER_INSPECTION_HINT} Blocking effect ${effect.effect_id} (kind ${effect.kind}, state ${effect.state}${effect.recovering ? ', recovering' : ''}) `+ + `for source ${effect.source_id}, page ${effect.slug}, request ${effect.request_id}. Inspect it with: ${effect.inspect}. `+ + 'Inspection cannot clear it: the resident owner drains queued and running effects, gbrain sources writer retry-effects only re-authorizes failed or parked effects, '+ + 'and a stuck queued embedding effect has no clearing command until the deferred reconcile path lands.';+}++/** `writer_not_quiesced` naming the first blocking request, else the first blocking effect. */+export async function notQuiescedError(tx: SqlEngine, message: string, opts: { queuedEffects: boolean }): Promise<OperationError> {+ const [request] = await tx.executeRaw<{ request_id: string; source_id: string; slug: string; operation: string; state: string }>(+ `SELECT request_id::text AS request_id,source_id,slug,operation,state FROM persistence_requests+ WHERE state IN ('queued','running','recovering') OR recovery IS NOT NULL ORDER BY sequence LIMIT 1`);+ if (request) return new OperationError('writer_not_quiesced', message, `${WRITER_INSPECTION_HINT} Blocking request ${request.request_id} `+ + `(${request.operation}, ${request.state}) for source ${request.source_id}, page ${request.slug}. Inspect it with: ${inspect(request.source_id)}. `+ + 'Let the resident owner publish or recover it, then retry.');+ const [effect] = await listBlockingEffects(tx, { limit: 1, recoveringOnly: !opts.queuedEffects });+ return new OperationError('writer_not_quiesced', message, effect ? blockingEffectHint(effect) : WRITER_INSPECTION_HINT);+}diff --git a/src/core/persistence/canonical-projections.ts b/src/core/persistence/canonical-projections.tsindex 902824a31d..c1105cb80f 100644--- a/src/core/persistence/canonical-projections.ts+++ b/src/core/persistence/canonical-projections.ts@@ -264,9 +264,14 @@ export async function prepareCanonicalProjections(engine: BrainEngine, page: Parif (!snapshot) return;// Fact IDs in permanent receipts remain meaningful when a canonical row is// removed/replaced. Expire and detach its row position instead of deleting it.+ // Conversation-extractor rows share the page coordinate without a fence+ // (#1928, as in the extract_facts reconcile); their replay owns them. A+ // fence row that takes one of their row numbers wins that position.const incoming=JSON.stringify(factRows.map(f=>({row_num:f.row_num,fact:f.fact,visibility:f.visibility})));await tx.executeRaw(`UPDATE facts f SET expired_at=COALESCE(expired_at,now()),row_num=NULLWHERE source_id=$1 AND source_markdown_slug=$2 AND row_num IS NOT NULL+ AND (COALESCE(f.source,'') NOT LIKE 'cli:extract-conversation-facts%'+ OR EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS c(row_num integer) WHERE c.row_num=f.row_num))AND NOT EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS n(row_num integer,fact text,visibility text)WHERE n.row_num=f.row_num AND n.fact=f.fact AND n.visibility=f.visibility)`,[sourceId,slug,incoming]);if (factRows.length) {diff --git a/src/core/persistence/connector-account.ts b/src/core/persistence/connector-account.tsnew file mode 100644index 0000000000..adc880bfb7--- /dev/null+++ b/src/core/persistence/connector-account.ts@@ -0,0 +1,55 @@+/**+ * Resolve the account a connector credential actually belongs to, before any+ * service runs (#5686 account pin). Credential-delivery fields are excluded+ * from the connector identity, so a swapped token behind an unchanged+ * `g_token_env` / `gh_token_env` name is caught here instead.+ */+import type { GoogleService } from '../google/types.ts';+import type { GmailClient, CalendarClient, PeopleClient } from '../google/google-clients.ts';+import type { GitHubClient, GitHubSourceConfig } from '../github-source.ts';+import type { ConnectorAccount } from './connector-state.ts';++/**+ * Google: the first enabled service whose granted scope can name the account+ * (Gmail profile, Calendar primary calendar, People `me`). Null when none can.+ */+export async function resolveGoogleAccount(clients: { gmail: GmailClient; calendar: CalendarClient; people: PeopleClient },+ services: readonly GoogleService[], signal?: AbortSignal): Promise<string | null> {+ const opts = signal ? { signal } : {};+ const attempts: Array<[GoogleService, () => Promise<string | undefined>]> = [+ ['gmail', async () => (await clients.gmail.getProfile(opts)).emailAddress],+ ['calendar', async () => (await clients.calendar.fetchJSON<{ id?: string }>('https://www.googleapis.com/calendar/v3/calendars/primary', 'calendar-json', opts)).id],+ ['contacts', async () => {+ const me = await clients.people.fetchJSON<{ emailAddresses?: Array<{ value?: string; metadata?: { primary?: boolean } }> }>(+ 'https://people.googleapis.com/v1/people/me?personFields=emailAddresses', 'people', opts);+ return (me.emailAddresses?.find(address => address.metadata?.primary) ?? me.emailAddresses?.[0])?.value;+ }],+ ];+ for (const [service, attempt] of attempts) {+ if (!services.includes(service)) continue;+ signal?.throwIfAborted();+ try {+ const email = (await attempt())?.trim().toLowerCase();+ if (email && email.includes('@')) return email;+ } catch (error) {+ if (signal?.aborted) throw error;+ }+ }+ return null;+}++/**+ * GitHub: an App resolves to the installation its token was minted for; token+ * auth under `scope: auto` resolves to the authenticated login. Token auth+ * under `scope: repos` reads an explicit repo list, so it pins nothing.+ */+export async function resolveGitHubAccount(cfg: GitHubSourceConfig, client: GitHubClient,+ app: { getToken(): Promise<string>; installationId: number | null } | null, signal?: AbortSignal): Promise<ConnectorAccount> {+ if (app) {+ await app.getToken();+ return { kind: 'github', installationId: app.installationId, login: null };+ }+ if (cfg.scope !== 'auto') return { kind: 'github', installationId: null, login: null };+ const user = await client.fetchJSON<{ login?: string }>('/user', signal ? { signal } : {});+ return { kind: 'github', installationId: null, login: typeof user.login === 'string' ? user.login : null };+}diff --git a/src/core/persistence/connector-checkpoint-migration.ts b/src/core/persistence/connector-checkpoint-migration.tsnew file mode 100644index 0000000000..d5e53eda08--- /dev/null+++ b/src/core/persistence/connector-checkpoint-migration.ts@@ -0,0 +1,157 @@+/**+ * #5686 upgrade: re-key connector checkpoints through retained receipts, and+ * clean up checkpoint rows no source can load.+ *+ * Old checkpoint keys hashed the raw `sources.config`, which the cycle stamp+ * rewrote after every run, so they cannot be recomputed. The newest committed+ * checkpoint receipt per source incarnation still names the key it saved, so+ * its row is copied to the stable key (`INSERT … ON CONFLICT DO NOTHING`,+ * never overwriting a newer row). A source whose newest receipt was compacted+ * or is missing re-walks its window once; it never falls back to an older+ * receipt. Every statement runs on its own (transaction-mode PgBouncer), ages+ * use the database clock, and a rerun changes nothing.+ *+ * Orphans: `managed-connector` rows no source can load, and retry pointers+ * whose checkpoint no source loads, are excluded from the 7-day checkpoint+ * purge, so every cycle since the stamp was added left one behind. Cleanup+ * keeps rows touched after it started and rows referenced by a non-terminal+ * request or a recorded pending set. `gbrain repair connector-checkpoints` and+ * the doctor count reuse the same predicate with a 7-day age floor, because an+ * older binary may still be using an old key during a mixed-version window.+ */+import type { BrainEngine } from '../engine.ts';+import { connectorCheckpointKey, connectorIdentity, type ConnectorKind } from './connector-identity.ts';+import { CONNECTOR_STATE_OP, connectorStateKey, emptyConnectorState, type ConnectorState } from './connector-state.ts';++type Sql = Pick<BrainEngine, 'executeRaw' | 'transaction' | 'kind'>;+/** The database time migration 176 first ran; classifies retired-format connector intents. */+export const CONNECTOR_MIGRATION_OP = 'managed-connector-migration';+export async function readConnectorV2Cutoff(engine: Pick<BrainEngine, 'executeRaw'>): Promise<string | null> {+ const [row] = await engine.executeRaw<{ cutoff: string | null }>("SELECT completed_keys->0->>'cutoff' AS cutoff FROM op_checkpoints WHERE op=$1 AND fingerprint='v2-cutoff'", [CONNECTOR_MIGRATION_OP]);+ return row?.cutoff ?? null;+}++interface SourceRow { id: string; incarnation: string; local_path: string | null; config: Record<string, unknown> | string | null; archived: boolean }++/** Stable checkpoint keys of every registered connector source (archived ones included: a restore must still find its cursor). */+export async function loadableConnectorKeys(engine: Pick<BrainEngine, 'executeRaw'>): Promise<Map<string, { id: string; incarnation: string; archived: boolean }>> {+ const rows = await engine.executeRaw<SourceRow>("SELECT id,incarnation::text,local_path,config,archived FROM sources WHERE config->>'kind' IN ('google','github')");+ const keys = new Map<string, { id: string; incarnation: string; archived: boolean }>();+ for (const row of rows) {+ const config = typeof row.config === 'string' ? JSON.parse(row.config) as Record<string, unknown> : row.config ?? {};+ keys.set(connectorCheckpointKey(row.id, row.incarnation, connectorIdentity(config.kind as ConnectorKind, config, row.local_path)),+ { id: row.id, incarnation: row.incarnation, archived: row.archived === true });+ }+ return keys;+}++export interface OrphanCheckpointRow { op: 'managed-connector' | 'managed-connector-retry'; fingerprint: string; updated_at: string }++/** The orphan test for op_checkpoints row `c`; binds loadable keys, before, min age days and the state op from parameter `$first` on. */+const orphanPredicate = (first: number) => {+ const [k, b, d, o] = [first, first + 1, first + 2, first + 3].map(n => `$${n}`);+ return `(+ ((c.op='managed-connector' AND NOT (c.fingerprint = ANY(${k}::text[])))+ OR (c.op='managed-connector-retry' AND NOT (COALESCE(c.completed_keys->0->>'checkpointKey','') = ANY(${k}::text[]))))+ AND NOT EXISTS (SELECT 1 FROM persistence_requests r+ WHERE (r.state IN ('queued','running','recovering') OR r.recovery IS NOT NULL)+ AND (r.intent->>'kind' LIKE 'connector\\_v2\\_%' OR r.intent->>'kind' LIKE 'managed\\_connector\\_%')+ AND (r.intent->>'checkpointKey' = c.fingerprint OR r.intent->>'checkpointKey' = c.completed_keys->0->>'checkpointKey'+ OR r.request_id::text = c.completed_keys->0->>'requestId'))+ AND NOT EXISTS (SELECT 1 FROM op_checkpoints s+ CROSS JOIN LATERAL jsonb_array_elements(COALESCE(s.completed_keys->0->'pending','[]'::jsonb)) p+ JOIN persistence_requests r ON r.request_id::text = p->>'requestId'+ WHERE s.op=${o} AND (r.intent->>'checkpointKey' = c.fingerprint OR r.intent->>'checkpointKey' = c.completed_keys->0->>'checkpointKey'+ OR r.request_id::text = c.completed_keys->0->>'requestId'))+ AND (${b}::text IS NULL OR c.updated_at <= ${b}::text::timestamptz)+ AND (${d}::integer IS NULL OR c.updated_at < now() - make_interval(days => ${d}::integer)))`;+};++/**+ * Checkpoint and retry rows no source can load. `before` bounds `updated_at`+ * (the migration start); `minAgeDays` adds the doctor/repair age floor.+ */+export async function orphanConnectorCheckpoints(engine: Pick<BrainEngine, 'executeRaw'>, opts: { before?: string; minAgeDays?: number; limit?: number } = {}): Promise<OrphanCheckpointRow[]> {+ const loadable = [...(await loadableConnectorKeys(engine)).keys()];+ return engine.executeRaw<OrphanCheckpointRow>(`SELECT c.op, c.fingerprint, c.updated_at::text AS updated_at FROM op_checkpoints c+ WHERE c.op IN ('managed-connector','managed-connector-retry') AND ${orphanPredicate(2)}+ ORDER BY c.op, c.fingerprint LIMIT $1`, [opts.limit ?? 100_000, loadable, opts.before ?? null, opts.minAgeDays ?? null, CONNECTOR_STATE_OP]);+}++/**+ * Deletes the given orphans. Each DELETE re-applies the whole orphan predicate+ * in the same statement, so a row loaded, touched or newly referenced since+ * planning survives.+ */+export async function deleteOrphanConnectorCheckpoints(engine: Pick<BrainEngine, 'executeRaw' | 'transaction'>, rows: OrphanCheckpointRow[], opts: { before?: string; minAgeDays?: number } = {}): Promise<{ checkpoints: number; retries: number }> {+ const removed = { checkpoints: 0, retries: 0 };+ if (!rows.length) return removed;+ // Connector source rows stay share-locked while loadability is recomputed and rows are deleted, so a config change cannot make a deleted key current.+ await engine.transaction(async tx => {+ await tx.executeRaw("SELECT id FROM sources WHERE config->>'kind' IN ('google','github') ORDER BY id FOR SHARE");+ const loadable = [...(await loadableConnectorKeys(tx)).keys()];+ for (const row of rows) {+ const deleted = await tx.executeRaw<{ op: string }>(`DELETE FROM op_checkpoints c WHERE c.op=$1 AND c.fingerprint=$2 AND c.updated_at=$3::text::timestamptz+ AND ${orphanPredicate(4)} RETURNING c.op`, [row.op, row.fingerprint, row.updated_at, loadable, opts.before ?? null, opts.minAgeDays ?? null, CONNECTOR_STATE_OP]);+ if (!deleted.length) continue;+ if (row.op === 'managed-connector') removed.checkpoints++; else removed.retries++;+ }+ });+ return removed;+}++export interface ConnectorMigrationReport {+ rekeyed: Array<{ source_id: string; resumed_from: string }>;+ rewalking: string[];+ removed: { checkpoints: number; retries: number };+}++export async function migrateConnectorCheckpoints(engine: Sql, log: (line: string) => void = line => process.stderr.write(`${line}\n`)): Promise<ConnectorMigrationReport> {+ const [clock] = await engine.executeRaw<{ now: string }>('SELECT now()::text AS now');+ const start = clock.now;+ await engine.executeRaw("INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES($1,'v2-cutoff',$2::text::jsonb) ON CONFLICT (op,fingerprint) DO NOTHING",+ [CONNECTOR_MIGRATION_OP, JSON.stringify([{ cutoff: start }])]);+ // One statement, bounded by its own timeout; no long transaction around the scan.+ const receipts = await engine.transaction(async tx => {+ await tx.executeRaw("SELECT set_config('statement_timeout','120s',true)");+ return tx.executeRaw<{ source_id: string; source_incarnation: string; kind: string | null; checkpoint_key: string | null; compacted: boolean; committed_at: string }>(`+ SELECT DISTINCT ON (source_id, source_incarnation) source_id, source_incarnation::text, intent->>'kind' AS kind, intent->>'checkpointKey' AS checkpoint_key,+ COALESCE(compacted,false) AS compacted, COALESCE(completed_at,updated_at)::text AS committed_at+ FROM persistence_requests+ -- Compaction nulls the intent but keeps the slug, so a compacted newest receipt is still found (and re-walks).+ WHERE state='committed' AND slug='__managed_connector_checkpoint__' AND operation='submit_job'+ ORDER BY source_id, source_incarnation, sequence DESC`);+ });+ const newest = new Map(receipts.map(row => [`${row.source_id}\u0000${row.source_incarnation}`, row]));+ const report: ConnectorMigrationReport = { rekeyed: [], rewalking: [], removed: { checkpoints: 0, retries: 0 } };+ // Archived sources are migrated too: archive and restore keep the incarnation, so a restore resumes its cursor.+ for (const [key, source] of await loadableConnectorKeys(engine)) {+ const receipt = newest.get(`${source.id}\u0000${source.incarnation}`);+ // No managed checkpoint yet, or already saved by this release under its stable key.+ if (!receipt || receipt.kind === 'connector_v2_checkpoint') continue;+ let recovery: Pick<ConnectorState, 'upgrade_recovery' | 'resumed_from'> = { upgrade_recovery: 'rewalking_once', resumed_from: null };+ if (!receipt.compacted && receipt.checkpoint_key) {+ await engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys)+ SELECT 'managed-connector',$1,completed_keys FROM op_checkpoints WHERE op='managed-connector' AND fingerprint=$2+ ON CONFLICT (op,fingerprint) DO NOTHING`, [key, receipt.checkpoint_key]);+ const [copied] = await engine.executeRaw<{ fingerprint: string }>("SELECT fingerprint FROM op_checkpoints WHERE op='managed-connector' AND fingerprint=$1", [key]);+ if (copied) recovery = { upgrade_recovery: 'resumed', resumed_from: receipt.committed_at };+ }+ const seeded: ConnectorState = { ...emptyConnectorState(), ...recovery };+ const inserted = await engine.executeRaw<{ op: string }>(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES($1,$2,$3::text::jsonb)+ ON CONFLICT (op,fingerprint) DO NOTHING RETURNING op`, [CONNECTOR_STATE_OP, connectorStateKey(source.id, source.incarnation), JSON.stringify([seeded])]);+ if (!inserted.length) continue;+ if (recovery.upgrade_recovery === 'resumed') {+ report.rekeyed.push({ source_id: source.id, resumed_from: recovery.resumed_from! });+ log(` ${source.id}: resumed from pre-upgrade checkpoint of ${recovery.resumed_from}`);+ log(` content selection since then is unverified; to re-walk: gbrain sync --source ${source.id} --reset-checkpoint`);+ } else report.rewalking.push(source.id);+ }+ report.removed = await deleteOrphanConnectorCheckpoints(engine, await orphanConnectorCheckpoints(engine, { before: start }), { before: start });+ if (report.rekeyed.length || report.rewalking.length || report.removed.checkpoints || report.removed.retries) {+ log(` connector checkpoints: ${report.rekeyed.length} source(s) re-keyed, ${report.rewalking.length} will re-walk once `+ + `(the first post-upgrade admission spike is expected and is not #5470 churn); removed ${report.removed.checkpoints} orphan checkpoint row(s) `+ + `and ${report.removed.retries} orphan retry pointer(s).`);+ }+ return report;+}diff --git a/src/core/persistence/connector-errors.ts b/src/core/persistence/connector-errors.tsnew file mode 100644index 0000000000..2104e65a97--- /dev/null+++ b/src/core/persistence/connector-errors.ts@@ -0,0 +1,92 @@+/**+ * Typed connector refusals and the hints that travel with them.+ *+ * The coordinator persists only a failed receipt's code and message+ * (coordinator.ts `requestError`), so a code delivered through a stored+ * receipt gets its `suggestion`, `detail` and `docs` pointer rebuilt here,+ * deterministically, from the code, the message and the receipt's own fields.+ */+import { OperationError } from '../ops/contract.ts';+import { describeConnectorAccount, type ConnectorAccount } from './connector-state.ts';+import type { ConnectorConfig, ConnectorKind } from './connector-identity.ts';+import type { GitHubSourceConfig } from '../github-source.ts';+import type { GoogleSourceConfig } from '../google/types.ts';+import { CONNECTOR_BOUND_HINT, CONNECTOR_BOUND_MESSAGE, UNBOUND_PUBLICATION_MESSAGE, UNBOUND_SOURCE_DOCS, unboundPublicationHint } from './unbound-source.ts';+import { EMBEDDING_ZERO_NORM, EMBEDDING_ZERO_NORM_DOCS } from '../ai/embedding-guard.ts';++export const REFUSAL_DOCS = 'docs/guides/write-refusals.md';+export const docsAnchor = (code: string) => `${REFUSAL_DOCS}#${code.replaceAll('_', '-')}`;++/** The two exits for a changed connector account: restore the credential, or add a new source deliberately. */+export function connectorAccountChanged(sourceId: string, kind: ConnectorKind, config: ConnectorConfig,+ recorded: ConnectorAccount | string, resolved: ConnectorAccount | string | null): OperationError {+ const show = (value: ConnectorAccount | string | null) => value === null ? 'no resolvable account' : typeof value === 'string' ? value : describeConnectorAccount(value);+ let restore: string;+ let replace: string;+ if (kind === 'google') {+ const google = config as GoogleSourceConfig;+ const where = google.access === 'command' ? `the command configured as g_token_command (${google.tokenCommand ?? 'unset'})`+ : google.access === 'env' ? `the environment variable configured as g_token_env (${google.tokenEnv ?? 'unset'})` : `the vault credential (gbrain google connect --account ${google.account})`;+ restore = `restore ${where} so it yields a token for ${show(recorded)}, then retry: gbrain sync --source ${sourceId}`;+ replace = `add a new source for the new account (gbrain google setup --account ${typeof resolved === 'object' && resolved?.kind === 'google' ? resolved.email : '<email>'}), `+ + `then archive this one: gbrain sources archive ${sourceId}`;+ } else {+ const github = config as GitHubSourceConfig;+ const installation = typeof resolved === 'object' && resolved?.kind === 'github' && resolved.installationId !== null ? resolved.installationId : '<installation-id>';+ restore = github.app ? `restore the GitHub App credential (gh_app_id ${github.app.appId}, key at gh_app_pem_path) for ${show(recorded)}, then retry: gbrain sync --source ${sourceId}`+ : `restore the token in the environment variable configured as gh_token_env (${github.tokenEnv}) for ${show(recorded)}, then retry: gbrain sync --source ${sourceId}`;+ replace = `add a new source pinned to the intended installation (gbrain sources add <new-id> --kind github --scope ${github.scope}`+ + `${github.scope === 'repos' ? ` --repos ${github.repos.join(',')}` : ''}${github.app ? ` --app-id ${github.app.appId} --app-pem <path>` : ''} --app-install ${installation}), `+ + `then archive this one: gbrain sources archive ${sourceId}`;+ }+ // Account emails and installation ids stay in the local suggestion: job records persist and serve the message remotely.+ const error = new OperationError('connector_account_changed',+ `Connector source ${sourceId} is pinned to a different account than its credential resolves to. Nothing was imported.`,+ `The source is pinned to ${show(recorded)}; the credential resolves to ${show(resolved)}. (A) ${restore}. `+ + `(B) For a deliberate account change, ${replace}; existing pages stay under ${sourceId}. No reset flag authorizes an account change.`,+ docsAnchor('connector_account_changed'));+ error.detail = resolved === null ? 'account_unresolved' : 'account_changed';+ return error;+}++export const CONNECTOR_INTENT_OUTDATED_PRE_UPGRADE = 'The connector request was admitted before this upgrade in the retired intent format.';+export const CONNECTOR_INTENT_OUTDATED_OLD_HOST = 'A connector host older than this release admitted the request in the retired intent format.';++/**+ * Rebuilds the suggestion, detail and docs pointer for a code delivered through+ * a stored receipt: connector codes, the #5254 unbound-source publication+ * refusal, and the per-item embedding refusal.+ */+export function receiptDeliveredHint(receipt: { error_code?: string | null; error_message?: string | null; source_id?: string; slug?: string | null; intent?: Record<string, unknown> | null }):+ { suggestion: string; detail?: string; docs: string } | null {+ const source = receipt.source_id ?? '<source>';+ switch (receipt.error_code) {+ case 'connector_intent_outdated': {+ const preUpgrade = receipt.error_message === CONNECTOR_INTENT_OUTDATED_PRE_UPGRADE;+ return preUpgrade+ ? { detail: 'pre_upgrade', docs: docsAnchor('connector_intent_outdated'),+ suggestion: `No host upgrade is needed: the item is fetched again on the next run under a new request ID. Run: gbrain sync --source ${source}` }+ : { docs: docsAnchor('connector_intent_outdated'),+ suggestion: `Upgrade gbrain on the host that runs connector jobs for ${source} (gbrain upgrade), then run gbrain sync --source ${source}; the item is fetched again under a new request ID.` };+ }+ case 'unsupported_mutation_protocol': {+ const kind = String(receipt.intent?.kind ?? '');+ if (!kind.startsWith('connector_v2_')) return null;+ return { detail: 'consumer_upgrade_required', docs: docsAnchor('unsupported_mutation_protocol'),+ suggestion: `The persistence consumer that owns ${source} runs a gbrain older than this connector. Run gbrain upgrade on every consumer and worktree-owner host, then gbrain sync --source ${source}.` };+ }+ case EMBEDDING_ZERO_NORM: {+ const slug = receipt.slug ?? '<slug>';+ const sourceFlag = receipt.source_id && receipt.source_id !== 'default' ? ` --source ${receipt.source_id}` : '';+ return { docs: EMBEDDING_ZERO_NORM_DOCS,+ suggestion: `The embedding provider gave no usable vector for some chunks of ${slug}; the other chunks were stored and nothing is retried. `+ + `Inspect those chunks' text (empty, whitespace- or symbol-only chunks are the usual cause) or the provider, then run gbrain embed ${slug}${sourceFlag}.` };+ }+ case 'owner_unavailable':+ if (receipt.error_message === CONNECTOR_BOUND_MESSAGE) return { suggestion: CONNECTOR_BOUND_HINT, docs: UNBOUND_SOURCE_DOCS };+ if (receipt.error_message !== UNBOUND_PUBLICATION_MESSAGE) return null;+ return { detail: 'unbound_source', docs: UNBOUND_SOURCE_DOCS, suggestion: unboundPublicationHint(source) };+ default:+ return null;+ }+}diff --git a/src/core/persistence/connector-google-receipts.ts b/src/core/persistence/connector-google-receipts.tsindex 87ad068d1c..127875bf57 100644--- a/src/core/persistence/connector-google-receipts.ts+++ b/src/core/persistence/connector-google-receipts.ts@@ -12,11 +12,12 @@ import type { GmailThreadAttachmentReceipts } from '../google/types.ts';export type GoogleReceipts = GmailThreadAttachmentReceipts;-export function ownedGoogleReceipts(snapshot: PageSnapshot | null, config: Record<string, unknown>, receipts: GoogleReceipts): GoogleReceipts {+/** `account` is the parsed connector account (connector-identity.ts), never read from raw source config. */+export function ownedGoogleReceipts(snapshot: PageSnapshot | null, account: string, receipts: GoogleReceipts): GoogleReceipts {const page = snapshot?.page;const fm = page?.frontmatter;if (!page || page.deleted_at || page.type !== 'email' || !page.source_path?.startsWith('emails/') ||- config.kind !== 'google' || typeof config.g_account !== 'string' || config.g_account.trim().toLowerCase() !== receipts.account || fm?.account !== receipts.account ||+ !account || account !== receipts.account || fm?.account !== receipts.account ||fm.thread_id !== receipts.threadId || !Array.isArray(fm.message_ids) || !fm.message_ids.length ||!fm.message_ids.every(id => typeof id === 'string' && /^[A-Za-z0-9]{1,128}$/.test(id)) || fm.message_ids.length > 512 ||new Set(fm.message_ids).size !== fm.message_ids.length || receipts.version !== 1 || !Array.isArray(receipts.messages) ||@@ -62,8 +63,8 @@ export function ownedGoogleReceipts(snapshot: PageSnapshot | null, config: Recor}export async function prepareGoogleReceiptPatch(engine: BrainEngine, row: WriteRequest, snapshot: PageSnapshot | null,- config: Record<string, unknown>, supplied: GoogleReceipts): Promise<PreparedMutation> {- const receipts = ownedGoogleReceipts(snapshot, config, supplied);+ account: string, supplied: GoogleReceipts): Promise<PreparedMutation> {+ const receipts = ownedGoogleReceipts(snapshot, account, supplied);const current = snapshot!;const frontmatter = { ...current.page.frontmatter, gmail_attachment_receipts: receipts };const page = { ...current.page, frontmatter };diff --git a/src/core/persistence/connector-identity.ts b/src/core/persistence/connector-identity.tsnew file mode 100644index 0000000000..5479e223eb--- /dev/null+++ b/src/core/persistence/connector-identity.ts@@ -0,0 +1,105 @@+/**+ * Stable connector identity (#5686).+ *+ * A connector checkpoint, its admission `configHash`, the publication change+ * check and the attachments preview key all derive from the PARSED connector+ * config, never from raw `sources.config`: the cycle writes bookkeeping stamps+ * (`last_source_cycle_at`, `last_full_cycle_at`) into that blob after every+ * run, and other writers pin keys there too. The digest covers every parsed+ * leaf except an explicit list of credential-delivery fields, so a field added+ * to a parser later joins the identity by default. The resolved account a+ * credential belongs to is checked separately against the connector state+ * pin (`connector-state.ts`), because excluded credential fields can change+ * which account a sweep reads.+ */+import { digest } from './digest.ts';+import { parseGoogleSourceConfig } from '../google/source-config.ts';+import { parseGitHubSourceConfig } from '../github-source-config.ts';+import type { GitHubSourceConfig } from '../github-source.ts';+import type { GoogleSourceConfig } from '../google/types.ts';++export type ConnectorKind = 'google' | 'github';++/** A managed Google or GitHub connector source (`sources.config.kind`). */+export function isConnectorSourceKind(kind: unknown): kind is ConnectorKind { return kind === 'google' || kind === 'github'; }+export type ConnectorConfig = GoogleSourceConfig | GitHubSourceConfig;+type LeafClass = 'identity' | 'excluded';+type Rule = LeafClass | ((config: GitHubSourceConfig) => LeafClass);++const underAuto = (config: GitHubSourceConfig): LeafClass => config.scope === 'auto' ? 'identity' : 'excluded';++/**+ * Every leaf each parser returns, classified. The unit test enumerates parser+ * output and fails on a leaf missing here; an unlisted leaf still joins the+ * identity at runtime, never the exclusion list.+ */+export const CONNECTOR_LEAF_RULES: { google: Record<string, LeafClass>; github: Record<string, Rule> } = {+ google: {+ account: 'identity', services: 'identity', historyDays: 'identity', calendarId: 'identity', dir: 'identity',+ access: 'excluded', tokenCommand: 'excluded', tokenEnv: 'excluded',+ },+ github: {+ scope: 'identity', repos: 'identity', dir: 'identity',+ // Under `scope: auto` the repo set is whatever the authenticated identity can see.+ tokenEnv: config => config.scope === 'auto' && !config.app ? 'identity' : 'excluded',+ app: underAuto, 'app.appId': underAuto, 'app.installId': underAuto, 'app.pemPath': 'excluded',+ },+};++/** Leaf paths of a parsed config: nested objects flatten to dotted keys; arrays and null are leaves. */+export function connectorConfigLeaves(config: object): Record<string, unknown> {+ const leaves: Record<string, unknown> = {};+ const walk = (value: Record<string, unknown>, prefix: string) => {+ for (const [key, child] of Object.entries(value)) {+ if (child === undefined) continue;+ const path = prefix ? `${prefix}.${key}` : key;+ if (child !== null && typeof child === 'object' && !Array.isArray(child)) walk(child as Record<string, unknown>, path);+ else leaves[path] = child;+ }+ };+ walk(config as Record<string, unknown>, '');+ return leaves;+}++export function classifyConnectorLeaf(kind: ConnectorKind, config: ConnectorConfig, path: string): LeafClass | undefined {+ const rule = (CONNECTOR_LEAF_RULES[kind] as Record<string, Rule>)[path];+ return typeof rule === 'function' ? rule(config as GitHubSourceConfig) : rule;+}++/** The identity-bearing leaves, canonicalized: set-valued lists sorted and de-duplicated. */+export function connectorIdentityLeaves(kind: ConnectorKind, config: ConnectorConfig): Record<string, unknown> {+ const identity: Record<string, unknown> = {};+ for (const [path, value] of Object.entries(connectorConfigLeaves(config))) {+ if (classifyConnectorLeaf(kind, config, path) === 'excluded') continue;+ identity[path] = (path === 'services' || path === 'repos') && Array.isArray(value) ? [...new Set(value.map(String))].sort() : value;+ }+ return identity;+}++export interface ConnectorIdentity { kind: ConnectorKind; config: ConnectorConfig; digest: string }++export function parseConnectorConfig(kind: ConnectorKind, raw: Record<string, unknown>, localPath: string | null): ConnectorConfig {+ return kind === 'google' ? parseGoogleSourceConfig(raw, localPath ?? '') : parseGitHubSourceConfig(raw, localPath ?? '');+}++/** The parsed connector config plus its identity digest. The raw config is never an identity. */+export function connectorIdentity(kind: ConnectorKind, raw: Record<string, unknown>, localPath: string | null): ConnectorIdentity {+ const config = parseConnectorConfig(kind, raw, localPath);+ return { kind, config, digest: digest({ kind, identity: connectorIdentityLeaves(kind, config) }) };+}++export function connectorCheckpointKey(sourceId: string, incarnation: string, identity: Pick<ConnectorIdentity, 'kind' | 'digest'>): string {+ return digest({ sourceId, incarnation, connector: identity.kind, identity: identity.digest });+}++/** Legacy and current connector intent namespaces; every filter on connector kinds uses these. */+export const CONNECTOR_INTENT_PREFIXES = ['connector_v2_', 'managed_connector_'] as const;+export function isConnectorIntentKind(kind: unknown): boolean {+ return typeof kind === 'string' && CONNECTOR_INTENT_PREFIXES.some(prefix => kind.startsWith(prefix));+}+/** SQL predicate over a `persistence_requests` alias accepting both connector namespaces. */+export function connectorIntentSql(alias = 'persistence_requests'): string {+ return `(${alias}.intent->>'kind' LIKE 'connector\\_v2\\_%' OR ${alias}.intent->>'kind' LIKE 'managed\\_connector\\_%')`;+}+/** Checkpoint receipts in either namespace (the migration reads legacy ones). */+export const CONNECTOR_CHECKPOINT_KINDS = ['connector_v2_checkpoint', 'managed_connector_checkpoint'] as const;diff --git a/src/core/persistence/connector-reset.ts b/src/core/persistence/connector-reset.tsnew file mode 100644index 0000000000..0fbd75b93f--- /dev/null+++ b/src/core/persistence/connector-reset.ts@@ -0,0 +1,10 @@+import type { BrainEngine } from '../engine.ts';+import { OperationError } from '../ops/contract.ts';++/** `gbrain sync --reset-checkpoint` names exactly one connector source. */+export async function assertResetCheckpointSource(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string | undefined): Promise<void> {+ const [source] = sourceId ? await engine.executeRaw<{ kind: string | null }>("SELECT config->>'kind' AS kind FROM sources WHERE id=$1 AND NOT archived", [sourceId]) : [];+ if (source?.kind === 'google' || source?.kind === 'github') return;+ throw new OperationError('invalid_params', `--reset-checkpoint applies only to a Google or GitHub connector source${sourceId ? `; ${sourceId} is not one` : ''}.`,+ sourceId ? `Git-backed sources re-import with: gbrain sync --source ${sourceId} --full` : 'Name the connector source: gbrain sync --source <id> --reset-checkpoint');+}diff --git a/src/core/persistence/connector-state.ts b/src/core/persistence/connector-state.tsnew file mode 100644index 0000000000..24e3593877--- /dev/null+++ b/src/core/persistence/connector-state.ts@@ -0,0 +1,96 @@+/**+ * Per-source connector state row (#5686, #5600): one `op_checkpoints` row per+ * source incarnation (`op='managed-connector-state'`, fingerprint+ * `digest({sourceId, incarnation})`), independent of the identity digest so a+ * content-config change or a checkpoint reset never loses it. It holds the+ * resolved account pin, the pending receipts a run ended with, the upgrade+ * recovery disclosure and the last run's counts. The connector session writes+ * it only while it holds the connector sync lease; the upgrade migration seeds+ * `upgrade_recovery`. The 7-day checkpoint purge never touches it.+ */+import type { BrainEngine } from '../engine.ts';+import { digest } from './digest.ts';++export const CONNECTOR_STATE_OP = 'managed-connector-state';++export type ConnectorAccount =+ | { kind: 'google'; email: string }+ | { kind: 'github'; installationId: number | null; login: string | null };++export interface ConnectorPendingEntry {+ /** The page slug, or `__managed_connector_checkpoint__` for a checkpoint save. */+ itemRef: string;+ requestId: string;+ /** The stable request identity the retry-pointer path keys on. */+ baseRequestId: string;+ admittedAt: string;+}++export interface ConnectorRunCounts {+ page_admissions: number;+ skipped_unchanged: number;+ pending: number;+ checkpoint_admissions: number;+ stopped_on_wait_budget: boolean;+ dropped_upstream: number;+ finished_at: string;+}++export type UpgradeRecovery = 'resumed' | 'rewalking_once' | 'none';++export interface ConnectorState {+ version: 1;+ account: ConnectorAccount | null;+ pinned_at: string | null;+ /** Earlier account continuity cannot be proven (a migrated source pinned on its first post-upgrade run). */+ continuity_unverified: boolean;+ pending: ConnectorPendingEntry[];+ upgrade_recovery: UpgradeRecovery;+ resumed_from: string | null;+ last_run: ConnectorRunCounts | null;+}++export const emptyConnectorState = (): ConnectorState => ({ version: 1, account: null, pinned_at: null, continuity_unverified: false,+ pending: [], upgrade_recovery: 'none', resumed_from: null, last_run: null });++export function connectorStateKey(sourceId: string, incarnation: string): string {+ return digest({ sourceId, incarnation });+}++export async function readManagedConnectorState(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string, incarnation: string): Promise<ConnectorState> {+ const [row] = await engine.executeRaw<{ completed_keys: ConnectorState[] }>(+ 'SELECT completed_keys FROM op_checkpoints WHERE op=$1 AND fingerprint=$2', [CONNECTOR_STATE_OP, connectorStateKey(sourceId, incarnation)]);+ const stored = row?.completed_keys?.[0];+ return stored?.version === 1 ? { ...emptyConnectorState(), ...stored } : emptyConnectorState();+}++/**+ * Upserts the state row. With `lease`, the write happens only while that+ * connector sync lease is still held (checked in the same statement) and+ * returns false otherwise; the upgrade migration seeds rows without a lease.+ */+export async function writeManagedConnectorState(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string, incarnation: string, state: ConnectorState,+ lease?: { id: string; token: string; acquiredAt: string }): Promise<boolean> {+ // FOR SHARE holds the lease row for this statement: a concurrent takeover waits, and one already made fails the match.+ const rows = await engine.executeRaw<{ op: string }>(`WITH lease AS (SELECT id FROM gbrain_cycle_locks+ WHERE id=$4 AND acquisition_token=$5::uuid AND extract(epoch from acquired_at)::text=$6 AND ttl_expires_at>now() FOR SHARE)+ INSERT INTO op_checkpoints(op,fingerprint,completed_keys)+ SELECT $1,$2,$3::text::jsonb WHERE $4::text IS NULL OR EXISTS (SELECT 1 FROM lease)+ ON CONFLICT(op,fingerprint) DO UPDATE SET completed_keys=EXCLUDED.completed_keys,updated_at=now() RETURNING op`,+ [CONNECTOR_STATE_OP, connectorStateKey(sourceId, incarnation), JSON.stringify([state]), lease?.id ?? null, lease?.token ?? null, lease?.acquiredAt ?? null]);+ return rows.length > 0;+}++/** Account pins compare the resolved identity only; the recorded display never includes credentials. */+export function sameConnectorAccount(a: ConnectorAccount, b: ConnectorAccount): boolean {+ if (a.kind !== b.kind) return false;+ if (a.kind === 'google') return a.email === (b as typeof a).email;+ const other = b as typeof a;+ return (a.installationId ?? null) === (other.installationId ?? null) && (a.login ?? null)?.toLowerCase() === (other.login ?? null)?.toLowerCase();+}++export function describeConnectorAccount(account: ConnectorAccount): string {+ if (account.kind === 'google') return account.email;+ return [account.installationId !== null ? `installation ${account.installationId}` : null, account.login ? `login ${account.login}` : null]+ .filter(Boolean).join(', ') || 'no installation or login';+}diff --git a/src/core/persistence/connector-status.ts b/src/core/persistence/connector-status.tsnew file mode 100644index 0000000000..f114ff3606--- /dev/null+++ b/src/core/persistence/connector-status.ts@@ -0,0 +1,43 @@+/**+ * `gbrain sources status` view of each managed connector source's state row:+ * upgrade recovery, account pin continuity, pending receipts and the last+ * run's counts. Never includes the pinned account or installation id.+ */+import type { BrainEngine } from '../engine.ts';+import { readManagedConnectorState, type ConnectorRunCounts, type UpgradeRecovery } from './connector-state.ts';++export interface ConnectorSourceStatus {+ upgrade_recovery: UpgradeRecovery;+ resumed_from: string | null;+ account_pinned: boolean;+ continuity_unverified: boolean;+ pending: number;+ last_run: ConnectorRunCounts | null;+}++export async function readConnectorSourceStatuses(engine: Pick<BrainEngine, 'executeRaw'>): Promise<Map<string, ConnectorSourceStatus>> {+ const sources = await engine.executeRaw<{ id: string; incarnation: string }>(+ "SELECT id,incarnation::text FROM sources WHERE NOT archived AND config->>'kind' IN ('google','github')");+ const statuses = new Map<string, ConnectorSourceStatus>();+ for (const source of sources) {+ const state = await readManagedConnectorState(engine, source.id, source.incarnation);+ statuses.set(source.id, { upgrade_recovery: state.upgrade_recovery, resumed_from: state.resumed_from, account_pinned: state.account !== null,+ continuity_unverified: state.continuity_unverified, pending: state.pending.length, last_run: state.last_run });+ }+ return statuses;+}++export function connectorStatusLines(sourceId: string, status: ConnectorSourceStatus): string[] {+ const lines: string[] = [];+ const run = status.last_run;+ lines.push(` ${sourceId}: connector ${run ? `last run ${run.finished_at.slice(0, 19).replace('T', ' ')}: ${run.page_admissions} page admission(s), `+ + `${run.skipped_unchanged} skipped unchanged, ${run.pending} pending, ${run.checkpoint_admissions} checkpoint admission(s)`+ + `${run.stopped_on_wait_budget ? ', stopped on wait budget' : ''}${run.dropped_upstream ? `, ${run.dropped_upstream} dropped (deleted upstream)` : ''}` : 'has not run since the upgrade'}`);+ if (status.upgrade_recovery === 'resumed') {+ lines.push(` resumed from pre-upgrade checkpoint of ${status.resumed_from}; content selection since then is unverified; to re-walk: gbrain sync --source ${sourceId} --reset-checkpoint`);+ } else if (status.upgrade_recovery === 'rewalking_once') {+ lines.push(' re-walking its window once after the upgrade (an expected admission spike, not #5470 churn)');+ }+ if (status.continuity_unverified) lines.push(' account pinned on its first post-upgrade run; continuity before the upgrade is unverified');+ return lines;+}diff --git a/src/core/persistence/connector-sync.ts b/src/core/persistence/connector-sync.tsindex c616c4f871..9beba3d1d4 100644--- a/src/core/persistence/connector-sync.ts+++ b/src/core/persistence/connector-sync.ts@@ -1,7 +1,7 @@import { realpathSync, statSync } from 'node:fs';import { basename, join, resolve } from 'node:path';import type { BrainEngine } from '../engine.ts';-import type { SyncOpts } from '../../commands/sync.ts';+import type { SyncOpts, SyncResult } from '../../commands/sync.ts';import { loadConfig } from '../config.ts';import { importFromContent } from '../import-file.ts';import { parseMarkdown, serializePageToMarkdown } from '../markdown.ts';@@ -28,9 +28,47 @@ import { assertPhysicalRoot } from './physical-root.ts';import type { PageSnapshot } from '../page-state/types.ts';import { LockStolenError, syncLockId, withRefreshingLock, type DbLockHandle } from '../db-lock.ts';import { ownedGoogleReceipts, prepareGoogleReceiptPatch, type GoogleReceipts } from './connector-google-receipts.ts';+import { connectorCheckpointKey, connectorIdentity, type ConnectorIdentity, type ConnectorKind } from './connector-identity.ts';+import { readManagedConnectorState, sameConnectorAccount, writeManagedConnectorState, type ConnectorAccount, type ConnectorPendingEntry, type ConnectorRunCounts, type ConnectorState } from './connector-state.ts';+import { connectorAccountChanged, CONNECTOR_INTENT_OUTDATED_OLD_HOST, CONNECTOR_INTENT_OUTDATED_PRE_UPGRADE } from './connector-errors.ts';+import { inspectUnchanged, screeningRequest } from './noop-kernel.ts';+import { conceptPreservationHold, preserveCanonicalFences } from '../cycle/concept-publication.ts';+import { FACTS_FENCE_BEGIN } from '../facts-fence.ts';+import { TAKES_FENCE_BEGIN } from '../takes-fence.ts';+import { readJournalLimits } from './limits.ts';+import { withCoordinatedWrite } from './context.ts';+import { readConnectorV2Cutoff } from './connector-checkpoint-migration.ts';+import type { GoogleSourceConfig } from '../google/types.ts';-type ConnectorKind = 'google' | 'github';interface ConnectorLease { handle: DbLockHandle; signal: AbortSignal; }+type ConnectorIntentKind = 'connector_v2_import' | 'connector_v2_delete' | 'connector_v2_checkpoint' | 'connector_v2_google_receipts';+const CONNECTOR_V2_KINDS: readonly string[] = ['connector_v2_import', 'connector_v2_delete', 'connector_v2_checkpoint', 'connector_v2_google_receipts'];+const CHECKPOINT_SLUG = '__managed_connector_checkpoint__';+/**+ * #5600: one connector run waits at most this long in total for accepted+ * writes. A write that commits within the grace costs no budget, so a healthy+ * owner never exhausts it; the reserve keeps the last second of the budget+ * for the checkpoint and state writes.+ */+export const CONNECTOR_WAIT_BUDGET_MS = 30_000;+/** Test seam: fixtures that pause the owner shorten the budget instead of waiting 30 s per run. */+export const connectorWaitBudget = { ms: CONNECTOR_WAIT_BUDGET_MS };+const WAIT_RESERVE_MS = 1_000;+const COMMIT_GRACE_MS = 1_000;+const ITEM_WAIT_MS = 5_000;+/**+ * Accepted-pending writes stop the sweep: the run ends partial with its pending+ * set recorded. A `write_pending` error, so direct session callers and+ * `rethrowConnectorWriteError` treat it like any accepted, unfinished write.+ */+export class ConnectorWaitBudgetStop extends OperationError {+ constructor(row?: WriteRequest) {+ super('write_pending', 'The connector wait budget is spent with accepted writes still pending.',+ 'The pending writes are recorded and resolved first on the next run of the same connector sync.');+ this.name = 'ConnectorWaitBudgetStop';+ if (row) { this.writeRequest = receiptFor(row); this.writeError = 'write_pending'; }+ }+}interface ConnectorSource { incarnation: string; archived: boolean; local_path: string | null; config: Record<string, unknown>; }interface ConnectorRetry {checkpointKey: string;@@ -42,7 +80,7 @@ interface ConnectorRetry {attempt: number;}interface ConnectorIntent extends Record<string, unknown> {- kind: 'managed_connector_import' | 'managed_connector_delete' | 'managed_connector_checkpoint' | 'managed_connector_google_receipts';+ kind: ConnectorIntentKind;connector: ConnectorKind;configHash: string;sourceRoot: string | null;@@ -99,10 +137,6 @@ function stableId(value: unknown): string {return `${hash.slice(0, 8)}-${hash.slice(8, 12)}-5${hash.slice(13, 16)}-a${hash.slice(17, 20)}-${hash.slice(20, 32)}`;}-export function connectorCheckpointKey(sourceId: string, incarnation: string, connector: ConnectorKind, config: Record<string, unknown>): string {- return digest({ sourceId, incarnation, connector, config });-}-async function connectorFileTarget(engine: BrainEngine, row: Pick<WriteRequest, 'source_id' | 'worktree_id' | 'slug'>,snapshot: PageSnapshot | null, content: string | null, sourcePath: string | null, root: string | null): Promise<PreparedMutation['file']> {if (!row.worktree_id || snapshot || !sourcePath || !root) return prepareFileTarget(engine, row, snapshot, content);@@ -116,7 +150,7 @@ async function connectorFileTarget(engine: BrainEngine, row: Pick<WriteRequest,}export async function beginConnectorSync(engine: BrainEngine, sourceId: string, connector: ConnectorKind,- suppliedConfig: unknown, opts: SyncOpts, lease?: ConnectorLease): Promise<ManagedConnectorSync | null> {+ suppliedConfig: unknown, opts: SyncOpts & { resetCheckpoint?: boolean }, lease?: ConnectorLease): Promise<ManagedConnectorSync | null> {const [brain] = await engine.executeRaw<{ enabled: boolean }>('SELECT enabled FROM persistence_brain WHERE singleton=1');if (!brain?.enabled) return null;assertPersistenceAccepting(engine);@@ -130,10 +164,8 @@ export async function beginConnectorSync(engine: BrainEngine, sourceId: string,const [source] = await engine.executeRaw<ConnectorSource>('SELECT incarnation,archived,local_path,config FROM sources WHERE id=$1', [sourceId]);if (!source || source.archived) throw new OperationError('source_changed', 'The connector source is not active.');if (source.config.kind !== connector) throw new OperationError('writer_coordinator_required', 'Managed connector sync requires a registered connector source; legacy filesystem calls are unsupported.');- const config = connector === 'google'- ? (await import('../google/google-source.ts')).parseGoogleSourceConfig(source.config, source.local_path ?? '')- : (await import('../github-source.ts')).parseGitHubSourceConfig(source.config, source.local_path ?? '');- if (digest(config) !== digest(suppliedConfig) || opts.sourceId !== undefined && opts.sourceId !== sourceId) {+ const identity = connectorIdentity(connector, source.config, source.local_path);+ if (digest(identity.config) !== digest(suppliedConfig) || opts.sourceId !== undefined && opts.sourceId !== sourceId) {throw new OperationError('source_changed', 'Connector options do not match the registered source.');}const authority = await managedSyncAuthority(engine, sourceId, source.incarnation, source.local_path ?? '');@@ -142,37 +174,92 @@ export async function beginConnectorSync(engine: BrainEngine, sourceId: string,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);+ const session = new ManagedConnectorSync(engine, sourceId, identity, source, authority, binding, canonicalRoot, opts.noEmbed === true, opts.noSchemaPack === true,+ opts.retryFailed === true, lease, opts.resetCheckpoint === true, opts.githubItem !== undefined, opts.full === true);await session.load();return session;}+/**+ * Runs one managed connector sweep under the per-source sync lease. `onPending`+ * shapes the caller's result when accepted writes are still pending at the end+ * (the checkpoint did not advance) or the wait budget stopped the sweep;+ * without it, a stopped sweep reports `write_pending`.+ */export async function withConnectorSync<T>(engine: BrainEngine, sourceId: string, connector: ConnectorKind,- config: unknown, opts: SyncOpts, work: (session: ManagedConnectorSync | null, opts: SyncOpts) => Promise<T>): Promise<T> {+ config: unknown, opts: SyncOpts & { resetCheckpoint?: boolean }, work: (session: ManagedConnectorSync | null, opts: SyncOpts) => Promise<T>,+ onPending?: (result: T | null, session: ManagedConnectorSync) => T): Promise<T> {const [brain] = await engine.executeRaw<{ enabled: boolean }>('SELECT enabled FROM persistence_brain WHERE singleton=1');- if (!brain?.enabled) return work(null, opts);+ if (!brain?.enabled) {+ if (opts.resetCheckpoint) throw new OperationError('invalid_params', '--reset-checkpoint applies to managed connector sources.',+ `This brain does not use managed persistence; re-walk this connector with: gbrain sync --source ${sourceId} --full`);+ return work(null, opts);+ }opts.signal?.throwIfAborted();return withRefreshingLock(engine, syncLockId(sourceId), async (signal, handle) => {const combined = opts.signal ? AbortSignal.any([opts.signal, signal]) : signal;const options = { ...opts, signal: combined };const session = await beginConnectorSync(engine, sourceId, connector, config, options, { handle, signal: combined });if (!session) throw new OperationError('source_changed', 'The managed connector mode changed before the sweep.');- const result = await work(session, options);+ let result: T;+ try {+ result = await work(session, options);+ } catch (error) {+ if (!(error instanceof ConnectorWaitBudgetStop)) {+ if (error instanceof OperationError) await session.finish().catch(() => {});+ throw error;+ }+ await session.finish();+ if (onPending) return onPending(null, session);+ error.suggestion = `Accepted connector writes are still pending; they are recorded and resolved first on the next run: gbrain sync --source ${sourceId}`;+ throw error;+ }await session.assertLease(engine);- return result;+ await session.finish();+ return session.deferred && onPending ? onPending(result, session) : result;});}+interface PendingWrite { entry: ConnectorPendingEntry; row: WriteRequest; bytes: number }++/** A connector sweep that ended with accepted writes pending, or stopped on its wait budget, reports `partial` / `writer_pending`. */+export function pendingConnectorResult(result: SyncResult | null, session: ManagedConnectorSync): SyncResult {+ const base: SyncResult = result ?? { status: 'partial', fromCommit: null, toCommit: '', added: session.counts.created, modified: session.counts.updated,+ deleted: session.counts.deleted, renamed: 0, chunksCreated: 0, embedded: 0, pagesAffected: [] };+ return { ...base, status: 'partial', reason: 'writer_pending' };+}+export class ManagedConnectorSync {private checkpoint: unknown[] = [];private receipts: string[] = [];private retryApprovals = new Map<string, string>();+ /** Failed receipts a previous run ended with: retried automatically, without --retry-failed. */+ private autoRetry = new Set<string>();+ private carried: ConnectorPendingEntry[] = [];+ private pendingRows = new Map<string, PendingWrite>();+ private failedPending: ConnectorPendingEntry[] = [];+ private reseen = new Set<string>();+ private reseenItems = new Set<string>();+ private connectorState!: ConnectorState;+ private waitCharged = 0;+ private outstandingCap = 90;+ private intentByteCap = 16 * 1024 ** 2;+ private lastSaveCommitted = false;+ private stopped = false;+ private blockedByCheckpoint = false;+ private pendingCheckpoint: ConnectorPendingEntry | null = null;+ /** True when this run ended with accepted writes pending, so its checkpoint did not advance. */+ deferred = false;+ readonly counts: Omit<ConnectorRunCounts, 'finished_at' | 'pending' | 'stopped_on_wait_budget'> & { created: number; updated: number; deleted: number } = {+ page_admissions: 0, skipped_unchanged: 0, checkpoint_admissions: 0, dropped_upstream: 0, created: 0, updated: 0, deleted: 0 };readonly checkpointKey: string;- constructor(private engine: BrainEngine, readonly sourceId: string, private connector: ConnectorKind,+ private readonly connector: ConnectorKind;+ constructor(private engine: BrainEngine, readonly sourceId: string, private identity: ConnectorIdentity,private source: ConnectorSource, private authority: SyncAuthority, private binding: WorktreeBinding | null,private canonicalRoot: string | null, private noEmbed: boolean, private noSchemaPack: boolean, private retryFailed = false,- private lease?: ConnectorLease) {- this.checkpointKey = connectorCheckpointKey(sourceId, source.incarnation, connector, source.config);+ private lease?: ConnectorLease, private resetRequested = false, private targeted = false, private fullSweep = false) {+ this.connector = identity.kind;+ this.checkpointKey = connectorCheckpointKey(sourceId, source.incarnation, identity);}async assertLease(engine: BrainEngine): Promise<void> {if (!this.lease) return;@@ -197,22 +284,90 @@ export class ManagedConnectorSync {await this.refuseRetryBlocker(this.engine);}}+ const limits = await readJournalLimits(this.engine);+ this.outstandingCap = Math.max(1, Math.min(90, limits.principalOutstanding - 10));+ this.intentByteCap = Math.max(1024 ** 2, Math.floor(limits.principalIntentBytes / 2));+ this.connectorState = await readManagedConnectorState(this.engine, this.sourceId, this.source.incarnation);+ await this.resolvePendingSet();const [row] = await this.engine.executeRaw<{ completed_keys: unknown[] }>("SELECT completed_keys FROM op_checkpoints WHERE op='managed-connector' AND fingerprint=$1", [this.checkpointKey]);this.checkpoint = row?.completed_keys ?? [];- if (this.retryFailed) {- const pointers = await this.engine.executeRaw<{ completed_keys: ConnectorRetry[] }>(`SELECT completed_keys FROM op_checkpoints- WHERE op='managed-connector-retry' AND completed_keys->0->>'checkpointKey'=$1- AND completed_keys->0->>'principalId'=$2 AND completed_keys->0->>'principalKind'=$3`,- [this.checkpointKey, this.authority.writer.principal.id, this.authority.writer.principal.kind]);- this.retryApprovals = new Map(pointers.map(row => [row.completed_keys[0].baseRequestId, row.completed_keys[0].requestId]));+ const pointers = await this.engine.executeRaw<{ completed_keys: ConnectorRetry[] }>(`SELECT completed_keys FROM op_checkpoints+ WHERE op='managed-connector-retry' AND completed_keys->0->>'checkpointKey'=$1+ AND completed_keys->0->>'principalId'=$2 AND completed_keys->0->>'principalKind'=$3`,+ [this.checkpointKey, this.authority.writer.principal.id, this.authority.writer.principal.kind]);+ this.retryApprovals = new Map(pointers.map(row => [row.completed_keys[0].baseRequestId, row.completed_keys[0].requestId]));+ }+ /**+ * #5600: the pending set a previous run ended with is resolved before the+ * sweep. Committed receipts are dropped; still-pending ones stay outstanding+ * and gate this run's checkpoint; failed or conflicted ones authorize one+ * automatic retry when the re-walk reaches their item. A checkpoint save+ * still pending is waited for (within the budget) before anything else.+ */+ private async resolvePendingSet(): Promise<void> {+ for (const entry of this.connectorState.pending) {+ // By source incarnation, not the current principal: a replaced writer registration must not orphan the ledger.+ let [row] = await this.engine.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE request_id=$1::uuid AND source_id=$2 AND source_incarnation=$3::uuid',+ [entry.requestId, this.sourceId, this.source.incarnation]);+ if (!row) { this.carried.push(entry); continue; }+ if (row && entry.itemRef === CHECKPOINT_SLUG && !isTerminal(row)) row = await this.budgetedWait(row, connectorWaitBudget.ms);+ if (row.state === 'committed') continue;+ if (entry.itemRef === CHECKPOINT_SLUG && !isTerminal(row)) { this.pendingCheckpoint = entry; this.blockedByCheckpoint = true; continue; }+ if (!isTerminal(row)) { this.pendingRows.set(row.id, { entry, row, bytes: 0 }); continue; }+ this.autoRetry.add(entry.baseRequestId);+ this.carried.push(entry);+ }+ }+ /**+ * Checks the credential's resolved account against the source's pin before+ * any service runs. The first post-upgrade run pins a migrated source. A+ * requested checkpoint reset runs only after the account check passes.+ */+ async assertAccount(resolved: ConnectorAccount | null): Promise<void> {+ if (this.blockedByCheckpoint) { this.stopped = true; throw new ConnectorWaitBudgetStop(); }+ const configured = this.identity.kind === 'google' ? (this.identity.config as GoogleSourceConfig).account : null;+ if (resolved === null) throw connectorAccountChanged(this.sourceId, this.identity.kind, this.identity.config, this.connectorState.account ?? configured ?? 'the pinned account', null);+ if (configured !== null && resolved.kind === 'google' && resolved.email !== configured) {+ throw connectorAccountChanged(this.sourceId, this.identity.kind, this.identity.config, this.connectorState.account ?? configured, resolved);+ }+ const pinned = this.connectorState.account;+ if (pinned && !sameConnectorAccount(pinned, resolved)) throw connectorAccountChanged(this.sourceId, this.identity.kind, this.identity.config, pinned, resolved);+ if (!pinned) {+ const migrated = this.connectorState.upgrade_recovery === 'resumed';+ this.connectorState = { ...this.connectorState, account: resolved, pinned_at: new Date().toISOString(), continuity_unverified: migrated };+ await this.writeState();+ if (migrated && this.connectorState.resumed_from) {+ process.stderr.write(`[connector] ${this.sourceId}: resumed from pre-upgrade checkpoint of ${this.connectorState.resumed_from}\n`+ + `[connector] content selection since then is unverified; to re-walk: gbrain sync --source ${this.sourceId} --reset-checkpoint\n`);+ }}+ if (this.resetRequested) await this.resetCheckpoint();+ }+ /** `--reset-checkpoint`: resolve pending writes, then start from an empty cursor. Existing pages stay; the pin is kept. */+ private async resetCheckpoint(): Promise<void> {+ this.resetRequested = false;+ await this.drainPending();+ if (this.pendingRows.size) {+ throw new OperationError('write_pending', 'Accepted connector writes are still pending, so the checkpoint was not reset.',+ `Let them finish, then repeat: gbrain sync --source ${this.sourceId} --reset-checkpoint`);+ }+ this.carried = []; this.autoRetry.clear(); this.failedPending = [];+ if (this.checkpoint.length) {+ // The empty cursor keeps a rising generation, so the next save can never replay an older committed checkpoint receipt.+ const next = [{ generation: Number((this.checkpoint[0] as { generation?: number }).generation ?? 0) + 1, state: null }];+ await this.submit('connector_v2_checkpoint', CHECKPOINT_SLUG, null, { checkpointAfter: next, receipts: [], fresh: false });+ this.checkpoint = next;+ this.receipts = [];+ }+ this.connectorState = { ...this.connectorState, upgrade_recovery: 'none', resumed_from: null };+ await this.writeState();}private async validate(engine: BrainEngine, slug: string): Promise<WorktreeBinding | null> {await this.assertLease(engine);await validateSyncAuthority(engine, this.authority, slug);const [source] = await engine.executeRaw<ConnectorSource>('SELECT incarnation,archived,local_path,config FROM sources WHERE id=$1', [this.sourceId]);- if (!source || source.archived || source.incarnation !== this.source.incarnation ||- source.local_path !== this.source.local_path || digest(source.config) !== digest(this.source.config)) {+ if (!source || source.archived || source.incarnation !== this.source.incarnation || source.local_path !== this.source.local_path ||+ source.config.kind !== this.connector || connectorIdentity(this.connector, source.config, source.local_path).digest !== this.identity.digest) {throw new OperationError('source_changed', 'The connector source changed during the sweep.');}const binding = await getWorktreeBinding(engine, this.sourceId);@@ -280,7 +435,10 @@ export class ManagedConnectorSync {error.writeError = 'recovery_required';throw error;}- state<T>(empty: T): T { return structuredClone((this.checkpoint[0] as { state?: T } | undefined)?.state ?? empty); }+ state<T>(empty: T): T {+ if (this.resetRequested) throw new OperationError('storage_error', 'A requested checkpoint reset runs after the connector account check, before the checkpoint is read.');+ return structuredClone((this.checkpoint[0] as { state?: T } | undefined)?.state ?? empty);+ }async page(slug: string) {slug = slugifyPath(`${slug}.md`);await this.recover(slug);@@ -291,48 +449,206 @@ export class ManagedConnectorSync {}async importMarkdown(sourcePath: string, content: string): Promise<{ slug: string; chunks: number; status: 'imported' | 'skipped'; created: boolean }> {const slug = slugifyPath(sourcePath);- const row = await this.submit('managed_connector_import', slug, sourcePath, { content });- return { slug, chunks: Number(row.outcome?.chunks ?? 0), status: row.outcome?.noop ? 'skipped' : 'imported', created: row.outcome?.status === 'created' };+ const done = await this.submit('connector_v2_import', slug, sourcePath, { content });+ if (!done.row) return { slug, chunks: 0, status: 'skipped', created: false };+ if (done.pending) return { slug, chunks: 0, status: 'imported', created: done.created };+ return { slug, chunks: Number(done.row.outcome?.chunks ?? 0), status: done.row.outcome?.noop ? 'skipped' : 'imported', created: done.row.outcome?.status === 'created' };}async delete(slug: string, sourcePath: string | null): Promise<boolean> {slug = slugifyPath(`${slug}.md`);- const row = await this.submit('managed_connector_delete', slug, sourcePath, {});- return row.outcome?.noop !== true;+ const done = await this.submit('connector_v2_delete', slug, sourcePath, {});+ if (!done.row) return false;+ return done.pending || done.row.outcome?.noop !== true;}async patchGoogleReceipts(slug: string, receipts: GoogleReceipts, pageId: number): Promise<GoogleReceipts> {if (this.connector !== 'google') throw new OperationError('invalid_params', 'Attachment repair requires a Google source.');- const row = await this.submit('managed_connector_google_receipts', slug, null, { googleReceipts: receipts, googlePageId: pageId, noEmbed: true });- return (row.intent as ConnectorIntent).googleReceipts!;+ const done = await this.submit('connector_v2_google_receipts', slug, null, { googleReceipts: receipts, googlePageId: pageId, noEmbed: true });+ return (done.row!.intent as ConnectorIntent).googleReceipts!;}+ /**+ * Saves the connector cursor once every page receipt of this run has+ * committed. With writes still pending the save is deferred: the cursor stays+ * at the last fully committed position and the pending set is recorded at+ * the end of the run. An unchanged cursor costs no admission; when that save+ * would have stamped freshness, the source is stamped directly under the lease.+ */async saveState(state: unknown, fresh = false, newestContentAt?: string): Promise<void> {+ await this.drainPending();+ // A targeted refresh must not move the cursor past a carried failure it did not revisit.+ const blocked = this.targeted && this.unreachedCarried().some(entry => entry.itemRef !== CHECKPOINT_SLUG);+ if (this.pendingRows.size || this.failedPending.length || blocked) { this.deferred = true; this.lastSaveCommitted = false; return; }+ if (this.checkpoint.length && digest((this.checkpoint[0] as { state?: unknown }).state ?? null) === digest(state ?? null)) {+ if (fresh) await this.stampFreshness(newestContentAt);+ this.receipts = [];+ this.lastSaveCommitted = true;+ return;+ }const next = [{ generation: Number((this.checkpoint[0] as { generation?: number } | undefined)?.generation ?? 0) + 1, state: structuredClone(state) }];- await this.submit('managed_connector_checkpoint', '__managed_connector_checkpoint__', null,+ await this.submit('connector_v2_checkpoint', CHECKPOINT_SLUG, null,{ checkpointAfter: next, receipts: [...this.receipts], fresh, ...(newestContentAt ? { newestContentAt } : {}) });this.checkpoint = next;this.receipts = [];+ this.lastSaveCommitted = true;+ }+ /** Carried pending entries this run has not re-submitted, by request identity or by item. */+ private unreachedCarried(): ConnectorPendingEntry[] {+ return this.carried.filter(entry => !this.reseen.has(entry.baseRequestId) && !this.reseenItems.has(entry.itemRef));+ }+ /** E-D4: the freshness a skipped checkpoint save would have stamped, guarded by the lease and the source incarnation. */+ private async stampFreshness(newestContentAt?: string): Promise<void> {+ await this.engine.transaction(async tx => {+ await this.assertLease(tx);+ await withCoordinatedWrite(tx, [this.sourceId], () => tx.executeRaw(+ 'UPDATE sources SET last_sync_at=now(),newest_content_at=COALESCE($3::timestamptz,newest_content_at) WHERE id=$1 AND incarnation=$2::uuid',+ [this.sourceId, this.source.incarnation, newestContentAt ?? null]));+ });+ }+ /** The run's remaining wait allowance; the caller's own deadline arrives through the lease signal. */+ private remainingWait(): number {+ return Math.max(0, connectorWaitBudget.ms - WAIT_RESERVE_MS - this.waitCharged);+ }+ private async budgetedWait(row: WriteRequest, cap = ITEM_WAIT_MS): Promise<WriteRequest> {+ if (isTerminal(row)) return row;+ const remaining = this.remainingWait();+ const waitMs = remaining > 0 ? Math.min(cap, remaining + COMMIT_GRACE_MS) : 0;+ const started = performance.now();+ const done = await waitForWrite(this.engine, row, loadConfig() ?? { engine: this.engine.kind }, waitMs);+ const elapsed = performance.now() - started;+ // A write that commits inside the grace is free; a wait that ends without progress spends its whole allowance.+ this.waitCharged += isTerminal(done) ? Math.max(0, elapsed - COMMIT_GRACE_MS) : Math.max(elapsed, waitMs);+ return done;+ }+ /** Re-read outstanding receipts: committed ones drop out, failed ones join the pending set for the next run. */+ private async refreshPending(): Promise<void> {+ if (!this.pendingRows.size) return;+ const rows = await this.engine.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE id=ANY($1::uuid[])', [[...this.pendingRows.keys()]]);+ const found = new Map(rows.map(row => [row.id, row]));+ for (const [id, pending] of this.pendingRows) {+ const row = found.get(id);+ if (!row || row.state === 'committed') { this.pendingRows.delete(id); continue; }+ if (isTerminal(row)) { this.pendingRows.delete(id); this.failedPending.push(pending.entry); continue; }+ pending.row = row;+ }+ }+ /** Waits, within the run's budget, for every outstanding receipt. */+ private async drainPending(): Promise<void> {+ await this.refreshPending();+ while (this.pendingRows.size && this.remainingWait() > 0) {+ const [oldest] = this.pendingRows.values();+ await this.budgetedWait(oldest.row, this.remainingWait() + COMMIT_GRACE_MS);+ await this.refreshPending();+ }+ }+ /**+ * One page never has two writes in flight from one sweep: a later write+ * would be prepared against the revision the earlier one replaces. Waits+ * (within the budget) for the page's outstanding write, else stops the sweep.+ */+ private async awaitPagePending(slug: string): Promise<void> {+ const outstanding = () => [...this.pendingRows.values()].find(pending => pending.entry.itemRef === slug);+ let pending = outstanding();+ while (pending) {+ if (this.remainingWait() <= 0) { this.stopped = true; throw new ConnectorWaitBudgetStop(pending.row); }+ await this.budgetedWait(pending.row);+ await this.refreshPending();+ pending = outstanding();+ }+ }+ /** Keeps outstanding writes below the principal's outstanding and intent-byte limits; stops the sweep when it cannot. */+ private async makeRoom(): Promise<void> {+ const full = () => this.pendingRows.size >= this.outstandingCap ||+ [...this.pendingRows.values()].reduce((sum, pending) => sum + pending.bytes, 0) >= this.intentByteCap;+ if (!full()) return;+ await this.refreshPending();+ while (full()) {+ const [oldest] = this.pendingRows.values();+ if (this.remainingWait() <= 0) { this.stopped = true; throw new ConnectorWaitBudgetStop(oldest.row); }+ await this.budgetedWait(oldest.row);+ await this.refreshPending();+ }+ }+ /** Records the run's pending set, counts and upgrade state; written only while the lease is held. */+ async finish(): Promise<void> {+ await this.refreshPending().catch(() => {});+ const now = new Date().toISOString();+ const outstanding = [...this.pendingRows.values()].map(pending => pending.entry);+ const complete = this.lastSaveCommitted && !outstanding.length && !this.failedPending.length && !this.stopped;+ // Only a complete --full sweep (which also reconciles deletions) proves that a failed item it never reached+ // was deleted upstream. Delta and targeted runs keep every unreached carried entry for its automatic retry.+ const unreached = this.unreachedCarried();+ const dropUnreached = complete && this.fullSweep && !this.targeted;+ const unresolved = dropUnreached ? [] : unreached;+ if (dropUnreached) this.counts.dropped_upstream += unreached.filter(entry => entry.itemRef !== CHECKPOINT_SLUG).length;+ const pending = [...new Map([...unresolved, ...this.failedPending, ...outstanding, ...(this.pendingCheckpoint ? [this.pendingCheckpoint] : [])]+ .map(entry => [entry.requestId, entry])).values()];+ if (outstanding.length || this.failedPending.length || this.pendingCheckpoint || this.stopped) this.deferred = true;+ const recovery = this.connectorState.upgrade_recovery === 'rewalking_once' && complete ? 'none' : this.connectorState.upgrade_recovery;+ this.connectorState = { ...this.connectorState, pending, upgrade_recovery: recovery, last_run: {+ page_admissions: this.counts.page_admissions, skipped_unchanged: this.counts.skipped_unchanged, pending: pending.length,+ checkpoint_admissions: this.counts.checkpoint_admissions, stopped_on_wait_budget: this.stopped, dropped_upstream: this.counts.dropped_upstream, finished_at: now } };+ await this.writeState();+ }+ /** One statement: the state row changes only while this run still holds the connector sync lease. */+ private async writeState(): Promise<void> {+ if (!this.lease) { await writeManagedConnectorState(this.engine, this.sourceId, this.source.incarnation, this.connectorState); return; }+ this.lease.signal.throwIfAborted();+ const { handle } = this.lease;+ const written = await writeManagedConnectorState(this.engine, this.sourceId, this.source.incarnation, this.connectorState,+ { id: handle.id, token: handle.acquisitionToken, acquiredAt: handle.acquiredAt });+ if (!written) throw new LockStolenError(handle.id);+ }+ /** The last run's counts, for the caller's result. */+ runCounts(): ConnectorRunCounts | null { return this.connectorState.last_run; }+ /**+ * #5470: screens an import or delete through the publication's own preparer+ * on an unadmitted request; the item skips admission only when the no-op+ * kernel finds nothing to publish and the preparer's validation still holds.+ */+ private async unchanged(kind: ConnectorIntentKind, slug: string, intent: ConnectorIntent, snapshot: PageSnapshot | null, sourcePath: string | null): Promise<boolean> {+ try {+ const row = screeningRequest({ source_id: this.sourceId, source_incarnation: this.source.incarnation, slug, page_id: snapshot?.page.id ?? null,+ worktree_id: this.binding?.worktree_id ?? null, authority: this.authority.writer, intent });+ const prepared = await prepareConnectorMutation(this.engine, row);+ if (kind === 'connector_v2_delete') {+ if (this.binding || prepared.noop !== true) return false;+ } else {+ const verdict = await inspectUnchanged(this.engine, { prepared, snapshot, sourcePath, databaseOnly: !this.binding });+ if (verdict.admitReason) return false;+ }+ await prepared.validate?.(this.engine);+ return true;+ } catch (error) {+ if (error instanceof LockStolenError) throw error;+ return false;+ }}- private async submit(kind: ConnectorIntent['kind'], slug: string, sourcePath: string | null, extra: Partial<ConnectorIntent>): Promise<WriteRequest> {+ private async submit(kind: ConnectorIntentKind, slug: string, sourcePath: string | null, extra: Partial<ConnectorIntent>):+ Promise<{ row: WriteRequest | null; pending: boolean; created: boolean }> {+ await this.awaitPagePending(slug);await this.recover(slug);const snapshot = await this.engine.readPageSnapshot(slug, { sourceId: this.sourceId, includeDeleted: true });- if (kind === 'managed_connector_google_receipts') {+ if (kind === 'connector_v2_google_receipts') {if (!snapshot || snapshot.page.id !== extra.googlePageId) throw new OperationError('page_identity_changed', 'The historical Gmail page was deleted or recreated.');- extra.googleReceipts = ownedGoogleReceipts(snapshot, this.source.config, extra.googleReceipts!);+ extra.googleReceipts = ownedGoogleReceipts(snapshot, (this.identity.config as GoogleSourceConfig).account, extra.googleReceipts!);sourcePath = snapshot!.page.source_path!;}- const file = kind === 'managed_connector_checkpoint' ? undefined : await connectorFileTarget(this.engine,+ const file = kind === 'connector_v2_checkpoint' ? undefined : await connectorFileTarget(this.engine,{ source_id: this.sourceId, worktree_id: this.binding?.worktree_id ?? null, slug }, snapshot, extra.content ?? null, sourcePath, this.canonicalRoot);if (file && sourcePath && resolve(file.path) !== resolve(this.canonicalRoot!, sourcePath)) {throw new OperationError('source_changed', 'The connector source path no longer names its canonical file.');}const intent: ConnectorIntent = { kind, connector: this.connector, sourceRoot: this.source.local_path,- configHash: digest(this.source.config), syncAuthority: this.authority, expected_revision: snapshot?.revision ?? null,+ configHash: this.identity.digest, syncAuthority: this.authority, expected_revision: snapshot?.revision ?? null,sourcePath, noEmbed: this.noEmbed, noSchemaPack: this.noSchemaPack, checkpointKey: this.checkpointKey, checkpointBefore: this.checkpoint,ownerEpoch: this.binding ? String(this.binding.owner_epoch) : null, canonicalRoot: this.canonicalRoot,filePath: file?.path ?? null, fileBeforeHash: file?.expectedBeforeHash ?? null, ...extra };const callerIntent = { ...intent, syncAuthority: undefined, newestContentAt: undefined,- ...(kind === 'managed_connector_checkpoint' ? { receipts: undefined } : {}) };+ ...(kind === 'connector_v2_checkpoint' ? { receipts: undefined } : {}) };const principal = this.authority.writer.principal;const baseRequestId = stableId({ principal, sourceId: this.sourceId, incarnation: this.source.incarnation, callerIntent });+ const page = kind === 'connector_v2_import' || kind === 'connector_v2_delete';+ this.reseen.add(baseRequestId);+ this.reseenItems.add(slug);const admission = (retry?: ConnectorRetry) => {const link = retry ? { retryBase: baseRequestId, retryOf: retry.retryOf, retryAttempt: retry.attempt } : {};return { principal, requestId: retry?.requestId ?? baseRequestId, operation: 'submit_job', sourceId: this.sourceId,@@ -351,11 +667,14 @@ export class ManagedConnectorSync {} else if (retry) throw new OperationError('storage_error', 'The approved connector retry receipt is unavailable.');return { retry, input, row };};- const mayRetry = (row: WriteRequest | null) => this.retryFailed && row && ['failed', 'conflict'].includes(row.state) &&+ const automatic = this.autoRetry.has(baseRequestId);+ const mayRetry = (row: WriteRequest | null) => (this.retryFailed || automatic) && row && ['failed', 'conflict'].includes(row.state) &&row.request_id === (this.retryApprovals.get(baseRequestId) ?? baseRequestId);const prior = await selected(this.engine);let row = prior.row;+ let admitted = false;if (mayRetry(row)) {+ const failedRow = row!;const lock = this.binding ? await acquireWorktree(this.binding, 1000, undefined, this.engine) : null;try {if (this.binding && !lock) {@@ -382,29 +701,71 @@ export class ManagedConnectorSync {const accepted = await admitWriteInTransaction(tx, admission(retry));await tx.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES('managed-connector-retry',$1,$2::text::jsonb)ON CONFLICT(op,fingerprint) DO UPDATE SET completed_keys=EXCLUDED.completed_keys,updated_at=now()`, [baseRequestId, JSON.stringify([retry])]);+ admitted = true;return accepted;});+ this.retryApprovals.set(baseRequestId, row.request_id);} catch (error) {+ // An automatic retry waits behind other accepted work like any pending write.+ if (automatic && !this.retryFailed && error instanceof OperationError && error.code === 'write_pending') {+ this.failedPending.push({ itemRef: slug, requestId: failedRow.request_id, baseRequestId, admittedAt: new Date(failedRow.created_at).toISOString() });+ return { row: failedRow, pending: true, created: !snapshot };+ }if (error instanceof OperationError) throw error;throw new OperationError('storage_error', 'Connector retry approval could not be confirmed.','Repeat the same connector sync options; an admitted replacement keeps its existing request identity.');} finally { await lock?.release(); }} else if (!row) {+ if (page && !prior.retry && await this.unchanged(kind, slug, intent, snapshot, sourcePath)) {+ this.counts.skipped_unchanged++;+ return { row: null, pending: false, created: false };+ }row = await this.engine.transaction(async tx => {await this.assertLease(tx);return admitWriteInTransaction(tx, prior.input);});+ admitted = true;}- row = await waitForWrite(this.engine, row!, loadConfig() ?? { engine: this.engine.kind });- writeResponse(row);- if (kind !== 'managed_connector_checkpoint') this.receipts.push(row.id);- return row;+ if (admitted) {+ if (page) this.counts.page_admissions++;+ if (kind === 'connector_v2_checkpoint') this.counts.checkpoint_admissions++;+ }+ if (kind === 'connector_v2_google_receipts') {+ row = await waitForWrite(this.engine, row!, loadConfig() ?? { engine: this.engine.kind });+ writeResponse(row);+ this.receipts.push(row.id);+ return { row, pending: false, created: false };+ }+ row = await this.budgetedWait(row!);+ if (kind === 'connector_v2_checkpoint') {+ if (!isTerminal(row)) {+ this.pendingCheckpoint = { itemRef: CHECKPOINT_SLUG, requestId: row.request_id, baseRequestId, admittedAt: new Date(row.created_at).toISOString() };+ this.stopped = true;+ throw new ConnectorWaitBudgetStop(row);+ }+ writeResponse(row);+ return { row, pending: false, created: false };+ }+ if (isTerminal(row)) {+ writeResponse(row);+ this.receipts.push(row.id);+ if (row.outcome?.noop !== true) {+ if (kind === 'connector_v2_delete') this.counts.deleted++; else if (row.outcome?.status === 'created') this.counts.created++; else this.counts.updated++;+ }+ return { row, pending: false, created: row.outcome?.status === 'created' };+ }+ this.receipts.push(row.id);+ this.pendingRows.set(row.id, { row, bytes: Buffer.byteLength(JSON.stringify(intent)),+ entry: { itemRef: slug, requestId: row.request_id, baseRequestId, admittedAt: new Date(row.created_at).toISOString() } });+ if (!snapshot) this.counts.created++; else if (kind === 'connector_v2_delete') this.counts.deleted++; else this.counts.updated++;+ await this.makeRoom();+ return { row, pending: true, created: !snapshot };}}export async function prepareConnectorMutation(engine: BrainEngine, row: WriteRequest): Promise<PreparedMutation> {const p = row.intent as ConnectorIntent | null;- if (!p || !['managed_connector_import', 'managed_connector_delete', 'managed_connector_checkpoint', 'managed_connector_google_receipts'].includes(p.kind) ||+ if (!p || !CONNECTOR_V2_KINDS.includes(p.kind) ||p.syncAuthority.writer.remote || p.syncAuthority.remoteJob) throw new OperationError('permission_denied', 'Unsupported connector authority.');if (!row.worktree_id && (row.authority.databaseOnlyReason !== 'connector_database' || p.syncAuthority.writer.databaseOnlyReason !== 'connector_database') ||row.worktree_id && (row.authority.databaseOnlyReason !== undefined || p.syncAuthority.writer.databaseOnlyReason !== undefined)) {@@ -414,7 +775,9 @@ export async function prepareConnectorMutation(engine: BrainEngine, row: WriteReawait validateSyncAuthority(tx, p.syncAuthority, row.slug);const [source] = await tx.executeRaw<ConnectorSource>('SELECT incarnation,archived,local_path,config FROM sources WHERE id=$1', [row.source_id]);if (!source || source.archived || source.incarnation !== row.source_incarnation || source.config.kind !== p.connector ||- digest(source.config) !== p.configHash || source.local_path !== p.sourceRoot) throw new OperationError('source_changed', 'The connector configuration changed after admission.');+ connectorIdentity(p.connector, source.config, source.local_path).digest !== p.configHash || source.local_path !== p.sourceRoot) {+ throw new OperationError('source_changed', 'The connector configuration changed after admission.');+ }const binding = await getWorktreeBinding(tx, row.source_id);if ((binding?.worktree_id ?? null) !== row.worktree_id || (binding ? String(binding.owner_epoch) : null) !== p.ownerEpoch) {throw new OperationError('source_changed', 'The connector ownership binding changed after admission.');@@ -423,13 +786,13 @@ export async function prepareConnectorMutation(engine: BrainEngine, row: WriteReif (p.filePath !== null && (!p.canonicalRoot || !isWriteTargetContained(p.filePath, p.canonicalRoot) || persistenceFileHash(p.filePath) !== p.fileBeforeHash)) {throw new OperationError('source_changed', 'The connector canonical file changed after admission.');}- if (p.kind !== 'managed_connector_checkpoint') {+ if (p.kind !== 'connector_v2_checkpoint') {const [checkpoint] = await tx.executeRaw<{ completed_keys: unknown[] }>("SELECT completed_keys FROM op_checkpoints WHERE op='managed-connector' AND fingerprint=$1", [p.checkpointKey]);if (digest(checkpoint?.completed_keys ?? []) !== digest(p.checkpointBefore)) throw new OperationError('revision_conflict', 'The connector checkpoint changed before publication.');}};await validate(engine);- if (p.kind === 'managed_connector_checkpoint') return { observedRevision: null, sourceExclusive: true, validate, apply: async tx => {+ if (p.kind === 'connector_v2_checkpoint') return { observedRevision: null, sourceExclusive: true, validate, apply: async tx => {const [current] = await tx.executeRaw<{ completed_keys: unknown[] }>("SELECT completed_keys FROM op_checkpoints WHERE op='managed-connector' AND fingerprint=$1 FOR UPDATE", [p.checkpointKey]);if (digest(current?.completed_keys ?? []) !== digest(p.checkpointBefore)) throw new OperationError('revision_conflict', 'The connector checkpoint changed during the sweep.');const receipts = p.receipts ?? [];@@ -446,8 +809,8 @@ 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,+ const deleteFile = p.kind === 'connector_v2_delete' ? await prepareFileTarget(engine, row, snapshot, null) : undefined;+ if (p.kind === 'connector_v2_delete') return { observedRevision: snapshot?.revision ?? null, sourceExclusive: true, validate,file: deleteFile, ...databaseOnlyPublication(row, deleteFile),noop: !snapshot || snapshot.page.deleted_at != null, apply: async tx => {if (snapshot && snapshot.page.deleted_at == null) {@@ -456,10 +819,11 @@ export async function prepareConnectorMutation(engine: BrainEngine, row: WriteRe}return { status: 'soft_deleted', slug: row.slug, source_id: row.source_id, noop: !snapshot || snapshot.page.deleted_at != null };} };- if (p.kind === 'managed_connector_google_receipts') {+ if (p.kind === 'connector_v2_google_receipts') {if (p.connector !== 'google' || !p.googleReceipts) throw new OperationError('invalid_params', 'Invalid Google attachment receipt mutation.');const [source] = await engine.executeRaw<ConnectorSource>('SELECT incarnation,archived,local_path,config FROM sources WHERE id=$1', [row.source_id]);- const prepared = await prepareGoogleReceiptPatch(engine, row, snapshot, source.config, p.googleReceipts);+ const account = (connectorIdentity('google', source.config, source.local_path).config as GoogleSourceConfig).account;+ const prepared = await prepareGoogleReceiptPatch(engine, row, snapshot, account, p.googleReceipts);return { ...prepared, validate };}if (!p.sourcePath || typeof p.content !== 'string' || slugifyPath(p.sourcePath) !== row.slug ||@@ -471,7 +835,15 @@ export async function prepareConnectorMutation(engine: BrainEngine, row: WriteReif (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;+ // Facts and takes fences added on the brain (remember, loop extraction) are not part of the provider's render;+ // carry them over verbatim so a re-render does not expire those facts. A render that brings its own fence+ // (a provider body that contains one) owns it, and ambiguous stored fences are left to the existing path.+ const hasFence = (text: string | null | undefined) => [FACTS_FENCE_BEGIN, TAKES_FENCE_BEGIN].some(begin => (text ?? '').includes(begin));+ const fenced = snapshot && hasFence(snapshot.page.compiled_truth) && !hasFence(parsed.compiled_truth) && !conceptPreservationHold(snapshot.page)+ ? preserveCanonicalFences(snapshot.page, parsed.compiled_truth) : parsed.compiled_truth;+ const content = (carried.materialized || fenced !== parsed.compiled_truth) && snapshot+ ? serializePageToMarkdown({ ...snapshot.page, ...parsed, compiled_truth: fenced, 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, content, { sourceId: row.source_id, sourcePath: p.sourcePath,filename: basename(p.sourcePath).replace(/\.mdx?$/i, ''), noEmbed: true, allowEmptyOverwrite: true, activePack,@@ -497,6 +869,20 @@ export async function prepareConnectorMutation(engine: BrainEngine, row: WriteRe} };}+/**+ * A connector intent in the retired `managed_connector_*` format. The consumer+ * recovers any file publication already in progress before it prepares a+ * request, so this runs only for requests with nothing left to recover and+ * fails them terminally. A request admitted before the upgrade's cutoff was+ * written by this host's previous binary and is simply fetched again; one+ * admitted after it names the connector host that still needs upgrading.+ */+export async function prepareOutdatedConnectorMutation(engine: BrainEngine, row: WriteRequest): Promise<PreparedMutation> {+ const cutoff = await readConnectorV2Cutoff(engine);+ const preUpgrade = cutoff !== null && new Date(row.created_at).getTime() < new Date(cutoff).getTime();+ throw new OperationError('connector_intent_outdated', preUpgrade ? CONNECTOR_INTENT_OUTDATED_PRE_UPGRADE : CONNECTOR_INTENT_OUTDATED_OLD_HOST);+}+export function rethrowConnectorWriteError(error: unknown): void {- if (error instanceof OperationError || error instanceof LockStolenError) throw error;+ if (error instanceof OperationError || error instanceof LockStolenError || error instanceof ConnectorWaitBudgetStop) throw error;}diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.tsindex 4d5c87a5c5..54b10309e0 100644--- a/src/core/persistence/coordinator.ts+++ b/src/core/persistence/coordinator.ts@@ -18,6 +18,7 @@ import { tryAcquirePublicationCapacity } from './pool-capacity.ts';import { queuePublicationEffects } from './effect-journal.ts';import { authorizePageVisibility } from './page-visibility.ts';import { withNoRepoWriteThroughWarning } from '../write-through.ts';+import { assertUnboundPublication, classifyUnboundPage, unboundWriteWarning } from './unbound-source.ts';import { assertRecoveryStagingAbsent, cleanupRecoveryStaging, recoveryStagingFile, upgradeRecoveryStaging } from './staging.ts';import { assertMutationProtocol, assertSharedSkillPersistence, declarePersistenceProtocol, PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';import { assertBundleRecoveryBinding, bundleFileHash, prepareBundleRecovery, publishStagedBundleFile, stageBundleFile, type MutationFile } from './bundle-files.ts';@@ -28,9 +29,11 @@ interface PreparedMutationBase {observedRevision: string | null;additionalPageKeys?: readonly {sourceId:string;slug:string}[];noop?: boolean;+ /** #5470 screening only: the content is unchanged, but publication still runs (and queues effects). */+ contentUnchanged?: boolean;deferEmbedding?: boolean;/** Why a page write bound to a worktree publishes no file (receipt `write_through.skipped`). */- databaseOnlyReason?: 'db_only';+ databaseOnlyReason?: 'db_only' | 'unbound_source';/** Must perform only transaction-composable database work. */apply(tx: BrainEngine): Promise<Record<string, unknown>>;validate?(tx: BrainEngine): Promise<void>;@@ -202,6 +205,7 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, prconst snapshot = await tx.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });await authorizePageVisibility(tx, row.authority, row.slug);if ((snapshot?.page.id ?? null) !== row.page_id) throw new OperationError('page_identity_changed', 'The accepted page was deleted or recreated.');+ await assertUnboundPublication(tx, row, snapshot?.page.source_path);if ((snapshot?.revision ?? null) !== prepared.observedRevision) throw new OperationError('revision_conflict', 'The page changed during preparation.', 'Read its current revision and submit the updated intent with a new request_id.');}await prepared.validate?.(tx);@@ -230,11 +234,15 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, prawait hooks.boundary?.('after_publication', row);}const outcome = await withCoordinatedWrite(tx, [row.source_id], () => prepared.apply(tx));+ if (!skill) await classifyUnboundPage(tx, row);const 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: 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);+ if (row.operation === 'put_page' && (outcome.write_through as { skipped?: string }).skipped === 'unbound_source') {+ outcome.write_through = { ...outcome.write_through as object, warning: unboundWriteWarning(row.source_id, row.authority.databaseOnlyReason === 'unbound_source') };+ }await queuePublicationEffects(tx, row, final, outcome, prepared);await hooks.boundary?.('before_commit', row);const committed = await completeWrite(tx, current, 'committed', outcome);diff --git a/src/core/persistence/derived-facts.ts b/src/core/persistence/derived-facts.tsnew file mode 100644index 0000000000..0fc280bad6--- /dev/null+++ b/src/core/persistence/derived-facts.ts@@ -0,0 +1,56 @@+import type { BrainEngine } from '../engine.ts';+import { OperationError } from '../ops/contract.ts';+import { currentSubmissionAuthority } from '../minions/submission-authority.ts';+import { withCoordinatedWrite } from './context.ts';+import { currentVerifiedLocalWriter } from './identity.ts';+import { managedPersistenceEnabled } from './ownership.ts';+import { assertPersistenceAccepting } from './service.ts';++/**+ * Database-only fact rows derived from page text (the fence reconcile, the+ * conversation fact index) never touch a canonical file, so a managed brain+ * publishes them like derived links: inside the coordinator's source+ * capability, serialized on the page key. Returns false on an unmanaged brain.+ * Runs before any provider spend.+ */+export async function managedDerivedFactsPreflight(engine: BrainEngine, sourceId: string): Promise<boolean> {+ if (!await managedPersistenceEnabled(engine)) return false;+ assertPersistenceAccepting(engine);+ const job = currentSubmissionAuthority();+ if (job && job.kind !== 'application' || currentVerifiedLocalWriter()?.remote) {+ throw new OperationError('permission_denied', 'Managed fact maintenance requires a local writer; remote maintenance jobs are not supported.');+ }+ const [source] = await engine.executeRaw<{ archived: boolean }>('SELECT archived FROM sources WHERE id=$1', [sourceId]);+ if (!source || source.archived) throw new OperationError('source_changed', 'The fact maintenance source is not active.');+ return true;+}++/**+ * One committed transaction holding the source capability and the page keys,+ * after revalidating (under a shared source lock, before the page locks) that+ * the source is still active: model work may have outlived an archive.+ */+export async function withDerivedFactsWrite<T>(engine: BrainEngine, sourceId: string, slugs: readonly string[],+ fn: (tx: BrainEngine) => Promise<T>): Promise<T> {+ return engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], async () => {+ const [source] = await tx.executeRaw<{ archived: boolean }>('SELECT archived FROM sources WHERE id=$1 FOR SHARE', [sourceId]);+ if (!source || source.archived) throw new OperationError('source_changed', 'The fact maintenance source changed during extraction; nothing was written.');+ await tx.lockPageKeys(slugs.map(slug => ({ sourceId, slug })));+ return fn(tx);+ }));+}++/**+ * Legacy writers keep their own engine call on unmanaged brains. On a managed+ * brain the page must still be live under its lock, so rows are never+ * published for a page deleted or purged while the model ran.+ */+export async function writeDerivedFacts<T>(engine: BrainEngine, sourceId: string, slug: string,+ fn: (db: BrainEngine) => Promise<T>): Promise<T> {+ if (!await managedPersistenceEnabled(engine)) return fn(engine);+ return withDerivedFactsWrite(engine, sourceId, [slug], async tx => {+ const [page] = await tx.executeRaw('SELECT id FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL', [sourceId, slug]);+ if (!page) throw new OperationError('page_not_found', 'The page was deleted during fact extraction; nothing was written.');+ return fn(tx);+ });+}diff --git a/src/core/persistence/effect-git.ts b/src/core/persistence/effect-git.tsindex 46fd1ebac8..620bf6907f 100644--- a/src/core/persistence/effect-git.ts+++ b/src/core/persistence/effect-git.ts@@ -19,72 +19,148 @@ function git(root: string, hooks: string, args: string[], signal?: AbortSignal):});}+type GitOutcome = { git: string; reason?: string; push?: string };+/**- * Caller owns the native worktree lock. Never run pull, rebase, or legacy hooks.- * `hardened` is the caller's durability probe of `root`, taken before it locked- * the worktree.+ * Stage one single-file target. Returns 'changed' when the index now differs+ * for the path, 'unchanged', or a skip outcome for an absent target.*/-export async function publishGitEffect(root: string, relativePath: string, signal?: AbortSignal,- hardened?: boolean): Promise<Record<string, unknown>> {- if (!(hardened ?? await isDurabilityHardenedAsync(root))) return { git: 'skipped', reason: 'durability_not_enabled', push: 'skipped' };+async function stageTarget(root: string, hooks: string, relativePath: string, signal?: AbortSignal): Promise<{ path: string; state: 'changed' | 'unchanged' } | { path: string; skip: GitOutcome }> {const path = nativeFileTarget(root, resolvePath(root, relativePath), 'git_target_unsafe');relativePath = relative(root, path).split(sep).join('/');+ const tracked = await git(root, hooks, ['ls-files', '-z', '--error-unmatch', '--', relativePath], signal);+ if (tracked.code !== 0 && tracked.code !== 1) throw new OperationError('git_unavailable', 'Cannot inspect the canonical Git target.');+ const changed = await git(root, hooks, ['status', '--porcelain', '--untracked-files=all', '--', relativePath], signal);+ if (changed.code !== 0) throw new OperationError('git_unavailable', 'Cannot inspect the canonical Git target.');+ if (changed.stdout.trim()) {+ if (tracked.code === 0 || existsSync(path)) {+ const add = await git(root, hooks, ['add', '-A', '--', relativePath], signal);+ if (add.code !== 0) throw new OperationError('git_unavailable', 'Cannot stage the canonical Git target.');+ }+ const diff = await git(root, hooks, ['diff', '--cached', '--quiet', '--', relativePath], signal);+ if (diff.code === 1) return { path: relativePath, state: 'changed' };+ if (diff.code !== 0) throw new OperationError('git_unavailable', 'Cannot compare the canonical Git target.');+ return { path: relativePath, state: 'unchanged' };+ }+ if (tracked.code === 0) return { path: relativePath, state: 'unchanged' };+ if (existsSync(path)) throw new OperationError('git_target_unsafe', 'Git cannot identify the existing canonical file by its native spelling.',+ 'Reconcile the index and worktree spelling before retrying publication.');+ let parent = dirname(path);+ while (!existsSync(parent)) {+ if (parent === resolvePath(root)) throw new OperationError('git_target_unsafe', 'The canonical Git root disappeared.');+ parent = dirname(parent);+ }+ const scope = relative(root, parent).split(sep).join('/') || '.';+ const deleted = await git(root, hooks, ['diff', '--name-only', '--diff-filter=D', '--no-renames', '-z', '--', scope], signal);+ const staged = await git(root, hooks, ['diff', '--cached', '--name-only', '--diff-filter=D', '--no-renames', '-z', '--', scope], signal);+ if (deleted.code !== 0 || staged.code !== 0) throw new OperationError('git_unavailable', 'Cannot inspect canonical Git deletions.');+ for (const entry of new Set(`${deleted.stdout}${staged.stdout}`.split('\0').filter(Boolean))) {+ if (existsSync(join(root, entry))) continue;+ let missingParent = dirname(nativeFileTarget(root, join(root, entry), 'git_target_unsafe'));+ while (!existsSync(missingParent)) {+ if (missingParent === resolvePath(root)) throw new OperationError('git_target_unsafe', 'The canonical Git root disappeared.');+ missingParent = dirname(missingParent);+ }+ if (missingParent === parent) throw new OperationError('git_target_unsafe', 'The absent target cannot be distinguished from an indexed deletion.',+ 'Reconcile the recorded deletion path with the Git index before retrying publication.');+ }+ return { path: relativePath, skip: { git: 'skipped', reason: 'target_absent', push: 'skipped' } };+}++function withHooks<T>(run: (hooks: string) => Promise<T>): Promise<T> {const base = join(persistenceHome(), 'empty-hooks');mkdirSync(base, { recursive: true, mode: 0o700 });const hooks = mkdtempSync(join(base, 'effect-'));- try {- const tracked = await git(root, hooks, ['ls-files', '-z', '--error-unmatch', '--', relativePath], signal);- if (tracked.code !== 0 && tracked.code !== 1) throw new OperationError('git_unavailable', 'Cannot inspect the canonical Git target.');- const changed = await git(root, hooks, ['status', '--porcelain', '--untracked-files=all', '--', relativePath], signal);- if (changed.code !== 0) throw new OperationError('git_unavailable', 'Cannot inspect the canonical Git target.');- let commit = 'unchanged';- if (changed.stdout.trim()) {- if (tracked.code === 0 || existsSync(path)) {- const add = await git(root, hooks, ['add', '-A', '--', relativePath], signal);- if (add.code !== 0) throw new OperationError('git_unavailable', 'Cannot stage the canonical Git target.');- }- const diff = await git(root, hooks, ['diff', '--cached', '--quiet', '--', relativePath], signal);- if (diff.code === 1) {- // --only keeps unrelated staged paths out of this commit. After a lost- // database acknowledgment the same HEAD/file state is an exact no-op.- const result = await git(root, hooks, ['commit', '--only', '-m', 'gbrain: persist canonical memory update', '--', relativePath], signal);- if (result.code !== 0) throw new OperationError('git_unavailable', 'Cannot commit the canonical Git target.');- commit = 'committed';- } else if (diff.code !== 0) throw new OperationError('git_unavailable', 'Cannot compare the canonical Git target.');- } else if (tracked.code !== 0) {- if (existsSync(path)) throw new OperationError('git_target_unsafe', 'Git cannot identify the existing canonical file by its native spelling.',- 'Reconcile the index and worktree spelling before retrying publication.');- let parent = dirname(path);- while (!existsSync(parent)) {- if (parent === resolvePath(root)) throw new OperationError('git_target_unsafe', 'The canonical Git root disappeared.');- parent = dirname(parent);- }- const scope = relative(root, parent).split(sep).join('/') || '.';- const deleted = await git(root, hooks, ['diff', '--name-only', '--diff-filter=D', '--no-renames', '-z', '--', scope], signal);- const staged = await git(root, hooks, ['diff', '--cached', '--name-only', '--diff-filter=D', '--no-renames', '-z', '--', scope], signal);- if (deleted.code !== 0 || staged.code !== 0) throw new OperationError('git_unavailable', 'Cannot inspect canonical Git deletions.');- for (const entry of new Set(`${deleted.stdout}${staged.stdout}`.split('\0').filter(Boolean))) {- if (existsSync(join(root, entry))) continue;- let missingParent = dirname(nativeFileTarget(root, join(root, entry), 'git_target_unsafe'));- while (!existsSync(missingParent)) {- if (missingParent === resolvePath(root)) throw new OperationError('git_target_unsafe', 'The canonical Git root disappeared.');- missingParent = dirname(missingParent);- }- if (missingParent === parent) throw new OperationError('git_target_unsafe', 'The absent target cannot be distinguished from an indexed deletion.',- 'Reconcile the recorded deletion path with the Git index before retrying publication.');+ return run(hooks).finally(() => rmSync(hooks, { recursive: true, force: true }));+}++/**+ * #5530: commit a group of single-file targets with one `commit --only`. The+ * caller owns the native worktree lock and has probed durability. Each+ * target's outcome (or its own error) is keyed by its requested relative+ * path; a failing target never enters the commit. Nothing is pushed.+ */+export async function commitGitTargets(root: string, relativePaths: string[], signal?: AbortSignal): Promise<Map<string, GitOutcome | OperationError>> {+ const results = new Map<string, GitOutcome | OperationError>();+ await withHooks(async hooks => {+ // One ls-files, one status, one add and one diff for the group; targets+ // that are neither tracked nor present take the per-target path, which+ // owns the absent-target and native-spelling refusals.+ const normalized = new Map<string, string>();+ for (const requested of new Set(relativePaths)) {+ try { normalized.set(requested, relative(root, nativeFileTarget(root, resolvePath(root, requested), 'git_target_unsafe')).split(sep).join('/')); }+ catch (error) { if (!(error instanceof OperationError)) throw error; results.set(requested, error); }+ }+ const paths = [...new Set(normalized.values())];+ const list = async (args: string[]) => {+ const out = paths.length ? await git(root, hooks, [...args, '--', ...paths], signal) : { stdout: '', code: 0 };+ if (out.code !== 0) throw new OperationError('git_unavailable', 'Cannot inspect the canonical Git target.');+ return out.stdout;+ };+ const tracked = new Set((await list(['ls-files', '-z'])).split('\0').filter(Boolean));+ const dirty = new Set((await list(['status', '--porcelain', '-z', '--no-renames', '--untracked-files=all'])).split('\0').filter(Boolean).map(entry => entry.slice(3)));+ const changed: { requested: string; path: string }[] = [];+ const staged: string[] = [];+ for (const [requested, path] of normalized) {+ if (!tracked.has(path) && !(existsSync(join(root, path)) && dirty.has(path))) {+ try {+ const target = await stageTarget(root, hooks, requested, signal);+ if ('skip' in target) results.set(requested, target.skip);+ else if (target.state === 'changed') changed.push({ requested, path: target.path });+ else results.set(requested, { git: 'unchanged' });+ } catch (error) { if (!(error instanceof OperationError)) throw error; results.set(requested, error); }+ } else if (dirty.has(path)) staged.push(path);+ else results.set(requested, { git: 'unchanged' });+ }+ if (staged.length) {+ const add = await git(root, hooks, ['add', '-A', '--', ...new Set(staged)], signal);+ if (add.code !== 0) throw new OperationError('git_unavailable', 'Cannot stage the canonical Git target.');+ const diff = await git(root, hooks, ['diff', '--cached', '--name-only', '-z', '--no-renames', '--', ...new Set(staged)], signal);+ if (diff.code !== 0) throw new OperationError('git_unavailable', 'Cannot compare the canonical Git target.');+ const indexed = new Set(diff.stdout.split('\0').filter(Boolean));+ for (const [requested, path] of normalized) {+ if (!staged.includes(path) || results.has(requested)) continue;+ if (indexed.has(path)) changed.push({ requested, path });+ else results.set(requested, { git: 'unchanged' });}- return { git: 'skipped', reason: 'target_absent', push: 'skipped' };}+ if (!changed.length) return;+ // --only keeps unrelated staged paths out of this commit. After a lost+ // database acknowledgment the same HEAD/file state is an exact no-op.+ const commitPaths = [...new Set(changed.map(c => c.path))];+ const message = commitPaths.length === 1 ? 'gbrain: persist canonical memory update' : `gbrain: persist ${commitPaths.length} canonical memory updates`;+ const result = await git(root, hooks, ['commit', '--only', '-m', message, '--', ...commitPaths], signal);+ const outcome = result.code === 0 ? { git: 'committed' } : new OperationError('git_unavailable', 'Cannot commit the canonical Git target.');+ for (const c of changed) results.set(c.requested, outcome);+ });+ return results;+}++/** Push the current branch to its tracking remote once. A plain push is idempotent and cannot import remote canonical content. */+export async function pushGitRoot(root: string, signal?: AbortSignal): Promise<{ push: 'committed' } | { push: 'skipped'; reason: 'no_tracking_remote' }> {+ return withHooks(async hooks => {const branch = await git(root, hooks, ['symbolic-ref', '--quiet', '--short', 'HEAD'], signal);- if (branch.code !== 0) return { git: commit, push: 'skipped', reason: 'no_tracking_remote' };+ if (branch.code !== 0) return { push: 'skipped', reason: 'no_tracking_remote' } as const;const remote = await git(root, hooks, ['config', '--get', `branch.${branch.stdout.trim()}.remote`], signal);const merge = await git(root, hooks, ['config', '--get', `branch.${branch.stdout.trim()}.merge`], signal);- if (remote.code !== 0 || merge.code !== 0 || !remote.stdout.trim() || remote.stdout.trim() === '.') {- return { git: commit, push: 'skipped', reason: 'no_tracking_remote' };- }- // A plain push is idempotent and cannot import remote canonical content.+ if (remote.code !== 0 || merge.code !== 0 || !remote.stdout.trim() || remote.stdout.trim() === '.') return { push: 'skipped', reason: 'no_tracking_remote' } as const;const push = await git(root, hooks, ['push', '--', remote.stdout.trim(), `HEAD:${merge.stdout.trim()}`], signal);if (push.code !== 0) throw new OperationError('git_push_unavailable', 'The canonical commit is durable locally; its push will retry.');- return { git: commit, push: 'committed' };- } finally { rmSync(hooks, { recursive: true, force: true }); }+ return { push: 'committed' } as const;+ });+}++/**+ * Caller owns the native worktree lock. Never run pull, rebase, or legacy hooks.+ * `hardened` is the caller's durability probe of `root`, taken before it locked+ * the worktree.+ */+export async function publishGitEffect(root: string, relativePath: string, signal?: AbortSignal,+ hardened?: boolean): Promise<Record<string, unknown>> {+ if (!(hardened ?? await isDurabilityHardenedAsync(root))) return { git: 'skipped', reason: 'durability_not_enabled', push: 'skipped' };+ const outcome = (await commitGitTargets(root, [relativePath], signal)).get(relativePath)!;+ if (outcome instanceof OperationError) throw outcome;+ if (outcome.reason === 'target_absent') return outcome;+ const pushed = await pushGitRoot(root, signal);+ return { git: outcome.git, ...pushed };}diff --git a/src/core/persistence/effect-journal.ts b/src/core/persistence/effect-journal.tsindex 09295ba874..f8417fc415 100644--- a/src/core/persistence/effect-journal.ts+++ b/src/core/persistence/effect-journal.ts@@ -62,6 +62,40 @@ export async function claimPersistenceEffect(engine: BrainEngine, hostId: string});}+/** #5530: an effect that commits exactly one recorded file (not a withdrawal walk or a source scan). */+export function singleFileGitEffect(effect: PersistenceEffect): boolean {+ return effect.kind === 'git' && typeof effect.data.relative_path === 'string' && effect.data.version === undefined+ && !effect.data.source_scan && effect.data.targets === undefined;+}++/**+ * #5530: claim up to `limit` more ready single-file Git effects for one+ * worktree, under the same readiness, recovery and withdrawal-mirror ordering+ * rules as claimPersistenceEffect, so the runner commits them together.+ */+export async function claimCoalescedGitEffects(engine: BrainEngine, hostId: string, worktreeId: string, limit: number): Promise<PersistenceEffect[]> {+ if (limit <= 0) return [];+ const rows = await engine.transactionDirect(async tx => {+ await declarePersistenceProtocol(tx);+ return tx.executeRaw<PersistenceEffect>(`WITH ready AS (SELECT e.id FROM persistence_effects e+ JOIN persistence_worktrees w ON w.id=e.worktree_id AND w.owner_host_id=$1::uuid+ WHERE e.worktree_id=$2::uuid AND e.kind='git' AND e.data ? 'relative_path'+ AND NOT (e.data ? 'targets') AND NOT (e.data ? 'source_scan') AND NOT (e.data ? 'version')+ AND (e.state='queued' OR e.state='running' AND e.claim_expires_at<now()) AND e.next_attempt_at<=now()+ 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 NOT EXISTS (SELECT 1 FROM persistence_effects mirror+ WHERE mirror.request_id=e.request_id AND mirror.kind='withdrawal-mirror' AND mirror.state<>'committed')+ ORDER BY e.next_attempt_at,e.id LIMIT $3 FOR UPDATE OF e SKIP LOCKED)+ UPDATE persistence_effects p SET state='running',execution_token=gen_random_uuid(),+ claim_expires_at=now()+interval '2 minutes',attempts=attempts+1,updated_at=now()+ FROM ready WHERE p.id=ready.id RETURNING p.*`, [hostId, worktreeId, limit]);+ });+ return rows.sort((a, b) => Number(a.id) - Number(b.id));+}+export async function renewPersistenceEffectClaim(engine: SqlEngine, effect: PersistenceEffect): Promise<boolean> {const rows = await engine.executeRaw(`UPDATE persistence_effects SET claim_expires_at=now()+interval '2 minutes',updated_at=now()WHERE id=$1 AND execution_token=$2::uuid AND state='running' AND recovery IS NULL AND ${PERSISTENCE_PROTOCOL_PREDICATE} RETURNING id`, [effect.id, effect.execution_token]);diff --git a/src/core/persistence/effects.ts b/src/core/persistence/effects.tsindex 1610aed677..f43981d902 100644--- a/src/core/persistence/effects.ts+++ b/src/core/persistence/effects.ts@@ -17,6 +17,7 @@ import { validateEmbeddingCreds, EmbeddingCredentialError } from '../embed-preflimport { wrapChunkTextsForStoredMode } from '../embedding-context.ts';import { isEmbedRetriableError, MAX_RATE_LIMIT_RETRIES, rateLimitDelayMs, restampIfDemotedToTitleTier, transientBackoffMs } from '../embed-retry.ts';import { AIConfigError, normalizeAIError } from '../ai/errors.ts';+import { EMBEDDING_ZERO_NORM, isEmbeddingZeroNormError, type EmbeddingZeroNormError } from '../ai/embedding-guard.ts';import { isAIInvocationPolicyError, withAIInvocationPreflight } from '../ai/invocation-guard.ts';import { quoteIdentifier } from '../search/embedding-column.ts';import { acquireWorktree, getWorktreeBinding, type WorktreeBinding } from './ownership.ts';@@ -24,9 +25,9 @@ import { persistenceFileHash, transientDatabaseFailure } from './coordinator.ts'import { sha256 } from './digest.ts';import { prepareFileTarget } from './page-prepare.ts';import { isSourceDbOnlySlug } from './source-storage.ts';-import { advanceEffectCursor, claimPersistenceEffect, completeEffect, failEffect, parkEffect, renewPersistenceEffectClaim, requeueEffect, retryEffect } from './effect-journal.ts';+import { advanceEffectCursor, claimCoalescedGitEffects, claimPersistenceEffect, completeEffect, failEffect, parkEffect, renewPersistenceEffectClaim, requeueEffect, retryEffect, singleFileGitEffect } from './effect-journal.ts';import { guardEffectSource, recoverEffectPublication, reserveEffectRecovery } from './effect-recovery.ts';-import { publishGitEffect } from './effect-git.ts';+import { commitGitTargets, publishGitEffect, pushGitRoot } from './effect-git.ts';import { isDurabilityHardenedAsync } from '../brain-repo-durability.ts';import { dispatchFactsBackstopEffect } from './effect-facts.ts';import { PARK_AFTER_FAILURES, type EffectRecovery, type PersistenceEffect } from './effect-model.ts';@@ -113,40 +114,56 @@ async function mirrorPage(engine: BrainEngine, effect: PersistenceEffect, bindinawait recoverEffectPublication(engine, effect, opts.hostId, opts);}+/**+ * Validate a single-file Git effect's recorded target. Returns the target's+ * path relative to the worktree root, or null after completing an effect+ * that has nothing to commit (superseded bytes or db_only content).+ */+async function singleFileGitTarget(engine: BrainEngine, effect: PersistenceEffect, binding: WorktreeBinding & { local_path: string },+ attempt: EffectAttempt): Promise<string | null> {+ 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;+ const sourceRoot = join(binding.local_path, binding.relative_path);+ let path = join(binding.local_path, effect.data.relative_path);+ if (!isWriteTargetContained(path, sourceRoot)) 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 null; }+ if (!isWriteTargetContained(path, sourceRoot)) 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.+ if (effect.data.slug && isSourceDbOnlySlug(sourceRoot, effect.data.slug, 'not_db_only')) {+ await completeEffect(engine, effect, { git: 'skipped', reason: 'db_only' });+ return null;+ }+ return relative(binding.local_path, path).split(sep).join('/');+}+async function gitPage(engine: BrainEngine, effect: PersistenceEffect, binding: WorktreeBinding | null, opts: EffectWorkerOptions,attempt: EffectAttempt, hardened: boolean | undefined): Promise<void> {if (!binding?.local_path) { await completeEffect(engine, effect, { git: 'skipped', reason: 'no_repo_configured' }); return; }- // Only a page walk reads snapshots; a single-file effect completes by its recorded hash.- const walk = targetedWithdrawalEffect(effect) || effect.data.source_scan;- const snapshot = walk ? await selectedEffectPage(engine, effect) : null;- let path: string;- if (walk) {- 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.');- path = file.path;- if (!existsSync(path)) { await materializeAndAdvance(engine, effect, snapshot, opts.hostId); return; }- 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; }+ const root = binding.local_path;+ if (!targetedWithdrawalEffect(effect) && !effect.data.source_scan) {+ const target = await singleFileGitTarget(engine, effect, { ...binding, local_path: root }, attempt);+ if (target !== null) await completeEffect(engine, effect, await publishGitEffect(root, target, opts.signal, hardened));+ 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')) {+ // Only a page walk reads snapshots; a single-file effect completes by its recorded hash.+ const snapshot = await selectedEffectPage(engine, effect);+ 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.');+ const path = file.path;+ if (!existsSync(path)) { await materializeAndAdvance(engine, effect, snapshot, opts.hostId); return; }+ if (snapshot.page.deleted_at && existsSync(path)) { await finishPage(engine, effect, snapshot, { reason: 'deleted_page_file_present' }); return; }+ if (!isWriteTargetContained(path, join(root, binding.relative_path))) throw new OperationError('source_changed', 'The Git target escaped its registered source.');+ if (isSourceDbOnlySlug(join(root, binding.relative_path), snapshot.page.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, hardened);+ const result = await publishGitEffect(root, relative(root, path).split(sep).join('/'), opts.signal, hardened);if (result.reason === 'durability_not_enabled') await completeEffect(engine, effect, result);else await finishPage(engine, effect, snapshot, result);}@@ -197,7 +214,9 @@ async function embedPage(engine: BrainEngine, config: GBrainConfig, effect: Persif (!renewing && !signal.aborted) renewing = renew().finally(() => { renewing = undefined; });}, 10_000);interval.unref?.();- let vectors: Float32Array[];+ let vectors: (Float32Array | null)[];+ // #4616: a degenerate vector refuses only its own chunk; the usable vectors still install.+ let refused: EmbeddingZeroNormError | undefined;try {await renew();signal.throwIfAborted();@@ -207,12 +226,16 @@ async function embedPage(engine: BrainEngine, config: GBrainConfig, effect: Perssignal.throwIfAborted();await assertEmbeddingEffectEnabled(engine, config);}, () => (opts.embedding?.embed ?? embedBatch)(wrapChunkTextsForStoredMode(prepared.snapshot.page, pending), { abortSignal: signal, maxRetries: 0 }));+ } catch (error) {+ if (!isEmbeddingZeroNormError(error) || error.vectors.length !== pending.length) throw error;+ refused = error;+ vectors = error.vectors;} finally {clearInterval(interval);await renewing;}signal.throwIfAborted();- if (vectors.length !== pending.length || pending.some((_, index) => !vectors[index]?.length)) {+ if (vectors.length !== pending.length || pending.some((_, index) => !vectors[index]?.length && !refused?.failures.some(f => f.index === index))) {throw new OperationError('embedding_unavailable', 'The provider returned an incomplete embedding batch.');}const installed = await engine.transaction(async tx => {@@ -222,13 +245,29 @@ async function embedPage(engine: BrainEngine, config: GBrainConfig, effect: Persawait tx.executeRaw("SELECT key FROM config WHERE key='embedding_disabled' FOR SHARE");await assertEmbeddingEffectEnabled(tx, config);signal.throwIfAborted();+ // A partially refused page keeps its signature unstamped so `gbrain embed --stale` finds the refused chunks.const installed = await installPageEmbeddings(tx, prepared, pending.map((chunk, i) => ({ chunk_index: chunk.chunk_index,- chunk_text: chunk.chunk_text, chunk_source: chunk.chunk_source, embedding: vectors[i], model: opts.embedding?.model })), signature);- if (installed) await restampIfDemotedToTitleTier(tx, prepared.snapshot.page, snapshot.page.slug, effect.source_id);+ chunk_text: chunk.chunk_text, chunk_source: chunk.chunk_source, embedding: vectors[i] ?? undefined, model: opts.embedding?.model })),+ refused ? undefined : signature);+ if (installed && refused) {+ // A refused chunk keeps no vector from an earlier convention, and the page reads as not fully embedded.+ const ids = refused.failures.map(f => pending[f.index]?.id).filter((id): id is number => id !== undefined);+ await tx.executeRaw(`UPDATE content_chunks SET ${quoteIdentifier(prepared.embeddingColumn.name)}=NULL,embedded_at=NULL,+ embedded_text_hash=NULL,embedding_input_hash=NULL WHERE page_id=$1 AND id=ANY($2::int[])`, [prepared.snapshot.page.id, ids]);+ await tx.executeRaw('UPDATE pages SET embedding_signature=NULL WHERE id=$1', [prepared.snapshot.page.id]);+ }+ if (installed && !refused) await restampIfDemotedToTitleTier(tx, prepared.snapshot.page, snapshot.page.slug, effect.source_id);signal.throwIfAborted();- if (installed) await finishPage(tx, effect, snapshot);+ if (installed && !refused) await finishPage(tx, effect, snapshot);return installed;});+ if (installed && refused) {+ // Terminal, never retried: the same input would return the same vector. A scan moves on to its next+ // page; the page keeps no signature, so `gbrain embed --stale` finds it.+ if (targetedWithdrawalEffect(effect) || effect.data.source_scan) await finishPage(engine, effect, snapshot);+ else await failEffect(engine, effect, EMBEDDING_ZERO_NORM);+ return;+ }if (!installed) {if (targetedWithdrawalEffect(effect) || effect.data.source_scan) throw new OperationError('revision_conflict', 'The page changed while embedding.');await completeEffect(engine, effect, { embedding: 'superseded', reason: 'revision_changed' }); return;@@ -320,6 +359,12 @@ async function parkEffectTarget(engine: BrainEngine, effect: PersistenceEffect,...(remaining.length ? { retry_slugs: remaining, target_failures: PARK_AFTER_FAILURES - 1 } : {}) }, code, 0);}+/** #5530: at most this many single-file Git effects share one commit. */+const GIT_GROUP_SIZE = 100;+/** A short Git group yields to queued publications at most this many claims, GIT_YIELD_MS apart. */+const GIT_YIELD_ATTEMPTS = 20;+const GIT_YIELD_MS = 250;+/*** Bounded, idempotent work. Recovery obtains kernel exclusion before a DB claim.* Resolves with the number of effects attempted, so a caller can keep draining.@@ -378,8 +423,67 @@ export async function runPersistenceEffects(engine: BrainEngine, config: GBrainC// probe per root per run). The probe runs while the rest of the batch// proceeds; git effects then run in claim order, never holding a worktree// lock while they wait for it.+ //+ // #5530: a claimed single-file git effect brings up to 99 more ready+ // single-file git effects of its worktree. Under the worktree lock each path+ // is validated as before, the group makes one `commit --only`, and every+ // root pushes once at the end of the pass. A path failure fails only its+ // effect; a push failure leaves the whole group retryable (the next pass+ // finds nothing to commit and pushes once). Nothing holds a lock or a+ // database connection while waiting.const probes = new Map<string, Promise<boolean>>();- const deferred: { effect: PersistenceEffect; binding: WorktreeBinding; hardened: Promise<boolean> }[] = [];+ const deferred: { effects: PersistenceEffect[]; binding: WorktreeBinding; hardened: Promise<boolean> }[] = [];+ const unpushed = new Map<string, { binding: WorktreeBinding; items: { effect: PersistenceEffect; git: string; target?: string }[] }>();+ const commitGroup = async (effects: PersistenceEffect[], binding: WorktreeBinding & { local_path: string }) => {+ // A short group yields to publications still queued for its worktree, so a+ // serial producer (the grandfather step) publishes ahead and its Git work+ // arrives as one group. Each yield is a claim, so attempts bound the delay.+ if (effects.length < GIT_GROUP_SIZE && effects.every(effect => effect.attempts <= GIT_YIELD_ATTEMPTS)) {+ const [pending] = await engine.executeRaw<{ pending: boolean }>(`SELECT EXISTS(SELECT 1 FROM persistence_requests+ WHERE worktree_id=$1::uuid AND state IN ('queued','running')) AS pending`, [effects[0]!.worktree_id]);+ if (pending?.pending) {+ for (const effect of effects) await retryEffect(engine, effect, 'publication_pending', GIT_YIELD_MS);+ return;+ }+ }+ let lock: Awaited<ReturnType<typeof acquireWorktree>> = null;+ try {+ lock = await acquireWorktree(binding, 0, undefined, engine);+ if (!lock) throw new OperationError('writer_busy', 'The canonical worktree is busy.');+ } catch (error) {+ for (const effect of effects) await recordFailure(engine, effect, error, opts.signal);+ return;+ }+ const targets: { effect: PersistenceEffect; path: string; attempt: EffectAttempt }[] = [];+ try {+ for (const effect of effects) {+ const attempt: EffectAttempt = {};+ try {+ // Sources sharing a worktree have their own relative roots: validate each path against its own binding.+ const own = await engine.transaction(async tx => {+ const guarded = await guardEffectSource(tx, effect, opts.hostId);+ const blocked = await tx.executeRaw('SELECT id FROM persistence_requests WHERE worktree_id=$1::uuid AND recovery IS NOT NULL LIMIT 1', [effect.worktree_id]);+ if (blocked.length) throw new OperationError('recovery_required', 'Canonical publication recovery must finish first.');+ return guarded;+ });+ if (!own?.local_path || own.local_path !== binding.local_path) throw new OperationError('source_changed', 'The effect canonical binding changed.');+ const path = await singleFileGitTarget(engine, effect, { ...own, local_path: own.local_path }, attempt);+ if (path !== null) targets.push({ effect, path, attempt });+ } catch (error) { await recordFailure(engine, effect, error, opts.signal, attempt.target); }+ }+ const outcomes = targets.length ? await commitGitTargets(binding.local_path, targets.map(t => t.path), opts.signal) : new Map();+ const pending = unpushed.get(binding.local_path) ?? { binding, items: [] };+ for (const { effect, path, attempt } of targets) {+ const outcome = outcomes.get(path)!;+ if (outcome instanceof OperationError) await recordFailure(engine, effect, outcome, opts.signal, attempt.target);+ else if (outcome.reason === 'target_absent') await completeEffect(engine, effect, outcome);+ else pending.items.push({ effect, git: outcome.git, target: attempt.target });+ }+ if (pending.items.length) unpushed.set(binding.local_path, pending);+ } catch (error) {+ for (const { effect, attempt } of targets) await recordFailure(engine, effect, error, opts.signal, attempt.target);+ } finally { await lock.release(); }+ };// A deferred effect that requeues itself (a page walk advancing its cursor,// or work unblocked by an earlier effect) is claimable again after the flush.for (;;) {@@ -394,10 +498,39 @@ export async function runPersistenceEffects(engine: BrainEngine, config: GBrainCif (effect.kind === 'git' && binding?.local_path) {const root = binding.local_path;if (!probes.has(root)) probes.set(root, isDurabilityHardenedAsync(root));- deferred.push({ effect, binding, hardened: probes.get(root)! });+ const group = singleFileGitEffect(effect) && effect.worktree_id+ ? [effect, ...await claimCoalescedGitEffects(engine, opts.hostId, effect.worktree_id, GIT_GROUP_SIZE - 1)] : [effect];+ deferred.push({ effects: group, binding, hardened: probes.get(root)! });} else await run(effect, binding);}- if (!deferred.length) return attempted;- for (const { effect, binding, hardened } of deferred.splice(0)) await run(effect, binding, await hardened);+ if (!deferred.length) break;+ for (const { effects, binding, hardened } of deferred.splice(0)) {+ const durable = await hardened;+ if (durable && singleFileGitEffect(effects[0]!)) await commitGroup(effects, { ...binding, local_path: binding.local_path! });+ // Coalesced siblings run with their own source's binding (sources can share a worktree).+ else for (const effect of effects) {+ let own: WorktreeBinding | null;+ try { own = effect === effects[0] ? binding : await getWorktreeBinding(engine, effect.source_id, opts.hostId); }+ catch (error) { await recordFailure(engine, effect, error, opts.signal); continue; }+ await run(effect, own, durable);+ }+ }+ }+ for (const [root, { binding, items }] of unpushed) {+ let pushed: Awaited<ReturnType<typeof pushGitRoot>> | undefined;+ let failure: unknown;+ let lock: Awaited<ReturnType<typeof acquireWorktree>> = null;+ try {+ lock = await acquireWorktree(binding, 0, undefined, engine);+ if (!lock) throw new OperationError('writer_busy', 'The canonical worktree is busy.');+ pushed = await pushGitRoot(root, opts.signal);+ } catch (error) { failure = error; } finally { await lock?.release(); }+ for (const { effect, git, target } of items) {+ try {+ if (!pushed) throw failure;+ await completeEffect(engine, effect, { git, ...pushed });+ } catch (error) { await recordFailure(engine, effect, error, opts.signal, target); }+ }}+ return attempted;}diff --git a/src/core/persistence/facts-maintenance.ts b/src/core/persistence/facts-maintenance.tsindex e5ca47aaf7..08c5d0da3a 100644--- a/src/core/persistence/facts-maintenance.ts+++ b/src/core/persistence/facts-maintenance.ts@@ -1,3 +1,4 @@+import { isConnectorSourceKind } from './connector-identity.ts';import type { BrainEngine, NewFact } from '../engine.ts';import type { GBrainConfig } from '../config.ts';import type { FactsBackstopCtx } from '../facts/backstop.ts';@@ -30,6 +31,8 @@ export interface ManagedFactIntent extends Record<string, unknown> {kind: 'managed_facts_entity' | 'managed_facts_complete';batchKey: string; inputDigest: string; origin: ManagedFactOrigin | null; originalRequestId: string | null;expected_revision?: string; facts?: FrozenExtractedFact[]; children?: string[];+ /** Direct single-fact writes keep writeSingleFact's supersession rule. */+ supersede?: true;embedding?: FactEmbeddingSignature | null;}export interface ManagedFactsSession {@@ -96,8 +99,8 @@ export async function prepareManagedFactsSession(ctx: FactsBackstopCtx,const engine = ctx.engine;if (!(await managedPersistenceEnabled(engine))) return null;assertPersistenceAccepting(engine);- const [source] = await engine.executeRaw<{ incarnation: string; archived: boolean; local_path: string | null }>(- 'SELECT incarnation,archived,local_path FROM sources WHERE id=$1', [ctx.sourceId]);+ const [source] = await engine.executeRaw<{ incarnation: string; archived: boolean; local_path: string | null; kind: string | null }>(+ "SELECT incarnation,archived,local_path,config->>'kind' AS kind FROM sources WHERE id=$1", [ctx.sourceId]);if (!source || source.archived) throw new OperationError('source_changed', 'The fact extraction source is unavailable.');let authority: WriteAuthority;let origin: ManagedFactOrigin | null = null;@@ -148,7 +151,9 @@ export async function prepareManagedFactsSession(ctx: FactsBackstopCtx,const binding = await getWorktreeBinding(engine, ctx.sourceId);const root = source.local_path || (ctx.sourceId === 'default' ? await engine.getConfig('sync.repo_path') : null);const writeThrough = !/^(false|0|off|no)$/i.test(await engine.getConfig('sync.write_through') ?? 'true');- if (writeThrough && root && !binding) throw new OperationError('owner_unavailable', 'The fact source has no canonical owner; extraction has not started.');+ // An unbound connector source is database-only by design (connector_database), like its connector sync.+ const connectorDatabase = writeThrough && !binding && isConnectorSourceKind(source.kind);+ if (writeThrough && root && !binding && !connectorDatabase) throw new OperationError('owner_unavailable', 'The fact source has no canonical owner; extraction has not started.');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()) {@@ -158,6 +163,7 @@ export async function prepareManagedFactsSession(ctx: FactsBackstopCtx,}}if (!writeThrough) authority.databaseOnlyReason = 'disabled_by_config';+ else if (connectorDatabase) authority.databaseOnlyReason = 'connector_database';else if (!binding) authority.databaseOnlyReason = 'no_repo_configured';const inputDigest = digest(ctx.requestIntent ?? { text: sha256(input.turnText), source: ctx.source, sessionId: ctx.sessionId, entityHints: ctx.entityHints ?? [],visibility: ctx.visibility ?? null, validFrom: ctx.validFrom?.toISOString() ?? null, sourceSlug: ctx.sourceSlug ?? null,@@ -184,6 +190,7 @@ async function collectManagedFacts(engine: BrainEngine, session: ManagedFactsSesconst out = finished.outcome!;result.inserted += Number(out.inserted ?? 0);result.duplicate += Number(out.duplicate ?? 0);+ result.superseded += Number(out.superseded ?? 0);result.fact_ids.push(...(out.fact_ids as number[] ?? []));if (out.inserted && out.fenced) result.entity_slugs.push(row.slug);}@@ -204,7 +211,8 @@ export async function resumeManagedFacts(engine: BrainEngine, session: ManagedFa}export async function publishManagedFacts(engine: BrainEngine, session: ManagedFactsSession, ctx: FactsBackstopCtx,- facts: ExtractedFact[], visibility: 'private' | 'world', pageSlug?: string): Promise<ManagedFactsResult> {+ facts: ExtractedFact[], visibility: 'private' | 'world', pageSlug?: string,+ options: { supersede?: boolean; explicitContext?: boolean } = {}): Promise<ManagedFactsResult> {const embedded = facts.some(fact => fact.embedding !== null && fact.embedding !== undefined);if (embedded) await assertManagedFactsEmbedding(engine, session.config, session.embedding);const sourceId = session.authority.sourceId;@@ -218,7 +226,7 @@ export async function publishManagedFacts(engine: BrainEngine, session: ManagedFawait authorizeWrite(engine, session.authority, 'extract_facts', slug);await authorizePageVisibility(engine, session.authority, slug);const group = groups.get(slug) ?? [];- group.push({ ...fact, entity_slug: entitySlug, visibility, context: ctx.sourceSlug ?? pageSlug ?? null,+ group.push({ ...fact, entity_slug: entitySlug, visibility, context: options.explicitContext ? fact.context ?? null : ctx.sourceSlug ?? pageSlug ?? null,embedding: fact.embedding ? Array.from(fact.embedding) : null,valid_from: (fact.valid_from ?? ctx.validFrom ?? new Date()).toISOString(), valid_until: fact.valid_until?.toISOString() ?? null });groups.set(slug, group);@@ -229,7 +237,7 @@ export async function publishManagedFacts(engine: BrainEngine, session: ManagedFif (snapshot?.page.deleted_at || group.some(fact => fact.entity_slug !== null) && !snapshot) throw new OperationError('page_identity_changed', 'The resolved fact entity was removed.');inputs.push({ slug, pageId: snapshot?.page.id ?? null, intent: { kind: 'managed_facts_entity', batchKey: session.batchKey,inputDigest: session.inputDigest, origin: session.origin, originalRequestId: session.originalRequestId,- embedding: session.embedding ?? null,+ embedding: session.embedding ?? null, ...(options.supersede ? { supersede: true as const } : {}),...(snapshot ? { expected_revision: snapshot.revision } : {}), facts: group } });}const rows = await engine.transaction(async tx => {diff --git a/src/core/persistence/facts-prepare.ts b/src/core/persistence/facts-prepare.tsindex 2cc0c31e5d..3826221cfb 100644--- a/src/core/persistence/facts-prepare.ts+++ b/src/core/persistence/facts-prepare.ts@@ -1,9 +1,9 @@import type { BrainEngine, NewFact } from '../engine.ts';import type { GBrainConfig } from '../config.ts';import { OperationError } from '../ops/contract.ts';-import { parseFactsFence, upsertFactRow, formatFenceDate } from '../facts-fence.ts';+import { parseFactsFence, upsertFactRow, formatFenceDate, renderFactsTable, replaceOrInsertFactsFence } from '../facts-fence.ts';import { serializePageToMarkdown } from '../markdown.ts';-import { assertFactNotWithdrawn, decideSingleFact } from '../facts/single-prepare.ts';+import { assertFactNotWithdrawn, decideSingleFact, type FactCandidate } from '../facts/single-prepare.ts';import { extractFactsFromFenceText } from '../facts/extract-from-fence.ts';import { authorizeWrite } from './authority.ts';import { authorizePageVisibility } from './page-visibility.ts';@@ -82,7 +82,7 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writif (parsed.warnings.length) throw new OperationError('invalid_params', 'The entity facts fence is malformed.');const [maximum] = await engine.executeRaw<{ n: number }>('SELECT COALESCE(MAX(row_num),0)::int AS n FROM facts WHERE source_id=$1 AND source_markdown_slug=$2', [row.source_id, row.slug]);let nextRow = Math.max(maximum?.n ?? 0, ...parsed.facts.map(fact => fact.rowNum)) + 1;- const entries: Array<{ fact: typeof facts[number]; duplicateId: number | null; rowNum?: number; duplicateOf?: number }> = [];+ const entries: Array<{ fact: typeof facts[number]; duplicateId: number | null; rowNum?: number; duplicateOf?: number; supersedes?: FactCandidate }> = [];const seen = new Map<string, number>();for (const fact of facts) {await assertFactNotWithdrawn(engine, row.source_id, fact);@@ -91,14 +91,20 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writif (earlier !== undefined) { entries.push({ fact, duplicateId: null, duplicateOf: earlier }); continue; }seen.set(key, entries.length);const decision = await decideSingleFact(engine, row.source_id, fact, fact.embedding ?? null, fact.embedding_model);- if (decision.candidate) { entries.push({ fact, duplicateId: decision.candidate.id }); continue; }+ const supersedes = p.supersede === true && decision.status === 'superseded' ? decision.candidate! : undefined;+ if (decision.candidate && !supersedes) { entries.push({ fact, duplicateId: decision.candidate.id }); continue; }const rowNum = fact.entity_slug !== null ? nextRow++ : undefined;if (rowNum !== undefined) body = upsertFactRow(body, { rowNum, claim: fact.fact, kind: fact.kind, visibility: fact.visibility,confidence: fact.confidence ?? 1, notability: fact.notability ?? 'medium', source: fact.source, context: fact.context ?? undefined,validFrom: formatFenceDate(fact.valid_from!), validUntil: fact.valid_until ? formatFenceDate(fact.valid_until) : undefined,claimMetric: fact.claim_metric ?? undefined, claimValue: fact.claim_value ?? undefined,claimUnit: fact.claim_unit ?? undefined, claimPeriod: fact.claim_period ?? undefined }).body;- entries.push({ fact, duplicateId: null, rowNum });+ // Strike the superseded row in this page's fence, as the remember mutation does.+ if (supersedes && rowNum !== undefined && supersedes.source_markdown_slug === row.slug && supersedes.row_num != null) {+ body = replaceOrInsertFactsFence(body, renderFactsTable(parseFactsFence(body).facts.map(f => f.rowNum === Number(supersedes.row_num)+ ? { ...f, active: false, supersededBy: rowNum, context: `superseded by #${rowNum}` } : f)));+ }+ entries.push({ fact, duplicateId: null, rowNum, supersedes });}const canonicalFacts = extractFactsFromFenceText(parseFactsFence(body).facts, row.slug, row.source_id);for (const entry of entries) {@@ -123,12 +129,13 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writawait assertFactNotWithdrawn(tx, row.source_id, entry.fact);if (entry.duplicateOf !== undefined) continue;const current = await decideSingleFact(tx, row.source_id, entry.fact, entry.fact.embedding ?? null, entry.fact.embedding_model);- if ((current.candidate?.id ?? null) !== entry.duplicateId) throw new OperationError('revision_conflict', 'The fact deduplication state changed before publication.');+ if ((current.candidate?.id ?? null) !== (entry.duplicateId ?? entry.supersedes?.id ?? null)) throw new OperationError('revision_conflict', 'The fact deduplication state changed before publication.');}}, apply: async tx => {await page?.apply(tx);const ids: number[] = [];let inserted = 0;+ let superseded = 0;for (const entry of entries) {if (entry.duplicateOf !== undefined) { ids.push(ids[entry.duplicateOf]); continue; }if (entry.duplicateId !== null) { ids.push(entry.duplicateId); continue; }@@ -138,8 +145,13 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writids.push(result.ids[0]);} else ids.push((await tx.insertFact(entry.fact, { source_id: row.source_id })).id);inserted++;+ if (entry.supersedes) {+ await tx.executeRaw('UPDATE facts SET expired_at=COALESCE(expired_at,now()),superseded_by=$3 WHERE id=$1 AND source_id=$2',+ [entry.supersedes.id, row.source_id, ids[ids.length - 1]]);+ superseded++;+ }}- return { status: 'completed', inserted, duplicate: entries.length - inserted, superseded: 0, fact_ids: ids,+ return { status: 'completed', inserted, duplicate: entries.length - inserted, superseded, fact_ids: ids,fenced: page !== undefined, kind: p.kind, batch_key: p.batchKey, input_digest: p.inputDigest };} };}diff --git a/src/core/persistence/grandfather.ts b/src/core/persistence/grandfather.tsindex 177fe07dff..60cce13ef0 100644--- a/src/core/persistence/grandfather.ts+++ b/src/core/persistence/grandfather.ts@@ -16,10 +16,26 @@ 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<{ status: 'touched'; revision: string | null } | { status: 'skipped' }> {+type GrandfatherSelection = { id: number; slug: string; source_id: string; source_incarnation: string };+type GrandfatherOutcome = { status: 'touched'; revision: string | null };++export async function grandfatherCanonicalPage(engine: BrainEngine, selected: GrandfatherSelection,+ before: (page: GrandfatherSelection & { frontmatter: Record<string, unknown>; knowledge_revision: string; request_id: string }) => void | Promise<void>,+): Promise<GrandfatherOutcome | { status: 'skipped' }> {+ const admitted = await admitCanonicalGrandfather(engine, selected, before);+ return admitted.status === 'skipped' ? admitted : admitted.complete();+}++/**+ * #5530: admit one page's grandfather write without waiting for it. The step+ * admits a bounded window of pages before waiting, so their Git effects are+ * ready together and the effect runner commits them as one group instead of+ * one commit per page. `complete()` waits for the publication and settles the+ * page's checkpoint exactly as the serial path does.+ */+export async function admitCanonicalGrandfather(engine: BrainEngine, selected: GrandfatherSelection,+ before: (page: GrandfatherSelection & { frontmatter: Record<string, unknown>; knowledge_revision: string; request_id: string }) => void | Promise<void>,+): Promise<{ status: 'skipped' } | { status: 'admitted'; complete: () => Promise<GrandfatherOutcome> }> {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 { status: 'skipped' };@@ -43,21 +59,27 @@ export async function grandfatherCanonicalPage(engine: BrainEngine,assertReplayIntent(prior, intentDigest({ operation: 'put_page', sourceId: selected.source_id, slug: selected.slug, callerIntent }));} else await before({ ...selected, frontmatter: snapshot.page.frontmatter ?? {}, knowledge_revision: snapshot.revision, request_id: requestId });const binding = await getWorktreeBinding(engine, selected.source_id);+ const settleFailure = async (error: unknown): Promise<never> => {+ 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])]);+ }+ throw error;+ };+ let request: WriteRequest;try {- const request = prior ?? await admitWrite(engine, { principal, operation: 'put_page', sourceId: selected.source_id,+ request = prior ?? await admitWrite(engine, { principal, operation: 'put_page', sourceId: selected.source_id,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 });- 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])]);- // 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)) {+ } catch (error) { return settleFailure(error); }+ return { status: 'admitted', complete: async () => {+ try {+ 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])]);- }- throw error;- }+ // 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) { return settleFailure(error); }+ } };}export async function prepareGrandfatherMutation(engine: BrainEngine, row: WriteRequest): Promise<PreparedMutation> {diff --git a/src/core/persistence/import-mutations.ts b/src/core/persistence/import-mutations.tsindex 33ed4c3b95..6564eae0c5 100644--- a/src/core/persistence/import-mutations.ts+++ b/src/core/persistence/import-mutations.ts@@ -10,7 +10,11 @@ import { currentVerifiedLocalWriter, localHostId } from './identity.ts';import { getWorktreeBinding } from './ownership.ts';import { initializeLocalPersistence, requestPrincipalForContext, submitPageMutation } from './page-mutations.ts';import { digest, sha256 } from './digest.ts';-import { assertImportPaths, managedImportContent, readImportBytes, type ImportPack, type ManagedImportIntent } from './import-prepare.ts';+import { assertImportPaths, managedImportContent, prepareManagedImportMutation, readImportBytes, type ImportPack, type ManagedImportIntent } from './import-prepare.ts';+import { submissionAuthority } from './authority.ts';+import { inspectUnchanged, screeningRequest } from './noop-kernel.ts';+import type { WorktreeBinding } from './ownership.ts';+import type { PageSnapshot } from '../page-state/types.ts';export async function importManagedFile(engine: BrainEngine, filePath: string, sourcePath: string,opts: { sourceId?: string; noEmbed?: boolean; activePack?: ImportPack; signal?: AbortSignal; slugRoot?: string } = {}): Promise<ImportResult> {@@ -51,10 +55,13 @@ export async function importManagedFile(engine: BrainEngine, filePath: string, slet params = await readPending();if (!params) {const snapshot = await engine.readPageSnapshot(slug, { sourceId, includeDeleted: true });- params = { kind: 'managed_file_import', slug, content, sourcePath, path, inputPath, inputHash,+ const intent: ManagedImportIntent = { kind: 'managed_file_import', slug, content, sourcePath, path, inputPath, inputHash,targetHash: existsSync(target) ? sha256(readImportBytes(target)) : null,ownerEpoch: String(binding.owner_epoch), ...(snapshot ? { expected_revision: snapshot.revision } : {}),- noEmbed: !!opts.noEmbed, ...(opts.activePack ? { activePack: opts.activePack } : {}), request_id: randomUUID(), source_id: sourceId };+ noEmbed: !!opts.noEmbed, ...(opts.activePack ? { activePack: opts.activePack } : {}) };+ // #5470: an import whose publication would change nothing takes no admission.+ if (await unchangedManagedImport(ctx, binding, intent, snapshot)) return { slug, status: 'skipped', chunks: 0 };+ params = { ...intent, request_id: randomUUID(), source_id: sourceId };await engine.executeRaw('INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES($1,$2,$3::text::jsonb) ON CONFLICT DO NOTHING', [op, key, JSON.stringify([params])]);params = (await readPending())!;}@@ -71,3 +78,19 @@ export async function importManagedFile(engine: BrainEngine, filePath: string, sthrow error;}}++/** Runs the managed-import preparer on an unadmitted request; true only when the no-op kernel finds nothing to publish. */+async function unchangedManagedImport(ctx: OperationContext, binding: WorktreeBinding, intent: ManagedImportIntent, snapshot: PageSnapshot | null): Promise<boolean> {+ if (!snapshot) return false;+ try {+ const authority = await submissionAuthority(ctx, 'put_page', binding.source_id, binding.source_incarnation, intent.slug);+ const row = screeningRequest({ source_id: binding.source_id, source_incarnation: binding.source_incarnation, slug: intent.slug,+ page_id: snapshot.page.id, worktree_id: binding.worktree_id, authority, intent, operation: 'put_page' });+ const prepared = await prepareManagedImportMutation(ctx.engine, row, ctx.config);+ if ((await inspectUnchanged(ctx.engine, { prepared, snapshot, sourcePath: intent.sourcePath, databaseOnly: false })).admitReason) return false;+ await prepared.validate?.(ctx.engine);+ return true;+ } catch {+ return false;+ }+}diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.tsindex c82d8593e3..bf56563ce6 100644--- a/src/core/persistence/journal.ts+++ b/src/core/persistence/journal.ts@@ -7,6 +7,7 @@ import { authorizeWrite } from './authority.ts';import { journalLimitKey, oneYearCapacity, readJournalLimits, readReceiptRetentionDays } from './limits.ts';import { retryWriteAdmission } from './admission-retry.ts';import { writeHealth, type WriteHealthFacts } from './health.ts';+import { writerStamp } from './writer-versions.ts';import { assertMutationProtocol, assertSharedSkillPersistence, declarePersistenceProtocol, PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';import {isTerminal, principalKey, requestPrincipal, recoveryFiles,@@ -104,6 +105,7 @@ async function prepareAdmission(engine: BrainEngine, input: WriteAdmission, overconst bytes = jsonBytes(input.intent) + jsonBytes(input.authority);const terminalBytes = input.terminalReservation ?? Math.max(16_384,jsonBytes(input.authority)+8192);if (!Number.isSafeInteger(terminalBytes) || terminalBytes < 1024) throw new TypeError('Invalid terminal receipt reservation.');+ const stamp = writerStamp();return { requestId, apply: async (tx: BrainEngine): Promise<WriteRequest> => {await declarePersistenceProtocol(tx);assertMutationProtocol({ target_kind: input.targetKind, protocol_version: input.protocolVersion });@@ -147,11 +149,13 @@ async function prepareAdmission(engine: BrainEngine, input: WriteAdmission, over}const [row] = await tx.executeRaw<WriteRequest>(`INSERT INTO persistence_requests(principal_kind,principal_id,request_id,operation,source_id,source_incarnation,page_id,slug,- worktree_id,topology_generation,digest,intent,authority,intent_bytes,terminal_reservation,target_kind,protocol_version)- VALUES($1,$2,$3::uuid,$4,$5,$6::uuid,$7,$8,$9::uuid,$10,$11,$12::text::jsonb,$13::text::jsonb,$14,$15,$16,$17)+ worktree_id,topology_generation,digest,intent,authority,intent_bytes,terminal_reservation,target_kind,protocol_version,+ admitter_version,admitter_host_id)+ VALUES($1,$2,$3::uuid,$4,$5,$6::uuid,$7,$8,$9::uuid,$10,$11,$12::text::jsonb,$13::text::jsonb,$14,$15,$16,$17,$18,$19::uuid)RETURNING *`, [input.principal.kind, input.principal.id, requestId, input.operation, input.sourceId,input.sourceIncarnation, input.pageId ?? null, input.slug, input.worktreeId ?? null, input.topologyGeneration ?? null,- fingerprint, JSON.stringify(input.intent), JSON.stringify(input.authority), bytes, terminalBytes, input.targetKind ?? 'page', input.protocolVersion ?? 1]);+ fingerprint, JSON.stringify(input.intent), JSON.stringify(input.authority), bytes, terminalBytes, input.targetKind ?? 'page', input.protocolVersion ?? 1,+ stamp.version, stamp.hostId]);await tx.executeRaw(`UPDATE persistence_counters SET outstanding_count=outstanding_count+1,intent_bytes=intent_bytes+$2,lifetime_ids=lifetime_ids+1,terminal_bytes=terminal_bytes+$3 WHERE key=ANY($1::text[])`,[counters.map(c => c.key), bytes, terminalBytes]);@@ -234,9 +238,14 @@ export async function completeWrite(tx: SqlEngine, row: WriteRequest, state: 'coconst [effects] = await tx.executeRaw<{bytes:string}>(`SELECT COALESCE(SUM(octet_length(data::text)+octet_length(kind)+1024),0)::text AS bytesFROM persistence_effects WHERE request_id=$1::uuid`,[row.id]);if (jsonBytes(outcome) + jsonBytes(current.authority) + 1024 + Buffer.byteLength(error?.message ?? '') + Number(effects.bytes) > Number(current.terminal_reservation)) throw capacityError('terminal result and effects exceed their reserved bounded encoding');+ // Only publication stamps the consumer; failures, cancellations and conflicts leave it unset.+ const stamp = writerStamp();const [done] = await tx.executeRaw<WriteRequest>(`UPDATE persistence_requests SET state=$2,outcome=$3::text::jsonb,- error_code=$4,error_message=$5,completed_at=now(),updated_at=now(),claim_expires_at=NULL,blocked_reason=NULL- WHERE id=$1::uuid RETURNING *`, [row.id, state, JSON.stringify(outcome), error?.code ?? null, error?.message ?? null]);+ error_code=$4,error_message=$5,completed_at=now(),updated_at=now(),claim_expires_at=NULL,blocked_reason=NULL,+ consumer_version=CASE WHEN $2='committed' THEN $6 ELSE consumer_version END,+ consumer_host_id=CASE WHEN $2='committed' THEN $7::uuid ELSE consumer_host_id END,+ published_at=CASE WHEN $2='committed' THEN now() ELSE published_at END+ WHERE id=$1::uuid RETURNING *`, [row.id, state, JSON.stringify(outcome), error?.code ?? null, error?.message ?? null, stamp.version, stamp.hostId]);await tx.executeRaw(`UPDATE persistence_counters SET outstanding_count=outstanding_count-1,intent_bytes=intent_bytes-$2WHERE key=ANY($1::text[])`, [['brain', principalKey(requestPrincipal(row))], Number(current.intent_bytes)]);// Recovery bytes remain reserved until physical cleanup has been verified.diff --git a/src/core/persistence/maintenance.ts b/src/core/persistence/maintenance.tsindex 6a01012be0..79467e646d 100644--- a/src/core/persistence/maintenance.ts+++ b/src/core/persistence/maintenance.ts@@ -5,7 +5,9 @@ import { assertManagedFilesystemWrite } from './filesystem-guard.ts';import { OperationError } from '../ops/contract.ts';import type { SqlEngine } from './model.ts';-export const UNSUPPORTED_MANAGED_BULK_WRITERS = ['cycle.extract_facts', 'extract-conversation-facts', 'conversation_facts_backfill', 'loops_extract'] as const;+// Every facts-family bulk writer now publishes through the coordinator on a+// managed brain (#5280); status and activation keep reporting the (empty) list.+export const UNSUPPORTED_MANAGED_BULK_WRITERS: readonly string[] = [];/** Refuse unsupported multi-stage writers before providers, files or git change. */export async function assertUnmanagedCanonicalWriter(engine: SqlEngine, operation: string): Promise<void> {diff --git a/src/core/persistence/manual-links.ts b/src/core/persistence/manual-links.tsnew file mode 100644index 0000000000..b022374239--- /dev/null+++ b/src/core/persistence/manual-links.ts@@ -0,0 +1,39 @@+import type { BrainEngine } from '../engine.ts';+import { OperationError, type OperationContext } from '../ops/contract.ts';+import { assertPersistenceAccepting } from './service.ts';+import { authorizeWrite, submissionAuthority } from './authority.ts';+import { managedPersistenceEnabled } from './ownership.ts';+import { initializeLocalPersistence } from './page-mutations.ts';+import { withCoordinatedWrite } from './context.ts';++/**+ * `add_link` / `remove_link` on a managed brain (#5280): a coordinated,+ * database-only write, like derived links. Manual edges live only in the+ * database, so there is no canonical file to write and no receipt to keep.+ * The caller's durable write authority is checked for the `from` page, then the+ * edge commits inside a source-scoped coordinated transaction that holds both+ * endpoint page keys, so it serializes with publications of either page.+ * Returns null on an unmanaged brain; the caller keeps its legacy path.+ */+export async function coordinatedManualLinkWrite<T>(ctx: OperationContext, operation: 'add_link' | 'remove_link',+ from: string, to: string, write: (engine: BrainEngine, sourceId: string) => Promise<T>): Promise<{ value: T } | null> {+ if (!await managedPersistenceEnabled(ctx.engine)) return null;+ assertPersistenceAccepting(ctx.engine);+ const sourceId = ctx.sourceId ?? 'default';+ const [source] = await ctx.engine.executeRaw<{ incarnation: string; archived: boolean }>(+ 'SELECT incarnation,archived FROM sources WHERE id=$1', [sourceId]);+ if (!source || source.archived) throw new OperationError('source_changed', 'The link source is not active.');+ await initializeLocalPersistence(ctx);+ const authority = await submissionAuthority(ctx, operation, sourceId, source.incarnation, from);+ const value = await ctx.engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], async () => {+ const [current] = await tx.executeRaw<{ incarnation: string; archived: boolean }>(+ 'SELECT incarnation,archived FROM sources WHERE id=$1 FOR SHARE', [sourceId]);+ if (!current || current.archived || current.incarnation !== source.incarnation) {+ throw new OperationError('source_changed', 'The link source changed before the write.');+ }+ await authorizeWrite(tx, authority, operation, from, true);+ await tx.lockPageKeys([{ sourceId, slug: from }, { sourceId, slug: to }]);+ return write(tx, sourceId);+ }));+ return { value };+}diff --git a/src/core/persistence/memory-mutations.ts b/src/core/persistence/memory-mutations.tsindex 19e2fe5741..1ffe33ec31 100644--- a/src/core/persistence/memory-mutations.ts+++ b/src/core/persistence/memory-mutations.ts@@ -9,6 +9,7 @@ import { authorizeStoredRequest, submissionAuthority } from './authority.ts';import { admitWrite, admitWriteInTransaction, assertPageRequestIdentity, assertReplayIntent, completeWrite, getWriteRequest, intentDigest } from './journal.ts';import { assertPersistenceAccepting, registerMutationPreparer, waitForWrite, writeResponse } from './service.ts';import { claimWorktree, getWorktreeBinding } from './ownership.ts';+import { isConnectorSourceKind } from './connector-identity.ts';import { WRITER_INSPECTION_HINT } from './admin-intent.ts';import { parseMutationPrecondition } from './preconditions.ts';import { withCoordinatedWrite } from './context.ts';@@ -49,8 +50,8 @@ export async function submitRememberMutation(ctx: OperationContext, params: Recoconst sub = await submission(ctx, 'remember', params);if (sub.prior) return writeResponse(await waitForWrite(ctx.engine, sub.prior, ctx.config, waitMs));const { p, sourceId, principal, callerIntent, requestId } = sub;- const [source] = await ctx.engine.executeRaw<{ incarnation: string; archived: boolean; local_path: string | null }>(- 'SELECT incarnation,archived,local_path FROM sources WHERE id=$1', [sourceId]);+ const [source] = await ctx.engine.executeRaw<{ incarnation: string; archived: boolean; local_path: string | null; kind: string | null }>(+ "SELECT incarnation,archived,local_path,config->>'kind' AS kind FROM sources WHERE id=$1", [sourceId]);if (!source || source.archived) throw new OperationError('source_changed', 'The write source is not active.');const { parseTtlParam } = await import('../ops/facts.ts');const validUntil = parseTtlParam(p.ttl);@@ -79,9 +80,11 @@ export async function submitRememberMutation(ctx: OperationContext, params: Recoif (sandbox) authority.databaseOnlyReason = 'subagent_sandbox';else if (!configuredWriteThrough) authority.databaseOnlyReason = 'disabled_by_config';const root = source.local_path || (sourceId === 'default' ? await ctx.engine.getConfig('sync.repo_path') : null);- if (fence && writeThrough && root && !binding) {+ // An unbound connector source is database-only by design; never claim it for a fence write.+ if (fence && writeThrough && root && !binding && isConnectorSourceKind(source.kind)) authority.databaseOnlyReason = 'connector_database';+ else if (fence && writeThrough && root && !binding) {if (ctx.engine.kind !== 'pglite') throw new OperationError('owner_unavailable', 'This source has no designated canonical owner.', WRITER_INSPECTION_HINT);- binding = await claimWorktree(ctx.engine, sourceId, root);+ binding = await claimWorktree(ctx.engine, sourceId, root, undefined, undefined, { automatic: true });}const row = await admitWrite(ctx.engine, { principal, operation: 'remember', sourceId, sourceIncarnation: source.incarnation,slug, pageId: snapshot?.page.id ?? null, requestId, callerIntent,diff --git a/src/core/persistence/model.ts b/src/core/persistence/model.tsindex 3f5dbe7164..8f230a22f2 100644--- a/src/core/persistence/model.ts+++ b/src/core/persistence/model.ts@@ -8,7 +8,7 @@ export interface WriteAuthority {remote: boolean;/** Original page-visibility ceiling; current policy can only narrow it. */excludePrivate?: boolean;- databaseOnlyReason?: 'subagent_sandbox' | 'disabled_by_config' | 'no_repo_configured' | 'connector_database';+ databaseOnlyReason?: 'subagent_sandbox' | 'disabled_by_config' | 'no_repo_configured' | 'connector_database' | 'unbound_source';autoLinkTrusted?: boolean;restrictedNamespace?: boolean;sourceId: string;diff --git a/src/core/persistence/noop-kernel.ts b/src/core/persistence/noop-kernel.tsnew file mode 100644index 0000000000..6f0ca0ce70--- /dev/null+++ b/src/core/persistence/noop-kernel.ts@@ -0,0 +1,79 @@+/**+ * #5470 no-op kernel: one request-free check, beneath the connector, managed+ * import, working-tree sync and company-profile paths, that decides whether an+ * item can skip admission because publishing it would change nothing.+ *+ * Each path runs its publication preparer on an unadmitted, synthetic request+ * (the preparers read only the database and the local canonical root, so this+ * runs on the connector or import host), then asks the kernel. An item is+ * skipped only when:+ * - the prepared mutation is a no-op and observed the snapshot revision,+ * - no projection work is pending (safe-chunk re-seal, text projection behind+ * the knowledge revision, an embedded page with no contextual mode, or+ * unembedded chunks when the publication would queue embedding),+ * - no metadata work is pending (the stored source path differs),+ * - the page exists and is not deleted, and+ * - the page has no canonical file by design (database-only), or the local+ * canonical file bytes equal the serialized page.+ * The preparer's own `validate` then re-checks authority, source incarnation,+ * identity and revision before the skip is counted. Anything else is admitted+ * and published exactly as before.+ */+import type { BrainEngine } from '../engine.ts';+import type { PreparedMutation } from './coordinator.ts';+import { persistenceFileHash } from './coordinator.ts';+import type { WriteRequest } from './model.ts';+import type { PageSnapshot } from '../page-state/types.ts';+import { belowSafeChunkFence } from '../search/safe-chunks.ts';+import { sha256 } from './digest.ts';++export interface NoopKernelResult {+ contentUnchanged: boolean;+ projectionWorkRequired: boolean;+ metadataWorkRequired: boolean;+ observedRevision: string | null;+ /** Why the item is admitted; absent when it may be skipped. */+ admitReason?: 'content_changed' | 'page_missing' | 'page_deleted' | 'revision_moved' | 'projection_work' | 'metadata_work' | 'canonical_file_differs';+}++/** A request-shaped value for preparers; it is never admitted or persisted. */+export function screeningRequest(fields: Pick<WriteRequest, 'source_id' | 'source_incarnation' | 'slug' | 'page_id' | 'worktree_id' | 'authority' | 'intent'>+ & Partial<WriteRequest>): WriteRequest {+ return { id: '00000000-0000-4000-8000-000000000000', request_id: '00000000-0000-4000-8000-000000000000', operation: 'submit_job', state: 'queued',+ principal_kind: fields.authority.principal.kind, principal_id: fields.authority.principal.id, created_at: new Date().toISOString(),+ updated_at: new Date().toISOString(), protocol_version: 1, target_kind: 'page', ...fields } as unknown as WriteRequest;+}++export async function inspectUnchanged(engine: Pick<BrainEngine, 'executeRaw'>, input: {+ prepared: PreparedMutation; snapshot: PageSnapshot | null; sourcePath: string | null; databaseOnly: boolean;+ /** The publication would queue an embedding effect: a page with unembedded chunks is then not skipped. */+ embeddingRequested?: boolean;+}): Promise<NoopKernelResult> {+ const { prepared, snapshot } = input;+ const observedRevision = prepared.observedRevision ?? null;+ const unchanged = prepared.noop === true || prepared.contentUnchanged === true;+ const result = (reason?: NoopKernelResult['admitReason'], flags: Partial<NoopKernelResult> = {}): NoopKernelResult => ({+ contentUnchanged: unchanged, projectionWorkRequired: false, metadataWorkRequired: false, observedRevision, ...flags,+ ...(reason ? { admitReason: reason } : {}) });+ if (!snapshot) return result('page_missing');+ if (snapshot.page.deleted_at != null) return result('page_deleted');+ if (!unchanged) return result('content_changed');+ if (observedRevision !== snapshot.revision) return result('revision_moved');+ const [page] = await engine.executeRaw<{ chunker_version: number | null; text_projection_revision: string | null; knowledge_revision: string;+ mode_pending: boolean; unembedded: boolean; source_path: string | null }>(`SELECT p.chunker_version,p.text_projection_revision::text,p.knowledge_revision::text,p.source_path,+ (p.contextual_retrieval_mode IS NULL AND EXISTS (SELECT 1 FROM content_chunks c WHERE c.page_id=p.id AND c.embedding IS NOT NULL)) AS mode_pending,+ EXISTS (SELECT 1 FROM content_chunks c WHERE c.page_id=p.id AND c.embedding IS NULL) AS unembedded+ FROM pages p WHERE p.id=$1 AND p.deleted_at IS NULL`, [snapshot.page.id]);+ if (!page) return result('page_missing');+ const projectionWorkRequired = belowSafeChunkFence(page.chunker_version === null ? null : Number(page.chunker_version))+ || page.text_projection_revision !== page.knowledge_revision || page.mode_pending === true+ || input.embeddingRequested === true && page.unembedded === true;+ if (projectionWorkRequired) return result('projection_work', { projectionWorkRequired });+ const metadataWorkRequired = input.sourcePath !== null && page.source_path !== input.sourcePath;+ if (metadataWorkRequired) return result('metadata_work', { metadataWorkRequired });+ if (!input.databaseOnly) {+ const file = prepared.file;+ if (!file || file.content === null || persistenceFileHash(file.path) !== sha256(file.content)) return result('canonical_file_differs');+ }+ return result();+}diff --git a/src/core/persistence/ownership.ts b/src/core/persistence/ownership.tsindex b1ed24db0c..53e212ef55 100644--- a/src/core/persistence/ownership.ts+++ b/src/core/persistence/ownership.ts@@ -13,6 +13,7 @@ import { assertPhysicalRoot, claimPhysicalRoot, isPhysicalRootMetadata, preparePimport { readPhysicalRootStamp } from './physical-root-record.ts';import { canonicalFilesystemPath, nativeFilesystemPath } from './root-registry.ts';import { assertWriterAdminState } from './admin-intent.ts';+import { assertWriterAdminUnlocked } from './admin-lock.ts';import { inspectPhysicalRootRecovery, repairPhysicalRoot, type PhysicalRootRecovery } from './physical-root-recovery.ts';export interface WorktreeBinding {@@ -44,11 +45,13 @@ export async function getWorktreeBinding(engine: SqlEngine, sourceId: string, hoWHERE s.source_id=$1`, [sourceId, hostId]);return row ?? null;}-export async function claimWorktree(engine: BrainEngine, sourceId: string, path: string, hostId = localHostId(), expectedAdminState?: string): Promise<WorktreeBinding> {+/** `automatic` is only the ordinary first-write claim; the writer admin lock never blocks it. */+export async function claimWorktree(engine: BrainEngine, sourceId: string, path: string, hostId = localHostId(), expectedAdminState?: string,+ options: { automatic?: boolean } = {}): Promise<WorktreeBinding> {if(await managedPersistenceEnabled(engine)) {if(hostId!==localHostId()) throw new OperationError('permission_denied','A source can be claimed only by the local registered host.');const { runManagedSourceLifecycle }=await import('./source-lifecycle.ts');- await runManagedSourceLifecycle(engine,{operation:'claim',sourceId,path,expectedAdminState});+ await runManagedSourceLifecycle(engine,{operation:'claim',sourceId,path,expectedAdminState,automaticClaim:options.automatic});return (await getWorktreeBinding(engine,sourceId,hostId))!;}let sourceRoot: string;@@ -73,6 +76,7 @@ export async function claimWorktree(engine: BrainEngine, sourceId: string, path:await tx.executeRaw("SELECT set_config('synchronous_commit','on',true)");await tx.executeRaw('SELECT singleton FROM persistence_brain WHERE singleton=1 FOR UPDATE');await assertWriterAdminState(tx, expectedAdminState);+ if (!options.automatic) await assertWriterAdminUnlocked(tx);const [source] = await tx.executeRaw<{ incarnation: string; archived: boolean }>('SELECT incarnation,archived FROM sources WHERE id=$1 FOR UPDATE', [sourceId]);if (!source || source.archived) throw new OperationError('source_changed', 'Only an active registered source can claim a worktree.');const current = await getWorktreeBinding(tx, sourceId, hostId);@@ -176,6 +180,7 @@ export async function prepareWriterTransfer(engine: BrainEngine, sourceId: strinreturn await engine.transaction(async tx => {await tx.executeRaw("SELECT set_config('synchronous_commit','on',true)");await assertWriterAdminState(tx, expectedAdminState);+ await assertWriterAdminUnlocked(tx);const [owner] = await tx.executeRaw<{ owner_host_id: string; owner_epoch: string; state: string }>('SELECT owner_host_id,owner_epoch,state FROM persistence_worktrees WHERE id=$1::uuid FOR UPDATE', [binding.worktree_id]);const current = await getWorktreeBinding(tx, sourceId, hostId);if (!owner || owner.owner_host_id !== hostId || JSON.stringify(current) !== JSON.stringify(binding)) throw new OperationError('owner_unavailable', 'Ownership changed during transfer.');@@ -211,6 +216,7 @@ export async function acceptWriterTransfer(engine: BrainEngine, sourceId: stringawait engine.transaction(async tx => {await tx.executeRaw("SELECT set_config('synchronous_commit','on',true)");await assertWriterAdminState(tx, expectedAdminState);+ await assertWriterAdminUnlocked(tx);const [owner] = await tx.executeRaw<{ owner_epoch: string; state: string; manifest: { digest: string; self_transfer?: PhysicalRootRecovery } }>('SELECT owner_epoch,state,manifest FROM persistence_worktrees WHERE id=$1::uuid FOR UPDATE', [binding.worktree_id]);if (!owner || owner.state !== 'draining' || String(owner.owner_epoch) !== expectedEpoch || owner.manifest?.digest !== expectedManifest) throw new OperationError('writer_transfer_conflict', 'Transfer preparation or epoch changed.');if (!!owner.manifest.self_transfer !== !!opts.selfTransfer || JSON.stringify(await getWorktreeBinding(tx, sourceId, hostId)) !== JSON.stringify(binding)) throw new OperationError('writer_transfer_conflict', 'The prepared transfer mode or binding changed.');diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.tsindex a35825c75b..7d65963e86 100644--- a/src/core/persistence/page-mutations.ts+++ b/src/core/persistence/page-mutations.ts@@ -19,7 +19,8 @@ import { assertPurgeParams } from './purge-params.ts';import type { Principal } from './model.ts';import { normalizeSubagentPageInput } from './page-input.ts';import { assertKnowledgePublicationAllowed } from '../shared-skills/knowledge-guard.ts';-import { WRITER_INSPECTION_HINT } from './admin-intent.ts';+import { readUnboundWritePolicy, unboundSourceError } from './unbound-source.ts';+import { isConnectorSourceKind } from './connector-identity.ts';export async function requestPrincipalForContext(ctx: OperationContext): Promise<Principal> {if (ctx.auth?.principal) return { ...ctx.auth.principal };@@ -98,8 +99,8 @@ export async function submitPageMutation(ctx: OperationContext,return writeResponse(await waitForWrite(ctx.engine, prior, ctx.config, input.waitMs));}if (input.operation === 'delete_page') assertPurgeParams(p, ctx.remote);- const [source] = await ctx.engine.executeRaw<{ incarnation: string; archived: boolean; local_path: string | null }>(- 'SELECT incarnation,archived,local_path FROM sources WHERE id=$1', [sourceId]);+ const [source] = await ctx.engine.executeRaw<{ incarnation: string; archived: boolean; local_path: string | null; kind: string | null }>(+ "SELECT incarnation,archived,local_path,config->>'kind' AS kind FROM sources WHERE id=$1", [sourceId]);if (!source || source.archived) throw new OperationError('source_changed', 'The write source is not active.');let slug = typeof p.slug === 'string' ? p.slug.toLowerCase() : '';const intent = ['takes_add','takes_update','takes_supersede','takes_resolve'].includes(input.operation)@@ -162,9 +163,18 @@ export async function submitPageMutation(ctx: OperationContext,if (!matches) throw new OperationError('invalid_params', 'The CLI directory must match the selected source canonical root.','Register the source canonical path, then omit --dir or use that same path.');}- if (writeThrough && root && !binding) {- if (ctx.engine.kind !== 'pglite') throw new OperationError('owner_unavailable', 'This source has no designated canonical owner.', WRITER_INSPECTION_HINT);- binding = await claimWorktree(ctx.engine, sourceId, root);+ // A connector source without a canonical owner is database-only by design+ // (connector_database): a page write never claims it or refuses as unbound.+ if (writeThrough && root && !binding && isConnectorSourceKind(source.kind)) authority.databaseOnlyReason = 'connector_database';+ else if (writeThrough && root && !binding) {+ if (ctx.engine.kind === 'pglite') binding = await claimWorktree(ctx.engine, sourceId, root, undefined, undefined, { automatic: true });+ else {+ const scope = input.operation !== 'put_page' ? 'other' : snapshot?.page.source_path ? 'file_backed' : 'put_page';+ if (scope !== 'put_page' || await readUnboundWritePolicy(ctx.engine) !== 'database_only') {+ throw unboundSourceError(sourceId, ctx.remote === false ? root : null, scope);+ }+ authority.databaseOnlyReason = 'unbound_source';+ }}const row = await admitWrite(ctx.engine, { principal, operation: input.operation, sourceId, sourceIncarnation: source.incarnation,slug, pageId: snapshot?.page.id ?? null, requestId, callerIntent, intent, authority,diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.tsindex 9f2e8e7fe5..cd127e8123 100644--- a/src/core/persistence/page-prepare.ts+++ b/src/core/persistence/page-prepare.ts@@ -18,7 +18,8 @@ import { digest, sha256 } from './digest.ts';import { getWorktreeBinding } from './ownership.ts';import type { PreparedContentImport } from './prepared-import.ts';import type { PreparedMutation } from './coordinator.ts';-import type { WriteRequest } from './model.ts';+import type { SqlEngine, WriteRequest } from './model.ts';+import { isUnboundSourcePage } from './unbound-source.ts';import { sealPageTextProjection } from '../page-state/projections.ts';import { overlayCanonicalBodies } from '../page-state/snapshot.ts';import { materializeTimeline, prepareCanonicalProjections } from './canonical-projections.ts';@@ -68,6 +69,10 @@ function putProvenance(row: WriteRequest, snapshot: PageSnapshot | null, parsed: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; capture?: { path: string; hash: string } } = {}): Promise<PreparedMutation['file']> {if (!row.worktree_id) return undefined;+ // #5254: a page written while its source was unbound stays database-only in+ // every state (live, tombstone, restore, revert, delete, purge); any file at+ // its derived path is not its canonical file and is neither written nor removed.+ if (snapshot && !snapshot.page.source_path && await isUnboundSourcePage(engine, row.source_id, row.slug)) 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);@@ -113,11 +118,16 @@ export async function prepareFileTarget(engine: BrainEngine, row: Pick<WriteRequ/*** 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.+ * db_only page whose file is absent, or a page written while its source was+ * unbound (#5254) in any state; 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' } : {};}+async function pageDatabaseOnlyPublication(engine: SqlEngine, row: WriteRequest, file: PreparedMutation['file']): Promise<Pick<PreparedMutation, 'databaseOnlyReason'>> {+ const reason = databaseOnlyPublication(row, file);+ return reason.databaseOnlyReason && await isUnboundSourcePage(engine, row.source_id, row.slug) ? { databaseOnlyReason: 'unbound_source' } : reason;+}/** Providers and parsing run before the OS lock and before any publication transaction. */export async function preparePageMutation(engine: BrainEngine, row: WriteRequest, _config: GBrainConfig,@@ -149,7 +159,7 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequest// 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.const file = await prepareFileTarget(engine, row, snapshot, null, undefined, { allowMissing: purge });- return { observedRevision, noop, file, ...databaseOnlyPublication(row, file), apply: async tx => {+ return { observedRevision, noop, file, ...await pageDatabaseOnlyPublication(engine, 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 };@@ -206,7 +216,7 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequestconst tags = versionTags ?? [...new Set([...snapshot.tags,...incoming.tags])].sort();if (digest(canonical(snapshot.page,snapshot.tags)) === digest(canonical(incoming,tags))) {const file=await prepareFileTarget(engine,row,snapshot,targetDeleted ? null : serializePageToMarkdown(snapshot.page,snapshot.tags));- return {observedRevision,noop:true,file,...databaseOnlyPublication(row,file),+ return {observedRevision,noop:true,file,...await pageDatabaseOnlyPublication(engine,row,file),apply:async()=>({...pageNoopAdvisories(row),status:'skipped',slug:row.slug,source_id:row.source_id,noop:true,chunks:0,chunk_skip_reason:'write_skipped',...(row.operation==='capture'?{channel:'capture',content_hash:p.capture_hash}:{})})};}@@ -263,7 +273,7 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequestconst 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 => {+ return { observedRevision, noop, additionalPageKeys:links?.pageKeys, file, ...await pageDatabaseOnlyPublication(engine, row, file), validate: ready.validate, apply: async tx => {let autoLinks: Awaited<ReturnType<NonNullable<typeof links>['apply']>> | undefined;if (!noop) {await ready.apply(tx);diff --git a/src/core/persistence/prepared-maintenance.ts b/src/core/persistence/prepared-maintenance.tsindex cb3354ac1f..ac199c5ec1 100644--- a/src/core/persistence/prepared-maintenance.ts+++ b/src/core/persistence/prepared-maintenance.ts@@ -92,11 +92,22 @@ async function submitMaintenance(engine: BrainEngine, authority: MaintenanceAuthreturn writeResponse(await waitForWrite(engine, row, loadConfig() ?? { engine: engine.kind }));}+/** #5523: a Life Chronicle timeline row projected onto the depth page in the same publication. */+export interface MaintenanceEventProjection { depth_slug: string; date: string; summary: string; }+export async function publishMaintenancePage(engine: BrainEngine, authority: MaintenanceAuthority, slug: string,- content: string, options: { requestId?: string; expectedRevision: string | null; file?: boolean }): Promise<Record<string, unknown>> {+ content: string, options: { requestId?: string; expectedRevision: string | null; file?: boolean;+ eventProjection?: MaintenanceEventProjection }): Promise<Record<string, unknown>> {+ const projection = options.eventProjection ? { event_projection: options.eventProjection } : {};return submitMaintenance(engine, authority, slug, { kind: 'managed_maintenance_page', content,- expected_revision: options.expectedRevision }, options.requestId ?? maintenanceRequestId({ authority: authority.writer,- slug, content, revision: options.expectedRevision, file: options.file ?? true }), options.file);+ expected_revision: options.expectedRevision, ...projection }, options.requestId ?? maintenanceRequestId({ authority: authority.writer,+ slug, content, revision: options.expectedRevision, file: options.file ?? true, ...projection }), options.file);+}++/** A maintenance request with its own intent kind, keyed by the intent (a retry replays its receipt). */+export async function submitMaintenanceIntent(engine: BrainEngine, authority: MaintenanceAuthority, slug: string,+ intent: Record<string, unknown> & { kind: string; expected_revision: string | null }): Promise<Record<string, unknown>> {+ return submitMaintenance(engine, authority, slug, intent, maintenanceRequestId({ authority: authority.writer, slug, intent }));}export async function stampMaintenancePage(engine: BrainEngine, authority: MaintenanceAuthority, slug: string,@@ -168,8 +179,24 @@ export async function submitMaintenanceConsolidation(engine: BrainEngine, authorexport async function prepareMaintenanceMutation(engine: BrainEngine, row: WriteRequest, config: GBrainConfig): Promise<PreparedMutation> {if (row.authority.remote) throw new OperationError('permission_denied', 'Remote maintenance publication is not supported.');- if (row.intent?.kind === 'managed_maintenance_page') return preparePageMutation(engine, row.intent.expected_revision === null- ? { ...row, intent: { ...row.intent, expected_revision: undefined } } : row, config);+ if (row.intent?.kind === 'managed_maintenance_page') {+ const prepared = await preparePageMutation(engine, row.intent.expected_revision === null+ ? { ...row, intent: { ...row.intent, expected_revision: undefined } } : row, config);+ const projection = row.intent.event_projection as MaintenanceEventProjection | undefined;+ if (!projection) return prepared;+ // #5523: the event page and its depth-page timeline row commit together in+ // the coordinator's source-scoped transaction; a missing depth page+ // projects nothing, exactly like the legacy writer.+ return { ...prepared, additionalPageKeys: [...prepared.additionalPageKeys ?? [],+ { sourceId: row.source_id, slug: projection.depth_slug }], apply: async tx => {+ const outcome = await prepared.apply(tx);+ const { projected } = await tx.upsertEventProjection({ depthSlug: projection.depth_slug, eventSlug: row.slug,+ date: projection.date, summary: projection.summary, sourceId: row.source_id });+ return { ...outcome, event_projected: projected };+ } };+ }+ if (row.intent?.kind === 'managed_maintenance_phantom_merge') return (await import('../cycle/phantom-redirect-managed.ts')).preparePhantomMerge(engine, row, config);+ if (row.intent?.kind === 'managed_maintenance_phantom_delete') return (await import('../cycle/phantom-redirect-managed.ts')).preparePhantomDelete(engine, row, config);if (row.intent?.kind !== 'managed_maintenance_consolidate') throw new OperationError('invalid_params', 'Unsupported maintenance request.');const p = row.intent;const facts = p.facts as FactSnapshot[];diff --git a/src/core/persistence/purge-deleted.ts b/src/core/persistence/purge-deleted.tsnew file mode 100644index 0000000000..cd4791c27d--- /dev/null+++ b/src/core/persistence/purge-deleted.ts@@ -0,0 +1,68 @@+import { randomUUID } from 'node:crypto';+import type { BrainEngine } from '../engine.ts';+import { loadConfig } from '../config.ts';+import type { OperationContext } from '../ops/contract.ts';+import { managedPersistenceEnabled } from './ownership.ts';+import { submitPageMutation } from './page-mutations.ts';++/** A tombstone that moved under a concurrent writer; the next run retries it. */+const DEFERRAL_CODES = new Set(['revision_conflict', 'page_not_found', 'page_identity_changed']);++export interface DeletedPagePurge {+ slugs: string[];+ count: number;+ /** Every expired tombstone not purged this run, with its reason. Empty on an unmanaged brain. */+ blocked: Array<{ source_id: string; slug: string; reason: string; code: string | null }>;+ /** Tombstones restored, changed or removed by a concurrent writer; retried next run. */+ deferred: number;+ /** Operational failures (owner, binding, storage, protocol). */+ failed: number;+ /** Present when `failed > 0`, so the caller cannot report success. */+ error?: { class: string; code: string; message: string };+}++/**+ * #5405: hard-delete tombstones older than the recovery window. An unmanaged+ * brain keeps the engine's bulk delete. A managed brain refuses that bulk+ * delete, so each expired tombstone is purged through the coordinator with the+ * trusted-local `delete_page --purge` protocol, bound to the tombstone's+ * revision. Pages in archived sources are left to the source-lifecycle purge.+ * A tombstone that cannot be purged is reported, never forced.+ */+export async function purgeDeletedPagesCoordinated(engine: BrainEngine, olderThanHours: number): Promise<DeletedPagePurge> {+ if (!await managedPersistenceEnabled(engine)) {+ const result = await engine.purgeDeletedPages(olderThanHours);+ return { slugs: result.slugs, count: result.count, blocked: [], deferred: 0, failed: 0 };+ }+ const hours = Math.max(0, Math.floor(olderThanHours));+ const rows = await engine.executeRaw<{ source_id: string; slug: string; cutoff: string }>(+ `SELECT p.source_id, p.slug, (now() - ($1 || ' hours')::interval)::text AS cutoff FROM pages p JOIN sources s ON s.id = p.source_id+ WHERE p.deleted_at IS NOT NULL AND p.deleted_at < now() - ($1 || ' hours')::interval AND NOT s.archived+ ORDER BY p.deleted_at ASC, p.source_id ASC, p.slug ASC`, [String(hours)]);+ const config = loadConfig() ?? { engine: engine.kind };+ const slugs: string[] = [];+ const blocked: DeletedPagePurge['blocked'] = [];+ let deferred = 0, failed = 0;+ for (const row of rows) {+ try {+ const snapshot = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });+ if (!snapshot?.page.deleted_at) continue;+ // Restored and deleted again since the scan: its recovery window restarted.+ if (new Date(snapshot.page.deleted_at).getTime() >= new Date(row.cutoff).getTime()) { deferred++; continue; }+ const ctx: OperationContext = { engine, config, remote: false, sourceId: row.source_id, dryRun: false,+ logger: { info() {}, warn() {}, error() {} } };+ await submitPageMutation(ctx, { operation: 'delete_page', params: { slug: row.slug, source_id: row.source_id,+ purge: true, expected_revision: snapshot.revision, request_id: randomUUID() } });+ slugs.push(row.slug);+ } catch (error) {+ const code = typeof (error as { code?: unknown })?.code === 'string' ? (error as { code: string }).code : null;+ if (code && DEFERRAL_CODES.has(code)) deferred++; else failed++;+ blocked.push({ source_id: row.source_id, slug: row.slug, code, reason: error instanceof Error ? error.message : String(error) });+ }+ }+ const failures = blocked.filter(b => !b.code || !DEFERRAL_CODES.has(b.code));+ const error = failed > 0 ? { class: 'ManagedPurgeFailed', code: 'managed_purge_failed',+ message: `${failed} expired page(s) could not be purged through the coordinator: ${failures.slice(0, 3)+ .map(b => `${b.source_id}/${b.slug}: ${b.reason}`).join('; ')}` } : undefined;+ return { slugs, count: slugs.length, blocked, deferred, failed, ...(error ? { error } : {}) };+}diff --git a/src/core/persistence/reconcile-prepare.ts b/src/core/persistence/reconcile-prepare.tsindex 0e663fa81c..683e0663fd 100644--- a/src/core/persistence/reconcile-prepare.ts+++ b/src/core/persistence/reconcile-prepare.ts@@ -46,7 +46,7 @@ export async function prepareReconcileResult(engine: BrainEngine, state: Reconciconst content = serializePageToMarkdown({ ...state.snapshot.page, ...result }, result.tags);let ready: PreparedContentImport | undefined;const imported = await importFromContent(engine, state.pins.slug, content, {- sourceId: state.pins.source_id, sourcePath: state.snapshot.page.source_path ?? undefined,+ sourceId: state.pins.source_id, sourcePath: state.snapshot.page.source_path ?? state.originSourcePath ?? undefined,filename: basename(state.path).replace(/\.mdx?$/i, ''), noEmbed: true, remote: false, allowEmptyOverwrite: true,prepareFrontmatter: page => stabilizeSafetyAssessments(page.frontmatter, state.snapshot.page.frontmatter, state.pins.assessment_at),prepare: async prepared => { ready = prepared; return prepared.result; },@@ -79,7 +79,8 @@ export async function prepareReconcileMutation(engine: BrainEngine, row: WriteRereturn {observedRevision: state.snapshot.revision,file: { path: state.path, root: state.root, content, expectedBeforeHash: state.pins.raw_file_hash },- noop: ready.noop && sha256(content) === state.pins.raw_file_hash,+ // A database-only page matched by its slug path always records that file as its origin.+ noop: ready.noop && sha256(content) === state.pins.raw_file_hash && state.origin === 'recorded',validate: async tx => {await authorizeStoredRequest(tx, row, true);assertReconcilePins(artifact.preconditions, (await readReconcileState(tx, row.source_id, row.slug, artifact.preconditions.assessment_at)).pins);@@ -88,6 +89,13 @@ export async function prepareReconcileMutation(engine: BrainEngine, row: WriteRe},apply: async tx => {await ready.apply(tx);+ if (state.originSourcePath) {+ await tx.executeRaw(`UPDATE pages SET source_path=$3 WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL+ AND source_path IS NULL`, [row.source_id, row.slug, state.originSourcePath]);+ // The page now has a canonical origin: drop the #5254 database-only classification.+ await tx.executeRaw(`UPDATE pages SET database_only_reason=NULL WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL+ AND database_only_reason='unbound_source' AND source_path IS NOT NULL`, [row.source_id, row.slug]);+ }if (!ready.noop) { await prepared.project!(tx); await sealPageTextProjection(tx, row.slug, row.source_id); }const final = await tx.readPageSnapshot(row.slug, { sourceId: row.source_id });const scanStateTransferred = final ? await transferLegacyAtomPageState(tx, state.snapshot, final) : false;diff --git a/src/core/persistence/reconcile-state.ts b/src/core/persistence/reconcile-state.tsindex 6876481d79..f13a017183 100644--- a/src/core/persistence/reconcile-state.ts+++ b/src/core/persistence/reconcile-state.ts@@ -11,6 +11,8 @@ import type { PageSnapshot } from '../page-state/types.ts';import { isWriteTargetContained } from '../path-confine.ts';import { recordedPathFromFileUri, scannerSlugRootMode } from '../write-through.ts';import { localHostId } from './identity.ts';+import { isDatabaseOnlyPage, slugDerivedOrigin } from './unbound-pages.ts';+import { isUnboundSourcePage } from './unbound-source.ts';import { getWorktreeBinding, type WorktreeBinding } from './ownership.ts';import { digest, requireUuid, sha256, stableJson } from './digest.ts';import { reconcileCanonical, strictReconcileKeys, validateReconcileJson, type ReconcileConflict, type ReconcileDecision } from './reconcile-merge.ts';@@ -30,6 +32,10 @@ export interface ReconcileArtifact {export interface ReconcileState {binding: WorktreeBinding; root: string; path: string; raw: Buffer; snapshot: PageSnapshot;storedPage: Record<string, unknown>; file: ParsedPage; pins: ReconcilePins;+ /** `slug_derived`: a database-only page matched to the canonical file at its slug path. */+ origin: 'recorded' | 'slug_derived';+ /** The `source_path` apply records for a `slug_derived` origin. */+ originSourcePath: string | null;}export async function reconcilePolicyDigest(engine: BrainEngine, sourceId: string): Promise<string> {const config = await loadConfigWithEngine(engine, loadConfig());@@ -60,7 +66,11 @@ export async function readReconcileState(engine: BrainEngine, sourceId: string,const root = realpathSync(join(binding.local_path, binding.relative_path));const recorded = recordedPathFromFileUri(snapshot.page.source_uri, root);const mode = await scannerSlugRootMode(engine, sourceId, root);- const path = recordedReconcilePath(root, snapshot.page, mode);+ const recordedPath = recordedReconcilePath(root, snapshot.page, mode);+ const derived = !recordedPath && isDatabaseOnlyPage({ ...snapshot.page,+ database_only_reason: await isUnboundSourcePage(engine, sourceId, slug) ? 'unbound_source' : null }) ? slugDerivedOrigin(root, slug, mode) : null;+ const origin = derived ? 'slug_derived' : 'recorded';+ const path = recordedPath ?? derived?.path ?? null;if (!path || !isWriteTargetContained(path, root)) throw new OperationError('source_changed', 'The page has no unambiguous confined recorded Markdown origin.');let size: number;try {@@ -107,7 +117,7 @@ export async function readReconcileState(engine: BrainEngine, sourceId: string,page_id: snapshot.page.id, worktree_id: binding.worktree_id, binding_digest: digest({ binding, root, path: canonicalPath }), owner_epoch: String(binding.owner_epoch),revision: snapshot.revision, raw_file_hash: sha256(raw), relative_path: relative(root, path),policy_digest: await reconcilePolicyDigest(engine, sourceId), withdrawals_digest: digest(snapshot.withdrawals), assessment_at: assessmentAt };- return { binding, root, path, raw, snapshot, storedPage, file: reconcileCanonical(parsed, parsed.tags), pins };+ return { binding, root, path, raw, snapshot, storedPage, file: reconcileCanonical(parsed, parsed.tags), pins, origin, originSourcePath: derived?.sourcePath ?? null };}export function assertReconcilePins(expected: ReconcilePins, actual: ReconcilePins): void {for (const key of Object.keys(expected) as Array<keyof ReconcilePins>) if (expected[key] !== actual[key]) staleReconcile(key);diff --git a/src/core/persistence/semantic-pages.ts b/src/core/persistence/semantic-pages.tsindex 04a2e96fbd..0f505a6643 100644--- a/src/core/persistence/semantic-pages.ts+++ b/src/core/persistence/semantic-pages.ts@@ -9,6 +9,8 @@ import type { PreparedMutation } from './coordinator.ts';import type { WriteRequest } from './model.ts';import { assertPageRevision } from '../page-state/types.ts';import { engineMutationPrecondition, parseMutationPrecondition } from './preconditions.ts';+import { materializedMarker } from '../timeline-marker.ts';+import { isConnectorSourceKind } from './connector-identity.ts';function hasExactBlock(text: string, block: string): boolean {const wanted = block.trimEnd().split('\n');@@ -33,12 +35,16 @@ export async function prepareSemanticPageMutation(engine: BrainEngine, row: Writconst entry = { date: String(p.date), summary: String(p.summary), source: String(p.source ?? ''), detail: String(p.detail ?? '') };const rendered = renderTimelineEntry(entry, row.slug);if (!rendered) throw new OperationError('invalid_params', 'The timeline entry cannot be represented losslessly in Markdown.');- const exact = hasExactBlock(snapshot.page.timeline, rendered.block);+ // #5567: a connector re-renders its pages from the provider, which never holds this entry. The+ // materialized marker makes the connector's preserving render carry the bullet forward instead of deleting it.+ const [source] = await engine.executeRaw<{ kind: string | null }>("SELECT config->>'kind' AS kind FROM sources WHERE id=$1", [row.source_id]);+ const block = isConnectorSourceKind(source?.kind) ? `${materializedMarker(rendered.canonical)}\n${rendered.block}` : rendered.block;+ const exact = hasExactBlock(snapshot.page.timeline, block);const tuples = extractTimelineFromContent(`${snapshot.page.compiled_truth}\n<!-- timeline -->\n${snapshot.page.timeline}`, row.slug);if (!exact && tuples.some(tuple => tuple.date === rendered.canonical.date && tuple.source === rendered.canonical.source && tuple.summary === rendered.canonical.summary)) {throw new OperationError('invalid_params', 'This timeline identity already exists with different detail.', 'Read and conditionally edit the existing page to change that entry.');}- const page = { ...snapshot.page, timeline: exact ? snapshot.page.timeline : spliceTimelineBlock(snapshot.page.timeline, entry.date, rendered.block) };+ const page = { ...snapshot.page, timeline: exact ? snapshot.page.timeline : spliceTimelineBlock(snapshot.page.timeline, entry.date, block) };const prepared = await preparePageMutation(engine, row, config, {expectedRevision: snapshot.revision, content: serializePageToMarkdown(page, snapshot.tags),});diff --git a/src/core/persistence/service.ts b/src/core/persistence/service.tsindex 704573669a..cef364c9db 100644--- a/src/core/persistence/service.ts+++ b/src/core/persistence/service.ts@@ -10,6 +10,7 @@ import { isWriteErrorCode, type WriteReceipt } from './types.ts';import { registerPgliteReopen } from '../pglite-lifecycle.ts';import { assertMutationProtocol } from './protocol.ts';import { pendingWriteHint } from './health.ts';+import { receiptDeliveredHint } from './connector-errors.ts';interface Service { consumer: PersistenceConsumer; stopping: boolean; unregisterStop?: () => void; unregisterReopen?: () => void; }const services = new WeakMap<BrainEngine, Service>();@@ -31,7 +32,8 @@ export async function preparePersistedMutation(e: BrainEngine, row: WriteRequest}if (row.operation === 'submit_job' && String(row.intent?.kind).startsWith('managed_atom_')) return (await import('./atom-maintenance.ts')).prepareManagedAtomMutation(e, row, cfg);if (row.operation === 'extract_facts' && String(row.intent?.kind).startsWith('managed_facts_')) return (await import('./facts-prepare.ts')).prepareManagedFactsMutation(e, row, cfg);- if (row.operation === 'submit_job' && String(row.intent?.kind).startsWith('managed_connector_')) return (await import('./connector-sync.ts')).prepareConnectorMutation(e, row);+ if (row.operation === 'submit_job' && String(row.intent?.kind).startsWith('connector_v2_')) return (await import('./connector-sync.ts')).prepareConnectorMutation(e, row);+ if (row.operation === 'submit_job' && String(row.intent?.kind).startsWith('managed_connector_')) return (await import('./connector-sync.ts')).prepareOutdatedConnectorMutation(e, row);if (row.operation === 'put_page' && row.intent?.kind === 'canonical_reconcile') return (await import('./reconcile-prepare.ts')).prepareReconcileMutation(e, row, cfg);if (row.operation === 'put_page' && row.intent?.kind === 'managed_grandfather') return (await import('./grandfather.ts')).prepareGrandfatherMutation(e, row);if (row.operation === 'submit_job' && row.intent?.kind === 'code_projection_reindex') return (await import('./projection-reindex.ts')).prepareCodeReindex(e, row);@@ -132,10 +134,12 @@ export function writeResponse(row: WriteRequest): Record<string, unknown> {const receipt = receiptFor(row);if (row.state === 'committed') return { ...receipt, write_request: receipt };const reason = !isTerminal(row) ? 'write_pending' : row.error_code ?? (row.state === 'cancelled' ? 'cancelled' : 'storage_error');+ const delivered = isTerminal(row) ? receiptDeliveredHint(row) : null;const error = new OperationError(reason, !isTerminal(row) ? 'The write is accepted and is still pending.': row.error_message ?? 'The write did not commit.', !isTerminal(row)? pendingWriteHint(receipt)- : 'Inspect this receipt before submitting a new request_id.');+ : delivered?.suggestion ?? 'Inspect this receipt before submitting a new request_id.', delivered?.docs);+ if (delivered?.detail) error.detail = delivered.detail;error.writeRequest = receipt as WriteReceipt;error.writeError = isWriteErrorCode(reason) ? reason : reason === 'page_identity_changed' ? 'source_changed' : 'storage_error';throw error;diff --git a/src/core/persistence/skill-activation.ts b/src/core/persistence/skill-activation.tsindex aca10d170e..c0dfa679b5 100644--- a/src/core/persistence/skill-activation.ts+++ b/src/core/persistence/skill-activation.ts@@ -7,6 +7,8 @@ import type { NativeLockHandle } from './native-lock.ts';import { declarePersistenceProtocol } from './protocol.ts';import { managedFilesystemDatastorePath, refreshManagedFilesystemRoots } from './filesystem-guard.ts';import { assertWriterAdminState, WRITER_INSPECTION_HINT } from './admin-intent.ts';+import { assertWriterAdminUnlocked } from './admin-lock.ts';+import { notQuiescedError } from './blocking-effects.ts';export async function activateSharedSkillPersistence(engine: BrainEngine,options: { confirmQuiesced?: boolean; dryRun?: boolean; expectedState?: string } = {}): Promise<{ activated: boolean; protocol_version: 2; filesystem_sources: number; drift_audit?: ActivationReport['drift_audit'] }> {@@ -44,6 +46,7 @@ export async function activateSharedSkillPersistence(engine: BrainEngine,await tx.executeRaw("SELECT set_config('synchronous_commit','on',true),set_config('lock_timeout','1s',true)");await assertWriterAdminState(tx, options.expectedState);await tx.executeRaw('SELECT singleton FROM persistence_brain WHERE singleton=1 FOR UPDATE');+ await assertWriterAdminUnlocked(tx);await tx.executeRaw('SELECT id FROM persistence_worktrees ORDER BY id FOR UPDATE');await tx.executeRaw('SELECT id FROM sources ORDER BY id FOR SHARE');await tx.executeRaw('LOCK TABLE gbrain_cycle_locks IN SHARE MODE');@@ -51,9 +54,11 @@ export async function activateSharedSkillPersistence(engine: BrainEngine,const identity = (rows: WorktreeBinding[]) => JSON.stringify(rows.map(row => [row.source_id, row.source_incarnation, row.worktree_id,row.owner_host_id, String(row.owner_epoch), String(row.topology_generation), row.relative_path, row.local_path, row.coordination_path]));if (identity(current) !== identity(initial)- || (await tx.executeRaw('SELECT id FROM gbrain_cycle_locks LIMIT 1')).length- || (await tx.executeRaw("SELECT id FROM persistence_requests WHERE state IN ('queued','running','recovering') OR recovery IS NOT NULL LIMIT 1")).length- || (await tx.executeRaw("SELECT id FROM persistence_effects WHERE state IN ('queued','running') OR recovery IS NOT NULL LIMIT 1")).length) throw quiescence();+ || (await tx.executeRaw('SELECT id FROM gbrain_cycle_locks LIMIT 1')).length) throw quiescence();+ if ((await tx.executeRaw("SELECT id FROM persistence_requests WHERE state IN ('queued','running','recovering') OR recovery IS NOT NULL LIMIT 1")).length+ || (await tx.executeRaw("SELECT id FROM persistence_effects WHERE state IN ('queued','running') OR recovery IS NOT NULL LIMIT 1")).length) {+ throw await notQuiescedError(tx, quiescence().message, { queuedEffects: true });+ }if (options.dryRun) return { activated: false, protocol_version: 2, filesystem_sources: current.length,...(base.drift_audit ? { drift_audit: base.drift_audit } : {}) };for (const binding of current) await tx.executeRaw(`INSERT INTO persistence_writer_protocols(worktree_id,host_id,owner_epoch,protocol_version)diff --git a/src/core/persistence/source-lifecycle.ts b/src/core/persistence/source-lifecycle.tsindex 82af918658..d3330eaccf 100644--- a/src/core/persistence/source-lifecycle.ts+++ b/src/core/persistence/source-lifecycle.ts@@ -20,6 +20,7 @@ import { canonicalFilesystemPath, nativeFilesystemPath } from './root-registry.timport { flushTopologyDirectory } from './topology-filesystem.ts';import { claimPhysicalRoot } from './physical-root.ts';import { assertWriterAdminState, WRITER_INSPECTION_HINT } from './admin-intent.ts';+import { assertWriterAdminUnlocked } from './admin-lock.ts';export interface SourceLifecycleInput {operation:'add'|'claim'|'archive'|'restore'|'remove'|'purge'|'rebind'|'reclone';@@ -30,6 +31,7 @@ export interface SourceLifecycleInput {expiredOnly?:boolean;requireGitContent?:boolean;expectedAdminState?:string;+ automaticClaim?:boolean;}interface SourceState {id:string;incarnation:string;archived:boolean;local_path:string|null;config:Record<string,unknown>;name:string;last_commit:string|null;}@@ -84,7 +86,7 @@ export async function runManagedSourceLifecycle(engine:BrainEngine,input:SourceLthrow new OperationError('invalid_params','request_id and expected_incarnation must be UUIDs.');if(['remove','purge','archive'].includes(input.operation)&&input.sourceId==='default') throw new OperationError('invalid_params','The default source cannot be removed or archived.');const principal=await topologyPrincipal(engine);- const intent={...input,requestId:undefined,dryRun:undefined};+ const intent={...input,requestId:undefined,dryRun:undefined,automaticClaim:undefined};const prior=await priorTopologyChange(engine,principal,requestId,intent);if(prior) return topologyReceipt(prior);if(input.requireGitContent&&input.path&&(!isInsideGitRepo(input.path)||!hasTrackedContent(input.path)))@@ -113,6 +115,7 @@ export async function runManagedSourceLifecycle(engine:BrainEngine,input:SourceLawait assertWriterAdminState(tx,input.expectedAdminState);await tx.executeRaw("SELECT set_config('synchronous_commit','on',true)");const sources=await lockTopologyRows(tx,input.sourceId,bindings);+ if(input.operation==='claim'&&!input.automaticClaim) await assertWriterAdminUnlocked(tx);const [source]=await tx.executeRaw<SourceState>('SELECT id,incarnation,archived,local_path,config,name,last_commit FROM sources WHERE id=$1',[input.sourceId]);if(source)source.config=parseSourceConfig(source.config);const repeated=await priorTopologyChange(tx,principal,requestId,intent);diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.tsindex 0734b109ef..a01db6d164 100644--- a/src/core/persistence/sync-prepare.ts+++ b/src/core/persistence/sync-prepare.ts@@ -26,6 +26,7 @@ import { loadActivePackForEngine, checkApprovedSchemaForEngine } from '../schemaimport type { CompanyBrainPlan } from '../company-brain/types.ts';import { companyBrainProfile } from '../company-brain/profile.ts';import { companyBrainPolicyFingerprint } from '../company-brain/policy.ts';+import { isUnboundSourcePage, UNBOUND_COLLISION_MESSAGE } from './unbound-source.ts';export interface SyncIntent extends Record<string, unknown> {companyApproval?: { schema: NonNullable<CompanyBrainPlan['schema']>; planDigest: string; extractorVersion: string; policyFingerprint: string };@@ -147,6 +148,9 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Writeif ((snapshot?.page.id ?? null) !== row.page_id || (snapshot?.page.source_path != null && !sameSyncOrigin(snapshot.page.source_path, recordedOrigin, originScope, snapshot.page.slug))) {throw new OperationError('page_identity_changed', 'The imported path no longer names the accepted page.');}+ if (snapshot && snapshot.page.source_path == null && await isUnboundSourcePage(engine, row.source_id, row.slug)) {+ throw new OperationError('source_changed', UNBOUND_COLLISION_MESSAGE);+ }if (p.kind === 'managed_sync_delete') return { observedRevision: snapshot?.revision ?? null, noop: !snapshot || snapshot.page.deleted_at != null,validate, apply: async tx => {if (snapshot && snapshot.page.deleted_at == null) { await tx.createVersion(row.slug, source); await tx.softDeletePage(row.slug, source); }@@ -228,6 +232,8 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Write// A rename projects against the moved page (same id), so its pinned timeline rows carry over.const project = await prepareCanonicalProjections(engine, ready.parsedPage, row.slug, row.source_id, base, p.companyApproval ? 'immutable' : 'file');return { observedRevision: snapshot?.revision ?? null,+ // Tells the #5470 screen the content is unchanged; publication still queues its effects.+ contentUnchanged: ready.noop && !moved && !overlay,...(renamed ? { additionalPageKeys: [{ sourceId: row.source_id, slug: renamed.slug }] } : {}),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 79a3ca6688..a7bb6a8346 100644--- a/src/core/persistence/sync-run.ts+++ b/src/core/persistence/sync-run.ts@@ -12,7 +12,10 @@ import { assertPersistenceAccepting, foregroundWriteCompletions, startPersistencimport { assertSyncEntryOrigin, discoverManagedSync, resolveManagedSyncContext, readSyncContent, readSyncFile, syncGit, type SyncDiscovery } from './sync-discovery.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 { prepareManagedSyncMutation, type SyncIntent } from './sync-prepare.ts';+import { inspectUnchanged, screeningRequest } from './noop-kernel.ts';+import type { GBrainConfig } from '../config.ts';+import { join } from 'node:path';import { currentCompanyBrainSync, getCompanyBrainProfile, readCompanyBrainPlan } from '../company-brain/profile.ts';import { readCommittedBlob } from '../company-brain/revision.ts';import { refreshProjectionStatistics } from '../search/projection-statistics.ts';@@ -361,6 +364,16 @@ export async function performManagedSync(engine: BrainEngine, opts: SyncOpts, slphase = 'admission';const prior = await getWriteRequest(engine, cursor.authority.writer.principal, pending.requestId);assertActive();+ // #5470: a frozen import whose publication would change nothing advances the cursor without an admission.+ if (!prior && await unchangedSyncImport(engine, cursor, pending, config)) {+ const skipped: Cursor = { ...cursor, index: cursor.index + 1, counts: { ...cursor.counts } }; delete skipped.pending;+ cursor = await saveCursor(engine, key, cursor, skipped);+ opts.onProgress?.({ phase: 'managed_sync.page_committed', bankedFiles: cursor.index });+ assertActive();+ // A skipped entry still counts toward the caller's slice, so a sliced run yields at the same positions.+ if (slice && (cursor.index - sliceFirstIndex >= slice.maxPages || performance.now() - sliceStarted >= slice.maxMs)) return result(cursor, 'partial', 'writer_yield');+ continue;+ }const admitting = cursor;const row = prior ?? await retryWriteAdmission(pending.requestId, remaining => engine.transaction(async tx => {assertActive();@@ -444,3 +457,27 @@ export async function performManagedSync(engine: BrainEngine, opts: SyncOpts, slthrow error;}}++/**+ * #5470 no-op screen for working-tree and company-profile sync: runs the sync+ * preparer on the frozen, unadmitted entry. A rename, a canonical overlay or a+ * working-tree file that differs from the imported bytes is always admitted.+ */+async function unchangedSyncImport(engine: BrainEngine, cursor: Cursor, pending: Pending, config: GBrainConfig): Promise<boolean> {+ const intent = pending.intent;+ if (intent.kind !== 'managed_sync_import' || intent.renameFrom || pending.pageId === null || typeof intent.path !== 'string' || typeof intent.content !== 'string') return false;+ try {+ const snapshot = await engine.readPageSnapshot(pending.slug, { sourceId: cursor.sourceId, includeDeleted: true });+ const row = screeningRequest({ source_id: cursor.sourceId, source_incarnation: cursor.incarnation, slug: pending.slug, page_id: pending.pageId,+ worktree_id: cursor.binding.worktree_id, authority: cursor.authority.writer, intent, request_id: pending.requestId });+ const prepared = await prepareManagedSyncMutation(engine, row, config);+ if (prepared.file || prepared.target === 'skill_bundle') return false;+ const file = { root: cursor.root, path: join(cursor.root, intent.path), content: intent.content };+ if ((await inspectUnchanged(engine, { prepared: { ...prepared, target: 'page', file }, snapshot, sourcePath: intent.sourcePath, databaseOnly: false,+ embeddingRequested: !prepared.deferEmbedding && !config.embedding_disabled && !!config.embedding_model?.trim() })).admitReason) return false;+ await prepared.validate?.(engine);+ return true;+ } catch {+ return false;+ }+}diff --git a/src/core/persistence/sync-wire.ts b/src/core/persistence/sync-wire.tsindex d0a8760cf9..6d40d5880d 100644--- a/src/core/persistence/sync-wire.ts+++ b/src/core/persistence/sync-wire.ts@@ -5,7 +5,7 @@ import { OperationError } from '../ops/contract.ts';export const SYNC_BOOLEAN_FLAGS = {'--full':'full','--dry-run':'dryRun','--no-pull':'noPull','--no-embed':'noEmbed','--no-extract':'noExtract','--no-schema-pack':'noSchemaPack','--retry-failed':'retryFailed','--skip-failed':'skipFailed',- '--include-gitignored':'includeGitignored','--working-tree':'workingTree',+ '--include-gitignored':'includeGitignored','--working-tree':'workingTree','--reset-checkpoint':'resetCheckpoint',} as const;export const SYNC_VALUE_FLAGS = { '--source':'sourceId','--repo':'repoPath','--src-subpath':'srcSubpath','--strategy':'strategy','--exclude':'exclude','--include-hidden':'includeHidden' } as const;diff --git a/src/core/persistence/types.ts b/src/core/persistence/types.tsindex a3cc58e8c5..80ce6fb648 100644--- a/src/core/persistence/types.ts+++ b/src/core/persistence/types.ts@@ -14,7 +14,8 @@ 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', 'take_row_collision', 'invalid_source_uri',+ 'skill_bundle_required', 'take_row_collision', 'invalid_source_uri', 'writer_admin_locked',+ 'connector_account_changed', 'connector_intent_outdated',] as const;export type WriteErrorCode = typeof WRITE_ERROR_CODES[number];diff --git a/src/core/persistence/unbound-pages.ts b/src/core/persistence/unbound-pages.tsnew file mode 100644index 0000000000..b9a757f4cd--- /dev/null+++ b/src/core/persistence/unbound-pages.ts@@ -0,0 +1,34 @@+/**+ * Database-only pages and their slug-derived canonical path (fix wave 3,+ * #5254 collision resolution). A page written while its source had no+ * canonical owner is stored without a recorded origin: no `source_path` and no+ * `source_uri`. After the source is bound, a canonical file can appear at the+ * page's slug-derived path; `gbrain sources reconcile` then previews both sides+ * against that path instead of refusing for want of a recorded origin.+ *+ * `isDatabaseOnlyPage` is the one predicate reconcile consults. It requires+ * the durable page-level marker (`pages.database_only_reason='unbound_source'`,+ * stamped in the publication transaction), so an ordinary page that merely+ * lacks a recorded origin is never matched to a slug-derived file.+ */+import { resolveSourceLocalFilePath } from '../markdown.ts';+import { scannerSourcePath } from '../write-through.ts';+import { resolveSlugForPath } from '../sync.ts';++export function isDatabaseOnlyPage(page: { source_path?: string | null; source_uri?: string | null; database_only_reason?: string | null }): boolean {+ return page.database_only_reason === 'unbound_source' && !page.source_path?.trim() && !page.source_uri?.trim();+}++/**+ * The canonical file an import would give this slug (`<slug>.md` under the Git+ * root or the source root, per the source's slug-root mode) and the+ * `source_path` a scan of that file records. Null when it resolves outside the+ * source, or when a scan of the candidate would give it a different slug (a+ * legacy source-relative fallback in a Git subfolder source names another page).+ */+export function slugDerivedOrigin(root: string, slug: string, mode: 'git-root' | 'source-root'): { path: string; sourcePath: string } | null {+ const path = resolveSourceLocalFilePath(root, `${slug}.md`, slug, mode);+ if (!path) return null;+ const sourcePath = scannerSourcePath(root, path, mode);+ return resolveSlugForPath(sourcePath) === slug ? { path, sourcePath } : null;+}diff --git a/src/core/persistence/unbound-source.ts b/src/core/persistence/unbound-source.tsnew file mode 100644index 0000000000..101c358993--- /dev/null+++ b/src/core/persistence/unbound-source.ts@@ -0,0 +1,99 @@+import type { BrainEngine } from '../engine.ts';+import { OperationError } from '../ops/contract.ts';+import type { SqlEngine, WriteRequest } from './model.ts';++/**+ * #5254: a Postgres page write to a filesystem source with no canonical owner.+ * Refused by default; `persistence.unbound_write=database_only` lets put_page+ * write new or already database-only pages to the database only. Those pages+ * carry `pages.database_only_reason='unbound_source'` so writes and sync after+ * binding keep them database-only instead of materializing or overwriting them.+ */+export const UNBOUND_WRITE_KEY = 'persistence.unbound_write';+export const UNBOUND_WRITE_VALUES = ['refuse', 'database_only'] as const;+export type UnboundWritePolicy = typeof UNBOUND_WRITE_VALUES[number];+export const UNBOUND_SOURCE_DOCS = 'docs/guides/write-refusals.md#unbound-sources-on-postgres';+export const UNBOUND_PUBLICATION_MESSAGE = 'The source was bound, or the page gained a canonical file, after this database-only write was accepted.';+export const CONNECTOR_BOUND_HINT = 'Nothing was written. Read the page again and submit the write with a new request_id; the bound source publishes it to its canonical file.';+export const CONNECTOR_BOUND_MESSAGE = 'The connector source gained a canonical owner after this database-only write was accepted.';+export const UNBOUND_COLLISION_MESSAGE = 'A database-only page written while its source was unbound already uses this slug.';++export function parseUnboundWriteValue(value: string): UnboundWritePolicy {+ if ((UNBOUND_WRITE_VALUES as readonly string[]).includes(value)) return value as UnboundWritePolicy;+ throw new OperationError('invalid_params', `${UNBOUND_WRITE_KEY} must be one of: ${UNBOUND_WRITE_VALUES.join(', ')} (got '${value}').`);+}++/** A missing or unreadable value keeps the refusal. */+export async function readUnboundWritePolicy(engine: Pick<BrainEngine, 'getConfig'>): Promise<UnboundWritePolicy> {+ return await engine.getConfig(UNBOUND_WRITE_KEY) === 'database_only' ? 'database_only' : 'refuse';+}++export function unboundBindCommand(sourceId: string, path: string | null): string {+ return `run gbrain sources writer status ${sourceId} --json and note admin_state, then run gbrain sources writer claim ${sourceId} `+ + `--path ${path ?? '<checkout path on the brain host>'} --admin-intent writer_claim --expected-state <admin_state>`;+}++/**+ * `path` is filled only for trusted local callers; remote callers get a+ * placeholder instead of a host path.+ */+export function unboundSourceError(sourceId: string, path: string | null, scope: 'put_page' | 'file_backed' | 'other'): OperationError {+ const bind = `bind the source on the brain host: ${unboundBindCommand(sourceId, path)} `+ + '(if an operator has locked writer administration, ask the operator to unlock it first)';+ const suggestion = scope === 'put_page'+ ? `Source '${sourceId}' has a checkout path but no canonical owner. Choose one: ${bind}; or allow database-only writes to unbound sources `+ + `with gbrain config set ${UNBOUND_WRITE_KEY} database_only. Pages written that way stay database-only and are not materialized into canonical files after binding.`+ : `Source '${sourceId}' has a checkout path but no canonical owner. To write this page, ${bind}. `+ + (scope === 'file_backed'+ ? `${UNBOUND_WRITE_KEY}=database_only does not apply: this page came from a canonical file, and a database-only edit would be lost on the owner's next sync.`+ : `${UNBOUND_WRITE_KEY} applies only to put_page.`);+ const error = new OperationError('owner_unavailable', 'This source has no designated canonical owner.', suggestion, UNBOUND_SOURCE_DOCS);+ error.detail = 'unbound_source';+ return error;+}++export function unboundPublicationHint(sourceId: string): string {+ return `Source '${sourceId}' gained a canonical owner, or the page gained a canonical file, after this database-only write was accepted, so nothing was written. `+ + 'Read the page again and submit the write with a new request_id; a bound source publishes it to its canonical file.';+}++/**+ * Runs inside the publication transaction after the source row is share-locked+ * (authorizeStoredRequest), so a concurrent claim either committed before this+ * read or waits for the publication to finish.+ */+export async function assertUnboundPublication(tx: SqlEngine, row: Pick<WriteRequest, 'authority' | 'source_id' | 'operation'>, sourcePath: string | null | undefined): Promise<void> {+ // A page or memory write admitted database-only to an unbound connector source (connector_database)+ // must not publish around canonical files once the source has an owner. Connector intents+ // (submit_job) carry their own sync-authority check.+ if (row.authority.databaseOnlyReason === 'connector_database' && row.operation !== 'submit_job') {+ const bound = await tx.executeRaw('SELECT 1 FROM persistence_source_bindings WHERE source_id=$1 LIMIT 1', [row.source_id]);+ if (bound.length) throw new OperationError('owner_unavailable', CONNECTOR_BOUND_MESSAGE, CONNECTOR_BOUND_HINT);+ return;+ }+ if (row.authority.databaseOnlyReason !== 'unbound_source') return;+ const bound = await tx.executeRaw('SELECT 1 FROM persistence_source_bindings WHERE source_id=$1 LIMIT 1', [row.source_id]);+ if (!bound.length && !sourcePath) return;+ const error = new OperationError('owner_unavailable', UNBOUND_PUBLICATION_MESSAGE, unboundPublicationHint(row.source_id), UNBOUND_SOURCE_DOCS);+ error.detail = 'unbound_source';+ throw error;+}++export async function classifyUnboundPage(tx: SqlEngine, row: Pick<WriteRequest, 'authority' | 'source_id' | 'slug'>): Promise<void> {+ if (row.authority.databaseOnlyReason !== 'unbound_source') return;+ await tx.executeRaw("UPDATE pages SET database_only_reason='unbound_source' WHERE source_id=$1 AND slug=$2 AND database_only_reason IS NULL",+ [row.source_id, row.slug]);+}++export async function isUnboundSourcePage(engine: SqlEngine, sourceId: string, slug: string): Promise<boolean> {+ const [row] = await engine.executeRaw<{ database_only_reason: string | null }>(+ 'SELECT database_only_reason FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, slug]);+ return row?.database_only_reason === 'unbound_source';+}++export function unboundWriteWarning(sourceId: string, admittedUnbound: boolean): string {+ return `put_page wrote only to the database for source '${sourceId}': ` + (admittedUnbound+ ? `the source has no canonical owner and ${UNBOUND_WRITE_KEY}=database_only, so no markdown file was created. `+ : 'this page was written while the source had no canonical owner. ')+ + 'The page stays database-only and is not materialized into a canonical file after binding.';+}diff --git a/src/core/persistence/verb-errors.ts b/src/core/persistence/verb-errors.tsindex 15619d4d87..18ce009bf4 100644--- a/src/core/persistence/verb-errors.ts+++ b/src/core/persistence/verb-errors.ts@@ -1,6 +1,7 @@import { verbError, OperationError } from '../ops/contract.ts';import { isTerminalWriteState, isWriteErrorCode, type WriteErrorCode, type WriteReceipt } from './types.ts';import { pendingWriteHint } from './health.ts';+import { UNBOUND_COLLISION_MESSAGE, UNBOUND_PUBLICATION_MESSAGE } from './unbound-source.ts';export function writeFailureDiagnostic(code: string, message?: string | null): { reason: string; message: string; suggestion: string } {if (code === 'source_changed') {@@ -35,9 +36,15 @@ export function writeFailureDiagnostic(code: string, message?: string | null): {reason: 'source_binding_changed', message: 'The source binding changed after this sync was accepted.',suggestion: 'Inspect the current source binding on its existing owner. Do not claim, transfer, or activate a source as a data-repair shortcut.',};+ if (message === UNBOUND_COLLISION_MESSAGE) return {+ reason: 'unbound_source', message: 'A canonical file now occupies the path of a page written while its source was unbound. Neither copy was overwritten.',+ suggestion: 'The database page stays served. Rename or remove the canonical file, commit, and sync again, or copy what you need from the file into the page first.',+ };return { reason: 'source_changed', message: 'A canonical source input or binding changed; the write was refused.',suggestion: 'Inspect the source on its existing owner. For file/database drift, preview gbrain sources reconcile <source> <slug> --brain <brain> --preview. Do not change ownership or permissions to bypass this guard.' };}+ if (code === 'owner_unavailable' && message === UNBOUND_PUBLICATION_MESSAGE) return { reason: 'unbound_source', message,+ suggestion: 'Read the page again and submit the write with a new request_id; a bound source publishes it to its canonical file.' };if (code === 'owner_unavailable') return { reason: code, message: 'The accepted source owner is unavailable or changed.',suggestion: 'Check the existing owner and its availability. Do not claim, transfer, or activate a source to repair content.' };if (code === 'permission_denied' || code === 'scope_denied') return { reason: code, message: 'The caller is not authorized for this write.',diff --git a/src/core/persistence/writer-versions.ts b/src/core/persistence/writer-versions.tsnew file mode 100644index 0000000000..2e67828526--- /dev/null+++ b/src/core/persistence/writer-versions.ts@@ -0,0 +1,81 @@+/** Writer-version stamps on persistence_requests (migration 178): observation of older writers, not prevention. */+import { VERSION } from '../../version.ts';+import { localHostId } from './identity.ts';+import type { SqlEngine } from './model.ts';++/** Writers older than this may still delete database-only timeline rows during publication. */+export const WRITER_VERSION_FLOOR = '0.60.5.0';+export const UNSTAMPED_WRITER = 'unstamped (binary older than this release)';++/** Numeric comparison on all four components; null when either side is not a version. */+export function compareWriterVersions(a: string, b: string): number | null {+ const parse = (value: string) => {+ const match = /^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:\.(\d+))?(?:[-+].*)?$/.exec(value.trim());+ return match ? match.slice(1, 5).map(part => Number(part ?? 0)) : null;+ };+ const left = parse(a), right = parse(b);+ if (!left || !right) return null;+ for (let i = 0; i < 4; i++) if (left[i] !== right[i]) return left[i] < right[i] ? -1 : 1;+ return 0;+}+export function writerVersionLabel(version: string | null): string { return version ?? UNSTAMPED_WRITER; }+/** True for a missing stamp or a recorded version below the floor (an unparsable version counts as below). */+export function writerVersionBelowFloor(version: string | null): boolean {+ if (version === null) return true;+ const order = compareWriterVersions(version, WRITER_VERSION_FLOOR);+ return order === null || order < 0;+}++/** This binary's stamp. An unavailable host identity stamps no host rather than failing the write. */+export function writerStamp(): { version: string; hostId: string | null } {+ let hostId: string | null = null;+ try { hostId = localHostId(); } catch { /* unwritable or invalid identity: stamp the version only */ }+ return { version: VERSION, hostId };+}++export interface ObservedWriterVersion {+ role: 'admitter' | 'consumer'; host_id: string | null; principal: string; version: string | null; version_label: string; last_seen: string | null;+}+const iso = (value: unknown) => value === null || value === undefined ? null : new Date(value as string).toISOString();++/** Latest admitter and consumer version per host and principal across all retained requests, newest first. */+export async function listWriterVersions(engine: SqlEngine, limit = 50): Promise<ObservedWriterVersion[]> {+ const rows = await engine.executeRaw<{ role: 'admitter' | 'consumer'; host_id: string | null; principal: string; version: string | null; last_seen: unknown }>(+ `SELECT * FROM (+ SELECT DISTINCT ON (admitter_host_id,principal_kind,principal_id) 'admitter' AS role,admitter_host_id::text AS host_id,+ principal_kind||':'||principal_id AS principal,admitter_version AS version,created_at AS last_seen+ FROM persistence_requests ORDER BY admitter_host_id,principal_kind,principal_id,created_at DESC) a+ UNION ALL SELECT * FROM (+ SELECT DISTINCT ON (consumer_host_id,principal_kind,principal_id) 'consumer' AS role,consumer_host_id::text AS host_id,+ principal_kind||':'||principal_id AS principal,consumer_version AS version,COALESCE(published_at,completed_at) AS last_seen+ FROM persistence_requests WHERE state='committed'+ ORDER BY consumer_host_id,principal_kind,principal_id,COALESCE(published_at,completed_at) DESC) c+ ORDER BY last_seen DESC LIMIT $1`, [limit]);+ return rows.map(row => ({ role: row.role, host_id: row.host_id, principal: row.principal, version: row.version,+ version_label: writerVersionLabel(row.version), last_seen: iso(row.last_seen) }));+}++export interface RecentWriterVersion extends ObservedWriterVersion { requests: number; }++/**+ * Committed requests published in the last `days`, grouped per role, host and principal. Admitters count+ * only when admitted after the migration cutoff and consumers only when published after it, so a request+ * admitted before the cutoff and published after it is judged by its publication. An unstamped consumer's+ * host falls back to the worktree owner, the only host that can publish a filesystem request.+ */+export async function recentWriterVersions(engine: SqlEngine, days = 7): Promise<RecentWriterVersion[]> {+ const rows = await engine.executeRaw<{ role: 'admitter' | 'consumer'; host_id: string | null; principal: string; version: string | null; last_seen: unknown; requests: number }>(+ `WITH cutoff AS (SELECT writer_version_cutoff AS at FROM persistence_brain WHERE singleton=1 AND writer_version_cutoff IS NOT NULL),+ recent AS (SELECT r.*,COALESCE(r.published_at,r.completed_at) AS publication FROM persistence_requests r+ WHERE r.state='committed' AND COALESCE(r.published_at,r.completed_at)>=now()-($1::double precision*interval '1 day'))+ SELECT 'admitter' AS role,r.admitter_host_id::text AS host_id,r.principal_kind||':'||r.principal_id AS principal,+ r.admitter_version AS version,MAX(r.created_at) AS last_seen,COUNT(*)::integer AS requests+ FROM recent r CROSS JOIN cutoff c WHERE r.created_at>=c.at GROUP BY 2,3,4+ UNION ALL+ SELECT 'consumer' AS role,COALESCE(r.consumer_host_id,w.owner_host_id)::text AS host_id,r.principal_kind||':'||r.principal_id AS principal,+ r.consumer_version AS version,MAX(r.publication) AS last_seen,COUNT(*)::integer AS requests+ FROM recent r LEFT JOIN persistence_worktrees w ON w.id=r.worktree_id CROSS JOIN cutoff c WHERE r.publication>=c.at GROUP BY 2,3,4+ ORDER BY last_seen DESC`, [days]);+ return rows.map(row => ({ role: row.role, host_id: row.host_id, principal: row.principal, version: row.version,+ version_label: writerVersionLabel(row.version), last_seen: iso(row.last_seen), requests: Number(row.requests) }));+}diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.tsindex f46fe21cb5..fa82de9473 100644--- a/src/core/pglite-engine.ts+++ b/src/core/pglite-engine.ts@@ -574,10 +574,12 @@ export function buildWalRepairNotice(receipt: WalRepairReceipt): string {'⚠️ gbrain repaired this brain\'s PGLite WAL in place.',` Data dir: ${receipt.dataDir}`,` Cause: torn WAL/checkpoint state from an unclean shutdown (issue #223 class).`,- ` Data files were preserved; transactions not checkpointed before the`,- ` corruption may be lost (the standard pg_resetwal caveat).`,+ ` Transactions not checkpointed before the corruption may be lost, and`,+ ` indexes are not rebuilt: pages written just before the crash can be`,+ ` missing from vector search while keyword search still finds them.`,` Pre-repair backup: ${receipt.backupPath}`,- ` Recommended: run \`gbrain doctor\` to verify brain integrity.`,+ ` Next: rebuild the vector indexes with \`gbrain reindex --vectors\`,`,+ ` then run \`gbrain doctor\` to verify brain integrity.`,` Disable auto-repair with GBRAIN_PGLITE_WAL_REPAIR=off.`,].join('\n');}diff --git a/src/core/pglite-schema.ts b/src/core/pglite-schema.tsindex 1f9eaf8351..301a5fc135 100644--- a/src/core/pglite-schema.ts+++ b/src/core/pglite-schema.ts@@ -115,6 +115,9 @@ CREATE TABLE IF NOT EXISTS pages (-- (mirrors src/schema.sql). NULL = never extracted. Powers-- gbrain extract --stale + the links_extraction_lag doctor check.links_extracted_at TIMESTAMPTZ,+ -- #5254 (migration v177; mirrors src/schema.sql): 'unbound_source' marks a+ -- page written database-only while its source had no canonical owner.+ database_only_reason TEXT,-- v0.40.3.0 contextual retrieval (renumbered from v81 to v90 on master-- merge; mirrors src/schema.sql).-- contextual_retrieval_mode is the tier the page was last embedded under;diff --git a/src/core/remediation-checkpoint.ts b/src/core/remediation-checkpoint.tsindex 3f780a5ed7..6e16a6ae4b 100644--- a/src/core/remediation-checkpoint.ts+++ b/src/core/remediation-checkpoint.ts@@ -41,6 +41,21 @@ export interface RemediationCheckpoint {reason: string;model_id?: string;};+ /**+ * Resume contract (fix wave 3). Optional so checkpoints written by older+ * binaries still load; a checkpoint that carries them binds its resume to+ * this brain, this cap (cumulative across the run and every resume), this+ * `--include-repairs` consent and this step manifest. New job ids or repair+ * kinds found later never inherit the recorded consent.+ */+ brain_id?: string;+ max_usd?: number | null;+ include_repairs?: boolean;+ /** Settled spend across the original run and its resumes. */+ spent_usd?: number;+ manifest?: { job_ids: string[]; repair_kinds: string[] };+ /** Sources whose re-sealed pages still need embeddings after the budget ran out mid-repair. */+ pending_embed_sources?: string[];}function checkpointDir(): string {diff --git a/src/core/remediation/plan.ts b/src/core/remediation/plan.tsindex e003e388fc..c957d04029 100644--- a/src/core/remediation/plan.ts+++ b/src/core/remediation/plan.ts@@ -11,6 +11,7 @@ import {} from '../brain-score-recommendations.ts';import { loadRecommendationContext } from './context.ts';import type { RemediationPlan, RemediationPlanOpts } from './types.ts';+import { planRepairSteps } from './repairs.ts';/*** Synthetic check list for classification. computeRecommendations operates@@ -73,5 +74,6 @@ export async function computeRemediationPlan(est_total_seconds: estTotalSeconds,est_total_usd_cost: Number(estTotalUsd.toFixed(2)),blocked,+ ...(opts.repairs ? { repair_steps: await planRepairSteps(engine, { noEmbed: opts.repairs.noEmbed }) } : {}),};}diff --git a/src/core/remediation/repairs.ts b/src/core/remediation/repairs.tsnew file mode 100644index 0000000000..d6eb8fcf55--- /dev/null+++ b/src/core/remediation/repairs.ts@@ -0,0 +1,121 @@+/**+ * Repair steps in the doctor remediation plan and run (fix wave 3, Lane D).+ *+ * Every registered `gbrain repair` kind is previewed brain-wide; a kind with+ * pending items becomes a PROTECTED, local-only step that needs the user's+ * agreement (`--include-repairs`). Repair steps are independent of the brain+ * score target: `--target-score` governs job steps only, and an included+ * repair step always runs to completion. A paid step (one that may queue+ * embeddings) is not started when its estimate exceeds the remaining budget;+ * free steps still run. Repairs run in-process on the brain host through the+ * same runner `gbrain repair` uses, never as Minion jobs.+ */+import type { BrainEngine } from '../engine.ts';+import { OperationError } from '../ops/contract.ts';+import { resolveRepairScope, type RepairKind } from '../repair/core.ts';+import { REPAIR_REGISTRY, repairApplyCommand, repairMaySpend, repairRunner } from '../repair/registry.ts';++export interface RepairPlanStep {+ step: number;+ id: string;+ kind: RepairKind;+ affected: number;+ /** The exact command that applies this step alone. */+ command: string;+ requires_user_agreement: true;+ protected: true;+ /** May spend on embeddings (a model is configured and the kind embeds under these flags). */+ paid: boolean;+ /** `effect`: the persistence consumer embeds after publication, so the estimate is charged against the cap up front. `none`: never embeds. */+ embeds: 'effect' | 'inline' | 'none';+ /** USD estimate; null when the step is paid and the model price is unknown. */+ est_usd_cost: number | null;+ lifetime_ids: number;+ checks: string[];+ rationale: string;+}++export type RepairStepStatus = 'completed' | 'stopped' | 'failed' | 'budget_refused' | 'budget_exhausted';++export interface RepairStepResult {+ id: string;+ kind: RepairKind;+ status: RepairStepStatus;+ applied: number;+ skipped: number;+ message?: string;+}++/** Brain-wide preview of every registered kind; kinds with nothing pending are omitted. */+export async function planRepairSteps(engine: BrainEngine, opts: { noEmbed?: boolean; kinds?: readonly RepairKind[] } = {}): Promise<RepairPlanStep[]> {+ const scope = await resolveRepairScope(engine);+ const runner = await repairRunner(engine, { apply: false, noEmbed: opts.noEmbed, logger: { info() {}, warn() {}, error() {} } });+ const steps: RepairPlanStep[] = [];+ for (const spec of REPAIR_REGISTRY) {+ if (opts.kinds && !opts.kinds.includes(spec.kind)) continue;+ const preview = await runner.run(spec.kind, scope);+ // contextual-mode stamps only sealed pages; pages the safe-chunks step re-seals become eligible during the run.+ const unlocked = spec.kind === 'contextual-mode' && steps.some(step => step.kind === 'safe-chunks') ? Number(preview.residuals.unsealed_projection ?? 0) : 0;+ if (!preview.affected && !unlocked) continue;+ const paid = repairMaySpend(spec, opts.noEmbed) && runner.embeddingModel !== undefined;+ steps.push({ step: steps.length + 1, id: `repair:${spec.kind}`, kind: spec.kind, affected: preview.affected + unlocked,+ command: repairApplyCommand(spec.kind, { noEmbed: opts.noEmbed }), requires_user_agreement: true, protected: true, paid, embeds: spec.embeds,+ est_usd_cost: paid ? preview.cost.embedding_usd : 0, lifetime_ids: preview.cost.lifetime_ids, checks: spec.checks,+ rationale: `${preview.affected} item(s) pending for gbrain repair ${spec.kind}${unlocked ? `, plus up to ${unlocked} after safe-chunks re-seals them` : ''}` });+ }+ return steps;+}++/**+ * Apply repair steps in order. `remainingUsd()` is the budget still available+ * (undefined = no cap); a paid step whose estimate exceeds it (or cannot be+ * estimated under a cap) is refused before it starts and the run continues+ * with the next step. Only a trusted local caller may run repairs.+ */+export async function runRepairSteps(engine: BrainEngine, steps: RepairPlanStep[], opts: {+ remote: boolean; noEmbed?: boolean; remainingUsd: () => number | undefined;+ /** Reserve spend the consumer will make after publication (effect kinds). */+ charge?: (usd: number) => void;+ /** True once the run's budget tracker fired, even if a callee swallowed the throw. */+ exhausted?: () => boolean;+ /** Runs one in-process paid step under a tracker capped at what is left after reservations. */+ stepBudget?: <T>(run: () => Promise<T>) => Promise<T>;+ onStep?: (step: RepairPlanStep, result: RepairStepResult) => void;+}): Promise<RepairStepResult[]> {+ if (opts.remote !== false) throw new OperationError('permission_denied', 'Repair steps are PROTECTED: only a trusted local caller on the brain host can run them.',+ 'On the brain host, run: gbrain doctor --remediation-plan');+ const { BudgetExhausted } = await import('../budget/budget-tracker.ts');+ const scope = await resolveRepairScope(engine);+ const runner = await repairRunner(engine, { apply: true, noEmbed: opts.noEmbed });+ const results: RepairStepResult[] = [];+ for (const step of steps) {+ const base = { id: step.id, kind: step.kind, applied: 0, skipped: 0 };+ let result: RepairStepResult;+ const remaining = opts.remainingUsd();+ if (step.paid && remaining !== undefined && (step.est_usd_cost === null || step.est_usd_cost > remaining)) {+ result = { ...base, status: 'budget_refused', message: step.est_usd_cost === null+ ? `Not started: its embedding cost cannot be estimated and a --max-usd cap is set ($${remaining.toFixed(2)} remaining).`+ : `Not started: estimated $${step.est_usd_cost.toFixed(4)} exceeds the $${remaining.toFixed(4)} remaining under --max-usd.` };+ } else if (step.paid && opts.exhausted?.()) {+ result = { ...base, status: 'budget_refused', message: 'Not started: the --max-usd budget ran out earlier in this run.' };+ } else {+ if (step.paid && step.embeds === 'effect' && step.est_usd_cost) opts.charge?.(step.est_usd_cost);+ try {+ const applied = step.paid && step.embeds === 'inline' && opts.stepBudget+ ? await opts.stepBudget(() => runner.run(step.kind, scope)) : await runner.run(step.kind, scope);+ result = { ...base, applied: applied.applied, skipped: applied.skipped,+ status: applied.stopped ? 'stopped' : applied.complete ? 'completed' : 'stopped',+ ...(applied.stopped ? { message: applied.stopped.message } : {}) };+ // A callee (for example the stale-embedding pass) may swallow BudgetExhausted; the tracker still knows.+ if (step.paid && step.embeds === 'inline' && opts.exhausted?.()) result = { ...result, status: 'budget_exhausted',+ message: 'The --max-usd budget ran out during the step; re-sealed pages keep their text, and the rest of their embeddings resume with the printed resume command or gbrain embed --stale.' };+ } catch (error) {+ if (error instanceof BudgetExhausted) result = { ...base, status: 'budget_exhausted', message: `Budget exhausted during the step: ${error.message}` };+ else result = { ...base, status: 'failed', message: error instanceof Error ? error.message.slice(0, 300) : String(error) };+ }+ }+ results.push(result);+ opts.onStep?.(step, result);+ }+ return results;+}diff --git a/src/core/remediation/run.ts b/src/core/remediation/run.tsindex af99b737d5..5624178b96 100644--- a/src/core/remediation/run.ts+++ b/src/core/remediation/run.ts@@ -18,6 +18,9 @@ import {import type { RemediationStep } from '../remediation-step.ts';import { loadRecommendationContext } from './context.ts';import { computeRemediationPlan } from './plan.ts';+import { planRepairSteps, runRepairSteps, type RepairPlanStep, type RepairStepResult } from './repairs.ts';+import { OperationError } from '../ops/contract.ts';+import type { RemediationCheckpoint } from '../remediation-checkpoint.ts';import type {RemediationHooks,RemediationOpts,@@ -44,10 +47,14 @@ export async function runRemediation(): Promise<RemediationResult> {const targetScore = opts.targetScore ?? 90;const maxJobs = opts.maxJobs ?? Infinity;- const maxUsd = opts.maxUsd;const dryRun = opts.dryRun ?? false;const resumeMode = opts.resume ?? false;const resumePlanHash = opts.resumePlanHash;+ const repairs = opts.repairs;+ if (repairs?.include && repairs.remote !== false) {+ throw new OperationError('permission_denied', 'Repair steps are PROTECTED: only a trusted local caller on the brain host can include them.',+ 'On the brain host, run: gbrain doctor --remediation-plan');+ }// Lazy-load orchestration deps so the library entry-point doesn't pay// their cost on a --dry-run shortcut path (or when callers only need@@ -67,97 +74,107 @@ export async function runRemediation(const ctx = await loadRecommendationContext(engine);const extraRemediations = opts.extraRemediations ?? [];+ const brainId = repairs ? (await (await import('../repair/core.ts')).resolveRepairScope(engine)).brain_id : undefined;+ const synthetic = (score: number, extra: Partial<RemediationResult> = {}): RemediationResult => ({+ doctor_run_id: crypto.randomUUID(), brain_score_initial: score, brain_score_final: score, brain_score_target: targetScore,+ target_reached: false, submitted: [], aborted_count: 0, ...extra,+ });++ // Resume loads its checkpoint first: a checkpoint that records a manifest+ // binds the run to its brain, cap, consent and original steps.+ let cp: RemediationCheckpoint | null = null;+ if (resumeMode) {+ cp = resumePlanHash ? loadRemediationCheckpoint(resumePlanHash) : null;+ if (!cp && !resumePlanHash) {+ for (const e of listRemediationCheckpoints()) {+ const candidate = loadRemediationCheckpoint(e.plan_hash);+ if (candidate?.manifest && brainId && candidate.brain_id === brainId) { cp = candidate; break; }+ }+ }+ if (cp?.manifest && brainId && cp.brain_id !== brainId) {+ hooks.onResumeBrainMismatch?.(cp.plan_hash, cp.brain_id ?? 'unknown', brainId);+ const health = await engine.getHealth();+ return synthetic(health.brain_score, { resume_refused: { reason: 'brain_mismatch', checkpoint_brain_id: cp.brain_id ?? 'unknown', brain_id: brainId, plan_hash: cp.plan_hash } });+ }+ }+ const manifest = cp?.manifest;+ // The cap is cumulative: a resume without --max-usd reuses the recorded cap,+ // and spend already settled by the original run and earlier resumes counts.+ const maxUsd = opts.maxUsd ?? (manifest ? cp?.max_usd ?? undefined : undefined);+ const spentBefore = manifest ? cp?.spent_usd ?? 0 : 0;+ if (manifest) hooks.onResumeCap?.(maxUsd ?? null, spentBefore);+ const includeRepairs = repairs !== undefined && (repairs.include || (manifest !== undefined && cp?.include_repairs === true));- // Pre-flight ceiling check via the shared plan computation.+ // Pre-flight ceiling check via the shared plan computation. The score target+ // governs job steps only; repair steps are planned independently of it.const initialPlan = await computeRemediationPlan(engine, { targetScore, extraRemediations });- if (initialPlan.target_unreachable) {+ let repairSteps: RepairPlanStep[] = repairs+ ? await planRepairSteps(engine, { noEmbed: repairs.noEmbed, kinds: manifest ? manifest.repair_kinds as RepairPlanStep['kind'][] : undefined })+ : [];+ // Embeddings a budget stop left behind after re-sealing; the re-sealed pages no longer show up in a repair plan.+ let pendingEmbedSources = includeRepairs && manifest ? [...(cp?.pending_embed_sources ?? [])] : [];+ if (initialPlan.target_unreachable && !(includeRepairs && (repairSteps.length || pendingEmbedSources.length))) {hooks.onTargetUnreachable?.(targetScore, initialPlan.max_reachable_score);- return {- doctor_run_id: crypto.randomUUID(),- brain_score_initial: initialPlan.brain_score_current,- brain_score_final: initialPlan.brain_score_current,- brain_score_target: targetScore,- target_reached: false,- submitted: [],- aborted_count: 0,- target_unreachable: {- target: targetScore,- ceiling: initialPlan.max_reachable_score,- },- };+ return synthetic(initialPlan.brain_score_current, {+ target_unreachable: { target: targetScore, ceiling: initialPlan.max_reachable_score },+ ...(repairs && repairSteps.length ? { repairs: [], repairs_skipped: repairSteps } : {}),+ });}+ const jobStepsSkipped = initialPlan.target_unreachable+ ? { reason: 'target_unreachable' as const, target: targetScore, ceiling: initialPlan.max_reachable_score } : undefined;+ if (jobStepsSkipped) hooks.onTargetUnreachable?.(targetScore, initialPlan.max_reachable_score);const initialHealth = await engine.getHealth();- let recs: RemediationStep[] = computeRecommendations(initialHealth, ctx, extraRemediations)- .filter((r) => r.status === 'remediable');- if (recs.length === 0) {+ let recs: RemediationStep[] = jobStepsSkipped ? [] : computeRecommendations(initialHealth, ctx, extraRemediations)+ .filter((r) => r.status === 'remediable' && (!manifest || manifest.job_ids.includes(r.id)));+ const skippedRepairs = includeRepairs ? [] : repairSteps;+ if (!includeRepairs) repairSteps = [];+ if (recs.length === 0 && repairSteps.length === 0 && pendingEmbedSources.length === 0) {hooks.onNothingToDo?.(initialHealth.brain_score, targetScore);return {- doctor_run_id: crypto.randomUUID(),- brain_score_initial: initialHealth.brain_score,- brain_score_final: initialHealth.brain_score,- brain_score_target: targetScore,+ ...synthetic(initialHealth.brain_score),target_reached: initialHealth.brain_score >= targetScore,- submitted: [],- aborted_count: 0,+ ...(jobStepsSkipped ? { job_steps_skipped: jobStepsSkipped } : {}),+ ...(repairs ? { repairs: [], repairs_skipped: skippedRepairs } : {}),};}- // A4 amended: compute plan_hash off the active recommendation ids so- // the checkpoint binds to THIS plan. Resume only fires for matching plans.- const planHash = computePlanHash(recs.map((r) => r.id));+ // A4 amended: compute plan_hash off the active step ids so the checkpoint+ // binds to THIS plan. A checkpoint with a manifest keeps its original hash.+ // The brain id is part of the hash so two brains on one host never share a checkpoint file.+ const planHash = cp?.manifest ? cp.plan_hash : computePlanHash([...recs.map((r) => r.id), ...repairSteps.map((r) => r.id), ...(brainId ? [`brain:${brainId}`] : [])]);+ const originalManifest = manifest ?? { job_ids: recs.map((r) => r.id), repair_kinds: repairSteps.map((r) => r.kind) };let completedFromCheckpoint = new Set<string>();if (resumeMode) {- const requested = resumePlanHash;- let cp = requested ? loadRemediationCheckpoint(requested) : null;- if (!cp && !requested) {- // No explicit hash: try newest checkpoint that matches the active plan.- const recent = listRemediationCheckpoints();- for (const e of recent) {+ if (!cp && !resumePlanHash) {+ // Legacy checkpoints (no manifest) resume only the identical job plan.+ for (const e of listRemediationCheckpoints()) {const candidate = loadRemediationCheckpoint(e.plan_hash);- if (candidate && candidate.plan_hash === planHash) {- cp = candidate;- break;- }+ if (candidate && !candidate.manifest && candidate.plan_hash === planHash) { cp = candidate; break; }}}- if (!cp || cp.plan_hash !== planHash) {- hooks.onResumeMissed?.(planHash, requested);+ if (!cp || (!cp.manifest && cp.plan_hash !== planHash)) {+ hooks.onResumeMissed?.(planHash, resumePlanHash);// Surface as a synthetic result so the CLI shell can exit 2.- return {- doctor_run_id: crypto.randomUUID(),- brain_score_initial: initialHealth.brain_score,- brain_score_final: initialHealth.brain_score,- brain_score_target: targetScore,- target_reached: false,- submitted: [],- aborted_count: 0,- target_unreachable: {- target: targetScore,- ceiling: initialPlan.max_reachable_score,- },- };+ return synthetic(initialHealth.brain_score, { target_unreachable: { target: targetScore, ceiling: initialPlan.max_reachable_score } });}completedFromCheckpoint = new Set(cp.completed.map((c) => c.id));+ repairSteps = repairSteps.filter((step) => !completedFromCheckpoint.has(step.id));hooks.onResumeLoaded?.(planHash,completedFromCheckpoint.size,- recs.length - completedFromCheckpoint.size,+ recs.filter((r) => !completedFromCheckpoint.has(r.id)).length + repairSteps.length,);}- const estTotalUsd = recs.reduce((sum, r) => sum + (r.est_usd_cost ?? 0), 0);- if (maxUsd !== undefined && estTotalUsd > maxUsd) {- hooks.onBudgetRefused?.(estTotalUsd, maxUsd);- return {- doctor_run_id: crypto.randomUUID(),- brain_score_initial: initialHealth.brain_score,- brain_score_final: initialHealth.brain_score,- brain_score_target: targetScore,- target_reached: false,- submitted: [],- aborted_count: 0,- };+ const remainingCap = maxUsd === undefined ? undefined : Math.max(0, maxUsd - spentBefore);+ const estJobUsd = recs.reduce((sum, r) => sum + (r.est_usd_cost ?? 0), 0);+ let jobsBudgetRefused = false;+ if (remainingCap !== undefined && estJobUsd > remainingCap) {+ hooks.onBudgetRefused?.(estJobUsd, remainingCap);+ if (repairSteps.length === 0) return synthetic(initialHealth.brain_score, repairs ? { repairs: [], repairs_skipped: skippedRepairs } : {});+ jobsBudgetRefused = true;+ recs = [];}if (dryRun) {@@ -165,18 +182,9 @@ export async function runRemediation(// Each rec lands in submitted[] with synthetic 'dry_run' status so the// shape stays consistent.return {- doctor_run_id: crypto.randomUUID(),- brain_score_initial: initialHealth.brain_score,- brain_score_final: initialHealth.brain_score,- brain_score_target: targetScore,- target_reached: false,- submitted: recs.map((r, i) => ({- step: i + 1,- id: r.id,- job_id: null,- status: 'dry_run',- })),- aborted_count: 0,+ ...synthetic(initialHealth.brain_score),+ submitted: [...repairSteps.map((r) => r.id), ...recs.map((r) => r.id)].map((id, i) => ({ step: i + 1, id, job_id: null, status: 'dry_run' })),+ ...(repairs ? { repairs: [], repairs_skipped: skippedRepairs } : {}),};}@@ -185,6 +193,7 @@ export async function runRemediation(const abortedIds = new Set<string>();const attemptedIds = new Set<string>();const doctorRunId = crypto.randomUUID();+ const repairResults: RepairStepResult[] = [];const { MinionQueue } = await import('../minions/queue.ts');const { waitForCompletion } = await import('../minions/wait-for-completion.ts');@@ -193,33 +202,95 @@ export async function runRemediation(// A4 amended: install a BudgetTracker scope around the plan-step loop so// any gateway.chat / embed / rerank inside a Minion handler (synthesize,- // patterns, consolidate) auto-enforces the cap. On BudgetExhausted, the- // onExhausted callback persists the checkpoint BEFORE the throw propagates;- // the caller hook surfaces the actionable --resume hint.- const remediateTracker = new BudgetTracker({- label: 'remediation.run',- maxCostUsd: maxUsd,- });+ // patterns, consolidate) or a repair step auto-enforces the cap. On+ // BudgetExhausted, the onExhausted callback persists the checkpoint BEFORE+ // the throw propagates; the caller hook surfaces the actionable --resume hint.+ // Repairs run first under their own tracker; job steps then get a tracker capped at what the repairs left,+ // so in-process spend, reserved effect estimates and job spend all draw on one cumulative cap.+ const repairTracker = new BudgetTracker({ label: 'remediation.repairs', maxCostUsd: remainingCap });+ let jobTracker: InstanceType<typeof BudgetTracker> | undefined;+ // Effect kinds embed in the persistence consumer, outside any tracker, so their estimate is reserved up front.+ let reservedUsd = 0;+ let trackerExhausted = false;+ const stepTrackers: Array<InstanceType<typeof BudgetTracker>> = [];+ const spentThisRun = () => repairTracker.totalSpent + reservedUsd + (jobTracker?.totalSpent ?? 0)+ + stepTrackers.reduce((sum, tracker) => sum + tracker.totalSpent, 0);+ const settledUsd = () => spentBefore + spentThisRun();+ const remainingUsd = () => remainingCap === undefined ? undefined : Math.max(0, remainingCap - spentThisRun());let exhaustionSnapshot: NonNullable<RemediationResult['budget_exhausted']> | undefined;- remediateTracker.onExhausted(() => {- const cp = {+ const saveCheckpoint = () => {+ const completed = [+ ...[...completedFromCheckpoint].map((id) => ({ id, job: '', status: 'completed' })),+ ...submitted.filter((s) => s.status === 'completed' && !completedFromCheckpoint.has(s.id))+ .map((s) => ({ id: s.id, job: '', status: s.status, job_id: s.job_id ?? null })),+ ...repairResults.filter((r) => r.status === 'completed').map((r) => ({ id: r.id, job: 'repair', status: r.status })),+ ];+ saveRemediationCheckpoint({schema_version: 1 as const,plan_hash: planHash,doctor_run_id: doctorRunId,target_score: targetScore,started_at: new Date().toISOString(),- completed: submitted- .filter((s) => s.status === 'completed')- .map((s) => ({ id: s.id, job: '', status: s.status, job_id: s.job_id ?? null })),+ completed,aborted_at: new Date().toISOString(),abort_reason: 'budget_exhausted' as const,budget_snapshot: exhaustionSnapshot? { spent: exhaustionSnapshot.spent, cap: exhaustionSnapshot.cap, reason: exhaustionSnapshot.reason, model_id: exhaustionSnapshot.model_id }: undefined,- };- saveRemediationCheckpoint(cp);- });+ ...(repairs ? {+ brain_id: brainId, max_usd: maxUsd ?? null, include_repairs: includeRepairs,+ spent_usd: settledUsd(), manifest: originalManifest,+ ...(pendingEmbedSources.length ? { pending_embed_sources: pendingEmbedSources } : {}),+ } : {}),+ });+ };+ const watch = (tracker: InstanceType<typeof BudgetTracker>) => {+ tracker.onExhausted(() => { trackerExhausted = true; });+ tracker.onExhausted(saveCheckpoint);+ };+ watch(repairTracker);++ const runRepairs = async (): Promise<void> => {+ if (!repairs) return;+ if (pendingEmbedSources.length) {+ const { embedStaleForSource } = await import('../embed-stale.ts');+ let status: RepairStepResult['status'] = 'completed';+ let embedded = 0;+ if (remainingUsd() === 0) status = 'budget_refused';+ for (const sourceId of status === 'completed' ? [...pendingEmbedSources] : []) {+ if (trackerExhausted) break;+ let result: Awaited<ReturnType<typeof embedStaleForSource>> | undefined;+ try { result = await embedStaleForSource(engine, sourceId); } catch (error) { if (!(error instanceof BudgetExhausted)) throw error; }+ embedded += result?.embedded ?? 0;+ // A source is done only when the pass finished without leaving chunks behind.+ if (!trackerExhausted && result && !result.failures && result.complete !== false && !result.remaining) {+ pendingEmbedSources = pendingEmbedSources.filter((id) => id !== sourceId);+ }+ }+ if (trackerExhausted) status = 'budget_exhausted';+ else if (status === 'completed' && pendingEmbedSources.length) status = 'stopped';+ repairResults.push({ id: 'repair:safe-chunks:embeddings', kind: 'safe-chunks', status, applied: embedded, skipped: 0,+ ...(status === 'budget_exhausted' || status === 'budget_refused' ? { message: 'The --max-usd budget does not cover the embeddings of re-sealed pages; resume with a higher cap to continue.' }+ : status === 'stopped' ? { message: `Some re-sealed pages still lack embeddings (${pendingEmbedSources.join(', ')}); check the embedding provider, then run gbrain embed --stale.` } : {}) });+ }+ if (repairSteps.length === 0) return;+ for (const step of repairSteps) hooks.onRepairStepStart?.(step);+ const results = await runRepairSteps(engine, repairSteps, { remote: repairs.remote, noEmbed: repairs.noEmbed, remainingUsd,+ charge: (usd) => { reservedUsd += usd; }, exhausted: () => trackerExhausted,+ stepBudget: async (run) => {+ const tracker = new BudgetTracker({ label: 'remediation.repair-step', maxCostUsd: remainingUsd() });+ stepTrackers.push(tracker);+ watch(tracker);+ return withBudgetTracker(tracker, run);+ },+ onStep: (step, result) => hooks.onRepairStepEnd?.(step, result) });+ repairResults.push(...results);+ // A re-seal whose embeddings the budget cut short resumes as an embedding pass over the same sources.+ if (results.some((r) => r.kind === 'safe-chunks' && r.status === 'budget_exhausted')) {+ pendingEmbedSources = [...new Set([...pendingEmbedSources, ...(await (await import('../repair/core.ts')).resolveRepairScope(engine)).source_ids])];+ }+ };const runLoop = async (): Promise<void> => {let stepCount = 0;@@ -333,27 +404,51 @@ export async function runRemediation(// would resubmit completed extras every iteration, forever.const pendingExtras = extraRemediations.filter((r) => !attemptedIds.has(r.id));recs = computeRecommendations(freshHealth, ctx, pendingExtras)- .filter((r) => r.status === 'remediable' && !attemptedIds.has(r.id));+ .filter((r) => r.status === 'remediable' && !attemptedIds.has(r.id) && (!manifest || manifest.job_ids.includes(r.id)));}};let budgetAbort: NonNullable<RemediationResult['budget_exhausted']> | undefined;try {- await withBudgetTracker(remediateTracker, runLoop);+ try { await withBudgetTracker(repairTracker, runRepairs); }+ catch (err) { if (!(err instanceof BudgetExhausted)) throw err; }+ // Job estimates are rechecked against what the repairs left, including reserved effect estimates.+ const afterRepairs = remainingUsd();+ if (recs.length && afterRepairs !== undefined && (trackerExhausted || estJobUsd > afterRepairs)) {+ hooks.onBudgetRefused?.(estJobUsd, afterRepairs);+ jobsBudgetRefused = true;+ recs = [];+ }+ jobTracker = new BudgetTracker({ label: 'remediation.run', maxCostUsd: afterRepairs });+ watch(jobTracker);+ await withBudgetTracker(jobTracker, runLoop);} catch (err) {if (err instanceof BudgetExhausted) {budgetAbort = exhaustionSnapshot;- if (budgetAbort) hooks.onBudgetExhausted?.(planHash, budgetAbort);} else {throw err;}}+ // Tracker snapshots are per phase; report the operator's cumulative cap and settled spend.+ if (budgetAbort) budgetAbort = { ...budgetAbort, spent: settledUsd(), cap: maxUsd ?? budgetAbort.cap };+ // A paid repair step the cap refused (or that ran out mid-step) ends the+ // run as budget-exhausted even though the free steps completed.+ const refusedRepair = repairResults.find((r) => r.status === 'budget_refused' || r.status === 'budget_exhausted');+ if (!budgetAbort && (refusedRepair || jobsBudgetRefused)) {+ budgetAbort = { spent: settledUsd(), cap: maxUsd ?? 0, reason: 'max_usd', plan_hash: planHash };+ exhaustionSnapshot = budgetAbort;+ saveCheckpoint();+ }+ if (budgetAbort) hooks.onBudgetExhausted?.(planHash, budgetAbort);// Clear checkpoint on a clean run (no budget abort). Failed steps in the// submitted set don't disqualify cleanup; an uncleared health signal can// produce the same stable id again in a later run.- if (!budgetAbort) {+ if (!budgetAbort && pendingEmbedSources.length === 0) {clearRemediationCheckpoint(planHash);+ } else if (!budgetAbort) {+ // Re-sealed pages whose embeddings did not land stay resumable.+ saveCheckpoint();}const finalHealth = await engine.getHealth();@@ -366,5 +461,10 @@ export async function runRemediation(submitted,aborted_count: abortedIds.size,budget_exhausted: budgetAbort,+ ...(jobStepsSkipped ? { job_steps_skipped: jobStepsSkipped } : {}),+ ...(repairs ? {+ repairs: repairResults, repairs_skipped: skippedRepairs,+ budget: { max_usd: maxUsd ?? null, spent_usd: settledUsd(), include_repairs: includeRepairs, plan_hash: planHash },+ } : {}),};}diff --git a/src/core/remediation/types.ts b/src/core/remediation/types.tsindex 5c8bc5fbd4..b6f986c1ab 100644--- a/src/core/remediation/types.ts+++ b/src/core/remediation/types.ts@@ -9,6 +9,7 @@// - src/core/operations.ts (MCP op run_onboard, admin scope)import type { RemediationStep } from '../remediation-step.ts';+import type { RepairPlanStep, RepairStepResult } from './repairs.ts';/*** Options for computeRemediationPlan. All fields are optional with@@ -26,6 +27,12 @@ export interface RemediationPlanOpts {* behavior).*/extraRemediations?: RemediationStep[];+ /**+ * Doctor CLI only: preview every registered `gbrain repair` kind and list+ * the ones with pending items as PROTECTED repair steps, independent of the+ * score target. Omitted by onboard and MCP callers.+ */+ repairs?: { noEmbed?: boolean };}/**@@ -42,6 +49,8 @@ export interface RemediationPlan {est_total_seconds: number;est_total_usd_cost: number;blocked: Array<{ check: string; reason: string }>;+ /** Present when `repairs` was requested: PROTECTED steps that need `--include-repairs`. */+ repair_steps?: RepairPlanStep[];}/**@@ -73,6 +82,13 @@ export interface RemediationOpts {* only applicable work was an extra (e.g. extract-ner).*/extraRemediations?: RemediationStep[];+ /**+ * Doctor CLI only. Plans the registered repair kinds as PROTECTED steps and+ * runs them when `include` is true (the user's `--include-repairs`+ * agreement) and the caller is trusted local (`remote === false`). A+ * remote caller asking to include repairs is refused.+ */+ repairs?: { include: boolean; remote: boolean; noEmbed?: boolean };}/**@@ -118,6 +134,16 @@ export interface RemediationResult {target: number;ceiling: number;};+ /** Set when job steps were skipped for an unreachable target while repair steps still ran. */+ job_steps_skipped?: { reason: 'target_unreachable'; target: number; ceiling: number };+ /** Set when `--resume` refused (a checkpoint for another brain). */+ resume_refused?: { reason: string; checkpoint_brain_id: string; brain_id: string; plan_hash: string };+ /** Repair steps the run applied or refused (only when `repairs` was passed). */+ repairs?: RepairStepResult[];+ /** Repair steps planned but not run because the user's agreement was missing. */+ repairs_skipped?: RepairPlanStep[];+ /** Cumulative cap and settled spend across the original run and its resumes. */+ budget?: { max_usd: number | null; spent_usd: number; include_repairs: boolean; plan_hash: string };}/**@@ -141,4 +167,11 @@ export interface RemediationHooks {onResumeLoaded?: (planHash: string, completedCount: number, remainingCount: number) => void;/** Fired on resume-checkpoint miss (resume mode only). */onResumeMissed?: (planHash: string, requested?: string) => void;+ /** Fired when the resume checkpoint belongs to another brain. */+ onResumeBrainMismatch?: (planHash: string, checkpointBrain: string, brain: string) => void;+ /** Fired with the cap a resume reuses from its checkpoint. */+ onResumeCap?: (cap: number | null, spent: number) => void;+ /** Fired before and after each repair step. */+ onRepairStepStart?: (step: RepairPlanStep) => void;+ onRepairStepEnd?: (step: RepairPlanStep, result: RepairStepResult) => void;}diff --git a/src/core/repair/connector-checkpoints.ts b/src/core/repair/connector-checkpoints.tsnew file mode 100644index 0000000000..763b34026f--- /dev/null+++ b/src/core/repair/connector-checkpoints.ts@@ -0,0 +1,31 @@+/**+ * `gbrain repair connector-checkpoints` (#5686): delete connector checkpoint+ * rows and retry pointers that no registered connector source can load and+ * that are older than 7 days. Cleanup only; the upgrade migration's re-key+ * copy never runs here. Rows referenced by a non-terminal request or a+ * recorded pending set are kept. No journal admission: these rows are+ * connector bookkeeping, not canonical pages.+ */+import { deleteOrphanConnectorCheckpoints, orphanConnectorCheckpoints, type OrphanCheckpointRow } from '../persistence/connector-checkpoint-migration.ts';+import type { RepairHandler, RepairItem } from './core.ts';++export const ORPHAN_CHECKPOINT_MIN_AGE_DAYS = 7;++export const connectorCheckpointsRepair: RepairHandler = {+ kind: 'connector-checkpoints',+ publication: 'projection',+ embeds: false,+ // Deletion is idempotent, so every run plans the orphans that remain (the cursor never skips any).+ async plan(engine) {+ const rows = await orphanConnectorCheckpoints(engine, { minAgeDays: ORPHAN_CHECKPOINT_MIN_AGE_DAYS });+ const items: RepairItem[] = rows.map((row, index) => ({ cursor: { phase: row.op === 'managed-connector' ? 0 : 1, id: index + 1 },+ source_id: '(brain)', slug: `${row.op}:${row.fingerprint.slice(0, 12)}`, chars: 0, action: 'delete_orphan',+ change: { from: JSON.stringify(row), to: 'deleted' } }));+ return { items, residuals: {} };+ },+ async apply(ctx, item) {+ const row = JSON.parse(item.change!.from!) as OrphanCheckpointRow;+ const removed = await deleteOrphanConnectorCheckpoints(ctx.engine, [row], { minAgeDays: ORPHAN_CHECKPOINT_MIN_AGE_DAYS });+ return removed.checkpoints + removed.retries > 0;+ },+};diff --git a/src/core/repair/contextual-mode.ts b/src/core/repair/contextual-mode.tsnew file mode 100644index 0000000000..17f8477d9f--- /dev/null+++ b/src/core/repair/contextual-mode.ts@@ -0,0 +1,70 @@+/**+ * `gbrain repair contextual-mode` (#5621): stamp `contextual_retrieval_mode`+ * and `corpus_generation` on live markdown pages imported before every import+ * recorded them (`--no-embed` imports left them NULL, so every later embed+ * pass embedded those pages raw, forever). Each page gets exactly the+ * convention a fresh import would record (`resolveImportContextualMode`).+ *+ * Projection-only, like `safe-chunks`: no page write, version, journal+ * admission or lifetime ID. Under the page guard the stamp is written and a+ * stored vector is kept only when its recorded embedding input is still one+ * the stamped convention accepts (the #5553 rule): a page whose embedding+ * input is unchanged by the stamp queues no re-embed, and a page whose input+ * changes has only those vectors cleared and is re-embedded once, unless+ * --no-embed is passed (then `gbrain embed --stale` does it). `embed_skip`+ * pages are left alone and counted.+ */+import type { BrainEngine } from '../engine.ts';+import { quoteIdentifier } from '../search/embedding-column.ts';+import { acceptedEmbeddingInputHashes, isContextualMode } from '../embedding-input-hash.ts';+import { embeddingInputContext, embeddingWriteTarget } from '../page-state/projections.ts';+import { resolveImportContextualMode } from '../import-contextual-mode.ts';+import { embedStalePages } from '../embed-stale.ts';+import { afterCursor, type RepairCursor, type RepairHandler, type RepairItem, type RepairScope } from './core.ts';++export const contextualModeRepair: RepairHandler = {+ kind: 'contextual-mode',+ publication: 'projection',+ async plan(engine: BrainEngine, scope: RepairScope, after: RepairCursor | null) {+ const rows = await engine.executeRaw<{ id: number; source_id: string; slug: string; chars: number; sealed: boolean; embed_skip: boolean }>(`SELECT p.id,p.source_id,p.slug,+ (p.text_projection_revision = p.knowledge_revision) AS sealed, (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AS embed_skip,+ COALESCE((SELECT sum(length(c.chunk_text)) FROM content_chunks c WHERE c.page_id=p.id), 0)::int AS chars+ FROM pages p WHERE p.source_id=ANY($1::text[]) AND p.deleted_at IS NULL AND p.page_kind='markdown'+ AND p.contextual_retrieval_mode IS NULL ORDER BY p.id`, [scope.source_ids]);+ const items: RepairItem[] = rows.filter(row => row.sealed && !row.embed_skip)+ .map(row => ({ cursor: { phase: 0, id: Number(row.id) }, source_id: row.source_id, slug: row.slug, chars: Number(row.chars),+ action: 'stamp contextual retrieval mode' }))+ .filter(item => afterCursor(item.cursor, after));+ // embed_skip pages keep their retained vectors and are never sent to a provider (#4306).+ return { items, residuals: { unsealed_projection: rows.filter(row => !row.sealed && !row.embed_skip).length, embed_skip: rows.filter(row => row.embed_skip).length } };+ },+ async apply(ctx, item, opts) {+ const cleared = await ctx.engine.transaction(async tx => {+ await tx.lockPageKeys([{ sourceId: item.source_id, slug: item.slug }]);+ const snapshot = await tx.readPageSnapshot(item.slug, { sourceId: item.source_id, requireLiveSource: true });+ if (!snapshot || snapshot.page.contextual_retrieval_mode != null || snapshot.page.text_projection_revision !== snapshot.revision+ || Object.hasOwn(snapshot.page.frontmatter ?? {}, 'embed_skip')) return null;+ const { mode, corpusGeneration } = await resolveImportContextualMode(tx, item.source_id, snapshot.page.frontmatter, true);+ await tx.updatePageContextualRetrievalState(item.slug, item.source_id, mode, corpusGeneration);+ const target = await embeddingWriteTarget(tx);+ const chunks = await tx.getChunks(item.slug, { sourceId: item.source_id, includeUnsealed: true });+ const provenance = embeddingInputContext(target, snapshot.page.title, corpusGeneration, chunks);+ const recorded = new Map((await tx.executeRaw<{ id: number; embedding_input_hash: string | null }>(+ 'SELECT id,embedding_input_hash FROM content_chunks WHERE page_id=$1', [snapshot.page.id])).map(r => [Number(r.id), r.embedding_input_hash]));+ const stale = chunks.filter(chunk => !chunk.embedding_is_null).filter(chunk => {+ const hash = recorded.get(Number(chunk.id)) ?? null;+ return hash === null ? isContextualMode(mode) : !acceptedEmbeddingInputHashes(provenance, mode, chunk).includes(hash);+ }).map(chunk => Number(chunk.id));+ if (stale.length) await tx.executeRaw(`UPDATE content_chunks SET ${quoteIdentifier(target.column.name)}=NULL,+ embedded_at=NULL,embedded_text_hash=NULL,embedding_input_hash=NULL WHERE page_id=$1 AND id=ANY($2::int[])`, [snapshot.page.id, stale]);+ return stale.length;+ });+ if (cleared === null) return false;+ if (cleared > 0 && opts?.embed) {+ const embedded = await embedStalePages(ctx.engine, [item.slug], item.source_id);+ if (embedded.pagesProcessed === 0) ctx.logger.warn(`[repair contextual-mode] ${item.source_id}:${item.slug} stamped, but its re-embed did not finish. `+ + `Run: gbrain embed --stale --source ${item.source_id}`);+ }+ return true;+ },+};diff --git a/src/core/repair/core.ts b/src/core/repair/core.tsindex af1b826355..9d46c505b5 100644--- a/src/core/repair/core.ts+++ b/src/core/repair/core.ts@@ -5,7 +5,7 @@* 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+ * rebuilds derived projections (`safe-chunks`, `contextual-mode`) 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@@ -22,7 +22,7 @@ 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 const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints'] as const;export type RepairKind = typeof REPAIR_KINDS[number];export interface RepairScope { brain_id: string; source_ids: string[] }@@ -46,6 +46,8 @@ export interface RepairHandler {kind: RepairKind;/** `projection`: items rebuild derived rows only and take no journal admission. Default `coordinated`. */publication?: 'coordinated' | 'projection';+ /** False for kinds whose items are bookkeeping rows, not pages: no embedding cost. */+ embeds?: boolean;/** 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. */@@ -156,7 +158,7 @@ export async function runRepair(ctx: OperationContext, handler: RepairHandler, sconst 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,+ cost: { lifetime_ids: admits, receipt_bytes: admits * RECEIPT_BYTES, embedding_pages: handler.embeds === false ? 0 : 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,diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.tsnew file mode 100644index 0000000000..c40ce48ff8--- /dev/null+++ b/src/core/repair/registry.ts@@ -0,0 +1,102 @@+/**+ * The `gbrain repair` kind registry: one entry per kind in `REPAIR_KINDS`+ * order (the `--all` dependency order). Everything that lists, previews or+ * runs repairs reads this table — the `gbrain repair` command, the doctor+ * remediation plan and run, and the post-upgrade banner — so a new kind plugs+ * in by adding its name to `REPAIR_KINDS` and one entry here.+ *+ * `checks` names the doctor checks whose findings this kind clears; the+ * remediation run uses it to classify those findings. `embeds` says how a kind+ * can spend on embeddings when a model is configured: `effect` kinds publish a+ * page write whose embedding effect the persistence consumer runs (outside+ * this process, not affected by `--no-embed`); `inline` kinds embed in this+ * process unless `--no-embed` is given.+ */+import type { BrainEngine } from '../engine.ts';+import type { OperationContext } from '../ops/contract.ts';+import { loadConfig } from '../config.ts';+import { REPAIR_KINDS, runRepair, type RepairHandler, type RepairKind, type RepairResult, type RepairScope } from './core.ts';+import { timelineRepair } from './timeline.ts';+import { visibilityRepair } from './visibility.ts';+import { safeChunksRepair } from './safe-chunks.ts';+import { contextualModeRepair } from './contextual-mode.ts';+import { connectorCheckpointsRepair } from './connector-checkpoints.ts';++export interface RepairKindSpec {+ kind: RepairKind;+ handler: RepairHandler;+ /** Help text for `REPAIR_HELP`, wrapped at 80 columns by the caller. */+ summary: string;+ /** How the kind can spend on embeddings; `none` for bookkeeping-row kinds. */+ embeds: 'effect' | 'inline' | 'none';+ /** Doctor check ids whose findings this kind clears. */+ checks: string[];+}++const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {+ timeline: {+ handler: timelineRepair, embeds: 'effect', checks: ['timeline_history'],+ summary: 'Write database-only timeline rows back into their pages as marked bullets (#5567). Rows that cannot round-trip are kept and counted. Each repaired page is re-embedded by its publication.',+ },+ visibility: {+ handler: visibilityRepair, embeds: 'effect', checks: ['derived_visibility'],+ summary: 'Stamp explicit visibility on extracted atoms and synthesized concepts, tighten-only (#5525). Transcript and missing origins become private; nothing is ever loosened. Each repaired page is re-embedded by its publication.',+ },+ 'safe-chunks': {+ handler: safeChunksRepair, embeds: 'inline', checks: ['safe_index_pending'],+ summary: '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.',+ },+ 'contextual-mode': {+ handler: contextualModeRepair, embeds: 'inline', checks: ['contextual_retrieval_coverage'],+ summary: 'Stamp the contextual retrieval mode on markdown pages imported without one (#5621), exactly as a fresh import would. '+ + 'Projection-only. Vectors whose embedding input is unchanged are kept; a page whose input changes is re-embedded once unless --no-embed.',+ },+ 'connector-checkpoints': {+ handler: connectorCheckpointsRepair, embeds: 'none', checks: ['connector_checkpoints'],+ summary: 'Delete connector checkpoint rows and retry pointers that no registered connector source can load and that are older than 7 days (#5686). '+ + 'Cleanup only; no journal admission. Rows a pending write still references are kept. Brain-wide.',+ },+};++export const REPAIR_REGISTRY: readonly RepairKindSpec[] = REPAIR_KINDS.map(kind => ({ kind, ...SPECS[kind] }));++/** Whether a kind may spend on embeddings under these flags (before knowing whether a model is configured). */+export function repairMaySpend(spec: RepairKindSpec, noEmbed?: boolean): boolean {+ return spec.embeds === 'effect' || (spec.embeds === 'inline' && !noEmbed);+}++export function repairSpec(kind: RepairKind): RepairKindSpec {+ return REPAIR_REGISTRY.find(spec => spec.kind === kind)!;+}++/** The registered kind that clears a doctor check's findings, if any. */+export function repairForCheck(checkId: string): RepairKindSpec | undefined {+ return REPAIR_REGISTRY.find(spec => spec.checks.includes(checkId));+}++/** `gbrain repair <kind> --apply [--source <id>] [--no-embed]`, the exact command that applies one kind. */+export function repairApplyCommand(kind: RepairKind, opts: { source?: string; noEmbed?: boolean } = {}): string {+ return `gbrain repair ${kind}${opts.source ? ` --source ${opts.source}` : ''}${opts.noEmbed && repairSpec(kind).embeds === 'inline' ? ' --no-embed' : ''} --apply`;+}++/**+ * One local, trusted repair context shared by `gbrain repair` and the doctor+ * remediation run: the same config, embedding model and `--no-embed` handling,+ * so a kind previews and applies identically from either entry point.+ */+export async function repairRunner(engine: BrainEngine, opts: { apply: boolean; noEmbed?: boolean; logger?: OperationContext['logger'] }) {+ const config = loadConfig() ?? { engine: engine.kind };+ let embeddingModel: string | undefined;+ try { embeddingModel = config.embedding_disabled ? undefined : (await import('../ai/gateway.ts')).getEmbeddingModel(); } catch { embeddingModel = undefined; }+ const logger = opts.logger ?? { info: console.error, warn: console.error, error: console.error };+ return {+ embeddingModel,+ async run(kind: RepairKind, scope: RepairScope, run: { limit?: number; sourceFlag?: string } = {}): Promise<RepairResult> {+ const ctx = { engine, config, logger, dryRun: !opts.apply, remote: false, sourceId: scope.source_ids[0] } as OperationContext;+ const spec = repairSpec(kind);+ return runRepair(ctx, spec.handler, scope, { apply: opts.apply, limit: run.limit, embeddingModel, sourceFlag: run.sourceFlag,+ embed: !opts.noEmbed && embeddingModel !== undefined, applyArgs: opts.noEmbed && spec.embeds === 'inline' ? ['--no-embed'] : [] });+ },+ };+}diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.tsindex 736001e7cd..01f383de0e 100644--- a/src/core/schema-embedded.generated.ts+++ b/src/core/schema-embedded.generated.ts@@ -138,6 +138,10 @@ CREATE TABLE IF NOT EXISTS pages (-- path). Powers \`gbrain extract --stale\` + the \`links_extraction_lag\` doctor-- check. NULL = never extracted.links_extracted_at TIMESTAMPTZ,+ -- #5254 (migration v177): 'unbound_source' marks a page written database-only+ -- while its filesystem source had no canonical owner. Writes and sync after+ -- binding keep it database-only. NULL for every other page.+ database_only_reason TEXT,-- v0.40.3.0 contextual retrieval (renumbered from v81 to v90 on master-- merge). contextual_retrieval_mode is what tier the page was last embedded-- under (NULL = pre-v90 = treated as 'none' for drift detection).diff --git a/src/core/sync-policy.ts b/src/core/sync-policy.tsindex 759ea79f69..facc7aaac8 100644--- a/src/core/sync-policy.ts+++ b/src/core/sync-policy.ts@@ -12,6 +12,7 @@* single-source cost preview.)*/+import type { BrainEngine } from './engine.ts';import { parseSourceConfig } from './sources-load.ts';/**@@ -22,3 +23,70 @@ import { parseSourceConfig } from './sources-load.ts';export function isSyncDisabledConfig(config: unknown): boolean {return parseSourceConfig(config).syncEnabled === false;}++/**+ * #5198: source ids that are claimed (`sources writer claim`) while persistence+ * is not yet activated. performSync refuses these with+ * `writer_coordinator_required` until deliberate activation+ * (resolveSyncPersistenceMode in persistence/sync-authority.ts), so automatic+ * dispatchers skip their sync instead of queueing a job that fails the same+ * way on every tick. The refusal contract itself is unchanged: an explicit+ * `gbrain sync --source <id>` still reaches performSync and still refuses.+ *+ * Mirrors resolveSyncPersistenceMode: a missing persistence_brain row counts as+ * not activated. Fail-open: when the persistence tables are unreadable (older+ * schema, stub engine) nothing is skipped and dispatch behaves as before.+ */+export async function loadActivationPendingSourceIds(+ engine: Pick<BrainEngine, 'executeRaw'>,+): Promise<Set<string>> {+ try {+ const rows = await engine.executeRaw<{ source_id: string }>(+ `SELECT b.source_id FROM persistence_source_bindings b+ WHERE NOT COALESCE((SELECT enabled FROM persistence_brain WHERE singleton=1), false)`,+ );+ return new Set(rows.map((r) => r.source_id));+ } catch {+ return new Set();+ }+}++const reportedActivationPending = new Set<string>();++/**+ * True the first time a process skips sync for `sourceId` because of a pending+ * activation, so a long-running daemon states the reason once instead of on+ * every tick.+ */+export function firstActivationPendingSkip(sourceId: string): boolean {+ if (reportedActivationPending.has(sourceId)) return false;+ reportedActivationPending.add(sourceId);+ return true;+}++/**+ * Dispatcher guard: true when `sourceId` is awaiting activation, in which case+ * the caller skips its sync. Reports the reason once per process — an NDJSON+ * `event` line under --json, plain prose otherwise.+ */+export function skipActivationPendingSync(+ pending: ReadonlySet<string>,+ sourceId: string,+ event: string,+ jsonMode: boolean,+ write: (line: string) => void,+): boolean {+ if (!pending.has(sourceId)) return false;+ if (firstActivationPendingSkip(sourceId)) {+ write(jsonMode+ ? JSON.stringify({ event, source_id: sourceId, reason: 'activation_pending' })+ : activationPendingSkipMessage(sourceId));+ }+ return true;+}++export function activationPendingSkipMessage(sourceId: string): string {+ return `[sync] skipping automatic sync for source=${sourceId}: it is claimed but persistence is not activated, ` ++ 'so sync refuses with writer_coordinator_required. Review `gbrain sources writer status`; ' ++ 'automatic sync resumes after activation.';+}diff --git a/src/core/timeline-write-through.ts b/src/core/timeline-write-through.tsindex e75bf898dd..ef6e034d0b 100644--- a/src/core/timeline-write-through.ts+++ b/src/core/timeline-write-through.ts@@ -59,6 +59,7 @@ import {import { withPageLock } from './page-lock.ts';import { assertSourceFilesystemActive, hasSourceFilesystemLock, withSourceFilesystemLock } from './minions/source-filesystem.ts';import { findTimelineSplitIndex } from './markdown.ts';+import { isMaterializedMarkerLine } from './timeline-marker.ts';import {isDurabilityHardened, commitWriteThroughFile, currentBranch, getLastPushOutcome,type PushLogOutcome,@@ -269,6 +270,8 @@ export function spliceTimelineIntoFileText(fileText: string, date: string, block}if (before !== -1) {insertAt = before;+ // #5567: a materialized marker belongs to the bullet below it; never split the pair.+ while (insertAt > sentinel + 1 && isMaterializedMarkerLine(lines[insertAt - 1])) insertAt--;} else {// After the LAST bullet, past its indented continuation (detail) lines.insertAt = bullets[bullets.length - 1].index + 1;diff --git a/src/core/workspace-push.ts b/src/core/workspace-push.tsindex 26ef06bea6..1e001f1bf8 100644--- a/src/core/workspace-push.ts+++ b/src/core/workspace-push.ts@@ -1,4 +1,5 @@import { assertManagedFilesystemWrite } from './persistence/filesystem-guard.ts';+import { OperationError } from './ops/contract.ts';/*** workspace-push.ts — the `gbrain sources push` core: scan-gated* add → commit → pull → push for an agent-workspace repo@@ -510,14 +511,26 @@ export function aheadCount(root: string, branch: string): number | undefined {}export async function workspacePush(opts: WorkspacePushOpts): Promise<WorkspacePushResult> {- assertManagedFilesystemWrite(opts.dir);const log = (line: string) => opts.logger?.(line);const root = resolveWorkspaceRoot(opts.dir);+ try {+ assertManagedFilesystemWrite(opts.dir);+ if (root) assertManagedFilesystemWrite(root);+ } catch (e) {+ // #5198: the managed-worktree guard refuses before the lock and before+ // finish(), so without this the previous success stays on record and every+ // status surface calls a push that can never run "stale" instead of failing.+ // No lock winner can be in flight here: the same guard refuses every legacy+ // push of this root.+ if (root && e instanceof OperationError) {+ writePushStatus({ ts: new Date().toISOString(), ok: false, reason: `${e.code}: ${e.message}`, repoRoot: root });+ }+ throw e;+ }if (!root) {return { ok: false, status: 'error', reason: `not a git repository: ${opts.dir}` };}- assertManagedFilesystemWrite(root);const branch = opts.branch || detectDefaultBranch(root);// ONE lock spans scan → stage → commit → pull → push [G14/A5, CX2-6].diff --git a/src/schema.sql b/src/schema.sqlindex b7bb6fe31a..6b9432f52f 100644--- a/src/schema.sql+++ b/src/schema.sql@@ -134,6 +134,10 @@ CREATE TABLE IF NOT EXISTS pages (-- path). Powers `gbrain extract --stale` + the `links_extraction_lag` doctor-- check. NULL = never extracted.links_extracted_at TIMESTAMPTZ,+ -- #5254 (migration v177): 'unbound_source' marks a page written database-only+ -- while its filesystem source had no canonical owner. Writes and sync after+ -- binding keep it database-only. NULL for every other page.+ database_only_reason TEXT,-- v0.40.3.0 contextual retrieval (renumbered from v81 to v90 on master-- merge). contextual_retrieval_mode is what tier the page was last embedded-- under (NULL = pre-v90 = treated as 'none' for drift detection).diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.mdindex 4882846a0b..c2571d830b 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.60.10.0 -->+<!-- gbrain-template-stamp: 0.60.11.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/autopilot-fanout-wiring.test.ts b/test/autopilot-fanout-wiring.test.tsindex 51b7f6aa0f..971328892b 100644--- a/test/autopilot-fanout-wiring.test.ts+++ b/test/autopilot-fanout-wiring.test.ts@@ -158,6 +158,23 @@ describe('autopilot.ts ↔ dispatchPerSource wiring', () => {expect(skipIdx).toBeGreaterThan(localPathGuardIdx);});+ test('#5198: freshness sync dispatch skips a claimed source awaiting activation BEFORE queuing a job', () => {+ // Same static-shape pin as #4399 above: the skip must sit inside the loop+ // and before the queue.add call, and it must `continue` rather than only+ // report. loadActivationPendingSourceIds is exercised against a real+ // claim/activate sequence in test/persistence-onboarding.test.ts.+ const loopIdx = AUTOPILOT_SRC.indexOf('for (const src of sources) {');+ const queueAddIdx = AUTOPILOT_SRC.indexOf('idempotency_key: `autopilot-sync:');+ expect(loopIdx).toBeGreaterThan(-1);+ expect(queueAddIdx).toBeGreaterThan(loopIdx);+ const loopBody = AUTOPILOT_SRC.slice(loopIdx, queueAddIdx);+ expect(loopBody).toContain("if (skipActivationPendingSync(activationPending, src.id, 'freshness_sync_skipped', jsonMode,");+ expect(loopBody).toMatch(/if \(skipActivationPendingSync\([^\n]*\)\) continue;/);+ const setupIdx = AUTOPILOT_SRC.lastIndexOf('const activationPending = await loadActivationPendingSourceIds(engine);', loopIdx);+ expect(setupIdx).toBeGreaterThan(-1);+ expect(loopIdx - setupIdx).toBeLessThan(300);+ });+test('#4046: targeted dispatch scopes stable recommendation keys to the interval', () => {expect(AUTOPILOT_SRC).toContain('idempotency_key: autopilotRemediationIdempotencyKey(step.idempotency_key, slot)',diff --git a/test/autopilot-fanout.test.ts b/test/autopilot-fanout.test.tsindex b066666dbe..5a38b725fb 100644--- a/test/autopilot-fanout.test.ts+++ b/test/autopilot-fanout.test.ts@@ -419,6 +419,32 @@ describe('dispatchPerSource — integration with stubbed engine + queue', () =>expect(normalData.pull).toBe(true);});+ test('#5198: a claimed source awaiting activation keeps its freshness cycle but is never pulled or synced', async () => {+ // performSync refuses a claimed-but-not-activated source by contract, so+ // the fan-out drops its sync phase (and pull) instead of dispatching a+ // cycle that fails the same way every tick. The reason is reported once.+ const claimed = src('claimed-5198', undefined, { remote_url: 'https://github.com/x/y' });+ const normal = src('normal-5198', undefined, { remote_url: 'https://github.com/x/y' });+ const { engine, queue, added, events, fanoutOpts } = makeStubs([claimed, normal]);+ (engine as unknown as { executeRaw: () => Promise<unknown[]> }).executeRaw = async () => [{ source_id: 'claimed-5198' }];+ await dispatchPerSource(engine, queue, fanoutOpts);+ const byId = new Map<string, AddedJob>(+ added.map(j => [(j.data as Record<string, unknown>).source_id as string, j]),+ );+ const claimedData = byId.get('claimed-5198')!.data as Record<string, unknown>;+ expect(claimedData.phases).toEqual(SOURCE_FRESHNESS_PHASES.filter((p) => p !== 'sync'));+ expect(claimedData.pull).toBe(false);+ const normalData = byId.get('normal-5198')!.data as Record<string, unknown>;+ expect(normalData.phases).toEqual(SOURCE_FRESHNESS_PHASES);+ expect(normalData.pull).toBe(true);+ const skipped = () => events.filter(e => e.includes('"fanout_sync_skipped"'));+ expect(skipped().map(e => JSON.parse(e))).toEqual([+ { event: 'fanout_sync_skipped', source_id: 'claimed-5198', reason: 'activation_pending' },+ ]);+ await dispatchPerSource(engine, queue, fanoutOpts);+ expect(skipped()).toHaveLength(1);+ });+test('fanoutMax cap: 3 sources, fanoutMax=1, 1 dispatched + 2 in skippedCap', async () => {const { engine, queue, added, fanoutOpts } = makeStubs([src('a'), src('b'), src('c')]);fanoutOpts.fanoutMax = 1;diff --git a/test/autopilot-operator-pause.test.ts b/test/autopilot-operator-pause.test.tsnew file mode 100644index 0000000000..a48c3b70f1--- /dev/null+++ b/test/autopilot-operator-pause.test.ts@@ -0,0 +1,90 @@+/**+ * `gbrain autopilot pause|resume` (fix wave 3, Lane D): the operator pause is+ * its own marker. The daemon and workers honor it, status shows it,+ * `autopilot --install` (which `gbrain upgrade` runs) keeps it, and resume+ * clears only it — never a migration or restore hold.+ */+import { describe, expect, test } from 'bun:test';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join } from 'node:path';+import { withEnv, emptyHome } from './helpers/with-env.ts';+import { autopilotOperatorPauseMarkerPath, autopilotPaused, autopilotPausedMarkerPath } from '../src/core/autopilot-paths.ts';+import { runAutopilotPauseCommand } from '../src/commands/autopilot-pause.ts';+import { resolveAutopilotPositionals, runAutopilot, runAutopilotStatus } from '../src/commands/autopilot.ts';++function out(run: () => unknown): string {+ const lines: string[] = [];+ const log = console.log;+ console.log = (...parts: unknown[]) => { lines.push(parts.map(String).join(' ')); };+ try { run(); } finally { console.log = log; }+ return lines.join('\n');+}++describe('autopilot operator pause', () => {+ test('pause and resume are subcommands', () => {+ expect(resolveAutopilotPositionals(['pause', '--reason', 'upgrade window'])).toEqual(['--pause', '--reason', 'upgrade window']);+ expect(resolveAutopilotPositionals(['resume'])).toEqual(['--resume']);+ });++ test('pause writes its own marker, pauses the daemon and workers, and status shows it', async () => {+ await withEnv({ GBRAIN_HOME: emptyHome() }, () => {+ expect(autopilotPaused()).toBe(false);+ const text = out(() => runAutopilotPauseCommand(['--pause', '--reason', 'upgrade window']));+ expect(text).toContain('Autopilot paused on this host');+ expect(text).toContain('gbrain autopilot resume');+ expect(existsSync(autopilotOperatorPauseMarkerPath())).toBe(true);+ expect(existsSync(autopilotPausedMarkerPath())).toBe(false);+ expect(autopilotPaused()).toBe(true);+ expect(readFileSync(autopilotOperatorPauseMarkerPath(), 'utf8')).toContain('upgrade window');+ const status = JSON.parse(out(() => runAutopilotStatus(['--status', '--json'])));+ expect(status.paused_reason).toContain('operator pause');+ expect(status.paused_reason).toContain('upgrade window');+ // Idempotent: pausing again keeps the pause.+ expect(out(() => runAutopilotPauseCommand(['--pause']))).toContain('already paused');+ expect(out(() => runAutopilotPauseCommand(['--resume']))).toContain('Operator pause cleared');+ expect(autopilotPaused()).toBe(false);+ expect(out(() => runAutopilotPauseCommand(['--resume']))).toContain('No operator pause was set');+ });+ });++ test('resume never clears a migration hold', async () => {+ await withEnv({ GBRAIN_HOME: emptyHome() }, () => {+ const hold = autopilotPausedMarkerPath();+ mkdirSync(dirname(hold), { recursive: true });+ writeFileSync(hold, `paused by gbrain migrate (pid ${process.pid})\n`);+ out(() => runAutopilotPauseCommand(['--pause']));+ const text = out(() => runAutopilotPauseCommand(['--resume']));+ expect(text).toContain('Another hold is still present and was not touched');+ expect(existsSync(hold)).toBe(true);+ expect(autopilotPaused()).toBe(true);+ });+ });++ test('autopilot --install (what gbrain upgrade runs) keeps the operator pause and clears only a leaked hold', async () => {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-autopilot-home-'));+ const repo = mkdtempSync(join(tmpdir(), 'gbrain-autopilot-repo-'));+ const bin = mkdtempSync(join(tmpdir(), 'gbrain-autopilot-bin-'));+ writeFileSync(join(bin, 'gbrain'), '#!/bin/sh\nexit 0\n', { mode: 0o755 });+ await withEnv({ GBRAIN_HOME: emptyHome(), HOME: home, PATH: `${bin}:${process.env.PATH}` }, async () => {+ out(() => runAutopilotPauseCommand(['--pause', '--reason', 'upgrading hosts']));+ writeFileSync(autopilotPausedMarkerPath(), 'leaked by a dead migration\n');+ const engine = { kind: 'postgres', getConfig: async () => null } as never;+ const log = console.log;+ console.log = () => {};+ try { await runAutopilot(engine, ['--install', '--target', 'ephemeral-container', '--repo', repo, '--no-inject']); } finally { console.log = log; }+ expect(existsSync(autopilotPausedMarkerPath())).toBe(false);+ expect(existsSync(autopilotOperatorPauseMarkerPath())).toBe(true);+ expect(autopilotPaused()).toBe(true);+ });+ });++ test('the daemon loop and job workers consult both markers', () => {+ const root = join(import.meta.dir, '..', 'src');+ // test-reads-source-ok[structural]: no in-process autopilot tick or worker claim harness exists (TODOS: extract a testable tick); pin both markers at the gates.+ const daemon = readFileSync(join(root, 'commands', 'autopilot.ts'), 'utf8');+ const worker = readFileSync(join(root, 'core', 'minions', 'worker.ts'), 'utf8');+ expect(daemon).toContain('if (autopilotPaused()) {\n // Self-heal an orphan');+ expect(worker.match(/existsSync\(autopilotPausedMarkerPath\(\)\) \|\| existsSync\(autopilotOperatorPauseMarkerPath\(\)\)/g)?.length).toBe(2);+ });+});diff --git a/test/bootstrap-verify.serial.test.ts b/test/bootstrap-verify.serial.test.tsindex 277514b7cc..cb90a7e6ca 100644--- a/test/bootstrap-verify.serial.test.ts+++ b/test/bootstrap-verify.serial.test.ts@@ -30,6 +30,8 @@ import type { CapabilityReport } from '../src/core/capability.ts';import { _resetWriteThroughCacheForTest } from '../src/core/write-through.ts';import { operations, type OperationContext } from '../src/core/operations.ts';import { loadCorpusPages, loadCorpusQueries } from './helpers/bootstrap-corpus.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';const KEYLESS: CapabilityReport = {embeddings: { available: false },@@ -610,3 +612,32 @@ describe('verifyWorkspace — real corpus graph floor + qrels recall', () => {expect(misses).toEqual([]);}, 240_000);});++describe('verifyWorkspace — managed brain (#5280)', () => {+ test('verify runs on a managed brain and purges its probes through the coordinator', async () => {+ await claimWorktree(engine, 'workspace', join(ws, 'brain'));+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ try {+ const res = await verifyWorkspace(engine, ws, { sourceId: 'workspace', gbrainHomeDir: home, capabilities: KEYLESS, skipHooksSmoke: true });+ for (const c of check(res.checks, 'roundtrip')) expect(c.ok).toBe(true);+ expect(res.checks.filter((c) => c.id === 'probe_cleanup')).toEqual([]);+ const probeRows = await engine.executeRaw<{ n: string }>(+ `SELECT count(*)::text AS n FROM pages WHERE source_id = 'workspace' AND slug = ANY($1::text[])`,+ [[VERIFY_PROBE_SLUG, VERIFY_PROBE_ENTITY_SLUG]],+ );+ expect(probeRows[0].n).toBe('0');+ expect(existsSync(join(ws, 'brain', `${VERIFY_PROBE_SLUG}.md`))).toBe(false);+ const purged = await engine.executeRaw<{ slug: string }>(+ `SELECT slug FROM persistence_requests WHERE source_id = 'workspace' AND operation = 'delete_page' AND state = 'committed'+ AND outcome->>'status' = 'purged' AND slug = ANY($1::text[]) ORDER BY slug`,+ [[VERIFY_PROBE_SLUG, VERIFY_PROBE_ENTITY_SLUG]],+ );+ expect(new Set(purged.map((r) => r.slug))).toEqual(new Set([VERIFY_PROBE_SLUG, VERIFY_PROBE_ENTITY_SLUG]));+ expect(await engine.executeRaw(`SELECT id FROM facts WHERE source_id = 'workspace' AND source_markdown_slug = ANY($1::text[])`,+ [[VERIFY_PROBE_SLUG, VERIFY_PROBE_ENTITY_SLUG]])).toEqual([]);+ } finally {+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ }+ }, 240_000);+});diff --git a/test/canonical-writer-inventory.test.ts b/test/canonical-writer-inventory.test.tsindex e83677837a..0b4b6bd965 100644--- a/test/canonical-writer-inventory.test.ts+++ b/test/canonical-writer-inventory.test.ts@@ -5,20 +5,30 @@ import { join, relative } from 'node:path';const root = join(import.meta.dir, '..');const method = 'putPage|refreshPageBody|deletePage|deletePages|softDeletePage|softDeletePages|restorePage|purgeDeletedPages|addTag|removeTag|addTimelineEntry|addTimelineEntriesBatch|upsertEventProjection|addTakesBatch|updateTake|supersedeTake|resolveTake|insertFact|insertFacts|deleteFactsForPage|expireFact|consolidateFact|migrateFactsToCanonical|revertToVersion|updateSlug|setPageAliases|addLink|removeLink|rewriteLinks';const pattern = new RegExp(`\\.(?:${method})\\s*(?:\\?\\.)?\\s*\\(|\\b(?:INSERT\\s+INTO|UPDATE|DELETE\\s+FROM|TRUNCATE)\\s+(?:pages|tags|slug_aliases|page_aliases|facts|takes|timeline_entries|sources)\\b`, 'gi');-function count(body: string): number { return [...body.matchAll(pattern)].length; }+// Direct content imports bypass the coordinator unless they carry `prepare`; count every call site.+const importPattern = /(?<!function\s+)(?<![.\w])importFromContent\s*\(/g;+function count(body: string): number { return [...body.matchAll(pattern)].length + [...body.matchAll(importPattern)].length; }function files(directory: string): string[] {return readdirSync(directory, { withFileTypes: true }).flatMap(entry => entry.isDirectory()? files(join(directory, entry.name)) : entry.name.endsWith('.ts') && !entry.name.endsWith('.generated.ts') ? [join(directory, entry.name)] : []);}-test('new canonical write callsites require a reviewed inventory and an enforcement boundary', () => {+type Inventory = Map<string, { ceiling: number; boundary: string; reason: string }>;+function loadInventory(): Inventory {const rows = readFileSync(join(root, 'docs/architecture/canonical-writers.tsv'), 'utf8').split('\n').filter(line => line && !line.startsWith('#')).map(line => line.split('\t'));- const inventory = new Map(rows.map(([path, ceiling, boundary, reason]) => [path, { ceiling: Number(ceiling), boundary, reason }]));+ return new Map(rows.map(([path, ceiling, boundary, reason]) => [path, { ceiling: Number(ceiling), boundary, reason }]));+}+function gapsFor(sources: Iterable<[string, string]>, inventory: Inventory): string[] {const gaps: string[] = [];- for (const file of files(join(root, 'src'))) {- const path = relative(root, file); const sites = count(readFileSync(file, 'utf8')); const row = inventory.get(path);+ for (const [path, body] of sources) {+ const sites = count(body); const row = inventory.get(path);if (sites && (!row || sites > row.ceiling)) gaps.push(`${path}: ${sites} write references; reviewed ceiling ${row?.ceiling ?? 0}`);}+ return gaps;+}+test('new canonical write callsites require a reviewed inventory and an enforcement boundary', () => {+ const inventory = loadInventory();+ const gaps = gapsFor(files(join(root, 'src')).map(file => [relative(root, file), readFileSync(file, 'utf8')] as [string, string]), inventory);for (const [path, row] of inventory) {expect(['coordinator', 'engine_guard', 'early_refusal', 'filesystem_guard', 'projection', 'schema', 'isolated_eval', 'contract']).toContain(row.boundary);expect(row.reason.length).toBeGreaterThan(20);@@ -26,6 +36,37 @@ test('new canonical write callsites require a reviewed inventory and an enforcem}expect(gaps, 'Classify each addition in canonical-writers.tsv after checking DB and filesystem ordering.').toEqual([]);});+test('a planted bypass in a converted writer or a new file fails the census', () => {+ const inventory = loadInventory();+ // test-reads-source-ok[structural]: the census is a source-text tripwire by design; the planted copy proves it flags a new bypass.+ const links = readFileSync(join(root, 'src/core/ops/links.ts'), 'utf8');+ const concepts = readFileSync(join(root, 'src/core/cycle/synthesize-concepts.ts'), 'utf8');+ expect(gapsFor([['src/core/ops/links.ts', links], ['src/core/cycle/synthesize-concepts.ts', concepts]], inventory)).toEqual([]);+ expect(gapsFor([+ ['src/core/ops/links.ts', `${links}\nawait ctx.engine.addLink(a, b, '', '', 'manual');`],+ ['src/core/cycle/synthesize-concepts.ts', `${concepts}\nawait importFromContent(engine, slug, md, { sourceId });`],+ ['src/core/cycle/new-writer.ts', 'await engine.putPage(slug, page);'],+ ], inventory)).toEqual([+ 'src/core/ops/links.ts: 4 write references; reviewed ceiling 3',+ 'src/core/cycle/synthesize-concepts.ts: 3 write references; reviewed ceiling 2',+ 'src/core/cycle/new-writer.ts: 1 write references; reviewed ceiling 0',+ ]);+});+test('every mutating operation and named CLI writer is classified for managed brains', async () => {+ const { operations } = await import('../src/core/operations.ts');+ const rows = readFileSync(join(root, 'docs/architecture/managed-mutating-writers.tsv'), 'utf8').split('\n')+ .filter(line => line && !line.startsWith('#')).map(line => line.split('\t'));+ const classes = ['coordinator', 'no_canonical_write', 'early_refusal', 'engine_guard'];+ for (const [kind, name, klass, reason] of rows) {+ expect(['op', 'cli']).toContain(kind);+ expect(classes).toContain(klass);+ expect(reason?.length ?? 0).toBeGreaterThan(20);+ if (kind === 'cli') expect(readFileSync(join(root, name), 'utf8').length).toBeGreaterThan(0);+ }+ const classified = rows.filter(([kind]) => kind === 'op').map(([, name]) => name).sort();+ const mutating = operations.filter(op => op.mutating).map(op => op.name).sort();+ expect(classified, 'Classify each mutating operation in managed-mutating-writers.tsv.').toEqual(mutating);+});test('the census detects direct, optional and multiline SQL writers', () => {expect(count('await engine.putPage("x", page); await engine.insertFact?.(fact); await tx.executeRaw(`UPDATE\n pages SET title=$1`);')).toBe(3);expect(count('await engine.getPage("x"); await tx.executeRaw(`UPDATE embedding_jobs SET status=$1`);')).toBe(0);diff --git a/test/cli-dispatch-thin-client.test.ts b/test/cli-dispatch-thin-client.test.tsindex dc88bc81ae..226c0d5294 100644--- a/test/cli-dispatch-thin-client.test.ts+++ b/test/cli-dispatch-thin-client.test.ts@@ -223,6 +223,15 @@ describe('thin-client scratch-DB guard — jobs partial dispatch + config refusaexpect(r.stderr).toContain('thin-client of https://brain-host.example/mcp');});+ // #5254: the unbound-write policy decides whether Postgres pages may skip+ // their canonical files; only the brain host may change it (no MCP op writes config).+ test('`gbrain config set persistence.unbound_write` is refused on a thin client', async () => {+ seedThinClientConfig(tmp);+ const r = await run(['config', 'set', 'persistence.unbound_write', 'database_only']);+ expect(r.exitCode).toBe(1);+ expect(r.stderr).toContain('not routable');+ });+test('`gbrain jobs work` is refused with pinpoint hint (host-queue-bound)', async () => {seedThinClientConfig(tmp);const r = await run(['jobs', 'work']);diff --git a/test/connector-checkpoint-identity.test.ts b/test/connector-checkpoint-identity.test.tsnew file mode 100644index 0000000000..87f2474c1e--- /dev/null+++ b/test/connector-checkpoint-identity.test.ts@@ -0,0 +1,125 @@+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { readFileSync } from 'node:fs';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { parseGoogleSourceConfig, runGoogleSync } from '../src/core/google/google-source.ts';+import { disposePersistenceConsumer, startPersistenceConsumer, waitForWrite } from '../src/core/persistence/service.ts';+import type { WriteRequest } from '../src/core/persistence/model.ts';+import { withEnv } from './helpers/with-env.ts';+import { createConnectorFixture, options, json, googleConfig, contact } from './helpers/connector-fixture.ts';++const { engines, env, source, boundSource, setup, teardown } = createConnectorFixture();+beforeAll(setup, 120_000);+afterAll(teardown);++async function mark(engine: BrainEngine, sourceId: string): Promise<string> {+ const [row] = await engine.executeRaw<{ seq: string | null }>('SELECT max(sequence)::text AS seq FROM persistence_requests WHERE source_id=$1', [sourceId]);+ return row?.seq ?? '0';+}++/** Page and checkpoint admissions since `after`, classified across both intent namespaces. */+async function admissions(engine: BrainEngine, sourceId: string, after: string) {+ const rows = await engine.executeRaw<{ kind: string }>('SELECT intent->>\'kind\' AS kind FROM persistence_requests WHERE source_id=$1 AND sequence>$2::bigint', [sourceId, after]);+ return { pages: rows.filter(r => /_(import|delete)$/.test(r.kind)).length, checkpoints: rows.filter(r => r.kind.endsWith('_checkpoint')).length };+}++async function stamp(engine: BrainEngine, sourceId: string): Promise<void> {+ const now = new Date().toISOString();+ expect(await engine.updateSourceConfig(sourceId, { last_source_cycle_at: now, last_full_cycle_at: now })).toBe(true);+}++/** A People fixture: `rotate` changes the sync token every sweep; `rewalk` ignores the token and lists everything. */+function peopleFetcher(opts: { rotate?: boolean; rewalk?: boolean; onList?: () => Promise<void> } = {}) {+ const calls: string[] = [];+ let sweep = 0;+ const fetcher = async (url: string) => {+ calls.push(url);+ const u = new URL(url);+ if (url.includes('/settings/sendAs')) return json({ sendAs: [] });+ if (u.pathname.endsWith('/people/me')) return json({ resourceName: 'people/me', emailAddresses: [{ value: googleConfig.g_account, metadata: { primary: true } }] });+ if (u.pathname.endsWith('/people/me/connections')) {+ await opts.onList?.();+ const token = opts.rotate ? `contacts-${++sweep}` : 'contacts-stable';+ if (u.searchParams.has('syncToken') && !opts.rewalk) return json({ connections: [], nextSyncToken: token });+ return json({ connections: [contact('first', 'First Example'), contact('second', 'Second Example')], nextSyncToken: token });+ }+ throw new Error(`Unexpected external fixture route ${u.pathname}`);+ };+ return { fetcher, calls };+}++test('#5686: two connector cycles with a cycle stamp between them resume one checkpoint and admit nothing new', async () => withEnv(env, async () => {+ for (const engine of engines) for (const bound of [false, true]) {+ const f = bound ? await boundSource(engine, googleConfig) : await source(engine, googleConfig);+ const cfg = parseGoogleSourceConfig(googleConfig, f.dir);+ const { fetcher, calls } = peopleFetcher();+ expect((await runGoogleSync(engine, f.id, cfg, options, fetcher)).added).toBe(2);+ await stamp(engine, f.id);+ await disposePersistenceConsumer(engine);+ const before = await mark(engine, f.id);+ calls.length = 0;+ const second = await runGoogleSync(engine, f.id, cfg, options, fetcher);+ expect(second.status).not.toBe('partial');+ expect(calls.some(url => url.includes('syncToken=contacts-stable'))).toBe(true);+ expect(await admissions(engine, f.id, before)).toEqual({ pages: 0, checkpoints: 0 });+ }+}), 180_000);++test('#5686: a cycle stamp landing mid-sweep does not abort the connector sweep', async () => withEnv(env, async () => {+ for (const engine of engines) {+ const f = await source(engine, googleConfig);+ const { fetcher } = peopleFetcher({ onList: () => stamp(engine, f.id) });+ const result = await runGoogleSync(engine, f.id, parseGoogleSourceConfig(googleConfig, f.dir), options, fetcher);+ expect(result.status).not.toBe('partial');+ expect(result.added).toBe(2);+ }+}), 120_000);++test('#5686: a connector write still pending when the stamp lands publishes instead of failing source_changed', async () => withEnv(env, async () => {+ for (const engine of engines) {+ const f = await boundSource(engine, googleConfig);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw("UPDATE persistence_worktrees SET state='draining' WHERE id=$1::uuid", [f.binding.worktree_id]);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const { fetcher } = peopleFetcher();+ try { await runGoogleSync(engine, f.id, parseGoogleSourceConfig(googleConfig, f.dir), options, fetcher); } catch { /* pending admission */ }+ const pending = await engine.executeRaw<WriteRequest>("SELECT * FROM persistence_requests WHERE source_id=$1 AND intent->>'kind' LIKE '%import' AND state='queued'", [f.id]);+ expect(pending.length).toBeGreaterThan(0);+ await stamp(engine, f.id);+ await disposePersistenceConsumer(engine);+ await engine.executeRaw("UPDATE persistence_worktrees SET state='active' WHERE id=$1::uuid", [f.binding.worktree_id]);+ startPersistenceConsumer(engine, { engine: engine.kind });+ for (const row of pending) expect((await waitForWrite(engine, row, { engine: engine.kind }, 20_000)).state).toBe('committed');+ expect(readFileSync(join(f.dir, 'people/first-example.md'), 'utf8')).toContain('First Example');+ }+}), 120_000);++test('#5470: a re-walk of unchanged provider content admits no page and, with a stable cursor, no checkpoint', async () => withEnv(env, async () => {+ for (const engine of engines) for (const bound of [false, true]) {+ const f = bound ? await boundSource(engine, googleConfig) : await source(engine, googleConfig);+ const cfg = parseGoogleSourceConfig(googleConfig, f.dir);+ const { fetcher } = peopleFetcher({ rewalk: true });+ expect((await runGoogleSync(engine, f.id, cfg, options, fetcher)).added).toBe(2);+ await disposePersistenceConsumer(engine);+ const before = await mark(engine, f.id);+ const second = await runGoogleSync(engine, f.id, cfg, options, fetcher);+ expect(second.status).toBe('up_to_date');+ expect(await admissions(engine, f.id, before)).toEqual({ pages: 0, checkpoints: 0 });+ }+}), 180_000);++test('#5470: a rotating provider cursor costs exactly one checkpoint admission and no page admission per quiet run', async () => withEnv(env, async () => {+ for (const engine of engines) {+ const f = await source(engine, googleConfig);+ const cfg = parseGoogleSourceConfig(googleConfig, f.dir);+ const { fetcher } = peopleFetcher({ rotate: true, rewalk: true });+ expect((await runGoogleSync(engine, f.id, cfg, options, fetcher)).added).toBe(2);+ for (let run = 0; run < 2; run++) {+ await stamp(engine, f.id);+ await disposePersistenceConsumer(engine);+ const before = await mark(engine, f.id);+ expect((await runGoogleSync(engine, f.id, cfg, options, fetcher)).status).toBe('up_to_date');+ expect(await admissions(engine, f.id, before)).toEqual({ pages: 0, checkpoints: 1 });+ }+ }+}), 180_000);diff --git a/test/connector-identity.test.ts b/test/connector-identity.test.tsnew file mode 100644index 0000000000..d3b18c1f89--- /dev/null+++ b/test/connector-identity.test.ts@@ -0,0 +1,67 @@+import { describe, expect, test } from 'bun:test';+import { classifyConnectorLeaf, connectorConfigLeaves, connectorIdentity, CONNECTOR_LEAF_RULES, isConnectorIntentKind } from '../src/core/persistence/connector-identity.ts';+import { parseGoogleSourceConfig } from '../src/core/google/google-source.ts';+import { parseGitHubSourceConfig } from '../src/core/github-source.ts';++// #5686: the connector identity is the parsed config minus credential-delivery+// fields. Raw sources.config bookkeeping (cycle stamps) never changes it.++const google = { kind: 'google', g_account: '[email protected]', g_services: 'gmail,calendar', g_access: 'env', g_token_env: 'TOKEN_A', g_history_days: 30 };+const githubRepos = { kind: 'github', gh_scope: 'repos', gh_repos: 'acme-example/app,acme-example/api', gh_token_env: 'TOKEN_A' };+const githubAuto = { kind: 'github', gh_scope: 'auto', gh_token_env: 'TOKEN_A' };+const githubApp = { kind: 'github', gh_scope: 'auto', gh_app_id: 42, gh_app_pem_path: '/keys/a.pem', gh_app_install_id: 7, gh_token_env: 'TOKEN_A' };+const id = (kind: 'google' | 'github', raw: Record<string, unknown>) => connectorIdentity(kind, raw, '/brain/source').digest;++describe('connector identity leaf classification', () => {+ test('every leaf each parser returns is classified as identity or excluded', () => {+ const samples: Array<['google' | 'github', Record<string, unknown>]> = [+ ['google', { ...google, g_access: 'command', g_token_command: 'print-token', g_calendar_id: '[email protected]', g_dir: '/brain/google' }],+ ['github', { ...githubApp, gh_dir: '/brain/github' }], ['github', githubRepos], ['github', githubAuto],+ ];+ for (const [kind, raw] of samples) {+ const parsed = kind === 'google' ? parseGoogleSourceConfig(raw, '/brain') : parseGitHubSourceConfig(raw, '/brain');+ for (const leaf of Object.keys(connectorConfigLeaves(parsed))) {+ expect(classifyConnectorLeaf(kind, parsed, leaf), `${kind}:${leaf}`).toMatch(/^(identity|excluded)$/);+ expect(Object.hasOwn(CONNECTOR_LEAF_RULES[kind], leaf), `${kind}:${leaf} has a rule`).toBe(true);+ }+ }+ });++ test('nested GitHub App leaves: pemPath excluded; appId and installId identity under scope auto', () => {+ const parsed = parseGitHubSourceConfig(githubApp, '/brain');+ expect(classifyConnectorLeaf('github', parsed, 'app.pemPath')).toBe('excluded');+ expect(classifyConnectorLeaf('github', parsed, 'app.appId')).toBe('identity');+ expect(classifyConnectorLeaf('github', parsed, 'app.installId')).toBe('identity');+ const repos = parseGitHubSourceConfig({ ...githubApp, gh_scope: 'repos', gh_repos: 'acme-example/app' }, '/brain');+ expect(classifyConnectorLeaf('github', repos, 'app.appId')).toBe('excluded');+ });+});++describe('connector identity stability', () => {+ test('cycle stamps and other raw bookkeeping keys never change the identity', () => {+ const stamped = { ...google, last_source_cycle_at: '2026-09-29T00:00:00Z', last_full_cycle_at: '2026-09-29T00:00:00Z', slug_root_mode: 'source-root' };+ expect(id('google', stamped)).toBe(id('google', google));+ expect(id('github', { ...githubRepos, last_source_cycle_at: 'x' })).toBe(id('github', githubRepos));+ });+ test('a content field changes the identity; reordered or duplicated services and repos do not', () => {+ expect(id('google', { ...google, g_history_days: 90 })).not.toBe(id('google', google));+ expect(id('google', { ...google, g_services: 'calendar,gmail,calendar' })).toBe(id('google', google));+ expect(id('github', { ...githubRepos, gh_repos: 'acme-example/api,acme-example/app,acme-example/app' })).toBe(id('github', githubRepos));+ });+ test('credential-delivery fields: Google access mode and token env, GitHub token env under scope repos, do not change it', () => {+ expect(id('google', { ...google, g_token_env: 'TOKEN_B' })).toBe(id('google', google));+ expect(id('google', { ...google, g_access: 'command', g_token_command: 'print-token' })).toBe(id('google', google));+ expect(id('github', { ...githubRepos, gh_token_env: 'TOKEN_B' })).toBe(id('github', githubRepos));+ });+ test('under scope auto the token env is identity without an App and ignored with one; moving the PEM keeps it', () => {+ expect(id('github', { ...githubAuto, gh_token_env: 'TOKEN_B' })).not.toBe(id('github', githubAuto));+ expect(id('github', { ...githubApp, gh_token_env: 'TOKEN_B' })).toBe(id('github', githubApp));+ expect(id('github', { ...githubApp, gh_app_pem_path: '/moved/a.pem' })).toBe(id('github', githubApp));+ expect(id('github', { ...githubApp, gh_app_install_id: 8 })).not.toBe(id('github', githubApp));+ });+ test('one predicate accepts both connector intent namespaces', () => {+ expect(isConnectorIntentKind('connector_v2_import')).toBe(true);+ expect(isConnectorIntentKind('managed_connector_checkpoint')).toBe(true);+ expect(isConnectorIntentKind('managed_sync_import')).toBe(false);+ });+});diff --git a/test/connector-wave3.test.ts b/test/connector-wave3.test.tsnew file mode 100644index 0000000000..5f6d357bed--- /dev/null+++ b/test/connector-wave3.test.ts@@ -0,0 +1,544 @@+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { randomUUID, generateKeyPairSync } from 'node:crypto';+import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { dirname, join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { parseGoogleSourceConfig, runGoogleSync } from '../src/core/google/google-source.ts';+import { parseGitHubSourceConfig, runGitHubSync } from '../src/core/github-source.ts';+import { disposePersistenceConsumer, startPersistenceConsumer, waitForWrite, writeResponse } from '../src/core/persistence/service.ts';+import { admitWrite, compactWriteReceipts } from '../src/core/persistence/journal.ts';+import { declarePersistenceProtocol } from '../src/core/persistence/protocol.ts';+import { readManagedConnectorState } from '../src/core/persistence/connector-state.ts';+import { readConnectorSourceStatuses } from '../src/core/persistence/connector-status.ts';+import { migrateConnectorCheckpoints, CONNECTOR_MIGRATION_OP } from '../src/core/persistence/connector-checkpoint-migration.ts';+import { connectorCheckpointKey, connectorIdentity } from '../src/core/persistence/connector-identity.ts';+import { preparePersistedMutation } from '../src/core/persistence/service.ts';+import { checkConnectorCheckpoints } from '../src/commands/doctor/checks/connector-checkpoints.ts';+import { connectorCheckpointsRepair } from '../src/core/repair/connector-checkpoints.ts';+import { resolveRepairScope, runRepair } from '../src/core/repair/core.ts';+import { performSync } from '../src/commands/sync.ts';+import { handleToolCall } from '../src/mcp/server.ts';+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { inspectUnchanged } from '../src/core/persistence/noop-kernel.ts';+import { ALL_SOURCES } from '../src/core/source-id.ts';+import type { WriteRequest } from '../src/core/persistence/model.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';+import { withEnv } from './helpers/with-env.ts';+import { createConnectorFixture, options, json, googleConfig, githubConfig, contact, issueFixture, githubFetch, withGoogleAccount, connectorPendingSet } from './helpers/connector-fixture.ts';++const { home, engines, env, source, boundSource, setup, teardown } = createConnectorFixture();+beforeAll(setup, 120_000);+afterAll(teardown);++const mark = async (engine: BrainEngine, id: string) => (await engine.executeRaw<{ seq: string | null }>('SELECT max(sequence)::text AS seq FROM persistence_requests WHERE source_id=$1', [id]))[0]?.seq ?? '0';+const since = (engine: BrainEngine, id: string, after: string) => engine.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE source_id=$1 AND sequence>$2::bigint ORDER BY sequence', [id, after]);+const incarnation = async (engine: BrainEngine, id: string) => (await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text FROM sources WHERE id=$1', [id]))[0].incarnation;++/** People fixture: `all` is the full listing a walk without a sync token returns; incremental walks return nothing. */+function people(all: () => Array<ReturnType<typeof contact>>, opts: { fail?: () => boolean; token?: () => string } = {}) {+ const calls: string[] = [];+ const fetcher = async (url: string) => {+ calls.push(url);+ const u = new URL(url);+ if (url.includes('/settings/sendAs')) return json({ sendAs: [] });+ if (opts.fail?.()) return json({ error: { message: 'fixture people outage' } }, 400);+ return json({ connections: u.searchParams.has('syncToken') ? [] : all(), nextSyncToken: opts.token?.() ?? 'contacts-stable' });+ };+ return { fetcher, calls };+}+const google = (engine: BrainEngine, f: { id: string; dir: string }, fetcher: (url: string) => Promise<Response>, account = googleConfig.g_account, extra: object = {}, config: Record<string, unknown> = googleConfig) =>+ runGoogleSync(engine, f.id, parseGoogleSourceConfig(config, f.dir), { ...options, ...extra }, withGoogleAccount(fetcher, account));++test('account pin: a contacts-only or calendar-only credential swap refuses before any admission; rotation for the same account resumes', async () => withEnv(env, async () => {+ for (const engine of engines) for (const service of ['contacts', 'calendar'] as const) {+ const config = { ...googleConfig, g_services: service };+ const f = await source(engine, config);+ const at = new Date(Date.now() - 3600_000).toISOString();+ const base = async (url: string) => {+ if (url.includes('/settings/sendAs')) return json({ sendAs: [] });+ if (url.includes('/calendar/')) return json({ items: [{ id: 'example-event', summary: 'Example planning', status: 'confirmed', start: { dateTime: at }, end: { dateTime: at } }], nextSyncToken: 'calendar-1' });+ return json({ connections: [contact('first', 'First Example')], nextSyncToken: 'contacts-1' });+ };+ expect((await google(engine, f, base, googleConfig.g_account, {}, config)).added).toBe(1);+ const state = await readManagedConnectorState(engine, f.id, await incarnation(engine, f.id));+ expect(state.account).toEqual({ kind: 'google', email: googleConfig.g_account });+ await disposePersistenceConsumer(engine);+ const before = await mark(engine, f.id);+ const swapped = google(engine, f, base, '[email protected]', {}, config);+ await expect(swapped).rejects.toMatchObject({ code: 'connector_account_changed', detail: 'account_changed', docs: 'docs/guides/write-refusals.md#connector-account-changed' });+ const error = await swapped.catch(e => e) as { suggestion: string; message: string };+ // Identities stay out of the message (job records persist and serve it remotely) and appear in the local suggestion.+ expect(error.message).not.toContain('[email protected]');+ expect(error.suggestion).toContain('pinned to [email protected]; the credential resolves to [email protected]');+ expect(error.suggestion).toContain('g_token_env (CONNECTOR_TEST_TOKEN)');+ expect(error.suggestion).toContain(`gbrain sync --source ${f.id}`);+ expect(error.suggestion).toContain(`gbrain sources archive ${f.id}`);+ expect(error.suggestion).toContain('gbrain google setup --account [email protected]');+ expect(await since(engine, f.id, before)).toHaveLength(0);+ // --reset-checkpoint never authorizes an account change.+ await expect(google(engine, f, base, '[email protected]', { resetCheckpoint: true }, config)).rejects.toMatchObject({ code: 'connector_account_changed' });+ // A rotated token for the same account resumes the checkpoint: no page admission.+ expect((await google(engine, f, base, googleConfig.g_account, {}, config)).status).not.toBe('partial');+ expect((await since(engine, f.id, before)).filter(row => String(row.intent?.kind).endsWith('_import'))).toHaveLength(0);+ }+}), 180_000);++test('account pin: a GitHub App without an install id that resolves a different installation refuses with the new-source hint', async () => withEnv(env, async () => {+ const { privateKey } = generateKeyPairSync('rsa', { modulusLength: 2048 });+ const pemPath = join(home, `app-${randomUUID().slice(0, 8)}.pem`);+ writeFileSync(pemPath, privateKey.export({ type: 'pkcs1', format: 'pem' }));+ const config = { kind: 'github', gh_scope: 'repos', gh_repos: 'acme-example/app', gh_app_id: 4242, gh_app_pem_path: pemPath };+ for (const engine of engines) {+ const f = await source(engine, config);+ let installation = 100;+ const fetcher = async (url: string) => {+ const path = new URL(url).pathname;+ if (path === '/app/installations') return json([{ id: installation }]);+ if (path === `/app/installations/${installation}/access_tokens`) return json({ token: 'ghs_fixture', expires_at: new Date(Date.now() + 3600_000).toISOString() });+ return githubFetch()(url);+ };+ const run = () => runGitHubSync(engine, f.id, parseGitHubSourceConfig(config, f.dir), options, fetcher);+ expect((await run()).status).not.toBe('partial');+ expect((await readManagedConnectorState(engine, f.id, await incarnation(engine, f.id))).account).toEqual({ kind: 'github', installationId: 100, login: null });+ installation = 200;+ const before = await mark(engine, f.id);+ const refused = await run().catch(e => e) as { code: string; suggestion: string };+ expect(refused.code).toBe('connector_account_changed');+ expect(refused.suggestion).toContain('--app-install 200');+ expect(refused.suggestion).toContain(`gbrain sources archive ${f.id}`);+ expect(await since(engine, f.id, before)).toHaveLength(0);+ // A token refresh re-mints for the installation first resolved, never a newly discovered one.+ const { AppTokenProvider } = await import('../src/core/github-source.ts');+ installation = 100;+ const minted: string[] = [];+ const provider = new AppTokenProvider(parseGitHubSourceConfig(config, f.dir).app!, async (url: string, init?: RequestInit) => { minted.push(new URL(url).pathname); return fetcher(url); });+ await provider.getToken();+ installation = 200;+ await provider.refresh().catch(() => {});+ expect(provider.installationId).toBe(100);+ expect(minted.filter(path => path.endsWith('/access_tokens'))).toEqual(['/app/installations/100/access_tokens', '/app/installations/100/access_tokens']);+ // Moving the PEM keeps the identity; the pin still decides.+ installation = 100;+ const moved = join(home, `moved-${randomUUID().slice(0, 8)}.pem`);+ writeFileSync(moved, privateKey.export({ type: 'pkcs1', format: 'pem' }));+ const movedConfig = { ...config, gh_app_pem_path: moved };+ expect(connectorIdentity('github', movedConfig, f.dir).digest).toBe(connectorIdentity('github', config, f.dir).digest);+ }+}), 180_000);++test('--reset-checkpoint re-walks once: newly covered items import, unchanged pages take no admission, the pin is kept; non-connector sources refuse', async () => withEnv(env, async () => {+ for (const engine of engines) {+ const f = await source(engine, googleConfig);+ const listing = [contact('first', 'First Example')];+ const { fetcher, calls } = people(() => listing);+ expect((await google(engine, f, fetcher)).added).toBe(1);+ // Provider now has an item only a full walk reveals (like a widened history window).+ listing.push(contact('second', 'Second Example'));+ await disposePersistenceConsumer(engine);+ expect((await google(engine, f, fetcher)).added).toBe(0);+ let before = await mark(engine, f.id);+ calls.length = 0;+ const reset = await google(engine, f, fetcher, googleConfig.g_account, { resetCheckpoint: true });+ expect(reset.added).toBe(1);+ expect(calls.some(url => url.includes('syncToken'))).toBe(false);+ const pages = (await since(engine, f.id, before)).filter(row => String(row.intent?.kind).endsWith('_import'));+ expect(pages.map(row => row.slug)).toEqual(['people/second-example']);+ const state = await readManagedConnectorState(engine, f.id, await incarnation(engine, f.id));+ expect(state.account).toEqual({ kind: 'google', email: googleConfig.g_account });+ // The re-walk saved a fresh cursor (it did not replay an older committed checkpoint), so the next run is incremental.+ await disposePersistenceConsumer(engine);+ calls.length = 0;+ await google(engine, f, fetcher);+ expect(calls.some(url => url.includes('syncToken=contacts-stable'))).toBe(true);+ await disposePersistenceConsumer(engine);+ before = await mark(engine, f.id);+ await google(engine, f, fetcher, googleConfig.g_account, { resetCheckpoint: true });+ expect((await since(engine, f.id, before)).filter(row => String(row.intent?.kind).endsWith('_import'))).toHaveLength(0);+ // A Git-backed source is not a connector.+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ const gitId = `git-${randomUUID().slice(0, 8)}`;+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [gitId, join(home, gitId)]);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ await expect(performSync(engine, { sourceId: gitId, resetCheckpoint: true, noPull: true })).rejects.toMatchObject({ code: 'invalid_params' });+ }+}), 180_000);++test('freshness: a quiet run with an unchanged cursor stamps last_sync_at under the lease so gbrain waiting stays fresh; a failed sweep does not stamp', async () => withEnv(env, async () => {+ for (const engine of engines) {+ const f = await source(engine, googleConfig);+ let fail = false;+ const { fetcher } = people(() => [contact('first', 'First Example')], { fail: () => fail });+ await google(engine, f, fetcher);+ const stamp = async () => (await engine.executeRaw<{ at: string }>('SELECT last_sync_at::text AS at FROM sources WHERE id=$1', [f.id]))[0].at;+ await engine.executeRaw("UPDATE sources SET last_sync_at=now()-interval '2 days' WHERE id=$1", [f.id]).catch(async () => {+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw("UPDATE sources SET last_sync_at=now()-interval '2 days' WHERE id=$1", [f.id]);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ });+ const old = await stamp();+ await disposePersistenceConsumer(engine);+ const before = await mark(engine, f.id);+ expect((await google(engine, f, fetcher)).status).toBe('up_to_date');+ expect(await since(engine, f.id, before)).toHaveLength(0);+ const fresh = await stamp();+ expect(new Date(fresh).getTime()).toBeGreaterThan(new Date(old).getTime());+ const waiting = await handleToolCall(engine, 'open_loops', { group_by: 'counterparty', limit: 3 }, { sourceId: ALL_SOURCES }) as { sources?: Array<{ id: string; stale: boolean }> };+ expect(waiting.sources?.find(row => row.id === f.id)?.stale ?? false).toBe(false);+ fail = true;+ expect((await google(engine, f, fetcher)).status).toBe('partial');+ expect(await stamp()).toBe(fresh);+ const status = (await readConnectorSourceStatuses(engine)).get(f.id)!;+ expect(status.upgrade_recovery).toBe('none');+ }+}), 180_000);++test('run counts: sources status reports the second run of the two-cycle fixture as zero admissions and N skipped unchanged', async () => withEnv(env, async () => {+ for (const engine of engines) {+ const f = await source(engine, googleConfig);+ const all = () => [contact('first', 'First Example'), contact('second', 'Second Example'), contact('third', 'Third Example')];+ const rewalk = async (url: string) => {+ if (url.includes('/settings/sendAs')) return json({ sendAs: [] });+ return json({ connections: all(), nextSyncToken: 'contacts-stable' });+ };+ await google(engine, f, rewalk);+ expect((await readConnectorSourceStatuses(engine)).get(f.id)!.last_run).toMatchObject({ page_admissions: 3, skipped_unchanged: 0 });+ await disposePersistenceConsumer(engine);+ await google(engine, f, rewalk);+ expect((await readConnectorSourceStatuses(engine)).get(f.id)!.last_run).toMatchObject({+ page_admissions: 0, skipped_unchanged: 3, pending: 0, checkpoint_admissions: 0, stopped_on_wait_budget: false });+ }+}), 180_000);++test('pending set: a pending write that later fails is re-fetched under a new request id without --retry-failed; one that commits is not re-fetched', async () => withEnv(env, async () => {+ for (const engine of engines) for (const outcome of ['fails', 'commits'] as const) {+ const f = await boundSource(engine, githubConfig);+ await engine.executeRaw("UPDATE persistence_worktrees SET state='draining' WHERE id=$1::uuid", [f.binding.worktree_id]);+ const run = () => runGitHubSync(engine, f.id, parseGitHubSourceConfig(githubConfig, f.dir), { ...options, githubItem: { repo: 'acme-example/app', number: 1, kind: 'issue' } }, githubFetch());+ expect(await run()).toMatchObject({ status: 'partial', reason: 'writer_pending' });+ const [entry] = await connectorPendingSet(engine, f.id);+ const [accepted] = await engine.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE source_id=$1 AND request_id=$2::uuid', [f.id, entry.requestId]);+ await disposePersistenceConsumer(engine);+ const path = join(f.dir, 'gh/acme-example/app/1.md');+ if (outcome === 'fails') mkdirSync(dirname(path), { recursive: true });+ if (outcome === 'fails') writeFileSync(path, '---\ntitle: Operator file\n---\nAn unindexed operator file occupies the path.\n');+ await engine.executeRaw("UPDATE persistence_worktrees SET state='active' WHERE id=$1::uuid", [f.binding.worktree_id]);+ startPersistenceConsumer(engine, { engine: engine.kind });+ expect((await waitForWrite(engine, accepted, { engine: engine.kind }, 20_000)).state).toBe(outcome === 'fails' ? 'conflict' : 'committed');+ if (outcome === 'fails') {+ rmSync(path);+ // A targeted refresh of a different item enumerates nothing else, so it keeps the failed entry for its own retry.+ await disposePersistenceConsumer(engine);+ await runGitHubSync(engine, f.id, parseGitHubSourceConfig(githubConfig, f.dir), { ...options, githubItem: { repo: 'acme-example/app', number: 2, kind: 'issue', deleted: true } }, githubFetch());+ expect((await connectorPendingSet(engine, f.id)).map(pending => pending.requestId)).toEqual([accepted.request_id]);+ }+ await disposePersistenceConsumer(engine);+ const before = await mark(engine, f.id);+ expect((await run()).status).not.toBe('partial');+ const pages = (await since(engine, f.id, before)).filter(row => String(row.intent?.kind).endsWith('_import'));+ if (outcome === 'fails') {+ expect(pages).toHaveLength(1);+ expect(pages[0]).toMatchObject({ state: 'committed' });+ expect(pages[0].request_id).not.toBe(accepted.request_id);+ expect(pages[0].intent?.retryOf).toBe(accepted.request_id);+ } else expect(pages).toHaveLength(0);+ expect(await connectorPendingSet(engine, f.id)).toEqual([]);+ expect(existsSync(path)).toBe(true);+ }+}), 180_000);++test('pending set: a committed-then-compacted pending receipt and a crash before the checkpoint cost no page admission on the next run; duplicates in one sweep admit once', async () => withEnv(env, async () => {+ for (const engine of engines) {+ const f = await boundSource(engine, googleConfig);+ await engine.executeRaw("UPDATE persistence_worktrees SET state='draining' WHERE id=$1::uuid", [f.binding.worktree_id]);+ const dup = async (url: string) => url.includes('/settings/sendAs') ? json({ sendAs: [] })+ : json({ connections: [contact('first', 'First Example'), contact('first', 'First Example')], nextSyncToken: 'contacts-dup' });+ expect(await google(engine, f, dup)).toMatchObject({ status: 'partial', reason: 'writer_pending' });+ const imports = await engine.executeRaw<WriteRequest>("SELECT * FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='connector_v2_import'", [f.id]);+ expect(imports).toHaveLength(1);+ await disposePersistenceConsumer(engine);+ await engine.executeRaw("UPDATE persistence_worktrees SET state='active' WHERE id=$1::uuid", [f.binding.worktree_id]);+ startPersistenceConsumer(engine, { engine: engine.kind });+ expect((await waitForWrite(engine, imports[0], { engine: engine.kind }, 20_000)).state).toBe('committed');+ await disposePersistenceConsumer(engine);+ await engine.executeRaw("UPDATE persistence_requests SET completed_at=now()-interval '31 days' WHERE source_id=$1", [f.id]);+ await compactWriteReceipts(engine);+ const before = await mark(engine, f.id);+ expect((await google(engine, f, dup)).status).not.toBe('partial');+ expect((await since(engine, f.id, before)).filter(row => String(row.intent?.kind).endsWith('_import'))).toHaveLength(0);+ expect(await connectorPendingSet(engine, f.id)).toEqual([]);+ }+}), 180_000);++test('mixed versions: a v2 receipt refused by an old consumer names the consumer upgrade; permission_denied is never relabeled', async () => {+ const receipt = (error_code: string, kind: string) => ({ id: randomUUID(), request_id: randomUUID(), operation: 'submit_job', source_id: 'connector-example', state: 'failed',+ error_code, error_message: 'refused', intent: { kind }, created_at: new Date().toISOString(), updated_at: new Date().toISOString() }) as unknown as WriteRequest;+ const refusal = (row: WriteRequest) => { try { writeResponse(row); } catch (error) { return error as { code: string; suggestion: string; detail?: string; docs?: string }; } throw new Error('expected refusal'); };+ const old = refusal(receipt('unsupported_mutation_protocol', 'connector_v2_import'));+ expect(old).toMatchObject({ code: 'unsupported_mutation_protocol', detail: 'consumer_upgrade_required', docs: 'docs/guides/write-refusals.md#unsupported-mutation-protocol' });+ expect(old.suggestion).toContain('gbrain upgrade on every consumer and worktree-owner host');+ for (const kind of ['connector_v2_import', 'managed_sync_import']) {+ const denied = refusal(receipt('permission_denied', kind));+ expect(denied.code).toBe('permission_denied');+ expect(denied.detail).toBeUndefined();+ expect(denied.suggestion).toBe('Inspect this receipt before submitting a new request_id.');+ }+ // A binary that predates the v2 namespace falls through to the same code for any kind it does not know.+ await expect(preparePersistedMutation({} as BrainEngine, receipt('', 'connector_v3_import') as WriteRequest & { operation: string }, { engine: 'pglite' }))+ .rejects.toMatchObject({ code: 'unsupported_mutation_protocol' });+});++test('mixed versions: a retired managed_connector_* intent fails connector_intent_outdated, pre_upgrade before the cutoff and naming the host upgrade after it', async () => withEnv(env, async () => {+ for (const engine of engines) for (const phase of ['pre_upgrade', 'post_cutoff'] as const) {+ const f = await source(engine, googleConfig);+ const { fetcher } = people(() => [contact('first', 'First Example')]);+ await google(engine, f, fetcher);+ const [template] = await engine.executeRaw<WriteRequest>("SELECT * FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='connector_v2_import' LIMIT 1", [f.id]);+ await disposePersistenceConsumer(engine);+ await engine.executeRaw("DELETE FROM op_checkpoints WHERE op=$1 AND fingerprint='v2-cutoff'", [CONNECTOR_MIGRATION_OP]);+ const cutoff = phase === 'pre_upgrade' ? "now()+interval '1 hour'" : "now()-interval '1 hour'";+ await engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES($1,'v2-cutoff',jsonb_build_array(jsonb_build_object('cutoff',(${cutoff})::text)))`, [CONNECTOR_MIGRATION_OP]);+ const intent = { ...template.intent, kind: 'managed_connector_import', checkpointKey: 'legacy-raw-config-key' };+ const row = await admitWrite(engine, { requestId: randomUUID(), operation: 'submit_job', sourceId: f.id, sourceIncarnation: template.source_incarnation,+ slug: template.slug, pageId: template.page_id, worktreeId: template.worktree_id ?? undefined, principal: { kind: template.principal_kind, id: template.principal_id },+ authority: template.authority, callerIntent: intent, intent } as never);+ startPersistenceConsumer(engine, { engine: engine.kind });+ const done = await waitForWrite(engine, row, { engine: engine.kind }, 20_000);+ expect(done).toMatchObject({ state: 'failed', error_code: 'connector_intent_outdated' });+ let delivered: { detail?: string; suggestion?: string; docs?: string } = {};+ try { writeResponse(done); } catch (error) { delivered = error as typeof delivered; }+ expect(delivered.docs).toBe('docs/guides/write-refusals.md#connector-intent-outdated');+ if (phase === 'pre_upgrade') {+ expect(delivered.detail).toBe('pre_upgrade');+ expect(delivered.suggestion).toContain('No host upgrade is needed');+ } else expect(delivered.suggestion).toContain('Upgrade gbrain on the host that runs connector jobs');+ await disposePersistenceConsumer(engine);+ }+}), 180_000);++/** A committed legacy checkpoint receipt, as a pre-upgrade connector host left it. */+async function legacyCheckpoint(engine: BrainEngine, f: { id: string }, key: string, state: unknown, compacted = false) {+ const [template] = await engine.executeRaw<WriteRequest>("SELECT * FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='connector_v2_checkpoint' ORDER BY sequence DESC LIMIT 1", [f.id]);+ await engine.executeRaw("INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES('managed-connector',$1,$2::text::jsonb)", [key, JSON.stringify([{ generation: 1, state }])]);+ const intent = { ...template.intent, kind: 'managed_connector_checkpoint', checkpointKey: key, configHash: 'legacy-raw-config-hash' };+ const row = await admitWrite(engine, { requestId: randomUUID(), operation: 'submit_job', sourceId: f.id, sourceIncarnation: template.source_incarnation,+ slug: template.slug, pageId: null, worktreeId: template.worktree_id ?? undefined, principal: { kind: template.principal_kind, id: template.principal_id },+ authority: template.authority, callerIntent: intent, intent } as never);+ await engine.transaction(async tx => {+ await declarePersistenceProtocol(tx);+ await tx.executeRaw(`UPDATE persistence_requests SET state='committed',completed_at=now(),outcome='{"status":"checkpointed"}'::jsonb${compacted ? ',compacted=true,intent=NULL' : ''} WHERE id=$1::uuid`, [row.id]);+ });+ return row;+}++test('migration 176: re-keys the newest committed checkpoint, re-walks a compacted one once, removes orphans, keeps referenced and newer rows, and a rerun changes nothing', async () => withEnv(env, async () => {+ for (const engine of engines) {+ const live = await source(engine, googleConfig), compacted = await source(engine, googleConfig), archived = await source(engine, googleConfig);+ const { fetcher, calls } = people(() => [contact('first', 'First Example')]);+ await google(engine, live, fetcher); await google(engine, compacted, fetcher); await google(engine, archived, fetcher);+ await disposePersistenceConsumer(engine);+ // Pretend the sources were last checkpointed by a pre-upgrade binary under raw-config keys.+ for (const f of [live, compacted, archived]) {+ await engine.executeRaw("DELETE FROM op_checkpoints WHERE op IN ('managed-connector','managed-connector-state') AND fingerprint IN ($1,$2)",+ [connectorCheckpointKey(f.id, await incarnation(engine, f.id), connectorIdentity('google', googleConfig, f.dir)), '']);+ await engine.executeRaw("DELETE FROM op_checkpoints WHERE op='managed-connector-state'");+ }+ const liveKey = `legacy-live-${randomUUID()}`;+ await legacyCheckpoint(engine, live, `legacy-older-${randomUUID()}`, { contacts_sync_token: 'older-token' });+ await legacyCheckpoint(engine, live, liveKey, { contacts_sync_token: 'legacy-token' });+ await legacyCheckpoint(engine, compacted, `legacy-compacted-${randomUUID()}`, { contacts_sync_token: 'lost-token' }, true);+ await legacyCheckpoint(engine, archived, `legacy-archived-${randomUUID()}`, { contacts_sync_token: 'archived-token' });+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw('UPDATE sources SET archived=true WHERE id=$1', [archived.id]);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const orphan = `legacy-orphan-${randomUUID()}`, newer = `legacy-newer-${randomUUID()}`, referenced = `legacy-referenced-${randomUUID()}`;+ await engine.executeRaw("INSERT INTO op_checkpoints(op,fingerprint,completed_keys,updated_at) VALUES('managed-connector',$1,'[]'::jsonb,now()-interval '9 days'),('managed-connector',$2,'[]'::jsonb,now()+interval '1 hour'),('managed-connector',$3,'[]'::jsonb,now()-interval '9 days')", [orphan, newer, referenced]);+ await engine.executeRaw("INSERT INTO op_checkpoints(op,fingerprint,completed_keys,updated_at) VALUES('managed-connector-retry',$1,$2::text::jsonb,now()-interval '9 days')",+ [randomUUID(), JSON.stringify([{ checkpointKey: orphan, requestId: randomUUID(), baseRequestId: randomUUID() }])]);+ const [template] = await engine.executeRaw<WriteRequest>("SELECT * FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='connector_v2_import' LIMIT 1", [live.id]);+ await admitWrite(engine, { requestId: randomUUID(), operation: 'submit_job', sourceId: live.id, sourceIncarnation: template.source_incarnation, slug: template.slug,+ pageId: template.page_id, principal: { kind: template.principal_kind, id: template.principal_id }, authority: template.authority,+ callerIntent: { ...template.intent, kind: 'managed_connector_import', checkpointKey: referenced }, intent: { ...template.intent, kind: 'managed_connector_import', checkpointKey: referenced } } as never);+ const lines: string[] = [];+ const report = await migrateConnectorCheckpoints(engine, line => lines.push(line));+ expect(report.rekeyed.map(row => row.source_id).sort()).toEqual([live.id, archived.id].sort());+ // An archived source keeps its cursor under the stable key, so a restore resumes it.+ const archivedKey = connectorCheckpointKey(archived.id, await incarnation(engine, archived.id), connectorIdentity('google', googleConfig, archived.dir));+ expect(await engine.executeRaw("SELECT fingerprint FROM op_checkpoints WHERE op='managed-connector' AND fingerprint=$1", [archivedKey])).toHaveLength(1);+ expect(report.rewalking).toEqual([compacted.id]);+ expect(lines.join('\n')).toContain(`${live.id}: resumed from pre-upgrade checkpoint of`);+ expect(lines.join('\n')).toContain(`to re-walk: gbrain sync --source ${live.id} --reset-checkpoint`);+ const fingerprints = (await engine.executeRaw<{ op: string; fingerprint: string }>("SELECT op,fingerprint FROM op_checkpoints WHERE op IN ('managed-connector','managed-connector-retry')")).map(row => row.fingerprint);+ expect(fingerprints).not.toContain(orphan);+ expect(fingerprints).toContain(newer);+ expect(fingerprints).toContain(referenced);+ const liveNew = connectorCheckpointKey(live.id, await incarnation(engine, live.id), connectorIdentity('google', googleConfig, live.dir));+ const [copied] = await engine.executeRaw<{ completed_keys: Array<{ state: { contacts_sync_token: string } }> }>("SELECT completed_keys FROM op_checkpoints WHERE op='managed-connector' AND fingerprint=$1", [liveNew]);+ expect(copied.completed_keys[0].state.contacts_sync_token).toBe('legacy-token');+ const statuses = await readConnectorSourceStatuses(engine);+ expect(statuses.get(live.id)).toMatchObject({ upgrade_recovery: 'resumed' });+ expect(statuses.get(live.id)!.resumed_from).not.toBeNull();+ expect(statuses.get(compacted.id)).toMatchObject({ upgrade_recovery: 'rewalking_once' });+ const snapshot = await engine.executeRaw("SELECT op,fingerprint,completed_keys FROM op_checkpoints WHERE op LIKE 'managed-connector%' ORDER BY op,fingerprint");+ expect(await migrateConnectorCheckpoints(engine, () => {})).toEqual({ rekeyed: [], rewalking: [], removed: { checkpoints: 0, retries: 0 } });+ expect(await engine.executeRaw("SELECT op,fingerprint,completed_keys FROM op_checkpoints WHERE op LIKE 'managed-connector%' ORDER BY op,fingerprint")).toEqual(snapshot);+ // The first post-upgrade runs: the live source resumes its legacy cursor and is pinned with unverified continuity; the compacted one re-walks once.+ calls.length = 0;+ await google(engine, live, fetcher);+ expect(calls.some(url => url.includes('syncToken=legacy-token'))).toBe(true);+ expect((await readConnectorSourceStatuses(engine)).get(live.id)).toMatchObject({ upgrade_recovery: 'resumed', continuity_unverified: true, account_pinned: true });+ await google(engine, compacted, fetcher);+ expect((await readConnectorSourceStatuses(engine)).get(compacted.id)).toMatchObject({ upgrade_recovery: 'none' });+ }+}), 240_000);++test('doctor counts a checkpoint orphaned by a content change once it is 7 days old; repair connector-checkpoints removes it and never copies', async () => withEnv(env, async () => {+ for (const engine of engines) {+ const f = await source(engine, googleConfig);+ const { fetcher } = people(() => [contact('first', 'First Example')]);+ await google(engine, f, fetcher);+ const oldKey = connectorCheckpointKey(f.id, await incarnation(engine, f.id), connectorIdentity('google', googleConfig, f.dir));+ const widened = { ...googleConfig, g_history_days: 365 };+ expect(await engine.updateSourceConfig(f.id, { g_history_days: 365 })).toBe(true);+ await disposePersistenceConsumer(engine);+ await google(engine, f, fetcher, googleConfig.g_account, {}, widened);+ const count = async () => ((await checkConnectorCheckpoints(engine)).details as { count: number }).count;+ const before = await count();+ await engine.executeRaw("UPDATE op_checkpoints SET updated_at=now()-interval '8 days' WHERE op='managed-connector' AND fingerprint=$1", [oldKey]);+ expect(await count()).toBe(before + 1);+ const aged = await checkConnectorCheckpoints(engine);+ expect(aged.status).toBe('warn');+ expect(aged.message).toContain('gbrain repair connector-checkpoints');+ const ctx = { engine, config: { engine: engine.kind }, remote: false, logger: console } as unknown as OperationContext;+ const scope = await resolveRepairScope(engine);+ const dry = await runRepair(ctx, connectorCheckpointsRepair, scope, { apply: false });+ expect(dry.affected).toBeGreaterThanOrEqual(1);+ expect(dry.cost).toMatchObject({ lifetime_ids: 0, embedding_pages: 0 });+ const applied = await runRepair(ctx, connectorCheckpointsRepair, scope, { apply: true });+ expect(applied.applied).toBe(dry.affected);+ expect(await engine.executeRaw("SELECT fingerprint FROM op_checkpoints WHERE op='managed-connector' AND fingerprint=$1", [oldKey])).toHaveLength(0);+ expect((await checkConnectorCheckpoints(engine)).status).toBe('ok');+ const liveKey = connectorCheckpointKey(f.id, await incarnation(engine, f.id), connectorIdentity('google', widened, f.dir));+ expect(await engine.executeRaw("SELECT fingerprint FROM op_checkpoints WHERE op='managed-connector' AND fingerprint=$1", [liveKey])).toHaveLength(1);+ }+}), 180_000);++test('#5470 connector kernel: a safe-chunk reseal, projection lag, a pending contextual-mode page, a deleted page and a changed page admit; a carried-forward timeline row does not defeat the skip', async () => withEnv(env, async () => {+ for (const engine of engines) {+ const f = await boundSource(engine, googleConfig);+ let org = 'Example Org', tombstone = false;+ const rewalk = async (url: string) => url.includes('/settings/sendAs') ? json({ sendAs: [] })+ : json({ connections: [tombstone ? { resourceName: 'people/first', metadata: { deleted: true } } : { ...contact('first', 'First Example'), organizations: [{ name: org }] }], nextSyncToken: 'contacts-stable' });+ const slug = 'people/first-example';+ const admitted = async (change: () => Promise<unknown>) => {+ await change();+ await disposePersistenceConsumer(engine);+ const before = await mark(engine, f.id);+ await google(engine, f, rewalk);+ return (await since(engine, f.id, before)).filter(row => row.slug === slug && String(row.intent?.kind).endsWith('_import')).length;+ };+ await google(engine, f, rewalk);+ // A database-only timeline row (as extract --stale records one) is carried forward into the connector+ // render (#5567): the first re-walk may materialize it into the page once; it survives, and later re-walks skip.+ const summaries = () => engine.executeRaw<{ summary: string }>('SELECT t.summary FROM timeline_entries t JOIN pages p ON p.id=t.page_id WHERE p.source_id=$1 AND p.slug=$2', [f.id, slug]);+ expect(await admitted(() => engine.transaction(tx => withCoordinatedWrite(tx, [f.id], () =>+ tx.addTimelineEntry(slug, { date: '2026-01-02', summary: 'Met to review the example plan', source: 'meetings/2026-01-02' }, { sourceId: f.id }))))).toBeLessThanOrEqual(1);+ expect(await admitted(async () => {})).toBe(0);+ expect(await summaries()).toEqual([{ summary: 'Met to review the example plan' }]);+ expect(await admitted(() => engine.executeRaw('UPDATE pages SET text_projection_revision=gen_random_uuid() WHERE source_id=$1 AND slug=$2', [f.id, slug]))).toBe(1);+ await engine.executeRaw('UPDATE pages SET text_projection_revision=knowledge_revision WHERE source_id=$1 AND slug=$2', [f.id, slug]);+ expect(await admitted(async () => {})).toBe(0);+ // Below the safe-chunk fence: asked of the kernel directly, since the owner's projection worker may re-seal it before a re-walk.+ await engine.executeRaw('UPDATE pages SET chunker_version=1 WHERE source_id=$1 AND slug=$2', [f.id, slug]);+ const snapshot = await engine.readPageSnapshot(slug, { sourceId: f.id, includeDeleted: true });+ const file = { root: f.dir, path: join(f.dir, `${slug}.md`), content: existsSync(join(f.dir, `${slug}.md`)) ? readFileSync(join(f.dir, `${slug}.md`), 'utf8') : '' };+ const prepared = { noop: true, observedRevision: snapshot!.revision, apply: async () => ({}), file };+ expect(await inspectUnchanged(engine, { prepared, snapshot, sourcePath: `${slug}.md`, databaseOnly: false })).toMatchObject({ admitReason: 'projection_work', projectionWorkRequired: true });+ await engine.executeRaw('UPDATE pages SET chunker_version=4 WHERE source_id=$1 AND slug=$2', [f.id, slug]);+ expect((await inspectUnchanged(engine, { prepared, snapshot, sourcePath: `${slug}.md`, databaseOnly: false })).admitReason).toBeUndefined();+ // A publication that would queue embedding is not skipped while chunks lack vectors.+ expect(await inspectUnchanged(engine, { prepared, snapshot, sourcePath: `${slug}.md`, databaseOnly: false, embeddingRequested: true })).toMatchObject({ admitReason: 'projection_work' });+ // An embedded page without a contextual mode awaits the contextual-mode repair: never skipped.+ const vector = `[${Array(1536).fill(0.01).join(',')}]`;+ await engine.executeRaw('UPDATE content_chunks SET embedding=$2::text::vector WHERE page_id=(SELECT id FROM pages WHERE source_id=$1 AND slug=$3)', [f.id, vector, slug]);+ await engine.executeRaw('UPDATE pages SET contextual_retrieval_mode=NULL WHERE source_id=$1 AND slug=$2', [f.id, slug]);+ expect(await inspectUnchanged(engine, { prepared, snapshot, sourcePath: `${slug}.md`, databaseOnly: false })).toMatchObject({ admitReason: 'projection_work' });+ await engine.executeRaw('UPDATE content_chunks SET embedding=NULL WHERE page_id=(SELECT id FROM pages WHERE source_id=$1 AND slug=$2)', [f.id, slug]);+ // The provider tombstones the contact, then lists it again: resurrecting a deleted page is always admitted.+ tombstone = true;+ await disposePersistenceConsumer(engine);+ await google(engine, f, rewalk);+ expect(await engine.getPage(slug, { sourceId: f.id })).toBeNull();+ tombstone = false;+ expect(await admitted(async () => {})).toBe(1);+ expect(await engine.getPage(slug, { sourceId: f.id })).not.toBeNull();+ org = 'Renamed Example Org';+ expect(await admitted(async () => {})).toBe(1);+ }+}), 240_000);++test('connector state row: a lost lease writes nothing; a new source incarnation starts empty', async () => withEnv(env, async () => {+ for (const engine of engines) {+ const f = await source(engine, googleConfig);+ const cfg = parseGoogleSourceConfig(googleConfig, f.dir);+ const { beginConnectorSync } = await import('../src/core/persistence/connector-sync.ts');+ const lost = { handle: { id: `gbrain-sync:${f.id}`, acquisitionToken: randomUUID(), acquiredAt: '1' }, signal: new AbortController().signal };+ await expect(beginConnectorSync(engine, f.id, 'google', cfg, options, lost as never)).rejects.toMatchObject({ name: 'LockStolenError' });+ expect(await engine.executeRaw("SELECT fingerprint FROM op_checkpoints WHERE op='managed-connector-state' AND completed_keys->0->'last_run' IS NOT NULL AND completed_keys::text LIKE '%' || $1 || '%'", [f.id])).toHaveLength(0);+ expect((await readManagedConnectorState(engine, f.id, await incarnation(engine, f.id))).account).toBeNull();+ const { fetcher } = people(() => [contact('first', 'First Example')]);+ await google(engine, f, fetcher);+ const first = await incarnation(engine, f.id);+ expect((await readManagedConnectorState(engine, f.id, first)).account).not.toBeNull();+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw('DELETE FROM sources WHERE id=$1', [f.id]);+ await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,$3::text::jsonb)', [f.id, f.dir, JSON.stringify(googleConfig)]);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const second = await incarnation(engine, f.id);+ expect(second).not.toBe(first);+ const fresh = await readManagedConnectorState(engine, f.id, second);+ expect(fresh).toMatchObject({ account: null, pending: [], upgrade_recovery: 'none', last_run: null });+ }+}), 180_000);++test('pending set: a checkpoint still pending at the end of a run is recorded and resolved first next run; a delta run keeps an unreached failure that only a full sweep drops', async () => withEnv(env, async () => {+ for (const engine of engines) {+ const f = await boundSource(engine, googleConfig);+ let token = 0;+ const { fetcher } = people(() => [contact('first', 'First Example')], { token: () => `contacts-${++token}` });+ await google(engine, f, fetcher);+ await engine.executeRaw("UPDATE persistence_worktrees SET state='draining' WHERE id=$1::uuid", [f.binding.worktree_id]);+ await disposePersistenceConsumer(engine);+ expect(await google(engine, f, fetcher)).toMatchObject({ status: 'partial', reason: 'writer_pending' });+ const [checkpoint] = await connectorPendingSet(engine, f.id);+ expect(checkpoint).toMatchObject({ itemRef: '__managed_connector_checkpoint__' });+ await disposePersistenceConsumer(engine);+ await engine.executeRaw("UPDATE persistence_worktrees SET state='active' WHERE id=$1::uuid", [f.binding.worktree_id]);+ expect((await google(engine, f, fetcher)).status).not.toBe('partial');+ expect(await connectorPendingSet(engine, f.id)).toEqual([]);+ }+ for (const engine of engines) {+ const f = await boundSource(engine, githubConfig);+ await engine.executeRaw("UPDATE persistence_worktrees SET state='draining' WHERE id=$1::uuid", [f.binding.worktree_id]);+ const run = (fetch: ReturnType<typeof githubFetch>, extra: object = {}) => runGitHubSync(engine, f.id, parseGitHubSourceConfig(githubConfig, f.dir), { ...options, ...extra }, fetch);+ expect(await run(githubFetch())).toMatchObject({ status: 'partial', reason: 'writer_pending' });+ const [entry] = await connectorPendingSet(engine, f.id);+ const [accepted] = await engine.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE request_id=$1::uuid', [entry.requestId]);+ await disposePersistenceConsumer(engine);+ const path = join(f.dir, 'gh/acme-example/app/1.md');+ mkdirSync(dirname(path), { recursive: true });+ writeFileSync(path, '---\ntitle: Operator file\n---\nAn unindexed operator file occupies the path.\n');+ await engine.executeRaw("UPDATE persistence_worktrees SET state='active' WHERE id=$1::uuid", [f.binding.worktree_id]);+ startPersistenceConsumer(engine, { engine: engine.kind });+ expect((await waitForWrite(engine, accepted, { engine: engine.kind }, 20_000)).state).toBe('conflict');+ rmSync(path);+ await disposePersistenceConsumer(engine);+ // The provider no longer lists the item: a delta run cannot tell deletion from absence, so it keeps the entry.+ expect((await run(githubFetch({ deleted: true }))).status).not.toBe('partial');+ expect((await connectorPendingSet(engine, f.id)).map(pending => pending.requestId)).toEqual([accepted.request_id]);+ await disposePersistenceConsumer(engine);+ await run(githubFetch({ deleted: true }), { full: true });+ expect(await connectorPendingSet(engine, f.id)).toEqual([]);+ expect((await readConnectorSourceStatuses(engine)).get(f.id)!.last_run).toMatchObject({ dropped_upstream: 1 });+ }+}), 240_000);diff --git a/test/contextual-retrieval-service-pure.test.ts b/test/contextual-retrieval-service-pure.test.tsindex 58d46bbd1c..812959668a 100644--- a/test/contextual-retrieval-service-pure.test.ts+++ b/test/contextual-retrieval-service-pure.test.ts@@ -123,19 +123,27 @@ describe('computeCorpusGeneration', () => {describe('inline import contextual synopsis containment', () => {test('uses the shared default without starting paid synopsis generation', () => {+ // The inline import's mode resolution lives in import-contextual-mode.ts (#5621 peel, shared with repair).const importSource = readFileSync(new URL('../src/core/import-file.ts', import.meta.url),'utf8',);+ // test-reads-source-ok[structural]: the #5621 peel moved the inline mode resolution here; pins the paid-synopsis containment.+ const resolverSource = readFileSync(+ new URL('../src/core/import-contextual-mode.ts', import.meta.url),+ 'utf8',+ );- expect(importSource).toContain(+ expect(importSource).toContain('await resolveImportContextualMode(');+ expect(resolverSource).toContain("import { DEFAULT_SYNOPSIS_MODEL } from './page-summary.ts';",);- expect(importSource).toContain('synopsisModel: DEFAULT_SYNOPSIS_MODEL');- expect(importSource).toContain(+ expect(resolverSource).toContain('synopsisModel: DEFAULT_SYNOPSIS_MODEL');+ expect(resolverSource).toContain("effectiveCRMode = resolution.mode === 'per_chunk_synopsis' ? 'title' : resolution.mode;",);expect(importSource).not.toContain('generatePerChunkSynopsis');+ expect(resolverSource).not.toContain('generatePerChunkSynopsis');});});diff --git a/test/cycle-phase-containment.test.ts b/test/cycle-phase-containment.test.tsnew file mode 100644index 0000000000..e55a3e9ef4--- /dev/null+++ b/test/cycle-phase-containment.test.ts@@ -0,0 +1,122 @@+/**+ * Fix wave 3 (CEO E2 / Eng E-D15): cycle phase containment.+ *+ * Contract: a phase that throws returns a `fail` phase result carrying the+ * typed error and later phases in the same job still run; the job still+ * reports the failure. Cancellation, a lost cycle lease and budget exhaustion+ * are never contained. A contained failure after paid model calls counts in+ * doctor's dream_paid_loop check.+ */+import { afterAll, beforeAll, beforeEach, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { runCycle } from '../src/core/cycle.ts';+import { timeContainedPhase } from '../src/core/cycle/phase-containment.ts';+import { countDeadDreamSubmissions, resetDreamBreakerKey } from '../src/core/cycle/dream-breaker.ts';+import { dreamPaidLoopCheck } from '../src/commands/doctor/checks/dream-breaker.ts';+import { LockStolenError } from '../src/core/db-lock.ts';+import { BudgetExhausted } from '../src/core/budget/budget-tracker.ts';+import { chat, configureGateway, resetGateway, __setChatTransportForTests, type ChatResult } from '../src/core/ai/gateway.ts';+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { withEnv } from './helpers/with-env.ts';++let engine: PGLiteEngine;+const dataDir = mkdtempSync(join(tmpdir(), 'gbrain-containment-db-'));+beforeAll(async () => {+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} });+ engine = new PGLiteEngine();+ await engine.connect({ database_path: dataDir });+ await engine.initSchema();+}, 120_000);+afterAll(async () => {+ __setChatTransportForTests(null);+ await disposePersistenceConsumer(engine);+ await engine.disconnect();+ resetGateway();+ rmSync(dataDir, { recursive: true, force: true });+});+beforeEach(async () => {+ await engine.executeRaw("DELETE FROM config WHERE key LIKE 'dream.breaker.%'");+ await engine.executeRaw('DELETE FROM gbrain_cycle_locks');+});++const containment = () => ({ engine, sourceId: 'default' });+const paidCall = async () => {+ __setChatTransportForTests(async (): Promise<ChatResult> => ({ text: 'ok', blocks: [], stopReason: 'end',+ usage: { input_tokens: 10, output_tokens: 10, cache_read_tokens: 0, cache_creation_tokens: 0 }, model: 'stub:stub', providerId: 'stub' }));+ try { await chat({ messages: [{ role: 'user', content: 'x' }] }); } finally { __setChatTransportForTests(null); }+};++test('a throwing phase becomes a fail result carrying its typed error', async () => {+ const { result } = await timeContainedPhase(containment(), 'synthesize_concepts', async () => {+ throw Object.assign(new Error('This source has no designated canonical owner.'), { code: 'owner_unavailable' });+ });+ expect(result).toMatchObject({ phase: 'synthesize_concepts', status: 'fail',+ details: { contained: true, paid_model_calls: 0, paid_loop_recorded: false }, error: { code: 'owner_unavailable' } });+ expect(await countDeadDreamSubmissions(engine)).toEqual([]);+});++test('abort, a lost lease and budget exhaustion are never contained', async () => {+ const aborted = new AbortController(); aborted.abort();+ await expect(timeContainedPhase({ ...containment(), signal: aborted.signal }, 'embed', async () => { throw new Error('stopped'); }))+ .rejects.toThrow('stopped');+ const abortError = Object.assign(new Error('aborted'), { name: 'AbortError' });+ await expect(timeContainedPhase(containment(), 'embed', async () => { throw abortError; })).rejects.toBe(abortError);+ await expect(timeContainedPhase(containment(), 'sync', async () => { throw new LockStolenError('cycle-lock'); }))+ .rejects.toBeInstanceOf(LockStolenError);+ await expect(timeContainedPhase(containment(), 'consolidate', async () => {+ throw new BudgetExhausted('cap reached', { reason: 'cost', spent: 1, cap: 1 });+ })).rejects.toBeInstanceOf(BudgetExhausted);+});++test('a contained failure after paid model calls counts in dream_paid_loop until reset', async () => {+ for (let i = 0; i < 3; i++) {+ const { result } = await timeContainedPhase(containment(), 'synthesize_concepts', async () => {+ await paidCall();+ throw new Error('publication refused after synthesis');+ });+ expect(result.details).toMatchObject({ contained: true, paid_model_calls: 1, paid_loop_recorded: true });+ }+ expect(await countDeadDreamSubmissions(engine)).toMatchObject([{ base_key: 'dream:phase:synthesize_concepts:default', dead_submissions: 3 }]);+ const check = await dreamPaidLoopCheck(engine);+ expect(check.status).toBe('warn');+ expect(check.message).toContain('dream:phase:synthesize_concepts:default (3x)');+ await resetDreamBreakerKey(engine, 'dream:phase:synthesize_concepts:default');+ expect((await dreamPaidLoopCheck(engine)).status).toBe('ok');+});++test('runCycle: a refused synthesize_concepts no longer kills the job; the next phase runs and the job reports the failure', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-containment-'));+ const root = join(dir, 'brain'); mkdirSync(root);+ const sourceId = `contain-${randomUUID().slice(0, 8)}`;+ try {+ await withEnv({ GBRAIN_HOME: join(dir, 'home'), GBRAIN_SCHEMA_PACK: 'gbrain-creator', OPENAI_API_KEY: undefined, ANTHROPIC_API_KEY: undefined }, async () => {+ 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)', [sourceId, root]);+ await engine.setConfig('sync.write_through', 'false');+ for (const n of [1, 2]) {+ await submitPageMutation({ engine, sourceId, remote: false, config: { engine: 'pglite', embedding_disabled: true } as never,+ dryRun: false, logger: { info() {}, warn() {}, error() {} } }, { operation: 'put_page', params: { slug: `atoms/idea-${n}`,+ request_id: randomUUID(), content: `---\ntitle: Idea ${n}\ntype: atom\nvisibility: world\nconcepts: [moats]\n---\nAtom ${n}.` } });+ }+ // Write-through on with a filesystem root and no canonical owner: the+ // managed maintenance preflight refuses before any model work.+ await engine.setConfig('sync.write_through', 'true');+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const report = await runCycle(engine, { brainDir: root, sourceId, phases: ['synthesize_concepts', 'purge'] });+ const concepts = report.phases.find(p => p.phase === 'synthesize_concepts');+ expect(concepts).toMatchObject({ status: 'fail', details: { contained: true }, error: { code: 'owner_unavailable' } });+ expect(report.phases.find(p => p.phase === 'purge')?.status).toBe('ok');+ expect(report.status).toBe('partial');+ });+ } finally {+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.setConfig('sync.write_through', 'true');+ rmSync(dir, { recursive: true, force: true });+ }+});diff --git a/test/doctor-self-capture.test.ts b/test/doctor-self-capture.test.tsnew file mode 100644index 0000000000..fb092e0109--- /dev/null+++ b/test/doctor-self-capture.test.ts@@ -0,0 +1,95 @@+/**+ * self_capture doctor check (#5413): counts corpus files captured from+ * gbrain's own claude-cli sessions (classified) and files whose harness+ * transcript is gone (unclassifiable), prints copy-paste quarantine commands+ * and never moves or deletes anything.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { selfCaptureCheck } from '../src/commands/doctor/checks/self-capture.ts';+import { CLAUDE_CLI_CWD_PREFIX } from '../src/core/ai/providers/claude-cli-scratch.ts';++let engine: PGLiteEngine;+const root = mkdtempSync(join(tmpdir(), 'gbrain-self-capture-'));+const corpus = join(root, 'corpus');+const projects = join(root, 'claude', 'projects');++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ mkdirSync(corpus, { recursive: true });+ // A gbrain claude-cli scratch project holding two self sessions, and an ordinary project.+ const self = join(projects, `-tmp-${CLAUDE_CLI_CWD_PREFIX.replace(/[^a-z0-9]/gi, '-')}4242`);+ mkdirSync(self, { recursive: true });+ mkdirSync(join(projects, '-home-user-work'), { recursive: true });+ for (const id of ['self-a', 'self-b']) writeFileSync(join(self, `${id}.jsonl`), '{}\n');+ writeFileSync(join(projects, '-home-user-work', 'human-1.jsonl'), '{}\n');+ writeFileSync(join(corpus, 'self-a.txt'), 'self capture a');+ writeFileSync(join(corpus, 'self-a.txt.ingested'), '{}');+ writeFileSync(join(corpus, 'self-b.txt'), 'self capture b');+ writeFileSync(join(corpus, 'human-1.txt'), 'a real session');+ writeFileSync(join(corpus, 'pruned-9.txt'), 'harness transcript gone');+ mkdirSync(join(corpus, 'nested'), { recursive: true });+ writeFileSync(join(self, 'self-c.jsonl'), '{}\n');+ writeFileSync(join(corpus, 'nested', 'self-c.txt'), 'nested self capture');+}, 60_000);++afterAll(async () => {+ await engine.disconnect();+ rmSync(root, { recursive: true, force: true });+});++describe('self_capture doctor check', () => {+ test('ok when no session corpus is configured', async () => {+ const check = await selfCaptureCheck(engine, { projectsRoot: projects });+ expect(check).toMatchObject({ name: 'self_capture', status: 'ok' });+ });++ test('counts classified and unclassifiable files, prints quarantine commands, and moves nothing', async () => {+ await engine.setConfig('dream.synthesize.session_corpus_dir', corpus);+ const before = readdirSync(corpus).sort();+ const check = await selfCaptureCheck(engine, { projectsRoot: projects });+ expect(check.status).toBe('warn');+ expect(check.details).toMatchObject({ classified: 3, unclassifiable: 1, corpus_files: 5, count: 'exact' });+ expect([...check.details!.classified_sample as string[]].sort()).toEqual(['nested/self-c.txt', 'self-a.txt', 'self-b.txt']);+ expect(check.message).toContain('Nothing was moved or deleted');+ expect(check.message).toContain('mkdir -p');+ expect(readdirSync(corpus).sort()).toEqual(before);++ // The printed commands are copy-paste runnable and move the capture with its sidecar.+ const commands = check.details!.quarantine_commands as string[];+ execFileSync('sh', ['-c', commands.join(' && ')]);+ const quarantine = check.details!.quarantine_dir as string;+ expect(readdirSync(quarantine).sort()).toEqual(['nested', 'self-a.txt', 'self-a.txt.ingested', 'self-b.txt']);+ expect(readdirSync(join(quarantine, 'nested'))).toEqual(['self-c.txt']);+ expect(readdirSync(corpus).sort()).toEqual(['human-1.txt', 'nested', 'pruned-9.txt']);+ expect(existsSync(join(corpus, 'human-1.txt'))).toBe(true);++ const after = await selfCaptureCheck(engine, { projectsRoot: projects });+ expect(after).toMatchObject({ status: 'ok', details: { classified: 0, unclassifiable: 1 } });+ expect(after.message).toContain('cannot be decided');+ });++ test.skipIf(process.getuid?.() === 0)('an unreadable nested corpus directory makes health unknown, never an exact count', async () => {+ const locked = join(corpus, 'locked');+ mkdirSync(locked);+ writeFileSync(join(locked, 'self-a.txt'), 'hidden');+ chmodSync(locked, 0o000);+ try {+ await engine.setConfig('dream.synthesize.session_corpus_dir', corpus);+ const check = await selfCaptureCheck(engine, { projectsRoot: projects });+ expect(check).toMatchObject({ status: 'warn', details: { health: 'unknown', count: 'lower_bound', unreadable_dirs: 1 } });+ } finally { chmodSync(locked, 0o755); rmSync(locked, { recursive: true, force: true }); }+ });++ test('an unreadable or missing corpus directory reports unknown health, never an exact zero', async () => {+ await engine.setConfig('dream.synthesize.session_corpus_dir', join(root, 'missing-corpus'));+ const check = await selfCaptureCheck(engine, { projectsRoot: projects });+ expect(check).toMatchObject({ status: 'warn', details: { health: 'unknown', count: 'unknown' } });+ });+});diff --git a/test/e2e/connector-wave3.test.ts b/test/e2e/connector-wave3.test.tsnew file mode 100644index 0000000000..996f610773--- /dev/null+++ b/test/e2e/connector-wave3.test.ts@@ -0,0 +1,8 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++// Fix wave 3 lane A (#5686, #5470, #5600): the PostgreSQL arm of the connector identity, no-op kernel and pending-batch suites.+await registerPostgresTests(+ () => import('../connector-checkpoint-identity.test.ts'),+ () => import('../connector-wave3.test.ts'),+ () => import('../noop-kernel-paths.test.ts'),+);diff --git a/test/e2e/embed-stale-dry-run-restamp-5289-postgres.test.ts b/test/e2e/embed-stale-dry-run-restamp-5289-postgres.test.tsnew file mode 100644index 0000000000..6d506d42d7--- /dev/null+++ b/test/e2e/embed-stale-dry-run-restamp-5289-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../embed-stale-dry-run-restamp-5289.serial.test.ts'));diff --git a/test/e2e/embedding-migration-settle-postgres.test.ts b/test/e2e/embedding-migration-settle-postgres.test.tsnew file mode 100644index 0000000000..ef607b35eb--- /dev/null+++ b/test/e2e/embedding-migration-settle-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../embedding-migration-settle.serial.test.ts'));diff --git a/test/e2e/embedding-zero-norm-4616-postgres.test.ts b/test/e2e/embedding-zero-norm-4616-postgres.test.tsnew file mode 100644index 0000000000..b534a97386--- /dev/null+++ b/test/e2e/embedding-zero-norm-4616-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../embedding-zero-norm-4616.serial.test.ts'));diff --git a/test/e2e/fix-wave-3-integration.test.ts b/test/e2e/fix-wave-3-integration.test.tsnew file mode 100644index 0000000000..4a118ca9fe--- /dev/null+++ b/test/e2e/fix-wave-3-integration.test.ts@@ -0,0 +1,10 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++// Fix wave 3 integrated scenario gate: the PostgreSQL arm of the cross-lane checks, the chaos scenario and the timed recovery run.+await registerPostgresTests(+ () => import('../fix-wave-3-integration.test.ts'),+ () => import('../fix-wave-3-chaos.test.ts'),+ () => import('../fix-wave-3-recovery-run.test.ts'),+ () => import('../fix-wave-3-managed-embedding.serial.test.ts'),+ () => import('../fix-wave-3-connector-loops.serial.test.ts'),+);diff --git a/test/e2e/managed-facts-writers.test.ts b/test/e2e/managed-facts-writers.test.tsnew file mode 100644index 0000000000..5a3124c85f--- /dev/null+++ b/test/e2e/managed-facts-writers.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../managed-facts-writers.test.ts'));diff --git a/test/e2e/managed-phase-matrix.test.ts b/test/e2e/managed-phase-matrix.test.tsnew file mode 100644index 0000000000..39708e12fc--- /dev/null+++ b/test/e2e/managed-phase-matrix.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../managed-phase-matrix.test.ts'));diff --git a/test/e2e/managed-writers-w3.test.ts b/test/e2e/managed-writers-w3.test.tsnew file mode 100644index 0000000000..000d915b25--- /dev/null+++ b/test/e2e/managed-writers-w3.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../managed-writers-w3.test.ts'));diff --git a/test/e2e/persistence-admin-intent.test.ts b/test/e2e/persistence-admin-intent.test.tsindex 828ac221d8..d0955b75f9 100644--- a/test/e2e/persistence-admin-intent.test.ts+++ b/test/e2e/persistence-admin-intent.test.ts@@ -60,7 +60,7 @@ run('real PostgreSQL hint, routine diagnosis, deliberate noninteractive administawait expect(submitPageMutation({ engine, config: { engine: 'postgres', embedding_disabled: true }, remote: false, dryRun: false,sourceId: 'default', logger: { info() {}, warn() {}, error() {} } }, {operation: 'put_page', params: { slug: 'notes/example', content: '# Generic example' }, waitMs: 0,- })).rejects.toMatchObject({ code: 'owner_unavailable', suggestion: expect.stringContaining('Inspect gbrain sources writer status --json') });+ })).rejects.toMatchObject({ code: 'owner_unavailable', detail: 'unbound_source', suggestion: expect.stringContaining('gbrain sources writer status default --json') });const identity = readFileSync(join(persistenceHome(), 'host.json'), 'utf8');for (const args of [['doctor', '--fast', '--json'], ['doctor', '--fast', '--fix', '--skills-dir', join(home, 'skills'), '--json']]) {const result = await cli(args);diff --git a/test/e2e/persistence-git-coalescing-5530-postgres.test.ts b/test/e2e/persistence-git-coalescing-5530-postgres.test.tsnew file mode 100644index 0000000000..da17ff9ccc--- /dev/null+++ b/test/e2e/persistence-git-coalescing-5530-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../persistence-git-coalescing-5530.slow.test.ts'));diff --git a/test/e2e/persistence-writer-admin-lock.test.ts b/test/e2e/persistence-writer-admin-lock.test.tsnew file mode 100644index 0000000000..5d003a834e--- /dev/null+++ b/test/e2e/persistence-writer-admin-lock.test.ts@@ -0,0 +1,143 @@+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';+import type { PostgresEngine } from '../../src/core/postgres-engine.ts';+import { acceptWriterTransfer, claimWorktree, prepareWriterTransfer } from '../../src/core/persistence/ownership.ts';+import { activatePersistence } from '../../src/core/persistence/activation.ts';+import { runPersistenceAdministration } from '../../src/core/persistence/administration.ts';+import { writeWriterAdminLock } from '../../src/core/persistence/admin-lock.ts';+import { localHostId } from '../../src/core/persistence/identity.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';++const run = process.env.DATABASE_URL ? test : test.skip;+const LOCK_KEY = 'persistence.writer_admin_lock';+const DOCS = 'docs/guides/write-refusals.md#writer_admin_locked';+let engine: PostgresEngine;+let close: (() => Promise<void>) | undefined;+let home: string;+let root: string;+beforeAll(async () => {+ if (!process.env.DATABASE_URL) return;+ home = mkdtempSync(join(tmpdir(), 'gbrain-admin-lock-pg-'));+ root = join(home, 'canonical'); mkdirSync(root);+ writeFileSync(join(root, 'example.md'), 'generic example');+ const isolated = await isolatedPersistencePostgres(process.env.DATABASE_URL);+ engine = isolated.engine; close = isolated.close;+ const [database] = await engine.executeRaw<{ name: string }>('SELECT current_database() AS name');+ const url = new URL(process.env.DATABASE_URL); url.pathname = `/${database.name}`;+ mkdirSync(join(home, '.gbrain'));+ mkdirSync(join(home, 'skills'));+ writeFileSync(join(home, 'skills', 'RESOLVER.md'), '# Generic fixture skills\n');+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'postgres', database_url: url.toString(), embedding_disabled: true }));+ await engine.executeRaw('UPDATE sources SET local_path=$1 WHERE id=$2', [root, 'default']);+}, 60_000);+afterAll(async () => {+ if (engine) await disposePersistenceConsumer(engine);+ await close?.();+ if (home) rmSync(home, { recursive: true, force: true });+});++async function cli(args: string[]) {+ const child = Bun.spawn([process.execPath, join(import.meta.dir, '../../src/cli.ts'), ...args], {+ cwd: home, env: { ...process.env, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined,+ GBRAIN_HOME: home, GBRAIN_BRAIN_ID: 'host', GBRAIN_NO_BANNER: '1', GBRAIN_BACKUP_CHECK: '0',+ GBRAIN_SKILLS_DIR: join(home, 'skills') }, stdin: 'ignore', stdout: 'pipe', stderr: 'pipe',+ });+ const [stdout, stderr, code] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]);+ return { stdout, stderr, code };+}+const settled = <T>(promise: Promise<T>) => {+ const state: { done: boolean; value?: T; error?: unknown } = { done: false };+ promise.then(value => { state.done = true; state.value = value; }, error => { state.done = true; state.error = error; });+ return state;+};+const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));++run('PostgreSQL: lock serializes with an in-flight claim, and a claim waits for an in-flight lock', async () => {+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {+ localHostId();+ let release!: () => void;+ const gate = new Promise<void>(resolve => { release = resolve; });+ let holding = false;+ const lockTx = engine.transaction(async tx => { const result = await writeWriterAdminLock(tx, true); holding = true; await gate; return result; });+ while (!holding) await sleep(10);+ const claim = settled(claimWorktree(engine, 'default', root));+ await sleep(750);+ expect(claim.done).toBe(false);+ release();+ expect(await lockTx).toMatchObject({ changed: true, admin_lock: { locked: true } });+ while (!claim.done) await sleep(10);+ expect(claim.error).toMatchObject({ code: 'writer_admin_locked', docs: DOCS });+ expect(await engine.executeRaw('SELECT id FROM persistence_worktrees')).toEqual([]);++ await runPersistenceAdministration(engine, 'writer_unlock', {});+ // An admin transaction holding the check's share lock keeps a lock attempt waiting until it commits.+ let releaseCheck!: () => void;+ const checkGate = new Promise<void>(resolve => { releaseCheck = resolve; });+ let checking = false;+ const checkTx = engine.transaction(async tx => {+ await tx.executeRaw('SELECT singleton FROM persistence_brain WHERE singleton=1 FOR SHARE');+ checking = true; await checkGate;+ });+ while (!checking) await sleep(10);+ const locking = settled(runPersistenceAdministration(engine, 'writer_lock', {}));+ await sleep(750);+ expect(locking.done).toBe(false);+ releaseCheck(); await checkTx;+ while (!locking.done) await sleep(10);+ expect(locking.value).toMatchObject({ changed: true, admin_lock: { locked: true } });+ await runPersistenceAdministration(engine, 'writer_unlock', {});++ // Racing claim and lock end in one of the two serial orders.+ const [claimed, locked] = await Promise.allSettled([claimWorktree(engine, 'default', root), runPersistenceAdministration(engine, 'writer_lock', {})]);+ expect(locked.status).toBe('fulfilled');+ const bindings = await engine.executeRaw('SELECT source_id FROM persistence_source_bindings');+ if (claimed.status === 'fulfilled') expect(bindings).toEqual([{ source_id: 'default' }]);+ else { expect(claimed.reason).toMatchObject({ code: 'writer_admin_locked' }); expect(bindings).toEqual([]); }+ await runPersistenceAdministration(engine, 'writer_unlock', {});+ if (claimed.status !== 'fulfilled') await claimWorktree(engine, 'default', root);+ });+}, 120_000);++run('PostgreSQL: internal and CLI callers are refused while locked; config cannot clear the lock; unlock restores administration', async () => {+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {+ const locked = JSON.parse((await cli(['sources', 'writer', 'lock', '--json'])).stdout);+ expect(locked).toMatchObject({ selected_brain: 'host', changed: true, admin_lock: { locked: true, host_id: localHostId() } });+ const status = JSON.parse((await cli(['sources', 'writer', 'status', '--json'])).stdout);+ expect(status).toMatchObject({ selected_brain: 'host', local_host_id: localHostId(), admin_lock: { locked: true, host_id: localHostId(), set_at: locked.admin_lock.set_at } });++ const refused = await cli(['sources', 'writer', 'transfer', 'prepare', 'default', '--admin-intent', 'writer_transfer_prepare', '--expected-state', status.admin_state, '--json']);+ expect(refused.code).toBe(1);+ const body = JSON.parse(refused.stdout);+ expect(body).toMatchObject({ error: 'writer_admin_locked', docs: DOCS });+ expect(body.suggestion).toContain('ask the operator');+ expect(body.suggestion).toContain(DOCS);+ expect(body.suggestion).not.toMatch(/unlock/i);+ expect(refused.stderr).toContain(`Fix: ${body.suggestion}`);++ for (const args of [['config', 'set', LOCK_KEY, '{"locked":false}', '--force'], ['config', 'unset', LOCK_KEY], ['config', 'unset', '--pattern', 'persistence.']]) {+ const result = await cli(args);+ expect(result.code).toBe(1);+ expect(result.stderr).toContain(`${LOCK_KEY} is reserved`);+ }+ expect(JSON.parse((await engine.getConfig(LOCK_KEY))!)).toMatchObject({ locked: true });++ await expect(prepareWriterTransfer(engine, 'default')).rejects.toMatchObject({ code: 'writer_admin_locked' });+ await expect(activatePersistence(engine, { confirmQuiesced: true })).rejects.toMatchObject({ code: 'writer_admin_locked' });+ expect(await engine.executeRaw('SELECT state FROM persistence_worktrees')).toEqual([{ state: 'active' }]);++ await runPersistenceAdministration(engine, 'writer_unlock', {});+ const prepared = await prepareWriterTransfer(engine, 'default');+ await expect(runPersistenceAdministration(engine, 'writer_lock', {})).rejects.toMatchObject({ code: 'writer_transfer_conflict' });+ await engine.setConfig(LOCK_KEY, JSON.stringify({ locked: true, set_at: new Date().toISOString(), host_id: localHostId(), generation: 50 }));+ await expect(acceptWriterTransfer(engine, 'default', root, prepared.owner_epoch, prepared.manifest.digest)).rejects.toMatchObject({ code: 'writer_admin_locked' });+ await runPersistenceAdministration(engine, 'writer_unlock', {});+ await acceptWriterTransfer(engine, 'default', root, prepared.owner_epoch, prepared.manifest.digest);+ expect(await runPersistenceAdministration(engine, 'writer_activate', { confirm_quiesced: true, ...await reviewedWriterIntent(engine, 'writer_activate') }))+ .toMatchObject({ activated: true });+ });+}, 180_000);diff --git a/test/e2e/persistence-writer-stamps.test.ts b/test/e2e/persistence-writer-stamps.test.tsnew file mode 100644index 0000000000..ad8061b9f8--- /dev/null+++ b/test/e2e/persistence-writer-stamps.test.ts@@ -0,0 +1,6 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(+ () => import('../persistence-writer-versions.test.ts'),+ () => import('../persistence-blocking-effects.test.ts'),+);diff --git a/test/e2e/reconcile-unbound-collision.test.ts b/test/e2e/reconcile-unbound-collision.test.tsnew file mode 100644index 0000000000..25910d2a32--- /dev/null+++ b/test/e2e/reconcile-unbound-collision.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../reconcile-unbound-collision.test.ts'));diff --git a/test/e2e/recovery-layer.test.ts b/test/e2e/recovery-layer.test.tsnew file mode 100644index 0000000000..1b6b898c27--- /dev/null+++ b/test/e2e/recovery-layer.test.ts@@ -0,0 +1,25 @@+/**+ * Postgres arms of the recovery-layer scenarios (fix wave 3, Lane D). Each run+ * gets a fresh isolated database from the managed-brain helper.+ */+import { describe, test } from 'bun:test';+import {+ budgetAndResumeContract, planListsRepairStepsIndependentOfTarget, remediateWithoutConsentSkipsRepairs,+ remoteCallerCannotRunRepairs, remoteLinesForWaveFindings, scriptedRecoveryRun, swallowedExhaustionIsReported, jobsRecheckedAfterRepairReservations, pendingEmbeddingsResume,+} from '../helpers/wave-scenarios.ts';++const url = process.env.DATABASE_URL;+describe.skipIf(!url)('recovery layer (Postgres)', () => {+ test('remote doctor host-action lines', () => remoteLinesForWaveFindings(url), 240_000);+ test('remediation plan lists repair steps independent of the target', () => planListsRepairStepsIndependentOfTarget(url), 240_000);+ test('--remediate without --include-repairs skips repairs', () => remediateWithoutConsentSkipsRepairs(url), 240_000);+ test('scripted recovery run', async () => {+ const measured = await scriptedRecoveryRun(url);+ console.error(`[recovery-run] postgres wall_ms=${measured.wall_ms} operator_commands=${measured.operator_commands}`);+ }, 300_000);+ test('zero budget, paid refusal and resume contract', () => budgetAndResumeContract(url), 240_000);+ test('remote caller cannot run repairs', () => remoteCallerCannotRunRepairs(url), 240_000);+ test('a swallowed budget exhaustion is still reported', () => swallowedExhaustionIsReported(url), 240_000);+ test('job steps are rechecked after repair reservations', () => jobsRecheckedAfterRepairReservations(url), 240_000);+ test('pending embeddings resume from the checkpoint', () => pendingEmbeddingsResume(url), 240_000);+});diff --git a/test/e2e/repair-contextual-mode-5621-postgres.test.ts b/test/e2e/repair-contextual-mode-5621-postgres.test.tsnew file mode 100644index 0000000000..26ee39bd07--- /dev/null+++ b/test/e2e/repair-contextual-mode-5621-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../repair-contextual-mode-5621.serial.test.ts'));diff --git a/test/e2e/unbound-source-postgres.test.ts b/test/e2e/unbound-source-postgres.test.tsnew file mode 100644index 0000000000..27a5ccf8cf--- /dev/null+++ b/test/e2e/unbound-source-postgres.test.ts@@ -0,0 +1,302 @@+/**+ * #5254: a Postgres put_page to a filesystem source with no canonical owner.+ *+ * Contract: refused by default with detail `unbound_source` and a hint naming+ * both exits (bind through `sources writer claim`, or opt in with+ * `persistence.unbound_write=database_only`). The opt-in writes new or already+ * database-only pages to the database only, classifies them durably, rechecks+ * the binding at publication, and keeps them database-only after binding.+ * Regression: the refusal carried only the generic writer-inspection hint and+ * there was no opt-in, so every Postgres brain with an unbound filesystem+ * source could not save pages at all. Existing Postgres put_page coverage+ * always claims the worktree first, so none of these paths ran.+ */+import { describe, expect, spyOn, test as bunTest } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { randomUUID } from 'node:crypto';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { hasDatabase } from './helpers.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { LEGACY_EMBEDDING_CONFIG } from '../helpers/legacy-embedding-config.ts';+import { withEnv } from '../helpers/with-env.ts';+import type { PostgresEngine } from '../../src/core/postgres-engine.ts';+import type { OperationContext } from '../../src/core/ops/contract.ts';+import { configureGateway, resetGateway } from '../../src/core/ai/gateway.ts';+import { dispatchToolCall } from '../../src/mcp/dispatch.ts';+import { claimWorktree } from '../../src/core/persistence/ownership.ts';+import { registerLocalWriter, withVerifiedLocalRegistration, type LocalRegistration } from '../../src/core/persistence/identity.ts';+import { disposePersistenceConsumer, registerMutationPreparer } from '../../src/core/persistence/service.ts';+import { preparePageMutation } from '../../src/core/persistence/page-prepare.ts';+import { submitPageMutation } from '../../src/core/persistence/page-mutations.ts';+import { performManagedSync } from '../../src/core/persistence/sync-run.ts';+import { _resetWriteThroughCacheForTest } from '../../src/core/write-through.ts';+import { runConfig } from '../../src/commands/config.ts';++const d = hasDatabase() ? describe : describe.skip;+let engine: PostgresEngine;+let root: string;+let registration: LocalRegistration;+const config = { engine: 'postgres' as const, embedding_disabled: true };+const slug = 'notes/unbound-example';+const content = (body: string) => `---\ntitle: Example\ntype: note\n---\n\n${body}`;+const DOCS = 'docs/guides/write-refusals.md#unbound-sources-on-postgres';++// Held between admission and publication by the gated preparer below; every+// put_page in this file is a plain page write, so delegating is exact.+let gate: { entered: () => void; release: Promise<void> } | null = null;+registerMutationPreparer('put_page', async (e, row, cfg, signal) => {+ if (gate) { gate.entered(); await gate.release; }+ return preparePageMutation(e, row, cfg, undefined, signal);+});++function git(dir: string, ...args: string[]): string {+ return execFileSync('git', ['-C', dir, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+}+function commit(dir: string): void {+ git(dir, 'add', '.');+ git(dir, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'fixture');+}++function test(name: string, run: () => Promise<void>) {+ bunTest(name, async () => {+ const fixtureDir = mkdtempSync(join(tmpdir(), 'gbrain-unbound-pg-'));+ configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: {} });+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);+ engine = pg.engine;+ root = join(fixtureDir, 'brain'); mkdirSync(join(root, 'notes'), { recursive: true });+ git(root, 'init', '-q');+ writeFileSync(join(root, 'notes', 'seed.md'), content('Seed file.'));+ commit(root);+ resetGateway(); _resetWriteThroughCacheForTest();+ try {+ await withEnv({ GBRAIN_HOME: join(fixtureDir, 'home') }, async () => {+ await engine.setConfig('sync.repo_path', root);+ registration = await registerLocalWriter(engine, 'stdio', {+ sourceIds: ['default'], operations: null, scopes: ['read', 'write'], slugPrefixes: ['notes'],+ });+ try { await run(); } finally { gate = null; await disposePersistenceConsumer(engine); }+ });+ } finally {+ resetGateway(); _resetWriteThroughCacheForTest();+ await pg.close();+ rmSync(fixtureDir, { recursive: true, force: true });+ }+ }, 60_000);+}++async function dispatch(name: string, params: Record<string, unknown>) {+ const response = await withVerifiedLocalRegistration(engine, registration, () => dispatchToolCall(engine, name, params, {+ remote: true, config, sourceId: 'default',+ auth: { token: 'fixture', clientId: 'fixture-client', scopes: ['read', 'write'], sourceId: 'default', boundSlugPrefixes: ['notes'] },+ logger: { info() {}, warn() {}, error() {} },+ }));+ return { response, payload: JSON.parse((response.content[0] as { text: string }).text), params };+}+async function put(body: string, pageSlug = slug) {+ const current = await engine.readPageSnapshot(pageSlug, { sourceId: 'default', includeDeleted: true });+ return dispatch('put_page', { slug: pageSlug, content: content(body), request_id: randomUUID(),+ ...(current ? { expected_revision: current.revision } : {}) });+}+function localContext(): OperationContext {+ return { engine, config, remote: false, sourceId: 'default', dryRun: false, logger: { info() {}, warn() {}, error() {} } } as OperationContext;+}+async function classification(pageSlug = slug): Promise<string | null | undefined> {+ const [row] = await engine.executeRaw<{ database_only_reason: string | null }>(+ 'SELECT database_only_reason FROM pages WHERE source_id=$1 AND slug=$2', ['default', pageSlug]);+ return row?.database_only_reason;+}+async function bindAndActivate(): Promise<void> {+ await claimWorktree(engine, 'default', root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+}+async function setUnboundWrite(value: string): Promise<{ exitCode: number | null; errors: string }> {+ const errors: string[] = [];+ let exitCode: number | null = null;+ const errSpy = spyOn(console, 'error').mockImplementation((...a: unknown[]) => { errors.push(a.map(String).join(' ')); });+ const logSpy = spyOn(console, 'log').mockImplementation(() => {});+ const exitSpy = spyOn(process, 'exit').mockImplementation(((code?: number) => { exitCode = code ?? 0; throw new Error(`EXIT:${code}`); }) as never);+ try { await runConfig(engine, ['set', 'persistence.unbound_write', value]); }+ catch (error) { if (!(error as Error).message.startsWith('EXIT:')) throw error; }+ finally { errSpy.mockRestore(); logSpy.mockRestore(); exitSpy.mockRestore(); }+ return { exitCode, errors: errors.join('\n') };+}++d('#5254 Postgres put_page to an unbound filesystem source', () => {+ test('default refuses with detail unbound_source and names the bind command and the opt-in key', async () => {+ const refused = await put('First note.');+ expect(refused.response.isError).toBe(true);+ expect(refused.payload.error).toBe('owner_unavailable');+ expect(refused.payload.detail).toBe('unbound_source');+ expect(refused.payload.docs).toBe(DOCS);+ const hint = refused.payload.suggestion as string;+ expect(hint).toContain('gbrain sources writer status default --json');+ expect(hint).toContain('gbrain sources writer claim default --path');+ expect(hint).toContain('--admin-intent writer_claim --expected-state <admin_state>');+ expect(hint).toContain('ask the operator to unlock it first');+ expect(hint).toContain('gbrain config set persistence.unbound_write database_only');+ expect(hint).toContain('stay database-only and are not materialized');+ expect(await engine.readPageSnapshot(slug, { sourceId: 'default', includeDeleted: true })).toBeNull();+ // An explicit refuse behaves exactly like the default.+ await engine.setConfig('persistence.unbound_write', 'refuse');+ expect((await put('First note.')).payload.detail).toBe('unbound_source');+ });++ test('a trusted local caller gets the real checkout path filled into the bind command', async () => {+ let error: { code?: string; detail?: string; suggestion?: string } | undefined;+ try { await submitPageMutation(localContext(), { operation: 'put_page', params: { slug, content: content('Local note.') } }); }+ catch (caught) { error = caught as typeof error; }+ expect(error?.code).toBe('owner_unavailable');+ expect(error?.detail).toBe('unbound_source');+ expect(error?.suggestion).toContain(`gbrain sources writer claim default --path ${root} --admin-intent writer_claim`);+ });++ test('config set accepts refuse and database_only and rejects anything else', async () => {+ expect(await setUnboundWrite('database_only')).toEqual({ exitCode: null, errors: '' });+ expect(await engine.getConfig('persistence.unbound_write')).toBe('database_only');+ expect(await setUnboundWrite('refuse')).toEqual({ exitCode: null, errors: '' });+ const bad = await setUnboundWrite('auto_claim');+ expect(bad.exitCode).toBe(1);+ expect(bad.errors).toContain('persistence.unbound_write must be one of: refuse, database_only');+ expect(await engine.getConfig('persistence.unbound_write')).toBe('refuse');+ });++ test('database_only writes a new page database-only, says why, and classifies it durably', async () => {+ await engine.setConfig('persistence.unbound_write', 'database_only');+ const written = await put('Database-only note.');+ expect(written.response.isError).not.toBe(true);+ expect(written.payload.state).toBe('committed');+ expect(written.payload.persistence).toEqual({ mode: 'database' });+ expect(written.payload.write_through.written).toBe(false);+ expect(written.payload.write_through.skipped).toBe('unbound_source');+ expect(written.payload.write_through.warning).toContain('has no canonical owner');+ expect(await classification()).toBe('unbound_source');+ expect(existsSync(join(root, `${slug}.md`))).toBe(false);+ // A page that is already database-only keeps accepting edits.+ const edited = await put('Edited database-only note.');+ expect(edited.payload.state).toBe('committed');+ expect(edited.payload.write_through.skipped).toBe('unbound_source');+ expect((await engine.getPage(slug, { sourceId: 'default' }))?.compiled_truth).toContain('Edited database-only note.');+ });++ test('database_only still refuses an edit to a page that came from a canonical file, with the bind branch only', async () => {+ await engine.setConfig('persistence.unbound_write', 'database_only');+ await engine.putPage('notes/seed', { type: 'note', title: 'Seed', compiled_truth: 'Seed file.', timeline: '', frontmatter: {} }, { sourceId: 'default' });+ await engine.executeRaw("UPDATE pages SET source_path='notes/seed.md' WHERE source_id='default' AND slug='notes/seed'");+ const refused = await put('Edited seed.', 'notes/seed');+ expect(refused.payload.error).toBe('owner_unavailable');+ expect(refused.payload.detail).toBe('unbound_source');+ expect(refused.payload.suggestion).toContain('gbrain sources writer claim default --path');+ expect(refused.payload.suggestion).not.toContain('gbrain config set persistence.unbound_write database_only');+ expect(refused.payload.suggestion).toContain('came from a canonical file');+ expect((await engine.getPage('notes/seed', { sourceId: 'default' }))?.compiled_truth).toBe('Seed file.');+ });++ test('binding between admission and publication fails the write with owner_unavailable/unbound_source', async () => {+ await engine.setConfig('persistence.unbound_write', 'database_only');+ let entered!: () => void;+ const reached = new Promise<void>(resolve => { entered = resolve; });+ let release!: () => void;+ gate = { entered, release: new Promise<void>(resolve => { release = resolve; }) };+ const pending = put('Accepted before binding.');+ await Promise.race([reached, pending.then(early => { throw new Error(`settled before publication: ${JSON.stringify(early.payload)}`); })]);+ await claimWorktree(engine, 'default', root);+ gate = null;+ release();+ const result = await pending;+ expect(result.response.isError).toBe(true);+ expect(result.payload.error).toBe('owner_unavailable');+ expect(result.payload.detail).toBe('unbound_source');+ expect(result.payload.docs).toBe(DOCS);+ expect(result.payload.write_request.state).toBe('failed');+ expect(result.payload.suggestion).toContain('new request_id');+ expect(await engine.readPageSnapshot(slug, { sourceId: 'default', includeDeleted: true })).toBeNull();+ });++ test('after binding, sync keeps the database-only page and later writes stay database-only', async () => {+ await engine.setConfig('persistence.unbound_write', 'database_only');+ expect((await put('Written while unbound.')).payload.state).toBe('committed');+ await bindAndActivate();+ const first = await performManagedSync(engine, { sourceId: 'default', noPull: true });+ expect(first.status).toBe('first_sync');+ expect((await engine.getPage('notes/seed', { sourceId: 'default' }))?.source_path).toBe('notes/seed.md');+ const kept = await engine.getPage(slug, { sourceId: 'default' });+ expect(kept?.compiled_truth).toContain('Written while unbound.');+ expect(kept?.source_path ?? null).toBeNull();+ expect(await classification()).toBe('unbound_source');+ // A later edit on the now-bound source publishes no canonical file.+ const edited = await put('Edited after binding.');+ expect(edited.payload.state).toBe('committed');+ expect(edited.payload.write_through).toMatchObject({ written: false, skipped: 'unbound_source' });+ expect(existsSync(join(root, `${slug}.md`))).toBe(false);+ expect(await classification()).toBe('unbound_source');+ // A canonical file appearing at the same path never overwrites the page.+ writeFileSync(join(root, `${slug}.md`), content('Colliding canonical file.'));+ commit(root);+ const collision = await performManagedSync(engine, { sourceId: 'default', noPull: true });+ expect(collision.status).toBe('blocked_by_failures');+ expect(collision.managedWrite).toMatchObject({ slug, write_error: 'source_changed', reason: 'unbound_source' });+ const after = await engine.getPage(slug, { sourceId: 'default' });+ expect(after?.compiled_truth).toContain('Edited after binding.');+ expect(after?.source_path ?? null).toBeNull();+ expect(await classification()).toBe('unbound_source');+ });++ test('after binding, delete, restore and revert of a database-only page never touch a canonical file', async () => {+ await engine.setConfig('persistence.unbound_write', 'database_only');+ expect((await put('Original while unbound.')).payload.state).toBe('committed');+ expect((await put('Second while unbound.')).payload.state).toBe('committed');+ await bindAndActivate();+ const file = join(root, `${slug}.md`);+ const mutate = async (name: string, params: Record<string, unknown> = {}) => {+ const current = await engine.readPageSnapshot(slug, { sourceId: 'default', includeDeleted: true });+ const result = await dispatch(name, { slug, request_id: randomUUID(), expected_revision: current!.revision, ...params });+ expect(result.response.isError, JSON.stringify(result.payload)).not.toBe(true);+ expect(result.payload.state).toBe('committed');+ expect(existsSync(file)).toBe(false);+ expect(await classification()).toBe('unbound_source');+ return result;+ };+ await mutate('delete_page');+ expect((await mutate('restore_page')).payload.write_through).toMatchObject({ written: false, skipped: 'unbound_source' });+ expect((await engine.getPage(slug, { sourceId: 'default' }))?.compiled_truth).toContain('Second while unbound.');+ const [version] = await engine.executeRaw<{ id: number }>(+ "SELECT v.id FROM page_versions v JOIN pages p ON p.id=v.page_id WHERE p.source_id='default' AND p.slug=$1 AND v.compiled_truth LIKE '%Original while unbound.%' ORDER BY v.id LIMIT 1", [slug]);+ await mutate('delete_page');+ await mutate('revert_version', { version_id: Number(version.id) });+ expect((await engine.getPage(slug, { sourceId: 'default' }))?.compiled_truth).toContain('Original while unbound.');+ // An unrelated file at the page's path is neither refused against nor removed by a delete.+ writeFileSync(file, content('Unrelated file.'));+ const current = await engine.readPageSnapshot(slug, { sourceId: 'default', includeDeleted: true });+ const deleted = await dispatch('delete_page', { slug, request_id: randomUUID(), expected_revision: current!.revision });+ expect(deleted.payload.state, JSON.stringify(deleted.payload)).toBe('committed');+ expect(existsSync(file)).toBe(true);+ const tombstone = await engine.readPageSnapshot(slug, { sourceId: 'default', includeDeleted: true });+ const purged = await submitPageMutation(localContext(), { operation: 'delete_page',+ params: { slug, purge: true, request_id: randomUUID(), expected_revision: tombstone!.revision } });+ expect(purged.state).toBe('committed');+ expect(await engine.readPageSnapshot(slug, { sourceId: 'default', includeDeleted: true })).toBeNull();+ expect(existsSync(file)).toBe(true);+ });++ test('doctor reports the unbound_source count: ok with the bind command while unbound, warn after binding', async () => {+ const { checkUnboundSource } = await import('../../src/commands/doctor/checks/unbound-source.ts');+ const empty = await checkUnboundSource(engine);+ expect(empty.name).toBe('unbound_source');+ expect(empty.status).toBe('ok');+ await engine.setConfig('persistence.unbound_write', 'database_only');+ expect((await put('Counted note.')).payload.state).toBe('committed');+ const unbound = await checkUnboundSource(engine);+ expect(unbound.status).toBe('ok');+ expect(unbound.message).toContain('default: 1');+ expect(unbound.message).toContain('gbrain sources writer claim default --path');+ expect(unbound.details).toMatchObject({ sources: [{ source_id: 'default', pages: 1, bound: false }] });+ await claimWorktree(engine, 'default', root);+ const bound = await checkUnboundSource(engine);+ expect(bound.status).toBe('warn');+ expect(bound.message).toContain('default: 1');+ expect(bound.message).toContain('outside canonical files');+ expect(bound.details).toMatchObject({ sources: [{ source_id: 'default', pages: 1, bound: true }] });+ });+});diff --git a/test/embed-stale-dry-run-restamp-5289.serial.test.ts b/test/embed-stale-dry-run-restamp-5289.serial.test.tsnew file mode 100644index 0000000000..867d393a55--- /dev/null+++ b/test/embed-stale-dry-run-restamp-5289.serial.test.ts@@ -0,0 +1,77 @@+import { installFixtureChunks } from './helpers/page-projection.ts';+/**+ * #5289 residual: `embed --stale --dry-run --include-null-signature` must not+ * count restamp-only chunks as work to embed.+ *+ * A NULL-signature page whose vectors are already in the current embedding+ * space is only restamped by the live run; its vectors are kept. Before the+ * fix the dry run added those chunks to `would_embed`, so the preview named+ * more embedding work (and cost) than the live run then did.+ *+ * Installs the process-global gateway transport seam (always fake), so this+ * stays a `.serial.test.ts`.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { runEmbedCore } from '../src/commands/embed.ts';+import { __setEmbedTransportForTests, configureGateway, resetGateway } from '../src/core/ai/gateway.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { EMBED_PROBE_TEXT } from '../src/core/embed-stale.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';++const DIMS = 1536;+const MODEL = 'openai:text-embedding-3-large';++let embeddedInputs: string[] = [];++async function seed(engine: BrainEngine, slug: string, chunk: { embedded: boolean; model?: string }): Promise<void> {+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: `# ${slug}` });+ await installFixtureChunks(engine, slug, [{+ chunk_index: 0, chunk_text: `${slug} body`, chunk_source: 'compiled_truth', token_count: 4,+ ...(chunk.embedded ? { embedding: new Float32Array(DIMS).fill(0.002), model: chunk.model ?? MODEL } : {}),+ }]);+}++beforeAll(() => {+ configureGateway({ embedding_model: MODEL, embedding_dimensions: DIMS, env: { ...process.env, OPENAI_API_KEY: 'sk-test-fake' } });+ __setEmbedTransportForTests((async (input: { values: string[] }) => {+ embeddedInputs.push(...input.values.filter(v => v !== EMBED_PROBE_TEXT));+ return { embeddings: input.values.map(() => new Array(DIMS).fill(0.001)), usage: { tokens: input.values.length * 4 } };+ }) as never);+});++afterAll(() => {+ __setEmbedTransportForTests(null);+ resetGateway();+});++for (const kind of testBackends()) describe(`#5289 embed --stale dry run vs live run (${kind})`, () => {+ 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({ embedding_dimensions: DIMS } as never); await engine.initSchema(); }+ }, 120_000);+ afterAll(async () => { if (close) await close(); else await engine.disconnect(); });+ beforeEach(() => { embeddedInputs = []; });++ test('restamp-only chunks are reported apart from chunks to embed, and the dry run matches the live run', async () => {+ await seed(engine, 'current-vectors', { embedded: true });+ await seed(engine, 'legacy-vectors', { embedded: true, model: 'legacy:model' });+ await seed(engine, 'no-vectors', { embedded: false });+ const opts = { stale: true, includeNullSignature: true, catchUp: true, quiet: true } as const;++ const preview = await runEmbedCore(engine, { ...opts, dryRun: true });+ expect(preview.would_embed).toBe(2);+ expect(preview.would_restamp).toBe(1);+ expect(embeddedInputs).toEqual([]);++ const live = await runEmbedCore(engine, opts);+ expect(live.embedded).toBe(preview.would_embed);+ expect(embeddedInputs.sort()).toEqual(['legacy-vectors body', 'no-vectors body']);++ const after = await runEmbedCore(engine, { ...opts, dryRun: true });+ expect(after.would_embed).toBe(0);+ expect(after.would_restamp ?? 0).toBe(0);+ });+});diff --git a/test/embedding-migration-settle.serial.test.ts b/test/embedding-migration-settle.serial.test.tsnew file mode 100644index 0000000000..8f31b31862--- /dev/null+++ b/test/embedding-migration-settle.serial.test.ts@@ -0,0 +1,394 @@+/**+ * #5680 — the embedding migration authorization reserves each provider request+ * at its maximum input size, settles it to the provider's reported usage, and+ * refuses a cap below the worst case before any vector is dropped.+ *+ * Authoring gate:+ * 1. Protects the durable `--max-cost-usd` contract: debits settle to reported+ * usage (missing usage keeps the maximum), settles serialize and are+ * idempotent, overshoot stops dispatch, and the printed worst-case+ * authorization is both sufficient and enforced before invalidation.+ * 2. Fails when settle is a no-op again (the #5680 stall: projection recovery+ * drops every vector, then the ceiling-only debits exhaust the cap), when+ * the settle loses a concurrent update, or when the cap check moves after+ * the destructive step.+ * 3. Existing recovery tests pin only the pre-dispatch debit and resume+ * retention; none settles a permit or compares the cap with a worst case.+ * 4. No new seam: the existing embed transport stub reports usage.+ * Serial: the gateway transport and configuration are process-global.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, spyOn, test } from 'bun:test';+import { mkdtempSync, mkdirSync, writeFileSync, rmSync } 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 { setupDB, teardownDB } from './e2e/helpers.ts';+import { testBackends } from './helpers/test-backends.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { installFixtureChunks } from './helpers/page-projection.ts';+import { withEnv } from './helpers/with-env.ts';+import { configureGateway, embed, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';+import { planEmbeddingMigration, readMigrationState, runSchemaTransition } from '../src/core/embedding-migration.ts';+import { readContentChunksEmbeddingDim } from '../src/core/embedding-dim-check.ts';+import { authorizeMigrationBudget } from '../src/core/embedding-migration-budget.ts';+import { invokeAI, withAIInvocationGuard, type AIInvocation } from '../src/core/ai/invocation-guard.ts';+import { runMigrateEmbeddings } from '../src/commands/migrate-embeddings.ts';++const model = 'openai:text-embedding-3-small';+const dimensions = 8;+const RATE_PER_MTOK = 1;+const usd = (tokens: number, rate = RATE_PER_MTOK) => tokens * rate / 1_000_000;+const call = (maxInputTokens: number): AIInvocation => ({ kind: 'embedding', operation: 'synthetic', model, maxInputTokens });+const usage = (inputTokens: number) => ({ inputTokens, outputTokens: 0 });+const vector = () => Array.from({ length: dimensions }, (_, i) => (i + 1) / 10);++class ExitSignal extends Error { constructor(public code: number) { super(`exit ${code}`); } }++for (const kind of testBackends()) {+ describe(`embedding migration budget settlement (${kind})`, () => {+ let engine: BrainEngine;+ let originalDimensions: number;+ let originalIdentity: Array<{ key: string; value: string }>;+ let transportCalls = 0;+ let reportedTokens = 0;++ const budget = async () => (await readMigrationState(engine)).state!.budget!;+ const plan = () => planEmbeddingMigration(engine, { to: model, dim: dimensions });++ function stubTransport(tokensOf = (value: string) => Math.ceil(value.length / 4)) {+ transportCalls = 0;+ reportedTokens = 0;+ __setEmbedTransportForTests(async ({ values }: { values: string[] }) => {+ transportCalls++;+ const tokens = values.reduce((sum, value) => sum + tokensOf(value), 0);+ reportedTokens += tokens;+ return { values, warnings: [], embeddings: values.map(vector), usage: { tokens } };+ });+ }++ async function seedPages(count: number) {+ for (let i = 0; i < count; i++) {+ const text = `Synthetic settlement page ${i}. ${'Alpha beta gamma delta. '.repeat(40)}`;+ await engine.putPage(`settle-${i}`, { type: 'note', title: `Synthetic ${i}`, compiled_truth: text });+ await installFixtureChunks(engine, `settle-${i}`, [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: text,+ embedding: new Float32Array(dimensions).fill(0.2) }]);+ }+ await engine.executeRaw('UPDATE pages SET embedding_signature=NULL');+ await engine.executeRaw("UPDATE content_chunks SET model='synthetic:legacy-model'");+ }++ async function cli(args: string[], target: { to: string; dim: number } = { to: model, dim: dimensions }) {+ const home = mkdtempSync(join(tmpdir(), 'migration-settle-'));+ mkdirSync(join(home, '.gbrain'));+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: kind, embedding_model: model, embedding_dimensions: dimensions, openai_api_key: 'synthetic-only' }));+ const out: string[] = [];+ const logSpy = spyOn(console, 'log').mockImplementation((...a: unknown[]) => { out.push(a.join(' ')); });+ const errSpy = spyOn(console, 'error').mockImplementation((...a: unknown[]) => { out.push(a.join(' ')); });+ let code = -1;+ try {+ await withEnv({ GBRAIN_HOME: home, GBRAIN_EMBEDDING_MODEL: undefined, GBRAIN_EMBEDDING_DIMENSIONS: undefined, NVIDIA_API_KEY: 'synthetic-only' }, async () => {+ try {+ await runMigrateEmbeddings(engine, ['--to', target.to, '--dim', String(target.dim), ...(args.includes('--reranker') ? [] : ['--reranker', 'off']), '--yes', ...args],+ { exit: (value: number): never => { throw new ExitSignal(value); } });+ } catch (error) {+ if (!(error instanceof ExitSignal)) throw error;+ code = error.code;+ }+ });+ } finally {+ logSpy.mockRestore();+ errSpy.mockRestore();+ rmSync(home, { recursive: true, force: true });+ }+ return { code, text: out.join('\n') };+ }++ const vectors = () => engine.executeRaw<{ slug: string; embedding: string | null }>(+ 'SELECT p.slug, cc.embedding::text AS embedding FROM content_chunks cc JOIN pages p ON p.id=cc.page_id ORDER BY p.slug');++ beforeAll(async () => {+ if (kind === 'postgres') engine = await setupDB();+ else { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }+ originalDimensions = (await readContentChunksEmbeddingDim(engine)).dims!;+ originalIdentity = await engine.executeRaw("SELECT key,value FROM config WHERE key IN ('embedding_model','embedding_dimensions')");+ await runSchemaTransition(engine, dimensions);+ }, 60_000);+ beforeEach(async () => {+ if (kind === 'pglite') await resetPgliteState(engine as PGLiteEngine);+ else {+ await engine.executeRaw('TRUNCATE facts, pages, fact_withdrawals, page_projection_jobs CASCADE');+ await engine.executeRaw("DELETE FROM config WHERE key LIKE 'embedding_migration.%' OR key='pricing.overrides'");+ }+ await engine.setConfig('embedding_model', model);+ await engine.setConfig('embedding_dimensions', String(dimensions));+ await engine.setConfig('pricing.overrides', JSON.stringify({ [model]: RATE_PER_MTOK }));+ resetGateway();+ configureGateway({ embedding_model: model, embedding_dimensions: dimensions, env: { OPENAI_API_KEY: 'synthetic-only' } });+ stubTransport();+ });+ afterAll(async () => {+ __setEmbedTransportForTests(null); resetGateway();+ await runSchemaTransition(engine, originalDimensions);+ await engine.executeRaw("DELETE FROM config WHERE key IN ('embedding_model','embedding_dimensions','pricing.overrides')");+ for (const row of originalIdentity) await engine.setConfig(row.key, row.value);+ if (kind === 'postgres') await teardownDB(); else await engine.disconnect();+ });++ test('a request reserves its maximum and settles to the reported usage', async () => {+ const debit = await authorizeMigrationBudget(engine, await plan(), 1);+ await withAIInvocationGuard(debit, () => invokeAI(call(40_000), async () => 'ok', () => usage(1_000)));+ const settled = await budget();+ expect(settled.requests).toBe(1);+ expect(settled.debited_usd).toBeCloseTo(usd(1_000), 12);+ expect(Object.keys(settled.pending ?? {})).toEqual([]);+ });++ test('a response without usage keeps the maximum debit', async () => {+ const debit = await authorizeMigrationBudget(engine, await plan(), 1);+ await withAIInvocationGuard(debit, () => invokeAI(call(40_000), async () => 'ok', () => null));+ expect((await budget()).debited_usd).toBeCloseTo(usd(40_000), 12);+ });++ test('settle is idempotent per attempt and a crash between reserve and settle keeps the maximum', async () => {+ const current = await plan();+ const debit = await authorizeMigrationBudget(engine, current, 1);+ const permit = await debit(call(40_000));+ await permit.settle(usage(1_000));+ const once = await budget();+ await permit.settle(usage(1));+ expect(await budget()).toEqual(once);+ const crashed = await debit(call(40_000));+ await authorizeMigrationBudget(engine, current, 1);+ await crashed.settle(usage(1));+ const resumed = await budget();+ expect(resumed.debited_usd).toBeCloseTo(usd(1_000) + usd(40_000), 12);+ expect(resumed.requests).toBe(2);+ expect(Object.keys(resumed.pending ?? {})).toHaveLength(1);+ });++ test('concurrent settles serialize on the migration state row', async () => {+ const debit = await authorizeMigrationBudget(engine, await plan(), 1);+ const permits = [];+ for (let i = 0; i < 6; i++) permits.push(await debit(call(40_000)));+ await Promise.all(permits.map((permit, i) => permit.settle(usage(100 * (i + 1)))));+ const settled = await budget();+ expect(settled.requests).toBe(6);+ expect(settled.debited_usd).toBeCloseTo(usd(100 * 21), 12);+ expect(Object.keys(settled.pending ?? {})).toEqual([]);+ });++ test('a retried request settles the sum of its attempts; a token-limit split settles from the parent headroom', async () => {+ const debit = await authorizeMigrationBudget(engine, await plan(), 1);+ const reserved: number[] = [];+ let attempts = 0;+ __setEmbedTransportForTests(async ({ values }: { values: string[] }) => {+ attempts++;+ if (values.length > 1) throw new Error("Invalid 'input': maximum request size is 300000 tokens per request.");+ return { values, warnings: [], embeddings: values.map(vector), usage: { tokens: 10 } };+ });+ await withAIInvocationGuard(async request => { reserved.push(request.maxInputTokens!); return debit(request); },+ () => embed(['a'.repeat(400), 'b'.repeat(400)], { embeddingModel: model, dimensions }));+ expect(attempts).toBe(3);+ expect(reserved).toHaveLength(3);+ expect(reserved[1] + reserved[2]).toBe(reserved[0]);+ const split = await budget();+ expect(split.requests).toBe(3);+ expect(split.debited_usd).toBeCloseTo(usd(10) + usd(10), 12);+ await expect(withAIInvocationGuard(debit, () => invokeAI(call(40_000), async () => { throw new Error('Synthetic timeout'); }, () => null))).rejects.toThrow();+ await withAIInvocationGuard(debit, () => invokeAI(call(40_000), async () => 'ok', () => usage(500)));+ expect((await budget()).debited_usd).toBeCloseTo(usd(20) + usd(40_000) + usd(500), 12);+ });++ test('usage above the reservation debits actual, records the overshoot and stops dispatch', async () => {+ const debit = await authorizeMigrationBudget(engine, await plan(), 1);+ await withAIInvocationGuard(debit, () => invokeAI(call(100), async () => 'ok', () => usage(1_000)));+ const over = await budget();+ expect(over.debited_usd).toBeCloseTo(usd(1_000), 12);+ expect(over.overshoot_usd).toBeCloseTo(usd(900), 12);+ let dispatched = false;+ await expect(withAIInvocationGuard(debit, () => invokeAI(call(100), async () => { dispatched = true; }, () => usage(1))))+ .rejects.toThrow(/exceeded its reservation/);+ expect(dispatched).toBe(false);+ expect((await budget()).requests).toBe(1);+ });++ test('a cap equal to the printed worst-case authorization completes the migration', async () => {+ const rate = 1_000;+ await engine.setConfig('pricing.overrides', JSON.stringify({ [model]: rate }));+ await seedPages(5);+ const preview = await cli(['--dry-run']);+ expect(preview.code).toBe(0);+ const printed = /Worst-case authorization: \$(\d+(?:\.\d+)?)/.exec(preview.text);+ expect(printed).not.toBeNull();+ expect(preview.text).toContain('retries and batch splits settle from the same headroom');+ stubTransport(value => Buffer.byteLength(value, 'utf8'));+ const run = await cli(['--max-cost-usd', printed![1], '--json']);+ expect(run.text).toContain('"status": "completed"');+ expect(run.code).toBe(0);+ expect((await vectors()).every(row => row.embedding !== null)).toBe(true);+ const receipt = JSON.parse((await engine.getConfig('embedding_migration.completed'))!);+ expect(receipt.budget.debited_usd).toBeCloseTo(usd(reportedTokens, rate), 9);+ expect(receipt.verify_search.status).toBe('pass');+ });++ test('chunks created by projection recovery count toward the printed worst case', async () => {+ const rate = 1_000;+ await engine.setConfig('pricing.overrides', JSON.stringify({ [model]: rate }));+ await seedPages(2);+ const body = Array.from({ length: 60 }, (_, i) => `Synthetic unsealed paragraph ${i}. ${'Epsilon zeta eta theta. '.repeat(12)}`).join('\n\n');+ await engine.putPage('settle-unsealed', { type: 'note', title: 'Synthetic unsealed', compiled_truth: body });+ const [unsealed] = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM pages p+ WHERE p.slug='settle-unsealed' AND p.text_projection_revision IS DISTINCT FROM p.knowledge_revision+ AND NOT EXISTS (SELECT 1 FROM content_chunks c WHERE c.page_id=p.id)`);+ expect(unsealed.n).toBe(1);+ const preview = await cli(['--dry-run']);+ const printed = /Worst-case authorization: \$(\d+(?:\.\d+)?)/.exec(preview.text);+ expect(printed).not.toBeNull();+ expect(Number(printed![1])).toBeGreaterThan(usd(Buffer.byteLength(body, 'utf8'), rate));+ stubTransport(value => Buffer.byteLength(value, 'utf8'));+ const run = await cli(['--max-cost-usd', printed![1], '--json']);+ expect(run.text).toContain('"status": "completed"');+ expect(run.code).toBe(0);+ const rows = await vectors();+ expect(rows.filter(row => row.slug === 'settle-unsealed').length).toBeGreaterThan(1);+ expect(rows.every(row => row.embedding !== null)).toBe(true);+ });++ test('an unpriced reranker switch still enforces the known embedding worst case', async () => {+ await seedPages(5);+ const before = await vectors();+ const preview = await cli(['--dry-run', '--reranker', 'nan:rerank']);+ expect(preview.text).toMatch(/Worst-case authorization: \$\d/);+ expect(preview.text).toContain('nan:rerank has no price');+ const run = await cli(['--max-cost-usd', '0.001', '--reranker', 'nan:rerank']);+ expect(run.code).toBe(1);+ expect(run.text).toContain('embedding_budget_below_worst_case');+ expect(transportCalls).toBe(0);+ expect(await vectors()).toEqual(before);+ });++ test('a batch split after a token-limit rejection settles within the printed worst case', async () => {+ const rate = 1_000;+ await engine.setConfig('pricing.overrides', JSON.stringify({ [model]: rate }));+ const texts = [0, 1, 2].map(i => `Synthetic split chunk ${i}. ${'Iota kappa lambda mu. '.repeat(40)}`);+ await engine.putPage('settle-split', { type: 'note', title: 'Synthetic split', compiled_truth: texts.join('\n\n') });+ await installFixtureChunks(engine, 'settle-split', texts.map((chunk_text, chunk_index) => ({ chunk_index, chunk_source: 'compiled_truth' as const,+ chunk_text, embedding: new Float32Array(dimensions).fill(0.2) })));+ await engine.executeRaw("UPDATE pages SET embedding_signature=NULL");+ await engine.executeRaw("UPDATE content_chunks SET model='synthetic:legacy-model'");+ const preview = await cli(['--dry-run']);+ const printed = /Worst-case authorization: \$(\d+(?:\.\d+)?)/.exec(preview.text);+ expect(printed).not.toBeNull();+ let rejected = 0;+ __setEmbedTransportForTests(async ({ values }: { values: string[] }) => {+ if (values.length > 1) { rejected++; throw new Error("Invalid 'input': maximum request size is 300000 tokens per request."); }+ return { values, warnings: [], embeddings: values.map(vector), usage: { tokens: Buffer.byteLength(values[0], 'utf8') } };+ });+ const run = await cli(['--max-cost-usd', printed![1], '--json']);+ expect(rejected).toBeGreaterThan(0);+ expect(run.text).toContain('"status": "completed"');+ expect((await vectors()).every(row => row.embedding !== null)).toBe(true);+ });++ test('content-drift chunks on a same-target resume count toward the printed worst case', async () => {+ const rate = 1_000;+ await engine.setConfig('pricing.overrides', JSON.stringify({ [model]: rate }));+ await seedPages(4);+ await engine.executeRaw('UPDATE pages SET embedding_signature=$1', [`${model}:${dimensions}`]);+ await engine.executeRaw('UPDATE content_chunks SET model=$1, embedded_text_hash=md5(chunk_text)', [model]);+ await engine.executeRaw(`UPDATE content_chunks cc SET embedded_text_hash=md5('Synthetic obsolete text')+ FROM pages p WHERE p.id=cc.page_id AND p.slug IN ('settle-0','settle-1','settle-2')`);+ await engine.setConfig('embedding_migration.state', JSON.stringify({ version: 2, to_model: model, to_dims: dimensions,+ from_model: 'synthetic:legacy-model', from_dims: dimensions, started_at: '2026-01-01T00:00:00.000Z',+ authorization_version: 1, authorization_generation: 1, budget: { max_cost_usd: 0, debited_usd: 0, requests: 0 } }));+ const preview = await cli(['--dry-run']);+ const printed = /Worst-case authorization: \$(\d+(?:\.\d+)?)/.exec(preview.text);+ expect(printed).not.toBeNull();+ stubTransport(value => Buffer.byteLength(value, 'utf8'));+ const run = await cli(['--max-cost-usd', printed![1], '--json']);+ expect(run.text).toContain('"status": "completed"');+ const drifted = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM content_chunks+ WHERE embedding IS NULL OR embedded_text_hash IS DISTINCT FROM md5(chunk_text)`);+ expect(drifted[0].n).toBe(0);+ });++ test('a cap near the estimate completes instead of dropping every vector and stalling', async () => {+ await seedPages(5);+ const run = await cli(['--max-cost-usd', '0.15', '--json']);+ expect(run.text).toContain('"status": "completed"');+ expect(run.code).toBe(0);+ expect((await vectors()).every(row => row.embedding !== null)).toBe(true);+ });++ test('a cap below the worst case refuses before any vector is dropped, naming cap, worst case and the raising flag', async () => {+ await seedPages(5);+ const before = await vectors();+ const run = await cli(['--max-cost-usd', '0.001']);+ expect(run.code).toBe(1);+ expect(transportCalls).toBe(0);+ expect(await vectors()).toEqual(before);+ expect(run.text).toContain('embedding_budget_below_worst_case');+ expect(run.text).toContain('cap is $0.001');+ const worst = /worst-case authorization is \$(\d+(?:\.\d+)?)/.exec(run.text);+ expect(worst).not.toBeNull();+ expect(Number(worst![1])).toBeGreaterThan(0.001);+ const raise = /--max-cost-usd (\d+(?:\.\d+)?) --yes/.exec(run.text);+ expect(raise).not.toBeNull();+ expect(Number(raise![1])).toBeGreaterThanOrEqual(Number(worst![1]));+ expect(run.text).toContain('write-refusals.md#embedding_budget_below_worst_case');+ expect(run.text).not.toContain('--max-cost $0.00');+ const json = await cli(['--max-cost-usd', '0.001', '--json']);+ const envelope = JSON.parse(json.text.slice(json.text.indexOf('{\n "status": "refused"'), json.text.lastIndexOf('}') + 1));+ expect(envelope).toMatchObject({ status: 'refused', reason: 'embedding_budget_below_worst_case', error: 'embedding_budget_below_worst_case', cap_usd: 0.001 });+ expect(envelope.suggestion).toBe(`gbrain migrate embeddings --to ${model} --dim ${dimensions} --max-cost-usd ${envelope.required_cap_usd.toFixed(2)} --yes`);+ expect(envelope.docs).toEndWith('docs/guides/write-refusals.md#embedding_budget_below_worst_case');+ expect(transportCalls).toBe(0);+ expect(await vectors()).toEqual(before);+ });++ test('healing an oversized stale chunk budgets the siblings it re-indexes', async () => {+ const rate = 1_000;+ await engine.setConfig('pricing.overrides', JSON.stringify({ [model]: rate }));+ const oversized = Array.from({ length: 400 }, (_, i) => `Synthetic oversized sentence ${i} about nu xi omicron.`).join(' ');+ const siblings = [1, 2].map(i => `Synthetic sibling ${i}. ${'Pi rho sigma tau upsilon. '.repeat(90)}`);+ await engine.putPage('settle-heal', { type: 'note', title: 'Synthetic heal', compiled_truth: [oversized, ...siblings].join('\n\n') });+ await installFixtureChunks(engine, 'settle-heal', [oversized, ...siblings].map((chunk_text, chunk_index) => ({ chunk_index,+ chunk_source: 'compiled_truth' as const, chunk_text, ...(chunk_index > 0 && { embedding: new Float32Array(dimensions).fill(0.2) }) })));+ await engine.executeRaw('UPDATE pages SET embedding_signature=$1', [`${model}:${dimensions}`]);+ await engine.executeRaw('UPDATE content_chunks SET model=$1, embedded_text_hash=md5(chunk_text) WHERE embedding IS NOT NULL', [model]);+ await engine.setConfig('embedding_migration.state', JSON.stringify({ version: 2, to_model: model, to_dims: dimensions,+ from_model: 'synthetic:legacy-model', from_dims: dimensions, started_at: '2026-01-01T00:00:00.000Z',+ authorization_version: 1, authorization_generation: 1, budget: { max_cost_usd: 0, debited_usd: 0, requests: 0 } }));+ const preview = await cli(['--dry-run']);+ const printed = /Worst-case authorization: \$(\d+(?:\.\d+)?)/.exec(preview.text);+ expect(printed).not.toBeNull();+ stubTransport(value => Buffer.byteLength(value, 'utf8'));+ const run = await cli(['--max-cost-usd', printed![1], '--json']);+ expect(run.text).toContain('"status": "completed"');+ expect((await vectors()).every(row => row.embedding !== null)).toBe(true);+ });++ test('projection recovery at the current limit followed by the target-limit heal fits the printed worst case', async () => {+ const target = { to: 'nvidia:nvidia/nv-embedqa-e5-v5', dim: 1024 };+ const perInput = 512;+ await engine.setConfig('pricing.overrides', JSON.stringify({ [model]: 1_000, [target.to]: 1_000 }));+ const body = Array.from({ length: 300 }, (_, i) => `Synthetic recovery sentence ${i} phi chi psi omega alpha beta.`).join(' ');+ await engine.putPage('settle-recover', { type: 'note', title: 'Synthetic recover', compiled_truth: body });+ configureGateway({ embedding_model: model, embedding_dimensions: dimensions, env: { OPENAI_API_KEY: 'synthetic-only', NVIDIA_API_KEY: 'synthetic-only' } });+ try {+ const preview = await cli(['--dry-run'], target);+ const printed = /Worst-case authorization: \$(\d+(?:\.\d+)?)/.exec(preview.text);+ expect(printed).not.toBeNull();+ __setEmbedTransportForTests(async ({ values }: { values: string[] }) => ({ values, warnings: [],+ embeddings: values.map(() => Array.from({ length: target.dim }, (_, i) => (i + 1) / target.dim)),+ usage: { tokens: values.reduce((sum, value) => sum + Math.min(perInput, Buffer.byteLength(value, 'utf8')), 0) } }));+ const run = await cli(['--max-cost-usd', printed![1], '--json'], target);+ expect(run.text).toContain('"status": "completed"');+ expect((await vectors()).every(row => row.embedding !== null)).toBe(true);+ } finally {+ await runSchemaTransition(engine, dimensions);+ }+ });+ });+}diff --git a/test/embedding-zero-norm-4616.serial.test.ts b/test/embedding-zero-norm-4616.serial.test.tsnew file mode 100644index 0000000000..3ad2244c79--- /dev/null+++ b/test/embedding-zero-norm-4616.serial.test.ts@@ -0,0 +1,162 @@+/**+ * #4616: the embedding gateway refuses vectors an ANN index cannot serve.+ *+ * A zero-norm, NaN or ±Inf vector has no cosine direction, so HNSW silently+ * skips its row and the chunk becomes unreachable by vector search while+ * keyword search still finds it. The refusal (`embedding_zero_norm`) is+ * terminal per item: the other chunks of the batch land, the refused chunk+ * stays unembedded, and the failure names the page's recovery command and+ * docs anchor. Empty inputs never reach the provider.+ *+ * Installs the process-global gateway transport seam (always fake), so this+ * stays a `.serial.test.ts`. Runs on PGLite, and on Postgres when the E2E+ * wrapper provides DATABASE_URL.+ */+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';+import { runEmbedCore } from '../src/commands/embed.ts';+import { __setEmbedTransportForTests, configureGateway, embed, resetGateway } from '../src/core/ai/gateway.ts';+import { embedBatch } from '../src/core/embedding.ts';+import { EmbeddingZeroNormError } from '../src/core/ai/embedding-guard.ts';+import { importFromContent } from '../src/core/import-file.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine, buildWalRepairNotice } from '../src/core/pglite-engine.ts';+import { runReindexVectors } from '../src/commands/reindex-vectors.ts';+import { EMBED_PROBE_TEXT } from '../src/core/embed-stale.ts';+import { installFixtureChunks } from './helpers/page-projection.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';++const DIMS = 1536;+const MODEL = 'openai:text-embedding-3-large';+const BAD: Record<string, number> = { zero: 0, nan: Number.NaN, inf: Number.POSITIVE_INFINITY };++let sent: string[][] = [];+let badValue = 0;++function vectorFor(text: string): number[] {+ if (text.includes('DEGENERATE')) return new Array(DIMS).fill(0).map((_, i) => (i === 0 ? badValue : 0));+ return new Array(DIMS).fill(0.01);+}++beforeAll(() => {+ configureGateway({ embedding_model: MODEL, embedding_dimensions: DIMS, env: { ...process.env, OPENAI_API_KEY: 'sk-test-fake' } });+ __setEmbedTransportForTests((async (input: { values: string[] }) => {+ sent.push(input.values.filter(v => v !== EMBED_PROBE_TEXT));+ return { embeddings: input.values.map(vectorFor), usage: { tokens: input.values.length } };+ }) as never);+});++afterAll(() => {+ __setEmbedTransportForTests(null);+ resetGateway();+});++afterEach(() => { sent = []; badValue = 0; });++describe('#4616 WAL-repair notice', () => {+ test('says indexes were not rebuilt and names the exact rebuild command', () => {+ const notice = buildWalRepairNotice({ dataDir: '/brain/brain.pglite', backupPath: '/brain/backup', backedUpFiles: [], reusedEpisodeBackup: false,+ resetSegment: '000000010000000000000002', timelineId: 1, walSegSize: 16 * 1024 * 1024, repairedAt: '2026-01-01T00:00:00.000Z' });+ expect(notice).not.toContain('Data files were preserved');+ expect(notice).toContain('indexes are not rebuilt');+ expect(notice).toContain('missing from vector search');+ expect(notice).toContain('`gbrain reindex --vectors`');+ });+});++describe('#4616 gateway guard', () => {+ test('empty and whitespace-only inputs are refused before the provider call', async () => {+ const error = await embed(['first input', ' ', 'third input']).catch(e => e);+ expect(error).toBeInstanceOf(EmbeddingZeroNormError);+ expect(error.code).toBe('embedding_zero_norm');+ expect(error.failures).toEqual([{ index: 1, reason: 'empty_input' }]);+ expect(error.vectors[0]).toBeInstanceOf(Float32Array);+ expect(error.vectors[1]).toBeNull();+ expect(error.vectors[2]).toBeInstanceOf(Float32Array);+ expect(sent).toEqual([['first input', 'third input']]);+ });++ test('an all-empty call never reaches the provider', async () => {+ await expect(embed(['', ' \n'])).rejects.toBeInstanceOf(EmbeddingZeroNormError);+ expect(sent).toEqual([]);+ });++ test('a degenerate vector past the first 100-input slice keeps every other slice', async () => {+ badValue = 0;+ const texts = Array.from({ length: 250 }, (_, i) => (i === 180 ? `chunk ${i} DEGENERATE` : `chunk ${i}`));+ const error = await embedBatch(texts, { onBatchComplete: () => {} }).catch(e => e);+ expect(error).toBeInstanceOf(EmbeddingZeroNormError);+ expect(error.failures).toEqual([{ index: 180, reason: 'zero_norm' }]);+ expect(error.vectors.filter(Boolean)).toHaveLength(249);+ expect(error.vectors[180]).toBeNull();+ });+});++for (const kind of testBackends()) describe(`#4616 per-item refusal on write paths (${kind})`, () => {+ 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({ embedding_dimensions: DIMS } as never); await engine.initSchema(); }+ }, 120_000);+ afterAll(async () => { if (close) await close(); else await engine.disconnect(); });++ const embeddedIndexes = async (slug: string) => (await engine.executeRaw<{ chunk_index: number }>(+ `SELECT c.chunk_index FROM content_chunks c JOIN pages p ON p.id=c.page_id+ WHERE p.slug=$1 AND p.source_id='default' AND c.embedding IS NOT NULL ORDER BY c.chunk_index`, [slug])).map(r => Number(r.chunk_index));++ for (const [label, value] of Object.entries(BAD)) {+ test(`one ${label} vector in a 100-chunk batch fails that chunk and the other 99 land`, async () => {+ badValue = value;+ const slug = `zero-norm-${label}`;+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: `# ${slug}` });+ await installFixtureChunks(engine, slug, Array.from({ length: 100 }, (_, i) => ({+ chunk_index: i, chunk_text: i === 42 ? `chunk ${i} DEGENERATE` : `chunk ${i} body`, chunk_source: 'compiled_truth' as const, token_count: 4,+ })));+ const result = await runEmbedCore(engine, { stale: true, catchUp: true, quiet: true });+ expect(result.embedded).toBe(99);+ expect(result.failures).toBe(1);+ expect(result.failure_samples.join('\n')).toContain('embedding_zero_norm');+ expect(result.failure_samples.join('\n')).toContain(`gbrain embed ${slug}`);+ expect(result.failure_samples.join('\n')).toContain('docs/guides/write-refusals.md#embedding_zero_norm');+ const embedded = await embeddedIndexes(slug);+ expect(embedded).toHaveLength(99);+ expect(embedded).not.toContain(42);+ // The degenerate chunk was sent once and never retried as a transient failure.+ expect(sent.flat().filter(t => t.includes('DEGENERATE'))).toHaveLength(1);+ await engine.deletePage(slug, { sourceId: 'default' });+ });+ }++ test('reindex --vectors rebuilds every HNSW index and vector search still serves the rows', async () => {+ const slug = 'reindex-vectors-fixture';+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: `# ${slug}` });+ await installFixtureChunks(engine, slug, [{ chunk_index: 0, chunk_text: 'vector fixture', chunk_source: 'compiled_truth', token_count: 2,+ embedding: new Float32Array(DIMS).fill(0.01), model: MODEL }]);+ const preview = await runReindexVectors(engine, ['--dry-run', '--json']);+ expect(preview.rebuilt).toBe(0);+ expect(preview.indexes.map(i => i.index)).toContain('idx_chunks_embedding');+ const result = await runReindexVectors(engine, ['--json']);+ expect(result.rebuilt).toBe(preview.indexes.length);+ const hits = await engine.searchVector(new Float32Array(DIMS).fill(0.01), { limit: 5 });+ expect(hits.map(h => h.slug)).toContain(slug);+ await engine.deletePage(slug, { sourceId: 'default' });+ });++ test('an import keeps the usable vectors and leaves the refused chunk for embed --stale', async () => {+ badValue = 0;+ const slug = 'zero-norm-import';+ const sections = Array.from({ length: 6 }, (_, i) => `## Section ${i}\n\n${(i === 3 ? 'DEGENERATE ' : '') + `Paragraph ${i} `.repeat(400)}`);+ const result = await importFromContent(engine, slug, `---\ntype: note\ntitle: Zero norm import\n---\n\n${sections.join('\n\n')}\n`);+ expect(result.status).toBe('imported');+ expect(result.chunks).toBeGreaterThan(1);+ expect(result.embedding_deferred).toBe(true);+ const chunks = await engine.executeRaw<{ chunk_text: string; embedded: boolean }>(+ `SELECT c.chunk_text, c.embedding IS NOT NULL AS embedded FROM content_chunks c JOIN pages p ON p.id=c.page_id+ WHERE p.slug=$1 AND p.source_id='default' ORDER BY c.chunk_index`, [slug]);+ for (const chunk of chunks) expect(chunk.embedded).toBe(!chunk.chunk_text.includes('DEGENERATE'));+ expect(chunks.some(c => !c.embedded)).toBe(true);+ const [page] = await engine.executeRaw<{ embedding_signature: string | null }>(+ "SELECT embedding_signature FROM pages WHERE slug=$1 AND source_id='default'", [slug]);+ expect(page.embedding_signature).toBeNull();+ });+});diff --git a/test/enrich/evidence-order.test.ts b/test/enrich/evidence-order.test.tsindex aeaacd699a..4177c5cf8e 100644--- a/test/enrich/evidence-order.test.ts+++ b/test/enrich/evidence-order.test.ts@@ -193,15 +193,6 @@ describe('runEnrichCore evidence + counters (#2085)', () => {expect(requests.map(row => row.state)).toEqual(['conflict']);}, 30000);- test('managed enrichment refuses before invoking providers or advancing checkpoints', async () => {- await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');- let calls = 0;- await expect(runEnrichCore(engine, { ...coreOpts, synthesizeFn: async () => { calls++; return 'SKIP'; } }))- .rejects.toMatchObject({ code: 'writer_coordinator_required' });- expect(calls).toBe(0);- expect(await engine.executeRaw("SELECT * FROM op_checkpoints WHERE op='enrich'")).toEqual([]);- });-test('model SKIP → pages_model_skip; empty output → pages_empty_output', async () => {await seedStub('people/alice-example', 'Alice Example');await seedBacklink('people/alice-example', 'meetings/m1',diff --git a/test/extract-atoms-accepted-pending.test.ts b/test/extract-atoms-accepted-pending.test.tsnew file mode 100644index 0000000000..60bd5329c8--- /dev/null+++ b/test/extract-atoms-accepted-pending.test.ts@@ -0,0 +1,60 @@+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { mkdtempSync, mkdirSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { configureGateway, resetGateway, type ChatResult } from '../src/core/ai/gateway.ts';+import { runPhaseExtractAtoms } from '../src/core/cycle/extract-atoms.ts';+import { registerLocalWriter } from '../src/core/persistence/identity.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { disposePersistenceConsumer, startPersistenceConsumer, waitForWrite } from '../src/core/persistence/service.ts';+import type { WriteRequest } from '../src/core/persistence/model.ts';+import { withEnv } from './helpers/with-env.ts';++// #5601: an atom batch the owner accepted but has not published yet is+// progress. extract_atoms reports it as pending, counts no failure and no+// halt, and the next run resumes the same batch without paying again.++let engine: PGLiteEngine;+const home = mkdtempSync(join(tmpdir(), 'gbrain-atoms-pending-'));+beforeAll(async () => {+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} });+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();+}, 60_000);+afterAll(async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); resetGateway(); rmSync(home, { recursive: true, force: true }); });++test('#5601: extract_atoms with a slow owner reports accepted-pending, not failed, and resumes without a second model call', async () => withEnv({ GBRAIN_HOME: home }, async () => {+ const sourceId = 'atoms-pending';+ const root = join(home, 'repo'); mkdirSync(root);+ 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)', [sourceId, root]);+ await engine.putPage('notes/2026-01-01-example', { type: 'source', title: 'Example', compiled_truth: 'A durable project record. '.repeat(40) }, { sourceId });+ const page = (await engine.getPage('notes/2026-01-01-example', { sourceId }))!;+ await registerLocalWriter(engine, 'cli');+ const binding = await claimWorktree(engine, sourceId, root);+ await engine.setConfig('sync.write_through', 'true');+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ let calls = 0;+ const chat = async (): Promise<ChatResult> => {+ calls++;+ // The owner stalls after admission: the batch is accepted and stays queued.+ await engine.executeRaw("UPDATE persistence_worktrees SET state='draining' WHERE id=$1::uuid", [binding.worktree_id]);+ return { text: '[{"title":"Measured progress","atom_type":"insight","body":"Measure progress against clear exit criteria."}]',+ blocks: [], stopReason: 'end', usage: { input_tokens: 10, output_tokens: 10, cache_read_tokens: 0, cache_creation_tokens: 0 }, model: 'anthropic:claude-haiku-4-5', providerId: 'anthropic' };+ };+ const run = () => runPhaseExtractAtoms(engine, { sourceId, _chat: chat, _transcripts: [], _pages: [{ slug: page.slug, content: page.compiled_truth, contentHash: page.content_hash! }] });+ const first = await run();+ expect(first.status).toBe('ok');+ expect(first.details).toMatchObject({ write_pending: 1, failures: [] });+ const [rollup] = await engine.executeRaw<{ halts: number }>("SELECT COALESCE(sum(halt_count),0)::int AS halts FROM extract_rollup_7d WHERE kind='atoms' AND source_id=$1", [sourceId]);+ expect(rollup.halts).toBe(0);+ const queued = await engine.executeRaw<WriteRequest>("SELECT * FROM persistence_requests WHERE source_id=$1 AND state='queued'", [sourceId]);+ expect(queued.length).toBeGreaterThan(0);+ await disposePersistenceConsumer(engine);+ await engine.executeRaw("UPDATE persistence_worktrees SET state='active' WHERE id=$1::uuid", [binding.worktree_id]);+ startPersistenceConsumer(engine, { engine: engine.kind });+ for (const row of queued) expect((await waitForWrite(engine, row, { engine: engine.kind }, 20_000)).state).toBe('committed');+ const second = await run();+ expect(second.details).toMatchObject({ duplicates_skipped: 1, failures: [] });+ expect(calls).toBe(1);+}), 90_000);diff --git a/test/fix-wave-3-chaos.test.ts b/test/fix-wave-3-chaos.test.tsnew file mode 100644index 0000000000..9ab5c1fc25--- /dev/null+++ b/test/fix-wave-3-chaos.test.ts@@ -0,0 +1,117 @@+/**+ * Fix wave 3 chaos scenario: a delayed persistence consumer with sustained+ * connector arrivals, then a provider outage, then recovery. PGLite here;+ * Postgres through test/e2e/fix-wave-3-integration.test.ts.+ *+ * Authoring gate. (1) Protects the backlog contract across Lane A's pending+ * batches and the consumer: every accepted connector write publishes once the+ * owner recovers, nothing is admitted twice, an outage neither loses the+ * pending set nor stamps freshness, and the backlog drains with no operator+ * step. (2) Fails when a pending set is dropped by an outage, when a later+ * sweep re-admits pages still pending, or when the drain stalls. (3) Lane A's+ * pending-set tests pause one run; none sustains arrivals across several+ * stopped runs and an outage. (4) No seam: the owner is delayed by draining its+ * worktree, the provider by a fixture fetcher. It reports time-to-searchable,+ * oldest pending age and drain rate on stderr.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import type { BrainEngine } from '../src/core/engine.ts';+import { parseGoogleSourceConfig, runGoogleSync } from '../src/core/google/google-source.ts';+import { disposePersistenceConsumer, startPersistenceConsumer } from '../src/core/persistence/service.ts';+import { connectorWaitBudget } from '../src/core/persistence/connector-sync.ts';+import { withEnv } from './helpers/with-env.ts';+import { createConnectorFixture, options, json, googleConfig, contact, withGoogleAccount, connectorPendingSet } from './helpers/connector-fixture.ts';++const fixture = createConnectorFixture();+const { engines, env, boundSource } = fixture;+beforeAll(fixture.setup, 120_000);+afterAll(fixture.teardown);++const ARRIVALS_PER_SWEEP = 4;+const SWEEPS = 3;++async function worktree(engine: BrainEngine, id: string, state: 'draining' | 'active') {+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw('UPDATE persistence_worktrees SET state=$2 WHERE id=$1::uuid', [id, state]);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+}++test('delayed consumer, sustained arrivals and a provider outage: the backlog drains with every page published once', async () => withEnv(env, async () => {+ const budget = connectorWaitBudget.ms;+ connectorWaitBudget.ms = 1_000;+ try {+ for (const engine of engines) {+ const f = await boundSource(engine, googleConfig);+ let listed = 0, down = false;+ const fetcher = async (url: string) => {+ if (url.includes('/settings/sendAs')) return json({ sendAs: [] });+ if (down) return json({ error: { message: 'fixture people outage' } }, 503);+ return json({ connections: Array.from({ length: listed }, (_, i) => contact(`arrival-${i}`, `Arrival Example ${i}`)), nextSyncToken: `contacts-${listed}` });+ };+ const run = () => runGoogleSync(engine, f.id, parseGoogleSourceConfig(googleConfig, f.dir), options, withGoogleAccount(fetcher)).catch(error => error);+ await worktree(engine, f.binding.worktree_id, 'draining');+ const started = Date.now();+ for (let sweep = 0; sweep < SWEEPS; sweep++) {+ listed += ARRIVALS_PER_SWEEP;+ await run();+ await disposePersistenceConsumer(engine);+ }+ const total = SWEEPS * ARRIVALS_PER_SWEEP;+ const queued = async () => (await engine.executeRaw<{ n: number }>(+ "SELECT COUNT(*)::int AS n FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='connector_v2_import' AND state IN ('queued','running')", [f.id]))[0]!.n;+ // While the owner is delayed, each sweep first waits on its recorded pending set and stops on the+ // wait budget; the checkpoint never advances past a pending page, so later arrivals wait upstream.+ const backlog = await queued();+ expect(backlog).toBeGreaterThanOrEqual(ARRIVALS_PER_SWEEP);+ expect(backlog).toBeLessThanOrEqual(total);+ expect((await connectorPendingSet(engine, f.id)).length).toBe(backlog);+ // The provider goes down while the owner is still delayed: nothing is lost or stamped.+ down = true;+ const lastSync = (await engine.executeRaw<{ at: string | null }>('SELECT last_sync_at::text AS at FROM sources WHERE id=$1', [f.id]))[0]!.at;+ await run();+ await disposePersistenceConsumer(engine);+ expect(await queued()).toBe(backlog);+ expect((await connectorPendingSet(engine, f.id)).length).toBe(backlog);+ expect((await engine.executeRaw<{ at: string | null }>('SELECT last_sync_at::text AS at FROM sources WHERE id=$1', [f.id]))[0]!.at).toBe(lastSync);+ const [oldest] = await engine.executeRaw<{ age_ms: number }>(+ "SELECT (EXTRACT(EPOCH FROM (now()-min(created_at)))*1000)::int AS age_ms FROM persistence_requests WHERE source_id=$1 AND state IN ('queued','running')", [f.id]);+ // Recovery: the owner and the provider return.+ down = false;+ const recovered = Date.now();+ await worktree(engine, f.binding.worktree_id, 'active');+ startPersistenceConsumer(engine, { engine: engine.kind });+ const deadline = Date.now() + 60_000;+ while (await queued() > 0 && Date.now() < deadline) await Bun.sleep(100);+ expect(await queued()).toBe(0);+ const drainMs = Date.now() - recovered;+ // Sweeps pick up the arrivals that waited upstream until every page is in, then admit nothing new.+ const imports = async () => (await engine.executeRaw<{ n: number }>("SELECT COUNT(*)::int AS n FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='connector_v2_import'", [f.id]))[0]!.n;+ let sweeps = 0;+ const present = async () => (await engine.executeRaw<{ n: number }>("SELECT COUNT(*)::int AS n FROM pages WHERE source_id=$1 AND slug LIKE 'people/arrival-example-%' AND deleted_at IS NULL", [f.id]))[0]!.n;+ const drain = async () => { while (await queued() > 0 && Date.now() < deadline) await Bun.sleep(100); };+ while (await present() < total && sweeps < 3) { await run(); await drain(); sweeps++; }+ expect(await present()).toBe(total);+ while (await queued() > 0 && Date.now() < deadline) await Bun.sleep(100);+ const searchable = async () => (await Promise.all(Array.from({ length: total }, async (_, i) =>+ (await engine.searchKeyword(`Arrival Example ${i}`, { sourceId: f.id } as never)).some(r => r.slug === `people/arrival-example-${i}`)))).every(Boolean);+ while (!await searchable() && Date.now() < deadline) await Bun.sleep(100);+ expect(await searchable()).toBe(true);+ const timeToSearchable = Date.now() - started;+ await disposePersistenceConsumer(engine);+ const before = await imports();+ await run();+ await disposePersistenceConsumer(engine);+ expect(await imports()).toBe(before);+ // Each arrival was admitted exactly once across the delay, the outage and recovery.+ expect(before).toBe(total);+ // No page is left pending; a checkpoint save may still be settling and resolves on the next run.+ expect((await connectorPendingSet(engine, f.id)).filter(item => item.itemRef !== '__managed_connector_checkpoint__')).toEqual([]);+ const pages = await engine.executeRaw<{ slug: string }>("SELECT slug FROM pages WHERE source_id=$1 AND slug LIKE 'people/arrival-example-%' AND deleted_at IS NULL", [f.id]);+ expect(pages).toHaveLength(total);+ const failed = await engine.executeRaw("SELECT 1 FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='connector_v2_import' AND state<>'committed'", [f.id]);+ expect(failed).toEqual([]);+ console.error(`[chaos] ${engine.kind} arrivals=${total} oldest_pending_ms=${oldest!.age_ms} drain_ms=${drainMs} `+ + `backlog=${backlog} drain_rate_per_s=${(backlog / Math.max(drainMs / 1000, 0.001)).toFixed(1)} time_to_searchable_ms=${timeToSearchable}`);+ }+ } finally { connectorWaitBudget.ms = budget; }+}), 300_000);diff --git a/test/fix-wave-3-connector-loops.serial.test.ts b/test/fix-wave-3-connector-loops.serial.test.tsnew file mode 100644index 0000000000..a81cc78a72--- /dev/null+++ b/test/fix-wave-3-connector-loops.serial.test.ts@@ -0,0 +1,52 @@+/**+ * Fix wave 3 cross-lane check: Lane B's coordinated Google loop extraction on+ * Lane A's database-only connector source.+ *+ * Authoring gate. (1) Protects loop extraction on the default connector+ * layout: a Google source with a local path and no canonical owner syncs+ * database-only (`connector_database`), so extracting its commitments must+ * publish database-only too, not refuse for want of an owner. (2) Fails when+ * the shared facts session demands a canonical owner for a connector source,+ * as it did before this integration (`owner_unavailable` before extraction).+ * (3) test/managed-facts-writers.test.ts runs loop extraction on a bound+ * filesystem source only. (4) The chat model is the gateway's process-global+ * transport seam, so this file is serial.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import type { OperationContext } from '../src/core/ops/contract.ts';+import { configureGateway, resetGateway, __setChatTransportForTests, type ChatResult } from '../src/core/ai/gateway.ts';+import { runLoopsExtract } from '../src/core/google/loops-extract.ts';+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { withEnv } from './helpers/with-env.ts';+import { createConnectorFixture, googleConfig } from './helpers/connector-fixture.ts';++const fixture = createConnectorFixture();+const { engines, env, source } = fixture;+const usage = { input_tokens: 10, output_tokens: 10, cache_read_tokens: 0, cache_creation_tokens: 0 };+beforeAll(fixture.setup, 120_000);+afterAll(async () => { __setChatTransportForTests(null); resetGateway(); await fixture.teardown(); });++test('loop extraction on a database-only connector source lands its commitment fact through the coordinator', async () => withEnv(env, async () => {+ configureGateway({ chat_model: 'anthropic:claude-sonnet-4-6', env: { ANTHROPIC_API_KEY: 'sk-ant-test' } });+ __setChatTransportForTests(async (): Promise<ChatResult> => ({ text: JSON.stringify({ commitments: [{ text: 'Send the deck by Friday', direction: 'owed_by_me',+ counterparty_name: 'people/alice-example', counterparty_email: '', due_iso: '2026-10-02', quote: 'I will send the deck by Friday.' }], decisions_pending: [] }),+ blocks: [], stopReason: 'end', usage, model: 'anthropic:claude-sonnet-4-6', providerId: 'anthropic' }));+ for (const engine of engines) {+ const f = await source(engine, googleConfig);+ await engine.setConfig('loops.extraction_enabled', 'true');+ const ctx = { engine, config: { engine: engine.kind, embedding_disabled: true }, sourceId: f.id, remote: false, dryRun: false,+ logger: { info() {}, warn() {}, error() {} } } as unknown as OperationContext;+ const put = (slug: string, content: string) => submitPageMutation(ctx, { operation: 'put_page', params: { slug, content, request_id: randomUUID() } });+ await put('people/alice-example', '---\ntitle: Alice Example\ntype: person\n---\n# Alice Example\n');+ await put('emails/example', '---\ntitle: Synthetic exchange\ntype: email\nthread_id: example\nfrom: [email protected]\n---\nI will send the deck by Friday.\n');+ const result = await runLoopsExtract(engine, { slug: 'emails/example', sourceId: f.id });+ expect(result).toMatchObject({ status: 'extracted', commitments: 1 });+ const rows = await engine.executeRaw<{ fact: string }>(+ "SELECT f.fact FROM facts f WHERE f.source_id=$1 AND f.entity_slug='people/alice-example' AND f.expired_at IS NULL", [f.id]);+ expect(rows.map(r => r.fact)).toEqual(['Send the deck by Friday']);+ expect(await engine.executeRaw('SELECT 1 FROM persistence_source_bindings WHERE source_id=$1', [f.id])).toHaveLength(0);+ await disposePersistenceConsumer(engine);+ }+}), 180_000);diff --git a/test/fix-wave-3-integration.test.ts b/test/fix-wave-3-integration.test.tsnew file mode 100644index 0000000000..0f61d83bb2--- /dev/null+++ b/test/fix-wave-3-integration.test.ts@@ -0,0 +1,578 @@+/**+ * Fix wave 3 integrated scenario gate: the twelve cross-lane checks from the+ * wave plan, on PGLite here and on Postgres through+ * test/e2e/fix-wave-3-integration.test.ts. Checks 1-8 are the S1 gate.+ *+ * Authoring gate. (1) Protects the seams between the four lanes: connector+ * identity, no-op skip and pending batches (Lane A); coordinated maintenance+ * writers and the #5254 unbound policy (Lane B); embedding and projection+ * repairs (Lane C); and the recovery layer, writer-version stamps and admin+ * lock (Lane D). (2) Fails when one lane's contract breaks another's: a+ * connector re-render that deletes history a user added, a page write that+ * claims a connector's database-only source, a repair kind missing from the+ * remediation plan, a reconcile that leaves the unbound marker behind, a+ * publication stamped after its recheck failed. (3) Each lane's own suite+ * covers its path alone (test/connector-wave3.test.ts,+ * test/managed-writers-w3.test.ts, test/repair-contextual-mode-5621.serial.test.ts,+ * test/recovery-layer.test.ts and siblings); none runs two lanes' code on one+ * brain. (4) No production seam: every step goes through the real mutation,+ * connector, repair, doctor and reconcile entry points.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { existsSync, mkdirSync, readFileSync, rmSync, 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 type { WriteRequest } from '../src/core/persistence/model.ts';+import { parseGoogleSourceConfig, runGoogleSync } from '../src/core/google/google-source.ts';+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { submitRememberMutation, submitForgetMutation } from '../src/core/persistence/memory-mutations.ts';+import { disposePersistenceConsumer, startPersistenceConsumer, waitForWrite, writeResponse } from '../src/core/persistence/service.ts';+import { admitWrite, compactWriteReceipts } from '../src/core/persistence/journal.ts';+import { declarePersistenceProtocol } from '../src/core/persistence/protocol.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { setWriterAdminLock } from '../src/core/persistence/admin-lock.ts';+import { writerStamp } from '../src/core/persistence/writer-versions.ts';+import { connectorCheckpointKey, connectorIdentity } from '../src/core/persistence/connector-identity.ts';+import { CONNECTOR_MIGRATION_OP } from '../src/core/persistence/connector-checkpoint-migration.ts';+import { localHostId, registerLocalWriter, withVerifiedLocalRegistration } from '../src/core/persistence/identity.ts';+import { runPersistenceEffects } from '../src/core/persistence/effects.ts';+import { runReconcileApply, runReconcilePreview } from '../src/core/persistence/reconcile.ts';+import { resolveRepairScope } from '../src/core/repair/core.ts';+import { REPAIR_REGISTRY, repairRunner } from '../src/core/repair/registry.ts';+import { planRepairSteps } from '../src/core/remediation/repairs.ts';+import { runWaveChecks, remoteWaveHandoff, WAVE_CHECKS } from '../src/commands/doctor/wave-checks.ts';+import { writerVersionCheck } from '../src/commands/doctor/checks/writer-version.ts';+import { checkUnboundSource } from '../src/commands/doctor/checks/unbound-source.ts';+import { runRemediate } from '../src/commands/doctor/remediate.ts';+import { runPhaseSynthesizeConcepts } from '../src/core/cycle/synthesize-concepts.ts';+import { timeContainedPhase } from '../src/core/cycle/phase-containment.ts';+import { LockStolenError } from '../src/core/db-lock.ts';+import { chat, configureGateway, resetGateway, __setChatTransportForTests, type ChatResult } from '../src/core/ai/gateway.ts';+import { postUpgradeRecoveryBanner } from '../src/commands/doctor/upgrade-banner.ts';+import { handleToolCall } from '../src/mcp/server.ts';+import { ALL_SOURCES } from '../src/core/source-id.ts';+import { withEnv } from './helpers/with-env.ts';+import { capture } from './helpers/wave-scenarios.ts';+import { createConnectorFixture, options, json, googleConfig, githubConfig, issueFixture, githubFetch, contact, withGoogleAccount } from './helpers/connector-fixture.ts';+import { parseGitHubSourceConfig, runGitHubSync } from '../src/core/github-source.ts';+import { renderFactsTable } from '../src/core/facts-fence.ts';++const fixture = createConnectorFixture();+const { engines, env, source, boundSource, home } = fixture;+beforeAll(fixture.setup, 120_000);+afterAll(fixture.teardown);++const quiet = { info() {}, warn() {}, error() {} };+const ctxFor = (engine: BrainEngine, sourceId: string) => ({ engine, config: { engine: engine.kind, embedding_disabled: true },+ sourceId, remote: false, dryRun: false, logger: quiet }) as unknown as OperationContext;+const mark = async (engine: BrainEngine, id: string) =>+ (await engine.executeRaw<{ seq: string | null }>('SELECT max(sequence)::text AS seq FROM persistence_requests WHERE source_id=$1', [id]))[0]?.seq ?? '0';+async function admissions(engine: BrainEngine, id: string, after: string) {+ const rows = await engine.executeRaw<{ kind: string | null }>("SELECT intent->>'kind' AS kind FROM persistence_requests WHERE source_id=$1 AND sequence>$2::bigint", [id, after]);+ return { pages: rows.filter(r => /_(import|delete)$/.test(r.kind ?? '')).length, checkpoints: rows.filter(r => (r.kind ?? '').endsWith('_checkpoint')).length };+}+const incarnation = async (engine: BrainEngine, id: string) => (await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text FROM sources WHERE id=$1', [id]))[0]!.incarnation;+const protocol = (engine: BrainEngine, sql: string, params: unknown[] = []) =>+ engine.transaction(async tx => { await declarePersistenceProtocol(tx); await tx.executeRaw(sql, params); });++/** A People listing with a stable sync token; `org` changes the rendered page, `fail` models a provider outage. */+function people(list: () => Array<Record<string, unknown>>, opts: { fail?: () => boolean; onList?: () => Promise<void> } = {}) {+ return async (url: string) => {+ if (url.includes('/settings/sendAs')) return json({ sendAs: [] });+ if (opts.fail?.()) return json({ error: { message: 'fixture people outage' } }, 503);+ await opts.onList?.();+ return json({ connections: new URL(url).searchParams.has('syncToken') ? [] : list(), nextSyncToken: 'contacts-stable' });+ };+}+const google = (engine: BrainEngine, f: { id: string; dir: string }, fetcher: (url: string) => Promise<Response>, extra: object = {}, config: Record<string, unknown> = googleConfig) =>+ runGoogleSync(engine, f.id, parseGoogleSourceConfig(config, f.dir), { ...options, ...extra }, withGoogleAccount(fetcher));+/** One connector run on a paused consumer, then the admissions it made. */+async function quietRun(engine: BrainEngine, f: { id: string; dir: string }, fetcher: (url: string) => Promise<Response>, extra: object = {},+ config: Record<string, unknown> = googleConfig) {+ await disposePersistenceConsumer(engine);+ const before = await mark(engine, f.id);+ await google(engine, f, fetcher, extra, config);+ return admissions(engine, f.id, before);+}+const addTimeline = (engine: BrainEngine, sourceId: string, slug: string, summary: string, date = '2026-03-01') => submitPageMutation(ctxFor(engine, sourceId),+ { operation: 'add_timeline_entry', params: { request_id: randomUUID(), slug, date, summary, source: 'operator' } });+const timeline = async (engine: BrainEngine, sourceId: string, slug: string) => (await engine.getTimeline(slug, { sourceId })).map(row => row.summary);+const VECTOR = `[${Array(1536).fill(0.01).join(',')}]`;++test('check 1 (S1): a cycle stamp mid-sweep while connector pages are pending; they publish and carry this release\'s writer stamps', async () => withEnv(env, async () => {+ for (const engine of engines) {+ const f = await boundSource(engine, googleConfig);+ // Hold publication: the owner's worktree drains, so accepted writes stay pending.+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw("UPDATE persistence_worktrees SET state='draining' WHERE id=$1::uuid", [f.binding.worktree_id]);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const stamp = async () => { const now = new Date().toISOString(); await engine.updateSourceConfig(f.id, { last_source_cycle_at: now, last_full_cycle_at: now }); };+ const fetcher = people(() => [contact('first', 'First Example'), contact('second', 'Second Example')], { onList: stamp });+ try { await google(engine, f, fetcher); } catch { /* the sweep stops on its wait budget with writes pending */ }+ const pending = await engine.executeRaw<WriteRequest>("SELECT * FROM persistence_requests WHERE source_id=$1 AND intent->>'kind' LIKE '%import' AND state='queued'", [f.id]);+ expect(pending.length).toBe(2);+ await stamp();+ await disposePersistenceConsumer(engine);+ await engine.executeRaw("UPDATE persistence_worktrees SET state='active' WHERE id=$1::uuid", [f.binding.worktree_id]);+ startPersistenceConsumer(engine, { engine: engine.kind });+ const { version } = writerStamp();+ for (const row of pending) {+ const done = await waitForWrite(engine, row, { engine: engine.kind }, 20_000);+ expect(done.state).toBe('committed');+ // Lane D stamps both sides of a Lane A connector publication; the publication time is the database clock.+ expect(done).toMatchObject({ admitter_version: version, consumer_version: version });+ expect((done as WriteRequest & { published_at: unknown }).published_at).not.toBeNull();+ }+ expect(readFileSync(join(f.dir, 'people/first-example.md'), 'utf8')).toContain('First Example');+ await disposePersistenceConsumer(engine);+ }+}), 180_000);++test('check 2 (S1): the no-op skip holds across a user timeline entry, a withdrawn fact, the contextual-mode repair and a safe-chunk reseal; the connector re-render keeps the history', async () => withEnv(env, async () => {+ for (const engine of engines) for (const bound of [true, false]) {+ const f = bound ? await boundSource(engine, googleConfig) : await source(engine, googleConfig);+ let org = 'Example Org';+ const fetcher = people(() => [{ ...contact('first', 'First Example'), organizations: [{ name: org }] }]);+ const slug = 'people/first-example';+ await google(engine, f, fetcher);+ // A user adds history to a connector page. On a database-only connector source the write stays+ // database-only (it never claims the connector's source); on a bound one it lands in the file.+ expect((await addTimeline(engine, f.id, slug, 'Operator note')).state).toBe('committed');+ // An earlier entry is spliced above the marked one without separating that bullet from its marker.+ expect((await addTimeline(engine, f.id, slug, 'Earlier note', '2026-02-01')).state).toBe('committed');+ expect(await engine.executeRaw('SELECT 1 FROM persistence_source_bindings WHERE source_id=$1', [f.id])).toHaveLength(bound ? 1 : 0);+ // A withdrawn fact and a live fact on the same page.+ const ctx = ctxFor(engine, f.id);+ const live = await submitRememberMutation(ctx, { fact: 'Example live detail', entity: slug, provenance: 'integration', visibility: 'world' }) as { id: number };+ const remembered = await submitRememberMutation(ctx, { fact: 'Example retired detail', entity: slug, provenance: 'integration', visibility: 'world' }) as { id: number };+ await submitForgetMutation(ctx, 'forget', { id: remembered.id });+ // An upstream change re-renders the page from the provider: the user's entry survives (#5567).+ org = 'Renamed Example Org';+ expect((await quietRun(engine, f, fetcher, { resetCheckpoint: true })).pages).toBe(1);+ expect((await timeline(engine, f.id, slug)).sort()).toEqual(['Earlier note', 'Operator note']);+ const page = (await engine.readPageSnapshot(slug, { sourceId: f.id }))!;+ expect(page.page.compiled_truth).toContain('Renamed Example Org');+ expect(page.page.timeline).toContain('Operator note');+ expect(page.page.timeline).toContain('Earlier note');+ if (bound) expect(readFileSync(join(f.dir, `${slug}.md`), 'utf8')).toContain('Earlier note');+ const facts = async () => Object.fromEntries((await engine.executeRaw<{ id: number; expired: boolean }>('SELECT id,expired_at IS NOT NULL AS expired FROM facts WHERE id=ANY($1::int[])',+ [[remembered.id, live.id]])).map(row => [Number(row.id), row.expired]));+ // The re-render keeps the page's facts fence: the withdrawn fact stays withdrawn, the live one stays live.+ expect(await facts()).toEqual({ [remembered.id]: true, [live.id]: false });+ expect(page.page.compiled_truth).toContain('Example live detail');+ // The carried-forward entry and the withdrawal do not defeat the skip.+ expect(await quietRun(engine, f, fetcher, { resetCheckpoint: true })).toEqual({ pages: 0, checkpoints: expect.any(Number) });+ // Lane C's contextual-mode repair stamps an embedded page with no mode; the next re-walk still skips.+ await engine.executeRaw('UPDATE content_chunks SET embedding=$2::text::vector WHERE page_id=(SELECT id FROM pages WHERE source_id=$1 AND slug=$3)', [f.id, VECTOR, slug]);+ await engine.executeRaw('UPDATE pages SET contextual_retrieval_mode=NULL WHERE source_id=$1 AND slug=$2', [f.id, slug]);+ const runner = await repairRunner(engine, { apply: true, noEmbed: true, logger: quiet });+ const scope = await resolveRepairScope(engine, f.id);+ expect((await runner.run('contextual-mode', scope)).applied).toBe(1);+ expect((await engine.executeRaw<{ mode: string | null }>('SELECT contextual_retrieval_mode AS mode FROM pages WHERE source_id=$1 AND slug=$2', [f.id, slug]))[0]!.mode).not.toBeNull();+ expect((await quietRun(engine, f, fetcher, { resetCheckpoint: true })).pages).toBe(0);+ // A page below the safe-chunk fence is re-sealed by the repair, and the re-walk skips afterwards.+ await engine.executeRaw('UPDATE content_chunks SET embedding=NULL WHERE page_id=(SELECT id FROM pages WHERE source_id=$1 AND slug=$2)', [f.id, slug]);+ await engine.executeRaw('UPDATE pages SET chunker_version=1 WHERE source_id=$1 AND slug=$2', [f.id, slug]);+ expect((await runner.run('safe-chunks', scope)).applied).toBe(1);+ expect((await quietRun(engine, f, fetcher, { resetCheckpoint: true })).pages).toBe(0);+ expect((await timeline(engine, f.id, slug)).sort()).toEqual(['Earlier note', 'Operator note']);+ expect(await facts()).toEqual({ [remembered.id]: true, [live.id]: false });+ await disposePersistenceConsumer(engine);+ }+}), 300_000);++test('check 2b (S1): a provider render that brings its own facts fence owns it: upstream corrections replace the stored rows', async () => withEnv(env, async () => {+ const fence = (claim: string) => `## Facts\n\n${renderFactsTable([{ rowNum: 1, claim, kind: 'fact', confidence: 1, visibility: 'world', notability: 'medium', active: true }])}`;+ for (const engine of engines) {+ const f = await source(engine, githubConfig);+ let body = `A useful synthetic issue body.\n\n${fence('Provider claim alpha')}`;+ let updated = issueFixture.updated_at;+ const fetcher = async (url: string) => {+ const path = new URL(url).pathname;+ if (path.endsWith('/issues')) return json([{ ...issueFixture, body, updated_at: updated }]);+ if (path.endsWith('/issues/1')) return json({ ...issueFixture, body, updated_at: updated });+ return githubFetch()(url);+ };+ const run = (extra: object = {}) => runGitHubSync(engine, f.id, parseGitHubSourceConfig(githubConfig, f.dir), { ...options, ...extra }, fetcher);+ await run();+ const [page] = await engine.executeRaw<{ slug: string }>("SELECT slug FROM pages WHERE source_id=$1 AND compiled_truth LIKE '%Provider claim alpha%'", [f.id]);+ expect(page).toBeDefined();+ body = `A useful synthetic issue body.\n\n${fence('Provider claim beta')}`;+ updated = '2026-02-01T00:00:00Z';+ await disposePersistenceConsumer(engine);+ await run({ resetCheckpoint: true });+ const current = (await engine.readPageSnapshot(page!.slug, { sourceId: f.id }))!;+ expect(current.page.compiled_truth).toContain('Provider claim beta');+ expect(current.page.compiled_truth).not.toContain('Provider claim alpha');+ await disposePersistenceConsumer(engine);+ }+}), 180_000);++test('check 3 (S1): a quiet run over a page with a user timeline entry still stamps freshness, so gbrain waiting stays fresh; a provider outage neither stamps nor loses the entry', async () => withEnv(env, async () => {+ for (const engine of engines) {+ const f = await source(engine, googleConfig);+ let down = false;+ const fetcher = people(() => [contact('first', 'First Example')], { fail: () => down });+ await google(engine, f, fetcher);+ expect((await addTimeline(engine, f.id, 'people/first-example', 'Operator note')).state).toBe('committed');+ // The first re-walk after a user entry may render the carried bullet into the page once.+ expect((await quietRun(engine, f, fetcher, { resetCheckpoint: true })).pages).toBeLessThanOrEqual(1);+ const seen = async () => (await engine.executeRaw<{ at: string }>('SELECT last_sync_at::text AS at FROM sources WHERE id=$1', [f.id]))[0]!.at;+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw("UPDATE sources SET last_sync_at=now()-interval '2 days' WHERE id=$1", [f.id]);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const stale = await seen();+ expect(await quietRun(engine, f, fetcher)).toEqual({ pages: 0, checkpoints: 0 });+ const fresh = await seen();+ expect(new Date(fresh).getTime()).toBeGreaterThan(new Date(stale).getTime());+ const waiting = await handleToolCall(engine, 'open_loops', { group_by: 'counterparty', limit: 3 }, { sourceId: ALL_SOURCES }) as { sources?: Array<{ id: string; stale: boolean }> };+ expect(waiting.sources?.find(row => row.id === f.id)?.stale ?? false).toBe(false);+ down = true;+ await disposePersistenceConsumer(engine);+ expect((await google(engine, f, fetcher)).status).toBe('partial');+ expect(await seen()).toBe(fresh);+ expect(await timeline(engine, f.id, 'people/first-example')).toEqual(['Operator note']);+ await disposePersistenceConsumer(engine);+ }+}), 180_000);++test('check 4 (S1): a checkpoint orphaned by a content change is listed by the remediation plan and cleared by the agreed run; the live checkpoint, compacted receipts and a new incarnation keep working', async () => withEnv(env, async () => {+ for (const engine of engines) {+ const f = await source(engine, googleConfig);+ const fetcher = people(() => [contact('first', 'First Example')]);+ await google(engine, f, fetcher);+ const oldKey = connectorCheckpointKey(f.id, await incarnation(engine, f.id), connectorIdentity('google', googleConfig, f.dir));+ const widened = { ...googleConfig, g_history_days: 365 };+ expect(await engine.updateSourceConfig(f.id, { g_history_days: 365 })).toBe(true);+ await disposePersistenceConsumer(engine);+ await google(engine, f, fetcher, {}, widened);+ await engine.executeRaw("UPDATE op_checkpoints SET updated_at=now()-interval '8 days' WHERE op='managed-connector' AND fingerprint=$1", [oldKey]);+ // Receipt compaction does not hide the live checkpoint from the migration's loader or the cleanup.+ await protocol(engine, "UPDATE persistence_requests SET completed_at=now()-interval '60 days' WHERE source_id=$1 AND state='committed'", [f.id]);+ await compactWriteReceipts(engine, 30);+ // Lane A's orphan is a Lane D wave finding with a registered repair.+ const findings = Object.fromEntries((await runWaveChecks(engine)).map(finding => [finding.spec.id, finding]));+ expect(findings.connector_checkpoints!.state).toBe('finding');+ const steps = await planRepairSteps(engine, { noEmbed: true });+ const step = steps.find(s => s.kind === 'connector-checkpoints');+ expect(step).toMatchObject({ command: 'gbrain repair connector-checkpoints --apply', paid: false, embeds: 'none', lifetime_ids: 0, checks: ['connector_checkpoints'] });+ const run = await capture(() => runRemediate(engine, ['--remediate', '--yes', '--include-repairs', '--no-embed', '--max-usd', '0', '--json']));+ const body = JSON.parse(run.out);+ expect(body.repairs.find((r: { kind: string }) => r.kind === 'connector-checkpoints')).toMatchObject({ status: 'completed' });+ expect(body.findings.find((r: { check_id: string }) => r.check_id === 'connector_checkpoints')).toMatchObject({ class: 'cleared' });+ expect(await engine.executeRaw("SELECT 1 FROM op_checkpoints WHERE op='managed-connector' AND fingerprint=$1", [oldKey])).toHaveLength(0);+ const liveKey = connectorCheckpointKey(f.id, await incarnation(engine, f.id), connectorIdentity('google', widened, f.dir));+ expect(await engine.executeRaw("SELECT 1 FROM op_checkpoints WHERE op='managed-connector' AND fingerprint=$1", [liveKey])).toHaveLength(1);+ expect((await quietRun(engine, f, fetcher, {}, widened)).pages).toBe(0);+ await disposePersistenceConsumer(engine);+ }+}), 240_000);++test('check 5 (S1): an account-change refusal and the connector findings never reach remote doctor lines', async () => withEnv(env, async () => {+ for (const engine of engines) {+ const f = await source(engine, googleConfig);+ const fetcher = people(() => [contact('first', 'First Example')]);+ await google(engine, f, fetcher);+ await disposePersistenceConsumer(engine);+ const refused = await runGoogleSync(engine, f.id, parseGoogleSourceConfig(googleConfig, f.dir), options, withGoogleAccount(fetcher, '[email protected]'))+ .catch(error => error) as { code?: string; suggestion?: string };+ expect(refused.code).toBe('connector_account_changed');+ expect(refused.suggestion).toContain('[email protected]');+ // A content change leaves an aged orphan: a real connector finding the remote caller sees only as a host-action line.+ await engine.executeRaw("UPDATE op_checkpoints SET updated_at=now()-interval '8 days' WHERE op='managed-connector'");+ expect(await engine.updateSourceConfig(f.id, { g_history_days: 400 })).toBe(true);+ const lines = await remoteWaveHandoff(engine, [f.id]);+ const text = JSON.stringify(lines);+ for (const secret of [googleConfig.g_account, '[email protected]', f.dir, home, 'op_checkpoints', 'managed-connector']) expect(text).not.toContain(secret);+ expect(lines.find(line => line.name === 'connector_checkpoints')).toMatchObject({ status: 'warn', details: { host_action: { state: 'action_required' } } });+ expect(new Set(lines.map(line => line.name))).toEqual(new Set(WAVE_CHECKS.filter(spec => !spec.hostOnly).map(spec => spec.id)));+ await disposePersistenceConsumer(engine);+ }+}), 180_000);++test('check 6 (S1): a retired connector intent fails with its delivered hint and no consumer stamp; the writer-version advisory counts only published requests', async () => withEnv(env, async () => {+ for (const engine of engines) {+ const f = await source(engine, googleConfig);+ await google(engine, f, people(() => [contact('first', 'First Example')]));+ const [template] = await engine.executeRaw<WriteRequest>("SELECT * FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='connector_v2_import' LIMIT 1", [f.id]);+ await disposePersistenceConsumer(engine);+ await engine.executeRaw("DELETE FROM op_checkpoints WHERE op=$1 AND fingerprint='v2-cutoff'", [CONNECTOR_MIGRATION_OP]);+ await engine.executeRaw("INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES($1,'v2-cutoff',jsonb_build_array(jsonb_build_object('cutoff',(now()-interval '1 hour')::text)))", [CONNECTOR_MIGRATION_OP]);+ const intent = { ...template!.intent, kind: 'managed_connector_import', checkpointKey: 'legacy-raw-config-key' };+ const row = await admitWrite(engine, { requestId: randomUUID(), operation: 'submit_job', sourceId: f.id, sourceIncarnation: template!.source_incarnation,+ slug: template!.slug, pageId: template!.page_id, worktreeId: template!.worktree_id ?? undefined, principal: { kind: template!.principal_kind, id: template!.principal_id },+ authority: template!.authority, callerIntent: intent, intent } as never);+ // An older connector binary admitted it: no admitter stamp.+ await protocol(engine, 'UPDATE persistence_requests SET admitter_version=NULL,admitter_host_id=NULL WHERE id=$1::uuid', [row.id]);+ startPersistenceConsumer(engine, { engine: engine.kind });+ const done = await waitForWrite(engine, row, { engine: engine.kind }, 20_000);+ expect(done).toMatchObject({ state: 'failed', error_code: 'connector_intent_outdated', consumer_version: null, published_at: null });+ const delivered = (() => { try { writeResponse(done); } catch (error) { return error as { suggestion?: string; docs?: string }; } return {}; })();+ expect(delivered.suggestion).toContain('Upgrade gbrain on the host that runs connector jobs');+ expect(delivered.docs).toBe('docs/guides/write-refusals.md#connector-intent-outdated');+ // The failed legacy request is never counted as an old writer; an unstamped published one is.+ await disposePersistenceConsumer(engine);+ // Only this source's requests fall inside the advisory's seven-day window.+ await protocol(engine, "UPDATE persistence_requests SET published_at=now()-interval '30 days',completed_at=now()-interval '30 days' WHERE source_id<>$1 AND state='committed'", [f.id]);+ await protocol(engine, "UPDATE persistence_requests SET consumer_version=$2,published_at=now() WHERE source_id=$1 AND state='committed'", [f.id, writerStamp().version]);+ const clean = await writerVersionCheck(engine);+ expect(clean.status).toBe('ok');+ await protocol(engine, "UPDATE persistence_requests SET consumer_version=NULL WHERE id=$1::uuid", [template!.id]);+ const warned = await writerVersionCheck(engine);+ expect(warned.status).toBe('warn');+ expect(warned.message).toContain('gbrain upgrade');+ }+}), 180_000);++test('check 7 (S1): concept publication through the maintenance helper keeps private-first, provenance and promotion while other writes are pending, and leaves no derived-visibility finding', async () => withEnv(env, async () => {+ for (const engine of engines) {+ const f = await boundSource(engine, { kind: 'filesystem' });+ const ctx = ctxFor(engine, f.id);+ for (const n of [1, 2]) await submitPageMutation(ctx, { operation: 'put_page', params: { request_id: randomUUID(), slug: `atoms/idea-${n}`,+ content: `---\ntitle: Idea ${n}\ntype: atom\nvisibility: world\nconcepts: [network-effects]\n---\nAtom ${n} about network effects.` } });+ // Another writer's request is admitted and still pending when synthesis starts.+ await disposePersistenceConsumer(engine);+ const [template] = await engine.executeRaw<WriteRequest>("SELECT * FROM persistence_requests WHERE source_id=$1 AND slug='atoms/idea-1' AND state='committed' LIMIT 1", [f.id]);+ const pendingIntent = { ...template!.intent, slug: 'notes/pending-example', content: '---\ntitle: Pending\ntype: note\n---\nA pending write.\n' };+ const pending = await admitWrite(engine, { requestId: randomUUID(), operation: 'put_page', sourceId: f.id, sourceIncarnation: template!.source_incarnation,+ slug: 'notes/pending-example', pageId: null, worktreeId: template!.worktree_id ?? undefined, topologyGeneration: template!.topology_generation, principal: { kind: template!.principal_kind, id: template!.principal_id },+ authority: template!.authority, callerIntent: pendingIntent, intent: pendingIntent } as never);+ const result = await runPhaseSynthesizeConcepts(engine, { sourceId: f.id, brainDir: f.dir, _chat: async () => { throw new Error('a T3 concept must not call the model'); } });+ expect(result.status).toBe('ok');+ const concept = await engine.executeRaw<{ content: string; consumer_version: string | null }>(+ "SELECT intent->>'content' AS content,consumer_version FROM persistence_requests WHERE source_id=$1 AND slug='concepts/network-effects' AND state='committed' ORDER BY sequence", [f.id]);+ expect(concept.map(r => /visibility: (\w+)/.exec(r.content)?.[1])).toEqual(['private', 'world']);+ for (const r of concept) expect(r.consumer_version).toBe(writerStamp().version);+ expect((await engine.getLinks('concepts/network-effects', { sourceId: f.id })).filter(l => l.link_source === 'concept-provenance').map(l => l.to_slug).sort())+ .toEqual(['atoms/idea-1', 'atoms/idea-2']);+ expect((await waitForWrite(engine, pending, { engine: engine.kind }, 20_000)).state).toBe('committed');+ const visibility = (await runWaveChecks(engine)).find(finding => finding.spec.id === 'derived_visibility')!;+ expect(Number(visibility.check.details?.looser_concepts ?? 0)).toBe(0);+ await disposePersistenceConsumer(engine);+ }+}), 180_000);++test('check 8 (S1, Postgres): an unbound write, binding between admission and publication, sync after binding and the reconcile that resolves the collision', async () => withEnv(env, async () => {+ for (const engine of engines) {+ const f = await source(engine, { kind: 'filesystem' });+ const ctx = ctxFor(engine, f.id);+ const note = (slug: string, body: string) => submitPageMutation(ctx, { operation: 'put_page', params: { request_id: randomUUID(), slug,+ content: `---\ntitle: Example\ntype: note\n---\n\n${body}\n` } });+ if (engine.kind === 'pglite') {+ // PGLite keeps its automatic first-write claim; a locked admin lock does not block it.+ await setWriterAdminLock(engine, true);+ expect((await note('notes/automatic', 'Claimed by its first write.')).state).toBe('committed');+ await setWriterAdminLock(engine, false);+ expect(existsSync(join(f.dir, 'notes/automatic.md'))).toBe(true);+ continue;+ }+ await expect(note('notes/refused', 'Refused by default.')).rejects.toMatchObject({ code: 'owner_unavailable', detail: 'unbound_source' });+ await engine.setConfig('persistence.unbound_write', 'database_only');+ expect((await note('notes/kept', 'Written while unbound.')).state).toBe('committed');+ const [template] = await engine.executeRaw<WriteRequest>("SELECT * FROM persistence_requests WHERE source_id=$1 AND slug='notes/kept' AND state='committed'", [f.id]);+ expect(template!.authority.databaseOnlyReason).toBe('unbound_source');+ expect((await checkUnboundSource(engine)).status).toBe('ok');+ // Admitted while unbound, published after binding: the recheck refuses and the consumer never stamps it.+ await disposePersistenceConsumer(engine);+ const intent = { ...template!.intent, slug: 'notes/raced', content: '---\ntitle: Raced\ntype: note\n---\n\nAdmitted while unbound.\n' };+ const raced = await admitWrite(engine, { requestId: randomUUID(), operation: 'put_page', sourceId: f.id, sourceIncarnation: template!.source_incarnation,+ slug: 'notes/raced', pageId: null, principal: { kind: template!.principal_kind, id: template!.principal_id },+ authority: template!.authority, callerIntent: intent, intent } as never);+ // The operator's admin lock blocks binding; unlocking lets the claim through.+ await setWriterAdminLock(engine, true);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await expect(claimWorktree(engine, f.id, f.dir)).rejects.toMatchObject({ code: 'writer_admin_locked' });+ await setWriterAdminLock(engine, false);+ await claimWorktree(engine, f.id, f.dir);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ startPersistenceConsumer(engine, { engine: engine.kind });+ const failed = await waitForWrite(engine, raced, { engine: engine.kind }, 20_000);+ expect(failed).toMatchObject({ state: 'failed', error_code: 'owner_unavailable', consumer_version: null, published_at: null });+ const delivered = (() => { try { writeResponse(failed); } catch (error) { return error as { detail?: string; suggestion?: string }; } return {}; })();+ expect(delivered.detail).toBe('unbound_source');+ expect(delivered.suggestion).toContain('new request_id');+ // After binding, the kept page sits outside canonical files: doctor warns and names reconcile.+ const bound = await checkUnboundSource(engine);+ expect(bound.status).toBe('warn');+ expect(bound.message).toContain('gbrain sources reconcile <source> <slug>');+ // A canonical file appears at its slug path; Lane D's reconcile accepts the marked page and resolves it.+ mkdirSync(join(f.dir, 'notes'), { recursive: true });+ writeFileSync(join(f.dir, 'notes/kept.md'), '---\ntitle: Example\ntype: note\nfile_field: kept\n---\n\nWritten into the checkout.\n');+ const registration = await registerLocalWriter(engine, 'cli');+ await withVerifiedLocalRegistration(engine, registration, async () => {+ const preview = await runReconcilePreview(engine, { source_id: f.id, slug: 'notes/kept' });+ const resolved = await runReconcilePreview(engine, { source_id: f.id, slug: 'notes/kept', from: preview.preview,+ decisions: ((preview.conflict_paths ?? []) as string[]).map(path => ({ path, action: 'take_database' })) });+ expect((await runReconcileApply(engine, { source_id: f.id, slug: 'notes/kept', preview: resolved.preview, request_id: randomUUID() })).state).toBe('committed');+ });+ expect((await engine.executeRaw<{ reason: string | null; path: string | null }>('SELECT database_only_reason AS reason,source_path AS path FROM pages WHERE source_id=$1 AND slug=$2',+ [f.id, 'notes/kept']))[0]).toEqual({ reason: null, path: 'notes/kept.md' });+ expect((await checkUnboundSource(engine)).status).toBe('ok');+ expect(readFileSync(join(f.dir, 'notes/kept.md'), 'utf8')).toContain('Written while unbound.');+ await engine.setConfig('persistence.unbound_write', 'refuse');+ await disposePersistenceConsumer(engine);+ }+}), 240_000);++test('check 9: every registered repair kind reaches the remediation plan with its cost class; --max-usd 0 still runs the free kinds', async () => withEnv(env, async () => {+ for (const engine of engines) {+ const f = await source(engine, googleConfig);+ const fetcher = people(() => [contact('first', 'First Example')]);+ await google(engine, f, fetcher);+ await disposePersistenceConsumer(engine);+ // Pending work for Lane C (mode) and Lane A (orphan checkpoint).+ await engine.executeRaw('UPDATE content_chunks SET embedding=$2::text::vector WHERE page_id=(SELECT id FROM pages WHERE source_id=$1 AND slug=$3)', [f.id, VECTOR, 'people/first-example']);+ await engine.executeRaw('UPDATE pages SET contextual_retrieval_mode=NULL WHERE source_id=$1', [f.id]);+ // A second page is both below the safe-chunk fence and unsealed: contextual-mode can stamp it only after safe-chunks re-seals it.+ await google(engine, f, people(() => [contact('first', 'First Example'), contact('second', 'Second Example')]), { resetCheckpoint: true });+ await disposePersistenceConsumer(engine);+ await engine.executeRaw("UPDATE pages SET contextual_retrieval_mode=NULL,chunker_version=1,text_projection_revision=gen_random_uuid() WHERE source_id=$1 AND slug='people/second-example'", [f.id]);+ await engine.executeRaw("INSERT INTO op_checkpoints(op,fingerprint,completed_keys,updated_at) VALUES('managed-connector',$1,'[]'::jsonb,now()-interval '9 days')", [`orphan-${randomUUID()}`]);+ const kinds = REPAIR_REGISTRY.map(spec => spec.kind);+ expect(kinds).toEqual(['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints']);+ const planned = Object.fromEntries((await planRepairSteps(engine, { noEmbed: true })).map(step => [step.kind, step]));+ expect(planned['contextual-mode']).toMatchObject({ paid: false, embeds: 'inline', command: 'gbrain repair contextual-mode --no-embed --apply' });+ expect(planned['connector-checkpoints']).toMatchObject({ paid: false, embeds: 'none' });+ expect(planned['safe-chunks']).toBeDefined();+ expect(planned['contextual-mode'].rationale).toContain('after safe-chunks re-seals them');+ const run = JSON.parse((await capture(() => runRemediate(engine, ['--remediate', '--yes', '--include-repairs', '--no-embed', '--max-usd', '0', '--json']))).out);+ const byKind = Object.fromEntries(run.repairs.map((r: { kind: string }) => [r.kind, r]));+ expect(byKind['contextual-mode']).toMatchObject({ status: 'completed' });+ expect(byKind['connector-checkpoints']).toMatchObject({ status: 'completed' });+ const modes = await engine.executeRaw<{ slug: string; mode: string | null }>('SELECT slug,contextual_retrieval_mode AS mode FROM pages WHERE source_id=$1 ORDER BY slug', [f.id]);+ for (const row of modes) expect(row.mode).not.toBeNull();+ const replanned = (await planRepairSteps(engine, { noEmbed: true })).map(step => step.kind);+ expect(replanned).not.toContain('contextual-mode');+ expect(replanned).not.toContain('connector-checkpoints');+ await disposePersistenceConsumer(engine);+ }+}), 240_000);++function git(root: string, ...args: string[]): string {+ const result = Bun.spawnSync(['git', '-C', root, ...args]);+ if (result.exitCode) throw new Error(`git ${args.join(' ')}: ${result.stderr.toString()}`);+ return result.stdout.toString();+}++test('check 10: connector writes on a bound, hardened source commit through coalesced Git effects; a failed push is retried and loses nothing', async () => withEnv(env, async () => {+ for (const engine of engines) {+ const f = await source(engine, googleConfig);+ const remote = `${f.dir}.git`, pushLog = `${f.dir}.pushes`, reject = `${f.dir}.reject`;+ git(f.dir, 'init', '-q', '-b', 'main');+ git(f.dir, 'config', 'user.name', 'Example Writer'); git(f.dir, 'config', 'user.email', '[email protected]');+ writeFileSync(join(f.dir, 'README.md'), 'connector\n'); git(f.dir, 'add', 'README.md'); git(f.dir, 'commit', '-q', '-m', 'Initial');+ mkdirSync(remote); git(remote, 'init', '-q', '--bare');+ git(f.dir, 'remote', 'add', 'origin', remote); git(f.dir, 'push', '-q', '-u', 'origin', 'main');+ writeFileSync(join(remote, 'hooks', 'pre-receive'), `#!/bin/sh\necho push >> '${pushLog}'\n[ -f '${reject}' ] && exit 1\nexit 0\n`, { mode: 0o755 });+ writeFileSync(join(f.dir, '.git', 'hooks', 'post-commit'), '#!/bin/sh\n# gbrain brain-durability post-commit hook (v0.42.44+)\n', { mode: 0o755 });+ const pushes = () => existsSync(pushLog) ? readFileSync(pushLog, 'utf8').trim().split('\n').filter(Boolean).length : 0;+ const commits = () => Number(git(f.dir, 'rev-list', '--count', 'HEAD').trim());+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await claimWorktree(engine, f.id, f.dir);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const pass = () => runPersistenceEffects(engine, { engine: engine.kind, embedding_disabled: true } as never, { hostId: localHostId(), limit: 20 });+ const release = () => protocol(engine, "UPDATE persistence_effects SET next_attempt_at=now() WHERE kind='git' AND state='queued'");+ let org = 'Example Org';+ const names = () => Array.from({ length: 12 }, (_, i) => ({ ...contact(`member-${i}`, `Member Example ${i}`), organizations: [{ name: i === 0 ? org : 'Example Org' }] }));+ const [beforeCommits, beforePushes] = [commits(), pushes()];+ await engine.executeRaw("ALTER TABLE persistence_effects ALTER COLUMN next_attempt_at SET DEFAULT (now()+interval '1 hour')");+ try {+ await google(engine, f, people(names));+ await disposePersistenceConsumer(engine);+ await release();+ await pass();+ // Twelve connector pages, one coalesced commit and one push (#5530 x Lane A).+ expect(commits() - beforeCommits).toBe(1);+ expect(pushes() - beforePushes).toBe(1);+ for (let i = 0; i < 12; i++) expect(git(f.dir, 'show', `HEAD:people/member-example-${i}.md`)).toContain(`Member Example ${i}`);+ // A rejected push leaves the next change committed and retryable.+ writeFileSync(reject, '');+ org = 'Renamed Example Org';+ expect((await quietRun(engine, f, people(names), { resetCheckpoint: true })).pages).toBe(1);+ await disposePersistenceConsumer(engine);+ await release();+ await pass();+ expect(git(f.dir, 'show', 'HEAD:people/member-example-0.md')).toContain('Renamed Example Org');+ rmSync(reject, { force: true });+ await release();+ await pass();+ expect(git(remote, 'show', 'main:people/member-example-0.md')).toContain('Renamed Example Org');+ expect((await engine.executeRaw<{ n: number }>("SELECT COUNT(*)::int AS n FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id WHERE r.source_id=$1 AND e.kind='git' AND e.state<>'committed'", [f.id]))[0]!.n).toBe(0);+ } finally {+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('ALTER TABLE persistence_effects ALTER COLUMN next_attempt_at SET DEFAULT now()');+ }+ }+}), 180_000);++test('check 11: a contained paid phase failure is an operator finding for the remediation run, the banner and remote doctor; a lost lease is never contained', async () => {+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} });+ __setChatTransportForTests(async (): Promise<ChatResult> => ({ text: 'ok', blocks: [], stopReason: 'end',+ usage: { input_tokens: 10, output_tokens: 10, cache_read_tokens: 0, cache_creation_tokens: 0 }, model: 'stub:stub', providerId: 'stub' }));+ try {+ for (const engine of engines) {+ await engine.executeRaw("DELETE FROM config WHERE key LIKE 'dream.breaker.%'");+ await engine.executeRaw('DELETE FROM gbrain_cycle_locks');+ for (let i = 0; i < 3; i++) {+ const { result } = await timeContainedPhase({ engine, sourceId: 'default' }, 'synthesize_concepts', async () => {+ await chat({ messages: [{ role: 'user', content: 'x' }] });+ throw Object.assign(new Error('publication refused after synthesis'), { code: 'owner_unavailable' });+ });+ expect(result).toMatchObject({ status: 'fail', details: { contained: true, paid_loop_recorded: true } });+ }+ await expect(timeContainedPhase({ engine, sourceId: 'default' }, 'sync', async () => { throw new LockStolenError('cycle-lock'); }))+ .rejects.toBeInstanceOf(LockStolenError);+ const run = JSON.parse((await capture(() => runRemediate(engine, ['--remediate', '--yes', '--no-embed', '--max-usd', '0', '--json']))).out);+ const finding = run.findings.find((f: { check_id: string }) => f.check_id === 'dream_paid_loop');+ expect(finding).toMatchObject({ class: 'operator_required' });+ expect((await postUpgradeRecoveryBanner(engine, 'host')).join('\n')).toContain('dream_paid_loop: 1 (needs an operator action)');+ const remote = (await remoteWaveHandoff(engine)).find(line => line.name === 'dream_paid_loop')!;+ expect(remote).toMatchObject({ status: 'warn', details: { host_action: { state: 'action_required' } } });+ expect(remote.message).not.toContain('dream:phase:synthesize_concepts');+ await engine.executeRaw("DELETE FROM config WHERE key LIKE 'dream.breaker.%'");+ }+ } finally { __setChatTransportForTests(null); resetGateway(); }+}, 180_000);++test('check 12: the admin lock never blocks ordinary publication or a connector page write; compaction keeps writer stamps', async () => withEnv(env, async () => {+ for (const engine of engines) {+ const f = await source(engine, googleConfig);+ await google(engine, f, people(() => [contact('first', 'First Example')]));+ await setWriterAdminLock(engine, true);+ try {+ // A page write to an unbound connector source is database-only and never claims, locked or not.+ expect((await addTimeline(engine, f.id, 'people/first-example', 'Locked note')).state).toBe('committed');+ expect(await engine.executeRaw('SELECT 1 FROM persistence_source_bindings WHERE source_id=$1', [f.id])).toHaveLength(0);+ const unchanged = people(() => [contact('first', 'First Example')]);+ expect((await quietRun(engine, f, unchanged, { resetCheckpoint: true })).pages).toBeLessThanOrEqual(1);+ expect((await quietRun(engine, f, unchanged, { resetCheckpoint: true })).pages).toBe(0);+ expect(await timeline(engine, f.id, 'people/first-example')).toEqual(['Locked note']);+ } finally { await setWriterAdminLock(engine, false); }+ // Admitted database-only while the connector source was unbound, published after an owner claimed it: refused.+ await disposePersistenceConsumer(engine);+ const [template] = await engine.executeRaw<WriteRequest>("SELECT * FROM persistence_requests WHERE source_id=$1 AND operation='add_timeline_entry' AND state='committed' LIMIT 1", [f.id]);+ expect(template!.authority.databaseOnlyReason).toBe('connector_database');+ const intent = { ...template!.intent, summary: 'Raced note', date: '2026-04-01' };+ const raced = await admitWrite(engine, { requestId: randomUUID(), operation: 'add_timeline_entry', sourceId: f.id, sourceIncarnation: template!.source_incarnation,+ slug: template!.slug, pageId: template!.page_id, principal: { kind: template!.principal_kind, id: template!.principal_id },+ authority: template!.authority, callerIntent: intent, intent } as never);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await claimWorktree(engine, f.id, f.dir);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ startPersistenceConsumer(engine, { engine: engine.kind });+ const refused = await waitForWrite(engine, raced, { engine: engine.kind }, 20_000);+ expect(refused).toMatchObject({ state: 'failed', error_code: 'owner_unavailable', consumer_version: null });+ const hint = (() => { try { writeResponse(refused); } catch (error) { return error as { suggestion?: string }; } return {}; })();+ expect(hint.suggestion).toContain('new request_id');+ expect(await timeline(engine, f.id, 'people/first-example')).not.toContain('Raced note');+ await disposePersistenceConsumer(engine);+ await protocol(engine, "UPDATE persistence_requests SET completed_at=now()-interval '60 days' WHERE source_id=$1 AND state='committed'", [f.id]);+ await compactWriteReceipts(engine, 30);+ const stamped = await engine.executeRaw<{ compacted: boolean; admitter_version: string | null; consumer_version: string | null }>(+ "SELECT compacted,admitter_version,consumer_version FROM persistence_requests WHERE source_id=$1 AND state='committed'", [f.id]);+ expect(stamped.some(row => row.compacted)).toBe(true);+ for (const row of stamped) expect(row).toMatchObject({ admitter_version: writerStamp().version, consumer_version: writerStamp().version });+ }+}), 180_000);diff --git a/test/fix-wave-3-managed-embedding.serial.test.ts b/test/fix-wave-3-managed-embedding.serial.test.tsnew file mode 100644index 0000000000..f517f040c6--- /dev/null+++ b/test/fix-wave-3-managed-embedding.serial.test.ts@@ -0,0 +1,104 @@+/**+ * Fix wave 3 cross-lane check: #4616 (Lane C) on a managed brain. Managed+ * writes embed through the persistence consumer's embedding effect, not the+ * import path Lane C's own suite drives.+ *+ * Authoring gate. (1) Protects the #4616 contract where most writes embed: one+ * degenerate vector refuses only its chunk; the page's other vectors install,+ * the page signature stays unstamped so `gbrain embed --stale` finds the+ * refused chunk, the effect ends terminally as `embedding_zero_norm` (never+ * retried), and the write receipt carries the recovery command. (2) Fails when+ * the effect throws the whole page's vectors away or records the refusal as+ * `embedding_configuration`, as it did before this integration.+ * (3) test/embedding-zero-norm-4616.serial.test.ts covers the gateway, import+ * and `gbrain embed` paths on an unmanaged brain only. (4) The provider is the+ * gateway's process-global transport seam, so this file is serial.+ */+import { afterAll, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import type { OperationContext } from '../src/core/ops/contract.ts';+import { operations } from '../src/core/operations.ts';+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { managedBrain } from './helpers/managed-brain.ts';+import { testBackends } from './helpers/test-backends.ts';++const DIMS = 1536;+// Installed per test, not in beforeAll: the Postgres arm imports this file beside suites that reset the gateway.+let degenerate = true;+function installProvider() {+ degenerate = true;+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: DIMS, env: { ...process.env, OPENAI_API_KEY: 'sk-test-fake' } });+ __setEmbedTransportForTests((async (input: { values: string[] }) => ({+ embeddings: input.values.map(text => new Array(DIMS).fill(degenerate && text.includes('DEGENERATE') ? 0 : 0.01)), usage: { tokens: input.values.length },+ })) as never);+}+afterAll(() => { __setEmbedTransportForTests(null); resetGateway(); });++const section = (n: number, marker = '') => `## Section ${n}\n\n${Array.from({ length: 120 }, (_, i) => `Example sentence ${n}.${i} about the plan${marker}.`).join(' ')}\n`;++for (const backend of testBackends()) test(`${backend}: a degenerate vector in a managed embedding effect refuses only its chunk and delivers the recovery command`, async () => {+ installProvider();+ await managedBrain(async ({ engine, ctx: base }) => {+ const ctx = { ...base, config: { engine: engine.kind } } as OperationContext;+ const slug = 'notes/zero-norm-example';+ const body = [section(1), section(2, ' DEGENERATE'), section(3)].join('\n');+ const receipt = await submitPageMutation(ctx, { operation: 'put_page', params: { slug, request_id: randomUUID(),+ content: `---\ntype: note\ntitle: Zero norm example\n---\n\n${body}` } }) as { state: string; request_id: string };+ expect(receipt.state).toBe('committed');+ const effect = async () => (await engine.executeRaw<{ state: string; error_code: string | null }>(+ "SELECT e.state,e.error_code FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id WHERE r.slug=$1 AND e.kind='embedding'", [slug]))[0];+ const deadline = Date.now() + 30_000;+ while (!['failed', 'committed'].includes((await effect())?.state ?? '') && Date.now() < deadline) await Bun.sleep(100);+ expect(await effect()).toEqual({ state: 'failed', error_code: 'embedding_zero_norm' });+ const chunks = await engine.executeRaw<{ text: string; embedded: boolean }>(+ "SELECT c.chunk_text AS text,c.embedding IS NOT NULL AS embedded FROM content_chunks c JOIN pages p ON p.id=c.page_id WHERE p.slug=$1 ORDER BY c.chunk_index", [slug]);+ expect(chunks.length).toBeGreaterThan(1);+ for (const chunk of chunks) expect(chunk.embedded).toBe(!chunk.text.includes('DEGENERATE'));+ expect(chunks.some(chunk => chunk.embedded)).toBe(true);+ const [page] = await engine.executeRaw<{ signature: string | null }>('SELECT embedding_signature AS signature FROM pages WHERE slug=$1', [slug]);+ expect(page!.signature).toBeNull();+ const op = operations.find(o => o.name === 'get_write_request')!;+ const status = await op.handler(ctx, { request_id: receipt.request_id }) as { effects: Array<{ kind: string; reason?: string; suggestion?: string; docs?: string }> };+ expect(status.effects.find(e => e.kind === 'embedding')).toMatchObject({ state: 'failed', reason: 'embedding_zero_norm',+ docs: 'docs/guides/write-refusals.md#embedding_zero_norm' });+ expect(status.effects.find(e => e.kind === 'embedding')!.suggestion).toContain(`gbrain embed ${slug}`);+ }, { databaseUrl: backend === 'postgres' ? process.env.DATABASE_URL : undefined });+}, 120_000);++for (const backend of testBackends()) test(`${backend}: a refused chunk that held an earlier vector is cleared, and the page is not left looking fully embedded`, async () => {+ installProvider();+ degenerate = false;+ await managedBrain(async ({ engine, ctx: base }) => {+ const ctx = { ...base, config: { engine: engine.kind } } as OperationContext;+ const slug = 'notes/zero-norm-reembed';+ const put = async (lead: string) => {+ const current = await engine.readPageSnapshot(slug, { sourceId: 'default' });+ return submitPageMutation(ctx, { operation: 'put_page', params: { slug, request_id: randomUUID(), ...(current ? { expected_revision: current.revision } : {}),+ content: `---\ntype: note\ntitle: Zero norm reembed\n---\n\n${lead}\n\n${[section(1), section(2, ' DEGENERATE'), section(3)].join('\n')}` } });+ };+ const settled = async () => {+ const deadline = Date.now() + 30_000;+ const state = async () => (await engine.executeRaw<{ state: string }>(+ "SELECT e.state FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id WHERE r.slug=$1 AND e.kind='embedding' ORDER BY e.id DESC LIMIT 1", [slug]))[0]?.state;+ while (!['failed', 'committed'].includes((await state()) ?? '') && Date.now() < deadline) await Bun.sleep(100);+ return state();+ };+ await put('First version.');+ expect(await settled()).toBe('committed');+ // Every chunk now has a vector. Under per-chunk synopsis every chunk is re-embedded on the next edit.+ await engine.executeRaw("UPDATE pages SET contextual_retrieval_mode='per_chunk_synopsis' WHERE slug=$1", [slug]).catch(async () => {+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw("UPDATE pages SET contextual_retrieval_mode='per_chunk_synopsis' WHERE slug=$1", [slug]);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ });+ degenerate = true;+ await put('Second version.');+ expect(await settled()).toBe('failed');+ const chunks = await engine.executeRaw<{ text: string; embedded: boolean }>(+ "SELECT c.chunk_text AS text,c.embedding IS NOT NULL AS embedded FROM content_chunks c JOIN pages p ON p.id=c.page_id WHERE p.slug=$1 ORDER BY c.chunk_index", [slug]);+ for (const chunk of chunks.filter(c => c.text.includes('DEGENERATE'))) expect(chunk.embedded).toBe(false);+ const [page] = await engine.executeRaw<{ signature: string | null }>('SELECT embedding_signature AS signature FROM pages WHERE slug=$1', [slug]);+ expect(page!.signature).toBeNull();+ }, { databaseUrl: backend === 'postgres' ? process.env.DATABASE_URL : undefined });+}, 120_000);diff --git a/test/fix-wave-3-recovery-run.test.ts b/test/fix-wave-3-recovery-run.test.tsnew file mode 100644index 0000000000..1b09938737--- /dev/null+++ b/test/fix-wave-3-recovery-run.test.ts@@ -0,0 +1,106 @@+/**+ * Fix wave 3 timed recovery run: from an upgraded brain carrying every wave+ * finding (Lane D's fixture plus a connector source re-walking once after the+ * checkpoint migration, an orphan connector checkpoint and a page awaiting the+ * contextual-mode stamp), count the operator commands from `gbrain+ * post-upgrade` to a `--remediation-plan` with no repairable finding. PGLite+ * here; Postgres through test/e2e/fix-wave-3-integration.test.ts.+ *+ * Authoring gate. (1) Protects the upgrade promise: at most 3 commands, every+ * repair kind the wave added reached through the banner and one agreed run,+ * inside a 5-minute CI ceiling (a hang detector; wall time is reported, not+ * gated). (2) Fails when a new repair kind is missing from the remediation run,+ * when the banner omits the connector re-walk or a wave finding, or when a+ * repairable finding survives the agreed run. (3) test/recovery-layer.test.ts+ * measures the same path over Lane D's three kinds only. (4) No seam.+ */+import { expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdirSync } from 'node:fs';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import type { WriteRequest } from '../src/core/persistence/model.ts';+import { parseGoogleSourceConfig, runGoogleSync } from '../src/core/google/google-source.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { admitWrite } from '../src/core/persistence/journal.ts';+import { declarePersistenceProtocol } from '../src/core/persistence/protocol.ts';+import { migrateConnectorCheckpoints } from '../src/core/persistence/connector-checkpoint-migration.ts';+import { readConnectorSourceStatuses } from '../src/core/persistence/connector-status.ts';+import { runRemediate, runRemediationPlan } from '../src/commands/doctor/remediate.ts';+import { postUpgradeRecoveryBanner } from '../src/commands/doctor/upgrade-banner.ts';+import { capture } from './helpers/wave-scenarios.ts';+import { waveBrain } from './helpers/wave-fixture.ts';+import { testBackends } from './helpers/test-backends.ts';+import { withEnv } from './helpers/with-env.ts';+import { options, json, googleConfig, contact, withGoogleAccount } from './helpers/connector-fixture.ts';++const VECTOR = `[${Array(1536).fill(0.01).join(',')}]`;++/** After the migration: a connector source whose newest pre-upgrade checkpoint receipt was compacted re-walks once. */+async function rewalkingConnector(engine: BrainEngine): Promise<string> {+ const id = `connector-${randomUUID().slice(0, 8)}`;+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ const dir = join(process.env.GBRAIN_HOME!, id);+ mkdirSync(dir);+ await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,$3::text::jsonb)', [id, dir, JSON.stringify(googleConfig)]);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const fetcher = async (url: string) => url.includes('/settings/sendAs') ? json({ sendAs: [] }) : json({ connections: [contact('first', 'First Example')], nextSyncToken: 'contacts-stable' });+ await runGoogleSync(engine, id, parseGoogleSourceConfig(googleConfig, dir), options, withGoogleAccount(fetcher));+ await disposePersistenceConsumer(engine);+ await engine.executeRaw("DELETE FROM op_checkpoints WHERE op IN ('managed-connector','managed-connector-state')");+ const [template] = await engine.executeRaw<WriteRequest>("SELECT * FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='connector_v2_checkpoint' ORDER BY sequence DESC LIMIT 1", [id]);+ const intent = { ...template!.intent, kind: 'managed_connector_checkpoint', checkpointKey: `legacy-${randomUUID()}`, configHash: 'legacy-raw-config-hash' };+ const row = await admitWrite(engine, { requestId: randomUUID(), operation: 'submit_job', sourceId: id, sourceIncarnation: template!.source_incarnation,+ slug: template!.slug, pageId: null, principal: { kind: template!.principal_kind, id: template!.principal_id }, authority: template!.authority, callerIntent: intent, intent } as never);+ await engine.transaction(async tx => {+ await declarePersistenceProtocol(tx);+ await tx.executeRaw(`UPDATE persistence_requests SET state='committed',completed_at=now(),outcome='{"status":"checkpointed"}'::jsonb,compacted=true,intent=NULL WHERE id=$1::uuid`, [row.id]);+ });+ expect((await migrateConnectorCheckpoints(engine, () => {})).rewalking).toEqual([id]);+ // An orphan checkpoint left by a pre-upgrade binary, older than the 7-day floor.+ await engine.executeRaw("INSERT INTO op_checkpoints(op,fingerprint,completed_keys,updated_at) VALUES('managed-connector',$1,'[]'::jsonb,now()-interval '9 days')", [`orphan-${randomUUID()}`]);+ return id;+}++for (const backend of testBackends()) test(`${backend}: post-upgrade to a clean plan in at most 3 commands, under the 5-minute ceiling`, async () => {+ const databaseUrl = backend === 'postgres' ? process.env.DATABASE_URL : undefined;+ await waveBrain(async ({ engine }) => {+ await withEnv({ CONNECTOR_TEST_TOKEN: 'synthetic-local-fixture' }, async () => {+ const connector = await rewalkingConnector(engine);+ // A page imported before every import recorded its contextual mode.+ await engine.executeRaw("UPDATE content_chunks SET embedding=$1::text::vector WHERE page_id=(SELECT id FROM pages WHERE source_id='default' AND slug='notes/base')", [VECTOR]);+ await engine.executeRaw("UPDATE pages SET contextual_retrieval_mode=NULL WHERE source_id='default' AND slug='notes/base'");+ const started = Date.now();+ const commands: string[] = [];++ const banner = (await postUpgradeRecoveryBanner(engine, 'host')).join('\n');+ commands.push('gbrain post-upgrade');+ for (const expected of ['[AGENT] Relay this to your operator', 'connector_checkpoints: 1', 'timeline_history', 'safe_index_pending',+ 'connector_rewalk: 1 connector source(s) re-walk their window once', 'gbrain doctor --remediation-plan']) expect(banner).toContain(expected);+ expect(banner).not.toContain('--yes');+ expect(banner).not.toContain('--apply');++ const run = await capture(() => runRemediate(engine, ['--remediate', '--yes', '--include-repairs', '--no-embed', '--max-usd', '1', '--json']));+ commands.push('gbrain doctor --remediate --yes --include-repairs --no-embed --max-usd 1');+ const body = JSON.parse(run.out);+ expect(body.repairs.map((r: { kind: string; status: string }) => [r.kind, r.status])).toEqual([+ ['timeline', 'completed'], ['visibility', 'completed'], ['safe-chunks', 'completed'], ['contextual-mode', 'completed'], ['connector-checkpoints', 'completed']]);+ const classes = Object.fromEntries(body.findings.map((f: { check_id: string; class: string }) => [f.check_id, f.class]));+ expect(classes).toMatchObject({ timeline_history: 'cleared', derived_visibility: 'cleared', safe_index_pending: 'cleared', connector_checkpoints: 'cleared',+ persistence_capacity: 'operator_required', parked_effects: 'operator_required', self_capture: 'operator_required', writer_version: 'operator_required',+ stale_embedding_effects: 'unsupported' });+ expect(run.exit).toBe(0);++ const verify = await capture(() => runRemediationPlan(engine, ['--remediation-plan', '--json']));+ commands.push('gbrain doctor --remediation-plan');+ expect(JSON.parse(verify.out).repair_steps).toEqual([]);++ const wallMs = Date.now() - started;+ console.error(`[recovery-run] ${backend} wall_ms=${wallMs} operator_commands=${commands.length}`);+ expect(commands.length).toBeLessThanOrEqual(3);+ expect(wallMs).toBeLessThan(5 * 60_000);+ // The re-walk itself is the connector's next scheduled run, not an operator step.+ expect((await readConnectorSourceStatuses(engine)).get(connector)?.upgrade_recovery).toBe('rewalking_once');+ });+ }, { databaseUrl });+}, 300_000);diff --git a/test/google-attachment-backfill.test.ts b/test/google-attachment-backfill.test.tsindex b8611d2663..d9ed9ec317 100644--- a/test/google-attachment-backfill.test.ts+++ b/test/google-attachment-backfill.test.ts@@ -78,7 +78,7 @@ test('historical repair preserves current body, facts, frontmatter and private rconst revision = (await engine.readPageSnapshot(slug(1), { sourceId: f.id }))!.revision;expect(await runGoogleAttachmentBackfill(engine, f.id, f.cfg, {}, fetcher)).toMatchObject({ status: 'complete', processed: 0 });expect((await engine.readPageSnapshot(slug(1), { sourceId: f.id }))!.revision).toBe(revision);- expect(await engine.executeRaw("SELECT e.id FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id WHERE r.source_id=$1 AND r.intent->>'kind'='managed_connector_google_receipts' AND e.kind<>'git'", [f.id])).toHaveLength(0);+ expect(await engine.executeRaw("SELECT e.id FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id WHERE r.source_id=$1 AND r.intent->>'kind'='connector_v2_google_receipts' AND e.kind<>'git'", [f.id])).toHaveLength(0);}}), 120_000);@@ -172,7 +172,7 @@ test('withdrawal wins after receipt preparation but before real canonical publicconst f = await seed(engine, true);await runGoogleAttachmentBackfill(engine, f.id, f.cfg, {}, fetcher);await disposePersistenceConsumer(engine);- const [template] = await engine.executeRaw<WriteRequest>("SELECT * FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_connector_google_receipts' LIMIT 1", [f.id]);+ const [template] = await engine.executeRaw<WriteRequest>("SELECT * FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='connector_v2_google_receipts' LIMIT 1", [f.id]);const snapshot = (await engine.readPageSnapshot(slug(1), { sourceId: f.id }))!;const [checkpoint] = await engine.executeRaw<{ completed_keys: unknown[] }>("SELECT completed_keys FROM op_checkpoints WHERE op='managed-connector' AND fingerprint=$1", [template.intent!.checkpointKey]);const intent = structuredClone(template.intent!);diff --git a/test/google-attachment-recovery.test.ts b/test/google-attachment-recovery.test.tsindex d5d8cdecb1..143c3d0e6a 100644--- a/test/google-attachment-recovery.test.ts+++ b/test/google-attachment-recovery.test.ts@@ -90,7 +90,7 @@ for (const crash of ['before_publication', 'after_publication', 'after_metadata_expect(after.page.frontmatter.gmail_attachment_receipts).toMatchObject({ messages: [{ inspection: { state: 'present', attachments: [{ filename: 'fixture.pdf' }] } }] });expect(readFileSync(join(f.dir, `${slug}.md`), 'utf8')).toContain('Exact preserved historical body.');expect(await engine.executeRaw('SELECT id FROM persistence_requests WHERE source_id=$1 AND recovery IS NOT NULL', [f.id])).toHaveLength(0);- const [count] = await engine.executeRaw<{ count: string }>("SELECT count(*)::text AS count FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_connector_google_receipts' AND state='committed' AND NOT COALESCE((outcome->>'noop')::boolean,false)", [f.id]);+ const [count] = await engine.executeRaw<{ count: string }>("SELECT count(*)::text AS count FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='connector_v2_google_receipts' AND state='committed' AND NOT COALESCE((outcome->>'noop')::boolean,false)", [f.id]);expect(Number(count.count)).toBe(1);}}), 120_000);diff --git a/test/google-attachment-sync.test.ts b/test/google-attachment-sync.test.tsindex c145c426af..ff4cf91368 100644--- a/test/google-attachment-sync.test.ts+++ b/test/google-attachment-sync.test.ts@@ -1,4 +1,5 @@import { afterAll, beforeAll, expect, test } from 'bun:test';+import { withGoogleAccount } from './helpers/connector-fixture.ts';import { parseGoogleSourceConfig, runGoogleSync } from '../src/core/google/google-source.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';import { createConnectorFixture, json, options, sourceCheckpoint } from './helpers/connector-fixture.ts';@@ -31,14 +32,14 @@ test('normal managed Gmail sync persists attachment receipts without marking hisfor (const engine of engines) {const f = await source(engine, config);const cfg = parseGoogleSourceConfig(config, f.dir);- const result = await runGoogleSync(engine, f.id, cfg, options, gmailFetch);+ const result = await runGoogleSync(engine, f.id, cfg, options, withGoogleAccount(gmailFetch));expect(result.added).toBe(1);const [page] = await engine.executeRaw<{ frontmatter: Record<string, any>; compiled_truth: string }>('SELECT frontmatter,compiled_truth FROM pages WHERE source_id=$1', [f.id]);expect(page.frontmatter.gmail_attachment_receipts.messages[0].inspection).toMatchObject({ state: 'present', attachments: [{ filename: 'synthetic-report.pdf', fetched: false, indexed: false }] });expect(page.compiled_truth).toContain('not downloaded; not indexed');expect(JSON.stringify(await sourceCheckpoint(engine, f.id))).not.toContain('gmail_attachment_backfill');await disposePersistenceConsumer(engine);- expect((await runGoogleSync(engine, f.id, cfg, options, gmailFetch)).added).toBe(0);+ expect((await runGoogleSync(engine, f.id, cfg, options, withGoogleAccount(gmailFetch))).added).toBe(0);expect(await engine.executeRaw('SELECT id FROM pages WHERE source_id=$1', [f.id])).toHaveLength(1);}}), 120_000);diff --git a/test/google-source-materialize.test.ts b/test/google-source-materialize.test.tsindex 801b2836d1..074da392fc 100644--- a/test/google-source-materialize.test.ts+++ b/test/google-source-materialize.test.ts@@ -487,6 +487,12 @@ describe('google-source materialize', () => {expect(res.deleted).toBe(0);expect(res.chunksCreated).toBeGreaterThan(0);expect(fx.tokenPosts).toBe(0); // fresh vault token — no refresh HTTP+ // #5621: noEmbed connector imports stamp the wrapping convention.+ const unstamped = await engine.executeRaw<{ n: number }>(+ `SELECT count(*)::int AS n FROM pages+ WHERE source_id = 'gsrc' AND page_kind = 'markdown' AND contextual_retrieval_mode IS NULL`,+ );+ expect(unstamped[0].n).toBe(0);// Contacts → person pages with aliases projected into page_aliases.expect(await slugsWhere(`slug LIKE 'people/%'`)).toEqual(['people/alice-example', 'people/dana-example']);diff --git a/test/helpers/connector-fixture.ts b/test/helpers/connector-fixture.tsindex 39d256365a..ae0a5343c6 100644--- a/test/helpers/connector-fixture.ts+++ b/test/helpers/connector-fixture.ts@@ -10,6 +10,8 @@ import { disposePersistenceConsumer } from '../../src/core/persistence/service.timport { isolatedPersistencePostgres } from './persistence-postgres.ts';import { syncLockId } from '../../src/core/db-lock.ts';import { testBackends } from './test-backends.ts';+import { connectorWaitBudget } from '../../src/core/persistence/connector-sync.ts';+import { readManagedConnectorState } from '../../src/core/persistence/connector-state.ts';export const options = { noEmbed: true, noExtract: true, noSchemaPack: true };export const json = (body: unknown, status = 200, headers = {}) => new Response(JSON.stringify(body), {@@ -47,6 +49,8 @@ export function createConnectorFixture() {let closePostgres: (() => Promise<void>) | undefined;const env = { GBRAIN_HOME: home, CONNECTOR_TEST_TOKEN: 'synthetic-local-fixture' };const setup = async () => {+ // Paused-owner fixtures stop on a 10 s wait budget instead of the production 30 s.+ connectorWaitBudget.ms = 10_000;if (backends.includes('pglite')) {const lite = new PGLiteEngine();await lite.connect({ database_path: join(home, 'database') });@@ -116,3 +120,24 @@ export function createConnectorFixture() {return { home, engines, env, backends, setup, teardown, source, boundSource, standaloneConnector };}++/**+ * #5686: a managed Google run resolves the credential's account (People `me`,+ * Calendar primary, Gmail profile) before any service runs. Fixture fetchers+ * that only model sweep routes get those identity routes answered here.+ */+export function withGoogleAccount(fetcher: ((url: string, init?: RequestInit) => Promise<Response>) | undefined, account = googleConfig.g_account) {+ return async (url: string, init?: RequestInit) => {+ const path = new URL(url).pathname;+ if (path.endsWith('/people/me')) return json({ resourceName: 'people/me', emailAddresses: [{ value: account, metadata: { primary: true } }] });+ if (path.endsWith('/calendars/primary')) return json({ id: account });+ if (!fetcher) throw new Error('Unexpected external fixture route');+ return fetcher(url, init);+ };+}++/** #5600: the pending set a managed connector run ended with (connector state row). */+export async function connectorPendingSet(engine: BrainEngine, sourceId: string) {+ const [source] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text FROM sources WHERE id=$1', [sourceId]);+ return (await readManagedConnectorState(engine, sourceId, source.incarnation)).pending;+}diff --git a/test/helpers/connector-restart.ts b/test/helpers/connector-restart.tsindex 295df0c3df..71b3c4ae49 100644--- a/test/helpers/connector-restart.ts+++ b/test/helpers/connector-restart.ts@@ -1,4 +1,5 @@import type { GBrainConfig } from '../../src/core/config.ts';+import { withGoogleAccount } from './connector-fixture.ts';import type { BrainEngine } from '../../src/core/engine.ts';import { PGLiteEngine } from '../../src/core/pglite-engine.ts';import { PostgresEngine } from '../../src/core/postgres-engine.ts';@@ -20,7 +21,7 @@ if (input.crash) {return transaction.call(this, async tx => {const result = await run(tx);const row = result as Partial<WriteRequest> | undefined;- if (row?.state === 'committed' && row.intent?.kind === 'managed_connector_import') {+ if (row?.state === 'committed' && row.intent?.kind === 'connector_v2_import') {writeSync(1, 'CONNECTOR_AFTER_PUBLICATION_BEFORE_COMMIT\n');process.kill(process.pid, 'SIGKILL');await new Promise(() => {});@@ -51,7 +52,7 @@ let failed = false;try {const options = { noEmbed: true, noExtract: true, noSchemaPack: true, retryFailed: input.retryFailed === true };const result = input.sourceConfig.kind === 'google'- ? await runGoogleSync(engine, input.sourceId, parseGoogleSourceConfig(input.sourceConfig, input.root), options, fetcher)+ ? await runGoogleSync(engine, input.sourceId, parseGoogleSourceConfig(input.sourceConfig, input.root), options, withGoogleAccount(fetcher)): await runGitHubSync(engine, input.sourceId, parseGitHubSourceConfig(input.sourceConfig, input.root),{ ...options, githubItem: { repo: 'acme-example/app', number: 1, kind: 'issue' } }, fetcher);process.stdout.write(`CONNECTOR_RESULT ${JSON.stringify(result)}\n`);diff --git a/test/helpers/google-attachment-restart.ts b/test/helpers/google-attachment-restart.tsindex a87dc2c613..8af5b9644e 100644--- a/test/helpers/google-attachment-restart.ts+++ b/test/helpers/google-attachment-restart.ts@@ -20,18 +20,18 @@ if (input.crash) {if (input.crash === 'before_publication') tx.executeRaw = async function (sql, params) {if (sql.includes('publication_started=true')) {const [row] = await executeRaw.call(tx, 'SELECT intent FROM persistence_requests WHERE id=$1::uuid', [params![0]]);- if ((row as Partial<WriteRequest>)?.intent?.kind === 'managed_connector_google_receipts') kill();+ if ((row as Partial<WriteRequest>)?.intent?.kind === 'connector_v2_google_receipts') kill();}return executeRaw.call(tx, sql, params);} as BrainEngine['executeRaw'];const value = await run(tx);const row = value as Partial<WriteRequest> | undefined;- if (input.crash === 'after_publication' && row?.state === 'committed' && row.intent?.kind === 'managed_connector_google_receipts') kill();+ if (input.crash === 'after_publication' && row?.state === 'committed' && row.intent?.kind === 'connector_v2_google_receipts') kill();return value;});const row = result as Partial<WriteRequest> | undefined;- if (row?.state === 'committed' && (input.crash === 'after_metadata_commit' && row.intent?.kind === 'managed_connector_google_receipts' ||- input.crash === 'after_checkpoint_commit' && row.intent?.kind === 'managed_connector_checkpoint' &&+ if (row?.state === 'committed' && (input.crash === 'after_metadata_commit' && row.intent?.kind === 'connector_v2_google_receipts' ||+ input.crash === 'after_checkpoint_commit' && row.intent?.kind === 'connector_v2_checkpoint' &&((row.intent.checkpointAfter as any)?.[0]?.state?.gmail_attachment_backfill?.afterPageId ?? 0) > 0)) kill();return result as T;};diff --git a/test/helpers/managed-atoms-contract.ts b/test/helpers/managed-atoms-contract.tsindex 980e577e5c..947be3b221 100644--- a/test/helpers/managed-atoms-contract.ts+++ b/test/helpers/managed-atoms-contract.ts@@ -167,8 +167,9 @@ export async function exerciseManagedAtoms(engine: BrainEngine, scenario: Case):return;}if (scenario === 'deferred') {- expect(first.status).toBe('warn');- expect(first.details?.atoms_extracted).toBe(0);+ // #5601: an atom batch the owner accepted but has not published is progress, not a failure.+ expect(first.status).toBe('ok');+ expect(first.details).toMatchObject({ write_pending: 1, failures: [] });expect(first.details?.write_requests).toEqual(expect.arrayContaining([expect.objectContaining({ state: 'queued' })]));await disposePersistenceConsumer(engine);const pending = await engine.executeRaw('SELECT request_id,state,outcome FROM persistence_requests WHERE source_id=$1 ORDER BY sequence', [sourceId]);diff --git a/test/helpers/memory-safety-wave-repair.ts b/test/helpers/memory-safety-wave-repair.tsindex 834b1885b6..88f226996d 100644--- a/test/helpers/memory-safety-wave-repair.ts+++ b/test/helpers/memory-safety-wave-repair.ts@@ -24,7 +24,7 @@ if (input.crash) {engine.transaction = async function <T>(this: BrainEngine, run: (tx: BrainEngine) => Promise<T>): Promise<T> {const result = await transaction.call(this, run);const row = result as Partial<WriteRequest> | undefined;- if (row?.state === 'committed' && row.intent?.kind === 'managed_connector_google_receipts') {+ if (row?.state === 'committed' && row.intent?.kind === 'connector_v2_google_receipts') {if (outboundCalls) throw new Error('Historical lifecycle repair attempted outbound requests');writeSync(1, 'MEMORY_WAVE_CRASH after_metadata_commit\n');process.kill(process.pid, 'SIGKILL');diff --git a/test/helpers/persistence-request-fixture.ts b/test/helpers/persistence-request-fixture.tsnew file mode 100644index 0000000000..cc7e1b6c66--- /dev/null+++ b/test/helpers/persistence-request-fixture.ts@@ -0,0 +1,93 @@+import { randomUUID } from 'node:crypto';+import type { BrainEngine } from '../../src/core/engine.ts';+import type { OperationContext } from '../../src/core/ops/contract.ts';+import { submissionAuthority } from '../../src/core/persistence/authority.ts';+import { registerLocalWriter, localHostId } from '../../src/core/persistence/identity.ts';+import { admitWrite, claimNextWrite } from '../../src/core/persistence/journal.ts';+import { publishMutation } from '../../src/core/persistence/coordinator.ts';+import { declarePersistenceProtocol } from '../../src/core/persistence/protocol.ts';+import type { WriteRequest } from '../../src/core/persistence/model.ts';++/** A database-only source with directly admitted and published put_page requests, bypassing operation handlers. */+export async function requestFixture(engine: BrainEngine, sourceId = `requests-${randomUUID()}`) {+ await registerLocalWriter(engine, 'cli');+ const [source] = await engine.executeRaw<{ incarnation: string }>(+ 'INSERT INTO sources(id,name) VALUES($1,$1) ON CONFLICT(id) DO UPDATE SET name=EXCLUDED.name RETURNING incarnation', [sourceId]);+ const ctx: OperationContext = { engine, config: { engine: engine.kind }, remote: false, dryRun: false, sourceId,+ logger: { info() {}, warn() {}, error() {} } };+ const admit = async (slug = 'page', requestId = randomUUID(), binding?: { worktree_id: string; topology_generation: string | number }) => {+ const authority = await submissionAuthority(ctx, 'put_page', sourceId, source.incarnation, slug);+ return admitWrite(engine, { principal: authority.principal, authority, operation: 'put_page', sourceId, sourceIncarnation: source.incarnation,+ slug, requestId, callerIntent: { body: slug }, intent: { body: slug },+ ...(binding ? { worktreeId: binding.worktree_id, topologyGeneration: binding.topology_generation } : {}) });+ };+ const publish = async (admitted: WriteRequest) => {+ const row = (await claimNextWrite(engine, localHostId()))!;+ if (row.id !== admitted.id) throw new Error('fixture expected the admitted request at the head of its queue');+ return publishMutation(engine, row, { observedRevision: null, apply: async tx => {+ await tx.putPage(row.slug, { type: 'note', title: 'Example', compiled_truth: row.slug, timeline: '', frontmatter: {} }, { sourceId });+ return {};+ } }, localHostId());+ };+ return { sourceId, incarnation: source.incarnation, ctx, admit, publish };+}++/** Row edits that simulate older binaries or elapsed time; the request trigger requires the protocol declaration. */+export async function editRequest(engine: BrainEngine, id: string, assignments: string, params: unknown[] = []) {+ await engine.transaction(async tx => {+ await declarePersistenceProtocol(tx);+ await tx.executeRaw(`UPDATE persistence_requests SET ${assignments} WHERE id=$1::uuid`, [id, ...params]);+ });+}+export async function readRequest(engine: BrainEngine, id: string) {+ const [row] = await engine.executeRaw<Record<string, unknown>>(`SELECT state,admitter_version,admitter_host_id::text AS admitter_host_id,+ consumer_version,consumer_host_id::text AS consumer_host_id,published_at,completed_at,compacted FROM persistence_requests WHERE id=$1::uuid`, [id]);+ return row;+}++/**+ * One migrated brain per test: PGLite resets its shared engine, PostgreSQL clones a migrated template+ * database (CREATE DATABASE ... TEMPLATE), so brain-wide checks never see another test's requests.+ */+export async function freshBrainFactory(kind: 'pglite' | 'postgres', databaseUrl?: string) {+ if (kind === 'pglite') {+ const { PGLiteEngine } = await import('../../src/core/pglite-engine.ts');+ const { resetPgliteState } = await import('./reset-pglite.ts');+ const engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ const version = (await engine.getConfig('version'))!;+ return {+ fresh: async () => { await resetPgliteState(engine); await engine.setConfig('version', version); return engine as BrainEngine; },+ dispose: () => engine.disconnect(),+ };+ }+ const { default: postgres } = await import('#postgres');+ const { PostgresEngine } = await import('../../src/core/postgres-engine.ts');+ const { isolatedPersistencePostgres } = await import('./persistence-postgres.ts');+ const template = await isolatedPersistencePostgres(databaseUrl!);+ const [row] = await template.engine.executeRaw<{ name: string }>('SELECT current_database() AS name');+ await template.engine.disconnect();+ const admin = postgres(databaseUrl!, { max: 1, prepare: false });+ const created: string[] = [];+ let current: BrainEngine | undefined;+ return {+ fresh: async () => {+ await current?.disconnect();+ const name = `${row.name}_${created.length}`;+ await admin.unsafe(`CREATE DATABASE ${name} TEMPLATE ${row.name}`);+ created.push(name);+ const url = new URL(databaseUrl!); url.pathname = `/${name}`;+ const engine = new PostgresEngine();+ await engine.connect({ database_url: url.toString(), poolSize: 4 });+ current = engine;+ return engine as BrainEngine;+ },+ dispose: async () => {+ await current?.disconnect();+ for (const name of created) await admin.unsafe(`DROP DATABASE IF EXISTS ${name} WITH (FORCE)`);+ await admin.unsafe(`DROP DATABASE IF EXISTS ${row.name} WITH (FORCE)`);+ await admin.end();+ },+ };+}diff --git a/test/helpers/wave-fixture.ts b/test/helpers/wave-fixture.tsnew file mode 100644index 0000000000..b3f0433154--- /dev/null+++ b/test/helpers/wave-fixture.ts@@ -0,0 +1,101 @@+/**+ * A managed brain carrying one instance of each wave finding the recovery+ * layer classifies (fix wave 3, Lane D): repairable (timeline_history,+ * derived_visibility, safe_index_pending), operator-required+ * (persistence_capacity, parked_effects, self_capture) and unsupported+ * (stale_embedding_effects). PGLite by default; pass a database URL for+ * Postgres. Seeding goes through coordinated writes plus the persistence+ * protocol, the same way the scenario helpers in w5-scenarios.ts do.+ */+import { randomUUID } from 'node:crypto';+import { mkdirSync, 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 { declarePersistenceProtocol } from '../../src/core/persistence/protocol.ts';+import { withCoordinatedWrite } from '../../src/core/persistence/context.ts';+import { CLAUDE_CLI_CWD_PREFIX } from '../../src/core/ai/providers/claude-cli-scratch.ts';+import { managedBrain, type ManagedBrain } from './managed-brain.ts';+import { withEnv } from './with-env.ts';++export type WaveFindingKind = 'timeline' | 'visibility' | 'safe_index' | 'capacity' | 'parked' | 'self_capture' | 'stale_embedding' | 'old_writer';+export const ALL_WAVE_FINDINGS: WaveFindingKind[] = ['timeline', 'visibility', 'safe_index', 'capacity', 'parked', 'self_capture', 'stale_embedding', 'old_writer'];++export const put = (ctx: OperationContext, slug: string, body: string, type = 'note', extra = '') => submitPageMutation(ctx, { operation: 'put_page',+ params: { slug, request_id: randomUUID(), content: `---\ntype: ${type}\ntitle: ${slug}\n${extra}---\n\n${body}\n` } });++async function protocol(engine: BrainEngine, sql: string, params: unknown[] = []) {+ await engine.transaction(async tx => { await declarePersistenceProtocol(tx); await tx.executeRaw(sql, params); });+}++/** Seed the requested findings; returns the directory holding the fake Claude config (CLAUDE_CONFIG_DIR). */+export async function seedWaveFindings(brain: ManagedBrain, home: string, kinds: WaveFindingKind[] = ALL_WAVE_FINDINGS): Promise<{ claudeDir: string; corpus: string }> {+ const { engine, ctx } = brain;+ const claudeDir = join(home, 'claude');+ const corpus = join(home, 'corpus');+ await put(ctx, 'notes/base', 'A base page.');+ if (kinds.includes('timeline')) {+ await put(ctx, 'notes/history', 'Body with history.');+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.executeRaw(+ `INSERT INTO timeline_entries(page_id,date,source,summary,detail) SELECT id,'2026-07-01','legacy','A database-only event','' FROM pages WHERE source_id='default' AND slug='notes/history'`)));+ }+ if (kinds.includes('visibility')) await put(ctx, 'atoms/unstamped', 'An extracted atom with no visibility.', 'atom');+ if (kinds.includes('safe_index')) {+ await put(ctx, 'notes/unsealed', 'A page chunked before the safe-chunk fence.');+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.executeRaw(+ "UPDATE pages SET chunker_version=3 WHERE source_id='default' AND slug='notes/unsealed'")));+ }+ await disposePersistenceConsumer(engine);+ if (kinds.includes('capacity')) {+ // 85% of a principal's permanent request ids, with room left under the 90% stop for the repairs.+ await engine.setConfig('persistence.limits.principal_lifetime_ids', '1000');+ await protocol(engine, "UPDATE persistence_counters SET lifetime_ids=850 WHERE key LIKE 'principal:%'");+ }+ if (kinds.includes('parked')) {+ await protocol(engine, `UPDATE persistence_effects SET state='failed',error_code='targets_parked',+ data=jsonb_set(data,'{parked}','[{"slug":"notes/base","error_code":"git_target_unsafe"}]'::jsonb)+ WHERE id=(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/base' LIMIT 1)`);+ }+ if (kinds.includes('stale_embedding')) {+ // A committed write whose embedding effect nobody claims (#5629): queued, parked in the future, last touched hours ago.+ await put(ctx, 'notes/orphan-embedding', 'Its embedding effect never runs.');+ await disposePersistenceConsumer(engine);+ const [request] = await engine.executeRaw<{ id: string; source_id: string; source_incarnation: string; worktree_id: string | null }>(+ "SELECT id,source_id,source_incarnation,worktree_id FROM persistence_requests WHERE slug='notes/orphan-embedding' AND state='committed' LIMIT 1");+ const [existing] = await engine.executeRaw<{ id: number }>("SELECT id FROM persistence_effects WHERE request_id=$1::uuid AND kind='embedding'", [request!.id]);+ if (existing) {+ await protocol(engine, `UPDATE persistence_effects SET state='queued',execution_token=NULL,next_attempt_at=now()+interval '10 years',+ updated_at=now()-interval '3 hours' WHERE id=$1`, [existing.id]);+ } else {+ await protocol(engine, `INSERT INTO persistence_effects(request_id,kind,data,state,source_id,source_incarnation,worktree_id,next_attempt_at,updated_at)+ VALUES($1::uuid,'embedding','{}'::jsonb,'queued',$2,$3::uuid,$4::uuid,now()+interval '10 years',now()-interval '3 hours')`,+ [request!.id, request!.source_id, request!.source_incarnation, request!.worktree_id]);+ }+ }+ if (kinds.includes('old_writer')) {+ // A recent write published by a consumer older than v0.60.5.0 (writer_version).+ await protocol(engine, `UPDATE persistence_requests SET consumer_version='0.60.4.0',published_at=now()+ WHERE id=(SELECT id FROM persistence_requests WHERE slug='notes/base' AND state='committed' ORDER BY sequence LIMIT 1)`);+ }+ if (kinds.includes('self_capture')) {+ const self = join(claudeDir, 'projects', `-tmp-${CLAUDE_CLI_CWD_PREFIX}9001`);+ mkdirSync(self, { recursive: true });+ mkdirSync(corpus, { recursive: true });+ writeFileSync(join(self, 'self-session.jsonl'), '{}\n');+ writeFileSync(join(corpus, 'self-session.txt'), 'captured from a gbrain claude-cli call');+ await engine.setConfig('dream.synthesize.session_corpus_dir', corpus);+ }+ return { claudeDir, corpus };+}++/** A managed brain seeded with wave findings, run with CLAUDE_CONFIG_DIR pointing at the fixture. */+export async function waveBrain(run: (brain: ManagedBrain & { corpus: string }) => Promise<void>,+ opts: { databaseUrl?: string; kinds?: WaveFindingKind[] } = {}): Promise<void> {+ await managedBrain(async brain => {+ const home = process.env.GBRAIN_HOME!;+ const { claudeDir, corpus } = await seedWaveFindings(brain, home, opts.kinds);+ await withEnv({ CLAUDE_CONFIG_DIR: claudeDir }, () => run({ ...brain, corpus }));+ }, { databaseUrl: opts.databaseUrl });+}diff --git a/test/helpers/wave-scenarios.ts b/test/helpers/wave-scenarios.tsnew file mode 100644index 0000000000..83fc4d2b4c--- /dev/null+++ b/test/helpers/wave-scenarios.ts@@ -0,0 +1,272 @@+/**+ * Engine-parametrized recovery-layer scenarios (fix wave 3, Lane D): remote+ * host-action lines, the remediation plan's repair steps, consent, the+ * scripted recovery run with finding classes and exit status, the cumulative+ * budget and the resume contract. test/ runs them on PGLite; test/e2e/ runs+ * the same bodies on Postgres.+ */+import { expect } from 'bun:test';+import type { BrainEngine } from '../../src/core/engine.ts';+import { doctorReportRemote } from '../../src/commands/doctor.ts';+import { remediationExitStatus, runRemediate, runRemediationPlan } from '../../src/commands/doctor/remediate.ts';+import { REMOTE_HOST_ACTION, remoteWaveHandoff } from '../../src/commands/doctor/wave-checks.ts';+import { currentExitCode, setCliExitVerdict } from '../../src/core/cli-force-exit.ts';+import { configureGateway, resetGateway } from '../../src/core/ai/gateway.ts';+import { computePlanHash, listRemediationCheckpoints, loadRemediationCheckpoint, saveRemediationCheckpoint } from '../../src/core/remediation-checkpoint.ts';+import { runRemediation } from '../../src/core/remediation/run.ts';+import { managedBrain } from './managed-brain.ts';+import { put, waveBrain } from './wave-fixture.ts';++/** Run a CLI shell function, capturing stdout/stderr lines and the exit verdict. */+export async function capture(run: () => Promise<void>): Promise<{ out: string; err: string; exit: number }> {+ const out: string[] = [], err: string[] = [];+ const log = console.log, error = console.error;+ console.log = (...parts: unknown[]) => { out.push(parts.map(String).join(' ')); };+ console.error = (...parts: unknown[]) => { err.push(parts.map(String).join(' ')); };+ setCliExitVerdict(0);+ try { await run(); } finally { console.log = log; console.error = error; }+ const exit = currentExitCode();+ setCliExitVerdict(0);+ return { out: out.join('\n'), err: err.join('\n'), exit };+}++const json = async (engine: BrainEngine, args: string[], fn = runRemediate) => {+ const result = await capture(() => fn(engine, args));+ return { ...result, body: JSON.parse(result.out) };+};++export async function remoteLinesForWaveFindings(databaseUrl?: string) {+ await waveBrain(async ({ engine, root, corpus }) => {+ const report = await doctorReportRemote(engine, { remote: true });+ for (const id of ['timeline_history', 'derived_visibility', 'persistence_capacity', 'parked_effects']) {+ const line = report.checks.filter(c => c.name === id);+ expect(line).toHaveLength(1);+ expect(line[0]).toMatchObject({ status: 'warn', details: { host_action: { check_id: id, state: 'action_required', preview_command: 'gbrain doctor --remediation-plan' } } });+ expect(line[0]!.message).toContain(REMOTE_HOST_ACTION);+ const text = JSON.stringify(line[0]);+ for (const secret of [root, corpus, 'notes/history', 'atoms/unstamped', 'notes/base', 'principal:', 'SELECT', 'persistence_counters', 'persistence_effects', '1000', '850', 'git_target_unsafe']) expect(text).not.toContain(secret);+ }+ }, { databaseUrl, kinds: ['timeline', 'visibility', 'capacity', 'parked'] });++ await managedBrain(async ({ engine, ctx }) => {+ await put(ctx, 'notes/clean', 'Nothing to repair.');+ const report = await doctorReportRemote(engine, { remote: true });+ expect(report.checks.filter(c => c.message.includes('host operator action required'))).toEqual([]);+ for (const id of ['timeline_history', 'derived_visibility', 'persistence_capacity', 'parked_effects']) {+ expect(report.checks.find(c => c.name === id)).toMatchObject({ status: 'ok', details: { host_action: { state: 'ok' } } });+ }+ // A check that cannot run reports unknown, never ok.+ const broken = new Proxy(engine, { get(target, prop, receiver) {+ if (prop === 'executeRaw') return (sql: string, params?: unknown[]) => /persistence_counters/.test(sql)+ ? Promise.reject(new Error('relation unavailable')) : target.executeRaw(sql, params as never);+ return Reflect.get(target, prop, receiver);+ } }) as BrainEngine;+ const lines = await remoteWaveHandoff(broken);+ const capacity = lines.find(c => c.name === 'persistence_capacity')!;+ expect(capacity).toMatchObject({ status: 'warn', details: { host_action: { state: 'unknown' } } });+ expect(capacity.message).toStartWith('Unknown:');+ expect(capacity.message).not.toContain('relation unavailable');+ }, { databaseUrl });+}++export async function planListsRepairStepsIndependentOfTarget(databaseUrl?: string) {+ await waveBrain(async ({ engine }) => {+ const { body } = await json(engine, ['--remediation-plan', '--json', '--target-score', '100'], runRemediationPlan);+ expect(body.repair_steps.map((s: { kind: string }) => s.kind)).toEqual(['timeline', 'visibility', 'safe-chunks']);+ for (const step of body.repair_steps) {+ expect(step).toMatchObject({ requires_user_agreement: true, protected: true, command: `gbrain repair ${step.kind} --apply` });+ expect(step.affected).toBeGreaterThan(0);+ }+ expect(body.combined_command).toStartWith('gbrain doctor --remediate --yes --include-repairs --max-usd ');+ for (const step of body.plan) expect(step.command).toStartWith(`gbrain jobs submit ${step.job}`);+ const human = await capture(() => runRemediationPlan(engine, ['--remediation-plan']));+ expect(human.out).toContain('requires user agreement');+ expect(human.out).toContain('apply: gbrain repair timeline --apply');+ expect(human.out).toContain('gbrain doctor --remediate --yes --include-repairs --max-usd');+ expect(human.out).not.toContain('Brain is at target');+ }, { databaseUrl, kinds: ['timeline', 'visibility', 'safe_index'] });+}++export async function remediateWithoutConsentSkipsRepairs(databaseUrl?: string) {+ await waveBrain(async ({ engine }) => {+ const timelineBefore = await engine.executeRaw("SELECT timeline FROM pages WHERE slug='notes/history'");+ const { body, exit } = await json(engine, ['--remediate', '--yes', '--json']);+ expect(body.repairs_skipped.map((s: { kind: string }) => s.kind)).toEqual(['timeline', 'visibility', 'safe-chunks']);+ expect(body.repairs).toEqual([]);+ const classes = Object.fromEntries(body.findings.map((f: { check_id: string; class: string }) => [f.check_id, f.class]));+ expect(classes).toMatchObject({ timeline_history: 'consent_required', derived_visibility: 'consent_required', safe_index_pending: 'consent_required' });+ expect(exit).toBe(1);+ expect(await engine.executeRaw("SELECT timeline FROM pages WHERE slug='notes/history'")).toEqual(timelineBefore);+ const human = await capture(() => runRemediate(engine, ['--remediate', '--yes']));+ expect(human.out).toContain('3 repair steps skipped (user agreement required): re-run with --include-repairs');+ expect(human.out).toContain('gbrain repair safe-chunks --apply');+ }, { databaseUrl, kinds: ['timeline', 'visibility', 'safe_index'] });+}++/** CEO Lane D test (5) + DX recovery measurement: every finding class, exit status, commands and wall time. */+export async function scriptedRecoveryRun(databaseUrl?: string): Promise<{ wall_ms: number; operator_commands: number }> {+ let measured = { wall_ms: 0, operator_commands: 0 };+ await waveBrain(async ({ engine }) => {+ const started = Date.now();+ const commands: string[] = [];+ const plan = await json(engine, ['--remediation-plan', '--json'], runRemediationPlan);+ commands.push('gbrain doctor --remediation-plan');+ expect(plan.body.repair_steps.length).toBe(3);+ const run = await json(engine, ['--remediate', '--yes', '--include-repairs', '--no-embed', '--max-usd', '1', '--json']);+ commands.push('gbrain doctor --remediate --yes --include-repairs --no-embed --max-usd 1');+ const byId = Object.fromEntries(run.body.findings.map((f: { check_id: string }) => [f.check_id, f]));+ for (const id of ['timeline_history', 'derived_visibility', 'safe_index_pending']) expect(byId[id]).toMatchObject({ class: 'cleared' });+ expect(byId.persistence_capacity).toMatchObject({ class: 'operator_required' });+ expect(byId.parked_effects).toMatchObject({ class: 'operator_required' });+ expect(byId.self_capture).toMatchObject({ class: 'operator_required' });+ expect(byId.self_capture.instruction).toContain('Quarantine');+ expect(byId.writer_version).toMatchObject({ class: 'operator_required' });+ expect(byId.writer_version.instruction).toContain('gbrain upgrade');+ expect(byId.writer_version.message).toContain('0.60.4.0');+ expect(byId.stale_embedding_effects).toMatchObject({ class: 'unsupported' });+ expect(byId.stale_embedding_effects.message).toContain('inspection cannot clear it');+ expect(run.body.repairs_completed).toBe(3);+ expect(run.body.healthy).toBe(false);+ expect(run.body.exit_status).toBe(0);+ expect(run.exit).toBe(0);+ const verify = await json(engine, ['--remediation-plan', '--json'], runRemediationPlan);+ commands.push('gbrain doctor --remediation-plan');+ expect(verify.body.repair_steps).toEqual([]);+ measured = { wall_ms: Date.now() - started, operator_commands: commands.length };+ expect(measured.operator_commands).toBeLessThanOrEqual(3);+ expect(measured.wall_ms).toBeLessThan(5 * 60_000);+ }, { databaseUrl });+ return measured;+}++/**+ * A zero cap refuses the paid step before it starts, still applies the free+ * steps, saves a checkpoint with brain, cap, consent and manifest, and a+ * copied resume command (or a bare --resume) keeps them; another brain's+ * checkpoint is refused.+ */+export async function budgetAndResumeContract(databaseUrl?: string) {+ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: 1536, env: {} });+ try {+ await waveBrain(async ({ engine }) => {+ // With a priced model, the page-write kinds are paid (their publication re-embeds each page, outside+ // this process, so the estimate is reserved up front); --no-embed makes only safe-chunks free.+ const plan = await json(engine, ['--remediation-plan', '--json', '--no-embed'], runRemediationPlan);+ const planned = Object.fromEntries(plan.body.repair_steps.map((s: { kind: string }) => [s.kind, s]));+ expect(planned.timeline).toMatchObject({ paid: true, embeds: 'effect' });+ expect(planned['safe-chunks']).toMatchObject({ paid: false, est_usd_cost: 0 });+ const first = await json(engine, ['--remediate', '--yes', '--include-repairs', '--no-embed', '--max-usd', '0', '--json']);+ const byKind = Object.fromEntries(first.body.repairs.map((r: { kind: string }) => [r.kind, r]));+ expect(byKind.timeline).toMatchObject({ status: 'budget_refused' });+ expect(byKind.visibility).toMatchObject({ status: 'budget_refused' });+ expect(byKind['safe-chunks']).toMatchObject({ status: 'completed', applied: 1 });+ expect(first.body.budget_exhausted).toMatchObject({ cap: 0, reason: 'max_usd' });+ expect(first.exit).toBe(1);+ expect(first.err).toContain(`gbrain doctor --remediate --yes --include-repairs --max-usd 0 --resume ${first.body.budget_exhausted.plan_hash}`);+ const history = await engine.executeRaw<{ timeline: string }>("SELECT timeline FROM pages WHERE slug='notes/history'");+ expect(history[0]!.timeline).not.toContain('gbrain:materialized');++ const cp = loadRemediationCheckpoint(first.body.budget_exhausted.plan_hash)!;+ expect(cp).toMatchObject({ max_usd: 0, include_repairs: true, manifest: { repair_kinds: ['timeline', 'visibility', 'safe-chunks'] } });+ expect(cp.completed.map(c => c.id)).toEqual(['repair:safe-chunks']);++ // Resume without --max-usd reuses the recorded cap and consent (no --include-repairs given).+ const again = await json(engine, ['--remediate', '--yes', '--no-embed', '--resume', '--json']);+ expect(again.err).toContain('cumulative cap $0.00');+ expect(again.body.budget).toMatchObject({ max_usd: 0, include_repairs: true });+ expect(again.body.repairs.map((r: { kind: string; status: string }) => [r.kind, r.status])).toEqual([['timeline', 'budget_refused'], ['visibility', 'budget_refused']]);++ // The copied resume command with a raised cap finishes the paid steps and reserves their estimate.+ const raised = await json(engine, ['--remediate', '--yes', '--include-repairs', '--no-embed', '--max-usd', '5', '--resume', first.body.budget_exhausted.plan_hash, '--json']);+ expect(raised.body.repairs.map((r: { kind: string; status: string }) => [r.kind, r.status])).toEqual([['timeline', 'completed'], ['visibility', 'completed']]);+ expect(raised.body.budget_exhausted).toBeUndefined();+ expect(raised.body.budget.spent_usd).toBeGreaterThan(0);+ expect((await engine.executeRaw<{ timeline: string }>("SELECT timeline FROM pages WHERE slug='notes/history'"))[0]!.timeline).toContain('gbrain:materialized');+ expect(listRemediationCheckpoints().map(e => e.plan_hash)).not.toContain(first.body.budget_exhausted.plan_hash);++ // A checkpoint recorded for another brain is refused, never silently resumed.+ saveRemediationCheckpoint({ ...cp, plan_hash: 'otherbrain000001', brain_id: '00000000-0000-4000-8000-000000000000' });+ const foreign = await json(engine, ['--remediate', '--yes', '--resume', 'otherbrain000001', '--json']);+ expect(foreign.body.resume_refused).toMatchObject({ reason: 'brain_mismatch', plan_hash: 'otherbrain000001' });+ expect(foreign.exit).toBe(2);+ expect(foreign.err).toContain('belongs to brain 00000000-0000-4000-8000-000000000000');+ // Two brains that need the same steps never share a checkpoint file.+ expect(first.body.budget_exhausted.plan_hash).not.toBe(computePlanHash(['repair:timeline', 'repair:visibility', 'repair:safe-chunks']));+ }, { databaseUrl, kinds: ['timeline', 'visibility', 'safe_index'] });+ } finally { resetGateway(); }+}++export async function remoteCallerCannotRunRepairs(databaseUrl?: string) {+ await waveBrain(async ({ engine }) => {+ await expect(runRemediation(engine, { repairs: { include: true, remote: true } })).rejects.toMatchObject({ code: 'permission_denied' });+ const { runRepairSteps, planRepairSteps } = await import('../../src/core/remediation/repairs.ts');+ const steps = await planRepairSteps(engine);+ await expect(runRepairSteps(engine, steps, { remote: true, remainingUsd: () => undefined })).rejects.toMatchObject({ code: 'permission_denied' });+ expect((await engine.executeRaw<{ timeline: string }>("SELECT timeline FROM pages WHERE slug='notes/history'"))[0]!.timeline).not.toContain('gbrain:materialized');+ }, { databaseUrl, kinds: ['timeline'] });+}++/** A budget exhaustion a callee swallowed (the stale-embedding pass) still marks the paid step and refuses later paid steps. */+export async function swallowedExhaustionIsReported(databaseUrl?: string) {+ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: 1536, env: {} });+ try {+ await waveBrain(async ({ engine }) => {+ const { planRepairSteps, runRepairSteps } = await import('../../src/core/remediation/repairs.ts');+ const steps = (await planRepairSteps(engine)).filter(step => step.kind === 'safe-chunks');+ expect(steps).toEqual([expect.objectContaining({ paid: true, embeds: 'inline' })]);+ let polls = 0, budgeted = 0;+ const [result, later] = await runRepairSteps(engine, [...steps, { ...steps[0]!, id: 'repair:safe-chunks-again' }], {+ remote: false, remainingUsd: () => 10, exhausted: () => ++polls > 1,+ stepBudget: async run => { budgeted++; return run(); } });+ // An in-process paid step runs under its own tracker capped at what reservations left.+ expect(budgeted).toBe(1);+ expect(result).toMatchObject({ kind: 'safe-chunks', status: 'budget_exhausted' });+ expect(result!.message).toContain('gbrain embed --stale');+ expect(later).toMatchObject({ status: 'budget_refused' });+ }, { databaseUrl, kinds: ['safe_index'] });+ } finally { resetGateway(); }+}++/** Reserved effect-repair estimates reduce what job steps may spend: a job that fit before the repairs is refused after them. */+export async function jobsRecheckedAfterRepairReservations(databaseUrl?: string) {+ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: 1536, env: {} });+ try {+ await waveBrain(async ({ engine }) => {+ const { makeRemediationStep } = await import('../../src/core/remediation-step.ts');+ const job = makeRemediationStep({ id: 'test.paid-job', job: 'lint', params: {}, severity: 'low', est_seconds: 1, est_usd_cost: 1,+ rationale: 'a job whose estimate equals the whole cap' } as never);+ const result = await runRemediation(engine, { targetScore: 0, maxUsd: 1, extraRemediations: [job], repairs: { include: true, remote: false } });+ expect(result.repairs).toEqual([expect.objectContaining({ kind: 'timeline', status: 'completed' })]);+ expect(result.submitted).toEqual([]);+ expect(result.budget_exhausted).toMatchObject({ cap: 1, reason: 'max_usd' });+ expect(result.budget!.spent_usd).toBeGreaterThan(0);+ }, { databaseUrl, kinds: ['timeline'] });+ } finally { resetGateway(); }+}++/** Embeddings a budget stop left after re-sealing resume from the checkpoint even though the pages left the repair plan. */+export async function pendingEmbeddingsResume(databaseUrl?: string) {+ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: 1536, env: {} });+ try {+ await waveBrain(async ({ engine }) => {+ await capture(async () => { const { runRepairCommand } = await import('../../src/commands/repair.ts'); await runRepairCommand(engine, ['safe-chunks', '--apply', '--no-embed']); });+ const { planRepairSteps } = await import('../../src/core/remediation/repairs.ts');+ expect(await planRepairSteps(engine)).toEqual([]);+ const brainId = (await engine.executeRaw<{ brain_id: string }>('SELECT brain_id FROM persistence_brain WHERE singleton=1'))[0]!.brain_id;+ saveRemediationCheckpoint({ schema_version: 1, plan_hash: 'pendingembeds001', doctor_run_id: 'x', target_score: 90, started_at: new Date().toISOString(),+ completed: [], aborted_at: new Date().toISOString(), abort_reason: 'budget_exhausted', brain_id: brainId, max_usd: 0, include_repairs: true,+ spent_usd: 0, manifest: { job_ids: [], repair_kinds: ['safe-chunks'] }, pending_embed_sources: ['default'] });+ const stopped = await runRemediation(engine, { resume: true, resumePlanHash: 'pendingembeds001', repairs: { include: false, remote: false } });+ expect(stopped.repairs).toEqual([expect.objectContaining({ id: 'repair:safe-chunks:embeddings', status: 'budget_refused' })]);+ expect(stopped.budget_exhausted).toMatchObject({ cap: 0 });+ expect(loadRemediationCheckpoint('pendingembeds001')!.pending_embed_sources).toEqual(['default']);+ // With a raised cap the pass runs; with no provider key nothing is embedded, so it reports the gap instead of completing.+ const ran = await runRemediation(engine, { resume: true, resumePlanHash: 'pendingembeds001', maxUsd: 5, repairs: { include: false, remote: false } });+ expect(ran.repairs).toEqual([expect.objectContaining({ id: 'repair:safe-chunks:embeddings', status: 'stopped' })]);+ expect(ran.repairs![0]!.message).toContain('gbrain embed --stale');+ expect(remediationExitStatus(ran, [])).toBe(1);+ // The unfinished embeddings stay resumable, with the settled spend.+ expect(loadRemediationCheckpoint('pendingembeds001')).toMatchObject({ pending_embed_sources: ['default'], max_usd: 5 });+ }, { databaseUrl, kinds: ['safe_index'] });+ } finally { resetGateway(); }+}diff --git a/test/import-signature-stamp.serial.test.ts b/test/import-signature-stamp.serial.test.tsindex 4614f0fb4c..9af03e5797 100644--- a/test/import-signature-stamp.serial.test.ts+++ b/test/import-signature-stamp.serial.test.ts@@ -45,7 +45,7 @@ beforeEach(async () => {// Fake transport (AI SDK embedMany shape): receives { values }, returns// one zero-vector (sized to the column) per input value.__setEmbedTransportForTests(async ({ values }: { values: string[] }) => ({- embeddings: values.map(() => Array(colDim).fill(0)),+ embeddings: values.map(() => Array(colDim).fill(0.01)),usage: { tokens: 0 },}) as any);});diff --git a/test/import-source-cr-mode.serial.test.ts b/test/import-source-cr-mode.serial.test.tsindex 070e79e7c9..502b4b3f5d 100644--- a/test/import-source-cr-mode.serial.test.ts+++ b/test/import-source-cr-mode.serial.test.ts@@ -8,11 +8,19 @@* so a per-source 'none' override was ignored and the global bundle* (balanced → title) silently won.*+ * #5621: legacy --no-embed imports (large syncs, connector sources) stamp+ * the same resolved mode, so the later embed pass wraps them as well.+ ** .serial: real PGLite + gateway stubbing (docs/TESTING.md R1).*/import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';+import { 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 { importFromContent } from '../src/core/import-file.ts';+import { importFile, importFromContent } from '../src/core/import-file.ts';+import { embedStaleForSource, type EmbedStaleOpts } from '../src/core/embed-stale.ts';+import { titleTierCorpusGeneration } from '../src/core/contextual-retrieval-service.ts';import {__setEmbedTransportForTests,configureGateway,@@ -115,3 +123,218 @@ describe('#3885 stored per-source CR mode applies on the inline import path', ()expect(await stampedMode('notes/probe-syn', 'vault-syn')).toBe('title');}, 60_000);});++describe('#5621 noEmbed imports record the wrapping convention for the later embed pass', () => {+ const WRAPPED = '<context>CR Mode Probe';+ const deferred = (tag: string) => CONTENT.replace('A body', `A ${tag} body`);+ const paragraph = (tag: string) => Array.from({ length: 250 }, (_, i) => `${tag}${i}`).join(' ') + '.';+ const probePage = (...paragraphs: string[]) =>+ `---\ntitle: "CR Mode Probe"\ntype: note\n---\n\n${paragraphs.join('\n\n')}\n`;+ let dir = '';++ beforeAll(() => {+ dir = mkdtempSync(join(tmpdir(), 'cr-defer-'));+ });++ afterAll(() => {+ rmSync(dir, { recursive: true, force: true });+ });++ async function plainSource(id: string): Promise<string> {+ await engine.executeRaw(`INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING`, [id]);+ return id;+ }++ async function stampedState(slug: string, sourceId: string) {+ const rows = await engine.executeRaw<{ contextual_retrieval_mode: string | null; corpus_generation: string | null }>(+ `SELECT contextual_retrieval_mode, corpus_generation FROM pages WHERE slug = $1 AND source_id = $2`,+ [slug, sourceId],+ );+ expect(rows.length).toBe(1);+ return rows[0];+ }++ async function drain(sourceId: string, extra: EmbedStaleOpts = {}): Promise<string[]> {+ const seen: string[] = [];+ await embedStaleForSource(engine, sourceId, {+ ...extra,+ embedFn: async (texts) => {+ seen.push(...texts);+ return texts.map(() => new Float32Array(STUB_DIMS).fill(0.001));+ },+ });+ return seen;+ }++ /** The sync / Google / GitHub entry point: importFile with embedding deferred. */+ async function importSynced(sourceId: string, relativePath: string, content: string): Promise<string> {+ const file = join(dir, `${sourceId}-${relativePath.split('/').pop() ?? 'page.md'}`);+ writeFileSync(file, content);+ const result = await importFile(engine, file, relativePath, { sourceId, noEmbed: true });+ expect(result.status).toBe('imported');+ return result.slug;+ }++ /** A page left NULL and embedded raw, the shape every noEmbed import had before #5621. */+ async function legacyEmbeddedPage(slug: string, sourceId: string, content: string): Promise<void> {+ await importFromContent(engine, slug, content, { sourceId, noEmbed: true });+ await engine.executeRaw(+ `UPDATE pages SET contextual_retrieval_mode = NULL, corpus_generation = NULL WHERE slug = $1 AND source_id = $2`,+ [slug, sourceId],+ );+ const seen = await drain(sourceId);+ expect(seen.length).toBeGreaterThan(0);+ expect(seen.some((text) => text.startsWith('<context>'))).toBe(false);+ }++ test('noEmbed import stamps the resolved title tier without calling the provider', async () => {+ await importFromContent(engine, 'notes/defer-plain', deferred('plain'), { sourceId: 'vault-plain', noEmbed: true });+ expect(embedderInputs).toHaveLength(0);+ expect(await stampedState('notes/defer-plain', 'vault-plain')).toEqual({+ contextual_retrieval_mode: 'title',+ corpus_generation: titleTierCorpusGeneration(),+ });+ }, 60_000);++ test("noEmbed import honors a source override of 'none'", async () => {+ await importFromContent(engine, 'notes/defer-off', deferred('off'), { sourceId: 'vault-off', noEmbed: true });+ expect(await stampedState('notes/defer-off', 'vault-off')).toEqual({+ contextual_retrieval_mode: 'none',+ corpus_generation: null,+ });+ }, 60_000);++ test("noEmbed import demotes a per_chunk_synopsis source to the title tier", async () => {+ const slug = await importSynced('vault-syn', 'notes/deferred-syn.md', deferred('synopsis'));+ expect(embedderInputs).toHaveLength(0);+ expect(await stampedState(slug, 'vault-syn')).toEqual({+ contextual_retrieval_mode: 'title',+ corpus_generation: titleTierCorpusGeneration(),+ });+ const seen = await drain('vault-syn');+ expect(seen.length).toBeGreaterThan(0);+ expect(seen.every((text) => text.startsWith(WRAPPED))).toBe(true);+ }, 60_000);++ test('a failed source read fails the noEmbed import instead of stamping the global mode', async () => {+ const slug = 'notes/defer-read-fault';+ const original = engine.executeRaw;+ let faults = 0;+ // Keep `this`: transaction engines inherit this property, and routing+ // their reads back to the outer engine would deadlock PGLite.+ engine.executeRaw = async function (this: PGLiteEngine, sql: string, params?: unknown[]) {+ if (faults === 0 && sql.includes('trust_frontmatter_overrides') && sql.includes('FROM sources WHERE id')) {+ faults++;+ throw new Error('source read reset');+ }+ return original.call(this, sql, params);+ } as typeof engine.executeRaw;+ try {+ await expect(importFromContent(engine, slug, deferred('fault'), { sourceId: 'vault-off', noEmbed: true }))+ .rejects.toThrow('source read reset');+ } finally {+ engine.executeRaw = original;+ }+ expect(faults).toBe(1);+ const rows = await engine.executeRaw(`SELECT 1 FROM pages WHERE slug = $1 AND source_id = 'vault-off'`, [slug]);+ expect(rows).toHaveLength(0);+ }, 60_000);++ test('a file synced with noEmbed is embedded title-wrapped by the stale drain', async () => {+ const sourceId = await plainSource('vault-drain');+ const slug = await importSynced(sourceId, 'notes/deferred.md', deferred('synced'));+ expect(embedderInputs).toHaveLength(0);+ const seen = await drain(sourceId);+ expect(seen.length).toBeGreaterThan(0);+ expect(seen.every((text) => text.startsWith(WRAPPED))).toBe(true);+ expect((await stampedState(slug, sourceId)).contextual_retrieval_mode).toBe('title');+ }, 60_000);++ test('a changed noEmbed re-import leaves no unwrapped vector under the new stamp', async () => {+ const sourceId = await plainSource('vault-changed');+ const slug = 'notes/defer-changed';+ await legacyEmbeddedPage(slug, sourceId, probePage(paragraph('a'), paragraph('b'), paragraph('c')));+ const before = await engine.getChunks(slug, { sourceId });+ expect(before.length).toBeGreaterThanOrEqual(3);++ await importFromContent(engine, slug, probePage(paragraph('a'), paragraph('b'), paragraph('edited')), {+ sourceId,+ noEmbed: true,+ });+ expect((await stampedState(slug, sourceId)).contextual_retrieval_mode).toBe('title');+ const chunks = await engine.getChunks(slug, { sourceId });+ // Unchanged paragraphs keep their chunk_text; their raw vectors must still go.+ expect(chunks.some((chunk) => before.some((old) => old.chunk_text === chunk.chunk_text))).toBe(true);+ expect(chunks.every((chunk) => chunk.embedding_is_null === true)).toBe(true);++ const seen = await drain(sourceId);+ expect(seen).toHaveLength(chunks.length);+ expect(seen.every((text) => text.startsWith(WRAPPED))).toBe(true);+ }, 60_000);++ test('unchanged content keeps its legacy convention: the backlog stays reindex work', async () => {+ const sourceId = await plainSource('vault-unchanged');+ const slug = 'notes/defer-unchanged';+ await legacyEmbeddedPage(slug, sourceId, deferred('unchanged'));++ const result = await importFromContent(engine, slug, deferred('unchanged'), { sourceId, noEmbed: true });+ expect(result.status).toBe('skipped');+ expect(await stampedState(slug, sourceId)).toEqual({ contextual_retrieval_mode: null, corpus_generation: null });+ const chunks = await engine.getChunks(slug, { sourceId });+ expect(chunks.length).toBeGreaterThan(0);+ expect(chunks.every((chunk) => chunk.embedding_is_null === false)).toBe(true);+ }, 60_000);++ test('a page whose chunks straddle a drain batch is wrapped on both sides of the boundary', async () => {+ const sourceId = await plainSource('vault-straddle');+ const slug = await importSynced(sourceId, 'notes/straddle.md', probePage(paragraph('x'), paragraph('y'), paragraph('z')));+ const chunks = await engine.getChunks(slug, { sourceId });+ expect(chunks.length).toBeGreaterThanOrEqual(3);++ const seen = await drain(sourceId, { concurrency: 1, batchSize: 2 });+ expect(seen).toHaveLength(chunks.length);+ expect(seen.every((text) => text.startsWith(WRAPPED))).toBe(true);+ expect((await stampedState(slug, sourceId)).contextual_retrieval_mode).toBe('title');+ expect((await engine.getChunks(slug, { sourceId })).every((chunk) => chunk.embedding_is_null === false)).toBe(true);+ }, 60_000);++ test('a code import keeps the raw convention', async () => {+ const sourceId = await plainSource('vault-code');+ const slug = await importSynced(sourceId, 'src/probe.ts', 'export function probe(value: number): number {\n return value * 2;\n}\n');+ const seen = await drain(sourceId);+ expect(seen.length).toBeGreaterThan(0);+ expect(seen.some((text) => text.includes('<context>'))).toBe(false);+ expect((await stampedState(slug, sourceId)).contextual_retrieval_mode).toBeNull();+ }, 60_000);++ test('a changed re-import during a drain supersedes the raw vectors it was computing', async () => {+ const sourceId = await plainSource('vault-race');+ const slug = 'notes/defer-race';+ await importFromContent(engine, slug, deferred('race'), { sourceId, noEmbed: true });+ await engine.executeRaw(+ `UPDATE pages SET contextual_retrieval_mode = NULL, corpus_generation = NULL WHERE slug = $1 AND source_id = $2`,+ [slug, sourceId],+ );++ let reimported = false;+ const raw: string[] = [];+ await embedStaleForSource(engine, sourceId, {+ embedFn: async (texts) => {+ raw.push(...texts);+ if (!reimported) {+ reimported = true;+ await importFromContent(engine, slug, deferred('race edited'), { sourceId, noEmbed: true });+ }+ return texts.map(() => new Float32Array(STUB_DIMS).fill(0.001));+ },+ });+ expect(reimported).toBe(true);+ expect(raw.some((text) => text.startsWith('<context>'))).toBe(false);+ expect((await stampedState(slug, sourceId)).contextual_retrieval_mode).toBe('title');+ expect((await engine.getChunks(slug, { sourceId })).every((chunk) => chunk.embedding_is_null === true)).toBe(true);++ const seen = await drain(sourceId);+ expect(seen.length).toBeGreaterThan(0);+ expect(seen.every((text) => text.startsWith(WRAPPED))).toBe(true);+ }, 60_000);+});diff --git a/test/init-embed-check.test.ts b/test/init-embed-check.test.tsindex 8a5c960e69..4101e138ed 100644--- a/test/init-embed-check.test.ts+++ b/test/init-embed-check.test.ts@@ -121,7 +121,7 @@ describe('runInitEmbedCheck — live probe (best-effort)', () => {// seam bypasses the SDK call, not the auth-resolution step).await withEnv({ OPENAI_API_KEY: 'sk-test' }, async () => {__setEmbedTransportForTests(async (args: any) => ({- embeddings: (args.values as string[]).map(() => new Array(1536).fill(0)),+ embeddings: (args.values as string[]).map(() => new Array(1536).fill(0.01)),usage: { tokens: 1 },}) as any);const { warn, warned } = capture();diff --git a/test/managed-connector-routing.serial.test.ts b/test/managed-connector-routing.serial.test.tsindex 36c95fee6f..77c65a228e 100644--- a/test/managed-connector-routing.serial.test.ts+++ b/test/managed-connector-routing.serial.test.ts@@ -110,6 +110,8 @@ test('deliberate activation and public sync route unbound API sources without crcalls++;const url = new URL(input instanceof Request ? input.url : String(input));if (url.pathname.endsWith('/settings/sendAs')) return json({ sendAs: [] });+ // #5686: the managed Google run resolves the credential's account before sweeping.+ if (url.pathname.endsWith('/people/me')) return json({ emailAddresses: [{ value: googleConfig.g_account, metadata: { primary: true } }] });if (url.pathname.endsWith('/people/me/connections')) return json({ connections: [{ resourceName: 'people/routing', names: [{ displayName: 'Connector Example' }], emailAddresses: [{ value: '[email protected]' }] }], nextSyncToken: 'routing-contacts' });if (url.pathname.endsWith('/issues')) return json([issue]);if (url.pathname.endsWith('/pulls') || url.pathname.endsWith('/comments')) return json([]);diff --git a/test/managed-facts-backstop.test.ts b/test/managed-facts-backstop.test.tsindex 996d176f80..ebe6d0298b 100644--- a/test/managed-facts-backstop.test.ts+++ b/test/managed-facts-backstop.test.ts@@ -52,12 +52,24 @@ test('omitted extraction request IDs create distinct writes and returned IDs rec} finally { await disposePersistenceConsumer(engine); rmSync(home, { recursive: true, force: true }); }}, 60_000);-test('legacy fact fence callers refuse managed work before falling back or touching files', async () => {- await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');- await expect(writeFactsToFence(engine, { sourceId: 'default', slug: 'people/example', localPath: null, resolutionSource: 'exact_page' }, [- { fact: 'A synthetic fact.', kind: 'fact', source: 'fixture', visibility: 'private', notability: 'medium', embedding: null, sessionId: null },- ])).rejects.toMatchObject({ code: 'writer_coordinator_required' });- expect(await engine.executeRaw('SELECT id FROM facts')).toHaveLength(0);+test('managed direct fact fence callers publish through the coordinator instead of the legacy fallback', async () => {+ // #5280: the legacy file edit and DB-only fallback never run on a managed+ // brain; an entity with no live page lands database-only through the+ // coordinator's fact intent (test/managed-facts-writers.test.ts covers a file-backed entity).+ const home = mkdtempSync(join(tmpdir(), 'gbrain-managed-fence-write-'));+ try {+ await withEnv({ GBRAIN_HOME: home }, async () => {+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const result = await writeFactsToFence(engine, { sourceId: 'default', slug: 'people/example', localPath: null, resolutionSource: 'exact_page' }, [+ { fact: 'A synthetic fact.', kind: 'fact', source: 'fixture', visibility: 'private', notability: 'medium', embedding: null, sessionId: null },+ ]);+ expect(result).toMatchObject({ inserted: 1 });+ expect(result.legacyFallback).toBeUndefined();+ const rows = await engine.executeRaw<{ id: number; source_markdown_slug: string | null }>('SELECT id,source_markdown_slug FROM facts');+ expect(rows.map(r => [Number(r.id), r.source_markdown_slug])).toEqual([[result.ids[0], null]]);+ expect(await engine.executeRaw("SELECT id FROM persistence_requests WHERE operation='extract_facts' AND state='committed'")).toHaveLength(2);+ });+ } finally { await disposePersistenceConsumer(engine); rmSync(home, { recursive: true, force: true }); }});test('managed extract_facts publishes multiple private entity fences and replays without provider calls', async () => {diff --git a/test/managed-facts-writers.test.ts b/test/managed-facts-writers.test.tsnew file mode 100644index 0000000000..24a1eac6d0--- /dev/null+++ b/test/managed-facts-writers.test.ts@@ -0,0 +1,490 @@+/**+ * #5280 remainder: the facts-family maintenance writers publish through the+ * persistence coordinator on a managed brain instead of refusing with+ * writer_coordinator_required.+ *+ * 1. Protects: extract_facts reconcile (and its soft-deleted-page expiry),+ * phantom redirect, direct fence writes, Google loops extraction and bulk+ * conversation fact extraction (core, CLI, cycle phase) each land their+ * intended rows/files on a managed brain.+ * 2. Fails when: any of these writers takes the legacy path (the managed+ * writer guard trigger refuses it) or keeps its early refusal.+ * 3. Existing coverage only pinned the refusals+ * (managed-unsupported-preflight.serial.test.ts).+ * 4. No production seam: model calls use the gateway's test transports and+ * the conversation core's existing extractor injection.+ *+ * Journaled writers assert a committed persistence request; DB-only derived+ * rows (fence reconcile, conversation facts) assert the committed rows+ * while the managed guard is armed (an uncoordinated write refuses).+ */+import { afterAll, afterEach, beforeAll, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { serializePageToMarkdown } from '../src/core/markdown.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { configureGateway, resetGateway, __setChatTransportForTests, __setEmbedTransportForTests, type ChatResult } from '../src/core/ai/gateway.ts';+import { runExtractFacts } from '../src/core/cycle/extract-facts.ts';+import { runExtractConversationFactsCore, runExtractConversationFacts } from '../src/commands/extract-conversation-facts.ts';+import { runPhaseConversationFactsBackfill } from '../src/core/cycle/conversation-facts-backfill.ts';+import { writeFactsToFence } from '../src/core/facts/fence-write.ts';+import { writeSingleFact } from '../src/core/facts/write-single.ts';+import { runLoopsExtract } from '../src/core/google/loops-extract.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { withEnv } from './helpers/with-env.ts';+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { testBackends } from './helpers/test-backends.ts';++const backends = testBackends();+const engines: BrainEngine[] = [];+const dataDir = mkdtempSync(join(tmpdir(), 'gbrain-managed-facts-writers-db-'));+let closePostgres: (() => Promise<void>) | undefined;+let chatReply = '{"facts":[]}';++const usage = { input_tokens: 10, output_tokens: 10, cache_read_tokens: 0, cache_creation_tokens: 0 };+beforeAll(async () => {+ configureGateway({ chat_model: 'anthropic:claude-sonnet-4-6', embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536,+ env: { ANTHROPIC_API_KEY: 'sk-ant-test', OPENAI_API_KEY: 'sk-test' } });+ __setChatTransportForTests(async (): Promise<ChatResult> => ({ text: chatReply, blocks: [], stopReason: 'end', usage,+ model: 'anthropic:claude-sonnet-4-6', providerId: 'anthropic' }));+ __setEmbedTransportForTests((async ({ values }: { values: string[] }) => ({ embeddings: values.map(() => Array(1536).fill(0.01)) })) as never);+ if (backends.includes('pglite')) {+ const engine = new PGLiteEngine();+ await engine.connect({ database_path: dataDir }); 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);+afterEach(() => { chatReply = '{"facts":[]}'; });+afterAll(async () => {+ __setChatTransportForTests(null); __setEmbedTransportForTests(null);+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }+ await closePostgres?.(); resetGateway(); rmSync(dataDir, { recursive: true, force: true });+});++interface Fixture { engine: BrainEngine; sourceId: string; root: string; put(slug: string, content: string): Promise<void>; }++/** Seeds through ordinary coordinated page writes while unmanaged, then enables managed mode. */+async function managed(seed: (f: Fixture) => Promise<void>, run: (f: Fixture) => Promise<void>) {+ for (const engine of engines) {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-managed-facts-writers-'));+ const root = join(dir, 'brain'); mkdirSync(root);+ const sourceId = `facts-${randomUUID().slice(0, 8)}`;+ try {+ await withEnv({ GBRAIN_HOME: join(dir, 'home'), GBRAIN_AUDIT_DIR: join(dir, 'audit') }, async () => {+ 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)', [sourceId, root]);+ await engine.setConfig('sync.write_through', 'true');+ await engine.setConfig('facts.extraction_enabled', 'true');+ await engine.setConfig('conversation_parser.llm_fallback_enabled', 'false');+ await claimWorktree(engine, sourceId, root);+ const ctx = { engine, sourceId, remote: false as const, config: { engine: engine.kind, embedding_disabled: true },+ dryRun: false, logger: { info() {}, warn() {}, error() {} } };+ const fixture: Fixture = { engine, sourceId, root, put: async (slug, content) => {+ const prior = await engine.readPageSnapshot(slug, { sourceId });+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug, content, request_id: randomUUID(),+ ...(prior ? { expected_revision: prior.revision } : {}) } });+ } };+ await seed(fixture);+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ await expect(engine.executeRaw(`INSERT INTO facts(source_id,fact,kind,source,visibility) VALUES($1,'uncoordinated','fact','test','private')`,+ [sourceId])).rejects.toThrow(/writer_coordinator_required/);+ await run(fixture);+ });+ } finally {+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ rmSync(dir, { recursive: true, force: true });+ }+ }+}++const FENCE = (rows: string) => `## Facts++<!--- gbrain:facts:begin -->+| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |+|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|+${rows}+<!--- gbrain:facts:end -->+`;+const PERSON = (title: string, body = '') => `---\ntitle: ${title}\ntype: person\n---\n# ${title}\n\n${body}`;+const CONVERSATION = `---\ntitle: Synthetic chat\ntype: conversation\n---\n${[+ '**Alice Example** (2024-03-15 9:00 AM): I just signed the offer letter for Acme Corp.',+ '**Bob Demo** (2024-03-15 9:01 AM): Congrats! What is the title?',+ '**Alice Example** (2024-03-15 9:02 AM): Staff engineer on the platform team.',+].join('\n')}\n`;++async function facts(engine: BrainEngine, sourceId: string, slug: string) {+ return (await engine.executeRaw<{ id: number; fact: string; row_num: number | null; expired_at: unknown; source: string }>(+ 'SELECT id,fact,row_num,expired_at,source FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 ORDER BY row_num NULLS LAST,id', [sourceId, slug])).map(f => ({ ...f, id: Number(f.id), row_num: f.row_num == null ? null : Number(f.row_num) }));+}+async function committed(engine: BrainEngine, sourceId: string, slug: string) {+ return engine.executeRaw<{ state: string; operation: string; kind: string | null }>(+ "SELECT state,operation,intent->>'kind' AS kind FROM persistence_requests WHERE source_id=$1 AND slug=$2 AND state='committed' ORDER BY sequence",+ [sourceId, slug]);+}++test('managed extract_facts reconciles a drifted fence and expires a deleted page\'s facts inside the coordinator capability', async () => {+ await managed(async ({ engine, sourceId, put }) => {+ await put('people/alice-example', PERSON('Alice Example', FENCE([+ '| 1 | Founded Acme | fact | 1.0 | world | high | 2017-01-01 | | chat | |',+ '| 2 | Lives in Paris | fact | 1.0 | world | medium | 2018-01-01 | | chat | |'].join('\n'))));+ await put('people/bob-demo', PERSON('Bob Demo', FENCE('| 1 | Plays chess | fact | 1.0 | world | low | 2019-01-01 | | chat | |')));+ expect(await facts(engine, sourceId, 'people/alice-example')).toHaveLength(2);+ // Drift: the index lost the fence rows; the other page is deleted with active rows.+ await engine.executeRaw('DELETE FROM facts WHERE source_id=$1 AND source_markdown_slug=$2', [sourceId, 'people/alice-example']);+ await engine.softDeletePage('people/bob-demo', { sourceId });+ }, async ({ engine, sourceId }) => {+ const result = await runExtractFacts(engine, { sourceId, slugs: ['people/alice-example'] });+ expect(result.factsInserted).toBe(2);+ expect(result.factsExpiredForDeletedPages).toBe(1);+ expect((await facts(engine, sourceId, 'people/alice-example')).map(f => [f.row_num, f.fact, f.expired_at])).toEqual([+ [1, 'Founded Acme', null], [2, 'Lives in Paris', null]]);+ expect((await facts(engine, sourceId, 'people/bob-demo'))[0].expired_at).not.toBeNull();+ expect((await runExtractFacts(engine, { sourceId, slugs: ['people/alice-example'] })).factsInserted).toBe(0);+ });+}, 120_000);++test('managed phantom redirect merges the phantom fence into the canonical page and deletes the phantom through the coordinator', async () => {+ await managed(async ({ engine, sourceId, root, put }) => {+ await put('people/alice-example', PERSON('Alice Example'));+ // A legacy stub phantom: written without put_page provenance stamps, which the residue gate treats as content.+ await engine.putPage('alice', { type: 'person', title: 'alice', compiled_truth: `# alice\n\n${FENCE('| 1 | Founded Acme | fact | 1.0 | world | high | 2017-01-01 | | chat | |')}`.trim(),+ timeline: '', frontmatter: {} }, { sourceId });+ const phantom = (await engine.readPageSnapshot('alice', { sourceId }))!;+ writeFileSync(join(root, 'alice.md'), serializePageToMarkdown(phantom.page, phantom.tags));+ await runExtractFacts(engine, { sourceId, slugs: ['alice'] });+ }, async ({ engine, sourceId, root }) => {+ const [before] = await facts(engine, sourceId, 'alice');+ expect(before?.fact).toBe('Founded Acme');+ const result = await runExtractFacts(engine, { sourceId, brainDir: root });+ expect(result.phantomsRedirected).toBe(1);+ expect(result.warnings.filter(w => w.startsWith('phantom_redirect'))).toEqual([]);+ const moved = await facts(engine, sourceId, 'people/alice-example');+ expect(moved.map(f => [f.id, f.fact, f.expired_at])).toEqual([[before.id, 'Founded Acme', null]]);+ expect(readFileSync(join(root, 'people/alice-example.md'), 'utf8')).toContain('Founded Acme');+ expect(existsSync(join(root, 'alice.md'))).toBe(false);+ expect((await engine.readPageSnapshot('alice', { sourceId, includeDeleted: true }))?.page.deleted_at).not.toBeNull();+ expect(await engine.resolveSlugWithAlias('alice', sourceId)).toBe('people/alice-example');+ expect((await committed(engine, sourceId, 'people/alice-example')).map(r => r.kind)).toContain('managed_maintenance_phantom_merge');+ expect((await committed(engine, sourceId, 'alice')).map(r => r.kind)).toContain('managed_maintenance_phantom_delete');+ });+}, 120_000);++test('managed phantom redirect rechecks eligibility against the snapshot it merges', async () => {+ await managed(async ({ engine, sourceId, root, put }) => {+ await put('people/alice-example', PERSON('Alice Example'));+ await engine.putPage('alice', { type: 'person', title: 'alice', compiled_truth: `# alice\n\n${FENCE('| 1 | Founded Acme | fact | 1.0 | world | high | 2017-01-01 | | chat | |')}`.trim(),+ timeline: '', frontmatter: {} }, { sourceId });+ const phantom = (await engine.readPageSnapshot('alice', { sourceId }))!;+ writeFileSync(join(root, 'alice.md'), serializePageToMarkdown(phantom.page, phantom.tags));+ await runExtractFacts(engine, { sourceId, slugs: ['alice'] });+ }, async ({ engine, sourceId, root, put }) => {+ // After the pass judged the phantom residue-free, an edit adds timeline+ // text and metadata but leaves compiled_truth unchanged.+ const read = engine.readPageSnapshot;+ let edited = false;+ engine.readPageSnapshot = (async function (this: BrainEngine, slug: string, opts?: Parameters<BrainEngine['readPageSnapshot']>[1]) {+ if (this === engine && slug === 'alice' && !edited && new Error().stack?.includes('redirectManagedPhantom')) {+ edited = true;+ const current = (await read.call(this, slug, opts))!;+ await put('alice', serializePageToMarkdown({ ...current.page, frontmatter: { owner_note: 'keep me' },+ timeline: '- **2026-01-01** | Met at the offsite' }, current.tags));+ }+ return read.call(this, slug, opts);+ }) as BrainEngine['readPageSnapshot'];+ let result: Awaited<ReturnType<typeof runExtractFacts>>;+ try { result = await runExtractFacts(engine, { sourceId, brainDir: root }); }+ finally { delete (engine as { readPageSnapshot?: unknown }).readPageSnapshot; }+ expect(edited).toBe(true);+ const alive = await engine.readPageSnapshot('alice', { sourceId, includeDeleted: true });+ expect(alive?.page.deleted_at ?? null).toBeNull();+ expect(alive?.page.timeline).toContain('Met at the offsite');+ expect([result.phantomsRedirected, result.phantomsSkippedDrift]).toEqual([0, 1]);+ expect((await committed(engine, sourceId, 'people/alice-example')).map(r => r.kind)).not.toContain('managed_maintenance_phantom_merge');+ });+}, 120_000);++test('managed direct fence writes publish the fence row and index through the coordinator', async () => {+ await managed(async ({ put }) => { await put('people/alice-example', PERSON('Alice Example')); }, async ({ engine, sourceId, root }) => {+ const result = await writeFactsToFence(engine, { sourceId, localPath: root, slug: 'people/alice-example', resolutionSource: 'exact_page' }, [+ { fact: 'Prefers weekly status reports.', kind: 'preference', source: 'fixture', visibility: 'private', notability: 'medium', embedding: null, sessionId: null }]);+ expect(result.inserted).toBe(1);+ const rows = await facts(engine, sourceId, 'people/alice-example');+ expect(rows.map(f => [f.id, f.fact, f.row_num])).toEqual([[result.ids[0], 'Prefers weekly status reports.', 1]]);+ expect(readFileSync(join(root, 'people/alice-example.md'), 'utf8')).toContain('Prefers weekly status reports.');+ expect((await committed(engine, sourceId, 'people/alice-example')).map(r => r.kind)).toContain('managed_facts_entity');+ });+}, 120_000);++test('managed fence writes keep a fact\'s explicit context in the fence and the index', async () => {+ await managed(async ({ put }) => { await put('people/alice-example', PERSON('Alice Example')); }, async ({ engine, sourceId, root }) => {+ const write = (context: string) => writeFactsToFence(engine, { sourceId, localPath: root, slug: 'people/alice-example', resolutionSource: 'exact_page' }, [+ { fact: 'Prefers weekly status reports.', kind: 'preference', source: 'fixture', context, visibility: 'private', notability: 'medium', embedding: null, sessionId: null }]);+ const first = await write('meetings/review');+ const [row] = await engine.executeRaw<{ context: string | null }>('SELECT context FROM facts WHERE id=$1', [first.ids[0]]);+ expect(row.context).toBe('meetings/review');+ expect(readFileSync(join(root, 'people/alice-example.md'), 'utf8')).toContain('meetings/review');+ // Context is part of the write's identity: a different context is a new write, not a replay.+ expect((await committed(engine, sourceId, '__managed_facts_complete__')).length).toBe(1);+ await write('meetings/other');+ expect((await committed(engine, sourceId, '__managed_facts_complete__')).length).toBe(2);+ });+}, 120_000);++test('managed writeSingleFact supersedes a near-duplicate of the same kind like the unmanaged path', async () => {+ await managed(async ({ engine, put }) => {+ await engine.setConfig('embedding_model', 'openai:text-embedding-3-large');+ await engine.setConfig('embedding_dimensions', '1536');+ await put('people/alice-example', PERSON('Alice Example'));+ }, async ({ engine, sourceId, root }) => {+ const remember = (fact: string) => writeSingleFact(engine, sourceId, { fact, provenance: 'fixture', entity: 'people/alice-example', visibility: 'world' });+ const first = await remember('Alice Example works at Acme.');+ expect(first.status).toBe('inserted');+ const second = await remember('Alice Example works at Beta.');+ expect(second.status).toBe('superseded');+ expect(second.id).not.toBe(first.id);+ const [old] = await engine.executeRaw<{ expired_at: unknown; superseded_by: number | null }>('SELECT expired_at,superseded_by FROM facts WHERE id=$1', [first.id]);+ expect(old.expired_at).not.toBeNull();+ expect(Number(old.superseded_by)).toBe(second.id);+ expect((await facts(engine, sourceId, 'people/alice-example')).filter(f => f.expired_at === null).map(f => f.fact)).toEqual(['Alice Example works at Beta.']);+ expect(readFileSync(join(root, 'people/alice-example.md'), 'utf8')).toMatch(/~~Alice Example works at Acme\.~~/);+ });+}, 120_000);++test('managed Google loops extraction lands its commitment fact through the coordinator', async () => {+ await managed(async ({ engine, put }) => {+ await engine.setConfig('loops.extraction_enabled', 'true');+ await put('people/alice-example', PERSON('Alice Example'));+ await put('emails/example', `---\ntitle: Synthetic exchange\ntype: email\nthread_id: example\nfrom: [email protected]\n---\nI will send the deck by Friday.\n`);+ }, async ({ engine, sourceId, root }) => {+ chatReply = JSON.stringify({ commitments: [{ text: 'Send the deck by Friday', direction: 'owed_by_me',+ counterparty_name: 'people/alice-example', counterparty_email: '', due_iso: '2026-10-02', quote: 'I will send the deck by Friday.' }], decisions_pending: [] });+ const result = await runLoopsExtract(engine, { slug: 'emails/example', sourceId });+ expect(result).toMatchObject({ status: 'extracted', commitments: 1 });+ const [loop] = await engine.executeRaw<{ fact_id: number | null }>('SELECT fact_id FROM open_loops WHERE source_id=$1', [sourceId]);+ const rows = await facts(engine, sourceId, 'people/alice-example');+ expect(rows.map(f => [f.id, f.fact])).toEqual([[Number(loop.fact_id), 'Send the deck by Friday']]);+ expect(readFileSync(join(root, 'people/alice-example.md'), 'utf8')).toContain('Send the deck by Friday');+ expect((await committed(engine, sourceId, 'people/alice-example')).map(r => r.kind)).toContain('managed_facts_entity');+ });+}, 120_000);++const extractor = async () => [{ fact: 'Alice Example joined Acme Corp as a staff engineer.', kind: 'event' as const, entity_slug: null,+ confidence: 1, notability: 'high' as const, source: 'test', visibility: 'private' as const }];++test('managed bulk conversation extraction writes its facts and terminal audit row inside the coordinator capability', async () => {+ await managed(async ({ put }) => { await put('conversations/synthetic-chat', CONVERSATION); }, async ({ engine, sourceId }) => {+ const result = await runExtractConversationFactsCore(engine, { sourceId, overrideDisabled: true, extractor, types: ['conversation'] });+ expect(result.facts_inserted).toBe(1);+ expect(result.pages_failed).toBe(0);+ expect((await facts(engine, sourceId, 'conversations/synthetic-chat')).map(f => [f.fact, f.source])).toEqual([+ ['Alice Example joined Acme Corp as a staff engineer.', 'cli:extract-conversation-facts'],+ ['EXTRACTION_COMPLETE', 'cli:extract-conversation-facts:terminal:v2']]);+ // A forced replay deletes the prior rows first, also inside the capability.+ const replay = await runExtractConversationFactsCore(engine, { sourceId, overrideDisabled: true, extractor, types: ['conversation'], force: true });+ expect(replay.orphan_facts_cleaned).toBe(2);+ expect(await facts(engine, sourceId, 'conversations/synthetic-chat')).toHaveLength(2);+ });+}, 120_000);++test('republishing a managed conversation page keeps its extracted facts active and the page complete', async () => {+ // Conversation rows are numbered on the page coordinate but carry no fence;+ // like the legacy fence reconcile (#1928), the canonical projection must not+ // expire them as rows that left a fence.+ await managed(async ({ put }) => { await put('conversations/synthetic-chat', CONVERSATION); }, async ({ engine, sourceId, put }) => {+ await runExtractConversationFactsCore(engine, { sourceId, overrideDisabled: true, extractor, types: ['conversation'] });+ await put('conversations/synthetic-chat', CONVERSATION.replace('Staff engineer', 'A staff engineer'));+ expect((await facts(engine, sourceId, 'conversations/synthetic-chat')).map(f => [f.fact, f.row_num, f.expired_at])).toEqual([+ ['Alice Example joined Acme Corp as a staff engineer.', 0, null], ['EXTRACTION_COMPLETE', 1, null]]);+ // The edit changed the snapshot, so the next run replays the page delete-first.+ const rerun = await runExtractConversationFactsCore(engine, { sourceId, overrideDisabled: true, extractor, types: ['conversation'] });+ expect([rerun.facts_inserted, rerun.orphan_facts_cleaned]).toEqual([1, 2]);+ expect((await facts(engine, sourceId, 'conversations/synthetic-chat')).filter(f => f.expired_at === null).map(f => f.fact)).toEqual([+ 'Alice Example joined Acme Corp as a staff engineer.', 'EXTRACTION_COMPLETE']);+ });+}, 120_000);++test('managed phantom redirect defers the phantom delete when the phantom is edited after the merge', async () => {+ await managed(async ({ engine, sourceId, root, put }) => {+ await put('people/alice-example', PERSON('Alice Example'));+ await engine.putPage('alice', { type: 'person', title: 'alice', compiled_truth: `# alice\n\n${FENCE('| 1 | Founded Acme | fact | 1.0 | world | high | 2017-01-01 | | chat | |')}`.trim(),+ timeline: '', frontmatter: {} }, { sourceId });+ const phantom = (await engine.readPageSnapshot('alice', { sourceId }))!;+ writeFileSync(join(root, 'alice.md'), serializePageToMarkdown(phantom.page, phantom.tags));+ await runExtractFacts(engine, { sourceId, slugs: ['alice'] });+ }, async ({ engine, sourceId, root, put }) => {+ // A coordinated edit to the phantom lands right after the merge commits,+ // before the redirect rereads the phantom to delete it.+ const read = engine.readPageSnapshot;+ let edited = false;+ engine.readPageSnapshot = (async function (this: BrainEngine, slug: string, opts?: Parameters<BrainEngine['readPageSnapshot']>[1]) {+ // Transactions inherit this method; only the redirect's own read on the engine triggers the edit.+ if (this === engine && slug === 'alice' && !edited && new Error().stack?.includes('redirectManagedPhantom') && (await engine.executeRaw(+ "SELECT 1 FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_maintenance_phantom_merge' AND state='committed'", [sourceId])).length) {+ edited = true;+ await put('alice', `---\ntitle: alice\ntype: person\n---\n# alice\n\n${FENCE([+ '| 1 | Founded Acme | fact | 1.0 | world | high | 2017-01-01 | | chat | |',+ '| 2 | Moved to Lisbon | fact | 1.0 | world | high | 2020-01-01 | | chat | |'].join('\n'))}`);+ }+ return read.call(this, slug, opts);+ }) as BrainEngine['readPageSnapshot'];+ let result: Awaited<ReturnType<typeof runExtractFacts>>;+ try { result = await runExtractFacts(engine, { sourceId, brainDir: root }); }+ finally { delete (engine as { readPageSnapshot?: unknown }).readPageSnapshot; }+ expect(edited).toBe(true);+ const alive = await engine.readPageSnapshot('alice', { sourceId, includeDeleted: true });+ expect(alive?.page.deleted_at ?? null).toBeNull();+ expect([result.phantomsRedirected, result.phantomsSkippedDrift]).toEqual([0, 1]);+ expect(alive?.page.compiled_truth).toContain('Moved to Lisbon');+ expect(readFileSync(join(root, 'alice.md'), 'utf8')).toContain('Moved to Lisbon');+ expect(await committed(engine, sourceId, 'alice').then(rows => rows.filter(r => r.kind === 'managed_maintenance_phantom_delete'))).toEqual([]);+ });+}, 120_000);++const localCtx = (engine: BrainEngine, sourceId: string) => ({ engine, sourceId, remote: false as const,+ config: { engine: engine.kind, embedding_disabled: true }, dryRun: false, logger: { info() {}, warn() {}, error() {} } });++test('managed conversation extraction publishes nothing for a page purged while the model runs', async () => {+ await managed(async ({ put }) => { await put('conversations/synthetic-chat', CONVERSATION); }, async ({ engine, sourceId }) => {+ const purging = async () => {+ const page = (await engine.readPageSnapshot('conversations/synthetic-chat', { sourceId }))!;+ await submitPageMutation(localCtx(engine, sourceId), { operation: 'delete_page', params: { slug: 'conversations/synthetic-chat',+ purge: true, expected_revision: page.revision, request_id: randomUUID() } });+ return extractor();+ };+ const result = await runExtractConversationFactsCore(engine, { sourceId, overrideDisabled: true, extractor: purging, types: ['conversation'] });+ expect(await engine.readPageSnapshot('conversations/synthetic-chat', { sourceId, includeDeleted: true })).toBeNull();+ expect(await facts(engine, sourceId, 'conversations/synthetic-chat')).toEqual([]);+ expect(result.pages_failed).toBe(1);+ });+}, 120_000);++test('managed conversation extraction publishes nothing into a source archived while the model runs', async () => {+ await managed(async ({ put }) => { await put('conversations/synthetic-chat', CONVERSATION); }, async ({ engine, sourceId }) => {+ const archiving = async () => {+ await engine.transaction(async tx => {+ await tx.executeRaw("SELECT set_config('gbrain.topology_change','on',true)");+ await tx.executeRaw('UPDATE sources SET archived=true WHERE id=$1', [sourceId]);+ });+ return extractor();+ };+ try {+ const result = await runExtractConversationFactsCore(engine, { sourceId, overrideDisabled: true, extractor: archiving, types: ['conversation'] });+ expect(await facts(engine, sourceId, 'conversations/synthetic-chat')).toEqual([]);+ expect(result.pages_failed).toBe(1);+ } finally {+ await engine.transaction(async tx => {+ await tx.executeRaw("SELECT set_config('gbrain.topology_change','on',true)");+ await tx.executeRaw('UPDATE sources SET archived=false WHERE id=$1', [sourceId]);+ });+ }+ });+}, 120_000);++test('a Facts fence published on an extracted conversation takes its row numbers from colliding conversation rows', async () => {+ await managed(async ({ put }) => { await put('conversations/synthetic-chat', CONVERSATION); }, async ({ engine, sourceId, put }) => {+ await runExtractConversationFactsCore(engine, { sourceId, overrideDisabled: true, extractor, types: ['conversation'] });+ await put('conversations/synthetic-chat', `${CONVERSATION}\n${FENCE('| 1 | Acme hired a platform team | fact | 1.0 | world | high | 2024-03-15 | | chat | |')}`);+ const rows = await facts(engine, sourceId, 'conversations/synthetic-chat');+ expect(rows.filter(f => f.expired_at === null).map(f => [f.fact, f.row_num, f.source])).toEqual([+ ['Alice Example joined Acme Corp as a staff engineer.', 0, 'cli:extract-conversation-facts'],+ ['Acme hired a platform team', 1, 'chat']]);+ expect(rows.find(f => f.fact === 'EXTRACTION_COMPLETE')).toMatchObject({ row_num: null, source: 'cli:extract-conversation-facts:terminal:v2' });+ });+}, 120_000);++test('managed phantom delete moves an edge added to the phantom after its merge', async () => {+ await managed(async ({ engine, sourceId, root, put }) => {+ await put('people/alice-example', PERSON('Alice Example'));+ await put('meetings/offsite', '---\ntitle: Offsite\ntype: meeting\n---\nA planning meeting.');+ await engine.putPage('alice', { type: 'person', title: 'alice', compiled_truth: `# alice\n\n${FENCE('| 1 | Founded Acme | fact | 1.0 | world | high | 2017-01-01 | | chat | |')}`.trim(),+ timeline: '', frontmatter: {} }, { sourceId });+ const phantom = (await engine.readPageSnapshot('alice', { sourceId }))!;+ writeFileSync(join(root, 'alice.md'), serializePageToMarkdown(phantom.page, phantom.tags));+ await runExtractFacts(engine, { sourceId, slugs: ['alice'] });+ }, async ({ engine, sourceId, root }) => {+ const read = engine.readPageSnapshot;+ let linked = false;+ engine.readPageSnapshot = (async function (this: BrainEngine, slug: string, opts?: Parameters<BrainEngine['readPageSnapshot']>[1]) {+ if (this === engine && slug === 'alice' && !linked && new Error().stack?.includes('redirectManagedPhantom') && (await engine.executeRaw(+ "SELECT 1 FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_maintenance_phantom_merge' AND state='committed'", [sourceId])).length) {+ linked = true;+ await engine.addLink('meetings/offsite', 'alice', 'met', 'mentions', 'manual', undefined, undefined, { fromSourceId: sourceId, toSourceId: sourceId });+ }+ return read.call(this, slug, opts);+ }) as BrainEngine['readPageSnapshot'];+ let result: Awaited<ReturnType<typeof runExtractFacts>>;+ try { result = await runExtractFacts(engine, { sourceId, brainDir: root }); }+ finally { delete (engine as { readPageSnapshot?: unknown }).readPageSnapshot; }+ expect(linked).toBe(true);+ expect(result.phantomsRedirected).toBe(1);+ const edges = await engine.executeRaw<{ slug: string }>(`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.source_id=$1 AND f.slug='meetings/offsite'`, [sourceId]);+ expect(edges.map(e => e.slug)).toEqual(['people/alice-example']);+ });+}, 120_000);++test('managed deleted-page expiry waits for a concurrent restore of that page (Postgres)', async () => {+ await managed(async ({ put }) => {+ await put('people/bob-demo', PERSON('Bob Demo', FENCE('| 1 | Plays chess | fact | 1.0 | world | low | 2019-01-01 | | chat | |')));+ }, async ({ engine, sourceId }) => {+ if (engine.kind !== 'postgres') return;+ await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => tx.softDeletePage('people/bob-demo', { sourceId })));+ let release!: () => void;+ const gate = new Promise<void>(resolve => { release = resolve; });+ let locked!: () => void;+ const holding = new Promise<void>(resolve => { locked = resolve; });+ const restore = engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], async () => {+ await tx.lockPageKeys([{ sourceId, slug: 'people/bob-demo' }]);+ await tx.executeRaw('UPDATE pages SET deleted_at=NULL WHERE source_id=$1 AND slug=$2', [sourceId, 'people/bob-demo']);+ locked();+ await gate;+ }));+ await holding;+ const run = runExtractFacts(engine, { sourceId, slugs: [] });+ await new Promise(resolve => setTimeout(resolve, 500));+ release();+ await restore;+ expect((await run).factsExpiredForDeletedPages).toBe(0);+ expect((await facts(engine, sourceId, 'people/bob-demo'))[0].expired_at).toBeNull();+ });+}, 120_000);++test('managed writeSingleFact reports the entity it persisted for an unresolved reference', async () => {+ await managed(async () => {}, async ({ engine, sourceId }) => {+ const written = await writeSingleFact(engine, sourceId, { fact: 'Carol Unknown owns a sailboat.', provenance: 'fixture', entity: 'Carol Unknown' });+ const [row] = await engine.executeRaw<{ entity_slug: string | null }>('SELECT entity_slug FROM facts WHERE id=$1', [written.id]);+ expect(written.entity_slug).toBe(row.entity_slug);+ });+}, 120_000);++test('managed extract-conversation-facts CLI extracts instead of refusing', async () => {+ await managed(async ({ put }) => { await put('conversations/synthetic-chat', CONVERSATION); }, async ({ engine, sourceId }) => {+ chatReply = JSON.stringify({ facts: [{ fact: 'Alice Example joined Acme Corp.', kind: 'event', entity: null, confidence: 1, notability: 'high' }] });+ await runExtractConversationFacts(engine, ['--source-id', sourceId, '--slug', 'conversations/synthetic-chat', '--override-disabled']);+ expect((await facts(engine, sourceId, 'conversations/synthetic-chat')).map(f => f.fact)).toEqual(['Alice Example joined Acme Corp.', 'EXTRACTION_COMPLETE']);+ });+}, 120_000);++test('managed conversation_facts_backfill phase extracts instead of refusing', async () => {+ await managed(async ({ engine, put }) => {+ await engine.setConfig('cycle.conversation_facts_backfill.enabled', 'true');+ await put('conversations/synthetic-chat', CONVERSATION);+ }, async ({ engine, sourceId }) => {+ chatReply = JSON.stringify({ facts: [{ fact: 'Alice Example joined Acme Corp.', kind: 'event', entity: null, confidence: 1, notability: 'high' }] });+ const phase = await runPhaseConversationFactsBackfill(engine);+ expect(phase.status).toBe('ok');+ expect((phase.details.per_source as Record<string, { facts_inserted: number }>)[sourceId].facts_inserted).toBe(1);+ expect((await facts(engine, sourceId, 'conversations/synthetic-chat')).map(f => f.fact)).toEqual(['Alice Example joined Acme Corp.', 'EXTRACTION_COMPLETE']);+ });+}, 120_000);diff --git a/test/managed-phase-matrix.test.ts b/test/managed-phase-matrix.test.tsnew file mode 100644index 0000000000..c276d255d0--- /dev/null+++ b/test/managed-phase-matrix.test.ts@@ -0,0 +1,421 @@+/**+ * Managed-brain phase matrix (fix wave 3, CEO "Managed-brain phase matrix+ * test" / Eng E-D15). One fixture per cycle phase per engine: each runs that+ * single phase through runCycle on a managed brain (filesystem source with an+ * active local canonical owner, persistence enabled) with stub chat and+ * embedding providers and a seeded input for the phase to act on.+ *+ * - writes: the phase must commit a coordinated mutation with its intended result.+ * - no_coordinated_write: the phase must not fail or be refused by the coordinator.+ * - managed_skip: the phase result must carry the table's reason.+ *+ * Authoring gate: protects "every maintenance phase runs on a managed brain";+ * a writer that bypasses the coordinator (writer_coordinator_required,+ * owner_unavailable, a contained phase failure) or a phase that silently stops+ * writing fails its fixture, and a new phase fails until it is classified.+ * Per-writer tests cover individual writers, not every phase through runCycle.+ * No production seam: the stubs are the gateway's existing test transports.+ */+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 type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { ALL_PHASES, runCycle, type CycleOpts, type CyclePhase, type PhaseResult } from '../src/core/cycle.ts';+import { MANAGED_PHASE_TABLE } from '../src/core/cycle/phase-table.ts';+import { runPhaseGradeTakes } from '../src/core/cycle/grade-takes.ts';+import { LINK_EXTRACTOR_VERSION_TS } from '../src/core/link-extraction.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import type { ChatOpts, ChatResult } from '../src/core/ai/gateway.ts';+import { configureGateway, resetGateway, __setChatTransportForTests, __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 engines: BrainEngine[] = [];+const dataDir = mkdtempSync(join(tmpdir(), 'gbrain-phase-matrix-db-'));+const timings: string[] = [];+const matrixStart = Date.now();+let since = 0;+let closePostgres: (() => Promise<void>) | undefined;+const KEYS = { ANTHROPIC_API_KEY: 'sk-test-phase-matrix', OPENAI_API_KEY: 'sk-test-phase-matrix' };++beforeAll(async () => {+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: KEYS });+ __setEmbedTransportForTests(async ({ values }: { values: string[] }) =>+ ({ embeddings: values.map(() => [1, ...Array(1535).fill(0)]), usage: { tokens: values.length } }) as never);+ if (backends.includes('pglite')) {+ const engine = new PGLiteEngine();+ await engine.connect({ database_path: dataDir }); 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); await engine.disconnect(); }+ await closePostgres?.(); __setEmbedTransportForTests(null); __setChatTransportForTests(null); resetGateway();+ rmSync(dataDir, { recursive: true, force: true });+ console.log(`[phase-matrix] ${backends.join('+')} timings (ms):\n${timings.join('\n')}\n[phase-matrix] total ${Date.now() - matrixStart} ms`);+ expect(Date.now() - matrixStart).toBeLessThan(300_000);+});++interface Ctx { engine: BrainEngine; sourceId: string; root: string; result: PhaseResult; calls: ChatOpts[]; logs: string }+interface Entry {+ seed?: (c: Pick<Ctx, 'engine' | 'sourceId' | 'root'>) => Promise<unknown>;+ config?: Record<string, string>;+ env?: Record<string, string>;+ cycle?: Partial<CycleOpts>;+ reply?: (opts: ChatOpts, call: number) => string | Partial<ChatResult>;+ assert?: (c: Ctx) => Promise<void>;+}++const logger = { info() {}, warn() {}, error() {} };+const put = (engine: BrainEngine, sourceId: string, slug: string, content: string) =>+ submitPageMutation({ engine, sourceId, remote: false, config: { engine: engine.kind, embedding_disabled: true } as never, dryRun: false, logger },+ { operation: 'put_page', params: { slug, content, request_id: randomUUID() } });+const page = (type: string, title: string, body: string, extra = '') => `---\ntitle: ${title}\ntype: ${type}\n${extra}---\n${body}`;+const takesFence = (rows: string[]) => ['<!--- gbrain:takes:begin -->', '| # | claim | kind | who | weight | since | source |',+ '|---|-------|------|-----|--------|-------|--------|', ...rows, '<!--- gbrain:takes:end -->'].join('\n');+const daysAgo = (n: number) => new Date(Date.now() - n * 86_400_000).toISOString().slice(0, 10);+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });+const reply = (text: string, model = 'anthropic:claude-sonnet-4-6'): ChatResult => ({ text, blocks: [{ type: 'text', text }], stopReason: 'end',+ usage: { input_tokens: 10, output_tokens: 10, cache_read_tokens: 0, cache_creation_tokens: 0 }, model, providerId: 'anthropic' });++async function committed(engine: BrainEngine, sourceId: string, slug: string) {+ return engine.executeRaw<{ operation: string; intent: Record<string, unknown> | null; outcome: Record<string, unknown> | null }>(+ `SELECT operation,intent,outcome FROM persistence_requests WHERE source_id=$1 AND slug=$2 AND state='committed' AND sequence>$3 ORDER BY sequence`,+ [sourceId, slug, since]);+}+async function seedFacts(engine: BrainEngine, sourceId: string, slug: string) {+ const vector = `[${[1, ...Array(1535).fill(0)].join(',')}]`;+ for (let i = 0; i < 3; i++) {+ await engine.executeRaw(`INSERT INTO facts(source_id,entity_slug,fact,kind,source,visibility,confidence,valid_from,embedding,embedding_model,embedded_text_hash)+ VALUES($1,$2,$3,'fact','test','world',$4,$5::timestamptz,$6::vector,'openai:text-embedding-3-large',md5($3))`,+ [sourceId, slug, `Example claim ${i}`, 0.9 - i / 10, `2026-01-0${i + 1}T00:00:00Z`, vector]);+ }+}++const MATRIX: Record<CyclePhase, Entry> = {+ lint: {+ seed: async ({ engine, sourceId }) => put(engine, sourceId, 'notes/lint-example', page('note', 'Lint example', 'Body with a trailing space. \n\n\n\nToo many blank lines.')),+ },+ backlinks: {+ seed: async ({ engine, sourceId }) => {+ await put(engine, sourceId, 'people/alice-example', page('person', 'Alice', 'A person.'));+ await put(engine, sourceId, 'companies/acme-example', page('company', 'Acme', 'Hired [[people/alice-example]].'));+ },+ },+ sync: {+ seed: async ({ root }) => {+ git(root, 'init', '-q');+ mkdirSync(join(root, 'notes'));+ writeFileSync(join(root, 'notes/sync-example.md'), page('note', 'Sync example', 'A synced observation.\n'));+ git(root, 'add', '.');+ git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'seed');+ },+ assert: async ({ engine, sourceId }) => {+ expect(await committed(engine, sourceId, 'notes/sync-example')).not.toHaveLength(0);+ expect((await engine.getPage('notes/sync-example', { sourceId }))?.compiled_truth).toContain('A synced observation.');+ },+ },+ synthesize: {+ seed: async ({ engine, sourceId, root }) => {+ await put(engine, sourceId, 'people/example', page('note', 'Example', 'Example evidence.'));+ writeFileSync(join(root, '2026-09-20-session.txt'), `User: we charge for durability because reliable memories should survive every tool.\n${'Assistant: Discuss the long term roadmap.\n'.repeat(15)}`);+ },+ config: { 'dream.synthesize.enabled': 'true', 'dream.synthesize.cooldown_hours': '0', 'dream.synthesize.min_chars': '100',+ 'dream.synthesize.link_manifest': 'false', 'dream.synthesize.mode': 'oneshot', 'models.dream.synthesize': 'anthropic:claude-sonnet-4-6',+ 'models.dream.triage': 'anthropic:claude-sonnet-4-6', 'dream.synthesize.session_corpus_dir': '{root}' },+ cycle: { synthDate: '2026-09-20' },+ reply: (opts) => {+ const user = String(opts.messages?.[0]?.content ?? '');+ const hash = /hash suffix \(USE THIS in slugs\): ([a-z0-9-]+)/i.exec(user)?.[1] ?? 'missing';+ return (opts.system ?? '').startsWith('You triage a conversation transcript')+ ? JSON.stringify({ score: 0.9, content_type: 'reflection', segments: [{ quote: 'we charge for durability because reliable memories should survive every tool', note: 'evidence' }], entities: [], reasons: ['durable insight'] })+ : JSON.stringify({ pages: [{ slug: `wiki/personal/reflections/session-${hash}`, title: 'Session', type: 'note', body: 'A memory strategy with [[people/example]].' }], skipped: false });+ },+ assert: async ({ engine, sourceId, result }) => {+ expect(result.details.pages_written).toBe(1);+ const slug = (result.details.written_slugs as string[])[0];+ expect(await committed(engine, sourceId, slug)).not.toHaveLength(0);+ expect((await engine.getPage(slug, { sourceId }))?.compiled_truth).toContain('A memory strategy');+ },+ },+ extract: {+ config: { auto_link: 'false' },+ seed: async ({ engine, sourceId }) => {+ await put(engine, sourceId, 'companies/acme-example', page('company', 'Acme', 'A company.'));+ await put(engine, sourceId, 'people/alice-example', page('person', 'Alice', 'Works with [[companies/acme-example]].\n\n## Timeline\n\n- **2026-01-02** | test — Met Acme'));+ await engine.executeRaw("DELETE FROM timeline_entries WHERE page_id=(SELECT id FROM pages WHERE source_id=$1 AND slug='people/alice-example')", [sourceId]);+ },+ assert: async ({ engine, sourceId }) => {+ expect((await engine.getLinks('people/alice-example', { sourceId })).map(l => l.to_slug)).toContain('companies/acme-example');+ expect(await engine.executeRaw(`SELECT t.summary FROM timeline_entries t JOIN pages p ON p.id=t.page_id+ WHERE p.source_id=$1 AND p.slug='people/alice-example'`, [sourceId])).toEqual([{ summary: 'Met Acme' }]);+ expect(await engine.countStalePagesForExtraction({ sourceId, versionTs: LINK_EXTRACTOR_VERSION_TS })).toBe(0);+ },+ },+ extract_facts: {+ seed: async ({ engine, sourceId }) => {+ await engine.executeRaw(`INSERT INTO pages (slug, source_id, title, type, page_kind, compiled_truth, timeline, frontmatter)+ VALUES ('people/bob-example', $1, 'Bob', 'person', 'markdown', $2, '', '{}'::jsonb)`, [sourceId,+ '# Bob\n\nBody.\n\n## Facts\n\n<!--- gbrain:facts:begin -->\n'+ + '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |\n'+ + '|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|\n'+ + '| 1 | Founded Acme | fact | 1.0 | world | high | 2017-01-01 | | linkedin | |\n<!--- gbrain:facts:end -->\n']);+ },+ assert: async ({ engine, sourceId }) => {+ expect(await engine.executeRaw("SELECT fact FROM facts WHERE source_id=$1 AND entity_slug='people/bob-example'", [sourceId]))+ .toEqual([{ fact: 'Founded Acme' }]);+ },+ },+ extract_atoms: {+ env: { GBRAIN_SCHEMA_PACK: 'gbrain-creator' },+ seed: async ({ engine, sourceId }) => put(engine, sourceId, 'notes/atom-source', page('note', 'Atom source', 'A project record about measured progress. '.repeat(40))),+ reply: () => '[{"title":"Measured progress","atom_type":"insight","body":"Measure progress against clear exit criteria."}]',+ assert: async ({ engine, sourceId }) => {+ const atoms = await engine.executeRaw<{ slug: string; compiled_truth: string }>("SELECT slug,compiled_truth FROM pages WHERE source_id=$1 AND type='atom'", [sourceId]);+ expect(atoms).toHaveLength(1);+ expect(atoms[0].compiled_truth).toContain('Measure progress against clear exit criteria.');+ expect(await committed(engine, sourceId, atoms[0].slug)).not.toHaveLength(0);+ },+ },+ resolve_symbol_edges: {},+ patterns: {+ seed: async ({ engine, sourceId }) => {+ for (let i = 0; i < 3; i++) await put(engine, sourceId, `wiki/personal/reflections/example-${i}`, page('note', `Reflection ${i}`, `Example evidence ${i}.`));+ },+ config: { 'dream.patterns.enabled': 'true', 'models.dream.patterns': 'anthropic:claude-sonnet-4-6', 'agent.use_gateway_loop': 'true' },+ cycle: { onceForPhase: 'patterns' },+ reply: (opts, call) => call === 1+ ? { text: '', stopReason: 'tool_calls', blocks: [{ type: 'tool-call', toolCallId: 'pattern-write', toolName: 'brain_put_page', input: {+ slug: 'wiki/personal/patterns/example', content: page('note', 'Example pattern', 'A recurring theme in [[wiki/personal/reflections/example-0]].') } }] }+ : 'Saved the pattern.',+ assert: async ({ engine, sourceId, result }) => {+ expect(result.details.patterns_written).toBe(1);+ expect(await committed(engine, sourceId, 'wiki/personal/patterns/example')).not.toHaveLength(0);+ expect((await engine.getPage('wiki/personal/patterns/example', { sourceId }))?.compiled_truth).toContain('A recurring theme');+ },+ },+ synthesize_concepts: {+ env: { GBRAIN_SCHEMA_PACK: 'gbrain-creator' },+ seed: async ({ engine, sourceId }) => {+ for (const n of [1, 2]) await put(engine, sourceId, `atoms/idea-${n}`, page('atom', `Idea ${n}`, `Atom ${n} about network effects.`, 'visibility: world\nconcepts: [network-effects]\n'));+ },+ assert: async ({ engine, sourceId }) => {+ expect((await committed(engine, sourceId, 'concepts/network-effects')).map(r => r.intent?.kind)).toEqual(['managed_maintenance_page', 'managed_maintenance_page']);+ expect((await engine.getPage('concepts/network-effects', { sourceId }))?.frontmatter?.visibility).toBe('world');+ },+ },+ recompute_emotional_weight: {+ seed: async ({ engine, sourceId }) => put(engine, sourceId, 'people/weight-example', page('person', 'Weight', 'A person.', 'tags: [family]\n')),+ },+ consolidate: {+ seed: async ({ engine, sourceId }) => {+ await put(engine, sourceId, 'people/example', page('note', 'Example', 'Example evidence.'));+ await seedFacts(engine, sourceId, 'people/example');+ },+ assert: async ({ engine, sourceId, result }) => {+ expect(result.details.takes_written).toBe(1);+ expect(await committed(engine, sourceId, 'people/example')).not.toHaveLength(0);+ expect((await engine.getPage('people/example', { sourceId }))?.compiled_truth).toContain('Example claim 0');+ },+ },+ propose_takes: {+ config: { 'cycle.propose_takes.enabled': 'true' },+ seed: async ({ engine, sourceId }) => put(engine, sourceId, 'notes/propose-example', page('note', 'Propose', 'I bet the example market compresses within 18 months.')),+ reply: () => JSON.stringify([{ claim_text: 'The example market compresses within 18 months', kind: 'bet', holder: 'brain', weight: 0.7, domain: 'macro' }]),+ assert: async ({ engine, sourceId }) => {+ expect(await engine.executeRaw('SELECT id FROM take_proposals WHERE source_id=$1', [sourceId])).toHaveLength(1);+ },+ },+ grade_takes: {+ seed: async ({ engine, sourceId }) => put(engine, sourceId, 'notes/grade-example', page('note', 'Grade', `Draft.\n\n${takesFence(['| 1 | Acme will ship widgets | take | brain | 0.6 | 2025-01 | notes |'])}`)),+ reply: () => JSON.stringify({ verdict: 'correct', confidence: 0.99, reasoning: 'Acme shipped widgets.' }),+ assert: async ({ engine, sourceId, calls }) => {+ expect(calls.length).toBeGreaterThan(0);+ expect(await engine.executeRaw("SELECT verdict FROM take_grade_cache WHERE verdict='correct'")).toHaveLength(1);+ const applied = await runPhaseGradeTakes({ engine, sourceId, remote: false, config: {} as never, dryRun: false, logger } as never,+ { autoResolve: true, promptVersion: 'phase-matrix-apply' });+ expect(applied.details.auto_applied).toBe(1);+ expect((await committed(engine, sourceId, 'notes/grade-example')).at(-1)?.operation).toBe('takes_resolve');+ },+ },+ calibration_profile: {+ seed: async ({ engine, sourceId }) => {+ await put(engine, sourceId, 'notes/calibration-example', page('note', 'Calibration',+ `Draft.\n\n${takesFence([1, 2, 3, 4, 5].map(n => `| ${n} | Widget line ${n} ships | take | self | 0.7 | 2025-01 | notes |`))}`));+ await engine.executeRaw(`UPDATE takes SET resolved_at=now(), resolved_outcome=true, resolved_quality='correct', resolved_by='test'+ WHERE page_id=(SELECT id FROM pages WHERE source_id=$1 AND slug='notes/calibration-example')`, [sourceId]);+ },+ reply: () => JSON.stringify(['You were right about widget launches in 5 of 5 calls.']),+ assert: async ({ result }) => { expect(result.details.total_resolved).toBe(5); },+ },+ drift: {+ config: { 'dream.drift.enabled': 'true' },+ seed: async ({ engine, sourceId }) => put(engine, sourceId, 'notes/drift-example', page('note', 'Drift',+ `Draft.\n\n${takesFence(['| 1 | Acme will ship widgets | take | brain | 0.6 | 2025-01 | notes |'])}\n\n## Timeline\n\n- **${daysAgo(2)}** | test — Acme cancelled the widget line`)),+ reply: () => JSON.stringify({ drifted: true, confidence: 0.9, reasoning: 'Acme cancelled the widget line.' }),+ assert: async ({ engine, result }) => {+ const slug = String(result.summary).match(/reports\/drift-[0-9-]+/)?.[0];+ expect(slug).toBeDefined();+ expect(await committed(engine, 'default', slug!)).not.toHaveLength(0);+ expect((await engine.getPage(slug!, { sourceId: 'default' }))?.compiled_truth).toContain('DRIFTED — notes/drift-example');+ },+ },+ conversation_facts_backfill: {+ config: { 'cycle.conversation_facts_backfill.enabled': 'true' },+ seed: async ({ engine, sourceId }) => put(engine, sourceId, 'conversations/2026-09-20-example', page('conversation', 'Chat',+ '**Alice** (09:00): I moved to Lisbon last month.\n\n**Bob** (09:01): Congrats on the move.')),+ reply: () => JSON.stringify({ facts: [{ fact: 'Alice moved to Lisbon', kind: 'event', entity: 'people/alice-example', confidence: 0.9, notability: 'medium' }] }),+ assert: async ({ engine, sourceId }) => {+ expect(await engine.executeRaw("SELECT fact FROM facts WHERE source_id=$1 AND fact LIKE '%Lisbon%'", [sourceId])).not.toHaveLength(0);+ },+ },+ enrich_thin: {+ config: { 'cycle.enrich_thin.enabled': 'true', 'cycle.enrich_thin.types': '["person"]' },+ seed: async ({ engine, sourceId }) => {+ await put(engine, sourceId, 'people/alice-example', page('person', 'Alice Example', 'Stub page.'));+ await put(engine, sourceId, 'meetings/m1', page('note', 'M1', 'Notes about [[people/alice-example]].'));+ for (const fact of ['Alice founded WidgetCo and leads its design system.', 'Alice previously ran platform engineering at Acme Example for six years.',+ 'Alice mentors early-stage founders on hiring their first designers.', 'Alice is based in Lisbon and speaks at design conferences.']) {+ await engine.executeRaw(`INSERT INTO facts (source_id, entity_slug, fact, source, valid_from, visibility)+ VALUES ($1, 'people/alice-example', $2, 'test', now(), 'world')`, [sourceId, fact]);+ }+ },+ reply: () => '## Overview\nAlice founded WidgetCo. [Source: meetings/m1]',+ assert: async ({ engine, sourceId }) => {+ expect((await committed(engine, sourceId, 'people/alice-example')).at(-1)?.intent?.kind).toBe('managed_maintenance_page');+ expect((await engine.getPage('people/alice-example', { sourceId }))?.compiled_truth).toContain('Alice founded WidgetCo.');+ },+ },+ skillopt: {+ config: { 'cycle.skillopt.enabled': 'true', 'cycle.skillopt.per_skill_cap_usd': '10', 'cycle.skillopt.brain_wide_cap_usd': '10' },+ env: { GBRAIN_SKILLS_DIR: '{root}/../skills' },+ reply: () => '{"edits": []}',+ assert: async ({ result }) => { expect(result.details.no_improvement).toBe(1); },+ seed: async ({ root }) => {+ const skill = join(root, '..', 'skills', 'example-skill');+ mkdirSync(skill, { recursive: true });+ writeFileSync(join(root, '..', 'skills', 'RESOLVER.md'), '# Resolver\n\n- example-skill: skills/example-skill/SKILL.md\n');+ writeFileSync(join(skill, 'SKILL.md'), '---\nname: example-skill\ndescription: Answer example questions.\ntriggers: [example]\n---\nAnswer briefly.\n');+ writeFileSync(join(skill, 'skillopt-benchmark.jsonl'), Array.from({ length: 50 }, (_, i) => JSON.stringify({ task_id: `q${i}`, task: `Answer question ${i} briefly.`, judge: { kind: 'rule', checks: [{ op: 'max_chars', arg: 4000 }] } })).join('\n') + '\n');+ },+ },+ embed: {+ seed: async ({ engine, sourceId }) => put(engine, sourceId, 'notes/embed-example', page('note', 'Embed', 'A page whose chunks need vectors.')),+ },+ orphans: {+ seed: async ({ engine, sourceId }) => put(engine, sourceId, 'notes/orphan-example', page('note', 'Orphan', 'Nobody links here.')),+ },+ 'schema-suggest': {+ seed: async ({ engine, sourceId }) => put(engine, sourceId, 'notes/schema-example', page('note', 'Schema', 'A plain note.')),+ },+ purge: {+ seed: async ({ engine, sourceId }) => {+ await put(engine, sourceId, 'notes/expired', page('note', 'Expired', 'Gone soon.'));+ const snapshot = await engine.readPageSnapshot('notes/expired', { sourceId });+ await submitPageMutation({ engine, sourceId, remote: false, config: { engine: engine.kind, embedding_disabled: true } as never, dryRun: false, logger },+ { operation: 'delete_page', params: { slug: 'notes/expired', expected_revision: snapshot!.revision, request_id: randomUUID() } });+ await engine.executeRaw("UPDATE pages SET deleted_at=now() - interval '100 hours' WHERE source_id=$1 AND slug='notes/expired'", [sourceId]);+ },+ assert: async ({ engine, sourceId, result }) => {+ expect(result.details.purged_pages_count).toBe(1);+ expect(await engine.readPageSnapshot('notes/expired', { sourceId, includeDeleted: true })).toBeNull();+ expect((await committed(engine, sourceId, 'notes/expired')).at(-1)?.outcome?.status).toBe('purged');+ },+ },+};++test('every cycle phase is classified for managed brains, with no extra keys', () => {+ expect(Object.keys(MANAGED_PHASE_TABLE).sort()).toEqual([...ALL_PHASES].sort());+ expect(Object.keys(MATRIX).sort()).toEqual([...ALL_PHASES].sort());+ for (const entry of Object.values(MANAGED_PHASE_TABLE)) expect(entry.reason.length).toBeGreaterThan(0);+});++const REFUSALS = ['writer_coordinator_required', 'owner_unavailable'];++/** Seeds one managed brain for `phase`, runs only that phase through runCycle, and hands the result (plus anything logged to stderr) to `check`. */+async function runPhase(engine: BrainEngine, phase: CyclePhase, entry: Entry, check: (c: Ctx) => Promise<void>) {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-phase-matrix-'));+ const root = join(dir, 'brain'); mkdirSync(root);+ const sourceId = `matrix-${randomUUID().slice(0, 8)}`;+ const calls: ChatOpts[] = [];+ __setChatTransportForTests(async opts => {+ calls.push(opts);+ const out = entry.reply?.(opts, calls.length) ?? '{}';+ return typeof out === 'string' ? reply(out, opts.model) : { ...reply('', opts.model), ...out };+ });+ const expand = (values: Record<string, string> = {}) => Object.entries(values).map(([k, v]) => [k, v.replace('{root}', root)] as const);+ try {+ await withEnv({ GBRAIN_HOME: join(dir, 'home'), ...KEYS, ...Object.fromEntries(expand(entry.env)) }, async () => {+ 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)', [sourceId, root]);+ await engine.setConfig('sync.write_through', 'true');+ for (const [key, value] of expand(entry.config)) await engine.setConfig(key, value);+ await claimWorktree(engine, sourceId, root);+ await entry.seed?.({ engine, sourceId, root });+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ since = Number((await engine.executeRaw<{ s: string }>('SELECT COALESCE(max(sequence),0)::text AS s FROM persistence_requests'))[0].s);+ const logged: string[] = [];+ const { error, warn } = console;+ const write = process.stderr.write;+ console.error = (...args: unknown[]) => { logged.push(args.map(String).join(' ')); error(...args); };+ console.warn = (...args: unknown[]) => { logged.push(args.map(String).join(' ')); warn(...args); };+ process.stderr.write = ((chunk: string | Uint8Array, ...rest: never[]) => { logged.push(String(chunk)); return write.call(process.stderr, chunk, ...rest); }) as typeof write;+ const started = performance.now();+ let report;+ try { report = await runCycle(engine, { brainDir: root, sourceId, phases: [phase], ...entry.cycle }); }+ finally { console.error = error; console.warn = warn; process.stderr.write = write; }+ const result = report.phases.find(p => p.phase === phase)!;+ const ms = Math.round(performance.now() - started);+ const requests = await engine.executeRaw<{ state: string; operation: string; slug: string; error_code: string | null }>(+ 'SELECT state,operation,slug,error_code FROM persistence_requests WHERE sequence>$1 ORDER BY sequence', [since]);+ timings.push(` ${phase.padEnd(28)} ${String(ms).padStart(6)} ${result.status}, ${requests.length} coordinated request(s): ${result.summary.slice(0, 110)}`);+ expect(requests.filter(r => r.state !== 'committed')).toEqual([]);+ await check({ engine, sourceId, root, result, calls, logs: logged.join('\n') });+ });+ } finally {+ __setChatTransportForTests(null);+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ for (const key of Object.keys(entry.config ?? {})) await engine.executeRaw('DELETE FROM config WHERE key=$1', [key]);+ await engine.executeRaw('DELETE FROM sources WHERE id=$1', [sourceId]);+ await engine.executeRaw("DELETE FROM pages WHERE source_id='default'");+ rmSync(dir, { recursive: true, force: true });+ }+}++for (const phase of ALL_PHASES) {+ for (const backend of backends) {+ const klass = MANAGED_PHASE_TABLE[phase];+ test(`${phase} on a managed ${backend} brain: ${klass?.class ?? 'unclassified'}`, async () => {+ expect(klass).toBeDefined();+ const entry = MATRIX[phase];+ await runPhase(engines[backends.indexOf(backend)], phase, entry, async ctx => {+ const { result } = ctx;+ if (klass.class === 'managed_skip') {+ expect(result.status).toBe('skipped');+ expect(JSON.stringify(result)).toContain(klass.reason);+ return;+ }+ expect({ status: result.status, contained: result.details?.contained === true, error: result.error })+ .toMatchObject({ status: expect.not.stringMatching(/^fail$/), contained: false });+ for (const refusal of REFUSALS) {+ expect(JSON.stringify(result)).not.toContain(refusal);+ expect(ctx.logs).not.toContain(refusal);+ }+ if (klass.class === 'writes') expect(entry.assert).toBeDefined();+ await entry.assert?.(ctx);+ });+ }, 120_000);+ }+}diff --git a/test/managed-unsupported-preflight.serial.test.ts b/test/managed-unsupported-preflight.serial.test.tsindex c4620a228b..88a8d2fb82 100644--- a/test/managed-unsupported-preflight.serial.test.ts+++ b/test/managed-unsupported-preflight.serial.test.ts@@ -21,6 +21,7 @@ const { runExtractConversationFactsCore } = await import('../src/commands/extracconst { runPhaseConversationFactsBackfill } = await import('../src/core/cycle/conversation-facts-backfill.ts');const { runExtractFacts } = await import('../src/core/cycle/extract-facts.ts');const { runPersistenceAdministration } = await import('../src/core/persistence/administration.ts');+const { withSubmissionAuthority } = await import('../src/core/minions/submission-authority.ts');const home = mkdtempSync(join(tmpdir(), 'gbrain-managed-preflight-'));const env = { GBRAIN_HOME: home, GBRAIN_SOURCE: undefined, GBRAIN_BRAIN_ID: 'host' };let engine: InstanceType<typeof PGLiteEngine>;@@ -35,9 +36,14 @@ beforeAll(async () => withEnv(env, async () => {afterAll(async () => { await engine.disconnect(); rmSync(home, { recursive: true, force: true }); });-test('unsupported Google loop writes refuse before chat while unmanaged extraction remains usable', async () => withEnv(env, async () => {+// #5280: these writers publish through the coordinator on a managed brain+// (test/managed-facts-writers.test.ts). What stays pinned here is the order:+// a caller the coordinator cannot accept refuses before any provider work.+const remoteJob = <T>(fn: () => Promise<T>) => withSubmissionAuthority({ version: 1, kind: 'remote_generic' } as never, fn);++test('managed Google loop extraction refuses an unaccepted writer before chat while unmanaged extraction remains usable', async () => withEnv(env, async () => {chatCalls = 0;- await expect(runLoopsExtract(engine, { slug: 'emails/example', sourceId: 'default' })).rejects.toMatchObject({ code: 'writer_coordinator_required' });+ await expect(remoteJob(() => runLoopsExtract(engine, { slug: 'emails/example', sourceId: 'default' }))).rejects.toMatchObject({ code: 'writer_coordinator_required' });expect(chatCalls).toBe(0);await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');try {@@ -46,22 +52,24 @@ test('unsupported Google loop writes refuse before chat while unmanaged extracti} finally { await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1'); }}));-test('unsupported bulk conversation extraction refuses before either preview or execution providers', async () => withEnv(env, async () => {+test('managed bulk conversation extraction and fence reconciliation refuse an unaccepted writer before either preview or execution providers', async () => withEnv(env, async () => {let extractions = 0;for (const dryRun of [false, true]) {- await expect(runExtractConversationFactsCore(engine, {+ await expect(remoteJob(() => runExtractConversationFactsCore(engine, {sourceId: 'default', dryRun, overrideDisabled: true,extractor: async () => { extractions++; return []; },- })).rejects.toMatchObject({ code: 'writer_coordinator_required' });+ }))).rejects.toMatchObject({ code: 'permission_denied' });}expect(extractions).toBe(0);- await expect(runExtractFacts(engine, { sourceId: 'default' })).rejects.toMatchObject({ code: 'writer_coordinator_required' });+ await expect(remoteJob(() => runExtractFacts(engine, { sourceId: 'default' }))).rejects.toMatchObject({ code: 'permission_denied' });expect(await engine.executeRaw('SELECT id FROM facts')).toHaveLength(0);}));-test('bulk phase refuses before provider work but disabled gates retain their skip semantics', async () => withEnv(env, async () => {+test('bulk phase records an unaccepted writer per source before provider work but disabled gates retain their skip semantics', async () => withEnv(env, async () => {chatCalls = 0;- await expect(runPhaseConversationFactsBackfill(engine)).rejects.toMatchObject({ code: 'writer_coordinator_required' });+ const phase = await remoteJob(() => runPhaseConversationFactsBackfill(engine));+ expect(phase.status).toBe('warn');+ expect((phase.details.per_source as Record<string, { error?: string }>).default.error).toMatch(/local writer/);expect(chatCalls).toBe(0);await engine.setConfig('cycle.conversation_facts_backfill.enabled', 'false');await engine.setConfig('loops.extraction_enabled', 'false');@@ -70,11 +78,11 @@ test('bulk phase refuses before provider work but disabled gates retain their skexpect(chatCalls).toBe(0);}));-test('writer status and activation preview name unsupported bulk capabilities without changing them', async () => withEnv(env, async () => {+test('writer status and activation preview report no unsupported bulk capabilities without changing them', async () => withEnv(env, async () => {const before = await engine.executeRaw('SELECT * FROM persistence_brain');const status = await runPersistenceAdministration(engine, 'writer_status', {}) as any;const activation = await runPersistenceAdministration(engine, 'writer_activate', { confirm_quiesced: true, dry_run: true });- expect(status.onboarding.unsupported_maintenance).toEqual(['cycle.extract_facts', 'extract-conversation-facts', 'conversation_facts_backfill', 'loops_extract']);+ expect(status.onboarding.unsupported_maintenance).toEqual([]);expect(activation.unsupported_maintenance).toEqual(status.onboarding.unsupported_maintenance);expect(await engine.executeRaw('SELECT * FROM persistence_brain')).toEqual(before);}));diff --git a/test/managed-writers-w3.test.ts b/test/managed-writers-w3.test.tsnew file mode 100644index 0000000000..e7cd6b4b5d--- /dev/null+++ b/test/managed-writers-w3.test.ts@@ -0,0 +1,396 @@+/**+ * Fix wave 3, Lane B: managed-brain maintenance writers that used to bypass+ * the coordinator (#5484 synthesize_concepts, #5523 chronicle extract, #5405+ * purge, #5280 enrich / add_link / remove_link / bootstrap verify cleanup).+ *+ * Contract: on a managed brain each writer's mutation lands as a COMMITTED+ * coordinated write with its intended result, instead of refusing with+ * `writer_coordinator_required` (or being refused by the managed writer+ * trigger). Runs on PGLite and, with DATABASE_URL, Postgres.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdirSync, mkdtempSync, renameSync, 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/operations.ts';+import { operations } from '../src/core/operations.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { runCycle } from '../src/core/cycle.ts';+import { runPhaseSynthesizeConcepts } from '../src/core/cycle/synthesize-concepts.ts';+import { runChronicleExtract } from '../src/core/chronicle/extract-events.ts';+import { runEnrichCore } from '../src/commands/enrich.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { extractManagedStaleLinks } from '../src/core/persistence/links-maintenance.ts';+import { configureGateway, resetGateway } 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 engines: BrainEngine[] = [];+const dataDir = mkdtempSync(join(tmpdir(), 'gbrain-w3-writers-db-'));+let closePostgres: (() => Promise<void>) | undefined;+beforeAll(async () => {+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} });+ if (backends.includes('pglite')) {+ const engine = new PGLiteEngine();+ await engine.connect({ database_path: dataDir }); 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); await engine.disconnect(); }+ await closePostgres?.(); resetGateway(); rmSync(dataDir, { recursive: true, force: true });+});++const logger = { info() {}, warn() {}, error() {} };+function ctxFor(engine: BrainEngine, sourceId: string): OperationContext {+ return { engine, sourceId, remote: false, config: { engine: engine.kind, embedding_disabled: true } as never, dryRun: false, logger };+}++/** A filesystem source with an active local canonical owner; managed persistence turns on after `seed`. */+async function managedFixture(seed: (engine: BrainEngine, sourceId: string, root: string) => Promise<void>,+ run: (engine: BrainEngine, sourceId: string, root: string) => Promise<void>) {+ for (const engine of engines) {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-w3-writers-'));+ const root = join(dir, 'brain'); mkdirSync(root);+ const sourceId = `w3b-${randomUUID().slice(0, 8)}`;+ try {+ await withEnv({ GBRAIN_HOME: join(dir, 'home') }, async () => {+ 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)', [sourceId, root]);+ await engine.setConfig('sync.write_through', 'true');+ await claimWorktree(engine, sourceId, root);+ await seed(engine, sourceId, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ await run(engine, sourceId, root);+ });+ } finally {+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ rmSync(dir, { recursive: true, force: true });+ }+ }+}++async function committed(engine: BrainEngine, sourceId: string, slug: string) {+ return engine.executeRaw<{ operation: string; intent: Record<string, unknown> | null; outcome: Record<string, unknown> | null }>(+ `SELECT operation,intent,outcome FROM persistence_requests WHERE source_id=$1 AND slug=$2 AND state='committed' ORDER BY sequence`,+ [sourceId, slug]);+}++async function putPage(engine: BrainEngine, sourceId: string, slug: string, content: string) {+ await submitPageMutation(ctxFor(engine, sourceId), { operation: 'put_page', params: { slug, content, request_id: randomUUID() } });+}++test('#5484: synthesize_concepts publishes through the coordinator: private first, provenance, then world', async () => {+ await managedFixture(async (engine, sourceId) => {+ for (const n of [1, 2]) {+ await putPage(engine, sourceId, `atoms/idea-${n}`,+ `---\ntitle: Idea ${n}\ntype: atom\nvisibility: world\nconcepts: [network-effects]\n---\nAtom ${n} about network effects.`);+ }+ }, async (engine, sourceId, root) => {+ const result = await runPhaseSynthesizeConcepts(engine, { sourceId, brainDir: root,+ _chat: async () => { throw new Error('a T3 concept must not call the model'); } });+ expect(result.status).toBe('ok');+ expect(result.details.concepts_written).toBe(1);+ const requests = await committed(engine, sourceId, 'concepts/network-effects');+ expect(requests.map(r => r.intent?.kind)).toEqual(['managed_maintenance_page', 'managed_maintenance_page']);+ expect(String(requests[0].intent?.content)).toContain('visibility: private');+ expect(String(requests[1].intent?.content)).toContain('visibility: world');+ const page = await engine.getPage('concepts/network-effects', { sourceId });+ expect(page?.frontmatter?.visibility).toBe('world');+ expect(page?.frontmatter?.synthesized_by).toBe('synthesize_concepts-v0.41');+ const links = await engine.getLinks('concepts/network-effects', { sourceId });+ expect(links.filter(l => l.link_source === 'concept-provenance').map(l => l.to_slug).sort()).toEqual(['atoms/idea-1', 'atoms/idea-2']);+ });+});++test('#5484: a concept whose provenance cannot land stays private (promotion is gated on provenance)', async () => {+ await managedFixture(async (engine, sourceId) => {+ await putPage(engine, sourceId, 'atoms/idea-1', '---\ntitle: Idea 1\ntype: atom\nconcepts: [moats]\n---\nAtom 1 about moats.');+ }, async (engine, sourceId, root) => {+ const result = await runPhaseSynthesizeConcepts(engine, { sourceId, brainDir: root, _atoms: [+ { slug: 'atoms/idea-1', title: 'Idea 1', body: 'Atom 1 about moats.', concept_refs: ['moats'], visibility: 'world' },+ { slug: 'atoms/missing', title: 'Missing', body: 'Not in this source.', concept_refs: ['moats'], visibility: 'world' },+ ] });+ expect(result.details.concepts_written).toBe(1);+ const requests = await committed(engine, sourceId, 'concepts/moats');+ expect(requests).toHaveLength(1);+ expect(String(requests[0].intent?.content)).toContain('visibility: private');+ expect((await engine.getPage('concepts/moats', { sourceId }))?.frontmatter?.visibility).toBe('private');+ });+});++test('#5484: a concept edited while its narrative is being synthesized is not overwritten (Codex review)', async () => {+ await managedFixture(async (engine, sourceId) => {+ for (const n of [1, 2, 3, 4, 5]) {+ await putPage(engine, sourceId, `atoms/flywheel-${n}`,+ `---\ntitle: Flywheel ${n}\ntype: atom\nvisibility: world\nconcepts: [flywheels]\n---\nAtom ${n} about flywheels.`);+ }+ await putPage(engine, sourceId, 'concepts/flywheels',+ '---\ntitle: flywheels\ntype: concept\nsynthesized_by: synthesize_concepts-v0.41\nsynthesis_mode: llm\nmember_hash: stale\n---\nOld narrative.');+ }, async (engine, sourceId, root) => {+ const result = await runPhaseSynthesizeConcepts(engine, { sourceId, brainDir: root, _chat: (async () => {+ const current = await engine.readPageSnapshot('concepts/flywheels', { sourceId });+ await submitPageMutation(ctxFor(engine, sourceId), { operation: 'put_page', params: { slug: 'concepts/flywheels',+ expected_revision: current!.revision, request_id: randomUUID(), content: '---\ntitle: flywheels\ntype: concept\n---\nA human rewrote this.' } });+ return { text: 'Fresh narrative.', usage: { input_tokens: 1, output_tokens: 1 }, model: 'anthropic:claude-sonnet-4-6' };+ }) as never });+ expect((result.details.publication_deferred as unknown[]).length).toBe(1);+ const page = await engine.getPage('concepts/flywheels', { sourceId });+ expect(page?.compiled_truth).toContain('A human rewrote this.');+ expect(page?.frontmatter?.synthesized_by).toBeUndefined();+ });+});++test('#5523: chronicle extract publishes the event page and its depth timeline row together, and never resurrects a deleted event', async () => {+ await managedFixture(async (engine, sourceId) => {+ await putPage(engine, sourceId, 'meetings/2026-03-02', '---\ntitle: Standup\ntype: meeting\ndate: 2026-03-02\n---\nWe met.');+ }, async (engine, sourceId) => {+ const judge = async () => ({ events: [{ when: '2026-03-02T09:00:00Z', who: ['people/alice-example'], what: 'Morning standup', kind: 'meeting' }] });+ const first = await runChronicleExtract(engine, { slug: 'meetings/2026-03-02', sourceId, judge });+ expect(first).toMatchObject({ status: 'extracted', events_written: 1 });+ const [event] = await engine.executeRaw<{ slug: string }>(+ "SELECT slug FROM pages WHERE source_id=$1 AND slug LIKE 'life/events/%' AND deleted_at IS NULL", [sourceId]);+ expect(event).toBeDefined();+ const requests = await committed(engine, sourceId, event.slug);+ expect(requests).toHaveLength(1);+ expect(requests[0].outcome?.event_projected).toBe(true);+ const timeline = await engine.executeRaw<{ summary: string }>(+ `SELECT t.summary FROM timeline_entries t JOIN pages d ON d.id=t.page_id JOIN pages e ON e.id=t.event_page_id+ WHERE d.source_id=$1 AND d.slug='meetings/2026-03-02' AND e.slug=$2`, [sourceId, event.slug]);+ expect(timeline.map(r => r.summary)).toEqual(['Morning standup']);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.softDeletePage(event.slug, { sourceId });+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ await runChronicleExtract(engine, { slug: 'meetings/2026-03-02', sourceId, judge });+ const after = await engine.readPageSnapshot(event.slug, { sourceId, includeDeleted: true });+ expect(after?.page.deleted_at).toBeTruthy();+ });+});++test('#5405: the purge phase hard-deletes expired tombstones through the coordinator and still runs', async () => {+ await managedFixture(async (engine, sourceId) => {+ await putPage(engine, sourceId, 'notes/expired', '---\ntitle: Expired\ntype: note\n---\nGone soon.');+ const snapshot = await engine.readPageSnapshot('notes/expired', { sourceId });+ await submitPageMutation(ctxFor(engine, sourceId), { operation: 'delete_page', params: {+ slug: 'notes/expired', expected_revision: snapshot!.revision, request_id: randomUUID() } });+ await engine.executeRaw("UPDATE pages SET deleted_at=now() - interval '100 hours' WHERE source_id=$1 AND slug='notes/expired'", [sourceId]);+ }, async (engine, sourceId, root) => {+ const report = await runCycle(engine, { brainDir: root, phases: ['purge'], sourceId });+ const phase = report.phases.find(p => p.phase === 'purge')!;+ expect(phase.status).toBe('ok');+ expect(phase.details.purged_pages_count).toBe(1);+ expect(await engine.readPageSnapshot('notes/expired', { sourceId, includeDeleted: true })).toBeNull();+ const requests = await committed(engine, sourceId, 'notes/expired');+ expect(requests.at(-1)?.outcome?.status).toBe('purged');+ });+});++test('#5405: a tombstone restored and deleted again after the purge scan is not purged (its window restarted)', async () => {+ const { purgeDeletedPagesCoordinated } = await import('../src/core/persistence/purge-deleted.ts');+ await managedFixture(async (engine, sourceId) => {+ await putPage(engine, sourceId, 'notes/cycled', '---\ntitle: Cycled\ntype: note\n---\nBack again.');+ const snapshot = await engine.readPageSnapshot('notes/cycled', { sourceId });+ await submitPageMutation(ctxFor(engine, sourceId), { operation: 'delete_page', params: {+ slug: 'notes/cycled', expected_revision: snapshot!.revision, request_id: randomUUID() } });+ await engine.executeRaw("UPDATE pages SET deleted_at=now() - interval '100 hours' WHERE source_id=$1 AND slug='notes/cycled'", [sourceId]);+ }, async (engine, sourceId) => {+ let cycled = false;+ const racing = Object.create(engine) as BrainEngine;+ racing.readPageSnapshot = async (slug, opts) => {+ if (!cycled && slug === 'notes/cycled') {+ cycled = true;+ const tomb = await engine.readPageSnapshot(slug, { sourceId, includeDeleted: true });+ await submitPageMutation(ctxFor(engine, sourceId), { operation: 'restore_page', params: { slug, expected_revision: tomb!.revision, request_id: randomUUID() } });+ const live = await engine.readPageSnapshot(slug, { sourceId });+ await submitPageMutation(ctxFor(engine, sourceId), { operation: 'delete_page', params: { slug, expected_revision: live!.revision, request_id: randomUUID() } });+ }+ return engine.readPageSnapshot(slug, opts);+ };+ const result = await purgeDeletedPagesCoordinated(racing, 72);+ expect(result).toMatchObject({ count: 0, failed: 0, deferred: 1 });+ expect((await engine.readPageSnapshot('notes/cycled', { sourceId, includeDeleted: true }))?.page.deleted_at).toBeTruthy();+ });+});++test('#5405: the purge job fails when a coordinated purge fails, after reporting what it could not purge', async () => {+ const { registerBuiltinHandlers } = await import('../src/commands/jobs.ts');+ await managedFixture(async (engine, sourceId) => {+ await putPage(engine, sourceId, 'notes/stuck', '---\ntitle: Stuck\ntype: note\n---\nOwned elsewhere.');+ const snapshot = await engine.readPageSnapshot('notes/stuck', { sourceId });+ await submitPageMutation(ctxFor(engine, sourceId), { operation: 'delete_page', params: {+ slug: 'notes/stuck', expected_revision: snapshot!.revision, request_id: randomUUID() } });+ await engine.executeRaw("UPDATE pages SET deleted_at=now() - interval '100 hours' WHERE source_id=$1 AND slug='notes/stuck'", [sourceId]);+ }, async (engine, sourceId) => {+ const handlers = new Map<string, (job: unknown) => Promise<unknown>>();+ await registerBuiltinHandlers({ register(name: string, fn: (job: unknown) => Promise<unknown>) { handlers.set(name, fn); } } as never, engine);+ // Another host owns the canonical worktree now: the purge cannot publish here.+ await withEnv({ GBRAIN_HOME: mkdtempSync(join(tmpdir(), 'gbrain-w3-otherhost-')) }, async () => {+ await expect(handlers.get('purge')!({ id: 1, data: { scope: 'pages' } })).rejects.toThrow(/could not be purged through the coordinator/);+ });+ expect((await engine.readPageSnapshot('notes/stuck', { sourceId, includeDeleted: true }))?.page.deleted_at).toBeTruthy();+ });+});++test('#5280: enrich publishes the enriched page through the coordinator', async () => {+ await managedFixture(async (engine, sourceId) => {+ await putPage(engine, sourceId, 'people/alice-example', '---\ntitle: Alice Example\ntype: person\n---\nStub page.');+ await putPage(engine, sourceId, 'meetings/m1', '---\ntitle: M1\ntype: note\n---\nNotes about [[people/alice-example]].');+ await engine.executeRaw(`INSERT INTO facts (source_id, entity_slug, fact, source, valid_from, visibility)+ VALUES ($1, 'people/alice-example', 'Alice founded WidgetCo and leads its design system.', 'test', now(), 'world')`, [sourceId]);+ }, async (engine, sourceId) => {+ const result = await runEnrichCore(engine, { sourceId, types: ['person'] as never[], order: 'inbound-links' as const, thinThreshold: 400,+ model: 'test:model', workers: 1, minContextChars: 20,+ synthesizeFn: async () => '## Overview\nAlice founded WidgetCo. [Source: meetings/m1]' });+ expect(result.pages_failed).toBe(0);+ expect(result.pages_enriched).toBe(1);+ const requests = await committed(engine, sourceId, 'people/alice-example');+ expect(requests.at(-1)?.intent?.kind).toBe('managed_maintenance_page');+ const page = await engine.getPage('people/alice-example', { sourceId });+ expect(page?.compiled_truth).toContain('Alice founded WidgetCo.');+ expect(page?.frontmatter?.enriched_by).toBeTruthy();+ });+});++test('enrich carries the page facts and takes fences over the model output (Codex review)', async () => {+ const facts = ['<!--- gbrain:facts:begin -->', '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |',+ '|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|',+ '| 1 | Founded WidgetCo | fact | 1.0 | world | high | 2017-01-01 | | linkedin | |', '<!--- gbrain:facts:end -->'].join('\n');+ const takes = ['<!--- gbrain:takes:begin -->', '| # | claim | kind | who | weight | since | source |',+ '|---|-------|------|-----|--------|-------|--------|', '| 1 | Will ship widgets | take | brain | 0.5 | 2026-07 | notes |', '<!--- gbrain:takes:end -->'].join('\n');+ await managedFixture(async (engine, sourceId) => {+ await putPage(engine, sourceId, 'people/alice-example', `---\ntitle: Alice Example\ntype: person\n---\nStub.\n\n## Facts\n\n${facts}\n\n## Takes\n\n${takes}\n`);+ await putPage(engine, sourceId, 'meetings/m1', '---\ntitle: M1\ntype: note\n---\nNotes about [[people/alice-example]] and her widget design system work.');+ }, async (engine, sourceId) => {+ const activeFacts = () => engine.executeRaw(`SELECT id FROM facts WHERE source_id=$1 AND entity_slug='people/alice-example' AND expired_at IS NULL`, [sourceId]);+ const activeTakes = () => engine.executeRaw(`SELECT t.id FROM takes t JOIN pages p ON p.id=t.page_id WHERE p.source_id=$1 AND p.slug='people/alice-example' AND t.active`, [sourceId]);+ const before = { facts: (await activeFacts()).length, takes: (await activeTakes()).length };+ expect(before).toEqual({ facts: 1, takes: 1 });+ const result = await runEnrichCore(engine, { sourceId, types: ['person'] as never[], order: 'inbound-links' as const, thinThreshold: 4000,+ model: 'test:model', workers: 1, minContextChars: 20,+ synthesizeFn: async () => '## Overview\nAlice founded WidgetCo. [Source: meetings/m1]' });+ expect(result.pages_enriched).toBe(1);+ const page = await engine.getPage('people/alice-example', { sourceId });+ expect(page?.compiled_truth).toContain('Alice founded WidgetCo.');+ expect(page?.compiled_truth).toContain('Founded WidgetCo');+ expect({ facts: (await activeFacts()).length, takes: (await activeTakes()).length }).toEqual(before);+ });+});++test('#5280: grade_takes resolves the judged take by page identity when its page is renamed during judging (Codex review)', async () => {+ const { runPhaseGradeTakes } = await import('../src/core/cycle/grade-takes.ts');+ const takes = (claim: string) => ['<!--- gbrain:takes:begin -->', '| # | claim | kind | who | weight | since | source |',+ '|---|-------|------|-----|--------|-------|--------|', `| 1 | ${claim} | take | brain | 0.6 | 2025-01 | notes |`, '<!--- gbrain:takes:end -->'].join('\n');+ await managedFixture(async (engine, sourceId) => {+ await putPage(engine, sourceId, 'notes/graded', `---\ntitle: Graded\ntype: note\n---\nDraft.\n\n${takes('Acme will ship widgets')}\n`);+ }, async (engine, sourceId, root) => {+ let renamed = false;+ const judge = async ({ take }: { take: { claim: string } }) => {+ // Other sources' takes on this shared test brain are not part of this case.+ if (take.claim !== 'Acme will ship widgets' || renamed) return { verdict: 'unresolvable' as const, confidence: 0.1, reasoning: 'n/a' };+ renamed = true;+ // Simulate a rename that already committed, then a new page taking over the old slug.+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw("UPDATE pages SET slug='notes/graded-renamed', source_path=replace(source_path,'notes/graded.md','notes/graded-renamed.md') WHERE source_id=$1 AND slug='notes/graded'", [sourceId]);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ renameSync(join(root, 'notes/graded.md'), join(root, 'notes/graded-renamed.md'));+ await putPage(engine, sourceId, 'notes/graded', `---\ntitle: Graded\ntype: note\n---\nNew page.\n\n${takes('An unrelated claim')}\n`);+ return { verdict: 'correct' as const, confidence: 0.99, reasoning: 'Acme shipped widgets.' };+ };+ const result = await runPhaseGradeTakes({ engine, sourceId, remote: false, config: {} as never, dryRun: false, logger } as never,+ { autoResolve: true, minAgeMonths: 0, judge: judge as never, evidenceRetriever: (async () => 'evidence') as never, promptVersion: 'w3-rename' });+ expect(result.details.auto_applied).toBe(1);+ const rows = await engine.executeRaw<{ slug: string; resolved_quality: string | null }>(+ `SELECT p.slug, t.resolved_quality FROM takes t JOIN pages p ON p.id=t.page_id WHERE p.source_id=$1 ORDER BY p.slug`, [sourceId]);+ expect(rows).toEqual([{ slug: 'notes/graded', resolved_quality: null }, { slug: 'notes/graded-renamed', resolved_quality: 'correct' }]);+ });+});++test('#5280: grade_takes never applies a verdict to a fence row replaced before publication, and grades it again next run (Codex review)', async () => {+ const { runPhaseGradeTakes } = await import('../src/core/cycle/grade-takes.ts');+ const takes = (claim: string) => ['<!--- gbrain:takes:begin -->', '| # | claim | kind | who | weight | since | source |',+ '|---|-------|------|-----|--------|-------|--------|', `| 1 | ${claim} | take | brain | 0.6 | 2025-01 | notes |`, '<!--- gbrain:takes:end -->'].join('\n');+ await managedFixture(async (engine, sourceId) => {+ await putPage(engine, sourceId, 'notes/regraded', `---\ntitle: Regraded\ntype: note\n---\nDraft.\n\n${takes('Widgets ship in Q3')}\n`);+ }, async (engine, sourceId) => {+ const judged: string[] = [];+ const judge = async ({ take }: { take: { claim: string } }) => {+ judged.push(take.claim);+ return take.claim.startsWith('Widgets') || take.claim.startsWith('Gadgets')+ ? { verdict: 'correct' as const, confidence: 0.99, reasoning: 'shipped' } : { verdict: 'unresolvable' as const, confidence: 0.1, reasoning: 'n/a' };+ };+ let replaced = false;+ const racing = Object.create(engine) as BrainEngine;+ racing.readPageSnapshot = async (slug, opts) => {+ if (!replaced && slug === 'notes/regraded' && judged.includes('Widgets ship in Q3')) {+ replaced = true;+ const current = await engine.readPageSnapshot(slug, { sourceId });+ await submitPageMutation(ctxFor(engine, sourceId), { operation: 'put_page', params: { slug, expected_revision: current!.revision,+ request_id: randomUUID(), content: `---\ntitle: Regraded\ntype: note\n---\nDraft.\n\n${takes('Gadgets ship in Q4')}\n` } });+ }+ return engine.readPageSnapshot(slug, opts);+ };+ const opts = { autoResolve: true, minAgeMonths: 0, judge: judge as never, evidenceRetriever: (async () => 'evidence') as never, promptVersion: 'w3-replace' };+ const first = await runPhaseGradeTakes({ engine: racing, sourceId, remote: false, config: {} as never, dryRun: false, logger } as never, opts);+ expect(first.details.auto_applied).toBe(0);+ const resolved = () => engine.executeRaw<{ claim: string; resolved_quality: string | null }>(+ `SELECT t.claim, t.resolved_quality FROM takes t JOIN pages p ON p.id=t.page_id WHERE p.source_id=$1 AND p.slug='notes/regraded' AND t.active`, [sourceId]);+ expect(await resolved()).toEqual([{ claim: 'Gadgets ship in Q4', resolved_quality: null }]);+ // The row returns to the judged claim: its cached verdict must not block a retry.+ const current = await engine.readPageSnapshot('notes/regraded', { sourceId });+ await submitPageMutation(ctxFor(engine, sourceId), { operation: 'put_page', params: { slug: 'notes/regraded', expected_revision: current!.revision,+ request_id: randomUUID(), content: `---\ntitle: Regraded\ntype: note\n---\nDraft.\n\n${takes('Widgets ship in Q3')}\n` } });+ const second = await runPhaseGradeTakes({ engine, sourceId, remote: false, config: {} as never, dryRun: false, logger } as never, opts);+ expect(second.details.auto_applied).toBe(1);+ expect(await resolved()).toEqual([{ claim: 'Widgets ship in Q3', resolved_quality: 'correct' }]);+ });+});++test('#5280: incremental extract on a managed brain handles only the requested slugs, leaving the backlog to the bounded drain (Codex review)', async () => {+ const { runExtractCore } = await import('../src/commands/extract.ts');+ const { LINK_EXTRACTOR_VERSION_TS } = await import('../src/core/link-extraction.ts');+ await managedFixture(async (engine, sourceId) => {+ await engine.setConfig('auto_link', 'false');+ await putPage(engine, sourceId, 'notes/changed', '---\ntitle: Changed\ntype: note\n---\nSee [[notes/backlog]].');+ await putPage(engine, sourceId, 'notes/backlog', '---\ntitle: Backlog\ntype: note\n---\nOld page.');+ }, async (engine, sourceId, root) => {+ try {+ expect(await engine.countStalePagesForExtraction({ sourceId, versionTs: LINK_EXTRACTOR_VERSION_TS })).toBe(2);+ const result = await runExtractCore(engine, { mode: 'all', dir: root, sourceId, slugs: ['notes/changed'], quiet: true });+ expect(result.pages_processed).toBe(1);+ expect(await engine.countStalePagesForExtraction({ sourceId, versionTs: LINK_EXTRACTOR_VERSION_TS })).toBe(1);+ } finally { await engine.setConfig('auto_link', 'true'); }+ });+});++test('#5280: manual add_link / remove_link are coordinated on a managed brain, and a manual link survives re-derivation and republication', async () => {+ const addLink = operations.find(o => o.name === 'add_link')!;+ const removeLink = operations.find(o => o.name === 'remove_link')!;+ await managedFixture(async (engine, sourceId) => {+ await putPage(engine, sourceId, 'people/alice-example', '---\ntitle: Alice\ntype: person\n---\nAlice works on widgets.');+ await putPage(engine, sourceId, 'companies/acme-example', '---\ntitle: Acme\ntype: company\n---\nAcme makes widgets.');+ }, async (engine, sourceId) => {+ const ctx = ctxFor(engine, sourceId);+ expect(await addLink.handler(ctx, { from: 'people/alice-example', to: 'companies/acme-example', link_type: 'works_at' })).toEqual({ status: 'ok' });+ const manual = async () => (await engine.getLinks('people/alice-example', { sourceId }))+ .filter(l => l.to_slug === 'companies/acme-example' && l.link_source === 'manual');+ expect(await manual()).toHaveLength(1);+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug: 'people/alice-example', request_id: randomUUID(),+ expected_revision: (await engine.readPageSnapshot('people/alice-example', { sourceId }))!.revision,+ content: '---\ntitle: Alice\ntype: person\n---\nAlice still works on widgets.' } });+ await extractManagedStaleLinks(engine, { sourceId, slugs: ['people/alice-example'] });+ expect(await manual()).toHaveLength(1);+ expect(await removeLink.handler(ctx, { from: 'people/alice-example', to: 'companies/acme-example', link_source: 'manual' }))+ .toEqual({ status: 'ok', removed: 1 });+ expect(await manual()).toHaveLength(0);+ });+});diff --git a/test/memory-safety-wave.serial.test.ts b/test/memory-safety-wave.serial.test.tsindex c55440644d..358ef482d4 100644--- a/test/memory-safety-wave.serial.test.ts+++ b/test/memory-safety-wave.serial.test.ts@@ -1,4 +1,5 @@import { afterAll, beforeAll, expect, test } from 'bun:test';+import { withGoogleAccount } from './helpers/connector-fixture.ts';import { createHash, randomUUID } from 'node:crypto';import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';import { join } from 'node:path';@@ -98,7 +99,7 @@ test('sync, remember, withdraw, metadata repair, migration, export and HTTP MCPconst other = await fixture.boundSource(engine, { kind: 'filesystem' });const ctx = context(engine, source.id);const cfg = parseGoogleSourceConfig(config, source.dir);- expect((await runGoogleSync(engine, source.id, cfg, options, gmailFetch)).added).toBe(1);+ expect((await runGoogleSync(engine, source.id, cfg, options, withGoogleAccount(gmailFetch))).added).toBe(1);const [email] = await engine.executeRaw<{ slug: string }>("SELECT slug FROM pages WHERE source_id=$1 AND frontmatter->>'thread_id'='abc123'", [source.id]);const imported = (await engine.readPageSnapshot(email.slug, { sourceId: source.id }))!;const { gmail_attachment_receipts: oldReceipts, ...frontmatter } = imported.page.frontmatter;@@ -145,13 +146,13 @@ test('sync, remember, withdraw, metadata repair, migration, export and HTTP MCPexpect(killed.stdout, killed.stderr).toContain('MEMORY_WAVE_CRASH after_metadata_commit');expect(killed.exit).not.toBe(0);expect(JSON.stringify(await sourceCheckpoint(engine, source.id))).toContain('"afterPageId":0');- expect(await engine.executeRaw("SELECT id FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_connector_google_receipts' AND state='committed'", [source.id])).toHaveLength(1);+ expect(await engine.executeRaw("SELECT id FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='connector_v2_google_receipts' AND state='committed'", [source.id])).toHaveLength(1);const resumed = await repairChild(false);expect(resumed.exit, resumed.stderr).toBe(0);expect(resumed.stdout).toContain('"status":"complete"');expect(JSON.stringify(await sourceCheckpoint(engine, source.id))).toContain('"complete":true');expect(await engine.executeRaw('SELECT id FROM persistence_requests WHERE source_id=$1 AND recovery IS NOT NULL', [source.id])).toHaveLength(0);- expect(await engine.executeRaw("SELECT id FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_connector_google_receipts' AND state='committed' AND NOT COALESCE((outcome->>'noop')::boolean,false)", [source.id])).toHaveLength(1);+ expect(await engine.executeRaw("SELECT id FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='connector_v2_google_receipts' AND state='committed' AND NOT COALESCE((outcome->>'noop')::boolean,false)", [source.id])).toHaveLength(1);const repaired = (await engine.readPageSnapshot(email.slug, { sourceId: source.id }))!;expect(repaired.page.compiled_truth).toBe(beforeWithdrawal.page.compiled_truth);expect(repaired.page.frontmatter).toMatchObject({ visibility: 'private', custom: 'preserved', gmail_attachment_receipts: { messages: [{ inspection: { state: 'present' } }] } });diff --git a/test/noop-kernel-paths.test.ts b/test/noop-kernel-paths.test.tsnew file mode 100644index 0000000000..216268d320--- /dev/null+++ b/test/noop-kernel-paths.test.ts@@ -0,0 +1,148 @@+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { execFileSync } from 'node:child_process';+import { dirname, join } from 'node:path';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { importManagedFile } from '../src/core/persistence/import-mutations.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { registerLocalWriter } from '../src/core/persistence/identity.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { inspectCompanyBrain } from '../src/core/company-brain/inspection.ts';+import { resumeCompanyBrain } from '../src/core/company-brain/runtime.ts';+import { admitCompanyBrain } from '../src/core/company-brain/admission.ts';+import { performSync } from '../src/commands/sync.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { makeGitFixture } from './helpers/git-fixture.ts';+import { withEnv } from './helpers/with-env.ts';++// #5470: unchanged items take no admission in the managed import, working-tree+// sync and company-profile paths (the connector path is covered in+// connector-checkpoint-identity.test.ts). Each path screens through its own+// publication preparer; changed items and pending projection work still admit.++const home = mkdtempSync(join(tmpdir(), 'gbrain-noop-kernel-'));+const engines: BrainEngine[] = [];+// Company admission needs an empty brain, so that case gets its own stores.+const companyStores: Array<{ engine: BrainEngine; close: () => Promise<void> }> = [];+let closePostgres: (() => Promise<void>) | undefined;+const env = { GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home, GBRAIN_SOURCE: undefined, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined };+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).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; }+ const company = new PGLiteEngine(); await company.connect({}); await company.initSchema(); companyStores.push({ engine: company, close: () => company.disconnect() });+ if (process.env.DATABASE_URL) companyStores.push(await isolatedPersistencePostgres(process.env.DATABASE_URL));+}, 120_000);+afterAll(async () => {+ await withEnv(env, async () => {+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }+ for (const store of companyStores) { await disposePersistenceConsumer(store.engine); await store.close(); }+ });+ await closePostgres?.(); rmSync(home, { recursive: true, force: true });+});+const each = (fn: (engine: BrainEngine) => Promise<void>) => withEnv(env, async () => { for (const engine of engines) await fn(engine); });+const admissions = async (engine: BrainEngine, sourceId: string, slug: string) =>+ (await engine.executeRaw('SELECT id FROM persistence_requests WHERE source_id=$1 AND slug=$2', [sourceId, slug])).length;+async function unmanaged<T>(engine: BrainEngine, fn: () => Promise<T>): Promise<T> {+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ try { return await fn(); } finally { await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1'); }+}++async function importFixture(engine: BrainEngine) {+ const sourceId = `import-${randomUUID().slice(0, 8)}`;+ const root = join(home, sourceId), input = join(home, `${sourceId}-input`);+ mkdirSync(root); mkdirSync(input);+ await unmanaged(engine, async () => {+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);+ await registerLocalWriter(engine, 'cli');+ await claimWorktree(engine, sourceId, root);+ });+ return { sourceId, root, input };+}++test('#5470 managed import: an identical re-import takes no admission; a change, a safe-chunk reseal and projection lag still admit', async () => each(async engine => {+ const f = await importFixture(engine);+ const file = join(f.input, 'note.md');+ const run = () => importManagedFile(engine, file, 'note.md', { sourceId: f.sourceId, noEmbed: true });+ writeFileSync(file, '---\ntitle: Note\n---\nThe first durable observation.\n');+ expect((await run()).status).toBe('imported');+ expect(await run()).toMatchObject({ status: 'skipped' });+ expect(await admissions(engine, f.sourceId, 'note')).toBe(1);+ writeFileSync(file, '---\ntitle: Note\n---\nA changed durable observation.\n');+ expect((await run()).status).toBe('imported');+ expect(await admissions(engine, f.sourceId, 'note')).toBe(2);+ // Below the safe-chunk fence: admitted, so publication re-seals instead of the skip hiding it.+ await engine.executeRaw("UPDATE pages SET chunker_version=1 WHERE source_id=$1 AND slug='note'", [f.sourceId]);+ await run();+ expect(await admissions(engine, f.sourceId, 'note')).toBe(3);+ await engine.executeRaw('UPDATE pages SET text_projection_revision=gen_random_uuid() WHERE source_id=$1 AND slug=$2', [f.sourceId, 'note']);+ await run();+ expect(await admissions(engine, f.sourceId, 'note')).toBe(4);+}), 180_000);++async function syncFixture(engine: BrainEngine) {+ const id = `wt-${randomUUID().slice(0, 12)}`, root = join(home, id);+ mkdirSync(root); git(root, 'init', '-q');+ writeFileSync(join(root, 'a.md'), '---\ntitle: a\n---\nA committed observation.\n');+ git(root, 'add', '.'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'seed');+ await unmanaged(engine, async () => {+ await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,\'{}\')', [id, root]);+ await claimWorktree(engine, id, root);+ });+ return { id, root };+}++test('#5470 working-tree sync: a dirty file re-queued on the next run takes no second admission', async () => each(async engine => {+ const f = await syncFixture(engine);+ const opts = { sourceId: f.id, noPull: true, noEmbed: true, noExtract: true, workingTree: true, explicitProcessing: [] };+ expect((await performManagedSync(engine, opts)).status).not.toBe('partial');+ writeFileSync(join(f.root, 'a.md'), '---\ntitle: a\n---\nAn uncommitted working-tree edit.\n');+ expect((await performManagedSync(engine, opts)).status).not.toBe('partial');+ expect((await engine.getPage('a', { sourceId: f.id }))?.compiled_truth).toContain('uncommitted working-tree edit');+ const once = await admissions(engine, f.id, 'a');+ await disposePersistenceConsumer(engine);+ expect((await performManagedSync(engine, opts)).status).not.toBe('partial');+ expect(await admissions(engine, f.id, 'a')).toBe(once);+}), 180_000);++test('#5470 company profile: rediscovering an interrupted approved revision re-imports no committed entry', async () => withEnv(env, async () => {+ {+ for (const { engine } of companyStores) {+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const root = mkdtempSync(join(home, 'company-')), repo = await makeGitFixture(root);+ for (const [path, content] of Object.entries({+ 'people/operator.md': '---\ntype: person\ntitle: Example Operator\n---\n# Example Operator\nOwns the account.\n',+ 'customers/account.md': '---\ntype: customer\ntitle: Example Account\nowner: "[[people/operator]]"\naudience: internal\n---\n# Example Account\nA synthetic account.\n',+ })) { mkdirSync(dirname(join(root, path)), { recursive: true }); writeFileSync(join(root, path), content); }+ repo.commitAll('Add approved synthetic source');+ const sourceId = `company-${randomUUID().slice(0, 12)}`;+ const input = { brainId: 'company-example', sourceId, path: root, remote: false, requestId: randomUUID(),+ plan: await inspectCompanyBrain({ path: root, profile: 'company-brain' }) };+ await admitCompanyBrain(engine, input);+ // Interrupt the content phase once the first entry's page has committed.+ const abort = new AbortController(), transaction = engine.transaction;+ engine.transaction = async function<T>(this: BrainEngine, run: (tx: BrainEngine) => Promise<T>): Promise<T> {+ const value = await transaction.call(this, run) as T & { index?: number; sourceId?: string; runId?: string };+ if (value && typeof value === 'object' && value.runId && value.sourceId === sourceId && Number(value.index) >= 1) abort.abort();+ return value;+ };+ try { expect(await resumeCompanyBrain(engine, input, { signal: abort.signal })).toMatchObject({ ok: false }); }+ finally { engine.transaction = transaction; }+ const pages = async () => (await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_sync_import'", [sourceId]))[0].n;+ const before = await pages();+ expect(before).toBe(1);+ // A lost cursor makes the resume rediscover every included entry of the approved revision.+ await disposePersistenceConsumer(engine);+ await engine.executeRaw("DELETE FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1", [sourceId]);+ expect((await performSync(engine, { sourceId })).status).toBe('synced');+ expect(await pages()).toBe(before + 1);+ expect((await engine.getPage('customers/account', { sourceId }))?.compiled_truth).toContain('synthetic account');+ expect((await engine.getPage('people/operator', { sourceId }))?.compiled_truth).toContain('Owns the account');+ }+ }+}), 180_000);diff --git a/test/persistence-blocking-effects.test.ts b/test/persistence-blocking-effects.test.tsnew file mode 100644index 0000000000..d82f7545d3--- /dev/null+++ b/test/persistence-blocking-effects.test.ts@@ -0,0 +1,84 @@+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+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 { WRITER_INSPECTION_HINT } from '../src/core/persistence/admin-intent.ts';+import { activatePersistence } from '../src/core/persistence/activation.ts';+import { activateSharedSkillPersistence } from '../src/core/persistence/skill-activation.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { runPersistenceAdministration } from '../src/core/persistence/administration.ts';+import { listBlockingEffects } from '../src/core/persistence/blocking-effects.ts';+import { declarePersistenceProtocol } from '../src/core/persistence/protocol.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { freshBrainFactory, requestFixture } from './helpers/persistence-request-fixture.ts';+import { testBackends } from './helpers/test-backends.ts';+import { withEnv } from './helpers/with-env.ts';++const databaseUrl = process.env.DATABASE_URL;+for (const kind of testBackends()) {+ describe(`writer_not_quiesced names its blocker ${kind}`, () => {+ let factory: Awaited<ReturnType<typeof freshBrainFactory>>;+ let scratch: string;+ beforeAll(async () => {+ scratch = mkdtempSync(join(tmpdir(), 'gbrain-blocking-effects-'));+ factory = await freshBrainFactory(kind, databaseUrl);+ }, 120_000);+ afterAll(async () => {+ await factory?.dispose();+ if (scratch) rmSync(scratch, { recursive: true, force: true });+ });+ const check = (name: string, fn: (engine: BrainEngine, root: string) => Promise<void>) => test(name, async () => {+ const engine = await factory.fresh();+ const home = mkdtempSync(join(scratch, 'home-'));+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {+ const root = join(home, 'canonical'); mkdirSync(root);+ writeFileSync(join(root, 'example.md'), 'generic example');+ await engine.executeRaw("UPDATE sources SET local_path=$1 WHERE id='default'", [root]);+ try { await fn(engine, root); } finally { await disposePersistenceConsumer(engine); }+ });+ }, 120_000);++ check('a stuck queued embedding effect is named in the refusal and in writer status', async (engine, root) => {+ await claimWorktree(engine, 'default', root);+ const requests = await requestFixture(engine, 'effects-example');+ const published = await requests.publish(await requests.admit('notes/stuck'));+ const [effect] = await engine.transaction(async tx => {+ await declarePersistenceProtocol(tx);+ await tx.executeRaw("UPDATE persistence_effects SET state='committed' WHERE request_id=$1::uuid AND kind<>'embedding'", [published.id]);+ return tx.executeRaw<{ id: string }>(`UPDATE persistence_effects SET next_attempt_at=now()+interval '30 days'+ WHERE request_id=$1::uuid AND kind='embedding' AND state='queued' RETURNING id::text AS id`, [published.id]);+ });+ expect(effect).toBeDefined();++ const error = await activateSharedSkillPersistence(engine, { confirmQuiesced: true }).then(() => null, failure => failure as { code: string; suggestion: string });+ expect(error?.code).toBe('writer_not_quiesced');+ const suggestion = error!.suggestion;+ expect(suggestion.startsWith(WRITER_INSPECTION_HINT)).toBe(true);+ expect(suggestion).toContain(`Blocking effect ${effect.id} (kind embedding, state queued) for source effects-example, page notes/stuck, request ${published.request_id}.`);+ expect(suggestion).toContain('Inspect it with: gbrain sources writer status effects-example --json.');+ expect(suggestion).toContain('Inspection cannot clear it');+ expect(suggestion).toContain('deferred reconcile path');++ const expected = { effect_id: effect.id, kind: 'embedding', state: 'queued', recovering: false, source_id: 'effects-example',+ slug: 'notes/stuck', request_id: published.request_id, inspect: 'gbrain sources writer status effects-example --json' };+ expect(await listBlockingEffects(engine, { sourceId: 'effects-example', limit: 5 })).toEqual([expect.objectContaining(expected)]);+ expect(await listBlockingEffects(engine, { sourceId: 'default' })).toEqual([]);+ const status = await runPersistenceAdministration(engine, 'writer_status', {});+ expect(status.blocking_effects).toEqual([expect.objectContaining(expected)]);+ const scoped = await runPersistenceAdministration(engine, 'writer_status', { source_id: 'effects-example' });+ expect(scoped.blocking_effects).toEqual([expect.objectContaining(expected)]);+ });++ check('base activation names the queued request that blocks it', async (engine, root) => {+ await claimWorktree(engine, 'default', root);+ const requests = await requestFixture(engine, 'queued-example');+ const admitted = await requests.admit('notes/queued');+ const error = await activatePersistence(engine, { confirmQuiesced: true }).then(() => null, failure => failure as { code: string; suggestion: string });+ expect(error?.code).toBe('writer_not_quiesced');+ expect(error!.suggestion.startsWith(WRITER_INSPECTION_HINT)).toBe(true);+ expect(error!.suggestion).toContain(`Blocking request ${admitted.request_id} (put_page, queued) for source queued-example, page notes/queued.`);+ expect(error!.suggestion).toContain('Inspect it with: gbrain sources writer status queued-example --json.');+ });+ });+}diff --git a/test/persistence-connector-fencing.test.ts b/test/persistence-connector-fencing.test.tsindex 68c09e6539..5c291d28e3 100644--- a/test/persistence-connector-fencing.test.ts+++ b/test/persistence-connector-fencing.test.ts@@ -1,4 +1,5 @@import { afterAll, beforeAll, expect, test } from 'bun:test';+import { withGoogleAccount } from './helpers/connector-fixture.ts';import { existsSync, readFileSync } from 'node:fs';import { join } from 'node:path';import { performSync } from '../src/commands/sync.ts';@@ -69,7 +70,7 @@ for (const connector of ['github', 'google'] as const) {const run = () => connector === 'github'? runGitHubSync(engine, f.id, parseGitHubSourceConfig(config, f.dir), { ...options, skipLock: true,githubItem: { repo: 'acme-example/app', number: 1, kind: 'issue' } }, fetcher)- : runGoogleSync(engine, f.id, parseGoogleSourceConfig(config, f.dir), { ...options, skipLock: true }, fetcher);+ : runGoogleSync(engine, f.id, parseGoogleSourceConfig(config, f.dir), { ...options, skipLock: true }, withGoogleAccount(fetcher));const first = run();first.catch(() => {});await entered.promise;@@ -93,7 +94,7 @@ for (const connector of ['github', 'google'] as const) {globalThis.fetch = (async (url: string | URL | Request) => {again.resolve();await delayed.promise;- return fetcher(String(url));+ return withGoogleAccount(fetcher)(String(url));}) as typeof fetch;const command = performSync(engine, { ...options, sourceId: f.id, full: true, skipLock: true, lockId: 'caller-cannot-bypass-source-lease' });command.catch(() => {});@@ -127,7 +128,7 @@ for (const connector of ['github', 'google'] as const) {return connector === 'github'? runGitHubSync(engine, f.id, parseGitHubSourceConfig(config, f.dir), { ...options,githubItem: { repo: 'acme-example/app', number: 1, kind: 'issue' } }, fetcher)- : runGoogleSync(engine, f.id, parseGoogleSourceConfig(config, f.dir), options, fetcher);+ : runGoogleSync(engine, f.id, parseGoogleSourceConfig(config, f.dir), options, withGoogleAccount(fetcher));};const old = run(true);old.catch(() => {});diff --git a/test/persistence-connector-recovery.test.ts b/test/persistence-connector-recovery.test.tsindex 05fa1bcbd5..aa643c4b1e 100644--- a/test/persistence-connector-recovery.test.ts+++ b/test/persistence-connector-recovery.test.ts@@ -1,4 +1,5 @@import { afterAll, beforeAll, expect, test } from 'bun:test';+import { withGoogleAccount } from './helpers/connector-fixture.ts';import { randomUUID } from 'node:crypto';import { readFileSync, writeFileSync } from 'node:fs';import { join } from 'node:path';@@ -19,9 +20,9 @@ test('standalone connector restart recovers a real SIGKILL after file publicatiofor (const engine of engines) for (const connector of ['google', 'github'] as const) {const config = connector === 'google' ? googleConfig : githubConfig;const f = await boundSource(engine, config);- if (connector === 'google') await runGoogleSync(engine, f.id, parseGoogleSourceConfig(config, f.dir), options, async url =>+ if (connector === 'google') await runGoogleSync(engine, f.id, parseGoogleSourceConfig(config, f.dir), options, withGoogleAccount(async url =>json(url.includes('/settings/sendAs') ? { sendAs: [] } : { connections: [{ ...contact('first', 'First Example'),- organizations: [{ name: 'Initial organization' }] }], nextSyncToken: 'contacts-restart' }));+ organizations: [{ name: 'Initial organization' }] }], nextSyncToken: 'contacts-restart' })));else await runGitHubSync(engine, f.id, parseGitHubSourceConfig(config, f.dir), options, githubFetch());const slug = connector === 'google' ? 'people/first-example' : 'gh/acme-example/app/1';const before = await engine.readPageSnapshot(slug, { sourceId: f.id });diff --git a/test/persistence-connector-retry.test.ts b/test/persistence-connector-retry.test.tsindex 8a91c67943..fe5928e130 100644--- a/test/persistence-connector-retry.test.ts+++ b/test/persistence-connector-retry.test.ts@@ -1,4 +1,5 @@import { afterAll, beforeAll, expect, test } from 'bun:test';+import { withGoogleAccount } from './helpers/connector-fixture.ts';import { chmodSync, chownSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { dirname, join } from 'node:path';@@ -11,7 +12,7 @@ import { beginConnectorSync } from '../src/core/persistence/connector-sync.ts';import { compactWriteReceipts } from '../src/core/persistence/journal.ts';import { purgeStaleCheckpoints } from '../src/core/op-checkpoint.ts';import { withEnv } from './helpers/with-env.ts';-import { createConnectorFixture, options, json, googleConfig, githubConfig, contact, issueFixture, githubFetch, sourceCheckpoint } from './helpers/connector-fixture.ts';+import { createConnectorFixture, options, json, googleConfig, githubConfig, contact, issueFixture, githubFetch, sourceCheckpoint, connectorPendingSet } from './helpers/connector-fixture.ts';const { engines, env, backends, source, boundSource, standaloneConnector, setup, teardown } = createConnectorFixture();beforeAll(setup, 120_000);@@ -126,7 +127,7 @@ async function retryFixture(engine: BrainEngine, connector: 'google' | 'github',};const cfg = connector === 'google' ? parseGoogleSourceConfig(config, f.dir) : parseGitHubSourceConfig(config, f.dir);const run = (retryFailed = false) => connector === 'google'- ? runGoogleSync(engine, f.id, cfg as ReturnType<typeof parseGoogleSourceConfig>, { ...options, retryFailed }, fetcher)+ ? runGoogleSync(engine, f.id, cfg as ReturnType<typeof parseGoogleSourceConfig>, { ...options, retryFailed }, withGoogleAccount(fetcher)): runGitHubSync(engine, f.id, cfg as ReturnType<typeof parseGitHubSourceConfig>, { ...options, retryFailed }, fetcher);await run();await disposePersistenceConsumer(engine);@@ -173,7 +174,7 @@ test('checkpoint storage failures require explicit retry after pages have alreadawait expect(f.run()).rejects.toMatchObject({ code: 'storage_error' });await disposePersistenceConsumer(engine);const [failed] = await engine.executeRaw<WriteRequest>("SELECT * FROM persistence_requests WHERE source_id=$1 AND state='failed'", [f.id]);- expect(failed.intent?.kind).toBe('managed_connector_checkpoint');+ expect(failed.intent?.kind).toBe('connector_v2_checkpoint');expect(await sourceCheckpoint(engine, f.id)).toEqual(f.checkpoint);await engine.executeRaw("UPDATE persistence_requests SET completed_at=now()-interval '31 days' WHERE id=$1::uuid", [failed.id]);await compactWriteReceipts(engine);@@ -202,11 +203,11 @@ test('checkpoint replay keeps its originally admitted page dependencies when anoawait engine.executeRaw("UPDATE persistence_worktrees SET state='draining' WHERE id=$1::uuid", [f.binding.worktree_id]);const state = { cursor: 'same-logical-checkpoint' };await expect(first.saveState(state, true)).rejects.toMatchObject({ code: 'write_pending' });- const [accepted] = await engine.executeRaw<WriteRequest>("SELECT * FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_connector_checkpoint'", [f.id]);+ const [accepted] = await engine.executeRaw<WriteRequest>("SELECT * FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='connector_v2_checkpoint'", [f.id]);const [dependency] = await engine.executeRaw<WriteRequest>("SELECT * FROM persistence_requests WHERE source_id=$1 AND slug='notes/first'", [f.id]);expect(accepted.intent?.receipts).toEqual([dependency.id]);await expect(second.saveState(state, true)).rejects.toMatchObject({ code: 'write_pending', writeRequest: { request_id: accepted.request_id } });- expect(await engine.executeRaw("SELECT id FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_connector_checkpoint'", [f.id])).toHaveLength(1);+ expect(await engine.executeRaw("SELECT id FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='connector_v2_checkpoint'", [f.id])).toHaveLength(1);expect((await engine.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE id=$1::uuid', [accepted.id]))[0].intent?.receipts).toEqual([dependency.id]);await disposePersistenceConsumer(engine);await engine.executeRaw("UPDATE persistence_worktrees SET state='active' WHERE id=$1::uuid", [f.binding.worktree_id]);@@ -259,9 +260,10 @@ test('concurrent connector approvals and a restarted paused owner retain one penconst results = await Promise.allSettled(sessions.map(session => session!.importMarkdown(original.intent!.sourcePath as string, original.intent!.content as string)));const [retry] = await engine.executeRaw<WriteRequest>("SELECT * FROM persistence_requests WHERE source_id=$1 AND intent->>'retryOf'=$2", [f.id, original.request_id]);expect(retry).toMatchObject({ state: 'queued' });+ // #5600: a session that admitted or replayed the replacement reports accepted-pending progress; a racing approval refuses write_pending on the same receipt.for (const result of results) {- expect(result.status).toBe('rejected');- expect((result as PromiseRejectedResult).reason).toMatchObject({ code: 'write_pending', writeRequest: { request_id: retry.request_id } });+ if (result.status === 'fulfilled') expect(result.value).toMatchObject({ status: 'imported' });+ else expect(result.reason).toMatchObject({ code: 'write_pending', writeRequest: { request_id: retry.request_id } });}await disposePersistenceConsumer(engine);expect(await sourceCheckpoint(engine, f.id)).toEqual(f.checkpoint);@@ -270,7 +272,8 @@ test('concurrent connector approvals and a restarted paused owner retain one penexpect(restarted.stdout).not.toContain('CONNECTOR_FIXTURE_FETCH');expect(JSON.parse(restarted.stdout.split('CONNECTOR_ERROR ')[1].trim())).toMatchObject({ code: 'write_pending', receipt: { request_id: retry.request_id } });const count = await engine.executeRaw('SELECT id FROM persistence_requests WHERE source_id=$1 ORDER BY sequence', [f.id]);- await expect(f.run()).rejects.toMatchObject({ code: 'write_pending', writeRequest: { request_id: retry.request_id } });+ expect(await f.run()).toMatchObject({ status: 'partial', reason: 'writer_pending' });+ expect((await connectorPendingSet(engine, f.id)).map(entry => entry.requestId)).toEqual([retry.request_id]);expect(await engine.executeRaw('SELECT id FROM persistence_requests WHERE source_id=$1 ORDER BY sequence', [f.id])).toEqual(count);await disposePersistenceConsumer(engine);await engine.executeRaw("UPDATE persistence_worktrees SET state='active' WHERE id=$1::uuid", [original.worktree_id]);diff --git a/test/persistence-connectors.test.ts b/test/persistence-connectors.test.tsindex 8e7df589ef..18cbfa9392 100644--- a/test/persistence-connectors.test.ts+++ b/test/persistence-connectors.test.ts@@ -1,4 +1,5 @@import { afterAll, beforeAll, expect, test } from 'bun:test';+import { withGoogleAccount } from './helpers/connector-fixture.ts';import { randomUUID } from 'node:crypto';import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';import { join } from 'node:path';@@ -14,7 +15,7 @@ import { importFromContent } from '../src/core/import-file.ts';import { parseMarkdown } from '../src/core/markdown.ts';import { withEnv } from './helpers/with-env.ts';import { purgeStaleCheckpoints } from '../src/core/op-checkpoint.ts';-import { createConnectorFixture, options, json, googleConfig, githubConfig, contact, issueFixture, githubFetch, sourceCheckpoint } from './helpers/connector-fixture.ts';+import { createConnectorFixture, options, json, googleConfig, githubConfig, contact, issueFixture, githubFetch, sourceCheckpoint, connectorPendingSet } from './helpers/connector-fixture.ts';const { home, engines, env, source, boundSource, setup, teardown } = createConnectorFixture();beforeAll(setup, 120_000);@@ -32,16 +33,16 @@ test('public Google sync journals DB-only imports and repeat/restart checkpointsthrow new Error('Unexpected external fixture route');};const cfg = parseGoogleSourceConfig(config, f.dir);- expect((await runGoogleSync(engine, f.id, cfg, options, fetcher)).added).toBe(1);+ expect((await runGoogleSync(engine, f.id, cfg, options, withGoogleAccount(fetcher))).added).toBe(1);const pages = await engine.executeRaw<{ slug: string; source_path: string }>('SELECT slug,source_path FROM pages WHERE source_id=$1', [f.id]);expect(pages).toHaveLength(1);expect(existsSync(join(f.dir, pages[0].source_path))).toBe(false);- const [receipt] = await engine.executeRaw<WriteRequest>("SELECT * FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_connector_import' ORDER BY sequence LIMIT 1", [f.id]);+ const [receipt] = await engine.executeRaw<WriteRequest>("SELECT * FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='connector_v2_import' ORDER BY sequence LIMIT 1", [f.id]);expect(receipt.authority.databaseOnlyReason).toBe('connector_database');expect(receipt.outcome?.write_through).toEqual({ written: false, skipped: 'connector_database' });expect(await engine.executeRaw('SELECT id FROM persistence_requests WHERE source_id=$1 AND state<>\'committed\'', [f.id])).toHaveLength(0);await disposePersistenceConsumer(engine);- expect((await runGoogleSync(engine, f.id, cfg, options, fetcher)).added).toBe(0);+ expect((await runGoogleSync(engine, f.id, cfg, options, withGoogleAccount(fetcher))).added).toBe(0);expect(calls.some(url => url.includes('syncToken=contacts-1'))).toBe(true);}}), 120_000);@@ -82,13 +83,13 @@ test('Google pagination failure never advances a checkpoint; tombstones delete oreturn json({ connections: [contact('second', 'Second Example')], nextSyncToken: 'contacts-complete' });};const cfg = parseGoogleSourceConfig(googleConfig, f.dir);- expect((await runGoogleSync(engine, f.id, cfg, options, fetcher)).status).toBe('partial');+ expect((await runGoogleSync(engine, f.id, cfg, options, withGoogleAccount(fetcher))).status).toBe('partial');expect(await sourceCheckpoint(engine, f.id)).toHaveLength(0);expect(await engine.executeRaw('SELECT slug FROM pages WHERE source_id=$1', [f.id])).toHaveLength(0);fail = false;- expect((await runGoogleSync(engine, f.id, cfg, options, fetcher)).added).toBe(2);+ expect((await runGoogleSync(engine, f.id, cfg, options, withGoogleAccount(fetcher))).added).toBe(2);const other = await source(engine, googleConfig);- expect((await runGoogleSync(engine, other.id, parseGoogleSourceConfig(googleConfig, other.dir), options, fetcher)).added).toBe(2);+ expect((await runGoogleSync(engine, other.id, parseGoogleSourceConfig(googleConfig, other.dir), options, withGoogleAccount(fetcher))).added).toBe(2);deleted = true;const checkpoint = await sourceCheckpoint(engine, f.id);const executeRaw = engine.executeRaw;@@ -97,10 +98,10 @@ test('Google pagination failure never advances a checkpoint; tombstones delete oreturn executeRaw.call(engine, sql, params);} as BrainEngine['executeRaw'];try {- expect((await runGoogleSync(engine, f.id, cfg, options, fetcher)).status).toBe('partial');+ expect((await runGoogleSync(engine, f.id, cfg, options, withGoogleAccount(fetcher))).status).toBe('partial');expect(await sourceCheckpoint(engine, f.id)).toEqual(checkpoint);} finally { engine.executeRaw = executeRaw; }- expect((await runGoogleSync(engine, f.id, cfg, options, fetcher)).deleted).toBe(1);+ expect((await runGoogleSync(engine, f.id, cfg, options, withGoogleAccount(fetcher))).deleted).toBe(1);expect(await engine.getPage('people/first-example', { sourceId: f.id })).toBeNull();expect(await engine.getPage('people/first-example', { sourceId: other.id })).not.toBeNull();}@@ -161,7 +162,7 @@ test('managed connectors refuse unsupported dry runs and Git filters before credfor (const mode of [{ dryRun: true }, { skipFailed: true }, { srcSubpath: 'scoped' },{ exclude: ['private/**'] }, { includeHidden: ['.notes/**'] }, { includeGitignored: true }, { workingTree: true }, { strategy: 'code' as const }]) {const run = connector === 'google'- ? runGoogleSync(engine, f.id, parseGoogleSourceConfig(config, f.dir), { ...options, ...mode }, fetcher)+ ? runGoogleSync(engine, f.id, parseGoogleSourceConfig(config, f.dir), { ...options, ...mode }, withGoogleAccount(fetcher)): runGitHubSync(engine, f.id, parseGitHubSourceConfig(config, f.dir), { ...options, ...mode }, fetcher);await expect(run).rejects.toMatchObject({ code: 'invalid_params' });}@@ -188,7 +189,7 @@ test('source replacement after connector preflight cannot receive the old sweepreturn json({ connections: [contact('first', 'First Example')], nextSyncToken: 'stale-source-token' });};const run = connector === 'google'- ? runGoogleSync(engine, f.id, parseGoogleSourceConfig(config, f.dir), options, fetcher)+ ? runGoogleSync(engine, f.id, parseGoogleSourceConfig(config, f.dir), options, withGoogleAccount(fetcher)): runGitHubSync(engine, f.id, parseGitHubSourceConfig(config, f.dir), options, fetcher);await expect(run).rejects.toMatchObject({ code: 'source_changed' });expect(await engine.executeRaw('SELECT slug FROM pages WHERE source_id=$1', [f.id])).toHaveLength(0);@@ -223,19 +224,19 @@ test('Google Gmail and Calendar ingest, fail without advancing, restart, and del}throw new Error('Unexpected external fixture route');};- const first = await runGoogleSync(engine, f.id, cfg, options, fetcher);+ const first = await runGoogleSync(engine, f.id, cfg, options, withGoogleAccount(fetcher));expect(first.status).not.toBe('partial');expect(first.added).toBe(2);const checkpoint = await sourceCheckpoint(engine, f.id);delta = true;fail = true;- expect((await runGoogleSync(engine, f.id, cfg, options, fetcher)).status).toBe('partial');+ expect((await runGoogleSync(engine, f.id, cfg, options, withGoogleAccount(fetcher))).status).toBe('partial');expect(await sourceCheckpoint(engine, f.id)).toEqual(checkpoint);fail = false;await disposePersistenceConsumer(engine);- expect((await runGoogleSync(engine, f.id, cfg, options, fetcher)).status).not.toBe('partial');+ expect((await runGoogleSync(engine, f.id, cfg, options, withGoogleAccount(fetcher))).status).not.toBe('partial');removed = true;- expect((await runGoogleSync(engine, f.id, cfg, { ...options, full: true }, fetcher)).deleted).toBe(2);+ expect((await runGoogleSync(engine, f.id, cfg, { ...options, full: true }, withGoogleAccount(fetcher))).deleted).toBe(2);expect(await engine.executeRaw('SELECT slug FROM pages WHERE source_id=$1 AND deleted_at IS NULL', [f.id])).toHaveLength(0);}}), 120_000);@@ -249,13 +250,11 @@ test('paused connector owner returns one stable receipt and resident restart conawait engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');const cfg = parseGitHubSourceConfig(githubConfig, f.dir);const run = () => runGitHubSync(engine, f.id, cfg, options, githubFetch());- let requestId = '';- try { await run(); throw new Error('Expected pending receipt'); }- catch (error) {- expect(error).toMatchObject({ code: 'write_pending' });- requestId = (error as { writeRequest: { request_id: string } }).writeRequest.request_id;- }- await expect(run()).rejects.toMatchObject({ code: 'write_pending', writeRequest: { request_id: requestId } });+ // #5600: an accepted pending write is progress; the run ends partial with the receipt in its pending set.+ expect(await run()).toMatchObject({ status: 'partial', reason: 'writer_pending' });+ const [pending] = await connectorPendingSet(engine, f.id);+ expect(await run()).toMatchObject({ status: 'partial', reason: 'writer_pending' });+ expect((await connectorPendingSet(engine, f.id)).map(entry => entry.requestId)).toEqual([pending.requestId]);const rows = await engine.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE source_id=$1', [f.id]);expect(rows).toHaveLength(1);expect(await sourceCheckpoint(engine, f.id)).toHaveLength(0);@@ -284,13 +283,13 @@ test('bound connector directories publish import, update, unchanged replay, and: [{ ...contact('first', 'First Example'), organizations: [{ name: body }] }], nextSyncToken: 'contacts-bound' });};const run = () => connector === 'google'- ? runGoogleSync(engine, f.id, parseGoogleSourceConfig(config, f.dir), options, fetcher)+ ? runGoogleSync(engine, f.id, parseGoogleSourceConfig(config, f.dir), options, withGoogleAccount(fetcher)): runGitHubSync(engine, f.id, parseGitHubSourceConfig(config, f.dir), { ...options, githubItem: { repo: 'acme-example/app', number: 1, kind: 'issue', deleted } }, fetcher);const slug = connector === 'google' ? 'people/first-example' : 'gh/acme-example/app/1';const path = join(f.dir, `${slug}.md`);expect((await run()).added).toBe(1);expect(readFileSync(path, 'utf8')).toContain(body);- const [receipt] = await engine.executeRaw<WriteRequest>("SELECT * FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_connector_import' ORDER BY sequence LIMIT 1", [f.id]);+ const [receipt] = await engine.executeRaw<WriteRequest>("SELECT * FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='connector_v2_import' ORDER BY sequence LIMIT 1", [f.id]);expect(receipt.outcome?.persistence).toEqual({ mode: 'filesystem', file_written: true, git_state: 'queued' });expect(receipt.authority.databaseOnlyReason).toBeUndefined();const first = readFileSync(path, 'utf8');@@ -351,7 +350,7 @@ test('previously materialized connector pages stay canonical-file backed with mareturn json({ connections: [{ ...contact('first', 'First Example'), organizations: [{ name: body }] }], nextSyncToken: 'contacts-legacy' });};const run = () => connector === 'google'- ? runGoogleSync(engine, f.id, parseGoogleSourceConfig(config, f.dir), options, fetcher)+ ? runGoogleSync(engine, f.id, parseGoogleSourceConfig(config, f.dir), options, withGoogleAccount(fetcher)): runGitHubSync(engine, f.id, parseGitHubSourceConfig(config, f.dir), { ...options, githubItem: { repo: 'acme-example/app', number: 1, kind: 'issue' } }, fetcher);await run();const slug = connector === 'google' ? 'people/first-example' : 'gh/acme-example/app/1';@@ -380,7 +379,7 @@ test('a file edit after bound connector admission survives resident replay and pconst checkpoint = await sourceCheckpoint(engine, f.id);await engine.executeRaw("UPDATE persistence_worktrees SET state='draining' WHERE id=$1::uuid", [f.binding.worktree_id]);body = 'New API body';- await expect(run()).rejects.toMatchObject({ code: 'write_pending' });+ expect(await run()).toMatchObject({ status: 'partial', reason: 'writer_pending' });const [accepted] = await engine.executeRaw<WriteRequest>("SELECT * FROM persistence_requests WHERE source_id=$1 AND state='queued' ORDER BY sequence LIMIT 1", [f.id]);await disposePersistenceConsumer(engine);const path = join(f.dir, 'gh/acme-example/app/1.md');@@ -404,13 +403,13 @@ test('competing Google sweeps CAS their checkpoints instead of skipping each othlet entered!: () => void;const firstFetch = new Promise<void>(resolve => { entered = resolve; });const both = new Promise<void>(resolve => { release = resolve; });- const run = (token: string) => runGoogleSync(engine, f.id, cfg, options, async url => {+ const run = (token: string) => runGoogleSync(engine, f.id, cfg, options, withGoogleAccount(async url => {if (url.includes('/settings/sendAs')) return json({ sendAs: [] });arrived++;entered();await both;return json({ connections: [contact(token, `${token} Example`)], nextSyncToken: token });- });+ }));const first = run('first');await firstFetch;const second = run('second');@@ -433,7 +432,7 @@ test('resident publication revalidates accepted connector revisions, incarnationconst binding = await claimWorktree(engine, f.id, f.dir);await engine.executeRaw("UPDATE persistence_worktrees SET state='draining' WHERE id=$1::uuid", [binding.worktree_id]);await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');- await expect(runGitHubSync(engine, f.id, parseGitHubSourceConfig(githubConfig, f.dir), options, githubFetch())).rejects.toMatchObject({ code: 'write_pending' });+ expect(await runGitHubSync(engine, f.id, parseGitHubSourceConfig(githubConfig, f.dir), options, githubFetch())).toMatchObject({ status: 'partial', reason: 'writer_pending' });const [accepted] = await engine.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE source_id=$1', [f.id]);await disposePersistenceConsumer(engine);const [writer] = await engine.executeRaw<{ grant_ceiling: unknown }>('SELECT grant_ceiling FROM persistence_local_writers WHERE id=$1::uuid', [accepted.principal_id]);@@ -480,7 +479,7 @@ test('aged live connector cursors survive actual checkpoint purge and normal increturn json({ connections: [contact('first', 'First Example')], nextSyncToken: 'retained-contacts-cursor' });};const run = () => connector === 'google'- ? runGoogleSync(engine, f.id, parseGoogleSourceConfig(config, f.dir), options, fetcher)+ ? runGoogleSync(engine, f.id, parseGoogleSourceConfig(config, f.dir), options, withGoogleAccount(fetcher)): runGitHubSync(engine, f.id, parseGitHubSourceConfig(config, f.dir), options, fetcher);await run();await disposePersistenceConsumer(engine);diff --git a/test/persistence-diagnostics.test.ts b/test/persistence-diagnostics.test.tsindex 3d1c5dc7b1..39a59eed95 100644--- a/test/persistence-diagnostics.test.ts+++ b/test/persistence-diagnostics.test.ts@@ -97,14 +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(LATEST_VERSION).toBe(175);- expect(await runMigrations(engine)).toEqual({ applied: 11, current: 175 });+ expect(LATEST_VERSION).toBe(178);+ expect(await runMigrations(engine)).toEqual({ applied: 14, current: 178 });const [upgraded] = await engine.executeRaw<{ indexdef: string }>("SELECT indexdef FROM pg_indexes WHERE indexname='persistence_requests_database_pending'");expect(upgraded.indexdef).toBe(fresh.indexdef);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('175');+ expect(await engine.getConfig('version')).toBe('178');}}, 15000);diff --git a/test/persistence-git-coalescing-5530.slow.test.ts b/test/persistence-git-coalescing-5530.slow.test.tsnew file mode 100644index 0000000000..2c284fb3b4--- /dev/null+++ b/test/persistence-git-coalescing-5530.slow.test.ts@@ -0,0 +1,282 @@+/**+ * #5530: the effect runner coalesces ready single-file Git effects.+ *+ * The v0.13.1 grandfather step admits one put_page per page; before this fix+ * every page's Git effect made its own `git commit` and its own synchronous+ * `git push`. The runner now claims up to 100 ready single-file Git effects+ * for the same worktree, validates each path under the worktree lock, makes+ * one `commit --only` per group and pushes each root once per pass. A path+ * failure fails only its own effect; a failed push leaves the group+ * retryable and the next pass pushes once.+ *+ * Git effects are held back ("effect worker paused") with a future+ * `next_attempt_at` default, then released and drained with one explicit+ * runner pass, so commit and push counts are deterministic. Pushes are+ * counted by a pre-receive hook on the local bare remote.+ *+ * PGLite here; Postgres through test/e2e/persistence-git-coalescing-5530-postgres.test.ts.+ */+import { describe, expect, test } from 'bun:test';+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { 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 { admitCanonicalGrandfather } from '../src/core/persistence/grandfather.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 { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { runPersistenceEffects } from '../src/core/persistence/effects.ts';+import { localHostId } from '../src/core/persistence/identity.ts';+import { declarePersistenceProtocol } from '../src/core/persistence/protocol.ts';+import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';+import { testBackends } from './helpers/test-backends.ts';+import { withEnv } from './helpers/with-env.ts';++const HOOK = '#!/bin/sh\n# gbrain brain-durability post-commit hook (v0.42.44+)\n';++function git(root: string, ...args: string[]): string {+ const result = Bun.spawnSync(['git', '-C', root, ...args]);+ if (result.exitCode) throw new Error(`git ${args.join(' ')}: ${result.stderr.toString()}`);+ return result.stdout.toString();+}++interface Repo { root: string; remote: string; pushes: () => number; rejectPushes: (on: boolean) => void; commits: () => number }++function makeRepo(home: string, name: string): Repo {+ const root = join(home, name), remote = join(home, `${name}.git`), log = join(home, `${name}.pushes`), reject = join(home, `${name}.reject`);+ mkdirSync(root); mkdirSync(remote);+ git(root, 'init', '-q', '-b', 'main');+ git(root, 'config', 'user.name', 'Example Writer');+ git(root, 'config', 'user.email', '[email protected]');+ writeFileSync(join(root, 'README.md'), `${name}\n`);+ git(root, 'add', 'README.md'); git(root, 'commit', '-q', '-m', 'Initial');+ git(remote, 'init', '-q', '--bare');+ git(root, 'remote', 'add', 'origin', remote); git(root, 'push', '-q', '-u', 'origin', 'main');+ const preReceive = join(remote, 'hooks', 'pre-receive');+ writeFileSync(preReceive, `#!/bin/sh\necho push >> '${log}'\n[ -f '${reject}' ] && exit 1\nexit 0\n`);+ chmodSync(preReceive, 0o755);+ return {+ root, remote,+ pushes: () => existsSync(log) ? readFileSync(log, 'utf8').trim().split('\n').filter(Boolean).length : 0,+ rejectPushes: on => { if (on) writeFileSync(reject, ''); else rmSync(reject, { force: true }); },+ commits: () => Number(git(root, 'rev-list', '--count', 'HEAD').trim()),+ };+}++function harden(repo: Repo): void {+ git(repo.root, 'add', '-A'); git(repo.root, 'commit', '-q', '-m', 'Seed', '--allow-empty'); git(repo.root, 'push', '-q');+ rmSync(join(repo.remote, '..', `${repo.root.split('/').pop()}.pushes`), { force: true });+ const hook = join(repo.root, '.git', 'hooks', 'post-commit');+ writeFileSync(hook, HOOK); chmodSync(hook, 0o755);+}++const pageContent = (i: number, note = '') => `---\ntype: note\ntitle: Page ${i}\n---\n\nCoalescing page ${i}.${note}\n`;++async function withBrain(kind: 'pglite' | 'postgres', run: (b: { engine: BrainEngine; home: string; ctx: (source: string) => OperationContext }) => Promise<void>) {+ const home = realpathSync.native(mkdtempSync(join(tmpdir(), 'gbrain-coalesce-5530-')));+ try {+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {+ const { engine, close } = await isolatedSharedSkillsEngine(kind === 'postgres' ? process.env.GBRAIN_TEST_COALESCE_PG! : undefined);+ try {+ const ctx = (source: string) => ({ engine, config: { engine: engine.kind, embedding_disabled: true }, sourceId: source,+ remote: false, dryRun: false, logger: { info() {}, warn() {}, error() {} } }) as OperationContext;+ await run({ engine, home, ctx });+ } finally { await disposePersistenceConsumer(engine); await close(); }+ });+ } finally { rmSync(home, { recursive: true, force: true }); }+}++async function bindSource(engine: BrainEngine, source: string, repo: Repo): Promise<void> {+ if (source !== 'default') await engine.executeRaw('INSERT INTO sources (id, name, local_path) VALUES ($1, $1, $2)', [source, repo.root]);+ else await engine.executeRaw("UPDATE sources SET local_path=$1 WHERE id='default'", [repo.root]);+ await claimWorktree(engine, source, repo.root, localHostId());+}++async function seed(ctx: OperationContext, count: number, offset = 0): Promise<void> {+ for (let i = offset; i < offset + count; i++) {+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug: `notes/page-${String(i).padStart(4, '0')}`, request_id: randomUUID(), content: pageContent(i) } });+ }+}++async function pauseGitEffects<T>(engine: BrainEngine, run: () => Promise<T>): Promise<T> {+ await engine.executeRaw("ALTER TABLE persistence_effects ALTER COLUMN next_attempt_at SET DEFAULT (now()+interval '1 hour')");+ try { return await run(); } finally {+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('ALTER TABLE persistence_effects ALTER COLUMN next_attempt_at SET DEFAULT now()');+ }+}++const effectSql = (engine: BrainEngine, sql: string, params: unknown[] = []) =>+ engine.transaction(async tx => { await declarePersistenceProtocol(tx); await tx.executeRaw(sql, params); });+const release = (engine: BrainEngine) => effectSql(engine, "UPDATE persistence_effects SET next_attempt_at=now() WHERE kind='git' AND state='queued'");+const pass = (engine: BrainEngine) => runPersistenceEffects(engine, { engine: engine.kind, embedding_disabled: true } as never, { hostId: localHostId(), limit: 20 });+const gitStates = async (engine: BrainEngine) => Object.fromEntries((await engine.executeRaw<{ state: string; n: number }>(+ "SELECT state, count(*)::int AS n FROM persistence_effects WHERE kind='git' GROUP BY state ORDER BY state")).map(r => [r.state, Number(r.n)]));++const PAGES = Number(process.env.GBRAIN_TEST_COALESCE_PAGES ?? 250);++for (const kind of testBackends()) describe(`#5530 Git effect coalescing (${kind})`, () => {+ if (kind === 'postgres') process.env.GBRAIN_TEST_COALESCE_PG ??= process.env.DATABASE_URL;++ test(`${PAGES} grandfathered pages give ${Math.ceil(PAGES / 100)} commits and 1 push; an interleaved write still completes`, () => withBrain(kind, async ({ engine, home, ctx }) => {+ const repo = makeRepo(home, 'content');+ await bindSource(engine, 'default', repo);+ await activateSharedSkillPersistence(engine, { confirmQuiesced: true });+ await seed(ctx('default'), PAGES - 1);+ await disposePersistenceConsumer(engine);+ harden(repo);+ const commitsBefore = repo.commits();+ await pauseGitEffects(engine, async () => {+ const result = await phaseCGrandfather(engine, { yes: true, dryRun: false, noAutopilotInstall: true } as never);+ expect(result.detail).toMatchObject({ touched: PAGES - 1, failed: 0 });+ // An ordinary write on the same source publishes while the grandfather's Git work is still pending.+ const ordinary = await submitPageMutation(ctx('default'), { operation: 'put_page', params: { slug: 'notes/ordinary', request_id: randomUUID(), content: pageContent(9999) } }) as { state?: string };+ expect(ordinary.state).toBe('committed');+ });+ expect(await gitStates(engine)).toMatchObject({ queued: PAGES });+ await release(engine);+ await pass(engine);+ expect(await gitStates(engine)).toEqual({ committed: PAGES + (PAGES - 1) });+ expect(repo.commits() - commitsBefore).toBe(Math.ceil(PAGES / 100));+ expect(repo.pushes()).toBe(1);+ expect(git(repo.remote, 'rev-parse', 'main').trim()).toBe(git(repo.root, 'rev-parse', 'HEAD').trim());+ expect(git(repo.root, 'status', '--porcelain').trim()).toBe('');+ }), 900_000);++ test('two sources commit separately and push once each', () => withBrain(kind, async ({ engine, home, ctx }) => {+ const a = makeRepo(home, 'alpha'), b = makeRepo(home, 'beta');+ await bindSource(engine, 'default', a);+ await bindSource(engine, 'beta', b);+ await activateSharedSkillPersistence(engine, { confirmQuiesced: true });+ harden(a); harden(b);+ const [ca, cb] = [a.commits(), b.commits()];+ await pauseGitEffects(engine, async () => { await seed(ctx('default'), 5); await seed(ctx('beta'), 7, 100); });+ await release(engine);+ await pass(engine);+ expect(await gitStates(engine)).toMatchObject({ committed: 12 });+ expect([a.commits() - ca, b.commits() - cb]).toEqual([1, 1]);+ expect([a.pushes(), b.pushes()]).toEqual([1, 1]);+ }), 300_000);++ test('a failed push leaves the group retryable and the next pass pushes once', () => withBrain(kind, async ({ engine, home, ctx }) => {+ const repo = makeRepo(home, 'content');+ await bindSource(engine, 'default', repo);+ await activateSharedSkillPersistence(engine, { confirmQuiesced: true });+ harden(repo);+ const commitsBefore = repo.commits();+ await pauseGitEffects(engine, () => seed(ctx('default'), 6));+ repo.rejectPushes(true);+ await release(engine);+ await pass(engine);+ expect(repo.commits() - commitsBefore).toBe(1);+ expect(repo.pushes()).toBe(1);+ expect(await gitStates(engine)).toEqual({ queued: 6 });+ expect(new Set((await engine.executeRaw<{ error_code: string }>("SELECT error_code FROM persistence_effects WHERE kind='git'")).map(r => r.error_code)))+ .toEqual(new Set(['git_push_unavailable']));+ repo.rejectPushes(false);+ await release(engine);+ await pass(engine);+ expect(await gitStates(engine)).toEqual({ committed: 6 });+ expect(repo.commits() - commitsBefore).toBe(1);+ expect(repo.pushes()).toBe(2);+ expect(git(repo.remote, 'rev-parse', 'main').trim()).toBe(git(repo.root, 'rev-parse', 'HEAD').trim());+ }), 300_000);++ test('one unsafe path fails only its own effect; the rest of the group commits', () => withBrain(kind, async ({ engine, home, ctx }) => {+ const repo = makeRepo(home, 'content');+ await bindSource(engine, 'default', repo);+ await activateSharedSkillPersistence(engine, { confirmQuiesced: true });+ harden(repo);+ const commitsBefore = repo.commits();+ await pauseGitEffects(engine, () => seed(ctx('default'), 10));+ await effectSql(engine, `UPDATE persistence_effects SET data=jsonb_set(data,'{relative_path}','"../outside.md"')+ WHERE id=(SELECT id FROM persistence_effects WHERE kind='git' ORDER BY id LIMIT 1 OFFSET 4)`);+ await release(engine);+ await pass(engine);+ expect(await gitStates(engine)).toEqual({ committed: 9, queued: 1 });+ expect(repo.commits() - commitsBefore).toBe(1);+ expect(git(repo.root, 'show', '--name-only', '--format=', 'HEAD').trim().split('\n')).toHaveLength(9);+ expect(repo.pushes()).toBe(1);+ }), 300_000);++ test('a Git effect waits for its request\'s withdrawal mirror and is never coalesced ahead of it', () => withBrain(kind, async ({ engine, home, ctx }) => {+ const repo = makeRepo(home, 'content');+ await bindSource(engine, 'default', repo);+ await activateSharedSkillPersistence(engine, { confirmQuiesced: true });+ harden(repo);+ await pauseGitEffects(engine, () => seed(ctx('default'), 4));+ const [held] = await engine.executeRaw<{ request_id: string; source_id: string; source_incarnation: string; worktree_id: string }>(+ "SELECT request_id, source_id, source_incarnation, worktree_id FROM persistence_effects WHERE kind='git' ORDER BY id DESC LIMIT 1");+ await effectSql(engine, `INSERT INTO persistence_effects (request_id,kind,data,source_id,source_incarnation,worktree_id,next_attempt_at)+ VALUES ($1::uuid,'withdrawal-mirror','{}'::jsonb,$2,$3::uuid,$4::uuid,now()+interval '1 hour')`, [held.request_id, held.source_id, held.source_incarnation, held.worktree_id]);+ await release(engine);+ await pass(engine);+ expect(await gitStates(engine)).toEqual({ committed: 3, queued: 1 });+ expect(await engine.executeRaw("SELECT state FROM persistence_effects WHERE kind='git' AND request_id=$1::uuid", [held.request_id])).toEqual([{ state: 'queued' }]);+ }), 300_000);+ test('a short group yields to a queued publication on its worktree, within a bounded number of claims', () => withBrain(kind, async ({ engine, home, ctx }) => {+ const repo = makeRepo(home, 'content');+ await bindSource(engine, 'default', repo);+ await activateSharedSkillPersistence(engine, { confirmQuiesced: true });+ await seed(ctx('default'), 1, 500);+ await disposePersistenceConsumer(engine);+ harden(repo);+ await pauseGitEffects(engine, () => seed(ctx('default'), 3));+ const commitsBefore = repo.commits();+ const [target] = await engine.executeRaw<{ id: number; slug: string; source_id: string; source_incarnation: string }>(+ "SELECT p.id,p.slug,p.source_id,s.incarnation AS source_incarnation FROM pages p JOIN sources s ON s.id=p.source_id WHERE p.slug='notes/page-0500'");+ // Admitted and not yet published: the publication is queued for the same worktree.+ const admitted = await admitCanonicalGrandfather(engine, target!, () => {});+ expect(admitted.status).toBe('admitted');+ await release(engine);+ await pass(engine);+ expect(repo.commits()).toBe(commitsBefore);+ expect(await engine.executeRaw("SELECT DISTINCT state, error_code FROM persistence_effects WHERE kind='git' AND state<>'committed'"))+ .toEqual([{ state: 'queued', error_code: 'publication_pending' }]);+ // The yield is bounded: past the claim budget the group commits even with the publication still queued.+ await effectSql(engine, "UPDATE persistence_effects SET attempts=21 WHERE kind='git' AND state='queued'");+ await release(engine);+ await pass(engine);+ expect(repo.commits() - commitsBefore).toBe(1);+ expect(await gitStates(engine)).toEqual({ committed: 4 });+ if (admitted.status === 'admitted') expect((await admitted.complete()).revision).toBeTruthy();+ }), 300_000);+ test('sources sharing one worktree are each validated against their own binding', () => withBrain(kind, async ({ engine, home, ctx }) => {+ const repo = makeRepo(home, 'content');+ mkdirSync(join(repo.root, 'nested'));+ await bindSource(engine, 'default', repo);+ await engine.executeRaw("INSERT INTO sources (id, name, local_path) VALUES ('nested', 'nested', $1)", [join(repo.root, 'nested')]);+ await claimWorktree(engine, 'nested', join(repo.root, 'nested'), localHostId());+ await activateSharedSkillPersistence(engine, { confirmQuiesced: true });+ const [shared] = await engine.executeRaw<{ n: number }>('SELECT count(DISTINCT worktree_id)::int AS n FROM persistence_source_bindings');+ expect(Number(shared!.n)).toBe(1);+ harden(repo);+ const commitsBefore = repo.commits();+ // The nested source's effect is claimed first, so it seeds the group.+ await pauseGitEffects(engine, async () => { await seed(ctx('nested'), 2, 700); await seed(ctx('default'), 3); });+ await release(engine);+ await pass(engine);+ expect(await gitStates(engine)).toEqual({ committed: 5 });+ expect(repo.commits() - commitsBefore).toBe(1);+ expect(git(repo.root, 'show', '--name-only', '--format=', 'HEAD').trim().split('\n').sort())+ .toEqual(['nested/notes/page-0700.md', 'nested/notes/page-0701.md', 'notes/page-0000.md', 'notes/page-0001.md', 'notes/page-0002.md']);+ }), 300_000);+ test('without the durability hook, coalesced siblings of a shared worktree record their own outcome', () => withBrain(kind, async ({ engine, home, ctx }) => {+ const repo = makeRepo(home, 'content');+ mkdirSync(join(repo.root, 'nested'));+ await bindSource(engine, 'default', repo);+ await engine.executeRaw("INSERT INTO sources (id, name, local_path) VALUES ('nested', 'nested', $1)", [join(repo.root, 'nested')]);+ await claimWorktree(engine, 'nested', join(repo.root, 'nested'), localHostId());+ await activateSharedSkillPersistence(engine, { confirmQuiesced: true });+ await pauseGitEffects(engine, async () => { await seed(ctx('nested'), 2, 700); await seed(ctx('default'), 3); });+ await release(engine);+ await pass(engine);+ expect(await gitStates(engine)).toEqual({ committed: 5 });+ expect(new Set((await engine.executeRaw<{ reason: string }>("SELECT outcome->>'reason' AS reason FROM persistence_effects WHERE kind='git'")).map(r => r.reason)))+ .toEqual(new Set(['durability_not_enabled']));+ }), 300_000);+});diff --git a/test/persistence-internal-callers.test.ts b/test/persistence-internal-callers.test.tsindex fd8f8d0585..ba0ed166ce 100644--- a/test/persistence-internal-callers.test.ts+++ b/test/persistence-internal-callers.test.ts@@ -3,8 +3,6 @@ import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { operationsByName } from '../src/core/operations.ts';import { prepareBookMirrorPublication } from '../src/commands/book-mirror.ts';import { retainToolWriteRequestId } from '../src/core/minions/tool-write-identity.ts';-import { verifyWorkspace } from '../src/core/bootstrap/verify.ts';-import type { BrainEngine } from '../src/core/engine.ts';let engine: PGLiteEngine;beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 60_000);@@ -48,10 +46,3 @@ test('replayed persisted tool execution returns its original canonical receipt',retainToolWriteRequestId(later, 42, 5, 0, 'provider-reused-id', 'brain_put_page');expect(later.request_id).not.toBe(first.request_id);});--test('unsupported bootstrap maintenance stops before providers or filesystem probes', async () => {- let queries = 0;- const guarded = { executeRaw: async () => { queries++; return [{ enabled: true }]; } } as unknown as BrainEngine;- await expect(verifyWorkspace(guarded, '/nonexistent-synthetic-fixture')).rejects.toMatchObject({ code: 'writer_coordinator_required' });- expect(queries).toBe(1);-});diff --git a/test/persistence-onboarding.test.ts b/test/persistence-onboarding.test.tsindex 10e4b08172..bfef6be068 100644--- a/test/persistence-onboarding.test.ts+++ b/test/persistence-onboarding.test.ts@@ -8,7 +8,7 @@ import type { BrainEngine } from '../src/core/engine.ts';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { dispatchToolCall } from '../src/mcp/dispatch.ts';import { performSync } from '../src/commands/sync.ts';-import { runPersistenceAdministration } from '../src/core/persistence/administration.ts';+import { CLAIM_BEFORE_ACTIVATION_NOTICE, runPersistenceAdministration } from '../src/core/persistence/administration.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';import { persistenceHome } from '../src/core/persistence/identity.ts';import { PHYSICAL_ROOT_MARKER } from '../src/core/persistence/physical-root-record.ts';@@ -17,6 +17,7 @@ import { testBackends } from './helpers/test-backends.ts';import { reviewedWriterIntent } from './helpers/writer-admin-intent.ts';import { withEnv } from './helpers/with-env.ts';import { makeGitFixture } from './helpers/git-fixture.ts';+import { loadActivationPendingSourceIds } from '../src/core/sync-policy.ts';for (const kind of testBackends()) describe(`deliberate onboarding (${kind})`, () => {let engine: BrainEngine, close: (() => Promise<void>) | undefined;@@ -34,6 +35,8 @@ for (const kind of testBackends()) describe(`deliberate onboarding (${kind})`, (expect(status.onboarding.sources).toContainEqual(expect.objectContaining({ source_id: 'default', state: 'claim_required' }));expect(existsSync(join(persistenceHome(), 'host.json'))).toBe(false);expect(existsSync(join(root, PHYSICAL_ROOT_MARKER))).toBe(false);+ // #5198: autopilot's skip set tracks exactly the window in which sync refuses.+ expect(await loadActivationPendingSourceIds(engine)).toEqual(new Set());const write = () => dispatchToolCall(engine, 'put_page', { slug: 'onboarding-note', content: '---\ntitle: Onboarding example\ntype: note\n---\nA durable example.\n', request_id: randomUUID() }, { remote: false, sourceId: 'default', config: { engine: kind, embedding_disabled: true } });if (kind === 'postgres') {const refused = await write(); expect(refused.isError).toBe(true);@@ -41,10 +44,15 @@ for (const kind of testBackends()) describe(`deliberate onboarding (${kind})`, (expect(await engine.getPage('onboarding-note', { sourceId: 'default' })).toBeNull();expect(existsSync(join(root, PHYSICAL_ROOT_MARKER))).toBe(false);}- await runPersistenceAdministration(engine, 'writer_claim', { source_id: 'default', path: root, ...await reviewedWriterIntent(engine, 'writer_claim') });+ // #5198: the claim states what it fences, in the dry run and in the result.+ const claimPreview = await runPersistenceAdministration(engine, 'writer_claim', { source_id: 'default', path: root, dry_run: true }) as any;+ expect(claimPreview.activation_required).toBe(CLAIM_BEFORE_ACTIVATION_NOTICE);+ const claim = await runPersistenceAdministration(engine, 'writer_claim', { source_id: 'default', path: root, ...await reviewedWriterIntent(engine, 'writer_claim') }) as any;+ expect(claim).toMatchObject({ claimed: true, activation_required: CLAIM_BEFORE_ACTIVATION_NOTICE });const claimed = await runPersistenceAdministration(engine, 'writer_status', {}) as any;expect(claimed.onboarding.sources).toContainEqual(expect.objectContaining({ source_id: 'default', state: 'activation_required' }));await expect(performSync(engine, { sourceId: 'default', noEmbed: true, noPull: true })).rejects.toThrow();+ expect(await loadActivationPendingSourceIds(engine)).toEqual(new Set(['default']));const activate = async (params: Record<string, unknown> = {}) => runPersistenceAdministration(engine, 'writer_activate', {confirm_quiesced: true, ...params, ...await reviewedWriterIntent(engine, 'writer_activate'),});@@ -69,6 +77,8 @@ for (const kind of testBackends()) describe(`deliberate onboarding (${kind})`, (await engine.executeRaw('UPDATE gbrain_cycle_locks SET acquisition_token=$1::uuid', [randomUUID()]);await expect(runPersistenceAdministration(engine, 'writer_activate', { confirm_quiesced: true, cleanup_dead_local_locks: true, ...stale })).rejects.toMatchObject({ code: 'writer_admin_state_changed' });expect(await activate({ cleanup_dead_local_locks: true })).toMatchObject({ activated: true });+ expect(await runPersistenceAdministration(engine, 'writer_claim', { source_id: 'default', path: root, dry_run: true })).not.toHaveProperty('activation_required');+ expect(await loadActivationPendingSourceIds(engine)).toEqual(new Set());expect(await engine.executeRaw('SELECT id FROM gbrain_cycle_locks')).toEqual([]);const ready = await runPersistenceAdministration(engine, 'writer_status', {}) as any;expect(ready.onboarding.sources).toContainEqual(expect.objectContaining({ source_id: 'default', state: 'ready' }));diff --git a/test/persistence-physical-root-device.test.ts b/test/persistence-physical-root-device.test.tsindex 2517cb9b0c..2a49009a34 100644--- a/test/persistence-physical-root-device.test.ts+++ b/test/persistence-physical-root-device.test.ts@@ -1,6 +1,6 @@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 { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import type { BrainEngine } from '../src/core/engine.ts';@@ -41,7 +41,8 @@ test('device-only change is recognized only with a non-zero matching birth time});for (const kind of testBackends()) describe(`physical root device change (${kind})`, () => {- const directory = mkdtempSync(join(tmpdir(), 'gbrain-root-device-'));+ // The canonical root is the real path: on macOS the temporary directory sits behind the /var -> /private/var symlink.+ const directory = realpathSync.native(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!));diff --git a/test/persistence-unbound-source.test.ts b/test/persistence-unbound-source.test.tsnew file mode 100644index 0000000000..749c435a07--- /dev/null+++ b/test/persistence-unbound-source.test.ts@@ -0,0 +1,54 @@+/**+ * #5254 policy parsing and receipt-delivered hints, without a database.+ * Protects: an unreadable persistence.unbound_write keeps refusing (fail+ * closed), and a publication that lost its unbound precondition delivers the+ * unbound_source detail, hint and docs even though the receipt persists only+ * code and message. The Postgres e2e (test/e2e/unbound-source-postgres.test.ts)+ * covers the full lifecycle but runs only in database lanes.+ */+import { describe, expect, test } from 'bun:test';+import { OperationError } from '../src/core/ops/contract.ts';+import { writeResponse } from '../src/core/persistence/service.ts';+import type { WriteRequest } from '../src/core/persistence/model.ts';+import { parseUnboundWriteValue, readUnboundWritePolicy, UNBOUND_PUBLICATION_MESSAGE, UNBOUND_SOURCE_DOCS } from '../src/core/persistence/unbound-source.ts';++describe('persistence.unbound_write', () => {+ test('accepts only refuse and database_only', () => {+ expect(parseUnboundWriteValue('refuse')).toBe('refuse');+ expect(parseUnboundWriteValue('database_only')).toBe('database_only');+ expect(() => parseUnboundWriteValue('Database_Only')).toThrow('persistence.unbound_write must be one of: refuse, database_only');+ });++ test('a missing or unknown stored value keeps refusing', async () => {+ const engine = (value: string | null) => ({ getConfig: async () => value });+ expect(await readUnboundWritePolicy(engine(null))).toBe('refuse');+ expect(await readUnboundWritePolicy(engine('true'))).toBe('refuse');+ expect(await readUnboundWritePolicy(engine('database_only'))).toBe('database_only');+ });+});++describe('receipt-delivered unbound_source failure', () => {+ const row = (error_message: string) => ({+ request_id: '00000000-0000-4000-8000-000000000001', state: 'failed', source_id: 'notes-example',+ error_code: 'owner_unavailable', error_message, created_at: new Date(0), updated_at: new Date(0),+ }) as unknown as WriteRequest;+ const delivered = (message: string): OperationError => {+ try { writeResponse(row(message)); } catch (error) { return error as OperationError; }+ throw new Error('writeResponse did not throw for a failed receipt');+ };++ test('rebuilds detail, filled hint and docs from the persisted message', () => {+ const error = delivered(UNBOUND_PUBLICATION_MESSAGE);+ expect(error.code).toBe('owner_unavailable');+ expect(error.detail).toBe('unbound_source');+ expect(error.docs).toBe(UNBOUND_SOURCE_DOCS);+ expect(error.suggestion).toContain("Source 'notes-example' gained a canonical owner");+ expect(error.suggestion).toContain('new request_id');+ });++ test('leaves other owner_unavailable receipts unchanged', () => {+ const error = delivered('The accepted worktree ownership or source topology changed.');+ expect(error.detail).toBeUndefined();+ expect(error.suggestion).toBe('Inspect this receipt before submitting a new request_id.');+ });+});diff --git a/test/persistence-writer-admin-lock.test.ts b/test/persistence-writer-admin-lock.test.tsnew file mode 100644index 0000000000..d9887dda3f--- /dev/null+++ b/test/persistence-writer-admin-lock.test.ts@@ -0,0 +1,186 @@+import { afterAll, beforeAll, beforeEach, expect, spyOn, test } from 'bun:test';+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';+import { runPersistenceAdministration } from '../src/core/persistence/administration.ts';+import { acceptWriterTransfer, claimWorktree, prepareWriterTransfer } from '../src/core/persistence/ownership.ts';+import { activatePersistence } from '../src/core/persistence/activation.ts';+import { localHostId, registerLocalWriter, withVerifiedLocalRegistration } from '../src/core/persistence/identity.ts';+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { parsePersistenceAdminArgs, WRITER_HELP } from '../src/commands/persistence-admin.ts';+import { runConfig } from '../src/commands/config.ts';+import { dispatchToolCall } from '../src/mcp/dispatch.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { reviewedWriterIntent } from './helpers/writer-admin-intent.ts';+import { withEnv } from './helpers/with-env.ts';++const LOCK_KEY = 'persistence.writer_admin_lock';+let engine: PGLiteEngine;+let schemaVersion: string;+beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ schemaVersion = (await engine.getConfig('version'))!;+});+beforeEach(async () => { await resetPgliteState(engine); await engine.setConfig('version', schemaVersion); });+afterAll(async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); });++async function fixture(run: (root: string) => Promise<void>) {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-admin-lock-'));+ try {+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {+ const root = join(home, 'canonical'); mkdirSync(root);+ writeFileSync(join(root, 'example.md'), 'generic example');+ await engine.executeRaw('UPDATE sources SET local_path=$1 WHERE id=$2', [root, 'default']);+ try { await run(root); } finally { await disposePersistenceConsumer(engine); }+ });+ } finally { rmSync(home, { recursive: true, force: true }); }+}+const lock = () => runPersistenceAdministration(engine, 'writer_lock', {});+const unlock = () => runPersistenceAdministration(engine, 'writer_unlock', {});+const locked = { code: 'writer_admin_locked', docs: 'docs/guides/write-refusals.md#writer_admin_locked' };+async function expectLocked(run: Promise<unknown>) {+ const error = await run.then(() => null, failure => failure as { code: string; suggestion: string; docs: string });+ expect(error).toMatchObject(locked);+ expect(error!.suggestion).toContain('Stop.');+ expect(error!.suggestion).toContain('ask the operator');+ expect(error!.suggestion).toContain('docs/guides/write-refusals.md#writer_admin_locked');+ expect(error!.suggestion).not.toMatch(/unlock/i);+}+async function captureConfig(args: string[]) {+ const errors: string[] = [];+ let exit = null as number | null;+ const errorSpy = spyOn(console, 'error').mockImplementation((...parts: unknown[]) => { errors.push(parts.join(' ')); });+ const logSpy = spyOn(console, 'log').mockImplementation(() => {});+ const exitSpy = spyOn(process, 'exit').mockImplementation(((code?: number) => { exit = code ?? 0; throw new Error(`EXIT:${code}`); }) as never);+ try { await runConfig(engine, args); }+ catch (error) { if (!(error as Error).message.startsWith('EXIT:')) throw error; }+ finally { errorSpy.mockRestore(); logSpy.mockRestore(); exitSpy.mockRestore(); }+ return { errors, exit };+}++test('claim, activate, transfer prepare and accept refuse while locked, for reviewed and internal callers', () => fixture(async root => {+ await lock();+ await expectLocked(runPersistenceAdministration(engine, 'writer_claim', { source_id: 'default', path: root, ...await reviewedWriterIntent(engine, 'writer_claim') }));+ await expectLocked(runPersistenceAdministration(engine, 'writer_claim', { source_id: 'default', path: root, dry_run: true }));+ await expectLocked(claimWorktree(engine, 'default', root));+ expect(await engine.executeRaw('SELECT id FROM persistence_worktrees')).toEqual([]);++ await unlock();+ expect(await runPersistenceAdministration(engine, 'writer_claim', { source_id: 'default', path: root, ...await reviewedWriterIntent(engine, 'writer_claim') }))+ .toMatchObject({ claimed: true, binding: { owner_host_id: localHostId() } });++ await lock();+ await expectLocked(runPersistenceAdministration(engine, 'writer_activate', { confirm_quiesced: true, ...await reviewedWriterIntent(engine, 'writer_activate') }));+ await expectLocked(activatePersistence(engine, { confirmQuiesced: true }));+ expect(await engine.executeRaw('SELECT enabled FROM persistence_brain')).toEqual([{ enabled: false }]);+ await expectLocked(runPersistenceAdministration(engine, 'writer_transfer_prepare', { source_id: 'default', ...await reviewedWriterIntent(engine, 'writer_transfer_prepare') }));+ await expectLocked(prepareWriterTransfer(engine, 'default'));+ expect(await engine.executeRaw('SELECT state,manifest FROM persistence_worktrees')).toEqual([{ state: 'active', manifest: null }]);++ await unlock();+ const prepared = await runPersistenceAdministration(engine, 'writer_transfer_prepare', { source_id: 'default', ...await reviewedWriterIntent(engine, 'writer_transfer_prepare') }) as { owner_epoch: string; manifest: { digest: string } };+ // A lock row written while the transfer was pending (for example by an out-of-band write) still blocks accept.+ await engine.setConfig(LOCK_KEY, JSON.stringify({ locked: true, set_at: new Date().toISOString(), host_id: localHostId(), generation: 9 }));+ const accept = { source_id: 'default', path: root, expected_epoch: prepared.owner_epoch, manifest: prepared.manifest.digest };+ await expectLocked(runPersistenceAdministration(engine, 'writer_transfer_accept', { ...accept, ...await reviewedWriterIntent(engine, 'writer_transfer_accept') }));+ await expectLocked(acceptWriterTransfer(engine, 'default', root, prepared.owner_epoch, prepared.manifest.digest));+ expect(await engine.executeRaw('SELECT state,owner_epoch::text AS owner_epoch FROM persistence_worktrees')).toEqual([{ state: 'draining', owner_epoch: '1' }]);++ expect(await unlock()).toMatchObject({ changed: true, admin_lock: { locked: false, generation: 10 } });+ expect(await runPersistenceAdministration(engine, 'writer_transfer_accept', { ...accept, ...await reviewedWriterIntent(engine, 'writer_transfer_accept') }))+ .toMatchObject({ transferred: true });+ expect(await runPersistenceAdministration(engine, 'writer_activate', { confirm_quiesced: true, ...await reviewedWriterIntent(engine, 'writer_activate') }))+ .toMatchObject({ activated: true });+}), 120_000);++test('lock and unlock are idempotent and writer status reports the lock, selected host and local host id', () => fixture(async () => {+ const before = await runPersistenceAdministration(engine, 'writer_status', {});+ expect(before).toMatchObject({ admin_lock: { locked: false, set_at: null, host_id: null } });+ const first = await lock() as { changed: boolean; admin_lock: { locked: boolean; set_at: string; host_id: string; generation: number } };+ expect(first).toMatchObject({ changed: true, admin_lock: { locked: true, host_id: localHostId(), generation: 1 } });+ expect(Number.isNaN(Date.parse(first.admin_lock.set_at))).toBe(false);+ expect(await lock()).toMatchObject({ changed: false, admin_lock: first.admin_lock });+ const status = await runPersistenceAdministration(engine, 'writer_status', {});+ expect(status).toMatchObject({ local_host_id: localHostId(), admin_lock: { locked: true, set_at: first.admin_lock.set_at, host_id: localHostId() } });+ // The lock is not part of the reviewed topology fingerprint: relocking never invalidates a reviewed state.+ expect(status.admin_state).toBe(before.admin_state);+ expect(await unlock()).toMatchObject({ changed: true, admin_lock: { locked: false, generation: 2 } });+ expect(await unlock()).toMatchObject({ changed: false, admin_lock: { locked: false, generation: 2 } });+ expect(parsePersistenceAdminArgs('writer', ['lock', '--json'])).toMatchObject({ operation: 'writer_lock', json: true });+ expect(parsePersistenceAdminArgs('writer', ['unlock'])).toMatchObject({ operation: 'writer_unlock' });+ await expect(runPersistenceAdministration(engine, 'writer_lock', { force: true })).rejects.toMatchObject({ code: 'invalid_params' });+ for (const phrase of ['claim, activate and transfer', 'ordinary writes continue', 'There is no --force', 'not a security boundary',+ 'Binaries older than this release do not consult the lock']) expect(WRITER_HELP).toContain(phrase);+}), 120_000);++test('lock refuses while a transfer is prepared and not yet accepted', () => fixture(async root => {+ await runPersistenceAdministration(engine, 'writer_claim', { source_id: 'default', path: root, ...await reviewedWriterIntent(engine, 'writer_claim') });+ await runPersistenceAdministration(engine, 'writer_transfer_prepare', { source_id: 'default', ...await reviewedWriterIntent(engine, 'writer_transfer_prepare') });+ await expect(lock()).rejects.toMatchObject({ code: 'writer_transfer_conflict' });+ expect(await engine.getConfig(LOCK_KEY)).toBeNull();+}), 120_000);++test('remote callers can neither lock nor unlock', () => fixture(async () => {+ const stdio = await registerLocalWriter(engine, 'stdio');+ await expect(withVerifiedLocalRegistration(engine, stdio, () => lock())).rejects.toMatchObject({ code: 'permission_denied' });+ await lock();+ await expect(withVerifiedLocalRegistration(engine, stdio, () => unlock())).rejects.toMatchObject({ code: 'permission_denied' });+ for (const name of ['writer_lock', 'writer_unlock']) {+ const remote = await dispatchToolCall(engine, name, {}, { remote: true, sourceId: 'default', config: { engine: 'pglite' } });+ expect(remote.isError).toBe(true);+ expect(JSON.parse(remote.content[0].text)).toMatchObject({ error: 'unknown_tool' });+ }+ expect(JSON.parse((await engine.getConfig(LOCK_KEY))!)).toMatchObject({ locked: true });+}), 120_000);++test('config set, unset and prefix unset refuse the reserved lock key', () => fixture(async () => {+ await lock();+ const value = await engine.getConfig(LOCK_KEY);+ for (const args of [+ ['set', LOCK_KEY, '{"locked":false}'],+ ['set', LOCK_KEY, '{"locked":false}', '--force'],+ ['unset', LOCK_KEY],+ ['unset', '--pattern', 'persistence.'],+ ['unset', '--pattern', 'persistence.writer_admin'],+ ]) {+ const result = await captureConfig(args);+ expect(result.exit).toBe(1);+ expect(result.errors.join('\n')).toContain(`${LOCK_KEY} is reserved`);+ }+ expect(await engine.getConfig(LOCK_KEY)).toBe(value);+ await engine.setConfig('persistence.receipt_retention_days', '30');+ expect((await captureConfig(['unset', '--pattern', 'persistence.receipt'])).exit).toBeNull();+ expect(await engine.getConfig('persistence.receipt_retention_days')).toBeNull();+}), 120_000);++test('the automatic first write to an unbound PGLite source still claims while locked', () => fixture(async root => {+ await lock();+ const ctx: OperationContext = { engine, config: { engine: 'pglite', embedding_disabled: true }, remote: false, dryRun: false,+ sourceId: 'default', logger: { info() {}, warn() {}, error() {} } };+ const receipt = await submitPageMutation(ctx, { operation: 'put_page', params: { slug: 'notes/example', content: '# Generic example' }, waitMs: 10_000 });+ expect(receipt).toMatchObject({ state: 'committed' });+ expect(await engine.executeRaw('SELECT source_id FROM persistence_source_bindings')).toEqual([{ source_id: 'default' }]);++ // Managed persistence: an explicit claim of another source refuses inside the lifecycle transaction,+ // while the ordinary first write to that source still claims it automatically.+ const second = join(root, '..', 'second'); mkdirSync(second);+ await engine.executeRaw("INSERT INTO sources(id,name) VALUES('second-example','Second example')");+ await unlock();+ await runPersistenceAdministration(engine, 'writer_activate', { confirm_quiesced: true, ...await reviewedWriterIntent(engine, 'writer_activate') });+ await engine.transaction(async tx => {+ await tx.executeRaw("SELECT set_config('gbrain.topology_change','on',true)");+ await tx.executeRaw("UPDATE sources SET local_path=$1 WHERE id='second-example'", [second]);+ });+ await lock();+ await expectLocked(claimWorktree(engine, 'second-example', second));+ expect(await engine.executeRaw("SELECT source_id FROM persistence_source_bindings WHERE source_id='second-example'")).toEqual([]);+ const managed = await submitPageMutation({ ...ctx, sourceId: 'second-example' },+ { operation: 'put_page', params: { slug: 'notes/second', content: '# Second example' }, waitMs: 10_000 });+ expect(managed).toMatchObject({ state: 'committed' });+ expect(await engine.executeRaw("SELECT source_id FROM persistence_source_bindings WHERE source_id='second-example'")).toEqual([{ source_id: 'second-example' }]);+}), 120_000);diff --git a/test/persistence-writer-fences.test.ts b/test/persistence-writer-fences.test.tsindex 2b28017a51..9aa008629e 100644--- a/test/persistence-writer-fences.test.ts+++ b/test/persistence-writer-fences.test.ts@@ -10,7 +10,6 @@ import { softDeleteSource, restoreSource, purgeExpiredSources } from '../src/corimport { runGitHubSync } from '../src/core/github-source.ts';import { runGoogleSync } from '../src/core/google/google-source.ts';import { importFromContent } from '../src/core/import-file.ts';-import { operationsByName } from '../src/core/operations.ts';import { pullRepo, cloneRepo } from '../src/core/git-remote.ts';import { hardenBrainRepo } from '../src/core/brain-repo-durability.ts';import { recordManagedRoots, registeredManagedRoots } from '../src/core/persistence/root-registry.ts';@@ -69,10 +68,6 @@ test('unregistered source lifecycle and unsupported legacy writers refuse before() => runGitHubSync(engine, sourceId, {} as never, {} as never),() => runGoogleSync(engine, sourceId, {} as never, {} as never),() => importFromContent(engine, 'blocked', 'canonical material', { sourceId, noEmbed: true }),- () => operationsByName.add_link!.handler({ engine, sourceId, remote: false, config: { engine: engine.kind }, dryRun: false,- logger: { info() {}, warn() {}, error() {} } }, { from: 'notes/example', to: 'notes/other' }),- () => operationsByName.remove_link!.handler({ engine, sourceId, remote: false, config: { engine: engine.kind }, dryRun: false,- logger: { info() {}, warn() {}, error() {} } }, { from: 'notes/example', to: 'notes/other' }),]) await expect(work()).rejects.toMatchObject({ code: 'writer_coordinator_required' });expect(readFileSync(join(root, 'sentinel.md'), 'utf8')).toBe('canonical sentinel');expect(await engine.executeRaw('SELECT id FROM sources WHERE id=$1', [sourceId])).toHaveLength(1);diff --git a/test/persistence-writer-versions.test.ts b/test/persistence-writer-versions.test.tsnew file mode 100644index 0000000000..ac04058465--- /dev/null+++ b/test/persistence-writer-versions.test.ts@@ -0,0 +1,163 @@+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+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 { VERSION } from '../src/version.ts';+import { localHostId } from '../src/core/persistence/identity.ts';+import { claimNextWrite, compactWriteReceipts, completeWrite } from '../src/core/persistence/journal.ts';+import { declarePersistenceProtocol } from '../src/core/persistence/protocol.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { runPersistenceAdministration } from '../src/core/persistence/administration.ts';+import { compareWriterVersions, UNSTAMPED_WRITER } from '../src/core/persistence/writer-versions.ts';+import { writerVersionCheck } from '../src/commands/doctor/checks/writer-version.ts';+import { editRequest, freshBrainFactory, readRequest, requestFixture } from './helpers/persistence-request-fixture.ts';+import { testBackends } from './helpers/test-backends.ts';+import { withEnv } from './helpers/with-env.ts';++test('versions compare numerically on all four components', () => {+ expect(compareWriterVersions('0.60.10.0', '0.60.5.0')).toBe(1);+ expect(compareWriterVersions('0.60.4.9', '0.60.5.0')).toBe(-1);+ expect(compareWriterVersions('0.60.5.0', '0.60.5')).toBe(0);+ expect(compareWriterVersions('0.60.5.1-fixwave', '0.60.5.0')).toBe(1);+ expect(compareWriterVersions('not-a-version', '0.60.5.0')).toBeNull();+});++const databaseUrl = process.env.DATABASE_URL;+for (const kind of testBackends()) {+ describe(`writer-version stamps ${kind}`, () => {+ let factory: Awaited<ReturnType<typeof freshBrainFactory>>;+ let scratch: string;+ beforeAll(async () => {+ scratch = mkdtempSync(join(tmpdir(), 'gbrain-writer-versions-'));+ factory = await freshBrainFactory(kind, databaseUrl);+ }, 120_000);+ afterAll(async () => {+ await factory?.dispose();+ if (scratch) rmSync(scratch, { recursive: true, force: true });+ });+ const check = (name: string, fn: (engine: BrainEngine) => Promise<void>) => test(name, async () => {+ const engine = await factory.fresh();+ await withEnv({ GBRAIN_HOME: scratch, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, () => fn(engine));+ }, 120_000);++ check('admission stamps the admitter and a replay never rewrites it', async engine => {+ const requests = await requestFixture(engine);+ const requestId = randomUUID();+ const admitted = await requests.admit('page', requestId);+ expect(await readRequest(engine, admitted.id)).toMatchObject({ state: 'queued', admitter_version: VERSION, admitter_host_id: localHostId(),+ consumer_version: null, consumer_host_id: null, published_at: null });+ const other = randomUUID();+ await editRequest(engine, admitted.id, "admitter_version='0.60.9.0',admitter_host_id=$2::uuid", [other]);+ const replayed = await requests.admit('page', requestId);+ expect(replayed.id).toBe(admitted.id);+ expect(await readRequest(engine, admitted.id)).toMatchObject({ admitter_version: '0.60.9.0', admitter_host_id: other });+ });++ check('publication stamps the consumer and published_at; a failed completion does not', async engine => {+ const requests = await requestFixture(engine);+ const published = await requests.publish(await requests.admit('page'));+ const row = await readRequest(engine, published.id);+ expect(row).toMatchObject({ state: 'committed', consumer_version: VERSION, consumer_host_id: localHostId() });+ expect(row.published_at).not.toBeNull();+ expect(new Date(row.published_at as string).getTime()).toBe(new Date(row.completed_at as string).getTime());++ const failing = await requests.admit('failing');+ const claimed = (await claimNextWrite(engine, localHostId()))!;+ expect(claimed.id).toBe(failing.id);+ await engine.transaction(tx => completeWrite(tx, claimed, 'failed', {}, { code: 'storage_error', message: 'generic failure' }));+ expect(await readRequest(engine, failing.id)).toMatchObject({ state: 'failed', admitter_version: VERSION, consumer_version: null, consumer_host_id: null, published_at: null });+ });++ check('receipt compaction keeps the stamps', async engine => {+ const requests = await requestFixture(engine);+ const published = await requests.publish(await requests.admit('page'));+ const before = await readRequest(engine, published.id);+ await engine.transaction(async tx => {+ await declarePersistenceProtocol(tx);+ await tx.executeRaw("UPDATE persistence_effects SET state='committed' WHERE request_id=$1::uuid", [published.id]);+ await tx.executeRaw("UPDATE persistence_requests SET completed_at=now()-interval '3 days' WHERE id=$1::uuid", [published.id]);+ });+ expect(await compactWriteReceipts(engine, 1)).toBe(1);+ const after = await readRequest(engine, published.id);+ expect(after).toMatchObject({ compacted: true, admitter_version: before.admitter_version, admitter_host_id: before.admitter_host_id,+ consumer_version: before.consumer_version, consumer_host_id: before.consumer_host_id });+ expect(new Date(after.published_at as string).getTime()).toBe(new Date(before.published_at as string).getTime());+ });++ check('doctor: a pending request raises no warning and stamped current writers are ok', async engine => {+ const requests = await requestFixture(engine);+ await requests.publish(await requests.admit('published'));+ await requests.admit('pending');+ const result = await writerVersionCheck(engine);+ expect(result).toMatchObject({ name: 'writer_version', status: 'ok', details: { count: 0, truncated: false, hosts: [] } });+ expect((result.details!.observed as unknown[]).length).toBeGreaterThan(0);+ await editRequest(engine, (await requests.admit('unstamped-pending')).id, 'admitter_version=NULL,admitter_host_id=NULL');+ expect((await writerVersionCheck(engine)).status).toBe('ok');+ });++ check('doctor: an unstamped published request inside 7 days warns with the host UUID; outside the window it does not', async engine => {+ const root = join(scratch, `canonical-${randomUUID()}`); mkdirSync(root);+ await engine.executeRaw("UPDATE sources SET local_path=$1 WHERE id='default'", [root]);+ const binding = await claimWorktree(engine, 'default', root);+ const requests = await requestFixture(engine, 'default');+ const admitted = await requests.admit('notes/unstamped', randomUUID(), binding);+ // An older binary admits and publishes without stamps.+ await editRequest(engine, admitted.id, "state='committed',completed_at=now(),admitter_version=NULL,admitter_host_id=NULL");+ const warned = await writerVersionCheck(engine);+ expect(warned.status).toBe('warn');+ expect(warned.message).toContain(`host ${localHostId()}`);+ expect(warned.message).toContain(`principal ${admitted.principal_kind}:${admitted.principal_id}`);+ expect(warned.message).toContain(UNSTAMPED_WRITER);+ expect(warned.message).toContain('A writer older than v0.60.5.0 may still delete database-only timeline rows');+ expect(warned.message).toContain('Run `gbrain upgrade` on that host');+ expect(warned.message).toContain('observation, not prevention');+ expect(warned.details).toMatchObject({ count: 2, truncated: false });+ expect(warned.details!.hosts).toContainEqual(expect.objectContaining({ host_id: localHostId(), role: 'consumer', consumer_version: UNSTAMPED_WRITER }));+ expect(warned.details!.hosts).toContainEqual(expect.objectContaining({ host_id: null, role: 'admitter', admitter_version: UNSTAMPED_WRITER }));++ await editRequest(engine, admitted.id, "completed_at=now()-interval '8 days',created_at=now()-interval '8 days'");+ expect(await writerVersionCheck(engine)).toMatchObject({ status: 'ok', details: { count: 0 } });+ // Older rows stay visible in writer status.+ const status = await runPersistenceAdministration(engine, 'writer_status', {});+ expect(status.local_host_id).toBe(localHostId());+ expect(status.writer_versions).toContainEqual(expect.objectContaining({ role: 'consumer', host_id: null, version: null, version_label: UNSTAMPED_WRITER,+ principal: `${admitted.principal_kind}:${admitted.principal_id}` }));+ });++ check('doctor: a request admitted before the cutoff and published after it is judged by its publication', async engine => {+ const requests = await requestFixture(engine);+ const admitted = await requests.admit('straddle');+ const published = await requests.publish(admitted);+ await editRequest(engine, published.id, `admitter_version=NULL,admitter_host_id=NULL,+ created_at=(SELECT writer_version_cutoff FROM persistence_brain WHERE singleton=1)-interval '1 hour'`);+ expect(await writerVersionCheck(engine)).toMatchObject({ status: 'ok', details: { count: 0 } });+ await editRequest(engine, published.id, 'consumer_version=NULL,consumer_host_id=NULL,published_at=NULL');+ const warned = await writerVersionCheck(engine);+ expect(warned).toMatchObject({ status: 'warn', details: { count: 1 } });+ expect(warned.details!.hosts).toEqual([expect.objectContaining({ role: 'consumer', consumer_version: UNSTAMPED_WRITER })]);+ });++ check('doctor: a recorded version older than v0.60.5.0 warns and newer ones compare numerically', async engine => {+ const requests = await requestFixture(engine);+ const published = await requests.publish(await requests.admit('old-writer'));+ await editRequest(engine, published.id, "consumer_version='0.60.10.0',admitter_version='0.60.5.0'");+ expect((await writerVersionCheck(engine)).status).toBe('ok');+ await editRequest(engine, published.id, "consumer_version='0.60.4.9'");+ const warned = await writerVersionCheck(engine);+ expect(warned).toMatchObject({ status: 'warn', details: { count: 1 } });+ expect(warned.details!.hosts).toEqual([expect.objectContaining({ host_id: localHostId(), role: 'consumer', consumer_version: '0.60.4.9' })]);+ });++ check('doctor never throws: an unreadable brain reports unknown health', async engine => {+ const broken = new Proxy(engine, { get(target, property) {+ if (property === 'executeRaw') return async () => { throw new Error('simulated read failure'); };+ const value = Reflect.get(target, property); return typeof value === 'function' ? value.bind(target) : value;+ } }) as BrainEngine;+ const result = await writerVersionCheck(broken);+ expect(result).toMatchObject({ name: 'writer_version', status: 'warn', details: { count: 'unknown' } });+ expect(result.message).toContain('Health is unknown');+ });+ });+}diff --git a/test/post-upgrade-banner.test.ts b/test/post-upgrade-banner.test.tsnew file mode 100644index 0000000000..1759d8d7f3--- /dev/null+++ b/test/post-upgrade-banner.test.ts@@ -0,0 +1,45 @@+/**+ * `gbrain post-upgrade` recovery banner (fix wave 3, Lane D): one [AGENT]+ * block on a brain with wave findings, naming the brain, each finding's count+ * and the read-only preview; nothing on a clean brain; never an applying+ * command. The banner runs the full wave checks, not doctor --fast.+ */+import { describe, expect, test } from 'bun:test';+import { readFileSync } from 'node:fs';+import { join } from 'node:path';+import { postUpgradeRecoveryBanner } from '../src/commands/doctor/upgrade-banner.ts';+import { managedBrain } from './helpers/managed-brain.ts';+import { put, waveBrain } from './helpers/wave-fixture.ts';++describe('post-upgrade recovery banner', () => {+ test('a brain with wave findings gets one preview-only [AGENT] banner', async () => {+ await waveBrain(async ({ engine }) => {+ const lines = await postUpgradeRecoveryBanner(engine, 'host (pglite, id test-brain)');+ const text = lines.join('\n');+ expect(lines.filter(l => l.includes('Relay this to your operator'))).toHaveLength(1);+ expect(text).toContain('brain host (pglite, id test-brain)');+ expect(text).toContain('timeline_history: 1 (repairable after the user agrees)');+ expect(text).toContain('self_capture: 1 (needs an operator action)');+ expect(text).toContain('stale_embedding_effects: 1 (reported only; no command clears it yet)');+ expect(text).toContain('Preview (read-only): gbrain doctor --remediation-plan');+ expect(text).toContain('Ask the user before applying');+ expect(text).not.toContain('--yes');+ expect(text).not.toContain('--apply');+ for (const line of lines.filter(Boolean)) expect(line).toStartWith('[AGENT]');+ });+ }, 180_000);++ test('a clean brain prints nothing', async () => {+ await managedBrain(async ({ engine, ctx }) => {+ await put(ctx, 'notes/clean', 'Nothing to repair.');+ expect(await postUpgradeRecoveryBanner(engine, 'host')).toEqual([]);+ });+ }, 180_000);++ test('post-upgrade prints the banner and no longer prints an applying safe-chunk advisory', () => {+ // test-reads-source-ok[structural]: runPostUpgrade needs a configured brain plus a full migration run; this pins that it calls the banner and no longer prints the applying advisory.+ const source = readFileSync(join(import.meta.dir, '..', 'src', 'commands', 'upgrade.ts'), 'utf8');+ expect(source).toContain('postUpgradeRecoveryBanner(engine');+ expect(source).not.toContain('safeChunkUpgradeAdvisory');+ });+});diff --git a/test/reconcile-unbound-collision.test.ts b/test/reconcile-unbound-collision.test.tsnew file mode 100644index 0000000000..142a7b9bc4--- /dev/null+++ b/test/reconcile-unbound-collision.test.ts@@ -0,0 +1,152 @@+/**+ * `gbrain sources reconcile` for a database-only page that collides with a+ * canonical file at its slug-derived path (fix wave 3, Lane D; the #5254+ * unbound_source collision after a source is bound). Preview shows both sides+ * and changes neither; apply writes the chosen resolution through the owner+ * and records the file as the page's origin. PGLite always; Postgres when+ * DATABASE_URL is set.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { execFileSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, readFileSync, 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 { importFromContent } from '../src/core/import-file.ts';+import { parseMarkdown } from '../src/core/markdown.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { registerLocalWriter, withVerifiedLocalRegistration } from '../src/core/persistence/identity.ts';+import { runReconcileApply, runReconcilePreview } from '../src/core/persistence/reconcile.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { withEnv } from './helpers/with-env.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';++const home = mkdtempSync(join(tmpdir(), 'gbrain-reconcile-unbound-'));+const engines: BrainEngine[] = [];+let closePostgres: (() => Promise<void>) | undefined;+beforeAll(async () => {+ if (testBackends().includes('pglite')) { const engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); engines.push(engine); }+ if (testBackends().includes('postgres')) { 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); if (engine.kind === 'pglite') await engine.disconnect(); }+ });+ await closePostgres?.(); rmSync(home, { recursive: true, force: true });+});++const databaseSide = '---\ntype: note\ntitle: Example\ndb_only_field: kept\n---\nWritten while the source had no canonical owner.\n';+const fileSide = '---\ntype: note\ntitle: Example\nfile_field: kept\n---\nWritten into the checkout on another host.\n';++async function collision(engine: BrainEngine, opts: { file?: string; gitSubdir?: boolean; marked?: boolean } = {}) {+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ const id = `unbound-${randomUUID().slice(0, 12)}`;+ // In a Git subfolder source, slugs (and source paths) are Git-root-relative.+ const repo = join(home, id), root = opts.gitSubdir ? join(repo, 'sub') : repo, slug = opts.gitSubdir ? 'sub/notes/example' : 'notes/example';+ mkdirSync(join(root, 'notes'), { recursive: true });+ if (opts.gitSubdir) execFileSync('git', ['init', '-q', repo]);+ await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,\'{}\')', [id, root]);+ // A database-only page: no recorded source path or file origin, as an unbound-source write leaves it.+ await importFromContent(engine, slug, databaseSide, { sourceId: id, noEmbed: true });+ // The durable #5254 marker the unbound publication stamps; reconcile matches only marked pages.+ if (opts.marked !== false) await engine.executeRaw("UPDATE pages SET database_only_reason='unbound_source' WHERE source_id=$1 AND slug=$2", [id, slug]);+ const [page] = await engine.executeRaw<{ source_path: string | null; source_uri: string | null }>('SELECT source_path,source_uri FROM pages WHERE source_id=$1 AND slug=$2', [id, slug]);+ expect(page).toEqual({ source_path: null, source_uri: null });+ // After binding, a canonical file appears at the page's slug-derived path.+ const file = join(root, 'notes/example.md');+ writeFileSync(file, opts.file ?? fileSide);+ await claimWorktree(engine, id, root);+ const registration = await registerLocalWriter(engine, 'cli');+ return { id, slug, file, registration };+}++test('preview accepts a database-only page colliding with a canonical file, changes nothing, and apply resolves it', async () => {+ await withEnv({ GBRAIN_HOME: home, OPENAI_API_KEY: undefined, ANTHROPIC_API_KEY: undefined }, async () => {+ for (const engine of engines) {+ const f = await collision(engine);+ const before = (await engine.readPageSnapshot(f.slug, { sourceId: f.id }))!;+ await withVerifiedLocalRegistration(engine, f.registration, async () => {+ const preview = await runReconcilePreview(engine, { source_id: f.id, slug: f.slug });+ expect(preview.relative_path).toBe('notes/example.md');+ expect(preview.status).toBe('needs_resolution');+ expect(preview.conflict_paths).toContain('/compiled_truth');+ expect(Buffer.from(preview.preview.preimages.file_base64, 'base64').toString()).toBe(fileSide);+ expect(preview.preview.preimages.database.page.compiled_truth).toContain('no canonical owner');+ expect(readFileSync(f.file, 'utf8')).toBe(fileSide);+ expect((await engine.readPageSnapshot(f.slug, { sourceId: f.id }))!.revision).toBe(before.revision);++ const resolved = await runReconcilePreview(engine, { source_id: f.id, slug: f.slug, from: preview.preview,+ decisions: (preview.conflict_paths as string[]).map(path => ({ path, action: 'take_database' })) });+ expect(resolved.status).toBe('ready');+ const receipt = await runReconcileApply(engine, { source_id: f.id, slug: f.slug, preview: resolved.preview, request_id: randomUUID() });+ expect(receipt.state).toBe('committed');+ const current = (await engine.readPageSnapshot(f.slug, { sourceId: f.id }))!;+ expect(current.page.compiled_truth).toContain('no canonical owner');+ expect(current.page.frontmatter).toMatchObject({ db_only_field: 'kept', file_field: 'kept' });+ expect(parseMarkdown(readFileSync(f.file, 'utf8'), f.slug).compiled_truth).toContain('no canonical owner');+ const [page] = await engine.executeRaw<{ source_path: string | null; database_only_reason: string | null }>(+ 'SELECT source_path,database_only_reason FROM pages WHERE source_id=$1 AND slug=$2', [f.id, f.slug]);+ // The page now has a canonical origin, so the unbound_source doctor count no longer reports it.+ expect(page).toEqual({ source_path: 'notes/example.md', database_only_reason: null });+ });+ }+ });+}, 180_000);++test('a page without the durable unbound_source marker is never matched to a slug-derived file', async () => {+ await withEnv({ GBRAIN_HOME: home, OPENAI_API_KEY: undefined, ANTHROPIC_API_KEY: undefined }, async () => {+ for (const engine of engines) {+ const f = await collision(engine, { marked: false });+ await withVerifiedLocalRegistration(engine, f.registration, async () => {+ await expect(runReconcilePreview(engine, { source_id: f.id, slug: f.slug })).rejects.toMatchObject({ code: 'source_changed' });+ });+ expect(readFileSync(f.file, 'utf8')).toBe(fileSide);+ }+ });+}, 180_000);++test('an identical file still becomes the page origin, and a Git subfolder source records the Git-root-relative path', async () => {+ await withEnv({ GBRAIN_HOME: home, OPENAI_API_KEY: undefined, ANTHROPIC_API_KEY: undefined }, async () => {+ for (const engine of engines) {+ for (const opts of [{ file: databaseSide }, { gitSubdir: true, file: databaseSide }]) {+ const f = await collision(engine, opts);+ await withVerifiedLocalRegistration(engine, f.registration, async () => {+ const preview = await runReconcilePreview(engine, { source_id: f.id, slug: f.slug });+ expect(preview.status).toBe('ready');+ const receipt = await runReconcileApply(engine, { source_id: f.id, slug: f.slug, preview: preview.preview, request_id: randomUUID() });+ expect(receipt.state).toBe('committed');+ const [page] = await engine.executeRaw<{ source_path: string | null }>('SELECT source_path FROM pages WHERE source_id=$1 AND slug=$2', [f.id, f.slug]);+ expect(page!.source_path).toBe(opts.gitSubdir ? 'sub/notes/example.md' : 'notes/example.md');+ expect(parseMarkdown(readFileSync(f.file, 'utf8'), f.slug).compiled_truth).toContain('no canonical owner');+ });+ }+ }+ });+}, 180_000);++test('a Git subfolder page never matches a source-relative file whose scanned slug is another page', async () => {+ await withEnv({ GBRAIN_HOME: home, OPENAI_API_KEY: undefined, ANTHROPIC_API_KEY: undefined }, async () => {+ for (const engine of engines) {+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ const id = `unbound-${randomUUID().slice(0, 12)}`, repo = join(home, id), root = join(repo, 'docs');+ mkdirSync(join(root, 'architecture'), { recursive: true });+ execFileSync('git', ['init', '-q', repo]);+ await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,\'{"slug_root_mode":"git-root"}\')', [id, root]);+ // In Git-root mode this file's slug is docs/architecture/topologies, not architecture/topologies.+ await importFromContent(engine, 'architecture/topologies', databaseSide, { sourceId: id, noEmbed: true });+ await engine.executeRaw("UPDATE pages SET database_only_reason='unbound_source' WHERE source_id=$1 AND slug=$2", [id, 'architecture/topologies']);+ writeFileSync(join(root, 'architecture/topologies.md'), fileSide);+ await claimWorktree(engine, id, root);+ const registration = await registerLocalWriter(engine, 'cli');+ await withVerifiedLocalRegistration(engine, registration, async () => {+ await expect(runReconcilePreview(engine, { source_id: id, slug: 'architecture/topologies' })).rejects.toMatchObject({ code: 'source_changed' });+ });+ expect(readFileSync(join(root, 'architecture/topologies.md'), 'utf8')).toBe(fileSide);+ }+ });+}, 180_000);diff --git a/test/recovery-layer.test.ts b/test/recovery-layer.test.tsnew file mode 100644index 0000000000..3a75add676--- /dev/null+++ b/test/recovery-layer.test.ts@@ -0,0 +1,27 @@+/**+ * Recovery layer (fix wave 3, Lane D) on PGLite: remote host-action lines,+ * repair steps in the remediation plan and run, consent, the scripted+ * recovery run's finding classes and exit status, the cumulative budget and+ * resume contract, and the PROTECTED boundary. test/e2e/recovery-layer.test.ts+ * runs the same scenarios on Postgres.+ */+import { describe, test } from 'bun:test';+import {+ budgetAndResumeContract, planListsRepairStepsIndependentOfTarget, remediateWithoutConsentSkipsRepairs,+ remoteCallerCannotRunRepairs, remoteLinesForWaveFindings, scriptedRecoveryRun, swallowedExhaustionIsReported, jobsRecheckedAfterRepairReservations, pendingEmbeddingsResume,+} from './helpers/wave-scenarios.ts';++describe('recovery layer (PGLite)', () => {+ test('remote doctor shows one sanitized host-action line per wave finding, none when clean, unknown when a check cannot run', () => remoteLinesForWaveFindings(), 180_000);+ test('--remediation-plan lists repair steps with commands, independent of the score target', () => planListsRepairStepsIndependentOfTarget(), 180_000);+ test('--remediate --yes without --include-repairs skips repairs and exits non-zero', () => remediateWithoutConsentSkipsRepairs(), 180_000);+ test('scripted recovery run classifies every finding and exits 0', async () => {+ const measured = await scriptedRecoveryRun();+ console.error(`[recovery-run] pglite wall_ms=${measured.wall_ms} operator_commands=${measured.operator_commands}`);+ }, 300_000);+ test('zero budget runs free repairs, refuses the paid one, and resume keeps cap and consent', () => budgetAndResumeContract(), 180_000);+ test('a remote caller cannot run PROTECTED repair steps', () => remoteCallerCannotRunRepairs(), 180_000);+ test('a budget exhaustion a callee swallowed still marks the paid step and refuses later paid steps', () => swallowedExhaustionIsReported(), 180_000);+ test('reserved repair estimates reduce what job steps may spend', () => jobsRecheckedAfterRepairReservations(), 180_000);+ test('embeddings cut short after re-sealing resume from the checkpoint', () => pendingEmbeddingsResume(), 180_000);+});diff --git a/test/reindex.test.ts b/test/reindex.test.tsindex 7ec4e64a55..3d4eb285c0 100644--- a/test/reindex.test.ts+++ b/test/reindex.test.ts@@ -109,9 +109,13 @@ describe('gbrain reindex --markdown (v0.32.7)', () => {expect(rows.every(r => Number(r.chunker_version) === MARKDOWN_CHUNKER_VERSION)).toBe(true);});- test('idempotent: --no-embed re-run ignores contextual mode drift it cannot repair', async () => {+ test('idempotent: --no-embed stamps the contextual mode of the pages it re-chunks', async () => {await seedLegacyPage('note-e', 'body e');await runReindex(engine, ['--markdown', '--no-embed']);+ const [stamped] = await engine.executeRaw<{ contextual_retrieval_mode: string | null }>(+ `SELECT contextual_retrieval_mode FROM pages WHERE slug = 'note-e'`,+ );+ expect(stamped.contextual_retrieval_mode).toBe('title');const second = await runReindex(engine, ['--markdown', '--no-embed']);expect(second.pending).toBe(0);expect(second.reindexed).toBe(0);diff --git a/test/repair-command.test.ts b/test/repair-command.test.tsindex 2f28169ce8..f69e5761d4 100644--- a/test/repair-command.test.ts+++ b/test/repair-command.test.ts@@ -174,7 +174,7 @@ describe('gbrain repair 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.map((r: { kind: string }) => r.kind)).toEqual(['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints']);expect(json.results[0]).toMatchObject({ mode: 'dry_run', affected: 1 });expect(out[1]).toContain(`Scope: brain `);expect(out[1]).toContain(`sources ${source}`);diff --git a/test/repair-contextual-mode-5621.serial.test.ts b/test/repair-contextual-mode-5621.serial.test.tsnew file mode 100644index 0000000000..41b4542756--- /dev/null+++ b/test/repair-contextual-mode-5621.serial.test.ts@@ -0,0 +1,143 @@+/**+ * #5621: `gbrain repair contextual-mode` stamps the contextual retrieval mode+ * on existing markdown pages that were imported without one, exactly as a+ * fresh import would, and re-embeds only pages whose embedding input changes.+ *+ * Legacy pages are reproduced by importing with contextual retrieval off+ * (raw vectors, 'none'-tier input hashes) and clearing the stamp, which is+ * the state a pre-fix `--no-embed` import or a pre-stamp brain leaves.+ *+ * Installs the process-global gateway transport seam (always fake), so this+ * stays a `.serial.test.ts`. Runs on PGLite, and on Postgres through+ * test/e2e/repair-contextual-mode-5621-postgres.test.ts.+ */+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 type { BrainEngine } from '../src/core/engine.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { runRepair, resolveRepairScope } from '../src/core/repair/core.ts';+import { contextualModeRepair } from '../src/core/repair/contextual-mode.ts';+import { checkContextualRetrievalCoverage } from '../src/commands/doctor/checks/calibration.ts';+import { titleTierCorpusGeneration } from '../src/core/contextual-retrieval-service.ts';+import { __setEmbedTransportForTests, configureGateway, resetGateway } from '../src/core/ai/gateway.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';++const DIMS = 1536;+const MODEL = 'openai:text-embedding-3-large';+let inputs: string[][] = [];+let home: string;+const savedHome = process.env.GBRAIN_HOME;++beforeAll(() => {+ home = mkdtempSync(join(tmpdir(), 'gbrain-repair-cr-'));+ process.env.GBRAIN_HOME = home;+ configureGateway({ embedding_model: MODEL, embedding_dimensions: DIMS, env: { OPENAI_API_KEY: 'sk-test-fake' } });+ __setEmbedTransportForTests((async ({ values }: { values: string[] }) => {+ inputs.push([...values]);+ return { embeddings: values.map(() => new Array(DIMS).fill(0.001)), usage: { tokens: 0 } };+ }) as never);+});++afterAll(() => {+ __setEmbedTransportForTests(null);+ resetGateway();+ if (savedHome === undefined) delete process.env.GBRAIN_HOME; else process.env.GBRAIN_HOME = savedHome;+ rmSync(home, { recursive: true, force: true });+});++beforeEach(() => { inputs = []; });++for (const kind of testBackends()) describe(`#5621 gbrain repair contextual-mode (${kind})`, () => {+ 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({ embedding_dimensions: DIMS } as never); await engine.initSchema(); }+ await engine.executeRaw("INSERT INTO sources (id, name) VALUES ('plain', 'Plain') ON CONFLICT (id) DO NOTHING");+ await engine.executeRaw("INSERT INTO sources (id, name, contextual_retrieval_mode) VALUES ('off', 'Off', 'none') ON CONFLICT (id) DO NOTHING");+ }, 120_000);+ afterAll(async () => { if (close) await close(); else await engine.disconnect(); });++ const ctx = () => ({ engine, config: { engine: engine.kind }, remote: false, dryRun: false,+ logger: { info() {}, warn() {}, error() {} } }) as unknown as OperationContext;+ const body = (title: string) => `---\ntype: note\ntitle: ${title}\n---\n\n${`A paragraph about ${title}. `.repeat(20)}\n`;+ async function legacyPage(source: string, slug: string, title: string, opts: { noEmbed?: boolean } = {}) {+ await engine.setConfig('search.contextual_retrieval_disabled', 'true');+ await importFromContent(engine, slug, body(title), { sourceId: source, noEmbed: opts.noEmbed });+ await engine.setConfig('search.contextual_retrieval_disabled', 'false');+ await engine.executeRaw('UPDATE pages SET contextual_retrieval_mode=NULL, corpus_generation=NULL WHERE source_id=$1 AND slug=$2', [source, slug]);+ }+ const page = async (source: string, slug: string) => (await engine.executeRaw<{ mode: string | null; generation: string | null }>(+ 'SELECT contextual_retrieval_mode AS mode, corpus_generation AS generation FROM pages WHERE source_id=$1 AND slug=$2', [source, slug]))[0];+ const vectors = async (source: string, slug: string) => (await engine.executeRaw<{ v: string | null; h: string | null }>(+ `SELECT c.embedding::text AS v, c.embedding_input_hash AS h FROM content_chunks c JOIN pages p ON p.id=c.page_id+ WHERE p.source_id=$1 AND p.slug=$2 ORDER BY c.chunk_index`, [source, slug]));+ const run = async (apply: boolean, embed = true) => runRepair(ctx(), contextualModeRepair, await resolveRepairScope(engine),+ { apply, embed, embeddingModel: MODEL });++ test('stamps like a fresh import; unchanged inputs queue no re-embed, changed inputs re-embed once; a second run changes nothing', async () => {+ await legacyPage('plain', 'notes/raw-embedded', 'Raw Embedded Example');+ await legacyPage('off', 'notes/source-off', 'Source Off Example');+ await legacyPage('plain', 'notes/never-embedded', 'Never Embedded Example', { noEmbed: true });+ const offBefore = await vectors('off', 'notes/source-off');+ expect(offBefore.every(row => row.v !== null)).toBe(true);+ inputs = [];++ const before = await checkContextualRetrievalCoverage(engine);+ expect(before.status).toBe('warn');+ expect(before.message).toContain('gbrain repair contextual-mode --apply');+ expect(before.details).toMatchObject({ mode_null_pages: 3, mode_repair: 'contextual-mode' });++ const preview = await run(false);+ expect(preview).toMatchObject({ kind: 'contextual-mode', mode: 'dry_run', affected: 3, applied: 0 });+ expect(preview.apply_command).toBe('gbrain repair contextual-mode --apply');+ expect((await page('plain', 'notes/raw-embedded')).mode).toBeNull();++ const applied = await run(true);+ expect(applied).toMatchObject({ affected: 3, applied: 3, complete: true });+ expect(await page('plain', 'notes/raw-embedded')).toEqual({ mode: 'title', generation: titleTierCorpusGeneration() });+ expect(await page('plain', 'notes/never-embedded')).toEqual({ mode: 'title', generation: titleTierCorpusGeneration() });+ expect(await page('off', 'notes/source-off')).toEqual({ mode: 'none', generation: null });+ // Exactly one re-embed: the raw-embedded page, now title-wrapped.+ expect(inputs).toHaveLength(1);+ expect(inputs[0]!.every(text => text.includes('Raw Embedded Example'))).toBe(true);+ expect((await vectors('plain', 'notes/raw-embedded')).every(row => row.v !== null && row.h !== null)).toBe(true);+ // Unchanged input: the same vectors and hashes, no provider call.+ expect(await vectors('off', 'notes/source-off')).toEqual(offBefore);+ expect((await vectors('plain', 'notes/never-embedded')).every(row => row.v === null)).toBe(true);++ expect((await checkContextualRetrievalCoverage(engine)).details).toMatchObject({ mode_null_pages: 0 });+ inputs = [];+ const again = await run(true);+ expect(again).toMatchObject({ affected: 0, applied: 0 });+ expect(inputs).toHaveLength(0);+ });++ test('an embed_skip page keeps its retained vectors and is counted, not stamped', async () => {+ await legacyPage('plain', 'notes/skip-embedding', 'Skip Embedding Example');+ await engine.executeRaw(`UPDATE pages SET frontmatter = COALESCE(frontmatter, '{}'::jsonb) || '{"embed_skip": {"reason": "example"}}'::jsonb+ WHERE source_id='plain' AND slug='notes/skip-embedding'`);+ const before = await vectors('plain', 'notes/skip-embedding');+ inputs = [];+ const result = await run(true);+ expect(result.residuals).toMatchObject({ embed_skip: 1 });+ expect(inputs).toHaveLength(0);+ expect((await page('plain', 'notes/skip-embedding')).mode).toBeNull();+ expect(await vectors('plain', 'notes/skip-embedding')).toEqual(before);+ await engine.executeRaw("DELETE FROM pages WHERE source_id='plain' AND slug='notes/skip-embedding'");+ });++ test('--no-embed stamps and clears only the changed vectors without a provider call', async () => {+ await legacyPage('plain', 'notes/no-embed-repair', 'No Embed Repair');+ inputs = [];+ const result = await run(true, false);+ expect(result.applied).toBe(1);+ expect(inputs).toHaveLength(0);+ expect((await page('plain', 'notes/no-embed-repair')).mode).toBe('title');+ expect((await vectors('plain', 'notes/no-embed-repair')).every(row => row.v === null)).toBe(true);+ });+});diff --git a/test/repair-flags.test.ts b/test/repair-flags.test.tsnew file mode 100644index 0000000000..dc3c395acc--- /dev/null+++ b/test/repair-flags.test.ts@@ -0,0 +1,91 @@+/**+ * `gbrain repair` flag handling (fix wave 3, Lane D): unknown flags are+ * refused before any scope resolution or write, `--max-usd` points at the+ * capped doctor route, every registered kind has a help line and a+ * registration, and the `--all` preview lists every kind with its estimates.+ */+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 { OperationError } from '../src/core/ops/contract.ts';+import { REPAIR_KINDS } from '../src/core/repair/core.ts';+import { REPAIR_HELP, runRepairCommand } from '../src/commands/repair.ts';+import { withEnv } from './helpers/with-env.ts';++let engine: PGLiteEngine;+const home = mkdtempSync(join(tmpdir(), 'gbrain-repair-flags-'));++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 60_000);++afterAll(async () => {+ await engine.disconnect();+ rmSync(home, { recursive: true, force: true });+});++async function refusal(args: string[]): Promise<OperationError> {+ try {+ await withEnv({ GBRAIN_HOME: home }, () => runRepairCommand(engine, args));+ } catch (error) {+ if (error instanceof OperationError) return error;+ throw error;+ }+ throw new Error(`gbrain repair ${args.join(' ')} was accepted`);+}++async function captured(args: string[]): Promise<string> {+ const lines: string[] = [];+ const original = console.log;+ console.log = (...parts: unknown[]) => { lines.push(parts.map(String).join(' ')); };+ try { await withEnv({ GBRAIN_HOME: home }, () => runRepairCommand(engine, args)); } finally { console.log = original; }+ return lines.join('\n');+}++describe('gbrain repair flags', () => {+ test('--max-usd is refused with invalid_params naming the flag and the capped doctor route', async () => {+ const error = await refusal(['safe-chunks', '--apply', '--max-usd', '0']);+ expect(error.code).toBe('invalid_params');+ expect(error.message).toContain('--max-usd');+ expect(error.suggestion).toContain('gbrain doctor --remediate --yes --include-repairs --max-usd 0');+ });++ test('any unknown flag is refused and named, with or without a value', async () => {+ for (const args of [['timeline', '--bogus'], ['--apply', '--all', '--force'], ['visibility', '--sources=a']]) {+ const error = await refusal(args);+ expect(error.code).toBe('invalid_params');+ expect(error.message).toContain(args.find(a => a.startsWith('--') && !['--apply', '--all'].includes(a))!.split('=')[0]);+ }+ });++ test('a stray positional after the kind is refused instead of silently ignored', async () => {+ const error = await refusal(['timeline', 'extra']);+ expect(error.code).toBe('invalid_params');+ expect(error.message).toContain('extra');+ });++ test('help names every registered kind', () => {+ for (const kind of REPAIR_KINDS) expect(REPAIR_HELP).toContain(` ${kind}`);+ });++ test('--all preview lists every kind with lifetime-id and USD estimates and names the paid kinds', async () => {+ const out = await captured(['--all', '--json']);+ const parsed = JSON.parse(out) as { mode: string; results: Array<{ kind: string; cost: Record<string, unknown>; paid: boolean }>; paid_kinds: string[] };+ expect(parsed.mode).toBe('dry_run');+ expect(parsed.results.map(r => r.kind)).toEqual([...REPAIR_KINDS]);+ for (const result of parsed.results) {+ expect(result.cost).toHaveProperty('lifetime_ids');+ expect(result.cost).toHaveProperty('embedding_usd');+ expect(typeof result.paid).toBe('boolean');+ }+ expect(parsed.paid_kinds).toContain('safe-chunks');+ const human = await captured(['--all']);+ expect(human).toContain("may queue paid embeddings: timeline, visibility, safe-chunks");+ const free = JSON.parse(await captured(["--all", "--json", "--no-embed"])) as { paid_kinds: string[] };+ expect(free.paid_kinds).toEqual(["timeline", "visibility"]);+ });+});diff --git a/test/schema-bootstrap-coverage.test.ts b/test/schema-bootstrap-coverage.test.tsindex 5fb021882d..bb013ac7be 100644--- a/test/schema-bootstrap-coverage.test.ts+++ b/test/schema-bootstrap-coverage.test.ts@@ -990,6 +990,21 @@ const COLUMN_EXEMPTIONS = new Set<string>([// reference to trip on, and every reader treats NULL as an unclaimed legacy// row (never import-deleted).'tags.tag_source',+ // Migration 178 — writer-version stamps. persistence_requests and+ // persistence_brain are migration-created on PGLite (absent from+ // PGLITE_SCHEMA_SQL), so no PGLite-blob forward reference can exist; no+ // index in either blob references these columns; every reader treats NULL+ // as an unstamped (older) writer or an unrecorded cutoff.+ 'persistence_requests.admitter_version',+ 'persistence_requests.admitter_host_id',+ 'persistence_requests.consumer_version',+ 'persistence_requests.consumer_host_id',+ 'persistence_requests.published_at',+ 'persistence_brain.writer_version_cutoff',+ // #5254 (migration v177) — unbound-source page classification. Column-only+ // and nullable; no index in either schema blob references it, and every+ // reader treats NULL as an ordinary page.+ 'pages.database_only_reason',]);test('every ALTER TABLE ADD COLUMN in MIGRATIONS is covered by applyForwardReferenceBootstrap (column-only class)', async () => {diff --git a/test/scripts/ci-pr-scope.test.ts b/test/scripts/ci-pr-scope.test.tsindex adad707ac8..7c79bc0afc 100644--- a/test/scripts/ci-pr-scope.test.ts+++ b/test/scripts/ci-pr-scope.test.ts@@ -100,7 +100,7 @@ describe('pull-request CI scope', () => {const push = { github: { event_name: 'push' } };const security = load('test.yml').jobs['security-regressions'];expect(cells(security, push)).toHaveLength(6);- expect(cells(security, pr)).toEqual(['ubuntu-latest/1.3.13', 'macos-latest/1.3.13', 'windows-latest/1.3.13']);+ expect(cells(security, pr)).toEqual(['ubuntu-latest/1.3.13', 'macos-26/1.3.13', 'windows-latest/1.3.13']);const persistence = load('persistence-validation.yml').jobs;for (const name of ['read-performance', 'deployment-matrix', 'invariants', 'reconciliation']) {const full = cells(persistence[name], push);diff --git a/test/scripts/ci-runner-routing.test.ts b/test/scripts/ci-runner-routing.test.tsindex bba935c4c8..b4460c341e 100644--- a/test/scripts/ci-runner-routing.test.ts+++ b/test/scripts/ci-runner-routing.test.ts@@ -58,7 +58,7 @@ describe('CI runner routing', () => {test('security matrix labels and native platform coverage retain their identities', () => {const security = load('test.yml').jobs['security-regressions'];- expect(security.strategy!.matrix.os).toEqual(['ubuntu-latest', 'macos-latest', 'windows-latest']);+ expect(security.strategy!.matrix.os).toEqual(['ubuntu-latest', 'macos-26', 'windows-latest']);for (const os of security.strategy!.matrix.os!) {const expression = security['runs-on']!.replace(/^\$\{\{\s*|\s*\}\}$/g, '');expect(runInNewContext(expression, { matrix: { os } }, { timeout: 100 })).toBe(os === 'ubuntu-latest' ? small : os);@@ -67,8 +67,8 @@ describe('CI runner routing', () => {expect(targetRunners(native.jobs.native)).toEqual({'linux-x64-glibc': single,'linux-arm64-glibc': arm,- 'darwin-arm64': 'macos-15',- 'darwin-x64': 'macos-15-intel',+ 'darwin-arm64': 'macos-26',+ 'darwin-x64': 'macos-26-intel','win32-x64': 'windows-2022','win32-arm64': 'windows-11-arm',});@@ -77,6 +77,17 @@ describe('CI runner routing', () => {expect(native.jobs.musl.strategy!.matrix.target).toEqual(['linux-x64-musl', 'linux-arm64-musl']);});+ test('macOS 26 validation is pinned, time-boxed, label-gated on pull requests and uses no secrets', () => {+ const text = readFileSync(join(root, '.github/workflows/macos-validation.yml'), 'utf8');+ const workflow = safeLoad(text) as { on: Record<string, unknown>; jobs: Record<string, Job & { 'timeout-minutes'?: number; if?: string }> };+ expect(Object.keys(workflow.on).sort()).toEqual(['pull_request', 'schedule', 'workflow_dispatch']);+ const job = workflow.jobs['macos-26']!;+ expect(job['runs-on']).toBe('macos-26');+ expect(job['timeout-minutes']).toBeGreaterThan(0);+ expect(job.if).toContain("contains(github.event.pull_request.labels.*.name, 'macos-validation')");+ expect(text).not.toMatch(/\$\{\{[^}]*secrets\./);+ });+test('status and planning jobs stay small while coverage reports retain memory headroom', () => {for (const name of ['changes', 'gitleaks', 'dependency-audit', 'test-status', 'native-only-status']) {expect(load('test.yml').jobs[name]['runs-on'], name).toBe(small);diff --git a/test/sync-policy.test.ts b/test/sync-policy.test.tsindex 3e4fb5b546..2a2cda2b03 100644--- a/test/sync-policy.test.ts+++ b/test/sync-policy.test.ts@@ -5,7 +5,13 @@* check is deliberately untouched — see sync-policy.ts's module doc).*/import { describe, expect, test } from 'bun:test';-import { isSyncDisabledConfig } from '../src/core/sync-policy.ts';+import {+ activationPendingSkipMessage,+ firstActivationPendingSkip,+ isSyncDisabledConfig,+ loadActivationPendingSourceIds,+ skipActivationPendingSync,+} from '../src/core/sync-policy.ts';describe('isSyncDisabledConfig', () => {test('true when config.syncEnabled is explicitly false', () => {@@ -35,3 +41,37 @@ describe('isSyncDisabledConfig', () => {expect(isSyncDisabledConfig(JSON.stringify({ syncEnabled: true }))).toBe(false);});});++describe('#5198: activation-pending sync skip', () => {+ test('returns the bound source ids the query yields', async () => {+ const engine = { executeRaw: async () => [{ source_id: 'alpha' }, { source_id: 'beta' }] };+ expect(await loadActivationPendingSourceIds(engine as never)).toEqual(new Set(['alpha', 'beta']));+ });++ test('fails open to an empty set when the persistence tables are unreadable', async () => {+ const engine = { executeRaw: async () => { throw new Error('relation "persistence_source_bindings" does not exist'); } };+ expect(await loadActivationPendingSourceIds(engine as never)).toEqual(new Set());+ });++ test('reports each source once per process', () => {+ expect(firstActivationPendingSkip('policy-once-a')).toBe(true);+ expect(firstActivationPendingSkip('policy-once-a')).toBe(false);+ expect(firstActivationPendingSkip('policy-once-b')).toBe(true);+ });++ test('skipActivationPendingSync skips only pending sources and writes the reason once', () => {+ const lines: string[] = [];+ const pending = new Set(['policy-guard-a']);+ expect(skipActivationPendingSync(pending, 'policy-guard-b', 'x_skipped', true, l => lines.push(l))).toBe(false);+ expect(skipActivationPendingSync(pending, 'policy-guard-a', 'x_skipped', true, l => lines.push(l))).toBe(true);+ expect(skipActivationPendingSync(pending, 'policy-guard-a', 'x_skipped', true, l => lines.push(l))).toBe(true);+ expect(lines.map(l => JSON.parse(l))).toEqual([{ event: 'x_skipped', source_id: 'policy-guard-a', reason: 'activation_pending' }]);+ });++ test('the skip message names the source, the refusal code and where to look', () => {+ const message = activationPendingSkipMessage('alpha');+ expect(message).toContain('source=alpha');+ expect(message).toContain('writer_coordinator_required');+ expect(message).toContain('gbrain sources writer status');+ });+});diff --git a/test/workspace-push.serial.test.ts b/test/workspace-push.serial.test.tsindex 035c2523c8..90b923e19d 100644--- a/test/workspace-push.serial.test.ts+++ b/test/workspace-push.serial.test.ts@@ -17,7 +17,7 @@ import { tmpdir } from 'os';import { execFileSync, spawnSync } from 'child_process';import {workspacePush, acquirePushLock, pushLockDir, pushStatusPath, pushStatusPathForRoot,- readPushStatuses, summarizePushStatuses, verifyRemotePrivacy,+ readPushStatuses, readPushStatusForRoot, summarizePushStatuses, verifyRemotePrivacy,parseGithubOwnerRepo, resolveWorkspaceRoot, PUSH_LOCK_STALE_MS, PUSH_DENY_GLOBS,} from '../src/core/workspace-push.ts';import { SCAN_ALLOW_FILENAME } from '../src/core/secret-scan.ts';@@ -546,6 +546,32 @@ describe('error paths', () => {}, T);});+describe('managed-worktree refusal is recorded (#5198)', () => {+ test('a guard refusal overwrites the last success with ok:false and still throws', async () => {+ writeFileSync(join(work, 'note.md'), 'first\n');+ expect((await push()).status).toBe('pushed');+ expect(readPushStatuses()[0]!.ok).toBe(true);+ const commits = commitCount(work);+ writeFileSync(join(work, '.gbrain-owner.json'), '{}\n');+ writeFileSync(join(work, 'note.md'), 'second\n');+ await expect(push()).rejects.toMatchObject({ code: 'writer_coordinator_required' });+ const status = readPushStatuses()[0]!;+ expect(status.ok).toBe(false);+ expect(status.reason).toStartWith('writer_coordinator_required: ');+ expect(commitCount(work)).toBe(commits); // refused before staging: nothing committed+ expect(existsSync(pushLockDir(work))).toBe(false);+ }, T);++ test('a refusal on a subdirectory target is recorded against the workspace root', async () => {+ const sub = join(work, 'notes');+ mkdirSync(sub);+ writeFileSync(join(work, '.gbrain-owner.json'), '{}\n');+ await expect(workspacePush({ dir: sub, branch: 'main', allowUnverifiedRemote: true }))+ .rejects.toMatchObject({ code: 'writer_coordinator_required' });+ expect(readPushStatusForRoot(resolveWorkspaceRoot(sub)!)?.ok).toBe(false);+ }, T);+});+describe('unverified-remote escape hatches [D18/S3]', () => {test('env hatch: unverifiable origin + GBRAIN_ALLOW_UNVERIFIED_REMOTE=1 → pushed (WARN path)', async () => {process.env.GBRAIN_ALLOW_UNVERIFIED_REMOTE = '1';