Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
v0.59.17.0 fix(memory): subject-scoped forget, poison-page isolation, safe dream writes, connector checkpoints (#5666)
Garry Tana6eca5ed2d55
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 34996a6bd0..d95ba77bd9 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.59.13.0",+ "version": "0.59.17.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 ddd0b74a35..27ff33e827 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.59.13.0",+ "version": "0.59.17.0","description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.","author": {"name": "Garry Tan",diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.mdindex 75ca095b49..1d8df89cb8 100644--- a/BOOTSTRAP_FOR_AGENTS.md+++ b/BOOTSTRAP_FOR_AGENTS.md@@ -1,4 +1,4 @@-<!-- gbrain-runbook-stamp: 0.59.13.0 -->+<!-- gbrain-runbook-stamp: 0.59.17.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 f4cadfdef1..c0f5043efd 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,99 @@ 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.59.17.0] - 2026-09-28++**Forgetting one person's fact no longer erases it for everyone, and several maintenance jobs stop quietly losing or overwriting your notes.**++Say you tell your agent to forget that alice-example "prefers email". Before this release, gbrain forgot that sentence for every person in the brain: bob-example's identical fact was switched off too, rewritten as forgotten in his page the next time it was imported, and nobody could ever be remembered as preferring email again. Now a forget applies to the person or company it was about. Updating a fact ("works at acme-example" becomes "left acme-example") is also no longer treated as a forget, so the old wording can come back later and the update does not touch unrelated pages. That matters most for Gmail commitment tracking, which updates facts every time a due date moves.++The nightly maintenance cycle got safer too. One broken facts table no longer stops every page after it from updating. A hand-written concept page is never replaced by a generated summary. A short page whose real content is its timeline is no longer mistaken for an empty duplicate and deleted. Cleaning up old background jobs no longer makes the brain pay to summarize the same conversations again.++Live ChatGPT and Claude sync keeps up with renamed conversations, tracks progress separately for each source, keeps moving when you cap a run with `--limit`, and sets aside a conversation that keeps failing instead of re-fetching everything forever.++### What changes for you++| Situation | Before | Now |+| --- | --- | --- |+| Forget alice-example's "Prefers email" | Also switched off for bob-example and blocked for everyone | Only alice-example's fact is forgotten |+| A remembered fact is updated | Old wording blocked forever, whole source re-indexed | Old row marked as replaced; nothing else touched |+| One page's facts table has a bad row | Every later page stopped updating, every night | That page is reported; the rest update |+| You wrote `concepts/flywheel` yourself | Replaced by a generated paragraph | Left untouched and reported |+| Page `alice` holds only a title and a timeline | Deleted as an empty duplicate | Kept |+| `gbrain jobs prune` after 30 days | Every transcript summarized (and paid for) again | Nothing re-runs |+| Renamed ChatGPT/Claude conversation | New messages silently dropped | The existing page updates with them |+| `gbrain connectors sync --limit 50`, run daily | The same newest 50 forever | 50 new ones each run until caught up |+| Syncing the same account into a second source | Only the last week arrived | Full history |+| One conversation always fails to download | Every run re-fetched the whole window | Set aside after 3 tries; progress continues |++### How to use it++Nothing to configure. Useful checks after upgrading:++```bash+gbrain connectors status --json # watermark and last sync for the scheduled source+gbrain connectors sync chatgpt --limit 50 # repeat until status is "success"; each run moves on+gbrain dream --phase extract_facts # a bad page now shows FACTS_RECONCILE_FAILED instead of failing the phase+```++**Say to your agent:** *"Forget that alice-example prefers email."* Only alice-example's fact is withdrawn.++### Things to watch++- Forgets you made before this release keep applying to every entity, exactly as they did, so upgrading never brings a forgotten fact back. New forgets are scoped to one entity. A fact that was never about anyone in particular still withdraws everywhere in its source.+- A facts table with a confidence outside 0 to 1 (for example `7`) is now reported as malformed and that page's facts are left as they were until you fix the cell.+- A conversation that fails 3 times at the same version is skipped until it changes upstream. `gbrain connectors sync <provider> --full` retries everything.++### To take advantage of v0.59.17.0++`gbrain upgrade` should do this automatically. If it didn't, or if `gbrain doctor`+warns about a partial migration:++1. **Run the orchestrator manually:**+ ```bash+ gbrain apply-migrations --yes+ ```+2. **No agent action is needed.** Migrations v167 to v169 are schema-only; there is no `skills/migrations` file for this release.+3. **Verify the outcome:**+ ```bash+ gbrain doctor+ gbrain connectors status+ gbrain stats+ ```+4. **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++#### Forget and supersession++- Fact withdrawals are keyed by `(source_id, visibility, subject, fact_hash)`. `subject` is the forgotten row's `entity_slug`. `'*'` applies to every entity: subjectless facts use it, and so does every row recorded before migration v169. `recordFactWithdrawal`, the `facts_preserve_withdrawal` trigger, `isFactWithdrawn` (now takes the entity), the import and `get_page` snapshot overlays, and fact-embedding backfill all match `subject = '*' OR subject = entity_slug`. Fence rows match on their page slug.+- `updateSlug` (both engines) and the phantom-redirect merge move a page's withdrawals to the new slug, so a rename never restores a forgotten claim.+- `writeSingleFact` supersession strikes the old fence row with a `#N` supersession reference through `forgetFactInFence(..., { supersededBy })` and records no withdrawal. This path no longer invalidates the whole source, including from Gmail loop extraction.++#### Cycle phases++- `extract_facts` reconciles each page in isolation. A failure is reported as `<slug>: FACTS_RECONCILE_FAILED: <message>`, counted in `pagesFailed`, and booked as a halt in the extract rollup. `parseFactsFence` rejects confidence outside 0..1 as `FACTS_TABLE_MALFORMED`. Migration v167 makes `facts.superseded_by` `ON DELETE SET NULL`.+- `synthesize_concepts` checks `concepts/<x>` before any LLM spend and skips pages without `synthesized_by: synthesize_concepts-*`, listing them in `details.skipped_human_owned`.+- The phantom-redirect residue gate counts timeline text, `timeline_entries` rows, and frontmatter keys beyond `title`/`type`/`tags`.+- `MinionQueue.prune` archives completed `dream:synth%` keys into the new `dream_synthesis_completions` table (migration v168) in the same statement that deletes them; synthesis idempotency reads both.++#### Transcripts and chat connectors++- `runTranscriptsIngest` imports a session at the slug its existing page already uses (matched on part 1's `frontmatter.id`), so a retitled or re-dated conversation updates in place.+- Connector sync state is keyed by `(provider, source)`: `connectors.<p>.source.<id>.{watermark_iso,last_sync_at,synced,failed}`. A legacy per-provider watermark still applies to the scheduled `connectors.source_id` source until it writes its own. `auth_error_at` stays per provider.+- Listed conversations whose `updatedAt` a source already ingested are skipped before the `--limit` cap. A conversation that fails `QUARANTINE_ATTEMPTS` (3) times at one `updatedAt` is quarantined and reported in `quarantined`; it stops holding the watermark back. Results also report `skippedUnchanged`.++### For contributors++- New regression suites: `test/facts-withdrawal-subject.test.ts`, `test/facts-supersede-not-withdrawal.test.ts`, `test/extract-facts-poison-page.test.ts`, `test/cycle/synthesize-concepts-human-owned.test.ts`, `test/transcripts-retitle.test.ts`, `test/e2e/connectors-sync-checkpoints-pglite.test.ts`, plus new cases in `test/phantom-redirect.test.ts` and `test/cycle-synthesize-daily-cap.test.ts`. All run on in-memory PGLite with no provider calls.+- `watermarkKey` and `lastSyncAtKey` now take a source id; read connector progress through `readConnectorState`.+## [0.59.13.0] - 2026-09-28**Search now credits a page when several retrieval methods agree on it, keeps the reranker's order, and stops hiding timeline evidence behind "who is" questions.**diff --git a/VERSION b/VERSIONindex 4d23a329fa..284dbf1b09 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-0.59.13.0+0.59.17.0diff --git a/docs/architecture/canonical-writers.tsv b/docs/architecture/canonical-writers.tsvindex b041b32f5a..d80c5c6cd5 100644--- a/docs/architecture/canonical-writers.tsv+++ b/docs/architecture/canonical-writers.tsv@@ -53,7 +53,7 @@ src/core/extract/receipt-writer.ts 1 engine_guard Canonical table SQL trigger resrc/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/forget.ts 3 filesystem_guard Managed callers journal withdrawal; legacy filesystem helper requires coordinated write.+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.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/git-remote.ts 0 filesystem_guard Clone, pull and rebase entry points check the durable root refusal registry.diff --git a/docs/architecture/key-files/agent-bootstrap-continued.md b/docs/architecture/key-files/agent-bootstrap-continued.mdindex a8731e517a..5414ca9769 100644--- a/docs/architecture/key-files/agent-bootstrap-continued.md+++ b/docs/architecture/key-files/agent-bootstrap-continued.md@@ -33,4 +33,4 @@- `src/core/bootstrap/verify.ts` + `status.ts` — verify is the definition of done: fail-soft check suite over the REAL write path (put_page op → write-through file under `brain/` → in-process sweep → graph floor via link tables → recall), the keyless magic-moment check (`## Facts` fence → zero-LLM reconciliation → world-visibility read-back), source_id collision resolution (as the one bootstrap subcommand holding an engine: a manifest `source_id` already registered to a DIFFERENT checkout → derives a stable `workspace-<8char-path-hash>`, persists it to agent.json, names the re-register steps — every consumer reads `manifest.source_id`), the `embedding_plane` check (keyed installs live-embed ONE probe string and compare the RETURNED width to the actual `content_chunks.embedding` width — a plane split is a named FAIL with the recovery command, keyless passes, a dead probe warns; runs BEFORE the roundtrip so a keyless-passing roundtrip can never certify a brain whose keyed writes all fail), token sweep, byte floors, secret scan, deny globs, repo privacy, hooks smoke (in-process IPC), capability report, first-run tour; snapshots kept last-5 under `<home>/bootstrap/`. status owns the ordered PHASES list (the runbook defers to it), artifact-first detection, install.jsonl, the runbook version-stamp skew check, and the support blob doctor/agents relay verbatim.- `src/core/bootstrap/template-repo.ts` + `scripts/generate-template-repo.ts` — deterministic public-template generation (render `--minimal` + placeholder manifest + stamped README); published only by the release workflow after diffing against the vendored tree.- `scripts/check-bootstrap-tag.sh` / `scripts/check-bootstrap-templates.sh` — CI guards: sanctioned distribution ref only (`latest-stable`; the release job advances it after assets publish) + runbook stamp == VERSION; template↔question-bank token bijection + placeholder-only assertion + offline generator↔vendored byte-diff + runbook-phase↔status.ts consistency. Both skip gracefully when their subjects are absent.-- `src/core/cycle/synthesize-concepts.ts` concept-quality addendum — eligible groups are processed deterministically by tier, descending atom count, then concept slug so the fixed LLM budget reaches the strongest evidence first regardless of database row order. Every page and phase receipt distinguishes `llm`, intended `deterministic_tier`, `budget_fallback`, and `error_fallback` synthesis modes. The narrative call's output cap is sized from the resolved `models.dream.synthesize` model via `resolveSynthMaxOutputTokens`: 500 for non-thinking models, the gateway's `THINKING_MODEL_MAX_OUTPUT_TOKENS` (no phase-private number — DeepSeek v4 truncates at 8192-class caps) when the gateway's shared `isThinkingModel` matches (name-matched Claude 5 or recipe-declared `thinking_by_default`; unknown providers count as non-thinking), so a tier-`reasoning` thinking model no longer spends the whole budget on reasoning and persists a template stub or truncated chain-of-thought as the concept narrative. Pinned by `test/cycle/synthesize-concepts-token-cap.test.ts`. Right after each concept page write the phase banks concept<->member-atom provenance edges through `engine.addLinksBatch` (`link_source: 'concept-provenance'`; `synthesized_from` concept->atom, `synthesizes` atom->concept; audit site `cycle.synthesize_concepts.provenance`), both endpoints scoped to the cycle's source, so the concept pages are graph-reachable (backlinks, relational recall, doctor `graph_signals_coverage`/`orphans`) even though the prompt forbids enumerating atoms in the body. The dedicated `link_source` keeps reconcile passes from pruning them; `ON CONFLICT DO NOTHING` makes re-runs the backfill; a failed or zero-row edge write lands in `link_warnings[]` (phase `warn`) — NOT in `failures[]`, which means "LLM-failed → template fallback" downstream and drives the rollup's `halt_delta`/`round_completed_delta` — and never aborts the page write. Atom discovery (the `type = 'atom'` scan) is scoped to the cycle source (`opts.sourceId ?? 'default'`) so same-slug atoms from other sources are never grouped into this source's concepts. Pinned by the `#4589` describe in `test/cycle/extract-atoms-synthesize-concepts.test.ts` and `test/cycle/synthesize-concepts-source-scope.test.ts`.+- `src/core/cycle/synthesize-concepts.ts` concept-quality addendum — a `concepts/<x>` page whose frontmatter lacks `synthesized_by: synthesize_concepts-*` belongs to a human or another writer: the phase checks it before any LLM spend, never rewrites it, and reports it in `details.skipped_human_owned` (pinned by `test/cycle/synthesize-concepts-human-owned.test.ts`). Eligible groups are processed deterministically by tier, descending atom count, then concept slug so the fixed LLM budget reaches the strongest evidence first regardless of database row order. Every page and phase receipt distinguishes `llm`, intended `deterministic_tier`, `budget_fallback`, and `error_fallback` synthesis modes. The narrative call's output cap is sized from the resolved `models.dream.synthesize` model via `resolveSynthMaxOutputTokens`: 500 for non-thinking models, the gateway's `THINKING_MODEL_MAX_OUTPUT_TOKENS` (no phase-private number — DeepSeek v4 truncates at 8192-class caps) when the gateway's shared `isThinkingModel` matches (name-matched Claude 5 or recipe-declared `thinking_by_default`; unknown providers count as non-thinking), so a tier-`reasoning` thinking model no longer spends the whole budget on reasoning and persists a template stub or truncated chain-of-thought as the concept narrative. Pinned by `test/cycle/synthesize-concepts-token-cap.test.ts`. Right after each concept page write the phase banks concept<->member-atom provenance edges through `engine.addLinksBatch` (`link_source: 'concept-provenance'`; `synthesized_from` concept->atom, `synthesizes` atom->concept; audit site `cycle.synthesize_concepts.provenance`), both endpoints scoped to the cycle's source, so the concept pages are graph-reachable (backlinks, relational recall, doctor `graph_signals_coverage`/`orphans`) even though the prompt forbids enumerating atoms in the body. The dedicated `link_source` keeps reconcile passes from pruning them; `ON CONFLICT DO NOTHING` makes re-runs the backfill; a failed or zero-row edge write lands in `link_warnings[]` (phase `warn`) — NOT in `failures[]`, which means "LLM-failed → template fallback" downstream and drives the rollup's `halt_delta`/`round_completed_delta` — and never aborts the page write. Atom discovery (the `type = 'atom'` scan) is scoped to the cycle source (`opts.sourceId ?? 'default'`) so same-slug atoms from other sources are never grouped into this source's concepts. Pinned by the `#4589` describe in `test/cycle/extract-atoms-synthesize-concepts.test.ts` and `test/cycle/synthesize-concepts-source-scope.test.ts`.diff --git a/docs/architecture/key-files/core-cycle.md b/docs/architecture/key-files/core-cycle.mdindex 447efdd5e2..0b41d0b84e 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. 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. 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. Tests: `test/e2e/fact-vector-repair-parity.test.ts`, `test/extract-facts-phase.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. 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`, so a DB-only row whose successor is a fence row never blocks that page's wipe-and-reinsert. Tests: `test/e2e/fact-vector-repair-parity.test.ts`, `test/extract-facts-phase.test.ts`, `test/extract-facts-poison-page.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/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).@@ -29,7 +29,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/cycle/patterns.ts` — Patterns phase: cross-session theme detection over reflections within `dream.patterns.lookback_days` (default 30). Names a pattern only when ≥`dream.patterns.min_evidence` (default 3) reflections support it. Reflection excerpts use the shared UTF-16-safe truncator; a raw `.slice(0, 600)` can split an emoji pair and make Postgres reject the subagent job's JSONB payload. Single Sonnet subagent; same allow-list path as synthesize (imports `loadAllowedSlugPrefixes` + `loadOutputRoot` from synthesize.ts — the reflections lookup, prompt slug templates, and allow-list all honor `dream.synthesize.output_root`, default 'wiki'). Subagent job/wait timeouts are config keys `dream.patterns.subagent_timeout_ms` / `dream.patterns.subagent_wait_timeout_ms` (defaults 30/35 min, mirroring the `dream.synthesize.*` pair). The phase status reflects the child outcome: non-`completed` outcome with zero writes → `fail` (error code `PATTERNS_CHILD_<OUTCOME>`); non-`completed` with partial writes → `warn`. Runs AFTER `extract` so the graph is fresh. The fan-out sets `require_writes: true` so an all-writes-failed child dead-letters instead of reporting completed. Budget clamping: clamped to the remaining parent-job budget via `clampSubagentBudgets` when the cycle threads `deadlineAtMs` — the clamp template synthesize.ts reuses; `MIN_PATTERNS_SUBAGENT_BUDGET_MS` gates an honest skip, and `CYCLE_DEADLINE_RESERVE_MS` is re-exported here from its base-phase.ts home. Evidence watermark: a `completed` child stamps the newest consumed reflection `updated_at` into the state row `dream.patterns.last_evidence_ts` (never `now()`; fail/warn/timeout paths don't stamp, so a dead child retries next tick), and a later run skips `no_new_evidence` while no reflection in the window is newer — autopilot's hourly global tick becomes a free skip until a reflection actually changes; an absent/unparseable stamp fails open; `--once` bypasses the gate but a completed forced run still stamps. Managed local evidence is source-incarnation-scoped and live/non-private; unchanged evidence coalesces the admitted child request instead of inventing a remote maintenance grant.-- `src/core/cycle/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; zero residue = phantom). Handler order: body-shape gate → `resolvePhantomCanonical` (bypasses exact-self-match) → `findPrefixCandidates` ambiguity check → `fenceDbDrift` bi-directional check → dry-run early exit → materialize canonical via `serializeMarkdown` if DB-only → append phantom fence rows to canonical's disk fence with `(claim, valid_from)` dedup-guard + row_num continuation → `engine.refreshPageBody` with SHA-256 content_hash recomputed via the import-file shape → `engine.migrateFactsToCanonical` (lossless) → `engine.rewriteLinks` (DB FK rewrite; wiki-link text rewrite is a documented follow-up) → `engine.softDeletePage` + `engine.deleteFactsForPage(phantom)` + `fs.unlinkSync(phantomPath)`. `RedirectResult.canonical` populated on `'redirected'` (incl. dry-run preview) so the caller builds `touched_canonicals`. Idempotent on re-run: phantom soft-deleted → predicate fails (`deleted_at IS NULL`); migrate UPDATE matches no rows; dedup-guard prevents double-append.+- `src/core/cycle/phantom-redirect.ts` — Phantom-redirect orchestrator. Exports `runPhantomRedirectPass(engine, brainDir, sourceId, dryRun): Promise<PhantomPassResult>` (per-cycle wrapper acquiring the `gbrain-sync` writer lock once for the whole pass, 30s bounded retry, walks up to `GBRAIN_PHANTOM_REDIRECT_LIMIT` unprefixed phantoms) + `tryRedirectPhantom(engine, page, sourceId, brainDir, dryRun): Promise<RedirectResult>` + `stripFenceAndFrontmatterAndLeadingH1` (pure body-shape gate helper — strips facts fence incl. preceding `## Facts` heading and the leading H1). Only fence rows migrate, so the residue gate also counts the page's timeline text, any `timeline_entries` row, and frontmatter keys beyond `title`/`type`/`tags`; any residue = not a phantom. Handler order: body-shape gate → `resolvePhantomCanonical` (bypasses exact-self-match) → `findPrefixCandidates` ambiguity check → `fenceDbDrift` bi-directional check → dry-run early exit → materialize canonical via `serializeMarkdown` if DB-only → append phantom fence rows to canonical's disk fence with `(claim, valid_from)` dedup-guard + row_num continuation → `engine.refreshPageBody` with SHA-256 content_hash recomputed via the import-file shape → `engine.migrateFactsToCanonical` (lossless) → move the phantom's fact withdrawals to the canonical subject → `engine.rewriteLinks` (DB FK rewrite; wiki-link text rewrite is a documented follow-up) → `engine.softDeletePage` + `engine.deleteFactsForPage(phantom)` + `fs.unlinkSync(phantomPath)`. `RedirectResult.canonical` populated on `'redirected'` (incl. dry-run preview) so the caller builds `touched_canonicals`. Idempotent on re-run: phantom soft-deleted → predicate fails (`deleted_at IS NULL`); migrate UPDATE matches no rows; dedup-guard prevents double-append.- `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).@@ -39,7 +39,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/cycle/synthesize-verify.ts` — Mechanical quote verify/repair on newly-created dream pages (zero LLM). Exports the shared grounding primitive `normalizeForGrounding` (whitespace/curly-quote/dash/case folding WITH an offset map back to the original string, so every replacement is a verbatim transcript slice) + `normForGrounding` (plain form, also used by `buildTriageMapBlock` and triage-rescue). `verifyAndRepairDreamPages(engine, writtenRefs, transcriptsByPath)` scopes to pages whose slug carries the transcript's content-hash suffix (page↔transcript binding; modified pre-existing people/pattern pages are skipped + counted `skipped_preexisting` — they may quote other sources), extracts paired-quote spans from the page BODY (code fences/inline code/wikilinks/link targets masked; paragraph-paired; odd-mark paragraphs skipped + counted `unbalanced`; min span 15 chars, ≤200 spans/page), and runs the repair ladder per span: exact substring → keep; normalized match → replace with the verbatim original slice; near match (word-trigram anchors, ≥0.8 token overlap, ambiguity within 0.05 falls through) → replace; else STRIP the quote marks keeping the text — NEVER fabricates, never deletes content. Warn-only counter: numeric/date claims ($amounts, percents, ISO/month dates, 4+ digit numbers, deduped, fences skipped) absent from the normalized transcript → `numeric_claim_warns`. Write-back ONLY when a span changed, through the canonical `importFromContent` pipeline (page+tags+chunks+links in one transaction, content_hash recomputed, `noEmbed` — the phase-end sweep backfills; provenance nulls preserve the first-write record); bare `engine.putPage` is insufficient (pages row only — the embed sweep would embed stale chunk_text). Fail-open per page (read-back miss / write throw → count + continue; abort still unwinds). Kill switch `dream.synthesize.quote_verify` (default on). Telemetry shape = `QuoteVerifyStats` in `details.synthesis.quote_verify`. Pinned by `test/cycle-synthesize-verify.test.ts` + the write-path mini-eval harness `test/cycle-write-path-mini-eval.test.ts`.-- `src/core/cycle/synthesize.ts` — Synthesize phase: conversation-transcript-to-brain pipeline, a two-stage cascade where cheap scored triage gates frontier synthesis. Reads `dream.synthesize.session_corpus_dir`, runs `runTriagePass` (exported; bounded pool `dream.triage.concurrency` default 4, wall-clock cache-MISS budget `dream.triage.max_ms` default 5 min — cache hits are free and deferred files report `deferred: true`, never cached, so the next pass continues) whose judge `judgeSignificance` emits `{score 0-1 ordinal salience, content_type, segments ≤8 verbatim quotes, entities ≤12, reasons}` (non-overlapping bands LOW 0-0.29 / MEDIUM 0.30-0.69 / HIGH 0.70-1.0; head 50%/middle 20%/tail 30% sample within `dream.triage.max_chars` default 24K via `safeSplitIndex`; out-of-[0,1] scores are `unparseable`, never clamped) cached in `dream_verdicts` with the judging `model` + `TRIAGE_VERSION` — cache validity requires BOTH to match (switching `models.dream.triage` re-judges; `max_chars`/`max_tokens` deliberately excluded from validity — `dream retriage --force` re-judges under new sampling knobs). Degenerate verdicts (`truncated`/`refusal`/`unparseable`) are never cached. THE gate is `passesTriageGate` (triage-rescue.ts): `score >= dream.triage.threshold` (default 0.5) OR the verified-segment rescue, applied at report construction inside `runTriagePass` at READ time — retuning the threshold or rescue knobs re-gates with zero re-judging; the stored `worth_processing` boolean derives from the fixed `DEFAULT_TRIAGE_THRESHOLD` constant (back-compat only, never the live dial). Passing files fan out one subagent per chunk with `max_turns` from `dream.synthesize.max_turns` (default 16) and a bounded advisory `buildTriageMapBlock` (exported; score/type/entities + chunk-filtered segments, '' for legacy/degraded verdicts so the prompt is unchanged for those) spliced into `buildSynthesisPrompt`, with `allowed_slug_prefixes` (sourced from `skills/_brain-filing-rules.json` `dream_synthesize_paths.globs`; when `dream.synthesize.output_root` is set, `loadAllowedSlugPrefixes(outputRoot)` remaps the `wiki/`-rooted globs to the configured namespace, and the same root drives the prompt slug templates; default 'wiki', validated against the slug grammar via the exported `loadOutputRoot`). The phase is source-scoped: cycle.ts threads `cycleSourceId` as `opts.sourceId` → each child's `SubagentHandlerData.source_id` → the subagent tool registry's `OperationContext.sourceId`, so put_page writes, collected refs, the summary page, and reverse-writes all target the cycle's resolved source ('default' when unscoped; reverse-writes for the cycle's own source land at `brainDir/<slug>.md`, foreign sources under `brainDir/.sources/<id>/`). Orchestrator collects slugs from `subagent_tool_executions` (NOT `pages.updated_at`) and reverse-renders DB → markdown via `serializeMarkdown`. Cooldown via `dream.synthesize.last_completion_ts`, written only when children completed and neither synthesis-budget nor triage-budget deferrals remain. Idempotency keys `dream:synth-v2:<enc source>:filename:<enc basename>:<hash16>[:c<i>of<n>]` (byte-stable, pinned by `test/e2e/dream-synthesize-chunking.test.ts`; grammar parsed by exported `parseSynthV2Key`). Fan-out self-heals idempotency-coalesced rows stranded `waiting` in a FOREIGN dead `dream-inline-*` queue (cancel releases the key slot → re-add into the live run's queue) instead of burning the 35-min wait on a row no worker will ever claim. Opt-in per-source daily submission cap `dream.synthesize.max_submissions_per_source_per_day` (default 0 = off; skips whole files — never partial chunk sets; bypassed for explicit `--input/--date/--from/--to` targets; count-query failure fails OPEN with a stderr warn). `--dry-run` runs triage, skips synthesis; deferral-aware headlines append "(N not yet triaged — time budget...)" so a time-boxed cold pass never reads as mass rejection. `details.triage` (threshold/judged/cache_hits/unreliable/degraded/deferred/below_threshold + rescue_band/rescue_checked/rescue_fired + tokens_in/tokens_out/cost_usd) + `details.synthesis` (jobs/avg_turns/max_turns_config + quote_verify/spend/children_zero_pages) carry the phase telemetry. Subagent never gets fs-write access. `renderPageToMarkdown` (exported) stamps `dream_generated: true` + `dream_cycle_date` into every reverse-write's frontmatter; `writeSummaryPage` does the same on the summary index — this marker is the explicit identity surface `isDreamOutput` checks in `transcript-discovery.ts`. `stampDreamProvenance` additionally persists the same marker into the `pages.frontmatter` JSONB row (merge via `executeRawJsonb`, raw object bound to `$N::jsonb`) for every child-written page BEFORE reverse-rendering, so generated pages are DB-queryable and a later put_page write-through (which re-renders from the DB row) can't erase the stamp. `judgeSignificance`, `JudgeClient`, `runTriagePass`, `buildTriageMapBlock`, `parseSynthV2Key`, `loadSynthConfig`, `TRIAGE_VERSION`, and `DEFAULT_TRIAGE_THRESHOLD` are exported; the triage model resolves via an explicit pre-read of `models.dream.triage` (preferred; through exported `resolveAlias`) falling back to the standard `resolveModel` chain (`models.dream.synthesize_verdict` → deprecated `dream.synthesize.verdict_model` → tier `utility`). `splitTranscriptByBudget(content, contentHash, maxChars)` splits oversized transcripts at paragraph boundaries (`## Topic:` → `---` → `\n` ladder) using a deterministic offset seeded from the first 32 bits of `contentHash` so retries chunk identically; per-chunk char budget = `MODEL_CONTEXT_TOKENS[resolvedModel] × 0.9 × 3.5 chars/token` (non-Anthropic ids fall back to a 180K-token safe default + once-per-process stderr warn); operator overrides `dream.synthesize.max_prompt_tokens` (floor 100K, wins) and `dream.synthesize.max_chunks_per_transcript` (default 24); per-chunk subagent job/wait timeouts are `dream.synthesize.subagent_timeout_ms` / `dream.synthesize.subagent_wait_timeout_ms` (defaults 30/35 min). Legacy `dream:synth:` keys are never produced — `loadSuccessfulSynthesisKeys(engine, sourceId, keyPrefix)` reads the completed rows of BOTH key families once per phase, so existing brains skip with `already_synthesized_legacy_single_chunk`/`_chunked` instead of re-spending the synthesis model, and a transcript whose synth-v2 children already completed skips with `already_synthesized_v2_single_chunk`/`_chunked` (`findSynthV2Completion`; a cancelled row never counts) BEFORE its link manifest is built — otherwise queue.add's idempotency fast path coalesces onto the completed children and they re-enter writtenRefs, so their old pages get quote-repaired, restamped, reverse-written and re-embedded every night. `collectChildPutPageSlugs` raw-fetches every (job_id, slug) pair (not `SELECT DISTINCT`) and rewrites bare-hash6 slugs to `<hash6>-c<idx>` for chunked children (orchestrator-side, zero Sonnet trust). Cap-hit skips write nothing new to `dream_verdicts` (the pass's cached triage verdict remains — a free cache hit on retry) and record no synthesis job, so raising the cap on next run re-attempts cleanly. Bounds INITIAL prompt size only; tool-loop turn-N accumulation is caught by terminal-error classification in `subagent.ts`. Verdict routing is gateway-routed: `makeJudgeClient(verdictModel)` (exported) mirrors `tryBuildGatewayClient` in `src/core/think/index.ts` — a construction-time provider/key probe returns `null` on a clear miss (unknown provider id via `resolveRecipe` AIConfigError, or Anthropic provider with no key via `hasAnthropicKey()`). The verdict loop wraps `judgeSignificance` in try/catch for `AIConfigError` so mid-run provider failures surface as per-transcript `worth=false, reasons=['gateway error: ...']` instead of crashing the phase. Canonical config key `models.dream.synthesize_verdict` (per `PER_TASK_KEYS` in `src/core/model-config.ts`); `JudgeClient` signature preserved verbatim for test-seam stability; CI guard `scripts/check-gateway-routed-no-direct-anthropic.sh` prevents reintroducing `new Anthropic()` here or in `think/index.ts`. At the queue.add boundary a conditional `anthropic:` prefix is applied ONLY when the resolved model has no colon AND starts with `claude-` (because `resolveModel` returns bare ids from `TIER_DEFAULTS`/`DEFAULT_ALIASES` and the subagent validator requires `provider:model` form) — avoids changing the shared constants which would ripple across every `resolveModel` caller. Pinned by `test/cycle/synthesize-gateway-adapter.test.ts`, `test/e2e/dream-synthesize-pglite.test.ts` (gateway-adapter mid-run AIConfigError catch), `test/cycle/regression-pr-wave-r1-r2-r4.test.ts`. Drain-loop lock renewal runs through exported `runDrainRenewalTick` (per-call AbortSignal + timeout + re-entrancy guard) — a hung renewLock cannot stack one checked-out slot per interval firing. Pinned by `test/cycle-drain-renewal.test.ts`. Execution mode: `dream.synthesize.mode` (default `oneshot`) threads to every child as `data.mode` alongside `oneshot_slug_suffix` (the structural suffix contract) and `require_writes: true`; `details.synthesis` adds mode/oneshot_jobs/fallback_jobs/agentic_jobs/fallback_reasons plus the drain telemetry (inline_concurrency_config/effective, drain_ms, queue-wait + runtime p50/p95, dead_jobs, degraded). Pre-retrieval LINK CANDIDATES manifest (link-manifest.ts, `dream.synthesize.link_manifest` default on) is built once per transcript from the cached triage entities/segment notes and spliced into `buildSynthesisPrompt` together with an ALLOWED WRITE PATHS block rendered from the trusted allow-list (the oneshot path never sees a tool schema, so the fence lives in the prompt; rule 2 points at the candidates first). Phase outcome gate: ALL children dead/cancelled → phase fails with SYNTH_ALL_CHILDREN_DEAD (fan-out details preserved on the failure); ANY non-completed child → the cooldown stamp is skipped so released idempotency keys retry next run; 'timeout' (parent stopped waiting) degrades but never triggers the all-dead error. Phase-end deferred-embed closure: whenever the phase wrote pages (regardless of mode — an agentic revert still sweeps debt left by earlier oneshot runs), a 120s-bounded `embedStalePages` (embed-stale.ts) embeds the NULL-embedding chunks of exactly the pages this phase wrote — never a source-wide sweep; the pre-existing stale backlog stays with the budget-tracked embed-backfill machinery — closing the gap on invocation shapes that never reach the global embed phase (`--phase synthesize`, autopilot per-source NON_GLOBAL_PHASES). Best-effort (never fails a phase that wrote its pages) and stamps the current embedding signature on fully-re-embedded pages so they stay inside the model-drift invalidation contract. The inline drain lives in `src/core/cycle/inline-drain.ts` (re-exported here for patterns.ts + `__testing`). Budget clamping: clamped to the remaining parent-job budget when `opts.deadlineAtMs` is threaded (via patterns.ts's `clampSubagentBudgets` template): the clamp re-runs against the live clock PER SUBMIT (the phase is a fan-out with claim-time-anchored child kill switches, so one phase-start clamp only bounds the first child); under the minimum child budget the phase skips honestly (`insufficient_cycle_budget`) or defers the remaining transcripts (`details.budget_deferred_transcripts`), the inline drain stops CLAIMING when the budget can't fit another child and unclaimed children are cancelled + deferred (they'd otherwise strand forever in the run's private queue), each completion wait is additionally bounded by the remaining parent budget (floored at 1s so already-terminal children still resolve), and a deferring run neither writes the 12h cooldown timestamp nor counts deferred transcripts as processed — deferral genuinely retries next cycle. THE gate is `passesTriageGate` (triage-rescue.ts) applied at report construction inside `runTriagePass`: threshold pass OR the verified-segment rescue for band scores `[dream.triage.rescue_floor (0.30), threshold)` with content_type in `dream.triage.rescue_content_types` and ≥ `dream.triage.rescue_min_segments` (default 2; 0 = off) of the judge's segments verifying as normalized transcript substrings (≥40 chars, deduped) — reports carry `rescued`/`verified_segments`, `details.triage` adds rescue_band/rescue_checked/rescue_fired + judge tokens_in/tokens_out/cost_usd (null when unpriced), and dream-retriage's reconcile/audit read the SAME predicate. TRIAGE_VERSION is 2 (peak-not-average rubric; segment selection prefers concrete facts/decisions). After slug collection and BEFORE the provenance stamp/reverse-write/embed sweep, the quote verify/repair pass (synthesize-verify.ts, `dream.synthesize.quote_verify` default on) runs on newly-created pages; the phase is wrapped in `withChatPhase('phase:synthesize')` (children keep their own job tag — minion_jobs stays the child-spend authority) and `details.synthesis` adds `quote_verify`, `children_zero_pages` (completed children with zero put_page writes — the rule-D disposition), and `spend` (`cost_basis: 'in+out+cache_read'`; children summed from minion_jobs tokens_input/output/cache_read priced at the configured synth model, triage from the pass usage; total_usd null unless both price) `buildSynthesisPrompt` is mode-aware (`mode: 'agentic' | 'oneshot'`, passed from `config.mode` at the sole submit site): agentic children keep the search-tool and final-summary guidance; tool-less oneshot children receive neither, so the prompt never contradicts `ONESHOT_SYSTEM`'s JSON-only rule (the oneshot prompt is stored as `data.prompt` and reused verbatim by the in-job agentic fallback, whose tools stay in the schema). Pinned by `test/cycle-dream-output-root.test.ts`. Managed enabled local synthesis uses durable page admission with original authority and canonical-mirror validation; completed source-incarnation-qualified children survive restart. Quote-repair failure cannot silently certify grounded publication. Remote maintenance remains unsupported.+- `src/core/cycle/synthesize.ts` — Synthesize phase: conversation-transcript-to-brain pipeline, a two-stage cascade where cheap scored triage gates frontier synthesis. Reads `dream.synthesize.session_corpus_dir`, runs `runTriagePass` (exported; bounded pool `dream.triage.concurrency` default 4, wall-clock cache-MISS budget `dream.triage.max_ms` default 5 min — cache hits are free and deferred files report `deferred: true`, never cached, so the next pass continues) whose judge `judgeSignificance` emits `{score 0-1 ordinal salience, content_type, segments ≤8 verbatim quotes, entities ≤12, reasons}` (non-overlapping bands LOW 0-0.29 / MEDIUM 0.30-0.69 / HIGH 0.70-1.0; head 50%/middle 20%/tail 30% sample within `dream.triage.max_chars` default 24K via `safeSplitIndex`; out-of-[0,1] scores are `unparseable`, never clamped) cached in `dream_verdicts` with the judging `model` + `TRIAGE_VERSION` — cache validity requires BOTH to match (switching `models.dream.triage` re-judges; `max_chars`/`max_tokens` deliberately excluded from validity — `dream retriage --force` re-judges under new sampling knobs). Degenerate verdicts (`truncated`/`refusal`/`unparseable`) are never cached. THE gate is `passesTriageGate` (triage-rescue.ts): `score >= dream.triage.threshold` (default 0.5) OR the verified-segment rescue, applied at report construction inside `runTriagePass` at READ time — retuning the threshold or rescue knobs re-gates with zero re-judging; the stored `worth_processing` boolean derives from the fixed `DEFAULT_TRIAGE_THRESHOLD` constant (back-compat only, never the live dial). Passing files fan out one subagent per chunk with `max_turns` from `dream.synthesize.max_turns` (default 16) and a bounded advisory `buildTriageMapBlock` (exported; score/type/entities + chunk-filtered segments, '' for legacy/degraded verdicts so the prompt is unchanged for those) spliced into `buildSynthesisPrompt`, with `allowed_slug_prefixes` (sourced from `skills/_brain-filing-rules.json` `dream_synthesize_paths.globs`; when `dream.synthesize.output_root` is set, `loadAllowedSlugPrefixes(outputRoot)` remaps the `wiki/`-rooted globs to the configured namespace, and the same root drives the prompt slug templates; default 'wiki', validated against the slug grammar via the exported `loadOutputRoot`). The phase is source-scoped: cycle.ts threads `cycleSourceId` as `opts.sourceId` → each child's `SubagentHandlerData.source_id` → the subagent tool registry's `OperationContext.sourceId`, so put_page writes, collected refs, the summary page, and reverse-writes all target the cycle's resolved source ('default' when unscoped; reverse-writes for the cycle's own source land at `brainDir/<slug>.md`, foreign sources under `brainDir/.sources/<id>/`). Orchestrator collects slugs from `subagent_tool_executions` (NOT `pages.updated_at`) and reverse-renders DB → markdown via `serializeMarkdown`. Cooldown via `dream.synthesize.last_completion_ts`, written only when children completed and neither synthesis-budget nor triage-budget deferrals remain. Idempotency keys `dream:synth-v2:<enc source>:filename:<enc basename>:<hash16>[:c<i>of<n>]` (byte-stable, pinned by `test/e2e/dream-synthesize-chunking.test.ts`; grammar parsed by exported `parseSynthV2Key`). Fan-out self-heals idempotency-coalesced rows stranded `waiting` in a FOREIGN dead `dream-inline-*` queue (cancel releases the key slot → re-add into the live run's queue) instead of burning the 35-min wait on a row no worker will ever claim. Opt-in per-source daily submission cap `dream.synthesize.max_submissions_per_source_per_day` (default 0 = off; skips whole files — never partial chunk sets; bypassed for explicit `--input/--date/--from/--to` targets; count-query failure fails OPEN with a stderr warn). `--dry-run` runs triage, skips synthesis; deferral-aware headlines append "(N not yet triaged — time budget...)" so a time-boxed cold pass never reads as mass rejection. `details.triage` (threshold/judged/cache_hits/unreliable/degraded/deferred/below_threshold + rescue_band/rescue_checked/rescue_fired + tokens_in/tokens_out/cost_usd) + `details.synthesis` (jobs/avg_turns/max_turns_config + quote_verify/spend/children_zero_pages) carry the phase telemetry. Subagent never gets fs-write access. `renderPageToMarkdown` (exported) stamps `dream_generated: true` + `dream_cycle_date` into every reverse-write's frontmatter; `writeSummaryPage` does the same on the summary index — this marker is the explicit identity surface `isDreamOutput` checks in `transcript-discovery.ts`. `stampDreamProvenance` additionally persists the same marker into the `pages.frontmatter` JSONB row (merge via `executeRawJsonb`, raw object bound to `$N::jsonb`) for every child-written page BEFORE reverse-rendering, so generated pages are DB-queryable and a later put_page write-through (which re-renders from the DB row) can't erase the stamp. `judgeSignificance`, `JudgeClient`, `runTriagePass`, `buildTriageMapBlock`, `parseSynthV2Key`, `loadSynthConfig`, `TRIAGE_VERSION`, and `DEFAULT_TRIAGE_THRESHOLD` are exported; the triage model resolves via an explicit pre-read of `models.dream.triage` (preferred; through exported `resolveAlias`) falling back to the standard `resolveModel` chain (`models.dream.synthesize_verdict` → deprecated `dream.synthesize.verdict_model` → tier `utility`). `splitTranscriptByBudget(content, contentHash, maxChars)` splits oversized transcripts at paragraph boundaries (`## Topic:` → `---` → `\n` ladder) using a deterministic offset seeded from the first 32 bits of `contentHash` so retries chunk identically; per-chunk char budget = `MODEL_CONTEXT_TOKENS[resolvedModel] × 0.9 × 3.5 chars/token` (non-Anthropic ids fall back to a 180K-token safe default + once-per-process stderr warn); operator overrides `dream.synthesize.max_prompt_tokens` (floor 100K, wins) and `dream.synthesize.max_chunks_per_transcript` (default 24); per-chunk subagent job/wait timeouts are `dream.synthesize.subagent_timeout_ms` / `dream.synthesize.subagent_wait_timeout_ms` (defaults 30/35 min). Legacy `dream:synth:` keys are never produced — `loadSuccessfulSynthesisKeys(engine, sourceId, keyPrefix)` reads the completed rows of BOTH key families once per phase, unioned with `dream_synthesis_completions` (where `MinionQueue.prune` archives completed `dream:synth%` keys before deleting their rows, so `jobs prune` never makes a synthesized transcript eligible again), so existing brains skip with `already_synthesized_legacy_single_chunk`/`_chunked` instead of re-spending the synthesis model, and a transcript whose synth-v2 children already completed skips with `already_synthesized_v2_single_chunk`/`_chunked` (`findSynthV2Completion`; a cancelled row never counts) BEFORE its link manifest is built — otherwise queue.add's idempotency fast path coalesces onto the completed children and they re-enter writtenRefs, so their old pages get quote-repaired, restamped, reverse-written and re-embedded every night. `collectChildPutPageSlugs` raw-fetches every (job_id, slug) pair (not `SELECT DISTINCT`) and rewrites bare-hash6 slugs to `<hash6>-c<idx>` for chunked children (orchestrator-side, zero Sonnet trust). Cap-hit skips write nothing new to `dream_verdicts` (the pass's cached triage verdict remains — a free cache hit on retry) and record no synthesis job, so raising the cap on next run re-attempts cleanly. Bounds INITIAL prompt size only; tool-loop turn-N accumulation is caught by terminal-error classification in `subagent.ts`. Verdict routing is gateway-routed: `makeJudgeClient(verdictModel)` (exported) mirrors `tryBuildGatewayClient` in `src/core/think/index.ts` — a construction-time provider/key probe returns `null` on a clear miss (unknown provider id via `resolveRecipe` AIConfigError, or Anthropic provider with no key via `hasAnthropicKey()`). The verdict loop wraps `judgeSignificance` in try/catch for `AIConfigError` so mid-run provider failures surface as per-transcript `worth=false, reasons=['gateway error: ...']` instead of crashing the phase. Canonical config key `models.dream.synthesize_verdict` (per `PER_TASK_KEYS` in `src/core/model-config.ts`); `JudgeClient` signature preserved verbatim for test-seam stability; CI guard `scripts/check-gateway-routed-no-direct-anthropic.sh` prevents reintroducing `new Anthropic()` here or in `think/index.ts`. At the queue.add boundary a conditional `anthropic:` prefix is applied ONLY when the resolved model has no colon AND starts with `claude-` (because `resolveModel` returns bare ids from `TIER_DEFAULTS`/`DEFAULT_ALIASES` and the subagent validator requires `provider:model` form) — avoids changing the shared constants which would ripple across every `resolveModel` caller. Pinned by `test/cycle/synthesize-gateway-adapter.test.ts`, `test/e2e/dream-synthesize-pglite.test.ts` (gateway-adapter mid-run AIConfigError catch), `test/cycle/regression-pr-wave-r1-r2-r4.test.ts`. Drain-loop lock renewal runs through exported `runDrainRenewalTick` (per-call AbortSignal + timeout + re-entrancy guard) — a hung renewLock cannot stack one checked-out slot per interval firing. Pinned by `test/cycle-drain-renewal.test.ts`. Execution mode: `dream.synthesize.mode` (default `oneshot`) threads to every child as `data.mode` alongside `oneshot_slug_suffix` (the structural suffix contract) and `require_writes: true`; `details.synthesis` adds mode/oneshot_jobs/fallback_jobs/agentic_jobs/fallback_reasons plus the drain telemetry (inline_concurrency_config/effective, drain_ms, queue-wait + runtime p50/p95, dead_jobs, degraded). Pre-retrieval LINK CANDIDATES manifest (link-manifest.ts, `dream.synthesize.link_manifest` default on) is built once per transcript from the cached triage entities/segment notes and spliced into `buildSynthesisPrompt` together with an ALLOWED WRITE PATHS block rendered from the trusted allow-list (the oneshot path never sees a tool schema, so the fence lives in the prompt; rule 2 points at the candidates first). Phase outcome gate: ALL children dead/cancelled → phase fails with SYNTH_ALL_CHILDREN_DEAD (fan-out details preserved on the failure); ANY non-completed child → the cooldown stamp is skipped so released idempotency keys retry next run; 'timeout' (parent stopped waiting) degrades but never triggers the all-dead error. Phase-end deferred-embed closure: whenever the phase wrote pages (regardless of mode — an agentic revert still sweeps debt left by earlier oneshot runs), a 120s-bounded `embedStalePages` (embed-stale.ts) embeds the NULL-embedding chunks of exactly the pages this phase wrote — never a source-wide sweep; the pre-existing stale backlog stays with the budget-tracked embed-backfill machinery — closing the gap on invocation shapes that never reach the global embed phase (`--phase synthesize`, autopilot per-source NON_GLOBAL_PHASES). Best-effort (never fails a phase that wrote its pages) and stamps the current embedding signature on fully-re-embedded pages so they stay inside the model-drift invalidation contract. The inline drain lives in `src/core/cycle/inline-drain.ts` (re-exported here for patterns.ts + `__testing`). Budget clamping: clamped to the remaining parent-job budget when `opts.deadlineAtMs` is threaded (via patterns.ts's `clampSubagentBudgets` template): the clamp re-runs against the live clock PER SUBMIT (the phase is a fan-out with claim-time-anchored child kill switches, so one phase-start clamp only bounds the first child); under the minimum child budget the phase skips honestly (`insufficient_cycle_budget`) or defers the remaining transcripts (`details.budget_deferred_transcripts`), the inline drain stops CLAIMING when the budget can't fit another child and unclaimed children are cancelled + deferred (they'd otherwise strand forever in the run's private queue), each completion wait is additionally bounded by the remaining parent budget (floored at 1s so already-terminal children still resolve), and a deferring run neither writes the 12h cooldown timestamp nor counts deferred transcripts as processed — deferral genuinely retries next cycle. THE gate is `passesTriageGate` (triage-rescue.ts) applied at report construction inside `runTriagePass`: threshold pass OR the verified-segment rescue for band scores `[dream.triage.rescue_floor (0.30), threshold)` with content_type in `dream.triage.rescue_content_types` and ≥ `dream.triage.rescue_min_segments` (default 2; 0 = off) of the judge's segments verifying as normalized transcript substrings (≥40 chars, deduped) — reports carry `rescued`/`verified_segments`, `details.triage` adds rescue_band/rescue_checked/rescue_fired + judge tokens_in/tokens_out/cost_usd (null when unpriced), and dream-retriage's reconcile/audit read the SAME predicate. TRIAGE_VERSION is 2 (peak-not-average rubric; segment selection prefers concrete facts/decisions). After slug collection and BEFORE the provenance stamp/reverse-write/embed sweep, the quote verify/repair pass (synthesize-verify.ts, `dream.synthesize.quote_verify` default on) runs on newly-created pages; the phase is wrapped in `withChatPhase('phase:synthesize')` (children keep their own job tag — minion_jobs stays the child-spend authority) and `details.synthesis` adds `quote_verify`, `children_zero_pages` (completed children with zero put_page writes — the rule-D disposition), and `spend` (`cost_basis: 'in+out+cache_read'`; children summed from minion_jobs tokens_input/output/cache_read priced at the configured synth model, triage from the pass usage; total_usd null unless both price) `buildSynthesisPrompt` is mode-aware (`mode: 'agentic' | 'oneshot'`, passed from `config.mode` at the sole submit site): agentic children keep the search-tool and final-summary guidance; tool-less oneshot children receive neither, so the prompt never contradicts `ONESHOT_SYSTEM`'s JSON-only rule (the oneshot prompt is stored as `data.prompt` and reused verbatim by the in-job agentic fallback, whose tools stay in the schema). Pinned by `test/cycle-dream-output-root.test.ts`. Managed enabled local synthesis uses durable page admission with original authority and canonical-mirror validation; completed source-incarnation-qualified children survive restart. Quote-repair failure cannot silently certify grounded publication. Remote maintenance remains unsupported.- `src/core/cycle/transcript-discovery.ts` — Pure filesystem walk for synthesize. `discoverTranscripts(opts)` filters `.txt` files by date range, min_chars, and word-boundary regex `excludePatterns` (`medical` matches "medical advice" but NOT "comedical"; power users may pass full regex). `readSingleTranscript(path)` is the `gbrain dream --input <file>` ad-hoc path. Self-consumption guard: `DREAM_OUTPUT_MARKER_RE` (anchored at frontmatter open `---\n`, optional BOM + CRLF tolerance, scans first 2000 chars for `dream_generated: true` with case-insensitive value and word boundary on `true`) drives `isDreamOutput(content, bypass=false)`. Both functions skip matching files and emit a `[dream] skipped <basename>: dream_generated marker` stderr log (no silent skips). An `excludePatterns` hit is never logged per file (the matching files are sensitive by definition); instead both functions emit ONE `[dream] excluded N transcript(s) matching exclude_patterns (<label>: n, ...)` stderr line at the end of discovery, naming only the count and the configured pattern labels that fired, never a path, basename, or content. `DEFAULT_EXCLUDE_PATTERNS` is unchanged (`medical`, `therapy`). `bypassGuard?: boolean` on `DiscoverOpts` and `readSingleTranscript`'s opts disables the guard for the explicit `--unsafe-bypass-dream-guard` escape hatch only — never auto-applied for `--input`.diff --git a/docs/architecture/key-files/core-minions-1.md b/docs/architecture/key-files/core-minions-1.mdindex 1195f10e24..724c6004d6 100644--- a/docs/architecture/key-files/core-minions-1.md+++ b/docs/architecture/key-files/core-minions-1.md@@ -71,7 +71,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/minions/protected-names.ts` — side-effect-free constant module exporting `PROTECTED_JOB_NAMES` + `isProtectedJobName()`. Kept pure so queue core can import without loading handler modules. `PROTECTED_JOB_NAMES` includes `synthesize`, `patterns`, `consolidate`. These phases internally submit `subagent` children with `allowProtectedSubmit=true` and can spend Anthropic credits. Only trusted local callers (CLI, autopilot, `doctor --remediate`) can submit them; MCP requests are rejected by `submit_job`'s protected-name guard.-- `src/core/minions/queue.ts` — MinionQueue class (submit, claim, complete, fail, stall detection, parent-child, depth/child-cap, per-job timeouts, cascade-kill, attachments, idempotency keys, child_done inbox, removeOnComplete/Fail). `add()` takes a 4th `trusted` arg (separate from `opts` to prevent spread leakage); protected names in `PROTECTED_JOB_NAMES` require `{allowProtectedSubmit: true}` and the check runs trim-normalized (whitespace-bypass safe). The same trusted arg carries `{allowPgliteInlineWorker: true}`, a narrowly scoped exception used only when `gbrain jobs submit embed-backfill --follow` starts and awaits a worker in that process. Before config, schema, policy, SQL, or transaction access, `add()` invokes the centralized embed-backfill admission gate; PGLite and unknown engine kinds refuse, while explicit Postgres preserves queued submission. `add()` plumbs `max_stalled` through with a `[1, 100]` clamp; omitted values let the schema DEFAULT (5) kick in. `handleWallClockTimeouts(lockDurationMs)` is Layer 3 kill shot for jobs where `FOR UPDATE SKIP LOCKED` stall detection and the timeout sweep both fail to evict (wedged worker holding a row lock via a pending transaction). The submission backpressure guard covers two options sharing one `pg_advisory_xact_lock` namespace keyed on `(name, queue, source)`: `maxWaiting` (rate cap, counts `waiting` only, NULL-source-as-wildcard scope) and `maxPending` (single-flight, counts `waiting` + live-lock `active` rows where `lock_until > now()`, EXACT source scope via `COALESCE(data->>'sourceId', data->>'source_id')` — an expired-lock active never suppresses, keeping the waitingClaimable wedge detectors fed). All three coalesce return paths (idempotency fast-path, cap-hit, ON CONFLICT race fallback) stamp non-persisted `coalesced: true` metadata on the returned job. Both filter on `queue` in addition to `name` so cross-queue same-name jobs don't suppress each other. `claim` and `renewLock` issue their UPDATE via `engine.executeRawDirect` (not `executeRaw`) so the lock heartbeat runs on the direct session-mode pool that the transaction pooler won't recycle mid-hold; on PGLite this is identical to `executeRaw`. The two terminal dead-letter paths (`handleWallClockTimeouts` wall-clock kill and the stall dead-letter CTE in the stall sweep) BOTH increment `attempts_made` so a long job killed there reads as an honest attempt instead of `attempts 0 / started N`; the stall path also bumps `stalled_counter`, surfaced by `gbrain jobs get` as `Attempts: M/N (started: X, stalled: S/MaxS)`. At submit, `add()` stamps a default `timeout_ms` via `defaultTimeoutMsFor(jobName)` (from `handler-timeouts.ts`) when the caller passed none, and `claim()` COALESCEs a still-NULL `timeout_ms` from `HANDLER_DEFAULT_TIMEOUT_MS` (raw-object jsonb bind) deriving `timeout_at` from the coalesced value — the durable invariant covering rows that predate submit-time stamping; an explicit `opts.timeout_ms` always wins. The lock lease follows the identical three-layer shape: `add()` stamps `opts.lock_duration_ms` (clamped [5s,1h] via the shared `clampLockDurationMs`; INSERT-only — an idempotency-key re-submit never mutates the first submitter's lease) else `defaultLockDurationMsFor(jobName)`; `claim()` derives `lock_until` from `COALESCE(lock_duration_ms, map, worker default)` and stamps the resolved lease, SQL-clamping the row/map-resolved value to [5s,1h] (the worker-default fallback passes through unclamped — operator-configured, and tests legitimately use sub-5s leases) so a bypass-written out-of-range row can't produce a pathological lease; `handleWallClockTimeouts`' null-timeout fallback uses `COALESCE(lock_duration_ms, worker default)`. `handleStalled(graceMsOverride?)` applies the stall-sweep reclaim grace (`GBRAIN_MINION_STALL_RECLAIM_GRACE_MS`, default 15s, 0 = legacy predicate, capped at 600s with a warn-once clamp so an oversized value can't disable stalled-job recovery) to all three sweep predicates — a lease that lapsed within the grace is a starved owner's head start, not a steal candidate. Guarded by `test/queue-lock-retry.test.ts` (claim never falls back to `executeRaw`), `test/postgres-execute-raw-direct.test.ts` (routing decision matrix), and `test/minions.test.ts` (attempt accounting + default-timeout stamping). `MinionQueue.add()` gates `subagent` jobs on capability, not provider: `data.model` is classified via `classifyCapabilities()` (lazy-imported from `src/core/ai/capabilities.ts` to keep queue's eager-load surface small) and rejected only when the model cannot run a tool loop (`unusable:no_tools`) or names an unknown provider; degraded verdicts pass through with a gateway cost warning. Layer 1 of the three-layer subagent capability enforcement (layers 2+3: `model-config.ts:enforceSubagentCapable` runtime fallback + `src/commands/doctor.ts` `subagent_provider` check). Pinned by `test/agent-cli.test.ts`. All three terminal reaper paths (stall dead-letter, wall-clock kill, cascade) route through the ONE private `killJobs(tx, rows, cause, message)` tail: it emits `child_done(outcome)` to each non-terminal parent's inbox and flips any `waiting-children` parent whose last open child just died back to `waiting` — so a dead-lettered child can never strand its aggregator parent. Callers lock parents FIRST via `lockParentsOrdered` (ascending-id row locks, matching `failJob`'s parent-before-child order) so the reapers and `failJob` can never deadlock on parent/child lock acquisition. An idempotent stranded-parent sweep runs once per stall tick (~30s): any `waiting-children` parent with zero non-terminal children flips back to `waiting` (single UPDATE, NOT EXISTS on an indexed FK) — self-heals every stranding class, including parents stranded before the sweep existed. Every automatic re-run path clears `started_at` (`failJob`'s delayed retry branch, the stall requeue, lease release, `promoteDelayed`, and the parent-unblock flips) so the per-attempt wall clock measures execution, not backoff/queue wait — a retried job can't be dead-lettered by the wall-clock sweep before executing a line. Pinned by `test/queue-stall-parent-unblock.test.ts` + `test/queue-started-at-retry.test.ts`. `renewLock` accepts optional `{signal}` forwarded to executeRawDirect so the renewal tick's timeout race CANCELS a hung UPDATE instead of orphaning a checked-out pool slot (best-effort — the token fence is the correctness authority; a late-landing renewal can only extend a lease nobody else claimed).+- `src/core/minions/queue.ts` — MinionQueue class (submit, claim, complete, fail, stall detection, parent-child, depth/child-cap, per-job timeouts, cascade-kill, attachments, idempotency keys, child_done inbox, removeOnComplete/Fail). `prune()` archives each completed `dream:synth%` subagent key into `dream_synthesis_completions` in the same statement that deletes the row, so pruning never re-arms paid synthesis. `add()` takes a 4th `trusted` arg (separate from `opts` to prevent spread leakage); protected names in `PROTECTED_JOB_NAMES` require `{allowProtectedSubmit: true}` and the check runs trim-normalized (whitespace-bypass safe). The same trusted arg carries `{allowPgliteInlineWorker: true}`, a narrowly scoped exception used only when `gbrain jobs submit embed-backfill --follow` starts and awaits a worker in that process. Before config, schema, policy, SQL, or transaction access, `add()` invokes the centralized embed-backfill admission gate; PGLite and unknown engine kinds refuse, while explicit Postgres preserves queued submission. `add()` plumbs `max_stalled` through with a `[1, 100]` clamp; omitted values let the schema DEFAULT (5) kick in. `handleWallClockTimeouts(lockDurationMs)` is Layer 3 kill shot for jobs where `FOR UPDATE SKIP LOCKED` stall detection and the timeout sweep both fail to evict (wedged worker holding a row lock via a pending transaction). The submission backpressure guard covers two options sharing one `pg_advisory_xact_lock` namespace keyed on `(name, queue, source)`: `maxWaiting` (rate cap, counts `waiting` only, NULL-source-as-wildcard scope) and `maxPending` (single-flight, counts `waiting` + live-lock `active` rows where `lock_until > now()`, EXACT source scope via `COALESCE(data->>'sourceId', data->>'source_id')` — an expired-lock active never suppresses, keeping the waitingClaimable wedge detectors fed). All three coalesce return paths (idempotency fast-path, cap-hit, ON CONFLICT race fallback) stamp non-persisted `coalesced: true` metadata on the returned job. Both filter on `queue` in addition to `name` so cross-queue same-name jobs don't suppress each other. `claim` and `renewLock` issue their UPDATE via `engine.executeRawDirect` (not `executeRaw`) so the lock heartbeat runs on the direct session-mode pool that the transaction pooler won't recycle mid-hold; on PGLite this is identical to `executeRaw`. The two terminal dead-letter paths (`handleWallClockTimeouts` wall-clock kill and the stall dead-letter CTE in the stall sweep) BOTH increment `attempts_made` so a long job killed there reads as an honest attempt instead of `attempts 0 / started N`; the stall path also bumps `stalled_counter`, surfaced by `gbrain jobs get` as `Attempts: M/N (started: X, stalled: S/MaxS)`. At submit, `add()` stamps a default `timeout_ms` via `defaultTimeoutMsFor(jobName)` (from `handler-timeouts.ts`) when the caller passed none, and `claim()` COALESCEs a still-NULL `timeout_ms` from `HANDLER_DEFAULT_TIMEOUT_MS` (raw-object jsonb bind) deriving `timeout_at` from the coalesced value — the durable invariant covering rows that predate submit-time stamping; an explicit `opts.timeout_ms` always wins. The lock lease follows the identical three-layer shape: `add()` stamps `opts.lock_duration_ms` (clamped [5s,1h] via the shared `clampLockDurationMs`; INSERT-only — an idempotency-key re-submit never mutates the first submitter's lease) else `defaultLockDurationMsFor(jobName)`; `claim()` derives `lock_until` from `COALESCE(lock_duration_ms, map, worker default)` and stamps the resolved lease, SQL-clamping the row/map-resolved value to [5s,1h] (the worker-default fallback passes through unclamped — operator-configured, and tests legitimately use sub-5s leases) so a bypass-written out-of-range row can't produce a pathological lease; `handleWallClockTimeouts`' null-timeout fallback uses `COALESCE(lock_duration_ms, worker default)`. `handleStalled(graceMsOverride?)` applies the stall-sweep reclaim grace (`GBRAIN_MINION_STALL_RECLAIM_GRACE_MS`, default 15s, 0 = legacy predicate, capped at 600s with a warn-once clamp so an oversized value can't disable stalled-job recovery) to all three sweep predicates — a lease that lapsed within the grace is a starved owner's head start, not a steal candidate. Guarded by `test/queue-lock-retry.test.ts` (claim never falls back to `executeRaw`), `test/postgres-execute-raw-direct.test.ts` (routing decision matrix), and `test/minions.test.ts` (attempt accounting + default-timeout stamping). `MinionQueue.add()` gates `subagent` jobs on capability, not provider: `data.model` is classified via `classifyCapabilities()` (lazy-imported from `src/core/ai/capabilities.ts` to keep queue's eager-load surface small) and rejected only when the model cannot run a tool loop (`unusable:no_tools`) or names an unknown provider; degraded verdicts pass through with a gateway cost warning. Layer 1 of the three-layer subagent capability enforcement (layers 2+3: `model-config.ts:enforceSubagentCapable` runtime fallback + `src/commands/doctor.ts` `subagent_provider` check). Pinned by `test/agent-cli.test.ts`. All three terminal reaper paths (stall dead-letter, wall-clock kill, cascade) route through the ONE private `killJobs(tx, rows, cause, message)` tail: it emits `child_done(outcome)` to each non-terminal parent's inbox and flips any `waiting-children` parent whose last open child just died back to `waiting` — so a dead-lettered child can never strand its aggregator parent. Callers lock parents FIRST via `lockParentsOrdered` (ascending-id row locks, matching `failJob`'s parent-before-child order) so the reapers and `failJob` can never deadlock on parent/child lock acquisition. An idempotent stranded-parent sweep runs once per stall tick (~30s): any `waiting-children` parent with zero non-terminal children flips back to `waiting` (single UPDATE, NOT EXISTS on an indexed FK) — self-heals every stranding class, including parents stranded before the sweep existed. Every automatic re-run path clears `started_at` (`failJob`'s delayed retry branch, the stall requeue, lease release, `promoteDelayed`, and the parent-unblock flips) so the per-attempt wall clock measures execution, not backoff/queue wait — a retried job can't be dead-lettered by the wall-clock sweep before executing a line. Pinned by `test/queue-stall-parent-unblock.test.ts` + `test/queue-started-at-retry.test.ts`. `renewLock` accepts optional `{signal}` forwarded to executeRawDirect so the renewal tick's timeout race CANCELS a hung UPDATE instead of orphaning a checked-out pool slot (best-effort — the token fence is the correctness authority; a late-landing renewal can only extend a lease nobody else claimed).- `src/core/minions/rate-leases.ts` — lease-based concurrency cap for outbound providers (default key `anthropic:messages`, max via `GBRAIN_ANTHROPIC_MAX_INFLIGHT`). Owner-tagged rows with `expires_at` auto-prune on acquire; `pg_advisory_xact_lock` guards check-then-insert; CASCADE on owning job deletion. `renewLeaseWithBackoff` retries 3x (250/500/1000ms). Canonical home of `RateLeaseUnavailableError` (thrown when acquire finds no slot; the worker and the inline dream drain both recognize it and requeue WITHOUT burning an attempt — lease-full is a scheduling condition, not a failure; `subagent.ts` re-exports it for compatibility) and `leaseFullBackoffMs()` (the shared 1–3s jittered lease-full requeue backoff `worker.ts` and `inline-drain.ts` both use, so the two curves cannot silently desync).diff --git a/docs/architecture/key-files/core-services-1.md b/docs/architecture/key-files/core-services-1.mdindex abf85e948a..8311138596 100644--- a/docs/architecture/key-files/core-services-1.md+++ b/docs/architecture/key-files/core-services-1.md@@ -39,7 +39,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/chunkers/symbol-resolver.ts` — resolves and stamps each bounded chunk batch in one transaction. It takes ordered source/page guards before edge reads, revalidates current chunk/page/slug identity under those guards, and commits edge metadata with its backfill watermark. Concurrent projection replacement cannot certify new edges using an old resolver read; rollback leaves both metadata and watermark unchanged. Pinned by `test/symbol-resolver-projection-race.test.ts` with PGLite serialization and a real PostgreSQL lock-wait receipt.-- `src/core/connectors/` (directory) — the LIVE chat-history connector layer (front-end to the transcripts pipeline). `types.ts`: the `ChatHistoryProvider` contract (mirror of `TranscriptAdapter` — leaf module per provider; `spoolFormat` names the adapter that parses its output; dated `HostSpecTarget`). `credentials.ts`: file-plane store at `~/.gbrain/connectors/<provider>.json` (0600, dir 0700, atomic tmp+rename), env-above-file `resolveCredential` returning `{cred, source}`; credentials NEVER touch the DB / `sources.config` / config planes / op payloads. `classify.ts`: the pure §2A/§2B response classifier — distinguishes a Cloudflare-fingerprint 403 (`forbidden_fingerprint`, dead-end) from an auth-expired 403 (`auth_required`, re-auth) and flags a parses-but-no-`items` body as `drift`. `client.ts`: `ConnectorClient` modeled on `GitHubClient` (plain fetch against a hardcoded ORIGIN + off-origin guard so the cookie/bearer never leaks, browser UA, refresh-once-on-401, Retry-After backoff; `fetchImpl`/`sleep`/`now` injectable — NOT `fetchWithSSRFGuard`, which breaks SNI on Cloudflare hosts). `providers/chatgpt.ts` + `providers/claude.ts` (registry in `registry.ts`; Perplexity deliberately absent — no adapter): offset/updated pagination with a per-pass 500-page cap and a `stopBefore` watermark break, epoch/ISO normalization, ChatGPT's `is_archived` second pass, org discovery + content-block text assembly for Claude, and a `refreshAccessToken` (ChatGPT re-mints from the cookie via `/api/auth/session`; Claude's cookie is terminal). `spool.ts`: writes fetched conversations in native-export shape (0600, batched, pruned in the orchestrator `finally`). `sync.ts`: `runConnectorSync` — resolve credential → probe → read the **config-scalar watermark** `connectors.<p>.watermark_iso` (NOT op_checkpoint, whose 7-day GC would wipe it → full re-fetch) → list to `watermark − windowDays` → fetch → spool → `runTranscriptsIngest` → advance the watermark ONLY on a fully clean run → `logIngest` receipt → stamp `last_sync_at` → engine-branched embed kickoff (`maybeKickoffEmbed`: Postgres `submitEmbedBackfill`, PGLite `runEmbedCore` inline — NEVER `submitEmbedBackfill`, which refuses `no_worker_surface`). `config-keys.ts`: the `connectors.` key builders + the pure `isConnectorSyncStale(last, now, floor)` dispatch gate. `oauth-pkce.ts`: dependency-free S256 PKCE loopback (`Bun.serve`, timing-safe state) — best-effort `--try-oauth` only. Surfaces: the `connectors_status`/`connector_sync` ops (`src/core/ops/connectors.ts`, both `localOnly`), the `gbrain connectors` command family (`src/commands/connectors/` peeled dir), the `connector-sync` minion handler (`src/core/minions/handlers/connector-sync.ts`, single-flight lock), the autopilot `maybeDispatchConnectorSyncs` gate, and the `connectors` doctor check. Pinned by `test/connectors-*.test.ts` + `test/e2e/connectors-sync-pglite.test.ts` (full pipeline against a `Bun.serve` fixture backend, keyless) + `test/e2e/connector-sync-handler-pglite.test.ts` + `test/e2e/doctor-connectors-pglite.test.ts`.+- `src/core/connectors/` (directory) — the LIVE chat-history connector layer (front-end to the transcripts pipeline). `types.ts`: the `ChatHistoryProvider` contract (mirror of `TranscriptAdapter` — leaf module per provider; `spoolFormat` names the adapter that parses its output; dated `HostSpecTarget`). `credentials.ts`: file-plane store at `~/.gbrain/connectors/<provider>.json` (0600, dir 0700, atomic tmp+rename), env-above-file `resolveCredential` returning `{cred, source}`; credentials NEVER touch the DB / `sources.config` / config planes / op payloads. `classify.ts`: the pure §2A/§2B response classifier — distinguishes a Cloudflare-fingerprint 403 (`forbidden_fingerprint`, dead-end) from an auth-expired 403 (`auth_required`, re-auth) and flags a parses-but-no-`items` body as `drift`. `client.ts`: `ConnectorClient` modeled on `GitHubClient` (plain fetch against a hardcoded ORIGIN + off-origin guard so the cookie/bearer never leaks, browser UA, refresh-once-on-401, Retry-After backoff; `fetchImpl`/`sleep`/`now` injectable — NOT `fetchWithSSRFGuard`, which breaks SNI on Cloudflare hosts). `providers/chatgpt.ts` + `providers/claude.ts` (registry in `registry.ts`; Perplexity deliberately absent — no adapter): offset/updated pagination with a per-pass 500-page cap and a `stopBefore` watermark break, epoch/ISO normalization, ChatGPT's `is_archived` second pass, org discovery + content-block text assembly for Claude, and a `refreshAccessToken` (ChatGPT re-mints from the cookie via `/api/auth/session`; Claude's cookie is terminal). `spool.ts`: writes fetched conversations in native-export shape (0600, batched, pruned in the orchestrator `finally`). `sync.ts`: `runConnectorSync` — resolve credential → probe → read the **per-(provider, source) config-scalar watermark** `connectors.<p>.source.<id>.watermark_iso` (NOT op_checkpoint, whose 7-day GC would wipe it → full re-fetch) → list to `watermark − windowDays` → skip stubs whose `updatedAt` the source's `synced` ledger already holds and stubs quarantined in its `failed` ledger (after `QUARANTINE_ATTEMPTS` = 3 fetch failures at one `updatedAt`; an edit or `--full` retries) BEFORE the `--limit` cap, so capped runs progress → fetch → spool → `runTranscriptsIngest` → record ingested ids from clean batches → advance the watermark ONLY on a clean run (quarantined ids no longer block it; ledger entries older than the next list window are pruned) → `logIngest` receipt → stamp per-source `last_sync_at` → engine-branched embed kickoff (`maybeKickoffEmbed`: Postgres `submitEmbedBackfill`, PGLite `runEmbedCore` inline — NEVER `submitEmbedBackfill`, which refuses `no_worker_surface`). `config-keys.ts`: the `connectors.` key builders (sync progress keyed by `(provider, source)`; `auth_error_at` stays per provider because it describes the shared credential), `readConnectorState`/`writeConnectorState` (a legacy per-provider `watermark_iso`/`last_sync_at` is honored only for the scheduled `connectors.source_id` source until that source writes its own key, which retires it), and the pure `isConnectorSyncStale(last, now, floor)` dispatch gate. Status, doctor and the autopilot gate read the scheduled source's state. `oauth-pkce.ts`: dependency-free S256 PKCE loopback (`Bun.serve`, timing-safe state) — best-effort `--try-oauth` only. Surfaces: the `connectors_status`/`connector_sync` ops (`src/core/ops/connectors.ts`, both `localOnly`), the `gbrain connectors` command family (`src/commands/connectors/` peeled dir), the `connector-sync` minion handler (`src/core/minions/handlers/connector-sync.ts`, single-flight lock), the autopilot `maybeDispatchConnectorSyncs` gate, and the `connectors` doctor check. Pinned by `test/connectors-*.test.ts` + `test/e2e/connectors-sync-checkpoints-pglite.test.ts` (per-source watermark, `--limit` progress, quarantine, retitle) + `test/e2e/connectors-sync-pglite.test.ts` (full pipeline against a `Bun.serve` fixture backend, keyless) + `test/e2e/connector-sync-handler-pglite.test.ts` + `test/e2e/doctor-connectors-pglite.test.ts`.- `src/core/context/` — Retrieval Reflex (Layer 1). `entity-salience.ts`: pure, zero-LLM, precision-biased `extractCandidates(text)` (capitalized runs + `@handles`, STOPWORDS + soft COMMON_WORDS + sentence-start guard, deterministic, capped; a lowercase weak pass additionally emits `weak: true` candidates — lowercase words ≥3 chars on a separate `MAX_WEAK_CANDIDATES=32` budget that never evicts strong candidates — which downstream may resolve through the alias arm ONLY) + `extractCandidatesFromWindow(turns)` (merges per-turn extraction across the last N turns by normalizeAlias form with occurrence/newest-turn/user-mention metadata; salience-ordered — recency > frequency > user-role — so the cap drops stale assistant chatter first). `retrieval-reflex.ts`: `resolveEntitiesToPointers(engine, sourceId, candidates, opts)` — alias arm (`resolveAliases`, caught per-arm for pre-v110 brains) + exact title/slug-suffix arm (real slugs are namespaced `people/x` but `slugify` drops the prefix) + two lexical identity arms behind `opts.lexicalArms` (kill switch: config `retrieval_reflex_lexical_arms` / env `GBRAIN_RETRIEVAL_REFLEX_LEXICAL_ARMS`, default on): weak lowercase candidates probe the ALIAS arm ONLY (never title/slug-suffix, where ordinary lowercase words would fabricate pointers) and require GLOBAL uniqueness across all sources in play; the surname arm resolves a strong single capitalized token ≥3 chars via a `lower(title) LIKE '% <token>'` predicate on the same query, with exact-arm precedence and ambiguity counted over ALL person rows carrying the surname — ambiguity in either arm injects nothing; pointers carry `source_id`/`arm`/`confidence`/`matchedNorm` (`ARM_CONFIDENCE` alias 0.9 / title 0.8 / title-surname 0.72 (deliberately above the volunteer layer's 0.70 gate, below title) / slug-suffix 0.6 lives next to the arm definitions; arm-2 provenance classified in JS since the combined OR can't report which predicate matched); opts: `sourceIds?` federated scope (alias arm loops per source, arm 2 uses `source_id = ANY`), `suppression?` ('slug-and-title' default; 'slug-only' REQUIRED under windowing — the title rule would suppress every entity merely mentioned in a prior window turn), ambient-channel event logging is DELIVERY-side, not in-resolver — `logDeliveredReflexPointers(engine, pointers)` fires only once a block is actually handed to the consumer (serve's resolve-IPC `onDelivered` hook post-write; `buildReflexAddition` post-timeout on the direct rung), so abandoned/timed-out blocks never pollute the volunteered-vs-used stats; its event write is registered synchronously before return so the CLI background-work drain cannot miss it; synopsis runs through `stripTakesFence`/`stripFactsFence` (the same privacy boundary `get_page` applies) so private facts never reach the prompt; capped at `MAX_POINTERS`. `reflex.ts`: the orchestrator + engine-aware resolver ladder (host `resolveEntities` → PGLite serve IPC → Postgres cached process-singleton → disabled), zero-candidate fast path, fail-open + timeout, heartbeat write for the doctor check, `reflexEnabled(cfg)` (file/env gate, default ON; DB-plane does NOT gate — `assemble()` is sync); windowed extraction when `windowTurns` present and `retrieval_reflex_window_turns` (default 4; 1 = single-turn behavior) > 1 — switches suppression to slug-only; accept-side reflex-channel logging fires after the per-turn timeout admits the block (direct-Postgres rung only — IPC logs server-side at delivery; host-injected resolvers are a documented gap). `resolve-ipc.ts`: local unix-socket resolve protocol (client + server) so PGLite resolves through the single connection `gbrain serve` holds (a second opener would hit the exclusive lock; a subprocess would force-steal it past the 5-min staleness window and crash). Wired into both serve transports via `src/mcp/resolve-ipc-binding.ts` (engine-uniform; socket + secret keyed off `hash12(database_url)` under `~/.gbrain/run`, cleaned up on shutdown). Doctor surface: `retrieval_reflex_health` in `src/commands/doctor.ts` (reads the heartbeat for truthful runtime status; categorized in `doctor-categories.ts`) + `volunteer_channels` (engine-aware sibling: groups `context_volunteer_events` by channel over 7 days so operators see which push channels — reflex/op/watch/claude-code/codex — actually fire; info-only; the LOCAL doctor runs it brain-wide while the remote report path threads the caller's source scope, so a source-bound token never sees other sources' activity counts/timestamps; counts are reconciled against the hook heartbeat over the same 7-day window — a mostly-degraded week gets a CAUTION note, since a server-side delivery count isn't proof of injection; quiet-channel guidance is engine-aware — Postgres brains are told the hook lane is quiet by design rather than to chase registration — and walks both quiet classes (installed-but-unregistered vs registered-but-quiet; the check can't inspect registration itself); pre-v117 tolerant, and transient DB errors are reported as such, never as an old schema; pinned by `test/doctor-volunteer-channels.test.ts`). Config: `retrieval_reflex` + `retrieval_reflex_max_pointers` + `retrieval_reflex_window_turns` + `retrieval_reflex_lexical_arms` in `src/core/config.ts` (env `GBRAIN_RETRIEVAL_REFLEX_WINDOW_TURNS`, `GBRAIN_RETRIEVAL_REFLEX_LEXICAL_ARMS`). `volunteer.ts`: `parseWindow` (lenient `user:`/`assistant:` prefixes, unprefixed → one user turn), `volunteerContext` (extract → resolve → +0.05 multi-turn/newest-turn boost → `min_confidence` 0.7 gate → cap 3/5; deterministic rationale strings, never raw conversation text; slug-only suppression), `volunteerUsageStats` (per-arm/channel precision from the `pages.last_retrieved_at > volunteered_at` join — APPROXIMATE: the 5-min last-retrieved throttle causes false negatives, unrelated reads false positives). `volunteer-events.ts`: `insertVolunteerEvents` (ONE multi-row parameterized INSERT), `logVolunteerEventsFireAndForget` + bounded drain registered as the `volunteer-events` background-work sink (order 4), `purgeStaleVolunteerEvents` (90-day GC, called from the dream cycle's purge phase). Policy layer ships as the `retrieval-reflex` recipe (`recipes/retrieval-reflex/`). Pinned by `test/context/entity-salience.test.ts`, `test/retrieval-reflex.test.ts`, `test/retrieval-reflex-pre-v110.test.ts`, `test/context/resolve-ipc.test.ts`, `test/doctor-retrieval-reflex.test.ts`, `test/volunteer-context.test.ts`, `test/e2e/volunteer-context-postgres.test.ts`. Checkpoint-compaction modules in this dir: `corpus-segments.ts` — engine-free content-addressed compaction segments (`<session>.seg-<hash24>.txt`, idempotent by name; parsers accept 12–64 hex), the hash-keyed per-session ledger (atomic tmp+rename, fail-open, entry order = the only ordinal), `sliceBoundaryWindow`/`splitByBoundaries`, the redacted `renderSegmentText` (a segment is NEVER written unscanned — unlike the session-end full write, which degrades-and-writes), exact-set `coverageComplete`/`decideCorpusMode` (count equality can be fooled by a duplicated boundary), the compact-time `bankCompactSegment` step (per-step deadline degrades, segment-then-ledger crash order), the openclaw tail boundary reader (`readOpenclawBoundaryTail`, delegates mapping to the adapter's exported `mapOpenclawLine`; also returns turn-stamped `toolCalls`/`toolCallTurnIndexes` for the Memorable receipt — name-only v1, `input: null` by design until an observation run characterizes OpenClaw's args field), and orphan-sidecar/aged-ledger GC — pinned by `test/corpus-segments.test.ts`. `checkpoint-harvest.ts` — the serve-side prompt harvest of a segment: bounded FIFO (cap 8, 60s abort), sweep-shared claim fencing, capability-then-kill-switch gates, `signal.aborted` POST-check (the pipeline returns partials on abort; an aborted run writes nothing and stays retryable), receipt sidecar before idempotent manifest publish (source-scoped `getPage` verification — a link that resolves to nothing is never banked), `.ingested` last, explicit `shutdownCheckpointHarvest()` called by serve BEFORE `engine.disconnect()` (the background-work drain is CLI-exit-only by contract) — pinned by `test/checkpoint-harvest.serial.test.ts`. `hook-heartbeat.ts` — the hooks telemetry JSONL extracted from hook.ts (hook.ts re-exports; serve-side writers never import the command module); allowlist carries the checkpoint `segment`/`inserted`/`duplicate`/`links` count-only fields. `session-state.ts` also carries the v132 `checkpoint_manifest` helpers (`getCheckpointManifest`/`appendCheckpointManifest`: newest-first, dedup-by-slug, cap 20, seg-hash completion key, fail-open on pre-v132 schema) — pinned by `test/checkpoint-manifest.test.ts`. `sensitivity-scan.ts` + `compile-view.ts` — the compile-context stack: composed detector (secret-scan + ordered `PII_PATTERNS` + path/blocklist families + operator pattern file; uniform `.gbrain-scan-allow` fingerprint escape hatch; CONTENT hits drop an entry, CONFIG/loader failures THROW so the caller aborts without writing) and the deterministic compiled-view builder (recency decay anchored to the newest candidate `updated_at`, never wall-clock; total-order (score desc, slug asc); source-scoped listPages/getPage reads that skip op-layer write-backs; whole-file `packToBudget` math that never passes a <=0 budget) — pinned by `test/sensitivity-scan.test.ts` + `test/compile-view.test.ts` + `test/e2e/compile-context-pglite.test.ts`; the CLI shell is `src/commands/compile-context.ts` (targets claude-code|codex|openclaw, AGENTS.md managed-marker splice that throws on damaged markers, atomic writes, `--check` recompile-and-compare exit codes; the guide is `docs/guides/checkpoint-compaction.md`). It also owns the whole Memorable seam's engine-free plumbing: the session-receipt JSONL (`session-receipts.jsonl`, `appendSessionReceipt` — dedup by post-redaction `content_hash` so a resumed session neither duplicates its receipt nor re-fires the relay; tail-rewrite compaction triggered by the 32 MB byte ceiling alone — the read fires exactly when the pass will act, with the 2000-line budget enforced inside the pass — and a `skipCompaction` seam the openclaw compact() lane sets unconditionally: the hook lane is the ONE receipts compactor, so two processes can never race the read-filter-rename rewrite); ONE bounded adaptive `readJsonlTail` reader shared by `lastReceiptMatches`, `lastRelayResult` and `readSessionReceiptsTail` (a receipt line can exceed the 1 MB window — the window doubles rather than reading "empty"); `maybeTrimRelayResults` (BOTH capture lanes trim the child-appended `memorable-relay.jsonl` — an openclaw-only host has no hook lane, and converging newest-keeping trims make concurrent trims safe: mtime-stale preferred, hard 8 MB force backstop, line-boundary cut keeping the newest lines — the child appends open-by-path, so the residual loss window is one in-flight write); the CONSENT STAMP (`memorable-consent.json`, 0600, written ONLY by config-set's disclosure flow — deliberately outside config.json, which the external CLI full-file-rewrites; scope-bound to the disclosure sha256 + `MEMORABLE_CAPTURE_HARNESSES`, so widening the capture surface invalidates old stamps); `memorableGateAllowed(cfg)` ({allowed, reason: kill_switch|disabled|disclosure_missing} — one reason vocabulary for hook, context-engine and doctor); `memorableConsentEvidence()` (the CLI-side opt-in read fail-closed from ~/.memorable/config.json, dated provisional spec note, GBRAIN_MEMORABLE_CONFIG test seam); `redactedToolCallsJson` (the security-load-bearing span-filter + highEntropy redaction, ONE implementation for both capture lanes; string LEAVES are redacted raw before serialization — scanning the serialized JSON would let quoted secrets through via \" escaping — with a post-serialization re-scan as belt-and-braces); `recordAndRelayReceipt` (per-receipt harness scope-binding first — a harness outside `MEMORABLE_CAPTURE_HARNESSES` is refused with `memorable_harness_undisclosed` → receipt → prior-run outcome surfacing with the child's reason clamped via the shared `clampRelayCause` (32 chars, so the 16-char prefix keeps composites inside the 48-char reason bound) and appended LAST → consent evidence → `resolveMemorableBin` → detached spawn; never throws; `spawnFn` test seam); and `priorRelayFailure`, which surfaces the PREVIOUS relay run's self-reported exit status so a relay that records nothing is never reported healthy. `resolveMemorableBin` does the pre-spawn PATH/`MEMORABLE_BIN` resolution so a missing CLI is a named heartbeat reason rather than a silent async ENOENT.diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.mdindex bfb189e266..9d74546e05 100644--- a/docs/architecture/key-files/core-services-2.md+++ b/docs/architecture/key-files/core-services-2.md@@ -13,15 +13,15 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/facts/extract.ts` — the LLM facts extractor (`extractFactsFromTurnWithOutcome` and friends; the output cap, truncation retry, and salvage behavior are described under the trajectory entry). Deterministic junk gate: `isJunkFact(text, kind?)` tests `JUNK_FACT_PATTERNS` — assistant plan/offer narration, meta-narration about the conversation itself, provider billing/rate-limit strings captured verbatim — and is kind-aware: a candidate the extractor classified `commitment` is exempt from the plan-narration arm ONLY ("I'll send the deck by Friday" is the surface shape of a genuine commitment, the one kind the loop engine exists to capture); meta-narration and provider-error strings are junk for every kind. `isJunkFilterEnabled(engine)` is the config kill switch (fail-open on a config read error); `getFactsExtractionPromptAppendix` supplies the config-driven prompt appendix. Entity gate at the candidate loop (the ONE seam where LLM-emitted entity tokens become `entity_slug`): `isUnknownSpeakerLabel` (anonymous diarizer labels — `Speaker A`, `SPEAKER_00`, `spk_0`, `other|unknown|guest`) and `isNullLikeEntity` (placeholder STRINGS `"null"`/`"None"`/`"n/a"` where the prompt asked for JSON null; shared with `write-single.ts`) both null the attribution and KEEP the fact, so no consumer (`runFactsPipeline`, `extract-conversation-facts`) can mint `entity_slug='null'` through the resolver's fallback-slugify floor. The provider-error arm is start-anchored (`^\W*`, optional error/status token or a `<step> stopped|failed because …` prefix, then `(spend|rate) (limit|cap) … (hit|exceeded|reached)`), so a genuine fact that merely mentions a spend limit or rate limit mid-sentence survives; the verbatim provider strings still match. Two config keys: `facts.extraction_prompt_appendix` (non-empty text is appended to the extraction prompt, so an operator can steer what counts as a fact without a release) and `facts.extraction_junk_filter` (`false` disables the deterministic junk gate; default on). Every extractor `chat()` call (first attempt, the #2113 truncation retry, the malformed-output retry) carries `responseSchema: FACTS_EXTRACTION_SCHEMA` (mirrors `RawExtracted`: `facts[]` of `{fact, kind ∈ ALL_EXTRACT_KINDS}` plus `entity/confidence/notability/metric/value/unit/period` — EVERY property in `required`, the optional ones nullable via type unions, `additionalProperties: false` at both levels, so the schema is OpenAI-strict-safe for proxies that honor the SDK's default `strict: true`); the gateway honors it only on openai-compatible recipes that declare structured outputs (Ollama's server-side grammar), so small local models cannot emit malformed JSON, while `parseExtractorJsonDetailed` still validates the reply text on every lane. Pinned by `test/facts-extract-structured-output.test.ts`.-- `src/core/facts/forget.ts` — `forgetFactInFence(engine, id, {reason?, sourceId?, worldOnly?})` checks source and visibility before inspecting state, then commits a durable withdrawal through `facts/withdrawal.ts`. A writable source fence is atomically struck with a date and reason; otherwise the DB-body mirror is best-effort. Both paths remain withdrawn on stale reimport while the withdrawal database is preserved. The file resolver and per-page lock match fence writes. The body-only mirror deliberately leaves a hash mismatch so the next import re-chunks. Forget is retraction, not deletion of original prose, files or backups. Pinned by `test/forget-reconcile-durability.test.ts`, `test/privacy-strip-and-forget.test.ts`, and `test/e2e/delegated-grants-withdrawal.test.ts`.+- `src/core/facts/forget.ts` — `forgetFactInFence(engine, id, {reason?, sourceId?, worldOnly?, supersededBy?})` checks source and visibility before inspecting state, then commits a durable withdrawal through `facts/withdrawal.ts`. With `supersededBy: { rowNum }` (the `writeSingleFact` supersession path) it only expires the row and strikes it with a page-local `#N` supersession reference: no withdrawal, so the old claim stays rememberable and no other page is invalidated. A writable source fence is atomically struck with a date and reason; otherwise the DB-body mirror is best-effort. Both paths remain withdrawn on stale reimport while the withdrawal database is preserved. The file resolver and per-page lock match fence writes. The body-only mirror deliberately leaves a hash mismatch so the next import re-chunks. Forget is retraction, not deletion of original prose, files or backups. Pinned by `test/forget-reconcile-durability.test.ts`, `test/privacy-strip-and-forget.test.ts`, and `test/e2e/delegated-grants-withdrawal.test.ts`.- `src/core/facts/phantom-audit.ts` — JSONL audit at `${resolveAuditDir()}/phantoms-YYYY-Www.jsonl`. Pattern copy of `src/core/audit-slug-fallback.ts` (ISO-week rotation, honors `GBRAIN_AUDIT_DIR`). Exports `logPhantomEvent(record)` + `readRecentPhantomEvents(days)` + `computePhantomAuditFilename(now?)`. Records every outcome: `redirected | ambiguous | drift | no_canonical | not_phantom_has_residue | pass_skipped_lock_busy`. Best-effort writes — stderr warn on failure, never throws. Separate file from `stub-guard-audit.ts` (distinct consumer + lifecycle: stub-guard logs PREVENTIVE blocks; phantom-audit logs CLEANUP decisions, to be read by a future `phantoms_pending` doctor check).- `src/core/facts/queue.ts:FactsQueue.drainPending` — method `drainPending({timeout?: number}): Promise<{drained, unfinished}>`. Semantically distinct from `shutdown()` (which calls `this.internalAbort.abort()` and would abort the very facts:absorb worker trying to log its post-completion event). Drain lets in-flight finish; only the wait is bounded. Default timeout `1000ms` so commands that don't enqueue facts pay one fast 0ms check before exit. `src/cli.ts` op-dispatch finally block awaits `getFactsQueue().drainPending({timeout: 1000})` BEFORE `engine.disconnect()`. Lazy-import keeps the facts-queue module off the hot path for ops that never touch it. Prevents a trailing `'No database connection'` line after `gbrain capture` (a post-page-write facts:absorb outliving the CLI process). Pinned by `test/facts-queue-drain-pending.test.ts` (4 cases: empty fast-path, in-flight settled without abort, unfinished count on timeout, default timeout = 1000ms).-- `src/core/facts/withdrawal.ts` + `withdrawal-schema.ts` + `withdrawal-discovery.ts` — durable withdrawal key is `(source_id, visibility, SHA256(normalized claim))`; entity/page names are excluded so rename and index recreation do not restore it. Normalization folds case and whitespace, not meaning. Bounded exact discovery parses canonical rows and verifies fingerprints with database normalization before mutation, refusing matching malformed evidence or row/byte/target capacity exhaustion. 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 before embedding, using the protocol error envelope. Ordinary TTL/supersession expiry creates no withdrawal. Migration backfill only trusts explicit `forgotten:` markers; old unmarked DB-only intent cannot be inferred. Markdown-only copies do not preserve DB-only withdrawals.+- `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`; '*' applies to all subjects and is used for subjectless facts (they cannot say whom they were about) and for every row recorded before migration v169. A withdrawal matches a fact when `subject = '*' OR subject = entity_slug`, so forgetting one entity's claim never expires, strikes or blocks the same claim about another entity. Fence rows belong to their page's entity: the import overlay and prepared-import check (`preserveWithdrawnFenceRows` / `assertPreparedFactWithdrawals` with the page slug), the snapshot overlay and Markdown export all match on the page slug. `updateSlug` (both engines) 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 folds case and whitespace, not meaning. Bounded exact discovery parses canonical rows and verifies fingerprints with database normalization before mutation, refusing matching malformed evidence or row/byte/target capacity exhaustion; it stays claim-wide (a superset of the pages a subject-scoped withdrawal changes), and only an existing withdrawal covering the same subject skips it. 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. Ordinary TTL/supersession expiry creates no withdrawal. Migration backfill only trusts explicit `forgotten:` markers; old unmarked DB-only intent cannot be inferred. Markdown-only copies do not preserve DB-only withdrawals. Pinned by `test/facts-withdrawal-subject.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) + superseded_by link; DB path: engine insertFact supersedeId). 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.- `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-services-3.md b/docs/architecture/key-files/core-services-3.mdindex 2970f1c2d9..e9a3219ada 100644--- a/docs/architecture/key-files/core-services-3.md+++ b/docs/architecture/key-files/core-services-3.md@@ -7,7 +7,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/think/intent.ts` + `src/core/think/entity-extract.ts` — pure `classifyIntent(question)` returns `'temporal' | 'knowledge_update' | 'other'` (regex-first, no LLM, `'other'` fast path short-circuits with zero SQL). `extractCandidateEntities(question, retrievedSlugs)` pulls high-precision candidates from retrieved entity-prefix slugs (`people/`, `companies/`, `organizations/`) and medium-precision noun phrases. Stop-word boundaries + leading-verb stripper handle "When did I last meet Marco" → `marco`. Both consumed by `runThink` and the LongMemEval harness so the two paths cannot drift. Pinned by `test/think-intent.test.ts` and `test/think-entity-extract.test.ts`.-- `src/core/transcripts/` (directory) — the transcript-adapter seam. `types.ts`: the `TranscriptAdapter` contract — `parse(path): AsyncGenerator<ParsedSession, FileDiagnostics>` (one FILE may hold many sessions; the generator RETURN value carries bytes/skipped-lines/zero-session diagnostics so an empty file explains itself), format-specific byte caps (JSONL 50MB hard cap — the 10MB default in `claude-code-jsonl.ts` belongs to the hook-lane tail reader, not imports; monolithic export JSON rejects-not-truncates at 200MB), and the ONE `buildTranscriptSlug` helper (per-provider dirs matching the conversation-archive layout; id suffixes are sha256 prefixes of the session id — hash12 in slugs, hash16 for the dedup identity — never a cleaned prefix of the source id, which would let same-prefix session ids collide). `detect.ts`: adapter registry + head-sample detection (explicit format wins; symlinks lstat-rejected) + injectable `harnessRoots` (the confined discovery surface). Adapters, each with a DATED `SPEC_TARGET` + scrubbed fixture + `bytes>0 && sessions==0` drift alarm: `claude-code.ts` (thin wrapper over the shipped `claude-code-jsonl.ts`, which also exposes the full-file `parseClaudeSessionFile` with real per-message timestamps — hook-lane `parseTranscript` output is pinned byte-identical; owns `isClaudeCodeSubagentFile` (a literal `subagents` path segment at ANY depth + `agent-*.jsonl` basename — both `<session>/subagents/agent-*.jsonl` and the workflow-nested `<session>/subagents/workflows/<wf>/agent-*.jsonl` are all-sidechain, zero-turn files carrying the PARENT session id; a project slug containing "subagents" is one segment and never matches) and `isClaudeCodeWorkflowArtifactFile` (everything under `<session>/subagents/workflows/<wf>/` — the agent logs plus the `journal.jsonl` run log that matches no adapter format; a UUID-named session directly under `subagents/` stays discoverable); `discover.ts` and the CLI's `expandPaths` skip both, so they never read as gap-table backlog, drift, or `unknown format` errors that hold the since-last watermark frozen; the adapter sets `expectedEmpty` when a file has zero turn-shaped records (`type` user/assistant, not sidechain) and zero skipped lines — a title/metadata-only stub is understood, not drift, while turn records that yield no text and unparseable lines still drift), `codex.ts` (turn selection is STRUCTURAL: user turns from `event_msg` user_message, assistant from `response_item` output_text; role user/developer response_items are injected preambles and never leak; identity is `payload.id` — the per-thread id codex embeds in the rollout filename — with `payload.session_id` (the ROOT session shared by every forked/subagent thread) only as the legacy fallback, and the FIRST `session_meta` header wins because a child rollout carries its inherited parent header later in the file; the hook lane's `parseCodexHookTranscript` follows the same two rules), `openclaw.ts` (session header + message lines; `.checkpoint.*.jsonl` snapshots rejected), `hermes.ts` (COPY-THEN-READ of state.db + wal/shm sidecars — readonly WAL opens need -shm write access and lock against a live writer; schema from the installed hermes-agent source; PROVISIONAL), `grok.ts` (Grok Build session dirs — structural turn selection, sidecar-aware discovery; see its own entry), `chatgpt-export.ts` (the `mapping`-tree current_node walk; branches dropped by design, orphaned parents terminate quietly, latest-leaf fallback; extracted conversations.json only) + `claude-export.ts` (flat chat_messages); both export adapters load through the shared `export-json.ts` (monolithic JSON over the cap REJECTS with a split hint; a zip or wrong-shape file gets the unzip-first hint) and give id-less conversations content-derived fallback ids so two id-less exports cannot dedup-skip or overwrite each other. `render.ts`: session → part pages — imessage-slack line format with the regex IMPORTED from `conversation-parser/builtins.ts` (round-trip pinned), REAL timestamps (missing ones carry forward; zero-timestamp sessions refused — provenance is never fabricated), anchor-shaped BODY lines backslash-escaped (hostile message content cannot forge speakers), quoted facts/takes fence-marker tokens backslash-escaped at the same per-message seam (`gbrain\:facts:begin` — a session that read another page cannot plant a live or unbalanced fence on the transcript page; every fence consumer is a substring matcher, so the escape lands inside the token), fail-closed redaction (secret-scan + `harvest-private-patterns.txt` user patterns, slack-channel default excluded because it eats issue refs; imperatives COUNTED into hash-covered `transcript_import` frontmatter, never content_flag), ~300KB message-boundary splitting with 2-message overlap (under the embed-skip threshold), part 1 keeps the base slug, `frontmatter.id` unique per part. `ingest.ts`: the engine-facing core — SESSION atomicity (failed sessions skip; integrity failures abort the run), stale-part reconciliation (deletes `part > of` leftovers), session metadata banked in the base page's raw_data as the REDACTED copy and healed by content-compare even on hash-skipped re-runs (a run that died before `putRawData`, or a private pattern added after first import, repairs on the next pass), `cleanScan`/`maxSessionTs` for the watermark. `ingest-facts.ts`: ONE `runExtractConversationFactsCore` invocation (batch `slugs` selector) inside ONE `withBudgetTracker`, `isFactsExtractionEnabled` pre-checked. Pinned by `test/transcript-adapters.test.ts`, `test/transcript-render.test.ts`, `test/e2e/transcripts-ingest-pglite.test.ts`, `test/e2e/transcripts-writeback-fidelity.test.ts` (raw files through the adapters into the gold-extractor facts path).+- `src/core/transcripts/` (directory) — the transcript-adapter seam. `types.ts`: the `TranscriptAdapter` contract — `parse(path): AsyncGenerator<ParsedSession, FileDiagnostics>` (one FILE may hold many sessions; the generator RETURN value carries bytes/skipped-lines/zero-session diagnostics so an empty file explains itself), format-specific byte caps (JSONL 50MB hard cap — the 10MB default in `claude-code-jsonl.ts` belongs to the hook-lane tail reader, not imports; monolithic export JSON rejects-not-truncates at 200MB), and the ONE `buildTranscriptSlug` helper (per-provider dirs matching the conversation-archive layout; id suffixes are sha256 prefixes of the session id — hash12 in slugs, hash16 for the dedup identity — never a cleaned prefix of the source id, which would let same-prefix session ids collide). `detect.ts`: adapter registry + head-sample detection (explicit format wins; symlinks lstat-rejected) + injectable `harnessRoots` (the confined discovery surface). Adapters, each with a DATED `SPEC_TARGET` + scrubbed fixture + `bytes>0 && sessions==0` drift alarm: `claude-code.ts` (thin wrapper over the shipped `claude-code-jsonl.ts`, which also exposes the full-file `parseClaudeSessionFile` with real per-message timestamps — hook-lane `parseTranscript` output is pinned byte-identical; owns `isClaudeCodeSubagentFile` (a literal `subagents` path segment at ANY depth + `agent-*.jsonl` basename — both `<session>/subagents/agent-*.jsonl` and the workflow-nested `<session>/subagents/workflows/<wf>/agent-*.jsonl` are all-sidechain, zero-turn files carrying the PARENT session id; a project slug containing "subagents" is one segment and never matches) and `isClaudeCodeWorkflowArtifactFile` (everything under `<session>/subagents/workflows/<wf>/` — the agent logs plus the `journal.jsonl` run log that matches no adapter format; a UUID-named session directly under `subagents/` stays discoverable); `discover.ts` and the CLI's `expandPaths` skip both, so they never read as gap-table backlog, drift, or `unknown format` errors that hold the since-last watermark frozen; the adapter sets `expectedEmpty` when a file has zero turn-shaped records (`type` user/assistant, not sidechain) and zero skipped lines — a title/metadata-only stub is understood, not drift, while turn records that yield no text and unparseable lines still drift), `codex.ts` (turn selection is STRUCTURAL: user turns from `event_msg` user_message, assistant from `response_item` output_text; role user/developer response_items are injected preambles and never leak; identity is `payload.id` — the per-thread id codex embeds in the rollout filename — with `payload.session_id` (the ROOT session shared by every forked/subagent thread) only as the legacy fallback, and the FIRST `session_meta` header wins because a child rollout carries its inherited parent header later in the file; the hook lane's `parseCodexHookTranscript` follows the same two rules), `openclaw.ts` (session header + message lines; `.checkpoint.*.jsonl` snapshots rejected), `hermes.ts` (COPY-THEN-READ of state.db + wal/shm sidecars — readonly WAL opens need -shm write access and lock against a live writer; schema from the installed hermes-agent source; PROVISIONAL), `grok.ts` (Grok Build session dirs — structural turn selection, sidecar-aware discovery; see its own entry), `chatgpt-export.ts` (the `mapping`-tree current_node walk; branches dropped by design, orphaned parents terminate quietly, latest-leaf fallback; extracted conversations.json only) + `claude-export.ts` (flat chat_messages); both export adapters load through the shared `export-json.ts` (monolithic JSON over the cap REJECTS with a split hint; a zip or wrong-shape file gets the unzip-first hint) and give id-less conversations content-derived fallback ids so two id-less exports cannot dedup-skip or overwrite each other. `render.ts`: session → part pages — imessage-slack line format with the regex IMPORTED from `conversation-parser/builtins.ts` (round-trip pinned), REAL timestamps (missing ones carry forward; zero-timestamp sessions refused — provenance is never fabricated), anchor-shaped BODY lines backslash-escaped (hostile message content cannot forge speakers), quoted facts/takes fence-marker tokens backslash-escaped at the same per-message seam (`gbrain\:facts:begin` — a session that read another page cannot plant a live or unbalanced fence on the transcript page; every fence consumer is a substring matcher, so the escape lands inside the token), fail-closed redaction (secret-scan + `harvest-private-patterns.txt` user patterns, slack-channel default excluded because it eats issue refs; imperatives COUNTED into hash-covered `transcript_import` frontmatter, never content_flag), ~300KB message-boundary splitting with 2-message overlap (under the embed-skip threshold), part 1 keeps the base slug, `frontmatter.id` unique per part. `ingest.ts`: the engine-facing core — a session whose part-1 `frontmatter.id` already has a live page imports at that page's slug (a renamed or re-dated conversation updates in place instead of being skipped as a cross-slug duplicate), SESSION atomicity (failed sessions skip; integrity failures abort the run), stale-part reconciliation (deletes `part > of` leftovers), session metadata banked in the base page's raw_data as the REDACTED copy and healed by content-compare even on hash-skipped re-runs (a run that died before `putRawData`, or a private pattern added after first import, repairs on the next pass), `cleanScan`/`maxSessionTs` for the watermark. `ingest-facts.ts`: ONE `runExtractConversationFactsCore` invocation (batch `slugs` selector) inside ONE `withBudgetTracker`, `isFactsExtractionEnabled` pre-checked. Pinned by `test/transcript-adapters.test.ts`, `test/transcript-render.test.ts`, `test/transcripts-retitle.test.ts`, `test/e2e/transcripts-ingest-pglite.test.ts`, `test/e2e/transcripts-writeback-fidelity.test.ts` (raw files through the adapters into the gold-extractor facts path).- `src/core/verbs/conformance.ts` + `src/core/verbs/conformance-fixtures.ts` — the conformance runner core (transport-agnostic: minimal `ConformanceClient` = list_tools + call_tool) and the embedded fixture set. Deterministic by construction: shape/enum/behavior/round-trip checks only, never ranking quality. Validation is NON-STRICT on extra fields (additive-forever means unknown fields are always legal). Entity-card cases seed via put_page when the target exposes it and skip honestly on verbs-only targets; synthesize is cost-gated behind --synthesize. `validateAgainstSchema` is a minimal JSON-Schema-subset validator (type unions, required, properties, enum, const, items). Fixtures mirror to `test/fixtures/memory-verbs/cases.json` (BrainBench seeds; drift-guarded by the conformance test). The negative self-test (test/memory-verbs-conformance.test.ts) proves the runner FAILS a lying server.diff --git a/docs/architecture/key-files/graph-and-facts.md b/docs/architecture/key-files/graph-and-facts.mdindex 9d3a871220..55c4ef6e5e 100644--- a/docs/architecture/key-files/graph-and-facts.md+++ b/docs/architecture/key-files/graph-and-facts.md@@ -84,7 +84,7 @@ rejection of serve-only flags before a brain opens.- `src/core/extraction-review.ts` — Extraction quarantine lane markers, sibling of `src/core/quarantine.ts` / `embed-skip.ts` (frontmatter-key pattern, no schema migration). Auto-extracted stubs from untrusted input carry the PAIR `provenance: 'auto-extracted'` + `status: 'unverified'` (both required — user pages with their own `status`/`provenance` never match). Exports `quarantineMarkers()`, `isUnverifiedExtraction()` (JS predicate) and `unverifiedExtractionFragment(alias)` — the single SQL source of truth consumed by `buildSourceFactorCase` (namespace source-boost guard), both engines' `getUnverifiedExtractionPageIds`, the `extraction_pending` op, and the `unverified_extractions` doctor check, so filter and marker keys can never drift. Consequences: unverified stubs are excluded from the compiled-truth fusion boost + the `people/`/`companies/` source-boost (rank as ordinary content), stamped `unverified: true` in search results (`stampUnverifiedExtractions`, hybrid.ts), listed by `extraction_pending`, promoted (status → `verified`, provenance kept for audit) or rejected (soft-delete) by the owner-only `extraction_review` op. Pinned by `test/extraction-review.test.ts` (PGLite) + `test/e2e/extraction-review-postgres.test.ts` (live Postgres parity).-- `src/core/facts-fence.ts` — the `## Facts` fence primitives: parse (`parseFactsFence`), render (`renderFactsTable`), and strip (`stripFactsFence({keepVisibility})` — the remote-read privacy boundary `get_page`/`fetch_page`/the chunker apply), plus the remote write-back merge, plus the ONE fence-placement rule: `replaceOrInsertFactsFence(body, fenceBlock)` replaces an existing fence in place or inserts a fresh `## Facts` section ABOVE the timeline sentinel (`timelineSentinelOffset`, #4756 — below it splitBody() files the fence into page.timeline where extract_facts refuses to reconcile it), EOF only when the page has no sentinel; every writer that materializes a fence (`upsertFactRow`, the phantom-redirect canonical append, the importer's hidden-row merge) routes through it, so no writer can re-grow its own EOF append. `restoreHiddenFactRows(incoming, existing)` is the row-level, visibility-aware merge `import-file.ts` applies per fence-bearing column (compiled_truth AND timeline) when a remote caller writes back a page it read with hidden rows stripped — without it, a remote get→edit→put round-trip would silently drop every non-`world` fact row. Rules: only non-`world` rows of the existing fence are restoration candidates (a caller's deletion of a VISIBLE row stays honored — world rows are never restored); a hidden row whose rowNum is absent from the incoming fence is restored at its stable rowNum (cross-page `#F<N>` refs survive); a rowNum collision (a caller-authored addition landing on a hidden number the caller never saw) keeps the hidden row's number and renumbers the CALLER's row onto fresh appended numbers (upsertFactRow's append-only contract); same rowNum + same claim keeps the incoming version (idempotent full-content write-throughs); either side parsing with warnings returns null — re-rendering a fence that didn't fully parse would drop the caller's unparsed rows — and `factsGapWarning` surfaces exactly that residual loss. Pure and side-effect-free. Pinned by `test/facts-fence.test.ts` + the remote write-back describes in `test/privacy-strip-and-forget.test.ts` (row-level merge, world-only deletion honored, timeline-embedded fence round-trip).+- `src/core/facts-fence.ts` — the `## Facts` fence primitives: parse (`parseFactsFence`; a confidence cell outside 0..1 is `FACTS_TABLE_MALFORMED`, so the page is non-authoritative instead of failing the DB CHECK), render (`renderFactsTable`), and strip (`stripFactsFence({keepVisibility})` — the remote-read privacy boundary `get_page`/`fetch_page`/the chunker apply), plus the remote write-back merge, plus the ONE fence-placement rule: `replaceOrInsertFactsFence(body, fenceBlock)` replaces an existing fence in place or inserts a fresh `## Facts` section ABOVE the timeline sentinel (`timelineSentinelOffset`, #4756 — below it splitBody() files the fence into page.timeline where extract_facts refuses to reconcile it), EOF only when the page has no sentinel; every writer that materializes a fence (`upsertFactRow`, the phantom-redirect canonical append, the importer's hidden-row merge) routes through it, so no writer can re-grow its own EOF append. `restoreHiddenFactRows(incoming, existing)` is the row-level, visibility-aware merge `import-file.ts` applies per fence-bearing column (compiled_truth AND timeline) when a remote caller writes back a page it read with hidden rows stripped — without it, a remote get→edit→put round-trip would silently drop every non-`world` fact row. Rules: only non-`world` rows of the existing fence are restoration candidates (a caller's deletion of a VISIBLE row stays honored — world rows are never restored); a hidden row whose rowNum is absent from the incoming fence is restored at its stable rowNum (cross-page `#F<N>` refs survive); a rowNum collision (a caller-authored addition landing on a hidden number the caller never saw) keeps the hidden row's number and renumbers the CALLER's row onto fresh appended numbers (upsertFactRow's append-only contract); same rowNum + same claim keeps the incoming version (idempotent full-content write-throughs); either side parsing with warnings returns null — re-rendering a fence that didn't fully parse would drop the caller's unparsed rows — and `factsGapWarning` surfaces exactly that residual loss. Pure and side-effect-free. Pinned by `test/facts-fence.test.ts` + the remote write-back describes in `test/privacy-strip-and-forget.test.ts` (row-level merge, world-only deletion honored, timeline-embedded fence round-trip).- `src/core/fence-shared.ts` — shared pipe-table primitives for the `## Takes` (`takes-fence.ts`) and `## Facts` (`facts-fence.ts`) fences: `parseRowCells`, `isSeparatorRow`, `stripStrikethrough`, `parseStringCell`, `escapeFenceCell`. `parseRowCells` is escape-aware: `\|` stays inside its cell and decodes back to a literal `|` (exact inverse of `escapeFenceCell`), while any other backslash passes through verbatim so existing fence text (e.g. Windows paths) is byte-stable across a render → parse cycle. This matters because the fence is canonical and reconcile is wipe-and-reinsert — a pipe inside a cell shifting the column layout would corrupt every row behind it on the next reconcile. Pinned by the escape cases in `test/facts-fence.test.ts` + the full render → parse → reconcile round-trip in `test/e2e/facts-fence-reconcile-postgres.test.ts`.diff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex 04e7786bc1..3c24a55e53 100644--- a/openclaw.plugin.json+++ b/openclaw.plugin.json@@ -1,7 +1,7 @@{"id": "gbrain-context-engine","name": "gbrain",- "version": "0.59.13.0",+ "version": "0.59.17.0","description": "Personal knowledge brain with Postgres + pgvector hybrid search","family": "bundle-plugin","kind": "context-engine",diff --git a/package.json b/package.jsonindex a5d2b1069a..38c1ba8823 100644--- a/package.json+++ b/package.json@@ -190,7 +190,7 @@"bun": ">=1.3.11"},"license": "MIT",- "version": "0.59.13.0",+ "version": "0.59.17.0","overrides": {"@ai-sdk/provider-utils": "4.0.33","@hono/node-server": "^2.0.5",diff --git a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json b/plugin-variants/gbrain-coding/.claude-plugin/plugin.jsonindex 8597965b06..bea0689911 100644--- a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json+++ b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-coding",- "version": "0.59.13.0",+ "version": "0.59.17.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 ef77b98563..9028eb0dbc 100644--- a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json+++ b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-coding",- "version": "0.59.13.0",+ "version": "0.59.17.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 6c378d7830..72ab0d5877 100644--- a/plugin-variants/gbrain-coding/README.md+++ b/plugin-variants/gbrain-coding/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.59.13.0 -->+<!-- gbrain-plugin-tree-stamp: 0.59.17.0 --># gbrain-coding (generated persona variant — do not hand-edit)Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant.diff --git a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json b/plugin-variants/gbrain-daily/.claude-plugin/plugin.jsonindex a570ca0c9e..9b2415cc90 100644--- a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json+++ b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-daily",- "version": "0.59.13.0",+ "version": "0.59.17.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 382a966343..79af49475a 100644--- a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json+++ b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-daily",- "version": "0.59.13.0",+ "version": "0.59.17.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 ae60d4d907..e7be3c3c58 100644--- a/plugin-variants/gbrain-daily/README.md+++ b/plugin-variants/gbrain-daily/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.59.13.0 -->+<!-- gbrain-plugin-tree-stamp: 0.59.17.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 f944fa828b..b9c2d6e841 100644--- a/plugin/README.md+++ b/plugin/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.59.13.0 -->+<!-- gbrain-plugin-tree-stamp: 0.59.17.0 --># gbrain plugin skill tree (generated — do not hand-edit)This tree is the curated skill set for the gbrain Codex and Claude Codediff --git a/scripts/e2e-test-map.ts b/scripts/e2e-test-map.tsindex af3271d83b..094469fe07 100644--- a/scripts/e2e-test-map.ts+++ b/scripts/e2e-test-map.ts@@ -188,6 +188,7 @@ export const E2E_TEST_MAP: Record<string, string[]> = {// these arrived unclaimed): connector classify/sync core + doctor check."src/core/connectors/**": ["test/e2e/connector-sync-handler-pglite.test.ts",+ "test/e2e/connectors-sync-checkpoints-pglite.test.ts","test/e2e/connectors-sync-pglite.test.ts","test/e2e/doctor-connectors-pglite.test.ts",],diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 32f44b2abe..ed2e9d350f 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -13,18 +13,18 @@ src/commands/jobs.ts 3260 ratchet grown v0.46.26.0 megawave (#4098 #2308) + mastsrc/commands/serve-http.ts 3098 ratchet registration and grant routes extracted; owner authentication and configured discovery remain in the HTTP facade; one shared bootstrap-token-shape import from serve-service; merged scoped shared-skill resources and named capability checkssrc/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 ceilingssrc/commands/sync.ts 5995 ratchet +1 #4786/#3068 pre-landing: pullFailed early return reports the sweep count (comment line); +1 #4786 x #2139 pre-landing: both embed-backfill submit gates require syncProducedEmbeddableContent (import line); re-summed after merging master v0.50.0.0 with the wave (include_hidden, sweep count, cost-gate envelope); +1 wave review: sync trigger --json emits {job_id} JSON; grown v0.46.26.0 megawave: image sync, ingest-log gating, dry-run purity, checkpoint honesty (#2683 #4342 #3875) + 3 nosemgrep dataflow annotations (path-traversal audit); +#2683 residual: status-error failure recording at both import sites; +143 wave G #3974: working-tree drift surfacing + opt-in --working-tree import; grown wave-g (#4412 #4543): break-lock ambient source resolution + named failing files; grown db-availability loop: GBRAIN_DB_ACCESS marker on checkpoint-dead aborts; fix cycle: marker via shared DB_ACCESS_MARKER_PREFIX + shouldEmitDbAccessMarker; wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +master-merge true-up; +25 post-sync backup-coverage stale-only refresh (monthly backup check); wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +1: #4412 refinement — explicit --source stays resolver-free (deleted-source locks breakable); +10 v0.47 gmail-loops: google source-kind dispatch branch; +48 #4667 adoption: persisted sync.exclude config union hoisted above the performFullSync early returns; +22 #4587: all 7 delete lanes swapped to softDeletePages (72h recovery window), decompose comments + summary wording; +16 #4583: seed_default write refusal on bulk-non-default brains (assessDefaultWriteGuard call site + escape-hatch comment); composition true-up (fix-wave multi-train); +33 #4597: trackedSlugIndex.anchorOnlyPaths (slug -> anchor paths that alone proved it) + the self-referential from-path rule in slugLiveness so a fallback rename's own pre-rename duplicate converges under incremental sync; +12 #4888: runSync wraps runSyncInner in withHumanLogsToStderr under --json (stdout = JSON lines only) + help text; wave composition: #4903 stored-strategy honor + #4597 fallback-rename duplicate convergence + #4888 --json stdout purity summed; security: durable queued authority and confined filesystem dispatch; drained cancellation and lease-safe partial results; master integration: +1 wave review: sync trigger --json emits {job_id} JSON; grown v0.46.26.0 megawave: image sync, ingest-log gating, dry-run purity, checkpoint honesty (#2683 #4342 #3875) + 3 nosemgrep dataflow annotations (path-traversal audit); +#2683 residual: status-error failure recording at both import sites; +143 wave G #3974: working-tree drift surfacing + opt-in --working-tree import; grown wave-g (#4412 #4543): break-lock ambient source resolution + named failing files; grown db-availability loop: GBRAIN_DB_ACCESS marker on checkpoint-dead aborts; fix cycle: marker via shared DB_ACCESS_MARKER_PREFIX + shouldEmitDbAccessMarker; wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +master-merge true-up; +25 post-sync backup-coverage stale-only refresh (monthly backup check); wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +1: #4412 refinement — explicit --source stays resolver-free (deleted-source locks breakable); +10 v0.47 gmail-loops: google source-kind dispatch branch; +48 #4667 adoption: persisted sync.exclude config union hoisted above the performFullSync early returns; +22 #4587: all 7 delete lanes swapped to softDeletePages (72h recovery window), decompose comments + summary wording; +16 #4583: seed_default write refusal on bulk-non-default brains (assessDefaultWriteGuard call site + escape-hatch comment); composition true-up (fix-wave multi-train); +33 #4597: trackedSlugIndex.anchorOnlyPaths (slug -> anchor paths that alone proved it) + the self-referential from-path rule in slugLiveness so a fallback rename's own pre-rename duplicate converges under incremental sync; +12 #4888: runSync wraps runSyncInner in withHumanLogsToStderr under --json (stdout = JSON lines only) + help text; wave composition: #4903 stored-strategy honor + #4597 fallback-rename duplicate convergence + #4888 --json stdout purity summed; #5252 wave: post-batch planner statistics refresh; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; merged reliability/shared-skills source integration; +1 cancellation guard before company dispatch-src/core/cycle.ts 3207 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+src/core/cycle.ts 3208 ratchet grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detailsrc/core/cycle/synthesize.ts 3218 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 delegatessrc/core/cycle/extract-atoms.ts 1752 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integrationsrc/core/engine.ts 2665 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contractsrc/core/import-file.ts 2236 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchorsrc/core/migrate.ts 722 region-exempt append-only MIGRATIONS array grows freely; runner logic is ratcheted — grown v0.46.26.0: repair-handler hooks (#3957 pages-upsert-arbiter); wave-k v142 takes-embedding resize is in-region (renumbered from v141; master consumed v141 for #4482); master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: projection migration helper; #5105: lease schema helper; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +1 import for focused topology migration module; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: static projection statistics import; DDL remains region-exempt; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestionsrc/core/operations.ts 329 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base-src/core/pglite-engine.ts 6144 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+src/core/pglite-engine.ts 6149 ratchet +6 #4881: ontology provenance-page visibility gate (getOntology/findOntologyConflicts); grown v0.46.26.0 megawave parity twins + master v0.46.26.0 private-queue columns; +#3754 traverseGraph soft-delete filters; grown wave-g (#4524 #4527): canonical islanded orphans + timestamp-preserving migrate; wave-k: +1 semantic takes retrieval delegate (#3776), +5 NUL-sanitize shared chunk_text local (#3998), +7 getAllConfig bulk read (#3980); +22: pre-close WAL CHECKPOINT in disconnect (#3893); +10: #4109 atomic link/timeline mutation + typed per-endpoint miss (parity); +1: getBacklinkCounts page-id keying comment (#4380); +14: dream-verdict TTL expiry predicate + sweep (#4069); +7 test-gap-wave merge true-up; +23: softDeletePages batch soft-delete primitive (#4587, parity twin); +51: #4592 source-scoped getStats/getHealth (bound $1 scope, both-endpoint link rule); +5 file-bytes snapshot hash (coverage-immune — CI shards were silently cold-initting); +7 2026-09 fix wave (#3617 follow-up): OR-fallback rows tagged keyword_relaxed in searchKeyword + title arm (fusion demotion reads it); cold-initting); +11: #4280 orphan/health served-memory denominators (quarantine + leaf-type metadata); composition true-up (fix-wave multi-train); +14: traversePathsDetailed row cap (LIMIT + truncated probe, parity twin); +7: resolveSlugWithAliasDetailed (owning source_id, parity twin) | merged v0.48.1.0 true-up; corrective release: shared batched enrichment peel; concrete content and Chronicle authorization; +2: #4681 listPages projects updated_at_iso (microsecond keyset cursor); master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: grant and authority schema bootstrap parity; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; upstream integration: preserve independently reviewed master additions with branch facade extraction; +1 v0.50.5.0 security merge (upstream delta; coordinated facade retained); +7 ceiling: bounded in-memory create retry with attached-database exclusion and second-failure diagnostics; #5252 bounded candidate recovery and statistics snapshot dependency; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared-skills integration on company-ingestion base; shared skills: include explicit access DDL in snapshot invalidation; archived eligibility: source-locked drift and raw signature mutations; +6 write-path wave: updateSlug records its rename alias in one transaction; +11 read-path wave: searchKeyword type/exclude_slugs Postgres parity + getTags private/deleted filters; +5: updateSlug carries entity-scoped fact withdrawalssrc/core/postgres-engine.ts 5577 ratchet +6 #4881: ontology provenance-page visibility gate (parity twin); lowered wave-g: #4477 bootstrap peel to src/core/postgres-engine/ modules (ratchet holds the win); +2 on wave-g-prs merge true-up; wave-k: +2 semantic takes retrieval (#3776), +5 NUL-sanitize shared chunk_text local (#3998), +11 getAllConfig bulk read (#3980); +13: #4109 atomic FOR KEY SHARE link/timeline mutation + typed per-endpoint miss; +2: getBacklinkCounts page-id keying comment (#4380); +12: dream-verdict TTL expiry predicate + sweep (#4069); +23: softDeletePages batch soft-delete primitive (#4587, parity twin); +61: #4592 source-scoped getStats/getHealth (scope predicate, both-endpoint link rule); +11 2026-09 fix wave (#3617 follow-up): OR-fallback rows tagged keyword_relaxed in searchKeyword + title arm (fusion demotion reads it); rule); +12: #4280 orphan/health served-memory denominators (quarantine + leaf-type metadata, parity twin); composition true-up (fix-wave multi-train); +14: traversePathsDetailed row cap (LIMIT + truncated probe, parity twin); +7: resolveSlugWithAliasDetailed (owning source_id, parity twin) | merged v0.48.1.0 true-up; corrective release: shared batched enrichment peel; concrete content and Chronicle authorization; +3: #4681 listPages projects updated_at_iso (microsecond keyset cursor, parity twin); #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop barrier and direct transaction route; upstream integration: preserve independently reviewed master additions with branch facade extraction; +1 v0.50.5.0 security merge (upstream delta; coordinated facade retained)src/core/search/hybrid.ts 3215 ratchet +2: preserve local query-deadline classification through gateway error wrapping; grown v0.46.26.0 megawave: CRAG escalation seam, degradation visibility, excludePrivate knobs-fold v23 (#1663 #3873 #4352); grown #4356: semantic-cache-hit slice honors resolved mode searchLimit (double-resolution caveat); grown #4414: offset!==0 cache-skip widening + knobs-hash v24; grown #4487: chunkless rows join the cosine blend (no raw-score head start); grown wave-g (#4480 #4415): shared salience/recency resolution + pattern-aware cache keying; grown db-availability loop: all-lexical-arms-dead access-error rethrow (a dead DB must never return an empty success) — refined to both-arms-FAILED (a succeeded-but-empty arm proves the DB is alive); grown v0.46.26.0 megawave: CRAG escalation seam, degradation visibility, excludePrivate knobs-fold v23 (#1663 #3873 #4352); grown #4356: semantic-cache-hit slice honors resolved mode searchLimit (double-resolution caveat); grown #4414: offset!==0 cache-skip widening + knobs-hash v24; grown #4487: chunkless rows join the cosine blend (no raw-score head start); grown wave-g (#4480 #4415): shared salience/recency resolution + pattern-aware cache keying; +2: backlink-boost counts page-id keying doc (#4380); +59 2026-09 adversarial batch 2: both-mode text-only demotion gate (textVectorArmNonEmpty) + relaxed_dropped meta + keyword_relaxed_carried degraded stamp + intent-skew caveat docs; +35 #3617 follow-up: relaxed-row fusion demotion (vectorArmNonEmpty gate + keywordFusionList/titleFusionList) with the LongMemEval 51.3%-vs-93.8% receipt comment; +24 2026-08 eval fix wave (E5b/D8): adaptive-return knobs-hash v27 fold (resolved gate + intent class threaded to the cache key), adaptive-on skipCache removal, dedupOpts cache-skip honesty, explicit-maxPerPage min() precedence under walk widening; (#4380); +20 wave #4256: compiledTruthBoost helper — synthetic chunkless title rows (chunk_id 0 + empty chunk_text) never gain the 2x compiled-truth boost (#3695); composition true-up (fix-wave multi-train) | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: read-policy propagation and semantic result-cache containment; ranker wave v0.48.4.0: role-tagged fusion arms, relational rerank pin, metadata boost gate, per-call knob seams, onRerankPool hook (+150) merged over master's read-policy plumbing (+31); +11 #4359 (#4972): thread the loaded search-mode config snapshot from hybridSearchCached into the inner hybridSearch call (INTERNAL _searchModeInput opt) so both resolve from the same one DB-plane config read instead of two independent ones — closes the cache-key/result desync window and removes the second config-table round trip on every hybridSearchCached call; #5252 wave: inclusive date bounds and public vector incompleteness; shared date-bounds peel retains exports; merged company ingestion/schema routing changes; retired provider integration removedsrc/core/types.ts 2076 ratchet +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note-src/core/minions/queue.ts 2513 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release+src/core/minions/queue.ts 2522 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keyssrc/commands/init.ts 1932 ratchet grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 provider normalization; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only init; shared-skills integration on company-ingestion base; retired provider integration removed; retain stored-vector identity on re-initsrc/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900)src/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 dispatchdiff --git a/src/commands/autopilot-fanout.ts b/src/commands/autopilot-fanout.tsindex 5c00117701..e0fddff8c7 100644--- a/src/commands/autopilot-fanout.ts+++ b/src/commands/autopilot-fanout.ts@@ -707,7 +707,7 @@ export async function maybeDispatchConnectorSyncs(const {autoSyncKey,authErrorAtKey,- lastSyncAtKey,+ readConnectorState,syncFloorMinKey,sourceIdKey,isTruthy,@@ -733,7 +733,7 @@ export async function maybeDispatchConnectorSyncs(const authErrorAt = await engine.getConfig(authErrorAtKey(provider));if (authErrorAt && cred.savedAt && authErrorAt > cred.savedAt) continue;- const lastSyncAt = await engine.getConfig(lastSyncAtKey(provider));+ const lastSyncAt = await readConnectorState(engine, provider, sourceId, 'last_sync_at');if (!isConnectorSyncStale(lastSyncAt, nowMs, floorMin)) continue;const job = await queue.add(diff --git a/src/commands/connectors/status.ts b/src/commands/connectors/status.tsindex fa2d891521..1e82f69e36 100644--- a/src/commands/connectors/status.ts+++ b/src/commands/connectors/status.ts@@ -14,8 +14,8 @@ import {authErrorAtKey,autoSyncKey,isTruthy,- lastSyncAtKey,- watermarkKey,+ readConnectorState,+ sourceIdKey,} from '../../core/connectors/config-keys.ts';export async function runConnectorStatus(engine: BrainEngine, args: string[]): Promise<void> {@@ -31,6 +31,7 @@ export async function runConnectorStatus(engine: BrainEngine, args: string[]): P}const rows = [];+ const sourceId = (await engine.getConfig(sourceIdKey())) || 'default';for (const prov of providers) {if (!prov) continue;const resolved = resolveCredential(prov.name);@@ -43,9 +44,10 @@ export async function runConnectorStatus(engine: BrainEngine, args: string[]): Pcredential_file_mode: credentialMode(prov.name),token_expires_at: resolved?.cred.expiresAt ?? null,auto_sync: isTruthy(await engine.getConfig(autoSyncKey(prov.name))),- last_sync_at: (await engine.getConfig(lastSyncAtKey(prov.name))) || null,+ source_id: sourceId,+ last_sync_at: await readConnectorState(engine, prov.name, sourceId, 'last_sync_at'),auth_error_at: (await engine.getConfig(authErrorAtKey(prov.name))) || null,- watermark_iso: (await engine.getConfig(watermarkKey(prov.name))) || null,+ watermark_iso: await readConnectorState(engine, prov.name, sourceId, 'watermark_iso'),});}diff --git a/src/commands/doctor/checks/connectors.ts b/src/commands/doctor/checks/connectors.tsindex 82cccfb4e7..0564f52c46 100644--- a/src/commands/doctor/checks/connectors.ts+++ b/src/commands/doctor/checks/connectors.ts@@ -22,7 +22,8 @@ import {doctorStaleHoursKey,DEFAULT_DOCTOR_STALE_HOURS,isTruthy,- lastSyncAtKey,+ readConnectorState,+ sourceIdKey,} from '../../../core/connectors/config-keys.ts';export async function connectorsHealthCheck(engine: BrainEngine): Promise<Check> {@@ -50,7 +51,7 @@ export async function connectorsHealthCheck(engine: BrainEngine): Promise<Check>}if (isTruthy(await engine.getConfig(autoSyncKey(provider)))) {- const lastSyncAt = await engine.getConfig(lastSyncAtKey(provider));+ const lastSyncAt = await readConnectorState(engine, provider, (await engine.getConfig(sourceIdKey())) || 'default', 'last_sync_at');const lastMs = lastSyncAt ? Date.parse(lastSyncAt) : NaN;if (!Number.isFinite(lastMs) || now - lastMs >= staleHours * 3_600_000) {problems.push(diff --git a/src/core/connectors/config-keys.ts b/src/core/connectors/config-keys.tsindex 878feaec0a..e18acbbd7a 100644--- a/src/core/connectors/config-keys.ts+++ b/src/core/connectors/config-keys.ts@@ -3,10 +3,13 @@** All connector knobs live in the `config` table under the `connectors.` prefix* (registered in KNOWN_CONFIG_KEY_PREFIXES). No secrets here — credentials are- * file-plane only. The watermark is a per-provider scalar (see sync.ts for why- * it is NOT op_checkpoint).+ * file-plane only. Sync progress (watermark, last sync, per-conversation+ * ledger) is keyed by (provider, source); see sync.ts for why it is NOT+ * op_checkpoint. The auth-error stamp stays per provider: it describes the+ * shared credential, not a source.*/+import type { BrainEngine } from '../engine.ts';import type { ConnectorProviderName } from './types.ts';/** Trailing gap-heal window behind the watermark, in days. */@@ -26,9 +29,43 @@ export const embedKickoffMinPagesKey = () => 'connectors.embed_kickoff_min_pagesexport const doctorStaleHoursKey = () => 'connectors.doctor_stale_hours';export const autoSyncKey = (p: ConnectorProviderName) => `connectors.${p}.auto_sync`;-export const lastSyncAtKey = (p: ConnectorProviderName) => `connectors.${p}.last_sync_at`;export const authErrorAtKey = (p: ConnectorProviderName) => `connectors.${p}.auth_error_at`;-export const watermarkKey = (p: ConnectorProviderName) => `connectors.${p}.watermark_iso`;++export type ConnectorSourceField = 'watermark_iso' | 'last_sync_at' | 'synced' | 'failed';+/** Per-(provider, source) sync state. */+export const connectorSourceKey = (p: ConnectorProviderName, sourceId: string, field: ConnectorSourceField) =>+ `connectors.${p}.source.${sourceId}.${field}`;+export const lastSyncAtKey = (p: ConnectorProviderName, sourceId: string) => connectorSourceKey(p, sourceId, 'last_sync_at');+export const watermarkKey = (p: ConnectorProviderName, sourceId: string) => connectorSourceKey(p, sourceId, 'watermark_iso');+/** Pre-per-source scalar; it can only have described the scheduled source. */+const legacyProviderKey = (p: ConnectorProviderName, field: 'watermark_iso' | 'last_sync_at') => `connectors.${p}.${field}`;++/**+ * Read a per-source watermark / last-sync stamp. A legacy per-provider value+ * is honored only for the scheduled source (`connectors.source_id`, default+ * 'default') and only until that source writes its own key.+ */+export async function readConnectorState(+ engine: BrainEngine, p: ConnectorProviderName, sourceId: string, field: 'watermark_iso' | 'last_sync_at',+): Promise<string | null> {+ const own = await engine.getConfig(connectorSourceKey(p, sourceId, field));+ if (own) return own;+ if (own !== null) return null;+ const scheduled = (await engine.getConfig(sourceIdKey())) || 'default';+ if (sourceId !== scheduled) return null;+ return (await engine.getConfig(legacyProviderKey(p, field))) || null;+}++/** Write a per-source stamp; the scheduled source retires the legacy scalar. */+export async function writeConnectorState(+ engine: BrainEngine, p: ConnectorProviderName, sourceId: string, field: 'watermark_iso' | 'last_sync_at', value: string,+): Promise<void> {+ await engine.setConfig(connectorSourceKey(p, sourceId, field), value);+ const scheduled = (await engine.getConfig(sourceIdKey())) || 'default';+ if (sourceId === scheduled && await engine.getConfig(legacyProviderKey(p, field))) {+ await engine.setConfig(legacyProviderKey(p, field), '');+ }+}/** The canonical truthiness parser for `auto_sync`-style flags. */export function isTruthy(v: string | null | undefined): boolean {diff --git a/src/core/connectors/sync.ts b/src/core/connectors/sync.tsindex c80154583b..b3d2f829bd 100644--- a/src/core/connectors/sync.ts+++ b/src/core/connectors/sync.ts@@ -3,13 +3,21 @@** Pipeline: resolve credential → build the real ConnectorClient → probe →* read the config-scalar watermark → list newest-first stopping at- * (watermark − windowDays) → fetch each new conversation → spool in batches in- * the provider's native-export shape → runTranscriptsIngest (reuses redaction,- * slugging, splitting, idempotency) → advance the watermark ONLY on a fully- * clean run → logIngest receipt → stamp last_sync_at → engine-branched embed- * kickoff → prune the spool.+ * (watermark − windowDays) → skip conversations whose `updatedAt` the source+ * already ingested → fetch the rest → spool in batches in the provider's+ * native-export shape → runTranscriptsIngest (reuses redaction, slugging,+ * splitting, idempotency) → advance the watermark ONLY on a clean run →+ * logIngest receipt → stamp last_sync_at → engine-branched embed kickoff →+ * prune the spool.*- * WATERMARK IS A CONFIG SCALAR (`connectors.<p>.watermark_iso`), NOT+ * All progress is keyed by (provider, source): the watermark, last_sync_at,+ * a `synced` ledger (conversation id → ingested updatedAt) that lets a capped+ * `--limit` run move on to older conversations, and a `failed` ledger. A+ * conversation that fails QUARANTINE_ATTEMPTS times at the same updatedAt is+ * quarantined: reported, no longer re-fetched, and no longer holding the+ * watermark back. An edit (new updatedAt) or `--full` retries it.+ *+ * STATE LIVES IN CONFIG SCALARS (`connectors.<p>.source.<id>.*`), NOT* op_checkpoint: op_checkpoint stores a completed-KEY set with no scalar since,* and purgeStaleCheckpoints GCs rows after 7 days — which would wipe the* watermark on any >7-day gap and trigger a full re-fetch (the exact hammer@@ -29,13 +37,16 @@ import { CONNECTOR_SPOOL_BATCH, pruneSpool, removeSpool, writeSpool } from './spimport type { ChatHistoryProvider, ConnectorProviderName, ConversationStub } from './types.ts';import {authErrorAtKey,+ connectorSourceKey,DEFAULT_EMBED_KICKOFF_MIN_PAGES,DEFAULT_WINDOW_DAYS,- lastSyncAtKey,- watermarkKey,+ readConnectorState,+ writeConnectorState,} from './config-keys.ts';export const CONNECTOR_SYNC_VERSION = 1;+/** Failed fetches at one updatedAt before a conversation is quarantined. */+export const QUARANTINE_ATTEMPTS = 3;export type ConnectorSyncStatus =| 'success'@@ -71,6 +82,10 @@ export interface ConnectorSyncResult {drift: boolean;};watermarkAdvancedTo?: string;+ /** Listed conversations skipped because this source already ingested that updatedAt. */+ skippedUnchanged: number;+ /** Conversation ids quarantined after repeated fetch failures (not re-fetched until edited). */+ quarantined: string[];spoolPaths: string[];embedKickoff: EmbedKickoffOutcome;hint?: string;@@ -164,6 +179,8 @@ export async function runConnectorSync(listed: 0,fetched: 0,fetchErrors: 0,+ skippedUnchanged: 0,+ quarantined: [],spoolPaths: [],embedKickoff: 'none',};@@ -199,8 +216,16 @@ export async function runConnectorSync(return { ...base, status: 'partial', hint: `probe failed: ${probe.detail}` };}- // Resolve the trailing-window since bound from the config-scalar watermark.- const watermark = opts.full ? '' : (await engine.getConfig(watermarkKey(opts.provider))) ?? '';+ // Resolve the trailing-window since bound from this source's watermark.+ const watermark = opts.full ? '' : (await readConnectorState(engine, opts.provider, sourceId, 'watermark_iso')) ?? '';+ const syncedKey = connectorSourceKey(opts.provider, sourceId, 'synced');+ const failedKey = connectorSourceKey(opts.provider, sourceId, 'failed');+ const synced = await readLedger<string>(engine, syncedKey);+ const failed = await readLedger<{ attempts: number; updatedAt: string }>(engine, failedKey);+ const saveLedgers = async () => {+ await engine.setConfig(syncedKey, JSON.stringify(synced));+ await engine.setConfig(failedKey, JSON.stringify(failed));+ };const stopBefore = watermark ? subtractDays(watermark, windowDays, now) : undefined;// LIST (metadata) — collect stubs newer than the window bound, newest-first.@@ -225,13 +250,28 @@ export async function runConnectorSync(base.listed = stubs.length;if (stubs.length === 0 && !listErrored) {- await engine.setConfig(lastSyncAtKey(opts.provider), new Date(now()).toISOString());+ await writeConnectorState(engine, opts.provider, sourceId, 'last_sync_at', new Date(now()).toISOString());return { ...base, status: 'nothing_new' };}+ // Skip what this source already holds and what is quarantined, BEFORE the+ // cap, so a capped run reaches conversations earlier runs did not.+ const quarantined: string[] = [];+ const pending = stubs.filter(stub => {+ if (opts.full) return true;+ if (stub.updatedAt && synced[stub.id] === stub.updatedAt) return false;+ const failure = failed[stub.id];+ if (failure && failure.updatedAt === (stub.updatedAt ?? '') && failure.attempts >= QUARANTINE_ATTEMPTS) {+ quarantined.push(stub.id);+ return false;+ }+ return true;+ });+ base.skippedUnchanged = stubs.length - pending.length - quarantined.length;+// Apply the per-run fetch cap (a cap ⇒ NOT a clean run).- const capped = typeof opts.limit === 'number' && stubs.length > opts.limit;- const toFetch = capped ? stubs.slice(0, opts.limit) : stubs;+ const capped = typeof opts.limit === 'number' && pending.length > opts.limit;+ const toFetch = capped ? pending.slice(0, opts.limit) : pending;if (opts.dryRun) {return { ...base, status: 'dry_run', listed: stubs.length, hint: `${toFetch.length} conversation(s) would be fetched` };@@ -241,6 +281,7 @@ export async function runConnectorSync(const spoolPaths: string[] = [];let fetched = 0;let fetchErrors = 0;+ let blockingFetchErrors = 0;let importedTotal = 0;let skippedTotal = 0;let erroredTotal = 0;@@ -254,10 +295,12 @@ export async function runConnectorSync(for (let bi = 0; bi < batches.length; bi++) {const batch = batches[bi];const convs: Array<Record<string, unknown>> = [];+ const convStubs: ConversationStub[] = [];for (const stub of batch) {if (opts.signal?.aborted) break;try {convs.push(await provider.fetchConversation(client, stub.id, { signal: opts.signal }));+ convStubs.push(stub);fetched++;opts.onProgress?.({ phase: 'fetch', listed: stubs.length, fetched, imported: importedTotal });} catch (e) {@@ -266,17 +309,25 @@ export async function runConnectorSync(await stampAuthError(engine, opts.provider, now);// Ingest whatever we already collected this batch before returning.if (convs.length) await ingestBatch();+ await saveLedgers();return { ...base, status: 'auth_required', listed: stubs.length, fetched, fetchErrors, spoolPaths, hint: provider.sessionInstructions() };}if (term === 'forbidden') {if (convs.length) await ingestBatch();+ await saveLedgers();return { ...base, status: 'forbidden', listed: stubs.length, fetched, fetchErrors, spoolPaths };}fetchErrors++;- log(`[connector] fetch error for ${stub.id}: ${e instanceof Error ? e.message : String(e)}`);+ const updatedAt = stub.updatedAt ?? '';+ const attempts = (failed[stub.id]?.updatedAt === updatedAt ? failed[stub.id].attempts : 0) + 1;+ failed[stub.id] = { attempts, updatedAt };+ if (attempts >= QUARANTINE_ATTEMPTS) quarantined.push(stub.id);+ else blockingFetchErrors++;+ log(`[connector] fetch error for ${stub.id} (attempt ${attempts}): ${e instanceof Error ? e.message : String(e)}`);}}if (convs.length) await ingestBatch();+ await saveLedgers();async function ingestBatch(): Promise<void> {const stamp = `${new Date(now()).toISOString().replace(/[:.]/g, '-')}-b${bi}`;@@ -295,6 +346,12 @@ export async function runConnectorSync(redactionsTotal += r.redactions;partsDeletedTotal += r.partsDeleted;if (!r.cleanScan) allBatchesClean = false;+ else {+ for (const stub of convStubs) {+ if (stub.updatedAt) synced[stub.id] = stub.updatedAt;+ delete failed[stub.id];+ }+ }if (r.driftFiles > 0) anyDrift = true;opts.onProgress?.({ phase: 'ingest', listed: stubs.length, fetched, imported: importedTotal });} finally {@@ -316,12 +373,20 @@ export async function runConnectorSync(drift: anyDrift,};- const clean = !listErrored && fetchErrors === 0 && !capped && allBatchesClean && !opts.signal?.aborted;+ base.quarantined = quarantined;+ // Quarantined conversations no longer hold the watermark back.+ const clean = !listErrored && blockingFetchErrors === 0 && !capped && allBatchesClean && !opts.signal?.aborted;- // Advance the watermark ONLY on a fully clean run.+ // Advance the watermark ONLY on a clean run.if (clean && maxUpdatedAt && maxUpdatedAt !== watermark) {- await engine.setConfig(watermarkKey(opts.provider), maxUpdatedAt);+ await writeConnectorState(engine, opts.provider, sourceId, 'watermark_iso', maxUpdatedAt);base.watermarkAdvancedTo = maxUpdatedAt;+ // Conversations older than the next run's list window are never listed+ // again, so their ledger entries are dead weight.+ const floor = subtractDays(maxUpdatedAt, windowDays, now);+ for (const [id, updatedAt] of Object.entries(synced)) if (updatedAt < floor) delete synced[id];+ for (const [id, entry] of Object.entries(failed)) if (entry.updatedAt < floor) delete failed[id];+ await saveLedgers();}// Receipt (written by the orchestrator, NOT runTranscriptsIngest).@@ -337,7 +402,7 @@ export async function runConnectorSync(});// Stamp last_sync_at (success + nothing_new both count as "we ran").- await engine.setConfig(lastSyncAtKey(opts.provider), new Date(now()).toISOString());+ await writeConnectorState(engine, opts.provider, sourceId, 'last_sync_at', new Date(now()).toISOString());// Clear a stale auth_error stamp on a clean run.if (clean) await engine.setConfig(authErrorAtKey(opts.provider), '');@@ -396,6 +461,17 @@ export async function maybeKickoffEmbed(}}+async function readLedger<T>(engine: BrainEngine, key: string): Promise<Record<string, T>> {+ const raw = await engine.getConfig(key);+ if (!raw) return {};+ try {+ const parsed: unknown = JSON.parse(raw);+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed as Record<string, T> : {};+ } catch {+ return {};+ }+}+async function readIntConfig(engine: BrainEngine, key: string, fallback: number): Promise<number> {const v = await engine.getConfig(key);if (v === null) return fallback;diff --git a/src/core/cycle.ts b/src/core/cycle.tsindex e1fc7b3686..1caf6d2707 100644--- a/src/core/cycle.ts+++ b/src/core/cycle.ts@@ -1523,6 +1523,7 @@ async function runPhaseExtractFacts(pagesWithFacts: result.pagesWithFacts,factsInserted: result.factsInserted,factsDeleted: result.factsDeleted,+ pagesFailed: result.pagesFailed,warnings: result.warnings.slice(0, 5),// v0.35.5: phantom counters surfaced so extractTotals() can lift// them to CycleReport.totals and the daily report makes thediff --git a/src/core/cycle/extract-facts.ts b/src/core/cycle/extract-facts.tsindex 5cd40778b8..998d91de07 100644--- a/src/core/cycle/extract-facts.ts+++ b/src/core/cycle/extract-facts.ts@@ -59,7 +59,7 @@ import type { BrainEngine } from '../engine.ts';import { assertUnmanagedCanonicalWriter } from '../persistence/maintenance.ts';import { resolveSupersededByRow, type SupersedeTarget } from '../facts/supersede-resolve.ts';import { writeReceipt } from '../extract/receipt-writer.ts';-import { upsertExtractRollup } from '../extract/rollup-writer.ts';+import { classifyRunStop, upsertExtractRollup } from '../extract/rollup-writer.ts';import { parseFactsFence, FACTS_FENCE_BEGIN } from '../facts-fence.ts';import {extractFactsFromFenceText,@@ -271,6 +271,8 @@ export interface ExtractFactsResult {factsDeleted: number;legacyRowsPending: number;guardTriggered: boolean;+ /** Pages whose reconcile threw and rolled back; later pages still ran. */+ pagesFailed: number;warnings: string[];/** v0.35.5: phantom-redirect pre-pass counts. */phantomsScanned: number;@@ -367,6 +369,7 @@ export async function runExtractFacts(factsInserted: 0,factsDeleted: 0,legacyRowsPending: 0,+ pagesFailed: 0,guardTriggered: false,warnings: [],phantomsScanned: 0,@@ -539,18 +542,14 @@ export async function runExtractFacts(}// ── Reconcile each page ───────────────────────────────────────- for (const slug of slugs) {- // #1972: bail at the top of the per-page loop on abort. Each page is an- // independent delete-then-insert commit, so breaking leaves a consistent- // partial state; the receipt/rollup below still runs with partial counts.- if (isAborted(opts.signal)) break;- result.pagesScanned += 1;-+ // Each page reconciles independently: 'stop' ends the walk (cancellation),+ // 'next' moves on. A thrown error is isolated to its page below.+ const reconcilePage = async (slug: string): Promise<'next' | 'stop'> => {const page = await engine.getPage(slug, { sourceId });if (!page) {// Slug listed but not in DB — skip silently. The next cycle// will pick it up if it exists.- continue;+ return 'next';}const body = page.compiled_truth ?? '';@@ -563,7 +562,7 @@ export async function runExtractFacts(// could still recover. That partial result is not authoritative: using// it for reconciliation would interpret skipped rows as deletions.// Preserve this page's existing index and continue with other pages.- continue;+ return 'next';}// #3625: splitBody() puts everything below the timeline sentinel into@@ -593,7 +592,7 @@ export async function runExtractFacts(`Move the fence above the sentinel and re-save — leaving it in place ` +`preserves the existing indexed facts but they will not update.`,);- continue;+ return 'next';}if (parsed.facts.length > 0) result.pagesWithFacts += 1;@@ -608,7 +607,7 @@ export async function runExtractFacts(extractFactsFromFenceText(parsed.facts, slug, sourceId, { pageEffectiveDate }),);- if (opts.dryRun) continue;+ if (opts.dryRun) return 'next';// #1781 — reconcile instead of unconditional wipe-and-reinsert. Compare// the fence's canonical (claim, source) row set against the page's@@ -644,7 +643,7 @@ export async function runExtractFacts(return true;});}, opts, result.warnings);- if (!restricted) continue;+ if (!restricted) return 'next';}if (extracted.length === 0) {@@ -674,11 +673,11 @@ export async function runExtractFacts(});}, opts, result.warnings);if (!deletion) {- continue;+ return 'next';}result.factsDeleted += deletion.deleted;}- continue;+ return 'next';}const hasStaleExisting = existing.some(f => !desiredByKey.has(factContentKey(f.fact, f.source)));@@ -761,7 +760,7 @@ export async function runExtractFacts(!hasSupersessionDrift &&!hasAttributeDrift) {- continue;+ return 'next';}let toInsert = extracted.filter(f => !existingKeys.has(factContentKey(f.fact, f.source)));@@ -827,15 +826,15 @@ export async function runExtractFacts(if (isAborted(opts.signal)) {result.warnings.push(`${slug}: fact reconciliation deferred after cancellation; existing rows preserved`);- break;+ return 'stop';}if (deleteForPageFirst && existing.some(fact => fact.has_embedding)&& toInsert.some(fact => !fact.embedding)) {result.warnings.push(`${slug}: destructive fact reconciliation deferred; existing vectors preserved until embedding succeeds`);- continue;+ return 'next';}- if (toInsert.length === 0) continue;+ if (toInsert.length === 0) return 'next';const insert = async () => {try {@@ -872,7 +871,7 @@ export async function runExtractFacts(return insert();}, opts, result.warnings): await insert();- if (!inserted) continue;+ if (!inserted) return 'next';result.factsInserted += inserted.inserted;// v0.46 (#3014) — the wipe (when needed) ran inside insertFacts' txn;// count it here from the atomic result rather than a separate delete.@@ -883,6 +882,25 @@ export async function runExtractFacts(// resolveSupersededByRow already prefixes each message with the slug +// row, so push verbatim — no `${slug}: ` re-prefix.for (const w of inserted.warnings) result.warnings.push(w);+ return 'next';+ };++ for (const slug of slugs) {+ // #1972: bail at the top of the per-page loop on abort. Each page is an+ // independent delete-then-insert commit, so breaking leaves a consistent+ // partial state; the receipt/rollup below still runs with partial counts.+ if (isAborted(opts.signal)) break;+ result.pagesScanned += 1;+ try {+ if (await reconcilePage(slug) === 'stop') break;+ } catch (error) {+ if (isAborted(opts.signal)) throw error;+ // One page the database rejects (CHECK/FK violation, malformed input the+ // parser tolerated) must not abort reconciliation for every later page.+ // Its transaction rolled back, so the existing index is preserved.+ result.pagesFailed += 1;+ result.warnings.push(`${slug}: FACTS_RECONCILE_FAILED: ${(error instanceof Error ? error.message : String(error)).slice(0, 300)}`);+ }}// v0.42 Wave B3: receipt + rollup. extract_facts is deterministic@@ -915,8 +933,7 @@ export async function runExtractFacts(kind: 'facts.fence',source_id: sourceId,cost_delta: 0,- round_completed_delta: 1,- halt_delta: 0,+ ...classifyRunStop({ error: result.pagesFailed > 0 }),});}diff --git a/src/core/cycle/phantom-redirect.ts b/src/core/cycle/phantom-redirect.tsindex 2adf282f4f..8489532a5a 100644--- a/src/core/cycle/phantom-redirect.ts+++ b/src/core/cycle/phantom-redirect.ts@@ -58,6 +58,7 @@ import { parseMarkdown, splitBody, serializeMarkdown } from '../markdown.ts';import { tryAcquireDbLock, syncLockId, type DbLockHandle } from '../db-lock.ts';import { isAborted } from '../abort-check.ts';import { logPhantomEvent, type PhantomOutcome } from '../facts/phantom-audit.ts';+import { MOVE_WITHDRAWAL_SUBJECT_SQL } from '../facts/withdrawal-schema.ts';/** Tagged-union outcome of a single phantom-redirect attempt. */export type RedirectOutcome =@@ -344,6 +345,9 @@ async function materializeCanonicalToDisk(fs.writeFileSync(canonicalPath, body, 'utf-8');}+/** Frontmatter a bare phantom stub may carry; any other key is residue. */+const PHANTOM_STUB_FRONTMATTER = new Set(['title', 'type', 'tags']);+/*** Single-phantom redirect. Caller (the pass) is responsible for the* outer lock + the audit-log cap.@@ -360,9 +364,15 @@ export async function tryRedirectPhantom(// A3 + codex #2: strict zero-residue body-shape gate. Real top-level// pages have prose; phantoms have only the stub-shape `# slug` + maybe- // a facts fence.- const residue = stripFenceAndFrontmatterAndLeadingH1(page.compiled_truth ?? '');- if (residue.length > 0) {+ // 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) {logPhantomEvent({phantom_slug: page.slug,outcome: 'not_phantom_has_residue',@@ -449,6 +459,8 @@ export async function tryRedirectPhantom(// Codex #3/#4/#12: lossless DB migration. Re-runs return migrated=0.const migrated = await engine.migrateFactsToCanonical(page.slug, canonical, sourceId);+ // Withdrawals are scoped to the entity; the phantom was the canonical entity.+ await engine.executeRaw(MOVE_WITHDRAWAL_SUBJECT_SQL, [sourceId, page.slug, canonical]);// D6: DB FK rewrite for the links table (wiki-link text rewrite is a// documented follow-up — codex #5).diff --git a/src/core/cycle/synthesize-concepts.ts b/src/core/cycle/synthesize-concepts.tsindex c484e35420..c217f83e6f 100644--- a/src/core/cycle/synthesize-concepts.ts+++ b/src/core/cycle/synthesize-concepts.ts@@ -275,7 +275,16 @@ export async function runPhaseSynthesizeConcepts(fallback: 'sonnet',});const synthMaxOutputTokens = resolveSynthMaxOutputTokens(synthModel);+ const skippedHumanOwned: string[] = [];for (const group of atomGroups) {+ const conceptSlug = `concepts/${group.conceptSlug.split('/').pop() ?? 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' });+ if (existing && !String(existing.frontmatter?.synthesized_by ?? '').startsWith('synthesize_concepts')) {+ skippedHumanOwned.push(conceptSlug);+ continue;+ }tierCounts[group.tier]++;let narrative: string;let synthesisMode: ConceptSynthesisMode;@@ -355,7 +364,7 @@ export async function runPhaseSynthesizeConcepts(synthesisModeCounts[synthesisMode]++;if (!opts.dryRun) {- const title = group.conceptSlug.split('/').pop() ?? group.conceptSlug;+ const title = conceptSlug.slice('concepts/'.length);// #2163: serialize to markdown and import via the canonical pipeline so// the page is chunked (+ embedded when a provider is configured) —// mirrors put_page's isAvailable('embedding') → noEmbed gate.@@ -372,7 +381,6 @@ export async function runPhaseSynthesizeConcepts('',{ type: 'concept', title: title.replace(/-/g, ' '), tags: [] },);- const conceptSlug = `concepts/${title}`;await importFromContent(engine, conceptSlug, md, {noEmbed: !isAvailable('embedding'),// #4416: target the cycle's resolved source, not the 'default' literal.@@ -465,7 +473,8 @@ export async function runPhaseSynthesizeConcepts(`synthesize_concepts: ${conceptsWritten} concepts ` +`(T1=${tierCounts.T1} T2=${tierCounts.T2} T3=${tierCounts.T3})` +(failures.length > 0 ? ` (${failures.length} LLM-failed → template fallback)` : '') +- (linkWarnings.length > 0 ? ` (${linkWarnings.length} provenance-link warning(s))` : ''),+ (linkWarnings.length > 0 ? ` (${linkWarnings.length} provenance-link warning(s))` : '') ++ (skippedHumanOwned.length > 0 ? ` (${skippedHumanOwned.length} human-owned page(s) left untouched)` : ''),details: {concepts_written: conceptsWritten,tier_counts: tierCounts,@@ -474,6 +483,7 @@ export async function runPhaseSynthesizeConcepts(atoms_seen: atoms.length,failures,link_warnings: linkWarnings,+ skipped_human_owned: skippedHumanOwned,...(abortedGlobalError ? { aborted_global_error: abortedGlobalError } : {}),estimated_spend_usd: estimatedSpendUsd,budget_usd: budgetCap,diff --git a/src/core/cycle/synthesize.ts b/src/core/cycle/synthesize.tsindex f75c0c818d..f695e28619 100644--- a/src/core/cycle/synthesize.ts+++ b/src/core/cycle/synthesize.ts@@ -2815,8 +2815,10 @@ async function collectChildPutPageSlugs(* transcripts the old code path never re-ran, and reading `result` at all* would need the `(result #>> '{}')` double-encoded-jsonb defense.*- * Loads source-scoped completions once per phase; no schema additions- * and no repeated history scan for each transcript.+ * Completed rows that `jobs prune` removed live on in+ * `dream_synthesis_completions` (the prune archives them), so pruning never+ * makes a synthesized transcript eligible again. Loads source-scoped+ * completions once per phase; no repeated history scan per transcript.*/async function loadSuccessfulSynthesisKeys(engine: BrainEngine,@@ -2829,7 +2831,10 @@ async function loadSuccessfulSynthesisKeys(WHERE name = 'subagent'AND status = 'completed'AND COALESCE(NULLIF(data->>'source_id', ''), 'default') = $1- AND idempotency_key LIKE $2`,+ AND idempotency_key LIKE $2+ UNION+ SELECT idempotency_key FROM dream_synthesis_completions+ WHERE source_id = $1 AND idempotency_key LIKE $2`,[sourceId, `${keyPrefix}%`],);return rows.map(row => row.idempotency_key);diff --git a/src/core/export-snapshot.ts b/src/core/export-snapshot.tsindex 9a018f1e01..b1e11afa1c 100644--- a/src/core/export-snapshot.ts+++ b/src/core/export-snapshot.ts@@ -4,16 +4,19 @@ import type { PageWithdrawal } from './page-state/types.ts';import { rowToPage } from './utils.ts';import { EXPORT_PAYLOAD_LIMIT } from './export-stage.ts';-export async function readExportWithdrawals(tx: BrainEngine, sourceId: string): Promise<PageWithdrawal[]> {+/** Withdrawals are entity-scoped: `subject` is the entity slug, '*' applies to every page. */+export type ExportWithdrawal = PageWithdrawal & { subject: string };++export async function readExportWithdrawals(tx: BrainEngine, sourceId: string): Promise<ExportWithdrawal[]> {const [size] = await tx.executeRaw<{ bytes: number }>(`SELECT COALESCE(sum(octet_length(- jsonb_build_object('visibility',visibility,'fact_hash',fact_hash,'withdrawn_at',withdrawn_at)::text)+1),0)+2 AS bytes+ jsonb_build_object('visibility',visibility,'fact_hash',fact_hash,'withdrawn_at',withdrawn_at,'subject',subject)::text)+1),0)+2 AS bytesFROM fact_withdrawals WHERE source_id=$1`, [sourceId]);if (Number(size.bytes) > EXPORT_PAYLOAD_LIMIT) throw new Error('Export withdrawal ledger capacity exceeded. No destination output was published.');- return tx.executeRaw<PageWithdrawal>(`SELECT visibility,fact_hash,withdrawn_at- FROM fact_withdrawals WHERE source_id=$1 ORDER BY visibility,fact_hash`, [sourceId]);+ return tx.executeRaw<ExportWithdrawal>(`SELECT visibility,fact_hash,withdrawn_at,subject+ FROM fact_withdrawals WHERE source_id=$1 ORDER BY visibility,fact_hash,subject`, [sourceId]);}-export async function readExportPage(tx: BrainEngine, key: { id: string; source_id: string; slug: string }, withdrawals: PageWithdrawal[]) {+export async function readExportPage(tx: BrainEngine, key: { id: string; source_id: string; slug: string }, withdrawals: ExportWithdrawal[]) {const [row] = await tx.executeRaw<Record<string, unknown>>(`WITH export_page AS MATERIALIZED (SELECT * FROM pages WHERE id=$1::bigint) SELECT p.*,@@ -23,7 +26,9 @@ export async function readExportPage(tx: BrainEngine, key: { id: string; source_if (!row) throw new Error('Export snapshot unexpectedly lost a selected page.');const page = rowToPage(row);if (page.compiled_truth.includes('gbrain:facts:') || page.timeline.includes('gbrain:facts:')) {- Object.assign(page, await overlayCanonicalBodies(tx.executeRaw.bind(tx), page.compiled_truth, page.timeline, withdrawals));+ const applicable = withdrawals.filter(w => w.subject === '*' || w.subject === page.slug)+ .map(({ visibility, fact_hash, withdrawn_at }) => ({ visibility, fact_hash, withdrawn_at }));+ Object.assign(page, await overlayCanonicalBodies(tx.executeRaw.bind(tx), page.compiled_truth, page.timeline, applicable));}return { page, tags: row.export_tags as string[] };}diff --git a/src/core/facts-fence.ts b/src/core/facts-fence.tsindex c4765953eb..e83007fac3 100644--- a/src/core/facts-fence.ts+++ b/src/core/facts-fence.ts@@ -77,7 +77,7 @@ export interface ParsedFact {rowNum: number;claim: string; // strikethrough markers stripped on parsekind: FactKind;- confidence: number; // 0..1 (clamp/normalize happens in the engine layer)+ confidence: number; // 0..1; out-of-range cells are FACTS_TABLE_MALFORMEDvisibility: FactVisibility;notability: FactNotability;validFrom?: string; // ISO date 'YYYY-MM-DD' (or empty)@@ -265,6 +265,10 @@ export function parseFactsFence(body: string): FactsFenceParseResult {warnings.push(`FACTS_TABLE_MALFORMED: non-numeric confidence "${confidenceRaw}" in row ${rowNumStr}`);continue;}+ if (confidence < 0 || confidence > 1) {+ warnings.push(`FACTS_TABLE_MALFORMED: confidence "${confidenceRaw}" in row ${rowNumStr} is outside 0..1`);+ continue;+ }const { text: claimText, struck } = stripStrikethrough(claimRaw);const context = parseStringCell(contextRaw);diff --git a/src/core/facts/embedding-identity.ts b/src/core/facts/embedding-identity.tsindex 612456cc51..8e05d70dd4 100644--- a/src/core/facts/embedding-identity.ts+++ b/src/core/facts/embedding-identity.ts@@ -5,7 +5,8 @@ export const retainedFactEmbedding = `f.expired_at IS NULL AND f.superseded_by IAND (f.valid_until IS NULL OR f.valid_until>now())AND NOT (f.source = ANY($2::text[]))AND NOT EXISTS (SELECT 1 FROM fact_withdrawals w WHERE w.source_id=f.source_id- AND w.visibility=f.visibility AND w.fact_hash=gbrain_fact_fingerprint(f.fact))`;+ AND w.visibility=f.visibility AND (w.subject = '*' OR w.subject = f.entity_slug)+ AND w.fact_hash=gbrain_fact_fingerprint(f.fact))`;export const eligibleFactEmbedding = `${retainedFactEmbedding}AND EXISTS (SELECT 1 FROM sources s WHERE s.id=f.source_id AND NOT s.archived)diff --git a/src/core/facts/forget.ts b/src/core/facts/forget.tsindex da75539139..08ea8a2164 100644--- a/src/core/facts/forget.ts+++ b/src/core/facts/forget.ts@@ -58,21 +58,28 @@ const FENCE_BEGIN = '<!--- gbrain:facts:begin -->';const FENCE_END = '<!--- gbrain:facts:end -->';/**- * Strike fence row `rowNum` inside `body`: strikethrough on the claim- * (already-struck rows stay struck), valid_until = today, `forgotten:- * <reason>` appended to context (preserving any existing context). Returns- * the rewritten body, or null when the fence lacks the row (DB drifted from- * markdown) or its markers — callers fall back to a DB-only expire.+ * A superseded row is struck like a forgotten one but carries the parser's+ * `superseded by #N` reference instead of the withdrawal marker, so the next+ * reconcile links it and it never becomes a durable withdrawal.*/-function strikeFenceRow(body: string, rowNum: number, reason: string, today: string): string | null {+function supersededFact(fact: ParsedFact, today: string, newRowNum: number | null): ParsedFact {+ const context = [newRowNum !== null ? `superseded by #${newRowNum}` : 'superseded', fact.context?.trim()].filter(Boolean).join(' | ');+ const validUntil = fact.validUntil && /^\d{4}-\d{2}-\d{2}$/.test(fact.validUntil) && fact.validUntil < today ? fact.validUntil : today;+ return { ...fact, active: false, validUntil, context };+}++/**+ * Strike fence row `rowNum` inside `body` with `strike` (strikethrough,+ * valid_until = today, and a withdrawal or supersession marker in context,+ * preserving existing context). Returns the rewritten body, or null when the+ * fence lacks the row (DB drifted from markdown) or its markers — callers+ * fall back to a DB-only expire.+ */+function strikeFenceRow(body: string, rowNum: number, strike: (fact: ParsedFact) => ParsedFact): string | null {const parsed = parseFactsFence(body);const target = parsed.facts.find(f => f.rowNum === rowNum);if (!target) return null;- const updated: ParsedFact[] = parsed.facts.map(f =>- f.rowNum === rowNum- ? withdrawnFact(f, today, reason)- : f,- );+ const updated: ParsedFact[] = parsed.facts.map(f => f.rowNum === rowNum ? strike(f) : f);const begin = body.indexOf(FENCE_BEGIN);const end = body.indexOf(FENCE_END, begin + 1);if (begin === -1 || end === -1) return null;@@ -109,10 +116,21 @@ export async function forgetFactInFence(* could never read (mirrors recall's remote posture).*/worldOnly?: boolean;+ /**+ * Supersession, not withdrawal: expire and strike the row with a+ * `superseded by #N` reference to the replacing fact's fence row. No+ * durable withdrawal is recorded, so the old claim can be remembered+ * again and no other page is invalidated.+ */+ supersededBy?: { rowNum: number | null };} = {},): Promise<ForgetFactResult> {const reason = opts.reason ?? 'forgotten';const today = todayUtc();+ const supersession = opts.supersededBy;+ const strike = (fact: ParsedFact) => supersession+ ? supersededFact(fact, today, supersession.rowNum)+ : withdrawnFact(fact, today, reason);const rows = await engine.executeRaw<FactDbRow>(`SELECT id, source_id, entity_slug, row_num, source_markdown_slug, expired_at, visibility@@ -141,7 +159,13 @@ export async function forgetFactInFence(// A stale source file or rebuilt index must not silently restore an exact// withdrawn claim. Intent commits independently of filesystem availability.- await recordFactWithdrawal(engine, factId, row.source_id, opts.worldOnly === true);+ // A supersession only expires the row.+ if (supersession) {+ await engine.executeRaw(`UPDATE facts SET valid_until = LEAST(COALESCE(valid_until, now()), now()), expired_at = now()+ WHERE id = $1 AND expired_at IS NULL`, [factId]);+ } else {+ await recordFactWithdrawal(engine, factId, row.source_id, opts.worldOnly === true);+ }if (row.expired_at !== null) {return { ok: false, path: 'already_expired', reason };@@ -154,7 +178,7 @@ export async function forgetFactInFence(const slug = row.source_markdown_slug;const page = await engine.getPage(slug, { sourceId: row.source_id });if (!page) return;- const struck = strikeFenceRow(page.compiled_truth ?? '', row.row_num, reason, today);+ const struck = strikeFenceRow(page.compiled_truth ?? '', row.row_num, strike);if (struck === null) return;// The FILE was not rewritten on this tier, so the row must NOT keep the// importer's hash: sync would see file == row and skip, leaving@@ -170,7 +194,7 @@ export async function forgetFactInFence(// holds the same per-page lock the fence writers do (`locked` = the fence// tier is calling from inside its own withPageLock).const legacyExpire = async (locked = false): Promise<ForgetFactResult> => {- const ok = row.expired_at === null; // recordFactWithdrawal already committed the expiry.+ const ok = row.expired_at === null; // the expiry already committed above.if (ok && row.source_markdown_slug !== null) {const slug = row.source_markdown_slug;await (locked ? strikeDbBody() : withPageLock(slug, strikeDbBody, { timeoutMs: 5_000 }))@@ -223,7 +247,7 @@ export async function forgetFactInFence(// Fence missing the row (DB drifted from markdown) or its markers (race /// corruption): fall through to legacy expire so the user's intent// succeeds; doctor surfaces the drift separately.- const newBody = strikeFenceRow(body, targetRowNum, reason, today);+ const newBody = strikeFenceRow(body, targetRowNum, strike);if (newBody === null) return legacyExpire(true);// Atomic .tmp + parse-validate + rename.diff --git a/src/core/facts/single-prepare.ts b/src/core/facts/single-prepare.tsindex ce39cf4b37..f2e14047ce 100644--- a/src/core/facts/single-prepare.ts+++ b/src/core/facts/single-prepare.ts@@ -21,7 +21,7 @@ export async function prepareFactEmbedding(fact: string, signal?: AbortSignal):return { embedding: null, embedding_model: null, degraded: true };}export async function assertFactNotWithdrawn(engine: BrainEngine, sourceId: string, input: SingleFactIntent): Promise<void> {- if (await isFactWithdrawn(engine, sourceId, input.visibility, input.fact)) {+ if (await isFactWithdrawn(engine, sourceId, input.visibility, input.fact, input.entity_slug)) {throw verbError('invalid_params', 'fact_withdrawn: this exact claim was explicitly forgotten in this source and visibility.','Remember a corrected claim. Repeating the old claim does not restore withdrawn memory.');}diff --git a/src/core/facts/withdrawal-schema.ts b/src/core/facts/withdrawal-schema.tsindex 156c509f06..234a59f95c 100644--- a/src/core/facts/withdrawal-schema.ts+++ b/src/core/facts/withdrawal-schema.ts@@ -1,11 +1,21 @@-/** Durable withdrawal survives deletion/recreation of the derived facts index. */+/**+ * Durable withdrawal survives deletion/recreation of the derived facts index.+ *+ * `subject` scopes a withdrawal to the entity whose fact was forgotten (the+ * withdrawn row's entity_slug). '*' applies to every subject: a subjectless+ * fact cannot say whom it was about, and rows recorded before subject scoping+ * keep their source-wide reach, so an upgrade never resurrects a forgotten+ * claim. A withdrawal matches a fact when `subject = '*' OR subject =+ * entity_slug`.+ */export const FACT_WITHDRAWAL_SCHEMA_STATEMENTS = [`CREATE TABLE IF NOT EXISTS fact_withdrawals (source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,visibility TEXT NOT NULL CHECK (visibility IN ('private','world')),+ subject TEXT NOT NULL DEFAULT '*',fact_hash TEXT NOT NULL,withdrawn_at TIMESTAMPTZ NOT NULL DEFAULT now(),- PRIMARY KEY (source_id, visibility, fact_hash)+ PRIMARY KEY (source_id, visibility, subject, fact_hash))`,`CREATE OR REPLACE FUNCTION gbrain_fact_fingerprint(claim TEXT) RETURNS TEXTLANGUAGE SQL IMMUTABLE STRICT AS $fn$@@ -19,8 +29,9 @@ export const FACT_WITHDRAWAL_SCHEMA_STATEMENTS = [-- Serializes insertion with source-locked withdrawal, including a-- concurrent reimport. Ordinary row locks work on both engines.PERFORM id FROM sources WHERE id = NEW.source_id FOR SHARE;- SELECT withdrawn_at INTO withdrawn FROM fact_withdrawals+ SELECT min(withdrawn_at) INTO withdrawn FROM fact_withdrawalsWHERE source_id = NEW.source_id AND visibility = NEW.visibility+ AND (subject = '*' OR subject = NEW.entity_slug)AND fact_hash = gbrain_fact_fingerprint(NEW.fact);IF withdrawn IS NOT NULL THENNEW.expired_at := withdrawn;@@ -31,7 +42,7 @@ export const FACT_WITHDRAWAL_SCHEMA_STATEMENTS = [END$fn$`,`DROP TRIGGER IF EXISTS facts_preserve_withdrawal ON facts`,- `CREATE TRIGGER facts_preserve_withdrawal BEFORE INSERT OR UPDATE OF fact, source_id, visibility, expired_at ON facts+ `CREATE TRIGGER facts_preserve_withdrawal BEFORE INSERT OR UPDATE OF fact, source_id, visibility, entity_slug, expired_at ON factsFOR EACH ROW EXECUTE FUNCTION gbrain_preserve_fact_withdrawal()`,] as const;@@ -43,3 +54,17 @@ export const FACT_WITHDRAWAL_BACKFILL_SQL = `INSERT INTO fact_withdrawals(sourceFROM facts WHERE expired_at IS NOT NULL AND context LIKE '%forgotten:%'GROUP BY source_id, visibility, gbrain_fact_fingerprint(fact)ON CONFLICT DO NOTHING`;++/** Subject-scoped withdrawal keys; existing rows keep the source-wide '*' subject. */+export const FACT_WITHDRAWAL_SUBJECT_SQL = `ALTER TABLE fact_withdrawals ADD COLUMN IF NOT EXISTS subject TEXT NOT NULL DEFAULT '*';+ALTER TABLE fact_withdrawals DROP CONSTRAINT IF EXISTS fact_withdrawals_pkey;+ALTER TABLE fact_withdrawals ADD CONSTRAINT fact_withdrawals_pkey PRIMARY KEY (source_id, visibility, subject, fact_hash);+` + FACT_WITHDRAWAL_SCHEMA_SQL;++/** Rename/merge: withdrawals follow the entity ($1 source, $2 old slug, $3 new slug). */+export const MOVE_WITHDRAWAL_SUBJECT_SQL = `WITH moved AS (+ DELETE FROM fact_withdrawals WHERE source_id = $1 AND subject = $2 AND $2 <> $3+ RETURNING visibility, fact_hash, withdrawn_at+ )+ INSERT INTO fact_withdrawals(source_id, visibility, subject, fact_hash, withdrawn_at)+ SELECT $1, visibility, $3, fact_hash, withdrawn_at FROM moved ON CONFLICT DO NOTHING`;diff --git a/src/core/facts/withdrawal.ts b/src/core/facts/withdrawal.tsindex 305ae3904d..1281168f2f 100644--- a/src/core/facts/withdrawal.ts+++ b/src/core/facts/withdrawal.ts@@ -18,25 +18,31 @@ export async function recordFactWithdrawal(// A managed caller takes this EXCLUSIVE source lock before authority,// counters and request rows. Repeating an already-held lock is safe.await tx.executeRaw('SELECT id FROM sources WHERE id=$1 FOR UPDATE', [sourceId]);- const visible = await tx.executeRaw<{ visibility: 'private' | 'world'; fact: string; fact_hash: string }>(- `SELECT visibility,fact,gbrain_fact_fingerprint(fact) AS fact_hash FROM facts WHERE id=$1 AND source_id=$2+ const visible = await tx.executeRaw<{ visibility: 'private' | 'world'; fact_hash: string; subject: string }>(+ `SELECT visibility,gbrain_fact_fingerprint(fact) AS fact_hash,COALESCE(entity_slug,'*') AS subject FROM facts WHERE id=$1 AND source_id=$2AND ($3::boolean=false OR visibility='world')`, [id, sourceId, worldOnly]);if (!visible.length) return { withdrawn: false, pages: [] };- const target = visible[0];+ const { visibility, fact_hash, subject } = visible[0];+ // Discovery stays claim-wide (a conservative superset of affected pages);+ // only an existing withdrawal covering this subject makes it a no-op.const existing = await tx.executeRaw(`SELECT 1 FROM fact_withdrawals- WHERE source_id=$1 AND visibility=$2 AND fact_hash=$3 LIMIT 1`, [sourceId, target.visibility, target.fact_hash]);- const affected = existing.length ? [] : await discoverWithdrawalTargets(tx, sourceId, [target]).catch(withdrawalDiscoveryFailure);+ WHERE source_id=$1 AND visibility=$2 AND fact_hash=$3 AND (subject='*' OR subject=$4) LIMIT 1`,+ [sourceId, visibility, fact_hash, subject]);+ const affected = existing.length ? [] : await discoverWithdrawalTargets(tx, sourceId, [{ visibility, fact_hash }]).catch(withdrawalDiscoveryFailure);await tx.lockPageKeys(affected.map(({ slug }) => ({ sourceId, slug })));- const rows = await tx.executeRaw<{ visibility: string; fact: string }>(- `SELECT visibility,fact FROM facts WHERE id=$1 AND source_id=$2+ const rows = await tx.executeRaw<{ visibility: string; fact: string; subject: string }>(+ `SELECT visibility,fact,COALESCE(entity_slug,'*') AS subject FROM facts WHERE id=$1 AND source_id=$2AND ($3::boolean=false OR visibility='world') FOR UPDATE`, [id, sourceId, worldOnly]);if (!rows.length) return { withdrawn: false, pages: [] };const row = rows[0];- const inserted = await tx.executeRaw(`INSERT INTO fact_withdrawals(source_id,visibility,fact_hash)- VALUES ($1,$2,gbrain_fact_fingerprint($3)) ON CONFLICT DO NOTHING RETURNING fact_hash`, [sourceId,row.visibility,row.fact]);+ // Scoped to the forgotten row's entity: the same claim about another+ // entity stays active and rememberable. A subjectless fact withdraws+ // source-wide ('*').+ const inserted = await tx.executeRaw(`INSERT INTO fact_withdrawals(source_id,visibility,subject,fact_hash)+ VALUES ($1,$2,$4,gbrain_fact_fingerprint($3)) ON CONFLICT DO NOTHING RETURNING fact_hash`, [sourceId,row.visibility,row.fact,row.subject]);await tx.executeRaw(`UPDATE facts SET expired_at=now(),valid_until=LEAST(COALESCE(valid_until,now()),now())WHERE source_id=$1 AND visibility=$2 AND gbrain_fact_fingerprint(fact)=gbrain_fact_fingerprint($3)- AND expired_at IS NULL`, [sourceId,row.visibility,row.fact]);+ AND ($4='*' OR entity_slug=$4) AND expired_at IS NULL`, [sourceId,row.visibility,row.fact,row.subject]);if (!inserted.length) return { withdrawn: false, pages: [] };// Logical revision and projection invalidation commit with the withdrawal.// The revision trigger queues durable rebuild work even for unmanaged calls.@@ -55,36 +61,43 @@ export async function recordFactWithdrawal(});}-async function ambiguousFenceMatchesWithdrawal(engine: BrainEngine, sourceId: string, bodies: readonly string[]): Promise<boolean> {+async function ambiguousFenceMatchesWithdrawal(engine: BrainEngine, sourceId: string, bodies: readonly string[], subject: string | null): Promise<boolean> {const claims = bodies.flatMap(ambiguousFenceClaims);if (!claims.length) return false;const rows = await engine.executeRaw(`SELECT 1 FROM jsonb_to_recordset($2::text::jsonb) incoming(claim text,visibility text)JOIN fact_withdrawals w ON w.source_id=$1 AND w.fact_hash=gbrain_fact_fingerprint(incoming.claim)- AND (incoming.visibility IS NULL OR w.visibility=incoming.visibility) LIMIT 1`,- [sourceId, JSON.stringify(claims)]);+ AND (incoming.visibility IS NULL OR w.visibility=incoming.visibility)+ AND ($3::text IS NULL OR w.subject = '*' OR w.subject = $3::text) LIMIT 1`,+ [sourceId, JSON.stringify(claims), subject]);return rows.length > 0;}-async function withdrawalDates(engine: BrainEngine, sourceId: string, facts: readonly ParsedFact[]): Promise<Map<number,string>> {+async function withdrawalDates(engine: BrainEngine, sourceId: string, facts: readonly ParsedFact[], subject: string | null): Promise<Map<number,string>> {if (!facts.length) return new Map();const rows = await engine.executeRaw<{ row_num: number; withdrawn_at: string }>(- `SELECT incoming.row_num, w.withdrawn_at::text FROM jsonb_to_recordset($2::text::jsonb)+ `SELECT incoming.row_num, min(w.withdrawn_at)::text AS withdrawn_at FROM jsonb_to_recordset($2::text::jsonb)AS incoming(row_num integer,claim text,visibility text)JOIN fact_withdrawals w ON w.source_id=$1 AND w.visibility=incoming.visibility- AND w.fact_hash=gbrain_fact_fingerprint(incoming.claim)`,- [sourceId, JSON.stringify(facts.map(f => ({ row_num:f.rowNum, claim:f.claim, visibility:f.visibility })))],+ AND w.fact_hash=gbrain_fact_fingerprint(incoming.claim)+ AND ($3::text IS NULL OR w.subject = '*' OR w.subject = $3::text)+ GROUP BY incoming.row_num`,+ [sourceId, JSON.stringify(facts.map(f => ({ row_num:f.rowNum, claim:f.claim, visibility:f.visibility }))), subject],);return new Map(rows.map(r => [r.row_num, new Date(r.withdrawn_at).toISOString().slice(0,10)]));}-/** Overlay stale source files before hashing/chunking, retaining an explicit retraction. */-export async function preserveWithdrawnFenceRows(engine: BrainEngine, sourceId: string, body: string): Promise<string> {+/**+ * Overlay stale source files before hashing/chunking, retaining an explicit+ * retraction. Fence rows belong to the page's entity, so pass the page slug+ * as `subject`; without it every subject's withdrawal applies (conservative).+ */+export async function preserveWithdrawnFenceRows(engine: BrainEngine, sourceId: string, body: string, subject?: string): Promise<string> {if (!body.includes('gbrain:facts:begin')) return body;const blocks = withdrawalFenceBlocks(body);for (const block of blocks.reverse()) {// Preserve malformed-fence diagnostics; never re-render a partial parse.if (block.parsed.warnings.length) continue;- const dates = await withdrawalDates(engine, sourceId, block.parsed.facts);+ const dates = await withdrawalDates(engine, sourceId, block.parsed.facts, subject ?? null);if (!dates.size) continue;const facts = block.parsed.facts.map(f => {const date = dates.get(f.rowNum);@@ -95,11 +108,15 @@ export async function preserveWithdrawnFenceRows(engine: BrainEngine, sourceId:return body;}-/** Refuse provider-free preparation that raced a newly committed withdrawal. */-export async function assertPreparedFactWithdrawals(engine: BrainEngine, sourceId: string, body: string, timeline: string): Promise<void> {- const changed = await preserveWithdrawnFenceRows(engine, sourceId, body) !== body ||- await preserveWithdrawnFenceRows(engine, sourceId, timeline) !== timeline;- const blocked = await ambiguousFenceMatchesWithdrawal(engine, sourceId, [body, timeline]);+/**+ * Refuse provider-free preparation that raced a newly committed withdrawal.+ * `subject` is the page slug the prepared body belongs to (see+ * preserveWithdrawnFenceRows); without it every subject's withdrawal counts.+ */+export async function assertPreparedFactWithdrawals(engine: BrainEngine, sourceId: string, body: string, timeline: string, subject?: string): Promise<void> {+ const changed = await preserveWithdrawnFenceRows(engine, sourceId, body, subject) !== body ||+ await preserveWithdrawnFenceRows(engine, sourceId, timeline, subject) !== timeline;+ const blocked = await ambiguousFenceMatchesWithdrawal(engine, sourceId, [body, timeline], subject ?? null);if (changed) {throw new OperationError('revision_conflict', 'A fact withdrawal changed during import preparation. Retry the import.','Read the current page revision, then submit the updated import with a new request_id.');@@ -110,9 +127,12 @@ export async function assertPreparedFactWithdrawals(engine: BrainEngine, sourceI}}-/** Explicit remember is not an implicit restore operation. */-export async function isFactWithdrawn(engine: BrainEngine, sourceId: string, visibility: string, claim: string): Promise<boolean> {+/** Explicit remember is not an implicit restore operation for that entity. */+export async function isFactWithdrawn(+ engine: BrainEngine, sourceId: string, visibility: string, claim: string, entitySlug: string | null,+): Promise<boolean> {const rows = await engine.executeRaw(`SELECT 1 FROM fact_withdrawals- WHERE source_id=$1 AND visibility=$2 AND fact_hash=gbrain_fact_fingerprint($3)`, [sourceId,visibility,claim]);+ WHERE source_id=$1 AND visibility=$2 AND fact_hash=gbrain_fact_fingerprint($3)+ AND (subject = '*' OR subject = $4::text)`, [sourceId,visibility,claim,entitySlug]);return rows.length > 0;}diff --git a/src/core/facts/write-single.ts b/src/core/facts/write-single.tsindex 08aab7f113..af81f0a87b 100644--- a/src/core/facts/write-single.ts+++ b/src/core/facts/write-single.ts@@ -88,13 +88,6 @@ export async function writeSingleFact(const kind = input.kind ?? 'fact';const visibility = input.visibility ?? 'private';const validUntil = input.validUntil ?? null;- const { isFactWithdrawn } = await import('./withdrawal.ts');- if (await isFactWithdrawn(engine, sourceId, visibility, factText)) {- const { verbError } = await import('../ops/contract.ts');- throw verbError('invalid_params', 'fact_withdrawn: this exact claim was explicitly forgotten in this source and visibility.',- 'Remember a corrected claim. Repeating the old claim does not restore withdrawn memory.');- }-// #4755: normalize null-like entity refs to ABSENT before resolution so// the `resolved?.slug ?? entityRef` fallback can never adopt "null" as a// slug. Applied here (not only at the verb boundary) so every@@ -109,6 +102,13 @@ export async function writeSingleFact(// resolver returned nothing (fail-closed — no live page was verified).const resolutionSource = resolved?.source ?? null;+ const { isFactWithdrawn } = await import('./withdrawal.ts');+ if (await isFactWithdrawn(engine, sourceId, visibility, factText, resolvedSlug)) {+ const { verbError } = await import('../ops/contract.ts');+ throw verbError('invalid_params', 'fact_withdrawn: this exact claim was explicitly forgotten in this source and visibility.',+ 'Remember a corrected claim. Repeating the old claim does not restore withdrawn memory.');+ }+// Embedding (NOT an LLM call): powers dedup + downstream recall. Fail-soft —// a missing/failing provider degrades dedup, never the write.let embedding: Float32Array | null = null;@@ -248,16 +248,21 @@ export async function writeSingleFact(}/**- * Fence-path supersession bookkeeping: expire the old row through the fence- * (strikethrough + valid_until, the same surface `forget` uses) and link- * `superseded_by` for the audit trail. Both steps best-effort — the new fact- * is already durably written; a partial supersede is an audit gap, not data- * loss.+ * Fence-path supersession bookkeeping: strike the old row in the fence with a+ * `superseded by #N` reference (strikethrough + valid_until) and link+ * `superseded_by` for the audit trail. A supersession is an update, never a+ * durable withdrawal: the old claim stays rememberable and no other page is+ * invalidated. Both steps best-effort — the new fact is already durably+ * written; a partial supersede is an audit gap, not data loss.*/async function expireSuperseded(engine: BrainEngine, oldId: number, newId: number): Promise<void> {try {const { forgetFactInFence } = await import('./forget.ts');- await forgetFactInFence(engine, oldId, { reason: `superseded by fact #${newId}` });+ const [replacement] = await engine.executeRaw<{ row_num: number | null; same_page: boolean }>(+ `SELECT n.row_num, n.source_markdown_slug IS NOT DISTINCT FROM o.source_markdown_slug AS same_page+ FROM facts n, facts o WHERE n.id = $1 AND o.id = $2`, [newId, oldId]);+ const rowNum = replacement?.same_page && replacement.row_num !== null ? Number(replacement.row_num) : null;+ await forgetFactInFence(engine, oldId, { supersededBy: { rowNum } });} catch {/* best-effort */}diff --git a/src/core/import-file.ts b/src/core/import-file.tsindex c7ededb64c..e5772783d2 100644--- a/src/core/import-file.ts+++ b/src/core/import-file.ts@@ -616,8 +616,8 @@ export async function importFromContent(parsed.timeline = mergeHiddenFactRowsIntoBody(slug, parsed.timeline, existing.timeline);}const { assertPreparedFactWithdrawals, preserveWithdrawnFenceRows } = await import('./facts/withdrawal.ts');- parsed.compiled_truth = await preserveWithdrawnFenceRows(engine, sourceId ?? 'default', parsed.compiled_truth);- parsed.timeline = await preserveWithdrawnFenceRows(engine, sourceId ?? 'default', parsed.timeline);+ parsed.compiled_truth = await preserveWithdrawnFenceRows(engine, sourceId ?? 'default', parsed.compiled_truth, slug);+ parsed.timeline = await preserveWithdrawnFenceRows(engine, sourceId ?? 'default', parsed.timeline, slug);// #1035: absence of an explicit frontmatter `type:` on an EXISTING page// means "preserve the stored type", not "re-infer". Pre-fix, a round-trip@@ -883,7 +883,7 @@ export async function importFromContent(let persistedProjection: ProjectionSnapshot | null = null;const applyPrepared = async (tx: BrainEngine) => {await assertImportBase(tx, slug, txOpts.sourceId, existing);- await assertPreparedFactWithdrawals(tx, txOpts.sourceId, parsed.compiled_truth, parsed.timeline || '');+ await assertPreparedFactWithdrawals(tx, txOpts.sourceId, parsed.compiled_truth, parsed.timeline || '', slug);if (existing) await tx.createVersion(slug, txOpts);// v0.29.1 — compute effective_date from frontmatter precedence chain.@@ -1044,7 +1044,7 @@ export async function importFromContent(slug, parsedPage, observedRevision: (existing as (typeof existing & { knowledge_revision?: string }) | null)?.knowledge_revision ?? null,noop: false, result: { slug, status: 'imported', chunks: chunks.length, parsedPage,...(pageQuarantined ? { quarantined: true } : {}), ...(pageFlagged ? { flagged: true, flag_reason: pageFlagReason } : {}) },- validate: tx => assertPreparedFactWithdrawals(tx, txOpts.sourceId, parsed.compiled_truth, parsed.timeline || ''),+ validate: tx => assertPreparedFactWithdrawals(tx, txOpts.sourceId, parsed.compiled_truth, parsed.timeline || '', slug),apply: applyPrepared,});await engine.transaction(applyPrepared).catch(async (err: unknown) => {diff --git a/src/core/migrate.ts b/src/core/migrate.tsindex 5bea9c6d5b..c72dc19046 100644--- a/src/core/migrate.ts+++ b/src/core/migrate.ts@@ -20,7 +20,7 @@ import { repairTimelineDedupIndex, repairLegacyTimelineSourceRows } from './timeimport { repairPagesUpsertArbiter } from './pages-upsert-arbiter.ts';import { repairLinkSourceCheck, LINK_SOURCE_GATE_MIGRATION_VERSION } from './link-source-check-repair.ts';import { GRANT_COLUMNS_SQL, GRANT_AUDIT_SCHEMA_SQL, GRANT_SPEND_COLUMNS_SQL } from './grants/schema.ts';-import { FACT_WITHDRAWAL_SCHEMA_SQL, FACT_WITHDRAWAL_BACKFILL_SQL } from './facts/withdrawal-schema.ts';+import { FACT_WITHDRAWAL_SCHEMA_SQL, FACT_WITHDRAWAL_BACKFILL_SQL, FACT_WITHDRAWAL_SUBJECT_SQL } from './facts/withdrawal-schema.ts';import { 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';@@ -6668,6 +6668,46 @@ CREATE TRIGGER minion_queue_protocol BEFORE INSERT OR UPDATE ON minion_jobsALTER TABLE facts ADD COLUMN IF NOT EXISTS embedded_text_hash TEXT;${MANAGED_WRITER_GUARD_SQL}`,},+ {+ // A legacy DB-only row can name a fence row as its successor. The fence+ // reconcile deletes and reinserts that row, so a NO ACTION reference made+ // the page fail to reconcile on every cycle. The superseded row stays+ // expired; only the pointer to the replaced row clears.+ version: 167,+ name: 'facts_superseded_by_set_null',+ idempotent: true,+ sql: `+ ALTER TABLE facts DROP CONSTRAINT IF EXISTS facts_superseded_by_fkey;+ ALTER TABLE facts ADD CONSTRAINT facts_superseded_by_fkey+ FOREIGN KEY (superseded_by) REFERENCES facts(id) ON DELETE SET NULL NOT VALID;+ ALTER TABLE facts VALIDATE CONSTRAINT facts_superseded_by_fkey;+ `,+ },+ {+ // The only record that a transcript was synthesized was its completed+ // subagent job row, which `jobs prune` deletes after 30 days; the next+ // cycle then paid to synthesize it again. Prune archives the keys here.+ version: 168,+ name: 'dream_synthesis_completions',+ idempotent: true,+ sql: `+ CREATE TABLE IF NOT EXISTS dream_synthesis_completions (+ source_id TEXT NOT NULL,+ idempotency_key TEXT NOT NULL,+ completed_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ PRIMARY KEY (source_id, idempotency_key)+ );+ `,+ },+ {+ // A withdrawal keyed only on the claim text expired and blocked that claim+ // for every entity in the source. New withdrawals carry the forgotten+ // row's subject; existing rows keep the source-wide '*' subject.+ version: 169,+ name: 'fact_withdrawal_subject',+ idempotent: true,+ sql: FACT_WITHDRAWAL_SUBJECT_SQL,+ },];export const LATEST_VERSION = MIGRATIONS.length > 0diff --git a/src/core/minions/queue.ts b/src/core/minions/queue.tsindex 425abbe55a..096845d90e 100644--- a/src/core/minions/queue.ts+++ b/src/core/minions/queue.ts@@ -1266,11 +1266,20 @@ export class MinionQueue {return parseInt(rows[0]?.count ?? '0', 10);}+ // A completed dream synthesis child is the record that its transcript was+ // synthesized. Archive the key before the row goes, or the next cycle+ // pays to synthesize the transcript again.const rows = await this.engine.executeRaw<{ count: string }>(`WITH pruned AS (DELETE FROM minion_jobsWHERE status = ANY($1) AND updated_at < $2- RETURNING id+ RETURNING name, status, data, idempotency_key, finished_at+ ), archived AS (+ INSERT INTO dream_synthesis_completions (source_id, idempotency_key, completed_at)+ SELECT COALESCE(NULLIF(data->>'source_id', ''), 'default'), idempotency_key, COALESCE(finished_at, now())+ FROM pruned+ WHERE name = 'subagent' AND status = 'completed' AND idempotency_key LIKE 'dream:synth%'+ ON CONFLICT DO NOTHING)SELECT count(*)::text as count FROM pruned`,[statuses, olderThan.toISOString()]diff --git a/src/core/ops/connectors.ts b/src/core/ops/connectors.tsindex 594dbd5284..73f8f5a3fb 100644--- a/src/core/ops/connectors.ts+++ b/src/core/ops/connectors.ts@@ -20,8 +20,8 @@ import {authErrorAtKey,autoSyncKey,isTruthy,- lastSyncAtKey,- watermarkKey,+ readConnectorState,+ sourceIdKey,} from '../connectors/config-keys.ts';import { isConnectorProviderName } from '../connectors/registry.ts';import { runConnectorSync } from '../connectors/sync.ts';@@ -48,6 +48,7 @@ const connectors_status: Operation = {const only = typeof p.provider === 'string' ? p.provider : undefined;const providers = connectorProviders.filter((prov) => !only || prov.name === only);const out = [];+ const sourceId = (await ctx.engine.getConfig(sourceIdKey())) || 'default';for (const prov of providers) {const resolved = resolveCredential(prov.name);out.push({@@ -57,9 +58,10 @@ const connectors_status: Operation = {credential: resolved ? { present: true, source: resolved.source, expires_at: resolved.cred.expiresAt ?? null } : { present: false },credential_file_mode: credentialMode(prov.name), // 0o600 expected; null if absentauto_sync: isTruthy(await ctx.engine.getConfig(autoSyncKey(prov.name))),- last_sync_at: (await ctx.engine.getConfig(lastSyncAtKey(prov.name))) || null,+ source_id: sourceId,+ last_sync_at: await readConnectorState(ctx.engine, prov.name, sourceId, 'last_sync_at'),auth_error_at: (await ctx.engine.getConfig(authErrorAtKey(prov.name))) || null,- watermark_iso: (await ctx.engine.getConfig(watermarkKey(prov.name))) || null,+ watermark_iso: await readConnectorState(ctx.engine, prov.name, sourceId, 'watermark_iso'),});}return { providers: out };diff --git a/src/core/page-state/snapshot.ts b/src/core/page-state/snapshot.tsindex 1650adae24..8b612e4c75 100644--- a/src/core/page-state/snapshot.ts+++ b/src/core/page-state/snapshot.ts@@ -43,8 +43,9 @@ export async function readPageSnapshot(query: ReadQuery, slug: string, opts?: Pa(SELECT s.incarnation FROM sources s WHERE s.id=p.source_id) AS source_incarnation,COALESCE((SELECT jsonb_agg(t.tag ORDER BY t.tag) FROM tags t WHERE t.page_id=p.id), '[]'::jsonb) AS snapshot_tags,COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',w.visibility,'fact_hash',w.fact_hash,'withdrawn_at',w.withdrawn_at)- ORDER BY w.visibility,w.fact_hash) FROM fact_withdrawals w WHERE w.source_id=p.source_id- ${opts?.excludePrivate ? "AND w.visibility='world'" : ''}), '[]'::jsonb) AS snapshot_withdrawals,+ ORDER BY w.visibility,w.fact_hash) FROM (SELECT visibility,fact_hash,min(withdrawn_at) AS withdrawn_at+ FROM fact_withdrawals WHERE source_id=p.source_id AND (subject='*' OR subject=p.slug)+ ${opts?.excludePrivate ? "AND visibility='world'" : ''} GROUP BY visibility,fact_hash) w), '[]'::jsonb) AS snapshot_withdrawals,(SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord)FROM unnest(string_to_array(p.compiled_truth,chr(10))) WITH ORDINALITY AS lines(line,ord)) AS fingerprint_body,(SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord)diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.tsindex 09d7c120af..69a047e9ae 100644--- a/src/core/pglite-engine.ts+++ b/src/core/pglite-engine.ts@@ -139,6 +139,7 @@ import type { PgliteCodeEdgesDeps } from './pglite-engine/code-edges.ts';import * as salienceImpl from './pglite-engine/salience.ts';import type { PgliteSalienceDeps } from './pglite-engine/salience.ts';import { searchKeywordCJK } from './pglite-engine/cjk-search.ts';+import { MOVE_WITHDRAWAL_SUBJECT_SQL } from './facts/withdrawal-schema.ts';/*** #4284 — opt-in out-of-band watchdog for a PGLite disconnect with a live@@ -5805,7 +5806,11 @@ export class PGLiteEngine implements BrainEngine {`UPDATE pages SET slug = $1, updated_at = now() WHERE slug = $2 AND source_id = $3 RETURNING id`,[newSlug, oldSlug, sourceId]);- if (moved.length > 0) await recordRenameAlias(tx, sourceId, oldSlug, newSlug);+ if (moved.length > 0) {+ await recordRenameAlias(tx, sourceId, oldSlug, newSlug);+ // A forgotten claim stays forgotten for the renamed entity.+ await tx.executeRaw(MOVE_WITHDRAWAL_SUBJECT_SQL, [sourceId, oldSlug, newSlug]);+ }// #3056: rows moved — a zero-row UPDATE does not throw, so the count is// the only way callers can see the no-op.return moved.length;diff --git a/src/core/pglite-schema.ts b/src/core/pglite-schema.tsindex 51b11fc8bc..f01f27c0fb 100644--- a/src/core/pglite-schema.ts+++ b/src/core/pglite-schema.ts@@ -1280,6 +1280,13 @@ CREATE TABLE IF NOT EXISTS extract_atoms_page_state (CREATE INDEX IF NOT EXISTS extract_atoms_page_state_tombstoned_idxON extract_atoms_page_state (source_incarnation, content_hash, page_id) WHERE tombstoned;CREATE INDEX IF NOT EXISTS extract_atoms_page_state_page_idx ON extract_atoms_page_state (page_id);+-- Durable record that a transcript was synthesized; survives minion_jobs pruning.+CREATE TABLE IF NOT EXISTS dream_synthesis_completions (+ source_id TEXT NOT NULL,+ idempotency_key TEXT NOT NULL,+ completed_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ PRIMARY KEY (source_id, idempotency_key)+);`;diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex af13c271ed..d4a1ca99b6 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -127,6 +127,7 @@ import type { PgSalienceDeps } from './postgres-engine/salience.ts';import { hasCJK } from './cjk.ts';import { searchKeywordCJK as searchKeywordCJKImpl } from './postgres-engine/cjk-search.ts';import type { CjkKeywordCtx } from './search/cjk-keyword-sql.ts';+import { MOVE_WITHDRAWAL_SUBJECT_SQL } from './facts/withdrawal-schema.ts';function escapeSqlStringLiteral(value: string): string {return value.replace(/'/g, "''");@@ -5031,7 +5032,11 @@ export class PostgresEngine implements BrainEngine {`UPDATE pages SET slug = $1, updated_at = now() WHERE slug = $2 AND source_id = $3 RETURNING id`,[newSlug, oldSlug, sourceId],);- if (moved.length > 0) await recordRenameAlias(tx, sourceId, oldSlug, newSlug);+ if (moved.length > 0) {+ await recordRenameAlias(tx, sourceId, oldSlug, newSlug);+ // A forgotten claim stays forgotten for the renamed entity.+ await tx.executeRaw(MOVE_WITHDRAWAL_SUBJECT_SQL, [sourceId, oldSlug, newSlug]);+ }// #3056: rows moved — a zero-row UPDATE does not throw, so the count is// the only way callers can see the no-op.return moved.length;diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.tsindex 854f022272..693f2cc8d3 100644--- a/src/core/schema-embedded.generated.ts+++ b/src/core/schema-embedded.generated.ts@@ -710,9 +710,10 @@ CREATE INDEX IF NOT EXISTS idx_oauth_grant_audit_client ON oauth_grant_audit(cliCREATE TABLE IF NOT EXISTS fact_withdrawals (source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,visibility TEXT NOT NULL CHECK (visibility IN ('private','world')),+ subject TEXT NOT NULL DEFAULT '*',fact_hash TEXT NOT NULL,withdrawn_at TIMESTAMPTZ NOT NULL DEFAULT now(),- PRIMARY KEY (source_id, visibility, fact_hash)+ PRIMARY KEY (source_id, visibility, subject, fact_hash));CREATE TABLE IF NOT EXISTS oauth_tokens (@@ -1691,6 +1692,13 @@ CREATE TABLE IF NOT EXISTS extract_atoms_page_state (CREATE INDEX IF NOT EXISTS extract_atoms_page_state_tombstoned_idxON extract_atoms_page_state (source_incarnation, content_hash, page_id) WHERE tombstoned;CREATE INDEX IF NOT EXISTS extract_atoms_page_state_page_idx ON extract_atoms_page_state (page_id);+-- Durable record that a transcript was synthesized; survives minion_jobs pruning.+CREATE TABLE IF NOT EXISTS dream_synthesis_completions (+ source_id TEXT NOT NULL,+ idempotency_key TEXT NOT NULL,+ completed_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ PRIMARY KEY (source_id, idempotency_key)+);ALTER TABLE pages ADD COLUMN IF NOT EXISTS knowledge_revision UUID NOT NULL DEFAULT gen_random_uuid();ALTER TABLE pages ADD COLUMN IF NOT EXISTS text_projection_revision UUID;ALTER TABLE page_versions ADD COLUMN IF NOT EXISTS knowledge_revision UUID;diff --git a/src/core/transcripts/ingest.ts b/src/core/transcripts/ingest.tsindex d00e36fdca..7ff4945e94 100644--- a/src/core/transcripts/ingest.ts+++ b/src/core/transcripts/ingest.ts@@ -36,6 +36,7 @@ import {loadImportRedactionPatterns,redactSession,renderSessionParts,+ type RenderSessionResult,} from './render.ts';export interface IngestActivePack {@@ -283,6 +284,8 @@ export async function runTranscriptsIngest(// title or corrected start date) — raw-data writes and stale-part// reconciliation must follow the page that actually exists, or// every re-run aborts on a nonexistent slug.+ await adoptExistingBaseSlug(engine, opts.sourceId ?? 'default', rendered);+ outcome.baseSlug = rendered.baseSlug;let resolvedBaseSlug = rendered.baseSlug;for (const part of rendered.parts) {try {@@ -454,3 +457,20 @@ export async function runTranscriptsIngest(if (opts.dryRun) result.cleanScan = false; // dry-runs never advance watermarksreturn result;}++/**+ * The slug embeds the title (and start day) for export formats, so a rename+ * renders a new slug for the same session. Import at the slug the session's+ * pages already live at: the content is then an in-place update. At a new+ * slug, the importer's cross-slug identity dedup skipped it as a duplicate+ * and every message added since the last import was silently dropped.+ */+async function adoptExistingBaseSlug(engine: BrainEngine, sourceId: string, rendered: RenderSessionResult): Promise<void> {+ const [existing] = await engine.executeRaw<{ slug: string }>(+ `SELECT slug FROM pages WHERE source_id = $1 AND deleted_at IS NULL AND frontmatter->>'id' = $2 ORDER BY id LIMIT 1`,+ [sourceId, rendered.parts[0].frontmatterId],+ );+ if (!existing || existing.slug === rendered.baseSlug) return;+ rendered.baseSlug = existing.slug;+ for (const part of rendered.parts) part.slug = part.part === 1 ? existing.slug : `${existing.slug}-p${part.part}`;+}diff --git a/src/schema.sql b/src/schema.sqlindex 91c65d0281..a925442f2e 100644--- a/src/schema.sql+++ b/src/schema.sql@@ -706,9 +706,10 @@ CREATE INDEX IF NOT EXISTS idx_oauth_grant_audit_client ON oauth_grant_audit(cliCREATE TABLE IF NOT EXISTS fact_withdrawals (source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,visibility TEXT NOT NULL CHECK (visibility IN ('private','world')),+ subject TEXT NOT NULL DEFAULT '*',fact_hash TEXT NOT NULL,withdrawn_at TIMESTAMPTZ NOT NULL DEFAULT now(),- PRIMARY KEY (source_id, visibility, fact_hash)+ PRIMARY KEY (source_id, visibility, subject, fact_hash));CREATE TABLE IF NOT EXISTS oauth_tokens (@@ -1687,6 +1688,13 @@ CREATE TABLE IF NOT EXISTS extract_atoms_page_state (CREATE INDEX IF NOT EXISTS extract_atoms_page_state_tombstoned_idxON extract_atoms_page_state (source_incarnation, content_hash, page_id) WHERE tombstoned;CREATE INDEX IF NOT EXISTS extract_atoms_page_state_page_idx ON extract_atoms_page_state (page_id);+-- Durable record that a transcript was synthesized; survives minion_jobs pruning.+CREATE TABLE IF NOT EXISTS dream_synthesis_completions (+ source_id TEXT NOT NULL,+ idempotency_key TEXT NOT NULL,+ completed_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ PRIMARY KEY (source_id, idempotency_key)+);ALTER TABLE pages ADD COLUMN IF NOT EXISTS knowledge_revision UUID NOT NULL DEFAULT gen_random_uuid();ALTER TABLE pages ADD COLUMN IF NOT EXISTS text_projection_revision UUID;ALTER TABLE page_versions ADD COLUMN IF NOT EXISTS knowledge_revision UUID;diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.mdindex 82347903c3..1fa25f847c 100644--- a/templates/bootstrap/template-repo/README.md+++ b/templates/bootstrap/template-repo/README.md@@ -1,6 +1,6 @@# gbrain agent workspace — template-<!-- gbrain-template-stamp: 0.59.13.0 -->+<!-- gbrain-template-stamp: 0.59.17.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/connectors-config-keys.test.ts b/test/connectors-config-keys.test.tsindex 91f294dd46..39bf8db70c 100644--- a/test/connectors-config-keys.test.ts+++ b/test/connectors-config-keys.test.ts@@ -33,8 +33,9 @@ describe('isTruthy', () => {});describe('key builders', () => {- test('per-provider keys are namespaced', () => {+ test('per-provider keys are namespaced; sync progress is per (provider, source)', () => {expect(autoSyncKey('chatgpt')).toBe('connectors.chatgpt.auto_sync');- expect(watermarkKey('claude')).toBe('connectors.claude.watermark_iso');+ expect(watermarkKey('claude', 'default')).toBe('connectors.claude.source.default.watermark_iso');+ expect(watermarkKey('claude', 'work')).toBe('connectors.claude.source.work.watermark_iso');});});diff --git a/test/cycle-synthesize-daily-cap.test.ts b/test/cycle-synthesize-daily-cap.test.tsindex c587251340..d033bacf03 100644--- a/test/cycle-synthesize-daily-cap.test.ts+++ b/test/cycle-synthesize-daily-cap.test.ts@@ -422,3 +422,30 @@ describe('daily cap — engaged', () => {}}, 60_000);});++describe('synthesis completion survives job pruning', () => {+ test('`jobs prune` of an old completed synth-v2 child does not make the transcript eligible again', async () => {+ const rig = await setupRig();+ try {+ const done = await seedPassingFile(rig, '2026-07-01-pruned.txt');+ const content = `conversation in 2026-07-01-pruned.txt\n`.repeat(200);+ const hash16 = createHash('sha256').update(content, 'utf8').digest('hex').slice(0, 16);+ await rig.engine.executeRaw(+ `INSERT INTO minion_jobs (submission_authority, name, queue, status, data, idempotency_key, created_at, finished_at, updated_at)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'subagent', 'dream-inline-old-run', 'completed', '{"source_id":"default"}'::jsonb, $1,+ now() - interval '40 days', now() - interval '40 days', now() - interval '40 days')`,+ [`dream:synth-v2:default:filename:2026-07-01-pruned.txt:${hash16}`],+ );+ const { MinionQueue } = await import('../src/core/minions/queue.ts');+ expect(await new MinionQueue(rig.engine).prune()).toBe(1);+ const left = await rig.engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM minion_jobs WHERE name='subagent'`);+ expect(left[0].n).toBe(0);++ const details = await runPhase(rig);+ expect(details.skips.find(s => s.filePath === done)?.reason).toBe('already_synthesized_v2_single_chunk');+ expect(details.children_submitted).toBe(0);+ } finally {+ await rig.cleanup();+ }+ }, 60_000);+});diff --git a/test/cycle/synthesize-concepts-human-owned.test.ts b/test/cycle/synthesize-concepts-human-owned.test.tsnew file mode 100644index 0000000000..cfc12cce8d--- /dev/null+++ b/test/cycle/synthesize-concepts-human-owned.test.ts@@ -0,0 +1,78 @@+// synthesize_concepts must never overwrite a concept page it did not write.+// A hand-written `concepts/<x>` page that atoms happen to reference keeps its+// body; the phase records the skip and spends nothing on it.++import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { runPhaseSynthesizeConcepts } from '../../src/core/cycle/synthesize-concepts.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import { resetPgliteState } from '../helpers/reset-pglite.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 240000);++afterAll(async () => {+ await engine.disconnect();+});++beforeEach(async () => {+ await resetPgliteState(engine);+}, 120000);++const atoms = [+ { slug: 'atoms/a1', title: 'A1', body: 'b1', concept_refs: ['flywheel', 'theme'] },+ { slug: 'atoms/a2', title: 'A2', body: 'b2', concept_refs: ['flywheel', 'theme'] },+];++async function persistAtoms(): Promise<void> {+ for (const a of atoms) {+ await engine.putPage(a.slug, { type: 'atom', title: a.title, compiled_truth: a.body, timeline: '' });+ }+}++describe('synthesize_concepts human-owned pages', () => {+ test('a hand-written concept page is left untouched; synthesized pages still refresh', async () => {+ await persistAtoms();+ const human = 'HUMAN-AUTHORED: a long hand-written essay on the flywheel.';+ await importFromContent(engine, 'concepts/flywheel',+ `---\ntype: concept\ntitle: Flywheel\n---\n\n${human}\n`, { noEmbed: true, sourceId: 'default' });++ const first = await runPhaseSynthesizeConcepts(engine, { _atoms: atoms, sourceId: 'default' });++ const flywheel = await engine.getPage('concepts/flywheel', { sourceId: 'default' });+ expect(flywheel?.compiled_truth.trim()).toBe(human);+ expect(flywheel?.frontmatter.synthesized_by).toBeUndefined();+ expect((first.details as Record<string, unknown>).skipped_human_owned).toEqual(['concepts/flywheel']);++ const theme = await engine.getPage('concepts/theme', { sourceId: 'default' });+ expect(String(theme?.frontmatter.synthesized_by)).toMatch(/^synthesize_concepts/);++ // The phase's own page is still eligible for a refresh on the next run.+ const second = await runPhaseSynthesizeConcepts(engine, { _atoms: atoms, sourceId: 'default' });+ expect((second.details as Record<string, unknown>).skipped_human_owned).toEqual(['concepts/flywheel']);+ expect((second.details as Record<string, unknown>).concepts_written).toBe(1);+ }, 120000);++ test('the ownership check runs before any LLM spend', async () => {+ await persistAtoms();+ await importFromContent(engine, 'concepts/flywheel',+ `---\ntype: concept\ntitle: Flywheel\n---\n\nHand-written.\n`, { noEmbed: true, sourceId: 'default' });+ await importFromContent(engine, 'concepts/theme',+ `---\ntype: concept\ntitle: Theme\n---\n\nHand-written too.\n`, { noEmbed: true, sourceId: 'default' });+ const many = Array.from({ length: 12 }, (_, i) => ({ slug: `atoms/m${i}`, title: `M${i}`, body: `m${i}`, concept_refs: ['flywheel', 'theme'] }));+ let calls = 0;+ const result = await runPhaseSynthesizeConcepts(engine, {+ _atoms: many,+ sourceId: 'default',+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ _chat: (async () => { calls++; throw new Error('must not be called'); }) as any,+ });+ expect(calls).toBe(0);+ expect((result.details as Record<string, unknown>).concepts_written).toBe(0);+ }, 120000);+});diff --git a/test/e2e/connectors-sync-checkpoints-pglite.test.ts b/test/e2e/connectors-sync-checkpoints-pglite.test.tsnew file mode 100644index 0000000000..59e6fcfef0--- /dev/null+++ b/test/e2e/connectors-sync-checkpoints-pglite.test.ts@@ -0,0 +1,160 @@+/**+ * connectors-sync checkpoints (PGLite): the watermark and per-conversation+ * sync state are keyed by (provider, source), a capped `--limit` run makes+ * progress across runs, and one permanently failing conversation is+ * quarantined instead of freezing the watermark forever.+ *+ * Real ConnectorClient against the scriptable fixture backend, real ingest,+ * isolated GBRAIN_HOME. No network, no provider spend.+ */+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { resetPgliteState } from '../helpers/reset-pglite.ts';+import { runConnectorSync } from '../../src/core/connectors/sync.ts';+import { saveCredential } from '../../src/core/connectors/credentials.ts';+import { readConnectorState, watermarkKey } from '../../src/core/connectors/config-keys.ts';+import { CHATGPT_BASE_URL } from '../../src/core/connectors/providers/chatgpt.ts';+import {+ type FixtureConversation,+ type FixtureState,+ chatgptHandler,+ newFixtureState,+ startFixture,+} from '../fixtures/connectors/fixture-server.ts';++let engine: PGLiteEngine;+let tmp: string;+let prevHome: string | undefined;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+});+afterAll(async () => {+ await engine.disconnect();+ if (prevHome === undefined) delete process.env.GBRAIN_HOME;+ else process.env.GBRAIN_HOME = prevHome;+});+beforeEach(async () => {+ await resetPgliteState(engine);+ tmp = mkdtempSync(join(tmpdir(), 'gb-connectors-ckpt-'));+ prevHome = process.env.GBRAIN_HOME;+ process.env.GBRAIN_HOME = tmp;+ saveCredential({ provider: 'chatgpt', strategy: 'browser-session', cookie: 'sessionKey=fixture', savedAt: new Date(0).toISOString() });+});+afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++const T0 = 1_786_000_000;+const NOW_MS = (T0 + 100_000) * 1000;++function conv(id: string, updateTime: number, marker = id): FixtureConversation {+ return { id, title: `Title ${id}`, createTime: updateTime - 100, updateTime,+ turns: [{ role: 'user', text: `question ${marker}` }, { role: 'assistant', text: `answer ${marker}` }] };+}++async function run(state: FixtureState, opts: Record<string, unknown> = {}) {+ const srv = startFixture(chatgptHandler(state));+ try {+ return await runConnectorSync(engine, {+ provider: 'chatgpt',+ sourceId: 'default',+ deps: {+ fetchImpl: (url, init) => fetch(url.replace(CHATGPT_BASE_URL, srv.baseUrl), init),+ now: () => NOW_MS,+ sleep: () => Promise.resolve(),+ },+ ...(opts as object),+ });+ } finally {+ srv.stop();+ }+}++async function conversationPages(sourceId: string): Promise<number> {+ const rows = await engine.executeRaw<{ n: number }>(+ `SELECT count(*)::int AS n FROM pages WHERE source_id=$1 AND slug LIKE 'conversations/chatgpt/%' AND deleted_at IS NULL`, [sourceId]);+ return rows[0].n;+}++describe('connector checkpoints', () => {+ test('the watermark is per source: a second source still receives the full history', async () => {+ const state = newFixtureState([conv('old-1', T0 - 30 * 86_400), conv('new-1', T0 + 10)]);+ const first = await run(state, { sourceId: 'default' });+ expect(first.listed).toBe(2);+ await engine.executeRaw(`INSERT INTO sources (id, name) VALUES ('work', 'work') ON CONFLICT DO NOTHING`);++ const second = await run(state, { sourceId: 'work' });++ expect(second.listed).toBe(2);+ expect(await conversationPages('work')).toBe(2);+ expect(await readConnectorState(engine, 'chatgpt', 'work', 'watermark_iso')).toBe(new Date((T0 + 10) * 1000).toISOString());+ expect(await readConnectorState(engine, 'chatgpt', 'default', 'watermark_iso')).toBe(new Date((T0 + 10) * 1000).toISOString());+ });++ test('a legacy per-provider watermark still applies to the scheduled source only', async () => {+ const legacy = new Date((T0 + 5) * 1000).toISOString();+ await engine.setConfig('connectors.chatgpt.watermark_iso', legacy);+ await engine.executeRaw(`INSERT INTO sources (id, name) VALUES ('work', 'work') ON CONFLICT DO NOTHING`);+ expect(await readConnectorState(engine, 'chatgpt', 'default', 'watermark_iso')).toBe(legacy);+ expect(await readConnectorState(engine, 'chatgpt', 'work', 'watermark_iso')).toBeNull();+ });++ test('repeated --limit runs make progress and finish with the watermark advanced', async () => {+ const state = newFixtureState([1, 2, 3, 4, 5].map(i => conv(`c-${i}`, T0 + i * 10)));+ const statuses: string[] = [];+ for (let k = 0; k < 3; k++) statuses.push((await run(state, { limit: 2 })).status);++ expect(await conversationPages('default')).toBe(5);+ for (let i = 1; i <= 5; i++) expect(state.hits[`detail:c-${i}`]).toBe(1);+ expect(statuses).toEqual(['partial', 'partial', 'success']);+ expect(await engine.getConfig(watermarkKey('chatgpt', 'default'))).toBe(new Date((T0 + 50) * 1000).toISOString());+ });++ test('an unchanged conversation is not re-fetched while the watermark is held back', async () => {+ const state = newFixtureState([conv('c-1', T0 + 10), conv('c-2', T0 + 20)]);+ state.script.push({ pathIncludes: '/backend-api/conversation/c-1', status: 404, body: { error: 'gone' } });+ await run(state);+ await run(state);+ expect(state.hits['detail:c-2']).toBe(1);+ });++ test('a permanently failing conversation is quarantined and stops freezing the watermark', async () => {+ const state = newFixtureState([conv('c-1', T0 + 10), conv('c-2', T0 + 20), conv('c-3', T0 + 30)]);+ state.script.push({ pathIncludes: '/backend-api/conversation/c-1', status: 404, body: { error: 'gone' } });+ const results = [];+ for (let k = 0; k < 4; k++) results.push(await run(state));++ expect(results.slice(0, 3).map(r => r.fetchErrors)).toEqual([1, 1, 1]);+ expect(results[2].watermarkAdvancedTo).toBe(new Date((T0 + 30) * 1000).toISOString());+ expect(results[2].quarantined).toEqual(['c-1']);+ expect(results[3].fetched).toBe(0);+ expect(results[3].status).toBe('nothing_new');+ expect(state.hits['detail:c-2']).toBe(1);+ expect(state.hits['detail:c-3']).toBe(1);++ // An edit to the quarantined conversation earns it a fresh attempt.+ state.script = [];+ state.conversations[0] = conv('c-1', T0 + 40, 'edited');+ const retried = await run(state);+ expect(retried.fetched).toBe(1);+ expect(await conversationPages('default')).toBe(3);+ });++ test('a renamed and continued conversation lands its new messages on the existing page', async () => {+ const state = newFixtureState([conv('c-9', T0 + 10)]);+ await run(state);+ state.conversations[0] = { ...conv('c-9', T0 + 500), title: 'Renamed',+ turns: [...conv('c-9', T0 + 500).turns, { role: 'user', text: 'NEWTURN-MARKER' }, { role: 'assistant', text: 'more' }] };+ const second = await run(state);+ expect(second.ingest?.imported).toBe(1);+ const rows = await engine.executeRaw<{ has_new: boolean }>(+ `SELECT compiled_truth LIKE '%NEWTURN-MARKER%' AS has_new FROM pages WHERE slug LIKE 'conversations/chatgpt/%' AND deleted_at IS NULL`);+ expect(rows).toEqual([{ has_new: true }]);+ });+});diff --git a/test/e2e/connectors-sync-pglite.test.ts b/test/e2e/connectors-sync-pglite.test.tsindex 3534b42f94..21a6a63a26 100644--- a/test/e2e/connectors-sync-pglite.test.ts+++ b/test/e2e/connectors-sync-pglite.test.ts@@ -160,13 +160,13 @@ describe('B. incremental + watermark', () => {const state = newFixtureState([conv('c-1', 'A', T0 + 10, [{ role: 'user', text: 'hi' }, { role: 'assistant', text: 'hello' }])]);const r1 = await runChatgpt(state, { windowDays: 0 });expect(r1.ingest?.imported).toBe(1);- const wm1 = await engine.getConfig(watermarkKey('chatgpt'));+ const wm1 = await engine.getConfig(watermarkKey('chatgpt', 'default'));expect(wm1).toBe(new Date((T0 + 10) * 1000).toISOString());state.hits = {}; // reset counters between runsconst r2 = await runChatgpt(state, { windowDays: 0 });expect(r2.status).toBe('nothing_new');expect(state.hits.detail ?? 0).toBe(0); // windowDays:0 → boundary conv excluded, nothing re-fetched- expect(await engine.getConfig(watermarkKey('chatgpt'))).toBe(wm1);+ expect(await engine.getConfig(watermarkKey('chatgpt', 'default'))).toBe(wm1);});test('B5 only the new conversation is detail-fetched; watermark advances (windowDays:0)', async () => {@@ -179,7 +179,7 @@ describe('B. incremental + watermark', () => {expect(state.hits['detail:c-2']).toBe(1);expect(state.hits['detail:c-1'] ?? 0).toBe(0); // old one excluded (windowDays:0)expect(r.ingest?.imported).toBe(1);- expect(await engine.getConfig(watermarkKey('chatgpt'))).toBe(new Date((T0 + 500) * 1000).toISOString());+ expect(await engine.getConfig(watermarkKey('chatgpt', 'default'))).toBe(new Date((T0 + 500) * 1000).toISOString());});test('B6 >30-day gap survives: next run is incremental, not a full history re-fetch', async () => {@@ -194,7 +194,7 @@ describe('B. incremental + watermark', () => {}const state = newFixtureState(oldConvs);await runChatgpt(state, { full: true });- expect(await engine.getConfig(watermarkKey('chatgpt'))).toBeTruthy();+ expect(await engine.getConfig(watermarkKey('chatgpt', 'default'))).toBeTruthy();state.hits = {};// A single new conv arrives well after the newest old one.state.conversations.push(conv('new-1', 'new', T0, [{ role: 'user', text: 'nq' }, { role: 'assistant', text: 'na' }]));@@ -233,12 +233,12 @@ describe('B. incremental + watermark', () => {const r = await runChatgpt(state);expect(r.status).toBe('partial');expect(r.fetchErrors).toBe(1);- expect(await engine.getConfig(watermarkKey('chatgpt'))).toBeNull(); // never advanced+ expect(await engine.getConfig(watermarkKey('chatgpt', 'default'))).toBeNull(); // never advanced// Clear the script; a clean re-run imports both and advances.state.script = [];const r2 = await runChatgpt(state);expect(r2.fetchErrors).toBe(0);- expect(await engine.getConfig(watermarkKey('chatgpt'))).toBe(new Date((T0 + 20) * 1000).toISOString());+ expect(await engine.getConfig(watermarkKey('chatgpt', 'default'))).toBe(new Date((T0 + 20) * 1000).toISOString());});});@@ -344,7 +344,7 @@ describe('G. client behavior', () => {const r = await runChatgpt(state);expect(r.status).toBe('auth_required');expect(await engine.getConfig(authErrorAtKey('chatgpt'))).toBeTruthy();- expect(await engine.getConfig(watermarkKey('chatgpt'))).toBeNull();+ expect(await engine.getConfig(watermarkKey('chatgpt', 'default'))).toBeNull();});test('G28 403 + Cloudflare HTML → forbidden (no JSON-parse crash)', async () => {@@ -379,7 +379,7 @@ describe('K. dry-run / limit / receipt / spool', () => {expect(r.status).toBe('dry_run');expect(state.hits.detail ?? 0).toBe(0);expect(await engine.listPages({ type: 'conversation', sourceId: 'default', limit: 10 })).toHaveLength(0);- expect(await engine.getConfig(watermarkKey('chatgpt'))).toBeNull();+ expect(await engine.getConfig(watermarkKey('chatgpt', 'default'))).toBeNull();});test('K45 --limit N imports N and does NOT advance the watermark (not clean)', async () => {@@ -392,7 +392,7 @@ describe('K. dry-run / limit / receipt / spool', () => {const r = await runChatgpt(state, { limit: 2 });expect(r.fetched).toBe(2);expect(r.status).toBe('partial'); // cap ⇒ not clean- expect(await engine.getConfig(watermarkKey('chatgpt'))).toBeNull();+ expect(await engine.getConfig(watermarkKey('chatgpt', 'default'))).toBeNull();});test('K46 the run writes a connector ingest_log receipt', async () => {@@ -409,7 +409,7 @@ describe('K. dry-run / limit / receipt / spool', () => {saveChatgptCookie();const state = newFixtureState([conv('c-1', 'A', T0 + 10, [{ role: 'user', text: 'q1' }, { role: 'assistant', text: 'a1' }])]);await runChatgpt(state);- expect(await engine.getConfig(lastSyncAtKey('chatgpt'))).toBeTruthy();+ expect(await engine.getConfig(lastSyncAtKey('chatgpt', 'default'))).toBeTruthy();// spool dir should be empty (pruned in finally)const spoolPath = join(tmp, '.gbrain', 'connectors', 'spool', 'chatgpt');let entries: string[] = [];diff --git a/test/e2e/doctor-connectors-pglite.test.ts b/test/e2e/doctor-connectors-pglite.test.tsindex dfd46e547b..5a8d9306e7 100644--- a/test/e2e/doctor-connectors-pglite.test.ts+++ b/test/e2e/doctor-connectors-pglite.test.ts@@ -48,7 +48,7 @@ describe('connectorsHealthCheck', () => {test('credential present, manual lane (auto_sync off), fresh → ok (never nags on staleness)', async () => {saveCred('2026-08-25T00:00:00.000Z');// auto_sync unset, last_sync_at ancient → still OK because manual lane isn't gated on staleness.- await engine.setConfig(lastSyncAtKey('chatgpt'), '2000-01-01T00:00:00.000Z');+ await engine.setConfig(lastSyncAtKey('chatgpt', 'default'), '2000-01-01T00:00:00.000Z');const c = await connectorsHealthCheck(engine);expect(c.status).toBe('ok');});@@ -71,7 +71,7 @@ describe('connectorsHealthCheck', () => {test('auto_sync on + stale last_sync → warn: stalled', async () => {saveCred('2026-08-25T00:00:00.000Z');await engine.setConfig(autoSyncKey('chatgpt'), 'true');- await engine.setConfig(lastSyncAtKey('chatgpt'), '2000-01-01T00:00:00.000Z');+ await engine.setConfig(lastSyncAtKey('chatgpt', 'default'), '2000-01-01T00:00:00.000Z');const c = await connectorsHealthCheck(engine);expect(c.status).toBe('warn');expect(c.message).toMatch(/stall/i);diff --git a/test/extract-facts-phase.test.ts b/test/extract-facts-phase.test.tsindex 73459014d6..c8326fdabd 100644--- a/test/extract-facts-phase.test.ts+++ b/test/extract-facts-phase.test.ts@@ -1680,7 +1680,11 @@ describe('runExtractFacts — v0.46 (#3014) supersession transport + heal', () =// eslint-disable-next-line @typescript-eslint/no-explicit-any(engine as any).insertFacts = async () => { throw new Error('simulated insert failure'); };try {- await expect(runExtractFacts(engine, { slugs: ['people/deal'] })).rejects.toThrow('simulated insert failure');+ // The failure is isolated to this page and reported, not thrown out of+ // the phase (a thrown error aborted every later page).+ const result = await runExtractFacts(engine, { slugs: ['people/deal'] });+ expect(result.pagesFailed).toBe(1);+ expect(result.warnings).toContain('people/deal: FACTS_RECONCILE_FAILED: simulated insert failure');} finally {// eslint-disable-next-line @typescript-eslint/no-explicit-any(engine as any).insertFacts = original;diff --git a/test/extract-facts-poison-page.test.ts b/test/extract-facts-poison-page.test.tsnew file mode 100644index 0000000000..eb939f12ac--- /dev/null+++ b/test/extract-facts-poison-page.test.ts@@ -0,0 +1,106 @@+/**+ * extract_facts isolates each page's reconcile: one page whose fence rows the+ * database rejects must not abort reconciliation for every later page (the+ * "poison page"). Real PGLite, no provider calls.+ */++import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { runExtractFacts } from '../src/core/cycle/extract-facts.ts';+import { parseFactsFence } from '../src/core/facts-fence.ts';++let engine: PGLiteEngine;++const fence = (rows: string) => `# Page++Body.++## Facts++<!--- gbrain:facts:begin -->+| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |+|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|+${rows}+<!--- gbrain:facts:end -->+`;++async function putPage(slug: string, body: string): Promise<void> {+ await engine.putPage(slug, { title: slug, type: 'person', compiled_truth: body, frontmatter: {}, timeline: '' });+}++async function fenceRowCount(slug: string): Promise<number> {+ const rows = await engine.executeRaw<{ n: number }>(+ `SELECT count(*)::int AS n FROM facts WHERE source_markdown_slug=$1 AND source_id='default'`, [slug]);+ return rows[0].n;+}++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+});++afterAll(async () => {+ await engine.disconnect();+});++beforeEach(async () => {+ await engine.executeRaw('UPDATE facts SET superseded_by=NULL');+ await engine.executeRaw('DELETE FROM facts');+ await engine.executeRaw('DELETE FROM pages');+});++describe('extract_facts poison-page isolation', () => {+ test('an out-of-range fence confidence is a parse warning, not a database error', () => {+ const parsed = parseFactsFence(fence('| 1 | Likes tea | fact | 7 | world | medium | 2026-01-01 | | chat | |'));+ expect(parsed.facts).toHaveLength(0);+ expect(parsed.warnings.some(w => w.includes('confidence "7"') && w.includes('0..1'))).toBe(true);+ });++ test('a page whose insert violates a constraint does not stop later pages from reconciling', async () => {+ await putPage('people/aaa-poison-example', fence('| 1 | Likes tea | fact | 1.0 | world | medium | 2026-01-01 | | chat | |'));+ await putPage('people/zzz-healthy-example', fence('| 1 | Prefers email | preference | 1.0 | world | medium | 2026-01-01 | | chat | |'));+ // Reject every insert for the poison page only, the way a CHECK or FK+ // violation would, without depending on which malformed input the parser+ // currently tolerates.+ await engine.executeRaw(`CREATE OR REPLACE FUNCTION test_reject_poison() RETURNS trigger LANGUAGE plpgsql AS $fn$+ BEGIN+ IF NEW.source_markdown_slug = 'people/aaa-poison-example' THEN RAISE EXCEPTION 'poison row rejected'; END IF;+ RETURN NEW;+ END $fn$`);+ await engine.executeRaw('CREATE TRIGGER test_reject_poison BEFORE INSERT ON facts FOR EACH ROW EXECUTE FUNCTION test_reject_poison()');+ try {+ const result = await runExtractFacts(engine, { slugs: ['people/aaa-poison-example', 'people/zzz-healthy-example'] });+ expect(await fenceRowCount('people/zzz-healthy-example')).toBe(1);+ expect(await fenceRowCount('people/aaa-poison-example')).toBe(0);+ expect(result.warnings.some(w => w.startsWith('people/aaa-poison-example: FACTS_RECONCILE_FAILED') && w.includes('poison row rejected'))).toBe(true);+ expect(result.pagesFailed).toBe(1);+ } finally {+ await engine.executeRaw('DROP TRIGGER IF EXISTS test_reject_poison ON facts');+ }+ });++ test('a DB-only row superseded by a fence row does not block that page from re-reconciling', async () => {+ const slug = 'people/alice-example';+ await putPage(slug, fence('| 1 | CEO of acme-example | fact | 1.0 | world | medium | 2026-01-01 | | chat | |'));+ await putPage('people/bob-example', fence('| 1 | Likes tea | fact | 1.0 | world | medium | 2026-01-01 | | chat | |'));+ await runExtractFacts(engine, { slugs: [slug] });+ const [fenceRow] = await engine.executeRaw<{ id: number }>(`SELECT id FROM facts WHERE source_markdown_slug=$1`, [slug]);+ // A DB-only legacy row that a later remember superseded with the fence row.+ const [legacy] = await engine.executeRaw<{ id: number }>(+ `INSERT INTO facts(source_id, entity_slug, fact, kind, visibility, source, expired_at, superseded_by)+ VALUES ('default', $1, 'COO of acme-example', 'fact', 'world', 'chat', now(), $2) RETURNING id`, [slug, fenceRow.id]);+ // Attribute drift forces the wipe-and-reinsert path for alice's page.+ await putPage(slug, fence('| 1 | CEO of acme-example | fact | 1.0 | world | high | 2026-01-01 | | chat | |'));++ const result = await runExtractFacts(engine, { slugs: [slug, 'people/bob-example'] });++ expect(result.warnings.filter(w => w.includes('FACTS_RECONCILE_FAILED'))).toEqual([]);+ expect(await fenceRowCount('people/bob-example')).toBe(1);+ const alice = await engine.executeRaw<{ notability: string }>(`SELECT notability FROM facts WHERE source_markdown_slug=$1`, [slug]);+ expect(alice.map(r => r.notability)).toEqual(['high']);+ const [kept] = await engine.executeRaw<{ expired: boolean }>(+ `SELECT expired_at IS NOT NULL AS expired FROM facts WHERE id=$1`, [legacy.id]);+ expect(kept.expired).toBe(true);+ });+});diff --git a/test/facts-supersede-not-withdrawal.test.ts b/test/facts-supersede-not-withdrawal.test.tsnew file mode 100644index 0000000000..802af5db05--- /dev/null+++ b/test/facts-supersede-not-withdrawal.test.ts@@ -0,0 +1,94 @@+/**+ * An ordinary supersession ("works at acme-example" → "left acme-example")+ * is an update, not a withdrawal. On the fence path it used to route through+ * forget: a durable withdrawal that blocked the old claim forever and, as a+ * side effect, invalidated every page in the source. Gmail commitment+ * extraction hits this path on every changed due date.+ *+ * Real PGLite; the embedding transport is a deterministic in-process stub.+ */+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+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 { importFromContent } from '../src/core/import-file.ts';+import { writeSingleFact } from '../src/core/facts/write-single.ts';+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';++let engine: PGLiteEngine;+let brainDir: string;+const SLUG = 'people/alice-example';+const DIM = 1536;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 120000);++afterAll(async () => {+ await engine.disconnect();+});++beforeEach(async () => {+ await resetPgliteState(engine);+ brainDir = mkdtempSync(join(tmpdir(), 'supersede-'));+ await engine.executeRaw(`UPDATE sources SET local_path = $1 WHERE id = 'default'`, [brainDir]);+ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: DIM, env: { OPENAI_API_KEY: 'sk-test-deterministic' } });+ __setEmbedTransportForTests((async (opts: { values: string[] }) => ({+ embeddings: opts.values.map(t => {+ const v = new Array(DIM).fill(0);+ if (t.includes('SUPERSEDE-PAIR')) v[0] = 1;+ else for (let i = 0; i < 16; i++) v[i] = ((t.charCodeAt(i % t.length) % 13) + 1) / 13;+ return v;+ }),+ })) as never);+ for (const [slug, title] of [[SLUG, 'Alice Example'], ['companies/acme-example', 'Acme Example']]) {+ const content = `---\ntitle: ${title}\ntype: ${slug.startsWith('people') ? 'person' : 'company'}\n---\n# ${title}\n\nSearchable body about ${title}.\n`;+ mkdirSync(join(brainDir, slug.split('/')[0]), { recursive: true });+ writeFileSync(join(brainDir, `${slug}.md`), content);+ await importFromContent(engine, slug, content, { noEmbed: true, sourceId: 'default' });+ }+});++afterEach(() => {+ __setEmbedTransportForTests(null);+ resetGateway();+ rmSync(brainDir, { recursive: true, force: true });+});++async function chunkCount(slug: string): Promise<number> {+ const rows = await engine.executeRaw<{ n: number }>(+ `SELECT count(c.id)::int AS n FROM pages p LEFT JOIN content_chunks c ON c.page_id=p.id WHERE p.slug=$1`, [slug]);+ return rows[0].n;+}++describe('fence-path supersession', () => {+ test('supersedes without recording a withdrawal or touching unrelated pages', async () => {+ const first = await writeSingleFact(engine, 'default', { fact: 'SUPERSEDE-PAIR works at acme-example', provenance: 'test', entity: SLUG, kind: 'fact', visibility: 'world' });+ expect(first.status).toBe('inserted');+ const unrelatedChunks = await chunkCount('companies/acme-example');+ expect(unrelatedChunks).toBeGreaterThan(0);++ const second = await writeSingleFact(engine, 'default', { fact: 'SUPERSEDE-PAIR left acme-example', provenance: 'test', entity: SLUG, kind: 'fact', visibility: 'world' });++ expect(second.status).toBe('superseded');+ expect(await engine.executeRaw('SELECT * FROM fact_withdrawals')).toEqual([]);+ const [old] = await engine.executeRaw<{ expired: boolean; superseded_by: number | null }>(+ `SELECT expired_at IS NOT NULL AS expired, superseded_by FROM facts WHERE id=$1`, [first.id]);+ expect(old).toEqual({ expired: true, superseded_by: second.id });+ const file = readFileSync(join(brainDir, `${SLUG}.md`), 'utf-8');+ expect(file).toMatch(/~~SUPERSEDE-PAIR works at acme-example~~[^\n]*superseded by #2/);+ expect(file).not.toContain('forgotten:');+ expect(await chunkCount('companies/acme-example')).toBe(unrelatedChunks);+ });++ test('the superseded claim can be remembered again later', async () => {+ await writeSingleFact(engine, 'default', { fact: 'SUPERSEDE-PAIR works at acme-example', provenance: 'test', entity: SLUG, kind: 'fact', visibility: 'world' });+ await writeSingleFact(engine, 'default', { fact: 'SUPERSEDE-PAIR left acme-example', provenance: 'test', entity: SLUG, kind: 'fact', visibility: 'world' });+ const back = await writeSingleFact(engine, 'default', { fact: 'SUPERSEDE-PAIR works at acme-example', provenance: 'test', entity: SLUG, kind: 'fact', visibility: 'world' });+ expect(['inserted', 'superseded']).toContain(back.status);+ });+});diff --git a/test/facts-withdrawal-subject.test.ts b/test/facts-withdrawal-subject.test.tsnew file mode 100644index 0000000000..b5df40ddb2--- /dev/null+++ b/test/facts-withdrawal-subject.test.ts@@ -0,0 +1,134 @@+/**+ * A withdrawal is scoped to the entity whose fact was forgotten. Forgetting+ * one person's "Prefers email" must not expire, strike or block the same+ * claim about anyone else, while it still survives reimport, re-extraction+ * and a rename of the forgotten entity's page. Real PGLite, no provider calls.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+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 { runExtractFacts } from '../src/core/cycle/extract-facts.ts';+import { forgetFactInFence } from '../src/core/facts/forget.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { isFactWithdrawn } from '../src/core/facts/withdrawal.ts';+import { readExportPage, readExportWithdrawals } from '../src/core/export-snapshot.ts';++let engine: PGLiteEngine;+let brainDir: string;++const page = (title: string, rows: string) => `---+title: ${title}+type: person+---+# ${title}++Some body text about ${title}.++## Facts++<!--- gbrain:facts:begin -->+| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |+|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|+${rows}+<!--- gbrain:facts:end -->+`;+const EMAIL_ROW = '| 1 | Prefers email | preference | 1.0 | world | medium | 2026-01-01 | | chat | |';++async function put(slug: string, content: string): Promise<void> {+ mkdirSync(join(brainDir, slug.split('/')[0]), { recursive: true });+ writeFileSync(join(brainDir, `${slug}.md`), content, 'utf-8');+ await importFromContent(engine, slug, content, { noEmbed: true, sourceId: 'default' });+}++async function activeFacts(): Promise<Array<{ entity_slug: string; expired: boolean }>> {+ return engine.executeRaw(`SELECT entity_slug, expired_at IS NOT NULL AS expired FROM facts+ WHERE fact='Prefers email' ORDER BY entity_slug`);+}++async function forgetAlice(): Promise<void> {+ const [alice] = await engine.executeRaw<{ id: number }>(`SELECT id FROM facts WHERE entity_slug='people/alice-example'`);+ const result = await forgetFactInFence(engine, Number(alice.id), { reason: 'alice asked' });+ expect(result.ok).toBe(true);+}++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ brainDir = mkdtempSync(join(tmpdir(), 'withdrawal-subject-'));+ await engine.executeRaw(`UPDATE sources SET local_path = $1 WHERE id = 'default'`, [brainDir]);+}, 120000);++afterAll(async () => {+ await engine.disconnect();+ rmSync(brainDir, { recursive: true, force: true });+});++beforeEach(async () => {+ await engine.executeRaw('DELETE FROM fact_withdrawals');+ await engine.executeRaw('UPDATE facts SET superseded_by=NULL');+ await engine.executeRaw('DELETE FROM facts');+ await engine.executeRaw('DELETE FROM content_chunks');+ await engine.executeRaw('DELETE FROM pages');+ await put('people/alice-example', page('Alice Example', EMAIL_ROW));+ await put('people/bob-example', page('Bob Example', EMAIL_ROW));+ await runExtractFacts(engine, { slugs: ['people/alice-example', 'people/bob-example'] });+});++describe('subject-scoped withdrawal', () => {+ test('forgetting one entity\'s claim leaves the same claim about another entity active', async () => {+ await forgetAlice();+ expect(await activeFacts()).toEqual([+ { entity_slug: 'people/alice-example', expired: true },+ { entity_slug: 'people/bob-example', expired: false },+ ]);+ });++ test('the claim stays rememberable for other entities and blocked for the forgotten one', async () => {+ await forgetAlice();+ expect(await isFactWithdrawn(engine, 'default', 'world', 'prefers EMAIL', 'people/alice-example')).toBe(true);+ expect(await isFactWithdrawn(engine, 'default', 'world', 'Prefers email', 'people/charlie-example')).toBe(false);+ expect(await isFactWithdrawn(engine, 'default', 'world', 'Prefers email', null)).toBe(false);+ });++ test('reimport and re-extraction keep the other entity\'s row active and its fence unstruck', async () => {+ await forgetAlice();+ const bobFile = readFileSync(join(brainDir, 'people/bob-example.md'), 'utf-8');+ await engine.executeRaw(`UPDATE pages SET content_hash='stale' WHERE slug='people/bob-example'`);+ await importFromContent(engine, 'people/bob-example', bobFile, { noEmbed: true, sourceId: 'default' });+ await runExtractFacts(engine, { slugs: ['people/alice-example', 'people/bob-example'] });++ const bob = await engine.getPage('people/bob-example', { sourceId: 'default' });+ expect(bob?.compiled_truth).toContain('| Prefers email |');+ expect(bob?.compiled_truth).not.toContain('forgotten:');+ expect((await activeFacts()).find(r => r.entity_slug === 'people/bob-example')?.expired).toBe(false);+ expect((await activeFacts()).find(r => r.entity_slug === 'people/alice-example')?.expired).toBe(true);+ });++ test('Markdown export strikes the claim only on the forgotten entity\'s page', async () => {+ await forgetAlice();+ const withdrawals = await readExportWithdrawals(engine, 'default');+ const exported = async (slug: string) => {+ const [row] = await engine.executeRaw<{ id: string }>(`SELECT id::text AS id FROM pages WHERE slug=$1`, [slug]);+ return (await readExportPage(engine, { id: row.id, source_id: 'default', slug }, withdrawals)).page.compiled_truth;+ };+ expect(await exported('people/alice-example')).toContain('~~Prefers email~~');+ expect(await exported('people/bob-example')).not.toContain('~~Prefers email~~');+ });++ test('the withdrawal follows a rename of the forgotten entity\'s page', async () => {+ await forgetAlice();+ expect(await engine.updateSlug('people/alice-example', 'people/alice-renamed-example', { sourceId: 'default' })).toBe(1);+ expect(await isFactWithdrawn(engine, 'default', 'world', 'Prefers email', 'people/alice-renamed-example')).toBe(true);+ expect(await isFactWithdrawn(engine, 'default', 'world', 'Prefers email', 'people/alice-example')).toBe(false);+ });++ test('a withdrawal recorded before subject scoping still applies to every entity', async () => {+ await engine.executeRaw(`INSERT INTO fact_withdrawals(source_id, visibility, fact_hash)+ VALUES ('default', 'world', gbrain_fact_fingerprint('Likes tea'))`);+ expect(await isFactWithdrawn(engine, 'default', 'world', 'Likes tea', 'people/bob-example')).toBe(true);+ expect(await isFactWithdrawn(engine, 'default', 'world', 'Likes tea', null)).toBe(true);+ });+});diff --git a/test/forget-reconcile-durability.test.ts b/test/forget-reconcile-durability.test.tsindex cfbd919e9e..32c84fd541 100644--- a/test/forget-reconcile-durability.test.ts+++ b/test/forget-reconcile-durability.test.ts@@ -196,6 +196,10 @@ describe('withdrawal survives stale imports and derived-index rebuilds', () => {await forgetFactInFence(engine, id);await engine.executeRaw('DELETE FROM facts');const renamed = 'people/renamed-example';+ // Withdrawals are scoped to the entity, so the rename goes through the+ // rename operation (which carries them); a different page that merely+ // repeats the claim keeps it (test/facts-withdrawal-subject.test.ts).+ expect(await engine.updateSlug(SLUG, renamed, { sourceId: 'default' })).toBe(1);await importFromContent(engine, renamed, FILE, { noEmbed: true, sourceId: 'default' });await runExtractFacts(engine, { slugs: [renamed] });const rows = await engine.executeRaw<{ expired_at: unknown }>('SELECT expired_at FROM facts WHERE source_markdown_slug=$1', [renamed]);diff --git a/test/persistence-diagnostics.test.ts b/test/persistence-diagnostics.test.tsindex c80a041a9c..c44e797219 100644--- a/test/persistence-diagnostics.test.ts+++ b/test/persistence-diagnostics.test.ts@@ -96,11 +96,11 @@ test('fresh and upgraded engines agree on the database-only pending index', asyn} finally { abort.abort(); release.resolve(); await holding; await interrupted; }}await engine.setConfig('version', '164');- expect(await runMigrations(engine)).toEqual({ applied: 2, current: 166 });+ expect(await runMigrations(engine)).toEqual({ applied: 5, current: 169 });const [upgraded] = await engine.executeRaw<{ indexdef: string }>("SELECT indexdef FROM pg_indexes WHERE indexname='persistence_requests_database_pending'");expect(upgraded.indexdef).toBe(fresh.indexdef);- expect(await engine.getConfig('version')).toBe('166');+ expect(await engine.getConfig('version')).toBe('169');}}, 15000);diff --git a/test/persistence-effects.test.ts b/test/persistence-effects.test.tsindex 3645828dc2..bead07be83 100644--- a/test/persistence-effects.test.ts+++ b/test/persistence-effects.test.ts@@ -46,10 +46,11 @@ async function admit(f: Awaited<ReturnType<typeof fixture>>) {sourceIncarnation: f.binding.source_incarnation, slug: 'page', pageId: f.snapshot.page.id, requestId: randomUUID(),callerIntent: { content: 'After' }, intent: { content: 'After' }, worktreeId: f.binding.worktree_id, topologyGeneration: f.binding.topology_generation });}-async function withdraw(f: Awaited<ReturnType<typeof fixture>>) {+async function withdraw(f: Awaited<ReturnType<typeof fixture>>, opts: { subjectless?: boolean } = {}) {const row = await admit(f);+ // Withdrawals are entity-scoped; a subjectless fact withdraws source-wide.const [fact] = await engine.executeRaw<{ id: number }>(`INSERT INTO facts(source_id,entity_slug,fact,source,visibility)- VALUES($1,'page','Withdraw this claim','test conversation','world') RETURNING id`, [f.sourceId]);+ VALUES($1,$2,'Withdraw this claim','test conversation','world') RETURNING id`, [f.sourceId, opts.subjectless ? null : 'page']);await engine.transaction(async tx => {await recordFactWithdrawal(tx, Number(fact.id), f.sourceId, false, { requestId: row.id });await completeWrite(tx, row, 'committed', { status: 'forgotten' });@@ -128,7 +129,7 @@ test('missing withdrawal files materialize and advance mirror and Git scans withawait engine.putPage('z-later', page(body()), { sourceId: f.sourceId });const later = (await engine.readPageSnapshot('z-later', { sourceId: f.sourceId }))!;const laterFile = join(f.root, 'z-later.md'); writeFileSync(laterFile, serializePageToMarkdown(later.page, later.tags));- const row = await withdraw(f); await onlyEffects(row.id); rmSync(f.file);+ const row = await withdraw(f, { subjectless: true }); await onlyEffects(row.id); rmSync(f.file);const logical = (await engine.readPageSnapshot('page', { sourceId: f.sourceId }))!;// Ordinary edits still refuse this unimported deletion.await expect(prepareFileTarget(engine, row, logical, 'Replacement', hostId)).rejects.toMatchObject({ code: 'source_changed' });diff --git a/test/phantom-redirect.test.ts b/test/phantom-redirect.test.tsindex 4da4ea9ab4..96ffa022fd 100644--- a/test/phantom-redirect.test.ts+++ b/test/phantom-redirect.test.ts@@ -816,3 +816,41 @@ describe('tryRedirectPhantom — fence placement above the timeline sentinel (#4});});});++describe('tryRedirectPhantom — content outside compiled_truth is residue', () => {+ test('a page whose content lives in the timeline is not a phantom and survives', async () => {+ await withTempDirs(async ({ brainDir }) => {+ await putPage('people/alice-example', '# Alice Example\n\nCanonical person page.\n', { type: 'person' });+ await engine.putPage('alice', {+ title: 'alice',+ type: 'person',+ compiled_truth: '# alice\n',+ timeline: '## Timeline\n\n- **2026-03-01** | Met alice at the acme-example offsite; TIMELINE-MARKER.\n',+ frontmatter: {},+ });+ writeMd(brainDir, 'alice', '# alice\n\n<!-- timeline -->\n\n## Timeline\n\n- **2026-03-01** | TIMELINE-MARKER\n');++ const phantom = await engine.getPage('alice', { sourceId: 'default' });+ const result = await tryRedirectPhantom(engine, phantom!, 'default', brainDir, false);++ expect(result.outcome).toBe('not_phantom');+ const after = await engine.getPage('alice', { sourceId: 'default' });+ expect(after?.timeline).toContain('TIMELINE-MARKER');+ expect(mdExists(brainDir, 'alice')).toBe(true);+ });+ });++ test('custom frontmatter is residue; title/type/tags alone are not', async () => {+ await withTempDirs(async ({ brainDir }) => {+ await putPage('people/alice-example', '# Alice Example\n\nCanonical person page.\n', { type: 'person' });+ await putPage('alice', STUB_BODY, { frontmatter: { email_hint: '[email protected]' } });+ writeMd(brainDir, 'alice', `---\nemail_hint: [email protected]\n---\n${STUB_BODY}`);+ const withCustom = await engine.getPage('alice', { sourceId: 'default' });+ expect((await tryRedirectPhantom(engine, withCustom!, 'default', brainDir, false)).outcome).toBe('not_phantom');++ await putPage('alice', STUB_BODY, { frontmatter: { title: 'alice', type: 'person', tags: [] } });+ const plain = await engine.getPage('alice', { sourceId: 'default' });+ expect((await tryRedirectPhantom(engine, plain!, 'default', brainDir, true)).outcome).toBe('redirected');+ });+ });+});diff --git a/test/safety-wave-coverage-export-ledger.test.ts b/test/safety-wave-coverage-export-ledger.test.tsindex 12ed59f175..9019c70cea 100644--- a/test/safety-wave-coverage-export-ledger.test.ts+++ b/test/safety-wave-coverage-export-ledger.test.ts@@ -17,7 +17,7 @@ test('export refuses an over-limit withdrawal ledger before fetching its payloadtest('export accepts the exact ledger limit and keeps both reads source scoped', async () => {const params: unknown[][] = [];- const ledger = [{ visibility: 'world' as const, fact_hash: 'synthetic-fingerprint', withdrawn_at: '2026-01-01T00:00:00Z' }];+ const ledger = [{ visibility: 'world' as const, fact_hash: 'synthetic-fingerprint', withdrawn_at: '2026-01-01T00:00:00Z', subject: '*' }];const engine = { executeRaw: async (_sql: string, bound: unknown[]) => {params.push(bound);return params.length === 1 ? [{ bytes: String(EXPORT_PAYLOAD_LIMIT) }] : ledger;diff --git a/test/transcripts-retitle.test.ts b/test/transcripts-retitle.test.tsnew file mode 100644index 0000000000..8d76030848--- /dev/null+++ b/test/transcripts-retitle.test.ts@@ -0,0 +1,78 @@+/**+ * A retitled conversation (ChatGPT/Claude rename, or Claude.ai naming a+ * thread after its first exchange) keeps its existing page and slug, and the+ * messages added since the last import land. Real PGLite, no provider calls.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } 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 { resetPgliteState } from './helpers/reset-pglite.ts';+import { runTranscriptsIngest } from '../src/core/transcripts/ingest.ts';++let engine: PGLiteEngine;+let dir: string;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+});+afterAll(async () => {+ await engine.disconnect();+});+beforeEach(async () => {+ await resetPgliteState(engine);+ dir = mkdtempSync(join(tmpdir(), 'gb-retitle-'));+ return () => rmSync(dir, { recursive: true, force: true });+});++function exportFile(name: string, title: string, grown: boolean): string {+ const message = (role: string, t: number, text: string) => ({ author: { role }, create_time: t, content: { content_type: 'text', parts: [text] } });+ const mapping: Record<string, unknown> = {+ root: { id: 'root', parent: null, children: ['n1'], message: null },+ n1: { id: 'n1', parent: 'root', children: ['n2'], message: message('user', 1786080005, 'First question about acme-example.') },+ n2: { id: 'n2', parent: 'n1', children: grown ? ['n3'] : [], message: message('assistant', 1786080015, 'First answer.') },+ };+ if (grown) {+ mapping.n3 = { id: 'n3', parent: 'n2', children: ['n4'], message: message('user', 1786090005, 'FOLLOWUP-MARKER new question') };+ mapping.n4 = { id: 'n4', parent: 'n3', children: [], message: message('assistant', 1786090015, 'Follow-up answer.') };+ }+ const path = join(dir, name);+ writeFileSync(path, JSON.stringify([{ title, create_time: 1786080000, update_time: grown ? 1786090015 : 1786080015,+ conversation_id: 'cgpt-retitle-1', current_node: grown ? 'n4' : 'n2', mapping }]));+ return path;+}++async function livePages(): Promise<Array<{ slug: string; title: string; has_new: boolean }>> {+ return engine.executeRaw(`SELECT slug, title, compiled_truth LIKE '%FOLLOWUP-MARKER%' AS has_new+ FROM pages WHERE deleted_at IS NULL AND slug LIKE 'conversations/%' ORDER BY slug`);+}++describe('retitled conversation', () => {+ test('rename + new messages update the existing page in place', async () => {+ await runTranscriptsIngest(engine, { paths: [exportFile('a.json', 'Original title', false)], sourceId: 'default', format: 'chatgpt' });+ const [first] = await livePages();+ expect(first.slug).toContain('original-title');++ const second = await runTranscriptsIngest(engine, { paths: [exportFile('b.json', 'Renamed by user', true)], sourceId: 'default', format: 'chatgpt' });++ expect(second.pages.imported).toBe(1);+ expect(second.pages.skipped).toBe(0);+ const pages = await livePages();+ expect(pages).toHaveLength(1);+ expect(pages[0].slug).toBe(first.slug);+ expect(pages[0].has_new).toBe(true);+ expect(pages[0].title).toBe('Renamed by user');+ });++ test('re-importing the renamed export after the update is a clean skip', async () => {+ await runTranscriptsIngest(engine, { paths: [exportFile('a.json', 'Original title', false)], sourceId: 'default', format: 'chatgpt' });+ const b = exportFile('b.json', 'Renamed by user', true);+ await runTranscriptsIngest(engine, { paths: [b], sourceId: 'default', format: 'chatgpt' });+ const again = await runTranscriptsIngest(engine, { paths: [b], sourceId: 'default', format: 'chatgpt' });+ expect(again.pages).toMatchObject({ imported: 0, skipped: 1 });+ expect(await livePages()).toHaveLength(1);+ });+});