Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
v0.60.6.0 fix wave: import identity, forget at scale, facts lifecycle, derived-data reconcile, dream/connector safety, managed lifecycle, search (#5694)
Garry Tan6f3a2a564237
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex c6c855c2cb..0d5a349225 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.60.5.0",+ "version": "0.60.6.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 a1fef08594..83384a2a03 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.60.5.0",+ "version": "0.60.6.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 328bc98466..5fa04692b8 100644--- a/BOOTSTRAP_FOR_AGENTS.md+++ b/BOOTSTRAP_FOR_AGENTS.md@@ -1,4 +1,4 @@-<!-- gbrain-runbook-stamp: 0.60.5.0 -->+<!-- gbrain-runbook-stamp: 0.60.6.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 09228311e7..5384291f97 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,174 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [0.60.6.0] - 2026-09-29++**Forgetting works on big brains again, renames and edits keep everything attached to the page, search understands reworded relationship questions, and the nightly dream cycle stops spending past a budget or rewriting pages it didn't write.**++This is a fix wave. Most of it is things that quietly went wrong in everyday use and now don't.++On a brain with more than about 12,000 pages, telling your agent to forget something always failed. Now it works at any size, and a forgotten sentence no longer comes back because the model re-extracted it with a period or different capitalization. Renaming or moving a note used to leave its facts and search nicknames behind at the old name, and on a fresh brain it cut the page off from every note that linked to it. Now they travel with the page. Editing a page kept handing out new ids to facts that didn't change, which broke `forget` for ids your agent had already seen. Those ids are stable now.++Your graph, timeline and tags follow your notes on every path: delete a wikilink, a dated bullet or a frontmatter tag, and it leaves the database. Editing one sentence no longer re-embeds the whole page. And the dream cycle has a default spending cap, stops stamping your hand-written pages as its own output, and keeps one concept page per concept instead of three.++Search got better at two everyday question shapes. Ask "who backs acme-example?" or "people who funded acme-example" and the relationship graph now answers, where before only the exact "who invested in" wording did. Ask "which document is the harbor street lease amendment?" and the page with that title now ranks first more often.++### What changes for you++| Situation | Before | Now |+| --- | --- | --- |+| Forget a fact on a 15,000-page brain | Refused before the claim was even checked | Works; only refuses if the claim is on more than 256 pages, and says which |+| Forgotten "Prefers email" re-extracted as "prefers email." | Came back as a live fact | Stays forgotten |+| Rename `people/erin.md` to `people/erin-2.md` | Facts and search nicknames stayed at the old name; on a fresh brain, links to Erin broke | Page keeps its id, links, facts and nicknames; the old name still resolves |+| Import a second folder that reuses a note's `id:` | Could rename your live page to the new folder's file | Creates a separate page |+| Edit one fact row in a page's facts table | Every fact on the page got a new id | Unchanged rows keep their ids |+| Delete a dated bullet, run `gbrain extract --stale` | Old timeline row stayed | Row removed |+| Remove a tag from frontmatter and sync | Tag stayed forever | Tag removed; tags added by enrichment stay |+| Edit one sentence in a 10-chunk page | 10 chunks re-embedded | Only the changed chunks |+| Dream synthesis on a big backlog | No per-run dollar cap | Stops at $5 per run by default and picks up next run |+| Dream edits your `people/alice-example` page | Page stamped as dream output | Page keeps its identity |+| "Network Effects" and "network-effects" in atoms | Three concept pages, one with a space in its slug | One page |+| A ChatGPT conversation that downloads but won't ingest | Held back every later sync | Set aside after 3 tries |+| Thin client call longer than 60 seconds | Cut off by the SDK | Honors your timeout |+| "Who backs acme-example?" | Graph never consulted | Graph answers (held-out rewordings: right page first 17% of the time, up from 5%) |+| "Which document is <title>?" | Title page often second | Title page first (+3/−0 on a 144-query title benchmark) |+| Graph walk on a densely linked group of pages | ~22 seconds | ~0.25 seconds |+| Long LongMemEval run | Hung around question 94 | Runs to completion |++### How to use it++```bash+gbrain upgrade # applies migrations v174 and v175+gbrain doctor # new checks: timeline_orphans, slug_collisions+gbrain extract timeline --prune-orphans --dry-run # preview timeline rows left from old page versions+gbrain extract timeline --prune-orphans # remove them+gbrain embed --stale --images # rebuild images missing their picture vector or OCR text+gbrain config set brain.timezone America/New_York # read frontmatter times without an offset in your zone+gbrain config set dream.synthesize.budget_usd 20 # raise the per-run synthesis cap (0 = spend nothing, unlimited = no cap)+gbrain config set search.source_boosts "wiki/:1.3,daily/:1.0" # per-brain source boosts; "none" drops the defaults+```++Opt-in settings, all off by default:++```bash+gbrain config set sync.git_first_commit_dates true # date undated notes by their first git commit on a full import+gbrain config set facts.extraction_missing_confidence 0.5 # confidence stored when the extractor gives none (default stays 1.0)+gbrain config set dream.synthesize.attribution_rules true # extra speaker-attribution rules in the synthesis prompt+gbrain config set dream.propose_takes.attribution_rules true # same for propose-takes+gbrain config set search.alias_token_hop true # a one-word query token that is a person/company alias pulls that page up+```++### Things to watch++- **Synthesis now has a default $5 per-run budget.** Before, `dream` synthesis had only the daily cap. A large backfill now spreads across several runs: a transcript that doesn't fit the budget is deferred to the next run, not dropped. Set `dream.synthesize.budget_usd` to raise it or `unlimited` to remove it. A budget of `0` now means spend nothing everywhere (it used to mean unlimited in the budget meter, and drift read `"0"` as $1). A model missing from the pricing table is metered at a Sonnet-tier rate instead of skipping the gate; local runtimes (Ollama, LM Studio, llama-server) count as $0, and `dream.budget.allow_unpriced=true` restores the old bypass. If the daily-cap count query fails, that run submits nothing.+- **Upgrading re-expires punctuation-only variants of forgotten facts.** Migration v174 folds case, spacing and sentence punctuation in withdrawal fingerprints. Any active fact that differs from a forgotten one only by punctuation, case or spacing is expired during the upgrade. `+`, `#` and in-word dots still count, so "C++" and "C" stay different claims. Paraphrases with different words are still different claims.+- **The missing-confidence default is unchanged.** A numeric-string confidence like `"0.3"` is now read as 0.3 instead of 1.0, but a missing or null confidence still stores 1.0. `facts.extraction_missing_confidence` is an opt-in knob; no matched eval has measured a new default.+- **Git first-commit dates are opt-in.** `sync.git_first_commit_dates` changes `effective_date`, which feeds recency ranking and since/until filters, so it stays off until you turn it on. It applies to full imports (first sync, `sync --full`, `gbrain import`), not incremental syncs.+- **Attribution prompt rules are opt-in.** The mechanical speaker check (a decision attributed to someone who never stated its numbers or dates is held back in `unverified_claims`) is on for everyone. The two prompt changes from #5425 ship behind `dream.synthesize.attribution_rules` and `dream.propose_takes.attribution_rules` because matched runs showed no benefit.+- **Search boosts a title that is the subject of a general or temporal question.** When a multi-word page title (or slug tail) supplies at least half of the question's content words, that page gets a bounded 1.18x boost; the longest nested title wins. Concept and relational questions are excluded. On the in-repo title benchmark this is +3/−0 hit@1 against the previous release, and the "mentions one title, asks for another" family is unchanged (24 of 36).+- **Reworded relationship questions now reach the graph.** "X's investors", "people who funded X", "who backs X", "who is the founder of X", "which companies has X backed", "relationship between A and B" and "who can introduce me to X" parse as relational, and the graph arm fires when the named entity resolves to a page. On a held-out set of 435 reworded questions it fires on 99 (was 0), hit@1 goes from 0.048 to 0.166, paired +51/−0. The original template wording is unchanged (+72/−6 as before), and parse-level false positives stayed at 1 of 500 LongMemEval questions and 0 on the other probe sets.+- **The single-word alias hop is opt-in.** `search.alias_token_hop` (or per-call `aliasTokenHop`) is off by default because no in-repo benchmark exercises it.+- **Per-brain source boosts, defaults unchanged.** `search.source_boosts` overrides the built-in source boosts for one brain; brains without the key rank exactly as before, and `GBRAIN_SOURCE_BOOST` still wins.+- Timeline rows an earlier version of a page produced and its text no longer has are removals: `--prune-orphans` deletes them (on managed-persistence brains, every fresh `gbrain init`, through a coordinated write), and `gbrain repair timeline` and doctor's `timeline_history` no longer count them as database-only history to write back into the page. Managed brains keep add-only tags for now.+- The facts write path now reports failures it used to swallow: resolver database errors propagate, and `FACTS_ROW_NUM_HINT_UNAVAILABLE`, `FACTS_PAGE_MIRROR_FAILED` and `FACTS_SUPERSEDE_BOOKKEEPING_FAILED` appear on stderr.+- Takes bootstrap from pages stops at `takes.bootstrap_budget_usd` (default 5.0, `0` disables).++### To take advantage of v0.60.6.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.** Migration v174 adds punctuation-folded withdrawal fingerprints, backfills them and expires matching facts; v175 adds `tags.tag_source`. There is no `skills/migrations` file for this release.+3. **Verify the outcome:**+ ```bash+ gbrain doctor+ gbrain extract timeline --prune-orphans --dry-run+ 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++### Itemized changes++#### Forgetting and withdrawal++- Discovery is keyed on the claim, its subject and its fingerprint (#5674, reported by @Grimnoth). The database shortlists pages and chunks whose text contains every normalized word of the claim, streams them by keyset and verifies each exactly (on a 2,500-page Postgres source each withdrawal takes well under a second); a subject-scoped withdrawal reads only its entity's page and the provenance of that entity's facts. Limits apply to the matched set (256 pages, 1 MiB manifest, 10 s scan budget), not the source's size, and a refusal names the matched count, sample pages and a recovery path. Legacy `source_scan` effects key discovery on their own forgotten fact.+- Migration v174 (`fact_withdrawal_normalized_fingerprint`): fingerprints fold case, whitespace and sentence punctuation, keeping `+`, `#` and in-word dots (write-path audit B-9). Pre-v174 ledger rows keep their exact hash and every match checks both; v174 adds a folded row wherever a fact row still holds the claim text, expires facts that became matching and builds `idx_facts_withdrawal_fingerprint`.+- `writeFactsToFence` rechecks each input under the page lock and drops claims withdrawn for the page's entity (`withdrawnSkipped`); the facts backstop skips them too, so a forgotten claim is never written to Markdown as a live row (B-10).+- Ported from #5469 by @tarush1989: the Postgres scale gate (`test/e2e/fact-withdrawal-scope-postgres.test.ts`) and the structural pin that every coordinated prepare path runs the pre-publication withdrawal recheck.++#### Import identity and renames++- Move inference binds to the root the existing page was imported from (#5675, reported by @Grimnoth). `importFromFile` records a `file://` origin in `pages.source_uri` (never replacing non-file provenance), falling back to the source's `local_path` or the default source's `sync.repo_path`. A missing path under another root is not evidence of a move; a content-changed move needs the old file gone under its own root, the new file under that same root and the same file name or title.+- `updateSlug` moves `facts.entity_slug`, `facts.source_markdown_slug`, `page_aliases` and withdrawal subjects in the rename transaction on both engines (`moveSlugBindings`, #5431 item 3, reported by @clatyceo). Rows left at the new slug by a purged page yield to the moved ones.+- Transcript re-ingest keeps frontmatter keys the collector does not render (#5431 item 2, @clatyceo); safety and atom-scan markers are still recomputed.+- `callRemoteTool` passes the caller's `timeoutMs` to the MCP SDK as the request deadline and reports an SDK `RequestTimeout` as a timeout (#5100, contributed by @xaviroblessarries).++#### Managed persistence lifecycle++- Slug collisions no longer block a managed sync: new files that map to one slug are settled after discovery (a live page whose file still exists keeps the slug, else the file named like the slug, else the first path), and losers are reported as `slugCollisions` and printed by sync. Case- or separator-only respellings of one origin still refuse.+- A Git-detected rename becomes one import that moves the page with `updateSlug` inside the coordinator transaction: same page id, inbound links, facts (ids kept), an `old -> new` slug alias, and an implicit type re-inferred from the new path. `renamed` counts them. Links written against an old slug follow its alias.+- Managed sync derives links for the pages it imported, after its checkpoint commits, in the process that owns the brain. Managed brains have one stale-extraction path, `extractManagedStaleLinks`: managed sync, every caller of `extractStaleFromDB` (the CLI, the cycle, jobs, `maintain`) and, with a live PGLite `gbrain serve`, the owner delegation (`writer_extract_stale`, trusted local callers only). Per page it replaces derived links (following slug aliases), adds the coordinator's unrecorded canonical timeline rows insert-only and stamps the watermark in one revision-bound coordinated transaction. `--json` reports the same `extract_stale_done` shape as unmanaged brains.++#### Facts and takes lifecycle++- The legacy `extract_facts` reconcile keys fence rows by row number (B-5). A row whose number and claim survive keeps its id and is updated in place; a removed or rewritten row is expired and detached (`row_num` NULL), never deleted. `ExtractFactsResult` gains `factsUpdated`. A claim that reverts (NYC, SF, NYC) stays active (B-4); supersession chains keep every hop (B-13); facts of soft-deleted pages leave recall and come back on restore (B-7).+- Fence `valid_from`/`valid_until` round-trip to the second (B-6, B-20). `claim_value` parses strictly, with separators, a currency symbol and k/M/B scaling; malformed numbers or confidence are `FACTS_TABLE_MALFORMED` (B-15).+- Extractor confidence: numeric strings are read as stated; `facts.extraction_missing_confidence` is opt-in; unknown kinds are counted in a warning (B-16).+- Fuzzy fact attribution lands only on a unique same-name entity page, never a meeting or note (B-8).+- Phantom-redirect merges are lossless (B-12): the canonical fence goes to the page's file of record, every phantom fact moves by id at the row number written to disk with `superseded by #N` renumbered, links move to the canonical page, and the phantom slug is recorded in `slug_aliases`. A fuzzy canonical needs a clear margin.+- Takes: bootstrap from pages dedupes against the fence, stops at `takes.bootstrap_budget_usd` and reports model failures as `llm_error:<code>` (B-14); fence takes extraction stays in its source, skips deleted pages and prunes rows removed from the fence (B-18).+- Temporal supersession orders by instant; same-day or unparseable dates get "date order unclear" (B-17). Entity identity links are atomic and re-linking the canonical member keeps it canonical (B-19). Write-path failures are reported (B-21).++#### Derived data, sync and embeddings++- `retractRemovedTimelineEntries` proves ownership against every stored `page_versions` text and runs on every extraction path: `extract --stale`, the file and database walks, the per-slug cycle extract and sync's hook (#5170 by @rodrigo-kiko, #4649 by @jarospm). Rows no version produced (enrichment, meeting fan-out, `--infer-dates`) are kept. `gbrain extract timeline --prune-orphans [--source-id] [--dry-run] [--json]` is the one-time cleanup, and doctor's `timeline_orphans` samples 500 pages.+- The file-walk `gbrain extract links|all` replaces each page's own markdown-derived links through `replacePageFileLinks`.+- The post-sync link hook loads metadata only for changed pages and their endpoints (A16) and reports per-page extraction errors as `extract_error` (A15).+- Markdown re-imports reuse stored vectors for unchanged chunks (A13): a chunk with the same source and text keeps its vector when its recorded embedding-input hash (`content_chunks.embedding_input_hash`, from v0.60.5.0) equals the one this import would record, or, for a vector stored before hashes existed, when the input is the raw chunk text under the same model. The index must be sealed and neither body may hold protected fences. In a 40-page matched test, a one-sentence edit to 20 pages embedded 31 chunks (21,278 tokens) instead of 110 (47,719) with the same hit@1, hit@5 and MRR. `--force-rechunk` re-embeds everything.+- Migration v175 (`tags_tag_source`) adds `tags.tag_source`: frontmatter tags stamp `'frontmatter'` and are deleted when they leave the frontmatter; every other `addTag` stamps `'added'` and is never import-deleted (A14).+- `gbrain embed --stale --images [--source] [--dry-run] [--json]` rebuilds image pages missing a visual vector or OCR text (requires `GBRAIN_EMBEDDING_MULTIMODAL=true`).+- Doctor `slug_collisions` names files that map to one page and which one is indexed.+- `brain.timezone` (IANA, validated by `gbrain config set`) reads offset-less frontmatter datetimes on import and in the `effective_date` backfill; date-only values stay UTC calendar dates.+- `sync.git_first_commit_dates` (opt-in) anchors undated new pages at the earliest of birth time, mtime and first-commit date in one `git log --diff-filter=A` pass per full import; shallow clones keep file times.++#### Dream cycle, synthesis and connectors++- `synthesize_concepts` normalizes refs through `slugifySegment`/`validatePageSlug` before grouping (C-4), records a `member_hash` to skip unchanged groups, and never replaces an LLM narrative with a template stub on budget exhaustion or model error (C-5).+- The dream provenance stamp and whole-page verification apply only to pages a child created; pages another writer created mid-run are diffed from the child's first write (C-8, #5685 follow-up by @garrytan). A `managed_maintenance_page` publish rebuilds automatic links from the published body.+- `dream.synthesize.budget_usd` (default $5) gates every submission with a per-run `BudgetMeter`; the daily cap fails closed (C-13). Budget meter gaps closed: unpriced models are metered, `0` spends nothing, drift estimates from its real prompt (C-16).+- One calendar date per cycle for synthesis, patterns, drift and verify (C-15). Atoms from undated sources are dated by page creation or `undated`, and a completed unmanaged re-extraction retires its stale atoms (C-14).+- Connector ingest failures are attributed per conversation; a conversation that fails to ingest 3 times at one version is quarantined (#5666 follow-up). Claude's list pages with `limit`/`offset` across every chat-capable org (C-17); ChatGPT's offset walk re-covers items shifted by a mid-walk removal and yields each id once (C-18). A session with no timestamps is a reported `skipped_no_timestamp` (C-19).+- New grounding failure `decision_misattributed` quarantines a decision whose numbers or dates only another speaker stated and the named speaker never accepted (#5425 by @clatyceo). In the repeated-consolidation harness: misattributed decisions active 1 to 0, supported claims kept 14 of 14.++#### Search and the read path++- General and temporal title-subject boost (#4694, thanks @jonathanlesh for the report and benchmark shape); benchmark corpus in `evals/title-mention/` (72 placeholder pages, 144 queries) for `gbrain import` plus `gbrain eval retrieval-quality`.+- Relational paraphrase recognition in `src/core/search/relational-intent.ts`.+- Rows the reranker scored exactly equal keep the fused order (#5428, thanks @clatyceo). Opt-in single-token alias hop in `src/core/search/alias-hop.ts` (#5428).+- `search.source_boosts` (audit #13); a `none` entry drops the defaults.+- The alias hop and the exact-lookup tier no longer inject a page under `exclude_slug_prefixes` or the hard excludes. Keyword-only search (no embedding provider) applies the same entity exact-match and alias-mention boost as hybrid.+- Failed keyword or title arms stamp `keyword_arm_failed` / `title_arm_failed` in `meta.degraded` (#5324, thanks @founders-sgp).+- Bare-name entity matches resolved by prefix expansion are tagged `prefix_expansion`, and facts written through them carry an "unverified, please confirm" note in their context cell (#4846, #5139, thanks @kweiner).+- `traversePaths` and `traverseGraph` stay bounded on dense hubs on both engines: a 12-page clique at depth 5 went from 21.9 s to 0.25 s and from 3.4 s to 0.06 s, with the shallow neighbourhood complete.+- Image rows in `both` mode rescore in the image embedding space. The token budget no longer drops every lower-ranked result after one oversized result, counts CJK at about one token per character and never splits a surrogate pair. `hybridSearchCached` drops two dead round-trips per search. Trajectory lookups clear their 5 s deadline timer.+- Expansion variant budget stays `null` by default: on 215 LongMemEval questions, budgets 1.0 and 0.25 lost against the legacy setting (recall_all@5 203 and 202 vs 205). Default search returned identical top-5 to the previous release on all 215.+- LongMemEval: embed-cache writes are buffered and flushed in one short `BEGIN IMMEDIATE`, so runs sharing a cache keep their writes; the harness replaces its benchmark brain every 40 questions so long runs finish (#5092, thanks @justinsharpe).++### For contributors++- Migration pin: `test/persistence-diagnostics.test.ts` expects v175.+- New suites include `test/import-identity-move.test.ts`, `test/fact-withdrawal-normalized.test.ts`, `test/fact-withdrawal-prepare-wiring.test.ts`, `test/extract-facts-stable-identity.test.ts`, `test/phantom-redirect-merge.test.ts`, `test/facts-fence-dates.test.ts`, `test/facts-write-path-failures.test.ts`, `test/timeline-reconcile-all-paths.test.ts`, `test/import-markdown-embedding-reuse.test.ts`, `test/import-frontmatter-tag-removal.test.ts`, `test/effective-date-brain-timezone.test.ts`, `test/effective-date-git-first-commit.test.ts`, `test/persistence-managed-lifecycle.test.ts`, `test/cycle/synthesize-concepts-identity.test.ts`, `test/cycle-date-consistency.test.ts`, `test/cycle/extract-atoms-reconcile.test.ts`, `test/managed-maintenance-links.test.ts` and `test/e2e/connectors-ingest-failure-pglite.test.ts`.+- More new suites: `test/relational-intent-paraphrase.test.ts`, `test/search/general-title-mention-boost.test.ts`, `test/search/alias-token-hop.test.ts`, `test/search/source-boost-config.test.ts`, `test/traverse-walk-cap.test.ts`, `test/facts-backstop-unverified-resolution.test.ts`, `test/longmemeval-embed-cache.test.ts` and `test/eval-longmemeval-brain-recycle.test.ts`.+- `docs/architecture/canonical-writers.tsv` classifies the new canonical write sites (`moveSlugBindings`, the v174 backfill, the managed rename).+## [0.60.5.0] - 2026-09-29**Your brain stops deleting history it can't see, managed brains stop wedging themselves, and background loops stop spending money and connections on nothing.**diff --git a/VERSION b/VERSIONindex f335719623..11a7538d2b 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-0.60.5.0+0.60.6.0diff --git a/docs/architecture/RETRIEVAL.md b/docs/architecture/RETRIEVAL.mdindex b2e92c1ed1..bcdddde65b 100644--- a/docs/architecture/RETRIEVAL.md+++ b/docs/architecture/RETRIEVAL.md@@ -74,7 +74,7 @@ Hybrid search applies a source-factor CASE expression at the SQL layer (lives in`archive/` is deliberately NOT hard-excluded: it holds high-signal historical content users expect to find, so it is demoted (`0.5x` in `DEFAULT_SOURCE_BOOSTS`), not hidden. The demote is a prior applied in the outer SQL re-rank; the cross-encoder reranker (balanced/tokenmax modes) can still PROMOTE an archive page that survives the demote into the rerank candidate window — it is not an unconditional suppression. `gbrain doctor`'s `hidden_by_search_policy` check reports how many chunked pages remain hidden by the surviving exclude prefixes.-The boost map is configurable via the `GBRAIN_SOURCE_BOOST` env var. Hard exclusions are separate: the exclusion set is defaults ∪ `GBRAIN_SEARCH_EXCLUDE` (env, comma-separated prefixes) ∪ per-call `SearchOpts.exclude_slug_prefixes`. Temporal queries (`detail: 'high'`) bypass the boost so chat pages re-surface for time-sensitive lookups.+The defaults fit one vault layout, so each brain can carry its own map: `gbrain config set search.source_boosts "wiki/:1.3,daily/:1.0"` overrides or extends the defaults per prefix, and a `none` entry (`"none,wiki/:1.3"`) drops them entirely. The `GBRAIN_SOURCE_BOOST` env var (same format) wins over the brain config for one process. Hard exclusions are separate: the exclusion set is defaults ∪ `GBRAIN_SEARCH_EXCLUDE` (env, comma-separated prefixes) ∪ per-call `SearchOpts.exclude_slug_prefixes`. Temporal queries (`detail: 'high'`) bypass the boost so chat pages re-surface for time-sensitive lookups.## Named-thing retrieval (per-page pool + title + alias + evidence)diff --git a/docs/architecture/canonical-writers.tsv b/docs/architecture/canonical-writers.tsvindex 1f2250e0f3..624639f21f 100644--- a/docs/architecture/canonical-writers.tsv+++ b/docs/architecture/canonical-writers.tsv@@ -2,6 +2,7 @@# path write-reference ceiling enforcement boundary review rationalesrc/core/persistence/activation.ts 0 coordinator Trusted private administration requires explicit quiescence and durable refusal records before enabling managed canonical writer enforcement.src/core/persistence/canonical-projections.ts 9 coordinator Facts, takes, timeline, chunks and aliases install within the guarded canonical publication transaction before its receipt commits.+src/core/persistence/links-maintenance.ts 1 coordinator Managed extract --stale and post-sync extraction add only the coordinator's unrecorded canonical timeline tuples inside a revision-bound withCoordinatedWrite transaction that also replaces the page's derived links and stamps its watermark.src/core/persistence/takes-prepare.ts 3 coordinator Semantic takes apply only through the journal publication callback after current revision, holder and authority validation.src/commands/extract-conversation-facts.ts 4 early_refusal Unsupported managed bulk extraction refuses before queue or provider work; legacy canonical writes retain SQL guard enforcement.src/commands/extract.ts 7 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication. On a managed brain extract --stale inserts only the canonical timeline tuples inside withCoordinatedWrite for that page, after the revision-bound derived-link replacement locked and verified the page revision in the same transaction.@@ -33,9 +34,9 @@ src/core/company-brain/profile.ts 1 engine_guard Company-profile legacy deletessrc/core/company-brain/runtime.ts 1 projection Only source policy metadata advances under the company-source lock and brain/source row locks; the same transaction validates immutable approval and creates a receipt with source-incarnation and managed owner/topology fences, without source-file writes.src/core/cycle/drift.ts 1 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.src/core/cycle/extract-atoms.ts 3 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.-src/core/cycle/extract-facts.ts 3 early_refusal Managed legacy fence reconciliation refuses before providers; unmanaged reconciliation preserves valid vectors transactionally and applies source-scoped privacy and withdrawal restrictions before embedding.+src/core/cycle/extract-facts.ts 6 early_refusal Managed legacy fence reconciliation refuses before providers; unmanaged reconciliation keys rows by fence row number under the page lock, updates matched rows in place, expires and detaches removed rows instead of deleting them, and expires fence-owned rows of soft-deleted pages.src/core/cycle/extract-atoms-page-state.ts 1 engine_guard Atom completion updates and cardinality checks share one transaction; managed canonical SQL remains fenced and scan/failure bookkeeping is stored separately.-src/core/cycle/extract-takes.ts 3 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.+src/core/cycle/extract-takes.ts 4 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication. Stale-row pruning deletes only takes whose rows left a cleanly parsed fence on a live page in the same source.src/core/cycle/grade-takes.ts 1 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.src/core/cycle/patterns.ts 0 coordinator Managed local patterns use admitted page operations and validate canonical outputs; the legacy reverse-file path runs only unmanaged.src/core/cycle/phantom-redirect.ts 5 early_refusal Managed mode refuses this legacy entry point before its canonical filesystem/provider effects.@@ -54,13 +55,14 @@ src/core/extract-timeline-from-meetings.ts 1 engine_guard Canonical table SQL trsrc/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 4 filesystem_guard Managed callers journal withdrawal; legacy filesystem helper and the supersession-only expiry require coordinated write.+src/core/facts/withdrawal-schema.ts 1 schema Migration v174 DDL/backfill expires fact rows that match a folded withdrawal fingerprint; schema installation runs under coordinated activation, which quiesces canonical writers.src/core/facts/withdrawal.ts 2 coordinator Publication is transaction-scoped under admitted authority, source/page guards and revision checks.src/core/facts/write-single.ts 2 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.src/core/git-remote.ts 0 filesystem_guard Clone, pull and rebase entry points check the durable root refusal registry.src/core/github-source.ts 3 coordinator Managed connector imports, deletion and checkpoints use prepared journal publication; unbound API sources explicitly persist in the database and bound sources retain canonical filesystem publication.src/core/google/google-source.ts 3 coordinator Managed connector imports, deletion and checkpoints use prepared journal publication; legacy materialization is confined to unmanaged sources.src/core/google/loops-extract.ts 1 early_refusal Unsupported managed loop extraction refuses before model calls; unchanged unmanaged fact/fence writes remain guarded.-src/core/import-file.ts 16 coordinator Prepared import applies under journal publication and revision CAS; direct managed imports refuse early, legacy source-path repair follows revision validation inside a savepoint, and a moved file's page is renamed only on the direct (unmanaged) path.+src/core/import-file.ts 17 coordinator Prepared import applies under journal publication and revision CAS; direct managed imports refuse early, legacy source-path repair follows revision validation inside a savepoint, and a moved file's page is renamed only on the direct (unmanaged) path. Frontmatter tag reconciliation deletes only import-owned tag rows inside the same guarded import transaction.src/core/last-retrieved.ts 1 projection Derived indexing, retrieval telemetry, or source settings; canonical fields remain guarded by SQL triggers.src/core/migrate.ts 13 schema Schema installation and forward-reference DDL; coordinated activation quiesces canonical writers.src/core/minions/handlers/ingest-capture.ts 1 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.@@ -74,7 +76,7 @@ src/core/page-state/materialize.ts 1 coordinator Publication is transaction-scopsrc/core/page-state/projection-schema.ts 1 schema Schema installation and forward-reference DDL; coordinated activation quiesces canonical writers.src/core/page-state/projections.ts 2 projection Derived indexing, retrieval telemetry, or source settings; canonical fields remain guarded by SQL triggers.src/core/page-state/schema.ts 2 schema Schema installation and forward-reference DDL; coordinated activation quiesces canonical writers.-src/core/page-state/tags.ts 2 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.+src/core/page-state/tags.ts 3 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication. The frontmatter-claim and explicit-add inserts are two branches of one guarded statement.src/core/persistence/memory-mutations.ts 1 coordinator Publication is transaction-scoped under admitted authority, source/page guards and revision checks.src/core/persistence/memory-prepare.ts 3 coordinator Publication is transaction-scoped under admitted authority, source/page guards and revision checks.src/core/persistence/page-prepare.ts 9 coordinator Publication, including versioned tombstone restoration, is transaction-scoped under admitted authority, source/page guards and revision checks; the sixth SQL site reconciles trusted first-write provenance with prepared canonical frontmatter and the seventh records canonical source_path in that same guarded transaction. Identical canonical no-ops do not heal physical metadata. The added local-CLI purge deletePage call runs in the prepared publication callback after recorded-artifact removal, under the same source/page identity, revision and durable authority guards as receipt completion; permanent journal IDs and outcomes survive the hard delete. The ninth site pins an inferred slug_root_mode on sources in the same publication transaction as the first bound origin.@@ -115,7 +117,7 @@ src/commands/files.ts 0 filesystem_guard Attachment copying, redirection, restorsrc/commands/schema.ts 0 filesystem_guard Schema manifest scaffolding and forks check managed roots before creating files; separate config settings are control data.src/core/ingestion/sources/inbox-folder.ts 0 filesystem_guard Inbox archive moves refuse managed canonical input paths before emitting the event or moving source bytes.src/core/persistence/links-preparation.ts 2 coordinator Automatic graph projections publish inside canonical page transactions; delayed reconciliation locks all affected page keys and compares the originating revision.-src/core/persistence/sync-prepare.ts 3 coordinator Managed imports and deletes validate the recorded raw file hash plus enumerated page identity/revision; the source-exclusive final checkpoint requires every selected receipt to be committed.+src/core/persistence/sync-prepare.ts 5 coordinator Managed imports and deletes validate the recorded raw file hash plus enumerated page identity/revision; a managed rename moves the page with updateSlug and re-infers an implicit type inside the same journal publication after the renamed page's identity and revision are rechecked; the source-exclusive final checkpoint requires every selected receipt to be committed.src/commands/enrich.ts 0 early_refusal Managed batch synthesis refuses before providers until its resume cursor retains prepared writes; legacy synthesis still carries a coherent revision and exposes pending request IDs.src/core/persistence/source-lifecycle.ts 6 coordinator Native affected roots precede topology, source, principal and receipt guards; every shared-root generation and old queued intent changes together.src/core/persistence/topology-recovery.ts 2 coordinator Verified directory-swap recovery checks source incarnation, current logical manifest and physical identity before topology commitment; permanent receipt IDs survive deletion.@@ -157,6 +159,6 @@ src/core/shared-skills/setup.ts 1 engine_guard Trusted preactivation empty-sourcsrc/core/shared-skills/optimizer.ts 0 coordinator Shared optimization preserves the exact approved closure and original grants in private staging; only accepted body changes reach put_skill with the original revision and stable request UUID.src/core/persistence/import-prepare.ts 1 coordinator The prepared local import updates source_path only inside canonical publication; owner, input and target hashes, source confinement and knowledge-versus-skill boundary revalidate before apply.src/core/persistence/grandfather.ts 2 coordinator Private migration intents preserve exact page/source/incarnation/revision identity and rollback snapshots; frontmatter/hash and existing text seals change only inside canonical file publication, without new embedding or fact-backstop effects.-src/core/page-state/rename-alias.ts 3 engine_guard Rename aliases write slug_aliases inside the updateSlug transaction; the canonical table SQL trigger requires coordinator capability, so legacy calls fail before publication.+src/core/page-state/rename-alias.ts 8 engine_guard Rename aliases (slug_aliases) and moveSlugBindings (facts entity/fence slugs, page_aliases, withdrawal subjects) run inside the updateSlug transaction; the canonical table SQL trigger requires coordinator capability, so legacy calls fail before publication.src/core/timeline-extract.ts 1 engine_guard Retracting removed markdown timeline rows is canonical table SQL; the trigger requires coordinator capability, so legacy calls fail before canonical DB publication.src/core/persistence/connector-google-receipts.ts 1 coordinator Account and message-owned Gmail receipt metadata changes only under canonical source/page locks, identity/revision and file guards; guarded projection installation preserves withdrawal overlays without replaying bodies or extracting facts.diff --git a/docs/architecture/key-files/agent-bootstrap-continued.md b/docs/architecture/key-files/agent-bootstrap-continued.mdindex b194dad565..cf786627fd 100644--- a/docs/architecture/key-files/agent-bootstrap-continued.md+++ b/docs/architecture/key-files/agent-bootstrap-continued.md@@ -24,7 +24,7 @@- `src/core/context/sync-ipc.ts` + `src/core/serve-sync-runner.ts` + `src/commands/sync-delegate.ts` — serve-delegated sync. `sync-ipc.ts` is the LEAF wire module: the `DELEGATED_SYNC_OPTION_FIELDS` table is the single source of truth for the validator, the CLI wire-builder, and the serve-side SyncOpts builder; `validateDelegatedSyncOptions` rejects unknown keys fail-closed (repoPath/skipLock/lockId/concurrency are unreachable from the socket), requires `timeoutSeconds` (0 = the explicit `--no-hard-deadline` unbounded encoding; everything else clamps to 24h), and `toWireSyncResult` truncates `pagesAffected` to 50 + a true total under the 256KB message cap. `serve-sync-runner.ts` is the serve-side module singleton: one job at a time (correctness still rests on the `gbrain-sync:<source>` row lock inside performSync), clientToken attach (a lost-ack retry finds its own running OR retained-terminal job instead of duplicate-running), per-job deadline timer, `[serve-sync]` lifecycle stderr lines, an idempotent shared `shutdownDelegatedSync()` both serve shutdown paths await BEFORE `engine.disconnect()` (the disconnect-mode drain is allowAbort:false after `_db` is nulled, so settle writes need the live engine; a registered drainer remains as backstop), and `maybeDrainDeferredEmbeds` (delegated jobs always run noEmbed — the cost gate lives in runSync — and the serve drains stale embeds afterwards via `runEmbedCore`, keyless-safe, cleared only when a drain finds nothing left; wire `noEmbed` records that the USER declined embeds and suppresses the drain). `sync-delegate.ts` is the CLI half: read-only holder probe (`probeLivePgliteHolder`), DEFAULT-DENY argv gate (any unclassified token refuses by name — a silently dropped `--exclude` would perform the wrong sync), engine-free source tiers (`resolveSourceIdEngineFree`), 1s poll loop tolerant of event-loop-blocked serves with a PID-probe backstop, `unknown_job` → serve-restarted resume hint, Ctrl-C → `sync_abort` (second Ctrl-C exits 130), and runSync's `pull_failed` verdict mirroring. Mounts and non-PGLite configs never delegate; opt-outs `--no-delegate` / `GBRAIN_SYNC_NO_DELEGATE=1` (client) and `GBRAIN_SERVE_SYNC_IPC=0` (serve). Pinned by `test/context/sync-ipc-validation.test.ts`, `test/sync-delegate-ladder.test.ts`, `test/serve-sync-runner.serial.test.ts`, `test/context/resolve-ipc-sync-kinds.test.ts`, and `test/e2e/sync-delegation-under-serve.serial.test.ts` (gating tier1 step).- `src/core/capability.ts` — config-plane keyless/keyed detection + the honest capability report (per-provider keyless banner: OpenAI = semantic search + auto-extraction, Voyage = semantic search, Anthropic = auto-extraction) rendered by verify and the runbook. The extraction probe resolves through the SAME shared `resolveEffectiveChatModel` the gateway's reconfigure fallback uses (`GBRAIN_MODEL` > servable file pin > key-aware tier default), so a stale unservable pin degrades identically in the report and at runtime. Key/env fold comes from `mergedProviderEnv` (`src/core/ai/provider-env.ts`). Accepted limitation (documented in the module): DB-plane overrides (`models.default`, `facts.extraction_model`) are invisible to this engine-less probe; the runtime gate in `facts/extract.ts` and the engine-aware pre-enqueue gate in `facts/backstop.ts` are the backstops.- `src/core/secret-scan.ts` — pattern-based secret detection shared by `sources push`, bootstrap verify, the compiled-context sensitivity scan and the transcripts redactor. Detection is FORMAT-based, not prefix-only: vendor shapes (anthropic, openai, voyage, github, gitlab, slack, aws AKIA/ASIA, google, stripe, sendgrid, twilio, supabase sb_secret_/sbp_, npm, huggingface, gbrain), JWTs, whole-block PEM keys, plus two catch-alls appended LAST (`bearer` — prebuilt two-group layout so only the token is the value; `db_url_credentials` — the `scheme://user:pass@` span of database URLs, host/db kept). Fixed-length shapes carry a trailing negative lookahead. Per-line claimed-span dedupe is first-wins for ATTRIBUTION (order matters: `Bearer <vendor key>` keeps the vendor name, a fully covered later span is skipped) but coverage is the UNION: every unclaimed slice of a later overlapping span is claimed as a hit of the later pattern (own value, own fingerprint), so a database URL whose username is a vendor-shaped id still loses its password. The opt-in `high_entropy_assignment` rule (`ScanOpts.highEntropy`) requires a 12+ char value that contains a digit AND clears 3.5 bits/char. Own minimal allowlist + `<ws>/.gbrain-scan-allow` per-finding overrides — deliberately NOT the repo's `.gitleaks.toml` (a public-repo CI fixture policy). Deliberately NOT patterns: `sb_publishable_`, Supabase project refs (identifiers, not credentials). Never spell a literal database URL with userinfo in this file's comments (`scripts/check-pg-url-redaction.sh`). Long lines are scanned in full (no length cap — a secret on a 1 MB minified line must still redact); what keeps that linear is bounded quantifiers on every shape whose value class could otherwise run to end-of-line — `db_url_credentials` (user ≤128 stopping at `:`/`/`; password 1–256 stopping only at whitespace, `@` and the string delimiters `"`/`'`, so unescaped `/ { } < > | ^ \` and backtick passwords redact), `jwt` (prebuilt so its boundary excludes `-` as well as `_`; segments ≤4096), `high_entropy_assignment` (≤64 identifier chars after the keyword, value ≤4096), and `PEM_BLOCK_RE`'s lazy body (≤`PEM_BODY_MAX_CHARS` = 16384; a longer body degrades to the header-only match) — plus a per-pattern `precheck` substring gate on the two catch-alls (`@`; `earer`/`EARER`, since an all-caps `BEARER` scheme is accepted), a carried next-newline position in `scanPemBlocks` (sticky -1, so the header-line count is O(text) even when thousands of hits sit ahead of a newline-free multi-megabyte tail), a lazily-allocated per-line claimed-char bitmap behind the first-wins dedupe (O(value) per hit), and a windowed `buildPreview` (whole line ≤160 chars; otherwise hit−40…+80, edges snapped outward to whole spans, every claimed span in the window spliced by position, so a preview never carries a sibling secret or a fragment). `redactFindings` (= `planRedaction` + `applyRedaction`) rebuilds the text by SPAN-SPLICE in one O(text + hits) pass over the claimed spans, and fills the UNCLAIMED gaps with a bounded echo pass: the values claimed by `bearer` and `high_entropy_assignment` form an echo dictionary (value → pattern; floors `ECHO_MIN_CHARS_BEARER` = 20 / `ECHO_MIN_CHARS_ENTROPY` = 12, values ≤ `ECHO_MAX_VALUE_CHARS` = 512, the first `ECHO_MAX_UNIQUE` = 64 unique values in claim order across BOTH patterns — a value past either cap is redacted at its claim, its echoes are the accepted miss), matched by a streaming merge over the ORIGINAL text — per value, the next occurrence at or beyond the emit cursor (`indexOf` resuming at the cursor, re-sought only once the cursor passes it), leftmost-longest at each step, emitted incrementally into the unclaimed gaps — so retained state is O(values) however long the text is (occurrences are never collected into a list: a repetitive tail against 64 short claimed values meant millions of candidate objects and hundreds of MB of RSS for 64 findings, ahead of message truncation) (never an alternation RegExp — O(text × Σ|values|) on prefix-sharing values; never over emitted tokens, so a value spelling a pattern name cannot nest). Echoes add no findings. `planRedaction` feeds a caller-supplied shared map (`RedactOpts.echoValues`) and `applyRedaction` reads it at apply time, so a multi-field document scrubs an echo in one field of a value claimed in another. Every other pattern redacts exactly what `scanText` reports (a value embedded past its boundary is left as-is; vendor shapes re-match on their own). Perf pins: `test/secret-scan-perf.test.ts`. Retrieval output is another consumer of its canonical scanner; that output boundary does not sanitize internal evaluation/provider inputs.-- `src/core/transcripts/render.ts` — session → conversation page(s) for `gbrain transcripts ingest`. `redactSession` is two-phase over message text, speaker labels, title and every raw-meta string, BEFORE any engine write: `planRedaction(…, { highEntropy: true, echoValues })` on every field into ONE session-wide echo dictionary, then `applyRedaction` per field, so a bearer or high-entropy value claimed in one message is scrubbed where it recurs bare in any other field, in either order; echoes add nothing to `redactionCount` (fail-closed: a scanner/pattern throw aborts the session), then the operator pattern file; nested raw-meta values are dropped. This is the only lane that opts into the entropy heuristic (pasted `.env` lines are most likely here). Rendering shares the imessage-slack anchor regex with the parser and escapes body lines that would forge it; long sessions split into `-pN` parts under the embed-skip threshold.+- `src/core/transcripts/render.ts` — session → conversation page(s) for `gbrain transcripts ingest`. `redactSession` is two-phase over message text, speaker labels, title and every raw-meta string, BEFORE any engine write: `planRedaction(…, { highEntropy: true, echoValues })` on every field into ONE session-wide echo dictionary, then `applyRedaction` per field, so a bearer or high-entropy value claimed in one message is scrubbed where it recurs bare in any other field, in either order; echoes add nothing to `redactionCount` (fail-closed: a scanner/pattern throw aborts the session), then the operator pattern file; nested raw-meta values are dropped. This is the only lane that opts into the entropy heuristic (pasted `.env` lines are most likely here). Rendering shares the imessage-slack anchor regex with the parser and escapes body lines that would forge it; long sessions split into `-pN` parts under the embed-skip threshold. Each `RenderedPart` carries the `frontmatter` it owns and its `body`; on re-ingest `runTranscriptsIngest` carries any other key already on the page (a review flag another tool added) onto the re-rendered part, except the re-derived safety and atom-scan markers (#5431, `test/transcripts-retitle.test.ts`).- `src/core/context/sensitivity-scan.ts` — composed detector for compiled-context entries (secret-scan → PII → path shapes → operator blocklist → operator pattern file). secret-scan OWNS credential-shaped families it also matches: a PII finding whose value (raw, or with the `Bearer ` keyword stripped) matches a secret finding's fingerprint is not reported twice; short bearer tokens under secret-scan's floor still surface as `pii:bearer`. Every family honors the same `.gbrain-scan-allow` fingerprint escape hatch.- `src/core/backup/status-file.ts` — ENGINE-FREE core of the monthly backup-coverage check: the cached verdict (`~/.gbrain/backup-status.json`, schema `gbrain-backup-status-v1`; fail-open load, atomic tmp+rename write, `invalidateBackupStatus()` fired by the fix paths — `bootstrap repo` receipt write, `sources harden`, `workspacePush` finish on ok when the cache carried a warn or failing/unpushed totals (a routine healthy push leaves an ok cache alone, preserving the monthly throttle)), the notice renderer (`backupNoticeText(s, 'human'|'aggregate')` — human ≤300 chars names assets, aggregate is counts-only for remote surfaces; the remote-privacy pin), and the bounded nag gate shared by every render channel (`backupNagGate(channel, s)` on `backup-nag-state.json`, OWN schema `gbrain-backup-nag-v1` — skillpack `loadNagState` would drop the extra fields on round-trip, so only the pure policy fns `decideNagAction`/`recordNagDisplay` are reused). Budget = AND of: 24h cross-channel dampener (`last_shown_at`), per-channel ceiling 3 per pseudo-version (`YYYY-MM(checked_at)` + no-remote fingerprint — month rollover or a changed verdict re-surfaces; a same-month recompute with an unchanged verdict stays quiet), and a global cap of 3 recorded impressions per month (`global_shown_count`/`global_month`). `backupNagReadOnlyConsult` is the OpenClaw context-engine's never-writes variant; `backupSpawnDue`/`recordBackupSpawn` debounce the session-end detached spawn (no sidecar file); `maybeEmitBackupNag` is the cli.ts startup rail body (skip set incl. serve/call/jobs; `BACKUP_LOCAL_ONLY <n>` machine marker + human line). Off switches: `GBRAIN_BACKUP_CHECK=0`, config `backup.check_enabled`; interval env `GBRAIN_BACKUP_CHECK_DAYS` > config `backup.check_interval_days` > 30; values <1 or non-numeric fall back to the 30-day default (`DAYS=0` never means "always stale"; `config set` rejects <1 outright). Tests: `test/backup-status-file.serial.test.ts`. Remote evidence is identity-bound and one-hour-limited; absent, stale, future-dated or inconsistent evidence cannot produce verified recovery counts, and failed refresh does not overwrite cache.- `src/core/backup/coverage.ts` + `src/core/backup/repository.ts` — local Git discovery and bounded remote readback. Trusted non-quiet local backup CLI/doctor may read at most eight refs per sweep with a shared eight-second budget, two-second subprocess timeout and no prompts, pushes or fetches; pending/oldest evidence rotates first. `currentBackupEvidence` retains one-hour readback only while source kind/id, physical Git directory, HEAD, branch, origin, push-status identity and clean tree match. `recoverable_repos` counts clean matching remote HEADs, while `configured_repos` counts configuration; expired, failed, mismatched, dirty or budget-exhausted observations cannot turn coverage green. New matching readback can supersede historical push failure without erasing it. Background/stdio are local-only; remote MCP doctor uses aggregate cache only. A failed refresh is degraded and does not overwrite a valid cache. Git covers committed files, not DB-only facts/config/credentials. Tests: `test/backup-verification.serial.test.ts`, `test/backup-coverage.serial.test.ts`, `test/e2e/backup-coverage-parity.test.ts`.@@ -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 — 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`.+- `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`). Concept refs are normalized before grouping (`conceptStemFor`: last path segment through `slugifySegment`, validated by `validatePageSlug`; one atom counts once per concept), so spelling variants share one page and no slug carries a space. Each page records `member_hash` (member atom slugs, titles and bodies plus the synthesis model); an unchanged hash on an `llm` or `deterministic_tier` page is skipped without spend (`details.skipped_unchanged`), and a budget or error fallback never replaces an existing `llm` narrative (`details.kept_existing_narrative`); fallback pages retry next cycle. Pinned by `test/cycle/synthesize-concepts-identity.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/commands-2.md b/docs/architecture/key-files/commands-2.mdindex 39d5049a19..1b4ccb54a5 100644--- a/docs/architecture/key-files/commands-2.md+++ b/docs/architecture/key-files/commands-2.md@@ -11,7 +11,7 @@ Doctor's embedding-dimension warning treats existing chunks as existing data eve- `src/commands/doctor.ts` — `gbrain doctor [--json] [--fast] [--fix] [--dry-run] [--index-audit] [--no-migrate]`: health checks. `checkPostgresCancellationDriver` (`postgres_cancellation_driver`) inspects a real reserved runtime owner through the shared cancellation helper: unsupported `discard()` is a typed local failure with a repair link, connection/deadline failure is a warning, and PGLite is exempt. The bounded reserve releases late arrivals and does not make general engine connect require cancellation, preserving broken-install diagnostics. `--no-migrate` keeps doctor observational: the CLI connects with `probeOnly` so a clean-or-behind schema is reported as-is instead of being auto-migrated before the checks run. The file is a façade carrying `buildChecks`/`runDoctor` and output rendering; the check-function library lives in bundles under `src/commands/doctor/checks/` plus four tail-cluster modules under `src/commands/doctor/` (see that entry), all re-exported here so the full surface is unchanged — structural guards pin its source text via `test/helpers/doctor-source.ts`, never by reading this file alone. Checks include `jsonb_integrity` + `markdown_body_completeness` (reliability), `schema_version` (fails loudly when `version=0`, routes to `gbrain apply-migrations --yes`; a version AHEAD of this client's `LATEST_VERSION` warns "upgrade this client"; and when the ledger reads current, a read-only `detectMissingColumns` diff from `src/core/schema-verify.ts` runs INSIDE the ledger-current branch — a PgBouncer-swallowed ALTER TABLE can advance `config.version` over a physically narrower table, so missing live columns downgrade the ok to a warn naming them with the `gbrain init --migrate-only` hint; diff failure is best-effort and the ledger ok stands; positional wiring pinned by `test/doctor-schema-column-diff.test.ts`), `upgrade_errors` (async `checkUpgradeErrors(engine)` over `~/.gbrain/upgrade-errors.jsonl`: the warn downgrades to an EXPLICIT status-ok line — never silence — only when the past failure is provably superseded, i.e. the running binary is at/past the failed target version AND the schema verifies current via `engine.getConfig('version')`; a missing engine or unverifiable schema keeps the warn, fail-closed, because `self-upgrade` swaps the binary before `post-upgrade` runs migrations and the binary alone can lie; pinned by `test/doctor-upgrade-errors.test.ts` + `test/doctor-upgrade-errors-stale.test.ts`), `queue_health` (Postgres-only: stalled-forever active jobs started_at > 1h, waiting-depth-per-name > threshold default 10 via `GBRAIN_QUEUE_WAITING_THRESHOLD`, and dead-lettered subagent jobs with `last_error` matching the `prompt_too_long` classifier in last 24h), `sync_failures` (`[CODE=N, ...]` breakdown for unacked-warn + acked-ok; severity comes from the shared `decideSyncFailureSeverity` in `src/core/sync-failure-ledger.ts` so the LOCAL and REMOTE/thin-client doctor surfaces can never drift — a stuck bookmark escalates to FAIL once an OPEN failure has blocked past the staleness window or ≥10 files block, while already `auto_skipped` rows stay a visible WARN), `rls_event_trigger` (healthy `evtenabled` set is `('O','A')` only; fix hint `gbrain apply-migrations --force-retry 35`), `graph_coverage` (short-circuits to ok when `SELECT COUNT(*) FROM pages WHERE type IN ('entity','person','company','organization')` returns 0; WARN hint is `gbrain extract all`), `embedding_column_registry` (probes each declared column via Postgres `format_type(atttypid, atttypmod)` to catch dim mismatch with a paste-ready `gbrain config set embedding_columns '{...}'` hint, probes HNSW index presence via `pg_indexes`, computes default-column population via `COUNT(*) FILTER (WHERE <col> IS NOT NULL) / COUNT(*)` warning below 90% except empty brains where chunk_count=0 short-circuits to ok; PGLite parity via `executeRaw`), and `skill_brain_first` (walks SKILL.md via `autoDetectSkillsDirReadOnly`, calls `analyzeSkillBrainFirst()` from `src/core/skill-brain-first.ts` per file with structured `Check.issues[]`; warn states `missing_brain_first`/`brain_first_typo`, ok states `compliant_callout`/`compliant_phase`/`compliant_position`/`exempt_frontmatter`/`no_external`; snapshot+diff audit at `~/.gbrain/audit/skill-brain-first-YYYY-Www.jsonl`). `--fix` delegates inlined cross-cutting rules to `> **Convention:** see [path](../path).` callouts via `src/core/dry-fix.ts` (and MISSING_RULE_PATTERNS for the brain-first callout); `--fix --dry-run` previews. `--index-audit` (Postgres-only, informational, no auto-drop) reports zero-scan indexes from `pg_stat_user_indexes`. Every DB check runs under a progress phase; `markdown_body_completeness` runs under a 1s heartbeat. `runDoctor` uses `autoDetectSkillsDirReadOnly` (from `src/core/repo-root.ts`; install-path fallback so `cd ~ && gbrain doctor` finds bundled skills); `--fix` carries a D6 install-path safety gate that refuses auto-repair when `detected.source === 'install_path'` (would rewrite the bundled tree). The Lane D supervisor check at `doctor.ts:1011-1043` consumes `summarizeCrashes(events)` from `src/core/minions/handlers/supervisor-audit.ts` (warn at `>=1` real crash; ok message has `clean_exits_24h=N`; warn message has `runtime=A oom=B unknown=C legacy=D` per-cause breakdown) so OOM/runtime/unknown crashes are distinguishable from clean code=0 worker drains; cross-surface parity with `gbrain jobs supervisor status` is pinned by source-grep wiring assertions requiring the breakdown substrings in BOTH `doctor.ts` and `jobs.ts`. `checkSyncFreshness` (exported, in `runDoctor` local + `doctorReportRemote` thin-client) is a staleness probe: warns at 24h, fails at 72h or never-synced; future-`last_sync_at` warns ("clock skew") instead of falling through ok; env overrides `GBRAIN_SYNC_FRESHNESS_WARN_HOURS`/`GBRAIN_SYNC_FRESHNESS_FAIL_HOURS` (invalid fall back with once-per-process stderr warn via `_resolveSyncFreshnessHours`); failure messages embed `source.id` so the printed `gbrain sync --source <id>` matches. A source holding a LIVE, non-expired per-source sync lock (`inspectLock(engine, syncLockId(source.id))` from `src/core/db-lock.ts`) is reported as actively syncing (the message names the holder pid + host) and counted in `synced_recently_count`, NOT flagged stale — the live lock is the only honest in-progress signal (checkpoint banking can't distinguish in-progress from wedged: a blocked sync banks its files but writes no anchor). A blocked/failed sync's process has exited (no lock row) and a wedged holder stops refreshing (TTL lapses), so either falls through to the stale path and is never masked; the dynamic `db-lock` import is swallowed to a no-op on a stub engine or pre-lock-table brain, so this can only ADD an in-progress verdict, never suppress a real stale one. The in-progress note is appended to whatever verdict the buckets produce and is empty when nothing is syncing, so steady-state messages stay byte-for-byte unchanged. It has a `localOnly`-gated git short-circuit (`runDoctor` passes `localOnly: true`; `doctorReportRemote` runs in the HTTP MCP server `src/commands/serve-http.ts` and keeps default `false` so that path never walks DB-supplied `local_path` via subprocess — trust boundary). The local predicate mirrors sync's "do work?" gate (HEAD == `last_commit` AND working tree clean via `requireCleanWorkingTree: 'ignore-untracked'` so a quiet repo with only untracked dirs is `unchanged` not SEVERE, AND `chunker_version === CURRENT`); the inline SELECT carries `last_commit + chunker_version + newest_content_at`. The REMOTE path computes lag via `lagFromContentMs(newest_content_at, lastSync, now)` from the stored column, NO git subprocess; LOCAL fall-through and the `< 0` clock-skew check stay on raw wall-clock. Three-bucket count math populates `Check.details = {unchanged_count, synced_recently_count, stale_count}` with the invariant `sum === sources.length`. `checkCycleFreshness` is DELIBERATELY NOT git-short-circuited or content-relativized (`last_commit == HEAD` can't answer "did the full cycle complete?"; a sync can succeed while later cycle phases fail; different axis `last_full_cycle_at`). Pinned by `test/doctor.test.ts` (incl. the IRON-RULE guard banning stale verb names, the sync_freshness boundary matrix, the D4 guard verifying git probes are NEVER called when `localOnly` is unset/false, the three-bucket invariant, and the untracked-folders / remote-never-shells-out trust-boundary cases). `pglite_data_dir` check: fs-only check that runs when a PGLite brain FAILS to connect (`!fastMode && !engine && config.engine === 'pglite'`, placed after `orphan_clones`, before the DB-checks gate): `computePgliteDataDirCheck(dataDir, diagnosis)` (exported pure fn, `computeWorkerOomLoopCheck` convention) maps the `inspectPgliteDataDir` verdict to a Check — corruption-likely/looks-healthy-but-unopenable/unsupported-layout → `fail` naming `gbrain pglite-repair --dry-run`/`--yes` or the rebuild path, live-lock/missing-dir → `warn`; all `remediation_status: 'human_only'` (Minion remediation needs the DB that is down). Escalates when ≥2 repair attempts failed inside 7 days (unclean-shutdown genesis still active → engine-switch pointer) and reports retained backup-dir inventory (orphan_clones disk-visibility class). Registered in `doctor-categories.ts` OPS_CHECK_NAMES. Pinned by `test/doctor-pglite-datadir.test.ts`. silent-failure checks: `content_hash_duplicates` (single GROUP BY over `(source_id, content_hash)` with FILTER aggregates — never N² — flagging hash groups that hold BOTH a bare and a path-prefixed slug, the wrong-import-root pattern; warn carries sample pairs + the `pages delete` → `purge-deleted --older-than 0` remediation); `undeclared_db_only_pages` (per source with a local repo: markdown pages with no backing file outside every declared + derive-phase-default db_only prefix — the one check deliberately allowed to stat the repo); `db_only_collector_collision` (configured recipe `output_paths` inside a declared db_only dir — auto-gitignore means sync AND import silently skip the collector's files; same warning fires in sync's `manageGitignore` at config-write time). All warn-level, engine-parity pinned by `test/e2e/doctor-silent-death-parity.test.ts`; units in `test/doctor-silent-death-checks.test.ts`. `graph_signals_coverage` check wired into both `runDoctor` (local) and `doctorReportRemote` (HTTP/JSON thin-client path). Reads `search.graph_signals` config first, falls back to mode default; silent `ok` when disabled. Computes inbound link coverage on the page set; warns at <10% with `gbrain extract all` fix hint; `ok` at ≥30% ("fire on most queries") and 10-29% ("fire occasionally"), each with the percentage embedded. Pinned by cases in `test/doctor.test.ts`. `subagent_provider` check (layer 3 of 3). Resolves subagent model config in runtime order (`models.subagent` > `models.default` > `models.tier.subagent` > built-in default) and warns when the selected model lacks native tool-loop capability (message names the bad value + paste-ready fix `gbrain config set models.tier.subagent anthropic:claude-sonnet-4-6`); also warns when `models.default` would sneak `subagent` into a non-Anthropic provider via tier inheritance. OK when subagent tier resolves to Anthropic. Tests in `test/doctor.test.ts`. `computeWorkerOomLoopCheck(engine)` is the single authoritative OOM-loop signal, unioning supervised `summarizeCrashes(readRecentSupervisorEvents(24)).by_cause.rss_watchdog` (cross-week read via `readRecentSupervisorEvents` so a Monday window can't lose Sunday) + bare-worker `minion_jobs error_text='aborted: watchdog'` count (Postgres-only; the same source `queue_health` subcheck 3 reads). Cap comes from the latest `rss_watchdog_loop` breaker alert's `max_rss_mb`, else `resolveDefaultMaxRssMb()` fallback. fail at breaker-tripped or oomKills≥5, warn at ≥1, null otherwise. `computePoolReapHealthCheck(engine)` is the Postgres-only `pool_reap_health` check reading `readRecentPoolRecoveries(1)` — fail when reconnect failures>0 (reconnect throwing is the actionable signal), warn at ≥10 reaps/hr (pooler thrash), null otherwise. Both registered in `buildChecks` after the `supervisor` block. The `supervisor` causeStr carries `rss=N (see worker_oom_loop)` and `queue_health`'s watchdog message cross-references `worker_oom_loop`. `DoctorReport.top_issues` + the cause-ranked render header. `worker_oom_loop` + `pool_reap_health` registered under ops in `doctor-categories.ts`. Pinned by `test/doctor-worker-oom-loop.test.ts`, `test/doctor-pool-reap-health.test.ts`. `supervisor_singleton` check, a SEPARATE check from `supervisor` (same split precedent as the niceness check) so a singleton-divergence warn can't clobber the crash/liveness precedence. Runs only when a `started` supervisor event was seen in the last 24h and a live engine is available. Reads the queue-scoped DB lock row (`gbrain_cycle_locks WHERE id = supervisorLockId(queue)`) and compares the lock holder (`holder_host:holder_pid`) against the local pidfile holder via the pure `classifySupervisorSingleton`. `mismatch` → warn (a second supervisor may be running with a different `--max-rss`; message names both holders, the effective cap from the `started` event's `max_rss_mb`, and the fix `gbrain jobs supervisor stop`); `single` → ok (names holder + cap); `no_lock` → no check emitted. Best-effort try/catch (silent skip on brains without the lock table). Registered under ops in `doctor-categories.ts` as `supervisor_singleton`. Pinned by `test/supervisor-db-lock.test.ts` + `test/doctor.test.ts`. `checkBatchRetryHealth`: `batch_retry_health` check surfacing Supavisor circuit-breaker incidents. Wired into both `runDoctor` (local) and `doctorReportRemote` (thin-client). Reads last 24h. States: `ok` (zero exhausted in 24h OR <3 from a single site), `warn` (>=3 same-site OR >=5 cross-site), `fail` (>=20 sustained breaker). Surfaces bad `GBRAIN_BULK_*` env at doctor startup. Corrupt-JSONL tolerant. Paste-ready fix hints in every warn/fail message. Also reads `readRecentDbDisconnects(24)` and appends `Disconnect-call audit: N call(s) in 24h (most recent caller: <frame>).` to ALL three message paths so connection-incident signal is greppable from one `gbrain doctor --json` call (module-import wrapped in try/catch so older brains without the audit file degrade silently). Pinned by `test/doctor-batch-retry.test.ts` (10 cases). three checks wired into `runDoctor()` and the JSON envelope, all warn-only with paste-ready fix hints. (1) `checkSourceRoutingHealth(engine)` scans up to 200 pages on federated brains and flags pages whose `source_id` doesn't match what `resolveSourceWithTier()` would have picked for their `source_path`; single-source brains short-circuit to `ok`; the 200-page cap is total across the brain so doctor stays under 5s. (2) `checkOauthConfidentialHealth(engine)` probes registered confidential clients for `/token` reachability. (3) `checkAutopilotLockScope()` (pure, no engine) compares the resolved lock path to `$GBRAIN_HOME`; warns when set but the lock lives elsewhere, with a PID-safe inspection hint (`kill -0 <pid>` before deletion). Pinned by `test/doctor-v0_37_7_checks.test.ts`. `buildChecks(engine, args, dbSource, connectError?): Promise<Check[]>` exported as a test seam; the optional `connectError` is the connect failure captured by the CLI's dead-DB fallback, which the null-engine path turns into a SYNTHESIZED classified `connection` fail entry (so `checks[name=="connection"]` exists in every failure shape — smoke-test branches on it). The `connection` check's failure path classifies via `src/core/pg-access-classify.ts` into a redacted message + `details: {reason, transient, fix_hint}` naming `gbrain db-repair` (deliberately NOT `remediation[]`/`makeRemediationStep` — that lane feeds `--remediate`, whose Minion jobs need the very DB that's down; applicator boundary: `--remediate` = brain-DATA quality with a live engine, `db-repair` = DB ACCESS engine-free). The URL-only `pgbouncerPrepareCheck` helper and the engine-free `db_repair_recurrence` check run BOTH before the connection check and in the dead-DB filesystem lane; `pglite_scale` (engine-fit, warn at ≥1000 pages on pglite) runs in the DB phase. `computeDoctorReport(checks, extras?)` accepts optional `{engine, db_url_source}` which land as additive `DoctorReport.engine` / `DoctorReport.db_url_source` JSON fields (schema_version stays 2). `runDoctor` is a thin wrapper: `buildChecks → computeDoctorReport → render + process.exit`. All 10 `process.exit` sites stay in the wrapper; the two early-return paths (no engine, connection failure) return partial check lists instead of inline exits (observable output identical). Pinned by `test/doctor-behavioral.test.ts` (13 cases: pure aggregation math over `computeDoctorReport`, orchestrator cases for `--fast` skip set + `--json` flag + no-engine partial path + snapshot of load-bearing check names) and `test/doctor-cli-smoke.serial.test.ts` (1 subprocess case spawning `bun run src/cli.ts doctor --json` against a fresh PGLite tempdir, asserting schema_version=2 envelope, status enum, non-empty checks array — the render-path coverage buildChecks-only tests miss; quarantined `.serial` because PGLite write-locks don't play with parallel runners). three checks wired into `runDoctor()` and the JSON envelope: `oversized_pages` (warns on pages exceeding `content_sanity.bytes_warn`), `scraper_junk_pages` (warns on live DB pages matching any junk pattern that escaped ingest), and `content_sanity_audit_recent` (reads the last 7 days of audit events, aggregates by pattern+source). Default scans the 1000 most-recent pages; `--content-audit` opts into a full scan. All three warn-only with paste-ready fix hints (junk → `gbrain sources audit <id>` + `git rm` source-of-truth, oversize → split or accept). two checks wired into `runDoctor()` + the JSON envelope: `quarantined_pages` (counts pages carrying the `quarantine` marker via `engine.executeRaw` JSONB `?` existence, works on PGLite + Postgres; warn-only with a `gbrain quarantine list` hint) and `flagged_pages` (counts `content_flag` pages — searchable but odd; warn-only). Both skip gracefully (status ok, "Skipped") on engines/brains where the probe errors. Pinned by `test/doctor.test.ts`. `home_dir_in_worktree`: filesystem check walking up from `gbrainPath()` toward `$HOME` looking for a `.git` directory (main repo) or `.git` file (linked worktree pointer; Conductor + git-worktrees topology). Walk terminates at `$HOME` so a `.git` above the user's home doesn't false-positive. Honors `GBRAIN_HOME` (appends `.gbrain` to the override). Warn (not fail) with worktree-root path + paste-ready fix pointing at `GBRAIN_HOME` override or moving the brain. `--remediation-plan [--json] [--target-score N]` prints what would run (stable `id`, `idempotency_key`, `severity`, `est_seconds`, `est_usd_cost`, `depends_on`); `--remediate [--yes] [--target-score N] [--max-usd N]` submits each plan step as a Minion job in dependency order, re-checking score between steps. `--target-score N` defaults to 90; refuses to start when target exceeds `maxReachableScore()` and lists what's missing. `--max-usd N` is the cron-safety guard — submission refuses when the plan's `est_total_usd_cost` exceeds the cap. JSON envelope adds a `Check.remediation` field (additive, schema_version unchanged). Pinned by tests in `test/doctor.test.ts`. 4 checks: `abandoned_threads`, `calibration_freshness`, `grade_confidence_drift` (mitigation surface; math ships later), `voice_gate_health`. Schema health is a two-check pair: `schema_version` resolves through `schemaVersionHealth` (`src/core/schema-version-health.ts`, shared with the remote doctor report; a DB AHEAD of the client warns with an upgrade-this-client hint rather than suggesting migrations), and on ledger-current brains a read-only `schema_columns` check diffs live columns against the expected schema (`detectMissingColumns`, dynamically imported inside the ledger-current branch — positional guard in `test/doctor-schema-column-diff.test.ts`) and warns naming the missing columns with the `gbrain init --migrate-only` hint.-- `src/commands/doctor/` — the doctor module directory (the meat behind the `doctor.ts` façade). `checks/` holds the check-function library in bundles grouped by concern (`core-health.ts`, `queue-jobs.ts`, `extraction-sync.ts` (its `atom_provenance_drift` check scopes drift to page-bound atoms and splits it into `source_changed` / `source_gone`; atoms with no `source_slug` — transcript-origin `source_path`-only rows, whose hash is over a file and whose page liveness cannot be resolved by slug — are reported as their own `slug_unbound` count and never enter the drift total or the WARN ratio), `graph-embedding.ts`, `search-eval.ts`, `calibration.ts`, `consolidation-cycle.ts`, `pglite-worker.ts`, `routing-federation.ts`, `verbs-reflex.ts`, `stale-mentions.ts`, `timeline-history.ts` (`timeline_history`: database-only timeline rows, bounded to 2,000 pages / 10 s with exact-or-lower-bound counts, kept non-round-trippable rows informational, repair `gbrain repair timeline`), `derived-visibility.ts` (`derived_visibility`: atoms and synthesized concepts without explicit visibility or looser than their origin, one exact aggregate, repair `gbrain repair visibility`), `engine-fit.ts` — the last carrying `pglite_scale` + the engine-free `db_repair_recurrence` over the db-repair receipts); `schema-pack-checks.ts`, `report-remote.ts`, `bootstrap-checks.ts`, and `skill-checks.ts` are the four tail-cluster modules (schema-pack checks, the remote/thin-client doctor report, bootstrap checks, skill checks). All are re-exported by the façade. Structural guards that pin doctor source text load it through `test/helpers/doctor-source.ts`: `doctorSource()` concatenates the façade plus every `src/commands/doctor/**/*.ts` (façade first, then sorted) so a module move can never take a pinned string out of a guard's sight; `doctorFileSource(rel)` reads one named file for positional/ordering assertions; the helper also feeds the `doctor-source-helper` detector in `scripts/classify-tests.ts`. `facadeExpansion` in `scripts/generate-flag-registry.ts` keeps this directory on the doctor command's flag-scan surface.+- `src/commands/doctor/` — the doctor module directory (the meat behind the `doctor.ts` façade). `checks/` holds the check-function library in bundles grouped by concern (`core-health.ts`, `queue-jobs.ts`, `extraction-sync.ts` (its `atom_provenance_drift` check scopes drift to page-bound atoms and splits it into `source_changed` / `source_gone`; atoms with no `source_slug` — transcript-origin `source_path`-only rows, whose hash is over a file and whose page liveness cannot be resolved by slug — are reported as their own `slug_unbound` count and never enter the drift total or the WARN ratio), `graph-embedding.ts`, `search-eval.ts`, `calibration.ts`, `consolidation-cycle.ts`, `pglite-worker.ts`, `routing-federation.ts`, `verbs-reflex.ts`, `stale-mentions.ts`, `timeline-history.ts` (`timeline_history`: database-only timeline rows, bounded to 2,000 pages / 10 s with exact-or-lower-bound counts, kept non-round-trippable rows informational, repair `gbrain repair timeline`), `derived-visibility.ts` (`derived_visibility`: atoms and synthesized concepts without explicit visibility or looser than their origin, one exact aggregate, repair `gbrain repair visibility`), `engine-fit.ts` — the last carrying `pglite_scale` + the engine-free `db_repair_recurrence` over the db-repair receipts); `schema-pack-checks.ts`, `report-remote.ts`, `bootstrap-checks.ts`, and `skill-checks.ts` are the four tail-cluster modules (schema-pack checks, the remote/thin-client doctor report, bootstrap checks, skill checks). All are re-exported by the façade. Structural guards that pin doctor source text load it through `test/helpers/doctor-source.ts`: `doctorSource()` concatenates the façade plus every `src/commands/doctor/**/*.ts` (façade first, then sorted) so a module move can never take a pinned string out of a guard's sight; `doctorFileSource(rel)` reads one named file for positional/ordering assertions; the helper also feeds the `doctor-source-helper` detector in `scripts/classify-tests.ts`. `facadeExpansion` in `scripts/generate-flag-registry.ts` keeps this directory on the doctor command's flag-scan surface. Two read-only derived-data checks live beside them: `timeline-orphans.ts` (`timeline_orphans`, samples 500 pages for rows an earlier page version produced that the current text no longer does; fix is `gbrain extract timeline --prune-orphans`) and `slug-collisions.ts` (`slug_collisions`, walks each live source checkout with `collectSyncableFiles` and reports paths that map to one slug plus the indexed one; sources without a checkout are skipped).- `src/commands/doctor/checks/default-source-path.ts` — the gathering wrapper on the doctor surface: reads the `default` sources row, page counts (live + file-backed), `sync.repo_path` resolution, and the leak-guard collision, then delegates the verdict to `assessDefaultSourcePath`. Only gathers the fallback-topology inputs when the pointer is actually null; returns null for the skip verdict.diff --git a/docs/architecture/key-files/commands-3.md b/docs/architecture/key-files/commands-3.mdindex e5658f7fdd..e3649db915 100644--- a/docs/architecture/key-files/commands-3.md+++ b/docs/architecture/key-files/commands-3.md@@ -31,7 +31,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/extract-conversation-facts.ts` + `src/core/cycle/conversation-facts-backfill.ts` — bulk fact extraction for long-form conversation pages. Walks conversation/meeting/slack/email/imessage/imessage-daily pages, splits them into time-windowed segments (30-min gap or 30-msg cap), prepends a topical/temporal header, and uses the strict `extractFactsFromTurnWithOutcome()` path so provider and output failures remain retryable instead of becoming successful empty pages. Invariants: **strict per-source core** (`runExtractConversationFactsCore({sourceId, ...})` always takes one sourceId; CLI + cycle phase each do their own multi-source iteration because `PHASE_SCOPE='source'` is taxonomy-only); **bounded two-phase enumeration** (paginated `listPages({type, sourceId, limit:10})`; per-page body cap `MAX_PAGE_BODY_BYTES=25MB`); **page-global `row_num` accumulator** (the facts unique index is `(source_id, source_markdown_slug, row_num)`); **versioned snapshot-bound outcomes** (`cli:extract-conversation-facts:terminal:v2` for complete pages and a separate `non-extractable:v2` source for recognized pages with no eligible segment); **operation checkpoints are scheduling hints only** and never suppress a replay without a matching v2 outcome; **optional `opts.budgetTracker?`** is used as-is, while an absent tracker is created with `maxCostUsd`; **body reads cover compiled truth, timeline, and configured raw-transcript sidecars**; **`facts.extraction_enabled` kill-switch** with `--override-disabled`; **`--types LIST` allowlist** (`conversation,meeting,slack,email,imessage,imessage-daily`); **`--background` via `maybeBackground`**; and **speaker-shaped-fold decline** — when the parse reports `unrecognized_headings` containing a speaker-shaped label (1-2 title-cased words, not in the doc-heading stoplist — the stoplist gates the DECLINE only, so a miss is warn-noise, never data loss) AND the parse produced fewer than two distinct speakers, the page is declined instead of extracted under wrong attribution: counted in `pages_skipped_unrecognized_speaker` (Result/CLI/cycle surfaces), warned to stderr with the folding pattern id, and deliberately NON-terminal (no durable audit row and no orphan cleanup, so a future parser/pattern fix retries the page); multi-speaker pages with folds proceed warn-only. The companion `conversation_facts_backfill` cycle phase is default-off, iterates every source, and enforces per-source plus brain-wide cost and wall-time caps. Migration v94 provides the partial facts index used by outcome lookups. `computeConversationFactsBacklogCheck` reports fresh completed, scanned-not-extractable, and unfinished counts separately, warning when more than 10 eligible pages lack a fresh v2 outcome. `sources audit` exposes `facts_backfill_estimate: {pages, est_segments, est_cost_usd, types}`. Pinned by `test/extract-conversation-facts.test.ts` and `test/doctor-conversation-facts-backlog.test.ts`. `--workers N` for LLM-bound fact extraction over conversation pages, with a per-page advisory lock via `src/core/db-lock.ts:withRefreshingLock` (lock id `extract-conversation-facts:<source>:<slug>`, TTL `PER_PAGE_LOCK_TTL_MINUTES=2` with 20s refresh via `Math.max(15s, 120s/6)`; `LockUnavailableError` triggers skip-and-continue with rate-limited log per (source, minute) + `pages_lock_skipped` counter + CLI exits 3 when non-zero AND no hard failures). `deleteOrphanFactsForPage(engine, sourceId, slug)` provides delete-orphans-first replay safety — wipes facts from a prior crashed run for this (sourceId, slug) before re-extracting, so a terminal audit row can never certify a partial insertFacts failure. `assertFactsEmbeddingDimMatchesConfig(engine)` is the startup preflight (throws `FactsEmbeddingDimMismatchError` with paste-ready ALTER hint BEFORE the first insert; cached per engine via WeakMap). Result type carries `pages_lock_skipped` + `orphan_facts_cleaned`. Additive `pages_skipped_unparsed`, `pages_skipped_type_mismatch`, `pages_skipped_insufficient_turns`, and `pages_skipped_since` explain the unchanged `pages_skipped` aggregate across core, CLI, workers, and cycle sources; durable completion remains separate. `--dry-run` stops after segmentation, with no parser-fallback, extractor, or embedding calls and no durable knowledge/checkpoint/receipt/rollup writes. The narrow `python-dict-utterance` registry format and its quoted/nested-example rejection are documented in [conversation parser patterns](../conversation-parser-patterns.md). Checkpoint state is a shared `cpMap: Map<slug, endIso>` (NOT a per-page-mutated `cpEntries: string[]`) so atomic `Map.set` survives parallel workers. Minion handler `extract-conversation-facts` in `src/commands/jobs.ts` round-trips `workers` via `job.data.workers` for `--background --workers 20`. Cycle config key `cycle.conversation_facts_backfill.workers` (default 1; opt-in concurrency under brain-wide cost + walltime caps). Pinned by `test/extract-conversation-facts-diagnostics.serial.test.ts` (pool workers, per-page lock skip + exit 3, delete-orphans-first replay, D15 preflight, `--workers` round-trip) + the existing extract-conversation-facts behavioral tests. with `src/commands/doctor.ts` durable outcome authority: page completion survives operation-checkpoint GC through versioned terminal audit rows (`cli:extract-conversation-facts:terminal:v2`), while recognized pages with no eligible segment use the separate `cli:extract-conversation-facts:non-extractable:v2` source. Each outcome is bound to the exact parsed snapshot: regular pages use `content_hash` plus the UTC effective date; raw-conversation sidecars and legacy null-hash pages use a canonical SHA-256 over every parser-relevant input. Selection checks the token before locking, refetches under the lock, and verifies it again before writing the outcome, so an edit cannot be certified by stale work. The strict extraction path treats provider, refusal, truncation, malformed/schema-invalid output, segment-write, cleanup, and terminal-write failures as unfinished work; bulk failures increment `pages_failed`, affect CLI/cycle receipts and exit status, and never advance the legacy checkpoint. Checkpoints are only a scheduling hint: a slug without a matching v2 outcome is replayed delete-first. `no_match`, errors, cancellation, and dry runs never become durable negatives. Result, CLI, cycle, and doctor surfaces keep completed, scanned-not-extractable, unfinished, failed, and lock-skipped counts separate. See [Conversation backfill durable outcomes](../../operations/conversation-backfill-outcomes.md) for the operator and maintainer contract. Pinned by `test/extract-conversation-facts.test.ts` and `test/doctor-conversation-facts-backlog.test.ts`. Managed bulk calls, including segmentation-only previews, refuse before queue or provider work; they are listed separately from the supported coordinated fact operation.-- `src/commands/extract.ts` — `gbrain extract links|timeline|all [--source fs|db] [--source-id <id>]`: batch link/timeline extraction. fs walks markdown files, db walks pages from the engine (mutation-immune snapshot iteration; use for live brains with no local checkout). The full fs/db walks buffer candidates 100 at a time and flush via `addLinksBatch` / `addTimelineEntriesBatch` (additive); `ON CONFLICT DO NOTHING` enforces uniqueness at the DB layer, `created` counter returns real rows inserted. `ExtractOpts.slugs?: string[]` enables incremental extract via `extractForSlugs()` (single combined links+timeline pass); the cycle path threads sync's `pagesAffected` through. Every per-slug extractor — `extractForSlugs` (the cycle's incremental pass) and the two sync hooks `extractLinksForSlugs` / `extractTimelineForSlugs` — resolves each requested slug through `resolveSlugRelPath`: the `buildSlugPathIndex(walkMarkdownFiles(dir))` index first, then — only on an index miss — the legacy `join(dir, slug + '.md')` existence check. The index is the primary because `pathToSlug` lowercases and slugifies, so a reconstructed path only finds files whose names are already slugs, and every other file looked deleted and was skipped in silence; the legacy fallback stays because sync ADMITS files the walker never emits (`_`-prefixed names, dot-dirs waived via `sync.include_hidden`) and those slugs still round-trip to their real path — without it such a page imports with no edges. On a slug collision the index prefers the file whose name IS the slug (else the first walked entry), so resolution never depends on directory-read order. The per-slug extractors reconcile like `put_page`: each page's own markdown-derived links are replaced through `replacePageFileLinks` (`src/core/link-reconciliation.ts`, `replaceDerivedLinks` with `preserveExisting`; other producers survive, a page with no row counts as processed with no links, and a failed replacement is reported on stderr and leaves the page stale), and `retractRemovedTimelineEntries` (`src/core/timeline-extract.ts`) deletes the exact (date, source, summary) rows the page's previous version produced that its current text no longer does. `loadSlugAliasTargets` adds renamed pages' old slugs (`slug_aliases`) to `allSlugs` so links written before a rename resolve to the current slug. Both return `ExtractForSlugsResult { created, processed }`; `processed` is the subset actually read, and the shared `slugsSafeToStamp(links, timeline)` intersection is what every caller may stamp. Stamping the full requested set marks a silently-skipped page fresh and hides it from `extract --stale` permanently. All three call sites (`src/commands/sync.ts`, `src/core/github-source.ts`, `src/core/google/google-source.ts`) stamp the intersection. `walkMarkdownFiles(brainDir)` still runs to build `allSlugs` for link resolution. `--source-id <id>` scopes extraction to one source on federated brains (resolved via `resolveSourceWithTier()` before any SQL; failures hint `gbrain sources list`). `gbrain extract --stale [--source-id <id>] [--catch-up] [--dry-run] [--json]` branch (`extractStaleFromDB`) — incremental DB-source link+timeline sweep over pages whose `pages.links_extracted_at` watermark is stale. Embedded callers (the cycle) pass `quiet: true` so the helper writes nothing to stdout, including its JSON result; standalone CLI output is unchanged. In `jsonMode` every fs path, `extractForSlugs` included, reports a dropped flush as a `{event:'batch_error'}` stderr line rather than going silent. Stale predicate (shared by both engines + the doctor check): `links_extracted_at IS NULL OR links_extracted_at < LINK_EXTRACTOR_VERSION_TS::timestamptz OR updated_at > links_extracted_at` (the `updated_at` arm catches MCP `put_page` / `sync --no-extract` edited-since-extract). Three `BrainEngine` methods (parity in postgres-engine.ts + pglite-engine.ts + bootstrap probes): `countStalePagesForExtraction(opts?)`, `listStalePagesForExtraction({batchSize, afterPageId?, sourceId?, versionTs?})` (returns page CONTENT to avoid N+1 `getPage`; `rowToStalePage` in utils.ts maps the row, `StalePageRow` in types.ts), `markPagesExtractedBatch(refs, defaultExtractedAt)` (3-array unnest `slug[],source_id[],ts[]`; each ref may carry its own `extractedAt`). `STALE_BATCH_SIZE` default 25 (`GBRAIN_EXTRACT_STALE_BATCH`; small because page bodies are unbounded — the LIMIT is the only fetch-time memory bound); `STALE_TIME_BUDGET_MS` 30min wall-clock (`--catch-up` removes the cap). Non-swallowing flush: link/timeline flush throws propagate and abort the batch; stamp LAST so a crash leaves pages unstamped and they re-extract idempotently (`addLinksBatch` ON CONFLICT DO NOTHING + timeline dedup). `extractStaleFromDB` stamps with each row's READ `updated_at` (not `now()`), so a concurrent edit during the sweep keeps the page stale and it re-extracts next run rather than marked fresh-with-old-content. On a managed-persistence brain each page publishes its derived links, the coordinator's canonical timeline tuples (`canonicalTimelineRows`, insert-only) and its watermark in one revision-bound `withCoordinatedWrite` transaction; a page edited since the read is skipped and stays stale. Tests: `test/extract-stale-managed.test.ts`. Source-correct stamping at DB-extract sites via `stampExtracted` (best-effort, never throws); `extractLinksFromDB` only stamps the combined watermark when `subcommand === 'all'` (a links-only run must not hide timeline staleness). `LINK_EXTRACTOR_VERSION_TS` lives in `src/core/link-extraction.ts` (bump like `CHUNKER_VERSION` to invalidate all prior stamps). Migration v112 (`pages_links_extracted_at`) adds nullable `TIMESTAMPTZ` + composite `(source_id, links_extracted_at)` index (CONCURRENTLY + invalid-remnant pre-drop on Postgres, plain on PGLite), NO backfill so the real backlog surfaces on first `gbrain doctor`. Schema parity in schema.sql + pglite-schema.ts + schema-embedded.generated.ts + `REQUIRED_BOOTSTRAP_COVERAGE`. `src/commands/doctor.ts:checkLinksExtractionLag` (the `links_extraction_lag` check, also in `doctorReportRemote`) warn-only by default (>`GBRAIN_EXTRACTION_LAG_WARN_PCT`, default 20%; shared `EXTRACTION_LAG_WARN_PCT_DEFAULT` + `EXTRACTION_LAG_MIN_PAGES=100` + exported `_resolveEnvNumber`), hard-fails only when `GBRAIN_EXTRACTION_LAG_FAIL_PCT` is set; vacuous-skips <100 pages (no `--source`); pre-v112 brains graceful-skip via `isUndefinedColumnError`; strictly a SQL COUNT (safe on remote/thin-client). `src/commands/sync.ts` carries `--no-extract` (threaded through single-source + `--all` + `syncOneSource`), stamps `links_extracted_at` at the inline-extract call site for the slugs the extractors actually read, and `maybeExtractionNudge` prints a one-line stderr nudge after a `synced | first_sync | up_to_date` sync that leaves a backlog (`shouldNudgeAfterSync` pure predicate; `GBRAIN_SYNC_NO_EXTRACT_NUDGE` suppresses). `src/core/retry.ts` lists `'extract.stale'` in `BATCH_AUDIT_SITES`; `src/core/doctor-categories.ts` lists `links_extraction_lag` in `BRAIN_CHECK_NAMES`. Pinned by `test/extract-stale.test.ts` (incl. edited-after-stamp + crash-contract), `test/sync-inline-extract-stamps.serial.test.ts`, `test/sync-nudge-status-gate.test.ts`, `test/doctor-links-extraction-lag.test.ts`, engine-parity (Postgres↔PGLite) for the 3 methods + v112 round-trip. The stale SELECT in both engines projects a deterministic full-µs UTC string `to_char(updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS updated_at_iso` (carried on `StalePageRow.updated_at_iso`, populated by `rowToStalePage` in utils.ts with an ISO-only fallback — never `String(Date)`, which `::timestamptz` misparses); `extractStaleFromDB` stamps that exact-precision value, not a JS `Date` (which truncates to milliseconds), so on Postgres `links_extracted_at` equals the row's `updated_at` to the microsecond and `links_extraction_lag` clears — a ms-truncated stamp stays strictly below the µs `updated_at` and leaves every page perpetually stale, which `extract --stale` could never satisfy. `to_char` (not raw `::text`, which is `DateStyle`-fragile) keeps the projection deterministic. The `markPagesExtractedBatch` SQL is unchanged, so callers passing an explicit (e.g. backdated) `extractedAt` still control the stamp and the edited-since arm is exact. A deterministic PGLite case in `test/extract-stale.test.ts` injects a µs `updated_at`, runs `--stale`, and asserts the lag is 0 and stays 0.+- `src/commands/extract.ts` — `gbrain extract links|timeline|all [--source fs|db] [--source-id <id>]`: batch link/timeline extraction. fs walks markdown files, db walks pages from the engine (mutation-immune snapshot iteration; use for live brains with no local checkout). The full fs walk replaces each page's own markdown-derived links through `replacePageFileLinks` (the per-slug contract below; a file with no page row is skipped and not stamped); the db link walk and `extract --stale` replace through `replaceDerivedLinks`. Timeline rows are inserted in batches of 100 via `addTimelineEntriesBatch` (`ON CONFLICT DO NOTHING`; `created` counts real inserts) after every path — fs walk, db walk, per-slug, sync hooks, `--stale` — runs `retractRemovedTimelineEntries` for the page. `ExtractOpts.slugs?: string[]` enables incremental extract via `extractForSlugs()` (single combined links+timeline pass); the cycle path threads sync's `pagesAffected` through. Every per-slug extractor — `extractForSlugs` (the cycle's incremental pass) and the two sync hooks `extractLinksForSlugs` / `extractTimelineForSlugs` — resolves each requested slug through `resolveSlugRelPath`: the `buildSlugPathIndex(walkMarkdownFiles(dir))` index first, then — only on an index miss — the legacy `join(dir, slug + '.md')` existence check. The index is the primary because `pathToSlug` lowercases and slugifies, so a reconstructed path only finds files whose names are already slugs, and every other file looked deleted and was skipped in silence; the legacy fallback stays because sync ADMITS files the walker never emits (`_`-prefixed names, dot-dirs waived via `sync.include_hidden`) and those slugs still round-trip to their real path — without it such a page imports with no edges. On a slug collision the index prefers the file whose name IS the slug (else the first walked entry), so resolution never depends on directory-read order. The per-slug extractors reconcile like `put_page`: each page's own markdown-derived links are replaced through `replacePageFileLinks` (`src/core/link-reconciliation.ts`, `replaceDerivedLinks` with `preserveExisting`; other producers survive, a page with no row counts as processed with no links, and a failed replacement is reported on stderr and leaves the page stale), and `retractRemovedTimelineEntries` (`src/core/timeline-extract.ts`) deletes the non-event rows whose (date, source, summary) any stored `page_versions` text of the page produced (under either timeline parser) and its current text no longer does; rows no version produced (enrichment, meeting fan-out, `--infer-dates` anchors) are kept, and the version scan only runs when the page holds a row the current text does not produce. `gbrain extract timeline --prune-orphans [--source-id] [--dry-run] [--json]` (`pruneTimelineOrphans`) runs that reconciliation over every page with timeline rows, without inserting — the one-time prune for rows orphaned while extraction was insert-only (managed brains retract each page's rows in a page-locked `withCoordinatedWrite` transaction; these rows are removals, so `gbrain repair timeline` / `timeline_history` exclude them; pinned in `test/persistence-managed-lifecycle.test.ts`); the read-only `timeline_orphans` doctor check (`src/commands/doctor/checks/timeline-orphans.ts`) samples 500 pages and points at it. Pinned by `test/timeline-reconcile-all-paths.test.ts`. `loadSlugAliasTargets` adds renamed pages' old slugs (`slug_aliases`) to `allSlugs` so links written before a rename resolve to the current slug. `extractLinksForSlugs` reads the requested files first, then loads page metadata only for those pages and their link endpoints (`fileLinkOwnership(engine, sourceId, { slugs })`); the unscoped whole-brain load happens only when a DB meeting or attendance origin needs `replaceFileLinks`. Both return `ExtractForSlugsResult { created, processed, errors? }`; `errors` names pages whose read or write failed, and sync reports them as `extract_error` (stderr line plus the `SyncResult` field) instead of swallowing them. `processed` is the subset actually read, and the shared `slugsSafeToStamp(links, timeline)` intersection is what every caller may stamp. Stamping the full requested set marks a silently-skipped page fresh and hides it from `extract --stale` permanently. All three call sites (`src/commands/sync.ts`, `src/core/github-source.ts`, `src/core/google/google-source.ts`) stamp the intersection. `walkMarkdownFiles(brainDir)` still runs to build `allSlugs` for link resolution. `--source-id <id>` scopes extraction to one source on federated brains (resolved via `resolveSourceWithTier()` before any SQL; failures hint `gbrain sources list`). `gbrain extract --stale [--source-id <id>] [--catch-up] [--dry-run] [--json]` branch (`extractStaleFromDB`; on a managed brain it hands the sweep to `extractManagedStaleLinks` in `src/core/persistence/links-maintenance.ts` for every caller, CLI, cycle, jobs and maintain, and a live PGLite owner runs it through `src/commands/extract-stale-delegate.ts`) — incremental DB-source link+timeline sweep over pages whose `pages.links_extracted_at` watermark is stale. Embedded callers (the cycle) pass `quiet: true` so the helper writes nothing to stdout, including its JSON result; standalone CLI output is unchanged. In `jsonMode` every fs path, `extractForSlugs` included, reports a dropped flush as a `{event:'batch_error'}` stderr line rather than going silent. Stale predicate (shared by both engines + the doctor check): `links_extracted_at IS NULL OR links_extracted_at < LINK_EXTRACTOR_VERSION_TS::timestamptz OR updated_at > links_extracted_at` (the `updated_at` arm catches MCP `put_page` / `sync --no-extract` edited-since-extract). Three `BrainEngine` methods (parity in postgres-engine.ts + pglite-engine.ts + bootstrap probes): `countStalePagesForExtraction(opts?)`, `listStalePagesForExtraction({batchSize, afterPageId?, sourceId?, versionTs?})` (returns page CONTENT to avoid N+1 `getPage`; `rowToStalePage` in utils.ts maps the row, `StalePageRow` in types.ts), `markPagesExtractedBatch(refs, defaultExtractedAt)` (3-array unnest `slug[],source_id[],ts[]`; each ref may carry its own `extractedAt`). `STALE_BATCH_SIZE` default 25 (`GBRAIN_EXTRACT_STALE_BATCH`; small because page bodies are unbounded — the LIMIT is the only fetch-time memory bound); `STALE_TIME_BUDGET_MS` 30min wall-clock (`--catch-up` removes the cap). Non-swallowing flush: link/timeline flush throws propagate and abort the batch; stamp LAST so a crash leaves pages unstamped and they re-extract idempotently (`addLinksBatch` ON CONFLICT DO NOTHING + timeline dedup). `extractStaleFromDB` stamps with each row's READ `updated_at` (not `now()`), so a concurrent edit during the sweep keeps the page stale and it re-extracts next run rather than marked fresh-with-old-content. On a managed-persistence brain each page publishes its derived links (`prepareAutomaticLinks`), the coordinator's unrecorded canonical timeline tuples (`unrecordedCanonicalTimeline`, insert-only) and its watermark in one revision-bound `withCoordinatedWrite` transaction; a page edited since the read is skipped and stays stale. Tests: `test/extract-stale-managed.test.ts`, `test/persistence-managed-lifecycle.test.ts`. Source-correct stamping at DB-extract sites via `stampExtracted` (best-effort, never throws); `extractLinksFromDB` only stamps the combined watermark when `subcommand === 'all'` (a links-only run must not hide timeline staleness). `LINK_EXTRACTOR_VERSION_TS` lives in `src/core/link-extraction.ts` (bump like `CHUNKER_VERSION` to invalidate all prior stamps). Migration v112 (`pages_links_extracted_at`) adds nullable `TIMESTAMPTZ` + composite `(source_id, links_extracted_at)` index (CONCURRENTLY + invalid-remnant pre-drop on Postgres, plain on PGLite), NO backfill so the real backlog surfaces on first `gbrain doctor`. Schema parity in schema.sql + pglite-schema.ts + schema-embedded.generated.ts + `REQUIRED_BOOTSTRAP_COVERAGE`. `src/commands/doctor.ts:checkLinksExtractionLag` (the `links_extraction_lag` check, also in `doctorReportRemote`) warn-only by default (>`GBRAIN_EXTRACTION_LAG_WARN_PCT`, default 20%; shared `EXTRACTION_LAG_WARN_PCT_DEFAULT` + `EXTRACTION_LAG_MIN_PAGES=100` + exported `_resolveEnvNumber`), hard-fails only when `GBRAIN_EXTRACTION_LAG_FAIL_PCT` is set; vacuous-skips <100 pages (no `--source`); pre-v112 brains graceful-skip via `isUndefinedColumnError`; strictly a SQL COUNT (safe on remote/thin-client). `src/commands/sync.ts` carries `--no-extract` (threaded through single-source + `--all` + `syncOneSource`), stamps `links_extracted_at` at the inline-extract call site for the slugs the extractors actually read, and `maybeExtractionNudge` prints a one-line stderr nudge after a `synced | first_sync | up_to_date` sync that leaves a backlog (`shouldNudgeAfterSync` pure predicate; `GBRAIN_SYNC_NO_EXTRACT_NUDGE` suppresses). `src/core/retry.ts` lists `'extract.stale'` in `BATCH_AUDIT_SITES`; `src/core/doctor-categories.ts` lists `links_extraction_lag` in `BRAIN_CHECK_NAMES`. Pinned by `test/extract-stale.test.ts` (incl. edited-after-stamp + crash-contract), `test/sync-inline-extract-stamps.serial.test.ts`, `test/sync-nudge-status-gate.test.ts`, `test/doctor-links-extraction-lag.test.ts`, engine-parity (Postgres↔PGLite) for the 3 methods + v112 round-trip. The stale SELECT in both engines projects a deterministic full-µs UTC string `to_char(updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS updated_at_iso` (carried on `StalePageRow.updated_at_iso`, populated by `rowToStalePage` in utils.ts with an ISO-only fallback — never `String(Date)`, which `::timestamptz` misparses); `extractStaleFromDB` stamps that exact-precision value, not a JS `Date` (which truncates to milliseconds), so on Postgres `links_extracted_at` equals the row's `updated_at` to the microsecond and `links_extraction_lag` clears — a ms-truncated stamp stays strictly below the µs `updated_at` and leaves every page perpetually stale, which `extract --stale` could never satisfy. `to_char` (not raw `::text`, which is `DateStyle`-fragile) keeps the projection deterministic. The `markPagesExtractedBatch` SQL is unchanged, so callers passing an explicit (e.g. backdated) `extractedAt` still control the stamp and the edited-since arm is exact. A deterministic PGLite case in `test/extract-stale.test.ts` injects a µs `updated_at`, runs `--stale`, and asserts the lag is 0 and stays 0.- Extract CLI help — `EXTRACT_HELP` in `src/commands/extract.ts` is the canonical detailed usage shared by `--help` and invalid-subcommand errors. `src/cli.ts` routes `extract --help` before engine connection so help works on unconfigured installs; the top-level TOOLS block advertises every mode-specific flag. Pinned by `test/cli-help-discoverability.test.ts`.- `src/commands/features.ts` — `gbrain features --json --auto-fix`: usage scan + feature adoption salesman.diff --git a/docs/architecture/key-files/core-cycle.md b/docs/architecture/key-files/core-cycle.mdindex 8eaf14a8e2..5e506b3e36 100644--- a/docs/architecture/key-files/core-cycle.md+++ b/docs/architecture/key-files/core-cycle.md@@ -3,11 +3,11 @@[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.-- `src/core/cycle/synthesize-postprocess.ts` — Managed synthesis quote repair and provenance stamping publish together through a deterministic maintenance request bound to the source incarnation, transcript hash, child output, and original committed page revision. The immutable committed receipt is the completion checkpoint: later runs skip finalized output rather than repairing user edits. Pending work replays its retained intent under the original revision and existing authority/file guards; missing provenance fails closed. Runs the same claim verification as the unmanaged path (`groundSource` + `resolveVerifyPrior` + `verifyDreamPage` from `synthesize-verify.ts`, scoped by the child write epochs the phase passes as `sinceByTranscript`); the unmanaged path retains its fail-open behavior. Covered by `test/managed-synthesis-postprocess.test.ts` and its PostgreSQL E2E wrapper.+- `src/core/cycle/synthesize-postprocess.ts` — Managed synthesis quote repair and provenance stamping publish together through a deterministic maintenance request bound to the source incarnation, transcript hash, child output, and original committed page revision. The immutable committed receipt is the completion checkpoint: later runs skip finalized output rather than repairing user edits. Pending work replays its retained intent under the original revision and existing authority/file guards; missing provenance fails closed. Runs the same claim verification as the unmanaged path (`groundSource` + `resolveVerifyPrior` + `verifyDreamPage` from `synthesize-verify.ts`, scoped by the ref's `first_write_at`, else the child write epochs passed as `sinceByTranscript`) and stamps the dream provenance fields only on dream-owned pages (`isDreamOwnedPage`); the published page reconciles its automatic links like an ordinary put_page (`page-prepare.ts` treats `managed_maintenance_page` intents as auto-linked); the unmanaged path retains its fail-open behavior. Covered by `test/managed-synthesis-postprocess.test.ts` and its PostgreSQL E2E wrapper.- `src/core/cycle/anomaly.ts` — Pure stats helpers for `find_anomalies`. `meanStddev` returns sample stddev (n-1 denominator) and (0,0) for empty input. `computeAnomaliesFromBuckets(baseline, today, sigma, limit)` takes densified daily-count buckets + today's counts per cohort, returns `AnomalyResult[]`. Zero-stddev fallback: cohort fires when `count > mean + 1`, with `sigma_observed = count - mean` as a finite sort proxy (no NaN). Brand-new cohorts (no baseline) have `mean=0, stddev=0` so the fallback fires at count >= 2. Sorted by `sigma_observed` desc, top `limit` (default 20). `page_slugs` capped at 50 per cohort.-- `src/core/cycle/cycle-date.ts` — the dream-cycle calendar-date policy: `resolveCycleDate` resolves explicit `--date` > `cycle.timezone` config > host IANA timezone > UTC, so a run after local midnight buckets into the day the user actually lived instead of rewriting yesterday's UTC-day summary. `isValidTimeZone` gates configured values (config.ts also validates at `gbrain config set` time); an invalid configured timezone falls back loudly instead of killing the cycle. `utcDate` is retained for source-date fallbacks and legacy pages.+- `src/core/cycle/cycle-date.ts` — the dream-cycle calendar-date policy (`runCycle` resolves it once and threads `cycleDate` into synthesize, patterns and drift, so one cycle never splits across days; `test/cycle-date-consistency.test.ts` also lints `src/core/cycle*` for the UTC-day `toISOString().slice(0, 10)` pattern; `shiftCalendarDate` does lookback arithmetic on the date string): `resolveCycleDate` resolves explicit `--date` > `cycle.timezone` config > host IANA timezone > UTC, so a run after local midnight buckets into the day the user actually lived instead of rewriting yesterday's UTC-day summary. `isValidTimeZone` gates configured values (config.ts also validates at `gbrain config set` time); an invalid configured timezone falls back loudly instead of killing the cycle. `utcDate` is retained for source-date fallbacks and legacy pages.- `src/core/cycle/emotional-weight.ts` — Pure function `computeEmotionalWeight({tags, takes}, {highEmotionTags?, userHolder?})`. Deterministic 0..1 score: tag-emotion boost (max 0.5, case-insensitive match against `HIGH_EMOTION_TAGS` seed list), take density (0.1/take, capped at 0.3), take avg weight (0..0.1), user-holder ratio (0..0.1 over active takes; default holder `'garry'`). Total clamped to [0..1]. Anglocentric / personal-life-biased seed list intentional; override via config `emotional_weight.high_tags` (JSON array). `userHolder` overridable via `emotional_weight.user_holder`.@@ -15,9 +15,9 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/cycle/extract-atoms-drain.ts` — pure single-hold bounded drain for the silent lens-phase backlog. `runExtractAtomsDrain(deps, opts)` over injected deps (`withLock`, `runBatch`, `countRemaining`, `now`, optional `onBatch`) loops bounded batches under ONE continuous lock hold, **rediscovering eligibility each batch** (idempotent NOT-EXISTS-on-`source_hash`, so content mutated by a concurrent process simply doesn't match — no cross-window stale cursor), until the backlog is empty OR the time window elapses. Returns `{phase, status, extracted, skipped, remaining, batches, stopped}`. Backs `gbrain dream --phase extract_atoms --drain`. Takes the SAME `cycleLockIdFor(sourceId)` the routine cycle takes (a concurrent autopilot tick genuinely defers with `cycle_already_running`); NO release/reacquire-between-windows primitive. The shared wiring helper `runExtractAtomsDrainForSource(engine, {sourceId, windowSeconds, brainDir?, maxBatches?, onBatch?})` owns the lock+batch+count+defer wiring (dynamic imports of db-lock/cycle/extract-atoms keep the pure loop cheap to unit-test) and is the ONE drain path for three callers — `gbrain dream --drain` (which calls it), the `extract-atoms-drain` Minion handler, and autopilot auto-drain — so lock id / window / defer-on-busy can't drift. `sourceId: undefined` → legacy `gbrain-cycle` lock + `'default'` extraction; a real id → `gbrain-cycle:<id>`. `LockUnavailableError` propagates to the caller (each reports the busy case its own way). Pinned by `test/extract-atoms-drain.test.ts`. The summary's `last_error` always passes through `sanitizeFailureText` (secret/DSN redaction, whitespace collapse, bounded): typed failure records use the source/reason caps, and the count-only `firstError` compatibility path is sanitized to the combined bound, so a provider payload cannot ride either path into `--json` output. `formatDrainProviderFailure(result)` renders the Minion handler's `provider_failure` throw (batches/remaining + `last_error`), so the dead-lettered job's `error_text` names the cause.-- `src/core/cycle/extract-atoms.ts` — the extract_atoms lens phase: mines eligible pages into `atoms/<date>/<stem>-<hash>` pages. Eligibility 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-atoms.ts` — the extract_atoms lens phase: mines eligible pages into `atoms/<date>/<stem>-<hash>` pages. Eligibility reads source-incarnation/page/full-hash-keyed derived scan state; scan and failure markers do not mutate canonical frontmatter. Managed extraction checks source-wide local authority and owner readiness before provider work, admits outputs plus a completion request together, and replays retained output without another model call. Managed atom files keep provisional source hashes; only the source-incarnation/page/full-hash durable completion receipt excludes an item from discovery and backlog counts. Unmanaged atom completion flips and their cardinality check share a transaction after provenance links persist, so a partial match rolls back and stays retryable. An undated source dates its atoms by the source page's creation date (`undated` for transcripts), never the run date. After an unmanaged item completes, `retireStaleAtoms` soft-deletes that source's atoms from earlier extractions (other or provisional `source_hash`) that this extraction did not re-produce, so LLM-chosen titles that drift between extractions don't pile up. Atom identity: page-derived atoms fold the source-page slug into the slug hash (8 chars, NUL-separated) so two same-date pages emitting the same title get DISTINCT slugs; the source CONTENT hash is deliberately NOT folded (a reworded source still upserts rather than duping); transcript atoms keep the legacy title-only 6-char hash. `resolvePageAtomSlug` adopts a legacy-slug atom with a compatible binding in place on re-extraction (upgrade idempotency — no migration, no duplicate), while `assertAtomImportBinding` fail-closed refuses to reuse a slug bound to a DIFFERENT source locator. Both share `isCompatibleAtomBinding(frontmatter, sourcePageSlug)` — the ONE definition of compatible: bound to THIS source page, or carrying no `source_slug`/`source_path` at all (pre-binding-era adoption, not a clobber); a `source_path`-bound legacy transcript atom or a different `source_slug` is a different origin, and a non-atom page squatting on the slug is refused. `source_quote` is verified at extraction time against the exact `truncateUtf8` prompt prefix the model saw (`locateQuote` advances by full code points): located quotes persist original characters + [start,end) offsets + `source_quote_verified`; unlocatable quotes are dropped with the atom kept. Edges write before the completion flip; per-item drain failures stay typed (bounded, sanitized, reconcilable). Transcript items carry the same failure-count/tombstone machinery as pages, in the `extract_atoms_transcript_state` table (migration `extract_atoms_transcript_state_table`; keyed `(source_id, file_path, content_hash)` with the 16-char hash prefix, so an edit is a new row and re-eligibilizes): `recordItemFailureCount` counts a transcript's malformed output toward `MAX_DETERMINISTIC_FAILURES`, a zero-yield transcript tombstones immediately (the same zero-yield policy as pages), and `tombstonedTranscriptsForHashes` is the batch read-side gate mirroring `atomsExistingForHashes` (fail-open on error). Reported as `tombstoned_transcripts` (paths), separate from the page-slug `tombstoned_for_failures`. Malformed managed output requires a newly approved protected-job retry identity; publication retry reuses retained output and original/current grants.-- `src/core/cycle/extract-facts.ts` — source-scoped `## Facts` fence reconciliation. 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/extract-facts.ts` — source-scoped `## Facts` fence reconciliation. Rows are keyed by fence row number, never by claim text: a DB row whose `(row_num, claim)` is still in the fence keeps its id and has its other cells updated in place (ids from recall stay valid for forget; `source_session`, `created_at`, consolidation state and vectors survive), a row whose number left the fence or whose claim was rewritten is expired and detached (`row_num` NULL), never deleted, and only new row numbers insert. Duplicate ACTIVE rows with the same claim and source index once; a struck history row never collapses onto an active row with the same text, so a claim that reverts (NYC → SF → NYC) stays active. `superseded by #N` links resolve on every hop of a chain (`supersede-resolve.ts`; forgotten targets and cycles still resolve to NULL with a warning). Each run first expires (without detaching) the active fence-owned rows of soft-deleted pages in the source; restoring the page re-activates them on its next reconcile. Previously embedded fact rows and their text/provenance remain intact when a full valid replacement embedding batch is unavailable; old vectors are never transplanted to changed text/model. Restrictive fence changes still expire removed/withdrawn claims and tighten visibility before deferral. Provider cancellation within database writes rolls back rather than publishing half a replacement. Keyless initial fact insertion remains supported; conversation-origin facts without a fence are not wiped by fence reconciliation. Each page reconciles in isolation: a page whose writes the database rejects rolls back, is reported as `<slug>: FACTS_RECONCILE_FAILED: …` (counted in `pagesFailed`, booked as a halt in the rollup), and later pages still reconcile. `facts.superseded_by` is `ON DELETE SET NULL`. Tests: `test/e2e/fact-vector-repair-parity.test.ts`, `test/extract-facts-phase.test.ts`, `test/extract-facts-poison-page.test.ts`, `test/extract-facts-stable-identity.test.ts`. Managed legacy fence reconciliation refuses before any provider work; it is distinct from the restored coordinated `extract_facts` operation and durable page backstop.- `src/core/cycle/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).@@ -31,7 +31,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. Maintenance runs (the only keyed patterns runs) consult the paid-loop breaker before submission and skip with `dream_breaker_tripped`.-- `src/core/cycle/phantom-redirect.ts` — Phantom-redirect orchestrator. Exports `runPhantomRedirectPass(engine, brainDir, sourceId, dryRun): Promise<PhantomPassResult>` (per-cycle wrapper acquiring the `gbrain-sync` writer lock once for the whole pass, 30s bounded retry, walks up to `GBRAIN_PHANTOM_REDIRECT_LIMIT` unprefixed phantoms) + `tryRedirectPhantom(engine, page, sourceId, brainDir, dryRun): Promise<RedirectResult>` + `stripFenceAndFrontmatterAndLeadingH1` (pure body-shape gate helper — strips facts fence incl. preceding `## Facts` heading and the leading H1). Only fence rows migrate, so the residue gate also counts the page's timeline text, any `timeline_entries` row, and frontmatter keys beyond `title`/`type`/`tags`; any residue = not a phantom. Handler order: body-shape gate → `resolvePhantomCanonical` (bypasses exact-self-match) → `findPrefixCandidates` ambiguity check → `fenceDbDrift` bi-directional check → dry-run early exit → materialize canonical via `serializeMarkdown` if DB-only → append phantom fence rows to canonical's disk fence with `(claim, valid_from)` dedup-guard + row_num continuation → `engine.refreshPageBody` with SHA-256 content_hash recomputed via the import-file shape → `engine.migrateFactsToCanonical` (lossless) → move the phantom's fact withdrawals to the canonical subject → `engine.rewriteLinks` (DB FK rewrite; wiki-link text rewrite is a documented follow-up) → `engine.softDeletePage` + `engine.deleteFactsForPage(phantom)` + `fs.unlinkSync(phantomPath)`. `RedirectResult.canonical` populated on `'redirected'` (incl. dry-run preview) so the caller builds `touched_canonicals`. Idempotent on re-run: phantom soft-deleted → predicate fails (`deleted_at IS NULL`); migrate UPDATE matches no rows; dedup-guard prevents double-append.+- `src/core/cycle/phantom-redirect.ts` — Phantom-redirect orchestrator. Exports `runPhantomRedirectPass(engine, brainDir, sourceId, dryRun): Promise<PhantomPassResult>` (per-cycle wrapper acquiring the `gbrain-sync` writer lock once for the whole pass, 30s bounded retry, walks up to `GBRAIN_PHANTOM_REDIRECT_LIMIT` unprefixed phantoms) + `tryRedirectPhantom(engine, page, sourceId, brainDir, dryRun): Promise<RedirectResult>` + `stripFenceAndFrontmatterAndLeadingH1` (pure body-shape gate helper — strips facts fence incl. preceding `## Facts` heading and the leading H1). Only fence rows migrate, so the residue gate also counts the page's timeline text, any `timeline_entries` row, and frontmatter keys beyond `title`/`type`/`tags`; any residue = not a phantom. Handler order: body-shape gate → `resolvePhantomCanonical` (bypasses exact-self-match; a fuzzy hit needs a 0.1 margin over the runner-up) → `findPrefixCandidates` ambiguity check (a canonical that is not the single prefix candidate is ambiguous too) → `fenceDbDrift` bi-directional check → dry-run early exit → canonical file resolved through `resolvePageWriteTarget` (recorded `source_path`, own-`local_path` roots; only a brain with no configured root falls back to `brainDir`) → materialize canonical via `serializeMarkdown` if DB-only → append phantom fence rows to that file with `(claim, valid_from)` dedup-guard, numbering past both the file's and the DB's highest row number and rewriting `superseded by #N` to the new numbers → `engine.refreshPageBody` → move the phantom's fact withdrawals to the canonical subject → move every phantom fact row by id (a row takes its on-disk canonical row number unless the canonical index already holds it; history, duplicates and rows absent from the fence move expired and detached, never deleted) → move the phantom's links to the canonical page id (skipping duplicates and self-links) → `recordRenameAlias` (phantom → canonical in `slug_aliases`) → `engine.softDeletePage` + unlink. `RedirectResult.canonical` populated on `'redirected'` (incl. dry-run preview) so the caller builds `touched_canonicals`. Idempotent on re-run: phantom soft-deleted → predicate fails (`deleted_at IS NULL`); migrate UPDATE matches no rows; dedup-guard prevents double-append.- `src/core/cycle/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,9 +39,9 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/cycle/recompute-emotional-weight.ts` — Cycle phase orchestrator. One read plus bounded writes: `engine.batchLoadEmotionalInputs(slugs?)` → `computeEmotionalWeight` (per-row pure function) → `engine.setEmotionalWeightBatch(slice)` in slices of 1000 rows. Between slices it checks `opts.signal` (throws → `fail`), awaits `opts.yieldDuringPhase` (cycle-lock refresh / steal detection), fires `opts.onProgress`, and yields a macrotask (`setTimeout(0)`) so PGLite's synchronous statement execution never wedges the main thread for a whole-brain pass; `runCycle` wires these exactly like consolidate (`racedTimePhase` + `buildYieldDuringPhase` + `cycleSignal` + `progress.tick`). Both engines' `setEmotionalWeightBatch` rewrite only rows whose weight changes (`IS DISTINCT FROM` in the WHERE — no trigger fan-out on same-value rows) and return rows CHANGED; `details.pages_recomputed` = pages evaluated (feeds the cycle totals), `details.pages_updated` = rows changed. Reads config `emotional_weight.high_tags` (JSON array, falls back to default seed list on parse error) and `emotional_weight.user_holder`. Empty `affectedSlugs` short-circuits with zero-work success. dry-run reports the would-write count without touching the DB. Engine throw bubbles into `status: 'fail'` with code `RECOMPUTE_EMOTIONAL_WEIGHT_FAIL` so the cycle continues.-- `src/core/cycle/synthesize-verify.ts` — Mechanical claim verification on every page a synthesis child wrote (zero LLM). Exports the shared grounding primitive `normalizeForGrounding` (whitespace/curly-quote/dash/ellipsis/case folding WITH an offset map back to the original string, so every replacement is a verbatim transcript slice) + `normForGrounding` (plain form, also used by `buildTriageMapBlock` and triage-rescue). `groundSource(path, content)` prepares a transcript: offset map, speaker turns (`parseSpeakerTurns`: bold `**Name** (ts):` anchors always, plain `Label:` anchors when the label is a role word or opens two or more lines), canonical numbers and dates (`numericFacts`: `$250K` = `$250,000` = `250 thousand`, `2026-03-14` = `March 14th`; the file basename counts), and speaker-mention patterns. `groundQuote` runs the ladder exact → normalized → near (word-trigram anchors, window clipped to the anchor's speaker turn, ≥0.8 token overlap, ambiguity within 0.05 falls through, trimmed to the first/last shared token, refused above 1.3x the quote length) and never accepts a match that touches a speaker label (`reason: 'crosses_speakers'`). `verifyBody` splits a body into claim units (`claimUnits`: sentences within a line, whole list items, whole table rows; no boundary inside a quote) and checks each NEW unit: every quote must ground in some source, a quote whose sentence names a transcript speaker must name the speaker of the matched turn, and every numeric/date claim (outside grounded quotes, code, wikilinks and link targets) must appear in a source. Any failure removes the whole unit from the body; `verifyDreamPage` records it in frontmatter `unverified_claims` (`text`, `reason` = `quote_not_in_source` / `quote_crosses_speakers` / `speaker_mismatch` / `number_not_in_source`, `detail`, `sources`, `detected_at`) and records every grounded quote's source path, character span and speaker in `grounding.quotes`; records from the pre-run revision carry forward, capped at 100 / 200. Frontmatter is neither chunked nor searched, so quarantined claims stay reviewable through `get_page` but out of search, recall, think and context packs. A page whose every unit failed keeps `ALL_CLAIMS_QUARANTINED_BODY`. Scope (`verifyAndRepairDreamPages(engine, refs, transcriptsByPath, { since, sinceByTranscript, checkedAt })`): sources are the transcripts of every child that wrote the page; the page epoch is the earliest `loadChildWriteEpochs` entry of its sources (child job `created_at`, so resumed or coalesced children keep their original epoch), else `since` (`readVerifyEpoch`, taken before fan-out). Pages created at or after the epoch are verified whole; older pages are verified only on units absent from their pre-epoch revision (`loadPreRunRevision`: the first `page_versions` snapshot at or after the epoch; none means the page was not overwritten → `skipped_unchanged`). Write-back goes through `importFromContent` (`noEmbed`; the phase-end embed sweep backfills) with a `beforeCommit` that re-projects timeline entries, facts, takes (`prepareCanonicalProjections`) and automatic links (`prepareAutomaticLinks`) from the verified body in the same transaction, so no derived row outlives its quarantined claim. Fail-open per page (read-back miss / write throw → `errors` + continue; abort still unwinds). Kill switch `dream.synthesize.quote_verify` (default on). Telemetry shape = `QuoteVerifyStats` in `details.synthesis.quote_verify`. Pinned by `test/cycle-synthesize-verify.test.ts`, the write-path mini-eval `test/cycle-write-path-mini-eval.test.ts`, and the three-cycle repeated-consolidation pin `test/cycle-repeated-consolidation.test.ts` (harness `test/helpers/repeated-consolidation.ts`, printable run `scripts/repeated-consolidation-experiment.ts`).+- `src/core/cycle/synthesize-verify.ts` — Mechanical claim verification on every page a synthesis child wrote (zero LLM). Exports the shared grounding primitive `normalizeForGrounding` (whitespace/curly-quote/dash/ellipsis/case folding WITH an offset map back to the original string, so every replacement is a verbatim transcript slice) + `normForGrounding` (plain form, also used by `buildTriageMapBlock` and triage-rescue). `groundSource(path, content)` prepares a transcript: offset map, speaker turns (`parseSpeakerTurns`: bold `**Name** (ts):` anchors always, plain `Label:` anchors when the label is a role word or opens two or more lines), canonical numbers and dates (`numericFacts`: `$250K` = `$250,000` = `250 thousand`, `2026-03-14` = `March 14th`; the file basename counts), and speaker-mention patterns. `groundQuote` runs the ladder exact → normalized → near (word-trigram anchors, window clipped to the anchor's speaker turn, ≥0.8 token overlap, ambiguity within 0.05 falls through, trimmed to the first/last shared token, refused above 1.3x the quote length) and never accepts a match that touches a speaker label (`reason: 'crosses_speakers'`). `verifyBody` splits a body into claim units (`claimUnits`: sentences within a line, whole list items, whole table rows; no boundary inside a quote) and checks each NEW unit: every quote must ground in some source, a quote whose sentence names a transcript speaker must name the speaker of the matched turn, and every numeric/date claim (outside grounded quotes, code, wikilinks and link targets) must appear in a source; a unit saying a named speaker decided, agreed, committed or will act (and recording no proposal, refusal or negation) must carry only numbers and dates that speaker stated, or that the turn they explicitly accepted stated (`numbersBySpeaker`; bare years and numbers no turn states are not attributed). Any failure removes the whole unit from the body; `verifyDreamPage` records it in frontmatter `unverified_claims` (`text`, `reason` = `quote_not_in_source` / `quote_crosses_speakers` / `speaker_mismatch` / `number_not_in_source` / `decision_misattributed`, `detail`, `sources`, `detected_at`) and records every grounded quote's source path, character span and speaker in `grounding.quotes`; records from the pre-run revision carry forward, capped at 100 / 200. Frontmatter is neither chunked nor searched, so quarantined claims stay reviewable through `get_page` but out of search, recall, think and context packs. A page whose every unit failed keeps `ALL_CLAIMS_QUARANTINED_BODY`. Scope (`verifyAndRepairDreamPages(engine, refs, transcriptsByPath, { since, sinceByTranscript, checkedAt })`): sources are the transcripts of every child that wrote the page; the page epoch is the child's first write to that page (`first_write_at` on the ref) when known, so a page another writer created while the child ran is diffed rather than treated as the run's own; otherwise the earliest `loadChildWriteEpochs` entry of its sources (child job `created_at`, so resumed or coalesced children keep their original epoch), else `since` (`readVerifyEpoch`, taken before fan-out). Pages created at or after the epoch are verified whole; older pages are verified only on units absent from their pre-epoch revision (`loadPreRunRevision`: the first `page_versions` snapshot at or after the epoch; none means the page was not overwritten → `skipped_unchanged`). Write-back goes through `importFromContent` (`noEmbed`; the phase-end embed sweep backfills) with a `beforeCommit` that re-projects timeline entries, facts, takes (`prepareCanonicalProjections`) and automatic links (`prepareAutomaticLinks`) from the verified body in the same transaction, so no derived row outlives its quarantined claim. Fail-open per page (read-back miss / write throw → `errors` + continue; abort still unwinds). Kill switch `dream.synthesize.quote_verify` (default on). Telemetry shape = `QuoteVerifyStats` in `details.synthesis.quote_verify`. Pinned by `test/cycle-synthesize-verify.test.ts`, the write-path mini-eval `test/cycle-write-path-mini-eval.test.ts`, and the three-cycle repeated-consolidation pin `test/cycle-repeated-consolidation.test.ts` (harness `test/helpers/repeated-consolidation.ts`, printable run `scripts/repeated-consolidation-experiment.ts`).-- `src/core/cycle/synthesize.ts` — Synthesize phase: conversation-transcript-to-brain pipeline, a two-stage cascade where cheap scored triage gates frontier synthesis. Reads `dream.synthesize.session_corpus_dir`, runs `runTriagePass` (exported; bounded pool `dream.triage.concurrency` default 4, wall-clock cache-MISS budget `dream.triage.max_ms` default 5 min — cache hits are free and deferred files report `deferred: true`, never cached, so the next pass continues) whose judge `judgeSignificance` emits `{score 0-1 ordinal salience, content_type, segments ≤8 verbatim quotes, entities ≤12, reasons}` (non-overlapping bands LOW 0-0.29 / MEDIUM 0.30-0.69 / HIGH 0.70-1.0; head 50%/middle 20%/tail 30% sample within `dream.triage.max_chars` default 24K via `safeSplitIndex`; out-of-[0,1] scores are `unparseable`, never clamped) cached in `dream_verdicts` with the judging `model` + `TRIAGE_VERSION` — cache validity requires BOTH to match (switching `models.dream.triage` re-judges; `max_chars`/`max_tokens` deliberately excluded from validity — `dream retriage --force` re-judges under new sampling knobs). Degenerate verdicts (`truncated`/`refusal`/`unparseable`) are never cached. THE gate is `passesTriageGate` (triage-rescue.ts): `score >= dream.triage.threshold` (default 0.5) OR the verified-segment rescue, applied at report construction inside `runTriagePass` at READ time — retuning the threshold or rescue knobs re-gates with zero re-judging; the stored `worth_processing` boolean derives from the fixed `DEFAULT_TRIAGE_THRESHOLD` constant (back-compat only, never the live dial). Passing files fan out one subagent per chunk with `max_turns` from `dream.synthesize.max_turns` (default 16) and a bounded advisory `buildTriageMapBlock` (exported; score/type/entities + chunk-filtered segments, '' for legacy/degraded verdicts so the prompt is unchanged for those) spliced into `buildSynthesisPrompt`, with `allowed_slug_prefixes` (sourced from `skills/_brain-filing-rules.json` `dream_synthesize_paths.globs`; when `dream.synthesize.output_root` is set, `loadAllowedSlugPrefixes(outputRoot)` remaps the `wiki/`-rooted globs to the configured namespace, and the same root drives the prompt slug templates; default 'wiki', validated against the slug grammar via the exported `loadOutputRoot`). The phase is source-scoped: cycle.ts threads `cycleSourceId` as `opts.sourceId` → each child's `SubagentHandlerData.source_id` → the subagent tool registry's `OperationContext.sourceId`, so put_page writes, collected refs, the summary page, and reverse-writes all target the cycle's resolved source ('default' when unscoped; reverse-writes for the cycle's own source land at `brainDir/<slug>.md`, foreign sources under `brainDir/.sources/<id>/`). Orchestrator collects slugs from `subagent_tool_executions` (NOT `pages.updated_at`) and reverse-renders DB → markdown via `serializeMarkdown`. Cooldown via `dream.synthesize.last_completion_ts`, written only when children completed and neither synthesis-budget nor triage-budget deferrals remain. Idempotency keys `dream:synth-v2:<enc source>:filename:<enc basename>:<hash16>[:c<i>of<n>]` (byte-stable, pinned by `test/dream-synthesize-chunking.serial.test.ts`; grammar parsed by exported `parseSynthV2Key`). Fan-out self-heals idempotency-coalesced rows stranded `waiting` in a FOREIGN dead `dream-inline-*` queue (cancel releases the key slot → re-add into the live run's queue) instead of burning the 35-min wait on a row no worker will ever claim. Opt-in per-source daily submission cap `dream.synthesize.max_submissions_per_source_per_day` (default 0 = off; skips whole files — never partial chunk sets; bypassed for explicit `--input/--date/--from/--to` targets; count-query failure fails OPEN with a stderr warn). `--dry-run` runs triage, skips synthesis; deferral-aware headlines append "(N not yet triaged — time budget...)" so a time-boxed cold pass never reads as mass rejection. `details.triage` (threshold/judged/cache_hits/unreliable/degraded/deferred/below_threshold + rescue_band/rescue_checked/rescue_fired + tokens_in/tokens_out/cost_usd) + `details.synthesis` (jobs/avg_turns/max_turns_config + quote_verify/spend/children_zero_pages) carry the phase telemetry. Subagent never gets fs-write access. `renderPageToMarkdown` (exported) stamps `dream_generated: true` + `dream_cycle_date` into every reverse-write's frontmatter; `writeSummaryPage` does the same on the summary index — this marker is the explicit identity surface `isDreamOutput` checks in `transcript-discovery.ts`. `stampDreamProvenance` additionally persists the same marker into the `pages.frontmatter` JSONB row (merge via `executeRawJsonb`, raw object bound to `$N::jsonb`) for every child-written page BEFORE reverse-rendering, so generated pages are DB-queryable and a later put_page write-through (which re-renders from the DB row) can't erase the stamp. `judgeSignificance`, `JudgeClient`, `runTriagePass`, `buildTriageMapBlock`, `parseSynthV2Key`, `loadSynthConfig`, `TRIAGE_VERSION`, and `DEFAULT_TRIAGE_THRESHOLD` are exported; the triage model resolves via an explicit pre-read of `models.dream.triage` (preferred; through exported `resolveAlias`) falling back to the standard `resolveModel` chain (`models.dream.synthesize_verdict` → deprecated `dream.synthesize.verdict_model` → tier `utility`). `splitTranscriptByBudget(content, contentHash, maxChars)` splits oversized transcripts at paragraph boundaries (`## Topic:` → `---` → `\n` ladder) using a deterministic offset seeded from the first 32 bits of `contentHash` so retries chunk identically; per-chunk char budget = `MODEL_CONTEXT_TOKENS[resolvedModel] × 0.9 × 3.5 chars/token` (non-Anthropic ids fall back to a 180K-token safe default + once-per-process stderr warn); operator overrides `dream.synthesize.max_prompt_tokens` (floor 100K, wins) and `dream.synthesize.max_chunks_per_transcript` (default 24); per-chunk subagent job/wait timeouts are `dream.synthesize.subagent_timeout_ms` / `dream.synthesize.subagent_wait_timeout_ms` (defaults 30/35 min). Legacy `dream:synth:` keys are never produced — `loadSuccessfulSynthesisKeys(engine, sourceId, keyPrefix)` reads the completed rows of BOTH key families once per phase, unioned with `dream_synthesis_completions` (where `MinionQueue.prune` archives completed `dream:synth%` keys before deleting their rows, so `jobs prune` never makes a synthesized transcript eligible again), so existing brains skip with `already_synthesized_legacy_single_chunk`/`_chunked` instead of re-spending the synthesis model, and a transcript whose synth-v2 children already completed skips with `already_synthesized_v2_single_chunk`/`_chunked` (`findSynthV2Completion`; a cancelled row never counts) BEFORE its link manifest is built — otherwise queue.add's idempotency fast path coalesces onto the completed children and they re-enter writtenRefs, so their old pages get quote-repaired, restamped, reverse-written and re-embedded every night. `collectChildPutPageSlugs` raw-fetches every (job_id, slug) pair (not `SELECT DISTINCT`) and rewrites bare-hash6 slugs to `<hash6>-c<idx>` for chunked children (orchestrator-side, zero Sonnet trust). Cap-hit skips write nothing new to `dream_verdicts` (the pass's cached triage verdict remains — a free cache hit on retry) and record no synthesis job, so raising the cap on next run re-attempts cleanly. Bounds INITIAL prompt size only; tool-loop turn-N accumulation is caught by terminal-error classification in `subagent.ts`. Verdict routing is gateway-routed: `makeJudgeClient(verdictModel)` (exported) mirrors `tryBuildGatewayClient` in `src/core/think/index.ts` — a construction-time provider/key probe returns `null` on a clear miss (unknown provider id via `resolveRecipe` AIConfigError, or Anthropic provider with no key via `hasAnthropicKey()`). The verdict loop wraps `judgeSignificance` in try/catch for `AIConfigError` so mid-run provider failures surface as per-transcript `worth=false, reasons=['gateway error: ...']` instead of crashing the phase. Canonical config key `models.dream.synthesize_verdict` (per `PER_TASK_KEYS` in `src/core/model-config.ts`); `JudgeClient` signature preserved verbatim for test-seam stability; CI guard `scripts/check-gateway-routed-no-direct-anthropic.sh` prevents reintroducing `new Anthropic()` here or in `think/index.ts`. At the queue.add boundary a conditional `anthropic:` prefix is applied ONLY when the resolved model has no colon AND starts with `claude-` (because `resolveModel` returns bare ids from `TIER_DEFAULTS`/`DEFAULT_ALIASES` and the subagent validator requires `provider:model` form) — avoids changing the shared constants which would ripple across every `resolveModel` caller. Pinned by `test/cycle/synthesize-gateway-adapter.test.ts`, `test/e2e/dream-synthesize-pglite.test.ts` (gateway-adapter mid-run AIConfigError catch), `test/cycle/regression-pr-wave-r1-r2-r4.test.ts`. Drain-loop lock renewal runs through exported `runDrainRenewalTick` (per-call AbortSignal + timeout + re-entrancy guard) — a hung renewLock cannot stack one checked-out slot per interval firing. Pinned by `test/cycle-drain-renewal.test.ts`. Execution mode: `dream.synthesize.mode` (default `oneshot`) threads to every child as `data.mode` alongside `oneshot_slug_suffix` (the structural suffix contract) and `require_writes: true`; `details.synthesis` adds mode/oneshot_jobs/fallback_jobs/agentic_jobs/fallback_reasons plus the drain telemetry (inline_concurrency_config/effective, drain_ms, queue-wait + runtime p50/p95, dead_jobs, degraded). Pre-retrieval LINK CANDIDATES manifest (link-manifest.ts, `dream.synthesize.link_manifest` default on) is built once per transcript from the cached triage entities/segment notes and spliced into `buildSynthesisPrompt` together with an ALLOWED WRITE PATHS block rendered from the trusted allow-list (the oneshot path never sees a tool schema, so the fence lives in the prompt; rule 2 points at the candidates first). Phase outcome gate: ALL children dead/cancelled → phase fails with SYNTH_ALL_CHILDREN_DEAD (fan-out details preserved on the failure); ANY non-completed child → the cooldown stamp is skipped so released idempotency keys retry next run; 'timeout' (parent stopped waiting) degrades but never triggers the all-dead error. Phase-end deferred-embed closure: whenever the phase wrote pages (regardless of mode — an agentic revert still sweeps debt left by earlier oneshot runs), a 120s-bounded `embedStalePages` (embed-stale.ts) embeds the NULL-embedding chunks of exactly the pages this phase wrote — never a source-wide sweep; the pre-existing stale backlog stays with the budget-tracked embed-backfill machinery — closing the gap on invocation shapes that never reach the global embed phase (`--phase synthesize`, autopilot per-source NON_GLOBAL_PHASES). Best-effort (never fails a phase that wrote its pages) and stamps the current embedding signature on fully-re-embedded pages so they stay inside the model-drift invalidation contract. The inline drain lives in `src/core/cycle/inline-drain.ts` (re-exported here for patterns.ts + `__testing`). Budget clamping: clamped to the remaining parent-job budget when `opts.deadlineAtMs` is threaded (via patterns.ts's `clampSubagentBudgets` template): the clamp re-runs against the live clock PER SUBMIT (the phase is a fan-out with claim-time-anchored child kill switches, so one phase-start clamp only bounds the first child); under the minimum child budget the phase skips honestly (`insufficient_cycle_budget`) or defers the remaining transcripts (`details.budget_deferred_transcripts`), the inline drain stops CLAIMING when the budget can't fit another child and unclaimed children are cancelled + deferred (they'd otherwise strand forever in the run's private queue), each completion wait is additionally bounded by the remaining parent budget (floored at 1s so already-terminal children still resolve), and a deferring run neither writes the 12h cooldown timestamp nor counts deferred transcripts as processed — deferral genuinely retries next cycle. THE gate is `passesTriageGate` (triage-rescue.ts) applied at report construction inside `runTriagePass`: threshold pass OR the verified-segment rescue for band scores `[dream.triage.rescue_floor (0.30), threshold)` with content_type in `dream.triage.rescue_content_types` and ≥ `dream.triage.rescue_min_segments` (default 2; 0 = off) of the judge's segments verifying as normalized transcript substrings (≥40 chars, deduped) — reports carry `rescued`/`verified_segments`, `details.triage` adds rescue_band/rescue_checked/rescue_fired + judge tokens_in/tokens_out/cost_usd (null when unpriced), and dream-retriage's reconcile/audit read the SAME predicate. TRIAGE_VERSION is 2 (peak-not-average rubric; segment selection prefers concrete facts/decisions). After slug collection and BEFORE the provenance stamp/reverse-write/embed sweep, the claim verification pass (synthesize-verify.ts, `dream.synthesize.quote_verify` default on) runs on every page the children wrote, scoped by `readVerifyEpoch` (taken before fan-out) and `loadChildWriteEpochs`; the phase is wrapped in `withChatPhase('phase:synthesize')` (children keep their own job tag — minion_jobs stays the child-spend authority) and `details.synthesis` adds `quote_verify`, `children_zero_pages` (completed children with zero put_page writes — the rule-D disposition), and `spend` (`cost_basis: 'in+out+cache_read'`; children summed from minion_jobs tokens_input/output/cache_read priced at the configured synth model, triage from the pass usage; total_usd null unless both price) `buildSynthesisPrompt` is mode-aware (`mode: 'agentic' | 'oneshot'`, passed from `config.mode` at the sole submit site): agentic children keep the search-tool and final-summary guidance; tool-less oneshot children receive neither, so the prompt never contradicts `ONESHOT_SYSTEM`'s JSON-only rule (the oneshot prompt is stored as `data.prompt` and reused verbatim by the in-job agentic fallback, whose tools stay in the schema). Pinned by `test/cycle-dream-output-root.test.ts`. Managed enabled local synthesis uses durable page admission with original authority and canonical-mirror validation; completed source-incarnation-qualified children survive restart. Quote-repair failure cannot silently certify grounded publication. Remote maintenance remains unsupported. Before submitting a transcript's chunk set, the phase asks the paid-loop breaker (`dream-breaker.ts`) and records a `dream_breaker_tripped` skip with the reset command instead of submitting; the opt-in daily cap counts dead rows through their released key.+- `src/core/cycle/synthesize.ts` — Synthesize phase: conversation-transcript-to-brain pipeline, a two-stage cascade where cheap scored triage gates frontier synthesis. Reads `dream.synthesize.session_corpus_dir`, runs `runTriagePass` (exported; bounded pool `dream.triage.concurrency` default 4, wall-clock cache-MISS budget `dream.triage.max_ms` default 5 min — cache hits are free and deferred files report `deferred: true`, never cached, so the next pass continues) whose judge `judgeSignificance` emits `{score 0-1 ordinal salience, content_type, segments ≤8 verbatim quotes, entities ≤12, reasons}` (non-overlapping bands LOW 0-0.29 / MEDIUM 0.30-0.69 / HIGH 0.70-1.0; head 50%/middle 20%/tail 30% sample within `dream.triage.max_chars` default 24K via `safeSplitIndex`; out-of-[0,1] scores are `unparseable`, never clamped) cached in `dream_verdicts` with the judging `model` + `TRIAGE_VERSION` — cache validity requires BOTH to match (switching `models.dream.triage` re-judges; `max_chars`/`max_tokens` deliberately excluded from validity — `dream retriage --force` re-judges under new sampling knobs). Degenerate verdicts (`truncated`/`refusal`/`unparseable`) are never cached. THE gate is `passesTriageGate` (triage-rescue.ts): `score >= dream.triage.threshold` (default 0.5) OR the verified-segment rescue, applied at report construction inside `runTriagePass` at READ time — retuning the threshold or rescue knobs re-gates with zero re-judging; the stored `worth_processing` boolean derives from the fixed `DEFAULT_TRIAGE_THRESHOLD` constant (back-compat only, never the live dial). Passing files fan out one subagent per chunk with `max_turns` from `dream.synthesize.max_turns` (default 16) and a bounded advisory `buildTriageMapBlock` (exported; score/type/entities + chunk-filtered segments, '' for legacy/degraded verdicts so the prompt is unchanged for those) spliced into `buildSynthesisPrompt`, with `allowed_slug_prefixes` (sourced from `skills/_brain-filing-rules.json` `dream_synthesize_paths.globs`; when `dream.synthesize.output_root` is set, `loadAllowedSlugPrefixes(outputRoot)` remaps the `wiki/`-rooted globs to the configured namespace, and the same root drives the prompt slug templates; default 'wiki', validated against the slug grammar via the exported `loadOutputRoot`). The phase is source-scoped: cycle.ts threads `cycleSourceId` as `opts.sourceId` → each child's `SubagentHandlerData.source_id` → the subagent tool registry's `OperationContext.sourceId`, so put_page writes, collected refs, the summary page, and reverse-writes all target the cycle's resolved source ('default' when unscoped; reverse-writes for the cycle's own source land at `brainDir/<slug>.md`, foreign sources under `brainDir/.sources/<id>/`). Orchestrator collects slugs from `subagent_tool_executions` (NOT `pages.updated_at`) and reverse-renders DB → markdown via `serializeMarkdown`. Cooldown via `dream.synthesize.last_completion_ts`, written only when children completed and neither synthesis-budget nor triage-budget deferrals remain. Idempotency keys `dream:synth-v2:<enc source>:filename:<enc basename>:<hash16>[:c<i>of<n>]` (byte-stable, pinned by `test/dream-synthesize-chunking.serial.test.ts`; grammar parsed by exported `parseSynthV2Key`). Fan-out self-heals idempotency-coalesced rows stranded `waiting` in a FOREIGN dead `dream-inline-*` queue (cancel releases the key slot → re-add into the live run's queue) instead of burning the 35-min wait on a row no worker will ever claim. Opt-in per-source daily submission cap `dream.synthesize.max_submissions_per_source_per_day` (default 0 = off; skips whole files — never partial chunk sets; bypassed for explicit `--input/--date/--from/--to` targets; count-query failure fails CLOSED: the run submits nothing and reports `daily_cap_unavailable`). Every transcript's whole chunk set is checked against a per-run USD `BudgetMeter` before submission (`dream.synthesize.budget_usd`, default 5; `0` submits nothing, `unlimited` removes the cap; estimate = prompt chars/4 plus the child output cap, times `max_turns` in agentic mode); a denied transcript and the rest of the run are deferred into `budget_deferred_transcripts` without a cooldown stamp, and `details.budget_usd` / `estimated_spend_usd` report the gate. `--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. The child prompt's date hint and the summary are dated by the cycle date (`cycleDate` from runCycle, else `resolveCycleDate`); opt-in `dream.synthesize.attribution_rules=true` adds `SYNTH_ATTRIBUTION_RULE` (keep who proposed what and later corrections explicit). `renderPageToMarkdown` (exported) stamps `dream_generated: true` + `dream_cycle_date` into every reverse-written dream-owned page (`isDreamOwnedPage`: created at or after the child's first put_page, or already stamped; a human page a child edited is rendered without the marker); `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 page a child created (the refs from `collectChildPutPageSlugs` carry `first_write_at`, the child's earliest put_page `started_at` per slug) or that is already stamped, BEFORE reverse-rendering; a pre-existing human page is never stamped, so generated pages are DB-queryable and a later put_page write-through (which re-renders from the DB row) can't erase the stamp. `judgeSignificance`, `JudgeClient`, `runTriagePass`, `buildTriageMapBlock`, `parseSynthV2Key`, `loadSynthConfig`, `TRIAGE_VERSION`, and `DEFAULT_TRIAGE_THRESHOLD` are exported; the triage model resolves via an explicit pre-read of `models.dream.triage` (preferred; through exported `resolveAlias`) falling back to the standard `resolveModel` chain (`models.dream.synthesize_verdict` → deprecated `dream.synthesize.verdict_model` → tier `utility`). `splitTranscriptByBudget(content, contentHash, maxChars)` splits oversized transcripts at paragraph boundaries (`## Topic:` → `---` → `\n` ladder) using a deterministic offset seeded from the first 32 bits of `contentHash` so retries chunk identically; per-chunk char budget = `MODEL_CONTEXT_TOKENS[resolvedModel] × 0.9 × 3.5 chars/token` (non-Anthropic ids fall back to a 180K-token safe default + once-per-process stderr warn); operator overrides `dream.synthesize.max_prompt_tokens` (floor 100K, wins) and `dream.synthesize.max_chunks_per_transcript` (default 24); per-chunk subagent job/wait timeouts are `dream.synthesize.subagent_timeout_ms` / `dream.synthesize.subagent_wait_timeout_ms` (defaults 30/35 min). Legacy `dream:synth:` keys are never produced — `loadSuccessfulSynthesisKeys(engine, sourceId, keyPrefix)` reads the completed rows of BOTH key families once per phase, unioned with `dream_synthesis_completions` (where `MinionQueue.prune` archives completed `dream:synth%` keys before deleting their rows, so `jobs prune` never makes a synthesized transcript eligible again), so existing brains skip with `already_synthesized_legacy_single_chunk`/`_chunked` instead of re-spending the synthesis model, and a transcript whose synth-v2 children already completed skips with `already_synthesized_v2_single_chunk`/`_chunked` (`findSynthV2Completion`; a cancelled row never counts) BEFORE its link manifest is built — otherwise queue.add's idempotency fast path coalesces onto the completed children and they re-enter writtenRefs, so their old pages get quote-repaired, restamped, reverse-written and re-embedded every night. `collectChildPutPageSlugs` raw-fetches every (job_id, slug) pair (not `SELECT DISTINCT`) and rewrites bare-hash6 slugs to `<hash6>-c<idx>` for chunked children (orchestrator-side, zero Sonnet trust). Cap-hit skips write nothing new to `dream_verdicts` (the pass's cached triage verdict remains — a free cache hit on retry) and record no synthesis job, so raising the cap on next run re-attempts cleanly. Bounds INITIAL prompt size only; tool-loop turn-N accumulation is caught by terminal-error classification in `subagent.ts`. Verdict routing is gateway-routed: `makeJudgeClient(verdictModel)` (exported) mirrors `tryBuildGatewayClient` in `src/core/think/index.ts` — a construction-time provider/key probe returns `null` on a clear miss (unknown provider id via `resolveRecipe` AIConfigError, or Anthropic provider with no key via `hasAnthropicKey()`). The verdict loop wraps `judgeSignificance` in try/catch for `AIConfigError` so mid-run provider failures surface as per-transcript `worth=false, reasons=['gateway error: ...']` instead of crashing the phase. Canonical config key `models.dream.synthesize_verdict` (per `PER_TASK_KEYS` in `src/core/model-config.ts`); `JudgeClient` signature preserved verbatim for test-seam stability; CI guard `scripts/check-gateway-routed-no-direct-anthropic.sh` prevents reintroducing `new Anthropic()` here or in `think/index.ts`. At the queue.add boundary a conditional `anthropic:` prefix is applied ONLY when the resolved model has no colon AND starts with `claude-` (because `resolveModel` returns bare ids from `TIER_DEFAULTS`/`DEFAULT_ALIASES` and the subagent validator requires `provider:model` form) — avoids changing the shared constants which would ripple across every `resolveModel` caller. Pinned by `test/cycle/synthesize-gateway-adapter.test.ts`, `test/e2e/dream-synthesize-pglite.test.ts` (gateway-adapter mid-run AIConfigError catch), `test/cycle/regression-pr-wave-r1-r2-r4.test.ts`. Drain-loop lock renewal runs through exported `runDrainRenewalTick` (per-call AbortSignal + timeout + re-entrancy guard) — a hung renewLock cannot stack one checked-out slot per interval firing. Pinned by `test/cycle-drain-renewal.test.ts`. Execution mode: `dream.synthesize.mode` (default `oneshot`) threads to every child as `data.mode` alongside `oneshot_slug_suffix` (the structural suffix contract) and `require_writes: true`; `details.synthesis` adds mode/oneshot_jobs/fallback_jobs/agentic_jobs/fallback_reasons plus the drain telemetry (inline_concurrency_config/effective, drain_ms, queue-wait + runtime p50/p95, dead_jobs, degraded). Pre-retrieval LINK CANDIDATES manifest (link-manifest.ts, `dream.synthesize.link_manifest` default on) is built once per transcript from the cached triage entities/segment notes and spliced into `buildSynthesisPrompt` together with an ALLOWED WRITE PATHS block rendered from the trusted allow-list (the oneshot path never sees a tool schema, so the fence lives in the prompt; rule 2 points at the candidates first). Phase outcome gate: ALL children dead/cancelled → phase fails with SYNTH_ALL_CHILDREN_DEAD (fan-out details preserved on the failure); ANY non-completed child → the cooldown stamp is skipped so released idempotency keys retry next run; 'timeout' (parent stopped waiting) degrades but never triggers the all-dead error. Phase-end deferred-embed closure: whenever the phase wrote pages (regardless of mode — an agentic revert still sweeps debt left by earlier oneshot runs), a 120s-bounded `embedStalePages` (embed-stale.ts) embeds the NULL-embedding chunks of exactly the pages this phase wrote — never a source-wide sweep; the pre-existing stale backlog stays with the budget-tracked embed-backfill machinery — closing the gap on invocation shapes that never reach the global embed phase (`--phase synthesize`, autopilot per-source NON_GLOBAL_PHASES). Best-effort (never fails a phase that wrote its pages) and stamps the current embedding signature on fully-re-embedded pages so they stay inside the model-drift invalidation contract. The inline drain lives in `src/core/cycle/inline-drain.ts` (re-exported here for patterns.ts + `__testing`). Budget clamping: clamped to the remaining parent-job budget when `opts.deadlineAtMs` is threaded (via patterns.ts's `clampSubagentBudgets` template): the clamp re-runs against the live clock PER SUBMIT (the phase is a fan-out with claim-time-anchored child kill switches, so one phase-start clamp only bounds the first child); under the minimum child budget the phase skips honestly (`insufficient_cycle_budget`) or defers the remaining transcripts (`details.budget_deferred_transcripts`), the inline drain stops CLAIMING when the budget can't fit another child and unclaimed children are cancelled + deferred (they'd otherwise strand forever in the run's private queue), each completion wait is additionally bounded by the remaining parent budget (floored at 1s so already-terminal children still resolve), and a deferring run neither writes the 12h cooldown timestamp nor counts deferred transcripts as processed — deferral genuinely retries next cycle. THE gate is `passesTriageGate` (triage-rescue.ts) applied at report construction inside `runTriagePass`: threshold pass OR the verified-segment rescue for band scores `[dream.triage.rescue_floor (0.30), threshold)` with content_type in `dream.triage.rescue_content_types` and ≥ `dream.triage.rescue_min_segments` (default 2; 0 = off) of the judge's segments verifying as normalized transcript substrings (≥40 chars, deduped) — reports carry `rescued`/`verified_segments`, `details.triage` adds rescue_band/rescue_checked/rescue_fired + judge tokens_in/tokens_out/cost_usd (null when unpriced), and dream-retriage's reconcile/audit read the SAME predicate. TRIAGE_VERSION is 2 (peak-not-average rubric; segment selection prefers concrete facts/decisions). After slug collection and BEFORE the provenance stamp/reverse-write/embed sweep, the claim verification pass (synthesize-verify.ts, `dream.synthesize.quote_verify` default on) runs on every page the children wrote, scoped by `readVerifyEpoch` (taken before fan-out) and `loadChildWriteEpochs`; the phase is wrapped in `withChatPhase('phase:synthesize')` (children keep their own job tag — minion_jobs stays the child-spend authority) and `details.synthesis` adds `quote_verify`, `children_zero_pages` (completed children with zero put_page writes — the rule-D disposition), and `spend` (`cost_basis: 'in+out+cache_read'`; children summed from minion_jobs tokens_input/output/cache_read priced at the configured synth model, triage from the pass usage; total_usd null unless both price) `buildSynthesisPrompt` is mode-aware (`mode: 'agentic' | 'oneshot'`, passed from `config.mode` at the sole submit site): agentic children keep the search-tool and final-summary guidance; tool-less oneshot children receive neither, so the prompt never contradicts `ONESHOT_SYSTEM`'s JSON-only rule (the oneshot prompt is stored as `data.prompt` and reused verbatim by the in-job agentic fallback, whose tools stay in the schema). Pinned by `test/cycle-dream-output-root.test.ts`. Managed enabled local synthesis uses durable page admission with original authority and canonical-mirror validation; completed source-incarnation-qualified children survive restart. Quote-repair failure cannot silently certify grounded publication. Remote maintenance remains unsupported. Before submitting a transcript's chunk set, the phase asks the paid-loop breaker (`dream-breaker.ts`) and records a `dream_breaker_tripped` skip with the reset command instead of submitting; the opt-in daily cap counts dead rows through their released key.- `src/core/cycle/transcript-discovery.ts` — Pure filesystem walk for synthesize. `discoverTranscripts(opts)` filters `.txt` files by date range, min_chars, and word-boundary regex `excludePatterns` (`medical` matches "medical advice" but NOT "comedical"; power users may pass full regex). `readSingleTranscript(path)` is the `gbrain dream --input <file>` ad-hoc path. Self-consumption guard: `DREAM_OUTPUT_MARKER_RE` (anchored at frontmatter open `---\n`, optional BOM + CRLF tolerance, scans first 2000 chars for `dream_generated: true` with case-insensitive value and word boundary on `true`) drives `isDreamOutput(content, bypass=false)`. Both functions skip matching files and emit a `[dream] skipped <basename>: dream_generated marker` stderr log (no silent skips). An `excludePatterns` hit is never logged per file (the matching files are sensitive by definition); instead both functions emit ONE `[dream] excluded N transcript(s) matching exclude_patterns (<label>: n, ...)` stderr line at the end of discovery, naming only the count and the configured pattern labels that fired, never a path, basename, or content. `DEFAULT_EXCLUDE_PATTERNS` is unchanged (`medical`, `therapy`). `bypassGuard?: boolean` on `DiscoverOpts` and `readSingleTranscript`'s opts disables the guard for the explicit `--unsafe-bypass-dream-guard` escape hatch only — never auto-applied for `--input`. Two path-level guards run before the content read: `selfCaptureSessionIds` (from `claudeCliSelfSessionIds`) skips a `.txt` corpus file (session-end, checkpoint segment or writeback form, via `corpusFileSessionId`) captured from gbrain's own claude-cli call, and `excludeDirs` (synthesize passes the reflections, originals, patterns-output and cycle-summary directories under `brainDir`, empty under `--unsafe-bypass-dream-guard`) skips any file whose resolved path sits inside one, so an output a failed postprocess left unmarked is never re-synthesized while a transcript that merely names such a path is still discovered; each class is reported as one count-only stderr line.diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.mdindex f199a938f2..b1b75b7397 100644--- a/docs/architecture/key-files/core-persistence.md+++ b/docs/architecture/key-files/core-persistence.md@@ -32,7 +32,7 @@ The page operations that submit through this layer are in [Core Services (2/3)](- `src/core/persistence/params.ts` — runtime-leaf mutation parameter and receipt schemas shared with the frozen verb registry. Its operation-contract import is type-only; runtime validators live in separate modules to avoid a registry initialization cycle. `preconditions.ts` validates UUID/revision/force syntax. `purge-params.ts` validates local-only purge shape/trust before admission and publication, keeping purge diagnostics out of generic precondition imports and unrelated command flag scans. `test/persistence-cold-import.test.ts` loads each validator/contract/registry entry in a fresh process and preserves schema and typed-error identity.-- `src/core/persistence/{effect-schema,effect-model,effect-journal,effect-recovery,effect-git,effects}.ts` — bounded postcommit outbox (migration 155). Canonical publication atomically queues Git and embedding work; withdrawals queue three versioned, bounded exact-page manifests with durable slug cursors. `effect-targets.ts` converts legacy source scans with complete bounded discovery while retaining each cursor; ambiguous or over-capacity legacy intent stays pending. Older workers must be quiesced before rollout. Independent mirror recovery reserves capacity before file effects, finishes forward without changing revision or receipt, and blocks only its worktree until reconciled. Git holds the native root lock, disables hooks, uses literal pathspecs and target-only commits, and pushes without pull/rebase. A Git effect for a declared db_only page completes as skipped (`reason: db_only`), keeping its gitignored cache file out of Git. A Git or withdrawal target parks after five consecutive execution failures (`data.target_failures` for `data.failing_target`, reset when the target advances or a different target fails; shutdown cancellation, contention, dependency waits (including recovery-capacity waits) and transient database failures do not count): a scan records it in `data.parked` and moves on, a single-target effect or a failure outside any target parks the whole effect, and an effect with parked targets finishes as `failed`/`targets_parked`, never committed. Migration 170 indexes parked effects for the `parked_effects` doctor check. `retryParkedEffects` (the `retry-effects` admin path) previews parked targets or authorizes one more attempt per target (`data.retry_slugs`, visited before the cursor); tests: `persistence-effect-parking.test.ts`. Old targets resolve under the same hash/confinement checks without changing frozen data; ambiguous absent spellings refuse after scoped staged/unstaged deletion checks. Embedding runs outside transactions/OS locks and installs with projection CAS. Receipt helpers return only public effect state/reason/push. Consumer shutdown aborts providers and awaits workers; receipt compaction is bounded. Tests: `persistence-effects.test.ts`, `persistence-git-publication.test.ts`, `persistence-publication-native.serial.test.ts`. Embedding completion checks active column/vector, embedded stamp, text hash, model and page signature; partial work sends only stale chunks and preserves valid siblings. A partial synopsis rebuild completes before title demotion. Provider timeouts use the gateway budget, five durable page claims/backoff, execution-token CAS after provider work and atomic vector/stamp/effect completion. Keyless work skips cleanly. `retry-effects` is an explicit one-shot failed-effect allowance; current vectors reconcile provider-free without changing canonical receipts.+- `src/core/persistence/{effect-schema,effect-model,effect-journal,effect-recovery,effect-git,effects}.ts` — bounded postcommit outbox (migration 155). Canonical publication atomically queues Git and embedding work; withdrawals queue three versioned, bounded exact-page manifests with durable slug cursors. `effect-targets.ts` converts legacy source scans with complete bounded discovery keyed on the request's own forgotten fact (falling back to the whole source ledger only when that fact row is gone) while retaining each cursor; ambiguous or over-capacity legacy intent stays pending. Older workers must be quiesced before rollout. Independent mirror recovery reserves capacity before file effects, finishes forward without changing revision or receipt, and blocks only its worktree until reconciled. Git holds the native root lock, disables hooks, uses literal pathspecs and target-only commits, and pushes without pull/rebase. A Git effect for a declared db_only page completes as skipped (`reason: db_only`), keeping its gitignored cache file out of Git. A Git or withdrawal target parks after five consecutive execution failures (`data.target_failures` for `data.failing_target`, reset when the target advances or a different target fails; shutdown cancellation, contention, dependency waits (including recovery-capacity waits) and transient database failures do not count): a scan records it in `data.parked` and moves on, a single-target effect or a failure outside any target parks the whole effect, and an effect with parked targets finishes as `failed`/`targets_parked`, never committed. Migration 170 indexes parked effects for the `parked_effects` doctor check. `retryParkedEffects` (the `retry-effects` admin path) previews parked targets or authorizes one more attempt per target (`data.retry_slugs`, visited before the cursor); tests: `persistence-effect-parking.test.ts`. Old targets resolve under the same hash/confinement checks without changing frozen data; ambiguous absent spellings refuse after scoped staged/unstaged deletion checks. Embedding runs outside transactions/OS locks and installs with projection CAS. Receipt helpers return only public effect state/reason/push. Consumer shutdown aborts providers and awaits workers; receipt compaction is bounded. Tests: `persistence-effects.test.ts`, `persistence-git-publication.test.ts`, `persistence-publication-native.serial.test.ts`. Embedding completion checks active column/vector, embedded stamp, text hash, model and page signature; partial work sends only stale chunks and preserves valid siblings. A partial synopsis rebuild completes before title demotion. Provider timeouts use the gateway budget, five durable page claims/backoff, execution-token CAS after provider work and atomic vector/stamp/effect completion. Keyless work skips cleanly. `retry-effects` is an explicit one-shot failed-effect allowance; current vectors reconcile provider-free without changing canonical receipts.- `src/core/persistence/native-file-target.ts` — shared preparation/Git execution spelling resolution. Native directory-entry inode/device identity proves aliases; no global case folding or separator rewrite. Missing suffixes retain exact spelling, descendant symlinks and ambiguous aliases refuse, and physical root identity is rechecked. Exact POSIX case-distinct names and literal backslashes remain distinct.diff --git a/docs/architecture/key-files/core-search-1.md b/docs/architecture/key-files/core-search-1.mdindex aef89f3d14..c8b5c31ce9 100644--- a/docs/architecture/key-files/core-search-1.md+++ b/docs/architecture/key-files/core-search-1.md@@ -5,6 +5,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/search/` — Hybrid search: vector + keyword + RRF + multi-query expansion + dedup. `searchKeyword`/`searchKeywordChunks`/`searchVector` apply source-aware ranking at the SQL layer (curated content like `originals/`, `concepts/`, `writing/` outranks bulk content like `<fork>/chat/`, `daily/`, `media/x/`). `searchVector` uses a two-stage CTE so source-boost re-ranking doesn't kill the HNSW index. Hard-exclude prefixes (`test/`, `archive/`, `attachments/`, `.raw/` by default) filter at retrieval, not post-rank. Both gates honor `detail !== 'high'` so temporal queries surface chat pages normally.+- `src/core/search/alias-hop.ts` — the post-rerank alias hop (`applyAliasHop`, re-exported by `hybrid.ts`), the opt-in single-token hop (`applyAliasTokenHop`, #5428) and the exclude contract both identity injections share (`IdentityTierOpts`, `isExcludedIdentity`; `exact-lookup.ts` imports it). Behavior is documented under the `hybrid.ts` entry. Pinned by `test/search/alias-hop.test.ts`, `test/search/alias-token-hop.test.ts`, `test/search/injection-excludes-keyword-boost.test.ts`.- `src/core/search/alias-normalize.ts` — ONE normalizer shared by the WRITE path (ingest projects frontmatter `aliases:` into `page_aliases`) and the READ path (search matches query against `page_aliases`), so stored aliases can't silently fail to match queries via divergent normalization (same single-source posture as `cjk.ts`). `normalizeAlias(raw)` does NFKC + lowercase + whitespace-collapse + trim + strip one layer of wrapping quotes/brackets; returns `''` for empty (callers MUST skip empty aliases). `normalizeAliasList(value)` coerces a frontmatter scalar / array / comma-list / garbage into a deduped list of normalized non-empty aliases — used by both the ingest projection and the `reindex --aliases` backfill.- `src/core/search/arm-confidence.ts` — arm-confidence-weighted fusion for the keyword arm (`search.keyword_arm_confidence_floor`; `null` = off in every bundle — the pre-registered Cat 13 E2 mechanism FAILED its held-out rule at the calibrated floor 0.6121 (53.0 → 53.0), so the knob ships default off for operators and the receipt is published). `keywordArmConfidence(rows)` reads the strict keyword arm's raw `score` column into a scale-free statistic (`top`, `second`, `margin_ratio`; TypeScript-side — engines still return raw `ts_rank × sourceFactor`, no SQL change); `decideKeywordArmWeight({keywordList, floor, vectorArmVoted, relationalQuery})` down-weights the keyword AND title fusion entries to `KEYWORD_ARM_WEAK_WEIGHT` (0.5) only when the floor is set, the keyword list is non-empty, a text vector arm voted, the query is not relational, and `margin_ratio < floor`; otherwise it emits no weight (byte-identical fusion). It is called from `composeFusionLists` (`fusion-lists.ts`) so the weight lands through the same per-list `weight` primitive as the expansion budget, never a k change. `normalizeKeywordArmConfidenceFloor` is the ONE range contract (number in `(0, 1]` or a string parsing to one; `null`/`false`/`off` → `null`; anything else → `undefined` = fall through), shared by `mode.ts:loadOverridesFromConfig` and both per-call seams in `hybrid.ts`. The decision (`{top, second, margin_ratio, downweighted}`) is surfaced as `HybridSearchMeta.keyword_arm_confidence` even with the floor off, so a calibration run can pick a floor from per-probe receipts; knobs-hash part `kacf=`. Pinned by `test/search/arm-confidence.test.ts` (pure contract) and `test/search/arm-confidence-hybrid.test.ts` (hermetic PGLite: a weak keyword arm is down-weighted only with the floor set; off is byte-identical).@@ -31,7 +32,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/search/graph-signals.ts` — per-query graph-signals helper. `applyGraphSignals(results, engine, opts)` runs as the 4th post-fusion stage (after backlink/salience/recency). Three boosts: `ADJACENCY_BOOST=1.05` (page linked from 2+ OTHER top-K results — local hub for THIS query), `CROSS_SOURCE_BOOST=1.10` (page linked from 2+ DIFFERENT sources — corroborated across team brains, dormant in single-source brains), `SESSION_DEMOTE=0.95` (3+ results from same chat session — keep the highest-scoring at full score, demote the rest). All three inherit the floor-ratio gate preventing weak pages from being boosted past strong ones via popularity. `computeScoreDistribution(results)` emits min/p25/p50/p75/p95/max + `reorder_band_width`. `sessionPrefix(slug)` extracts the chat-session anchor (`chat/2026-05-15-...`). Pure `pairedBootstrapPValue(deltas, resamples, rng)` exported for eval gates. Test seam via `adjacencyFn` DI. Fail-open: any error logs via `logGraphSignalsFailure` (JSONL audit via `audit-writer`) and returns the input array unchanged. Pinned by `test/search/graph-signals.test.ts` (incl. the IRON-RULE floor-gate guard). The atoms/ namespace is excluded from session diversification even when a later segment resembles a date or chat marker; daily, meeting and transcript siblings retain their existing demotion.-- `src/core/search/hybrid.ts` — `Promise<SearchResult[]>` return shape. `onMeta?: (m: HybridSearchMeta) => void` callback so op-layer capture records what hybridSearch actually did; callers that don't need it leave it undefined. `HybridSearchOpts.queryEmbedFn?: (text) => Float32Array | Promise<Float32Array>` is the hermetic eval seam: when set, the TEXT vector arm's query embedding comes from this function instead of the gateway's query-embed path AND the no-embedding-provider keyword-only short-circuit is bypassed, so deterministic eval canaries (`gbrain eval gate --embedder deterministic`, `scripts/run-eval-canary.ts`) run the vector arm with no provider key; never set on production paths — absent, the production path is untouched, and bare `hybridSearch` never touches the semantic query cache so the seam can't poison `query_cache`. `HybridSearchOpts.types?: PageType[]` (on `SearchOpts`) threads a multi-type filter into per-engine `searchKeyword` + `searchVector` + `searchKeywordChunks` as `AND p.type = ANY($N::text[])` (primary consumer `gbrain whoknows`, filters to `['person','company']`); AND-applies alongside the single-value `type` filter. `hybridSearch` resolves the embedding column at the boundary via `resolveColumn(loadRegistry(cfg), opts.embedding_column, cfg)` from `src/core/search/embedding-column.ts`, threads the `ResolvedColumn` descriptor (not a raw string) into per-engine `searchVector`, and uses `isCacheSafe(resolved, cfg)` for the cache-skip decision so a repointed `embedding` builtin doesn't leak across vector spaces. `cosineReScore` calls `engine.getEmbeddingsByChunkIds(ids, resolved.name)` so rerank uses vectors from the active column, not the hardcoded OpenAI `embedding`, and hydrates each result's raw query↔chunk `cosine` onto `SearchResult` (the calibrated signal evidence and `--explain` consume). `SearchOpts.onVectorPoolMeta` reports bounded candidate incompleteness after up to three pool escalations. SQL limits and offsets are independent of ef_search, filtered short pools need an exhaustion witness, and Postgres alone can use one exact fallback inside the remaining deadline. Hybrid and direct image query paths publish the scoped details and recall-affecting degraded stage; an exhausted genuine small corpus does not emit a false warning. The `query` MCP op accepts `embedding_column` for per-call A/B; `search` (keyword-only) rejects it. Two post-fusion stages + evidence stamp: `applyTitleBoost(results, query, titleBoost, floorThreshold)` multiplies a result's score by the resolved `title_boost` when `isTitlePhraseMatch` fires, stamps `title_match_boost`, inherits the floor-ratio gate so a title match can't shove a much-stronger page below it; `applyAliasHop(engine, results, query, opts)` normalizes the query, calls `engine.resolveAliases`, and on exact normalized-alias match surfaces that page at top-of-organic + epsilon with `alias_hit=true` (skipping `exclude_slugs`). Both post-rerank identity tiers (alias hop, `applyExactLookupTier`) are ORDER-PRESERVING: identity rows move to the front and every other row keeps its input (reranked) order — never a global re-sort by `score`, which is still the fusion score after reranking; `stampEvidence(...)` runs LAST (after the alias hop, before slice) on every path — keyword-only, no-embed, and full hybrid — so MCP callers and `--explain` read the same `evidence` + `create_safety` contract. `title_boost` resolved from the mode bundle and threaded in. `runPostFusionStages` has a 4th stage (`graphSignalsEnabled`, `onGraphMeta`, `onScoreDistribution`). `base_score` stamped at function entry idempotently (captured ONCE before any boost stage mutates `score`). Each post-fusion stage stamps its multiplier: `applyBacklinkBoost`→`backlink_boost`, `applySalienceBoost`→`salience_boost`, `applyRecencyBoost`→`recency_boost`. `applyReranker` (earlier in the pipeline) stamps `reranker_delta` as a rank delta (positive = improved). `applyExactMatchBoost` in `src/core/search/intent-weights.ts` stamps `exact_match_boost` when fired — on an exact slug/title match OR a title / slug tail mentioned inside the query (`isTitleMentionedInQuery`), and `applyAliasMentionBoost` gives the same bounded boost to a present row whose declared alias occurs in the query (one batched `resolveAliases` over 1–5-token query n-grams, fail-open). **Fusion is page-grain:** `rrfFusion`/`rrfFusionWeighted` sum each list's vote per page `(source_id, slug)` (a list counts a page once, at its best rank) and the page's LEAD chunk (largest own vote; ties to the first list, a vector arm) carries the page's summed score while the page's other chunks keep their own votes — giving every chunk the page score let a page's second chunk crowd other pages out of chunk-limited results. Every arm is page-grain with its own representative chunk, so chunk-keyed fusion split a page's cross-arm agreement. **Detail:** only an EXPLICIT `detail: 'low'` hard-filters every arm to compiled truth (with the 2x boost and the zero-result escalation); an auto-detected `low` (entity intent) passes no SQL filter and applies `AUTO_LOW_COMPILED_TRUTH_TILT` (1.2x) via `compiledTruthFusionBoost`. The engine opts rebuild forwards `exclude_slugs`, `exclude_slug_prefixes` and `include_slug_prefixes` to every arm. Under unified multimodal routing the cosine rescore hydrates `embedding_multimodal` (the space the query was embedded in), and `cosineSimilarity` returns 0 for vectors of different lengths. Per-stage attribution powers `gbrain search --explain` — every boost surface carries its own field so `formatResultsExplain` reads them all without coupling to internal stage ordering. with `src/core/search/sql-ranking.ts` + `src/core/operations.ts` + `src/core/types.ts`: agent-warning channel. `SearchResult.content_flag?: {reason, detail}` (optional field in `types.ts`) is stamped post-fusion by `stampContentFlags` (the `stampEvidence` precedent) in `hybridSearch` AND in the keyword-only `search` MCP op so both retrieval paths surface the marker. `get_page` returns a top-level `content_flag` parallel field via `getContentFlag(page.frontmatter)`. `buildVisibilityClause` (sql-ranking.ts) ANDs in `QUARANTINE_FILTER_FRAGMENT` so quarantined pages are excluded from all six search call sites (alongside soft-delete + archived-source filters). Pinned by `test/sql-ranking.test.ts` + `test/e2e/quarantine-search-exclusion.test.ts`. Cross-modal routing at the embed step: `effectiveModality` resolves per-call `opts.crossModal` (literal `'auto'` → undefined) → `suggestions.suggestedModality` → `'text'`. Image route: `embedQueryMultimodal` + `searchVector({embeddingColumn: 'embedding_image'})`, skipping expansion + keyword. `'both'` route: parallel text + image vector searches merged via `rrfFusionWeighted` with `effectiveRrfK(baseRrfK, weight)` from the configured cross-modal weights. Unified routing fires when `search.unified_multimodal` is true — bypasses dual-column branching, runs `embedQueryMultimodal` + `searchVector({embeddingColumn: 'embedding_multimodal'})`, fail-open on zero rows (non-strict falls through to dual-column). LLM modality escalation fires only when no explicit per-call opt is set AND the regex returned `'text'` AND `search.cross_modal.llm_intent` is on AND `isAmbiguousModalityQuery` fires; fail-open on every error. `compiledTruthBoost(result, applyBoost)` is exported for direct predicate tests: a synthetic chunkless title row (`chunk_id === 0` AND blank `chunk_text`) never receives the 2x compiled-truth boost (`test/search/compiled-truth-boost.test.ts`). The reranker pass-through callback is typed with `RerankPassThroughReason` imported from `rerank.ts` — one union, not a re-declaration. RRF inputs are assembled by ONE `composeFusionLists` call (next entry) over role-tagged `vectorArms` built with `pushVectorList` at every assembly site (unified, image-only, text/both, and the `allSettled` salvage path — where the `original` role additionally requires the original's `searchVector` to have succeeded); after `expandFn`, `queries[0]` is re-enforced to be the caller's query and repeats are deduped, so a variant can never take the anchor role. `HybridSearchOpts.onRerankPool` (eval-only, best-effort) fires immediately before `applyAutocut` with the exact pre-autocut `returnPool` — post alias-hop / exact-lookup / adaptive-return, unscored injected rows included, even when autocut is off — plus the deduped pre-rerank order, so an offline autocut replay is byte-faithful. Immediately after `applyReranker` — only when it actually reordered (`reranked !== deduped`) and never for image modality — `pinRelationalRows` (`relational-rerank-pin.ts`) re-pins the relational arm's rows above the reranked text rows bounded by `resolvedMode.relational_rerank_pin`, stamps `relational_pinned`, and emits `HybridSearchMeta.relational_rerank_pin`; `ensureRelationalEvidenceSlot` still runs after autocut (usually a no-op on relational queries now — it remains the page-1 guarantee for pin 0, reranker fail-open, and arm rows dropped before the pin).+- `src/core/search/hybrid.ts` — `Promise<SearchResult[]>` return shape. `onMeta?: (m: HybridSearchMeta) => void` callback so op-layer capture records what hybridSearch actually did; callers that don't need it leave it undefined. `HybridSearchOpts.queryEmbedFn?: (text) => Float32Array | Promise<Float32Array>` is the hermetic eval seam: when set, the TEXT vector arm's query embedding comes from this function instead of the gateway's query-embed path AND the no-embedding-provider keyword-only short-circuit is bypassed, so deterministic eval canaries (`gbrain eval gate --embedder deterministic`, `scripts/run-eval-canary.ts`) run the vector arm with no provider key; never set on production paths — absent, the production path is untouched, and bare `hybridSearch` never touches the semantic query cache so the seam can't poison `query_cache`. `HybridSearchOpts.types?: PageType[]` (on `SearchOpts`) threads a multi-type filter into per-engine `searchKeyword` + `searchVector` + `searchKeywordChunks` as `AND p.type = ANY($N::text[])` (primary consumer `gbrain whoknows`, filters to `['person','company']`); AND-applies alongside the single-value `type` filter. `hybridSearch` resolves the embedding column at the boundary via `resolveColumn(loadRegistry(cfg), opts.embedding_column, cfg)` from `src/core/search/embedding-column.ts`, threads the `ResolvedColumn` descriptor (not a raw string) into per-engine `searchVector`, and uses `isCacheSafe(resolved, cfg)` for the cache-skip decision so a repointed `embedding` builtin doesn't leak across vector spaces. `cosineReScore` calls `engine.getEmbeddingsByChunkIds(ids, resolved.name)` so rerank uses vectors from the active column, not the hardcoded OpenAI `embedding`, and hydrates each result's raw query↔chunk `cosine` onto `SearchResult` (the calibrated signal evidence and `--explain` consume). `SearchOpts.onVectorPoolMeta` reports bounded candidate incompleteness after up to three pool escalations. SQL limits and offsets are independent of ef_search, filtered short pools need an exhaustion witness, and Postgres alone can use one exact fallback inside the remaining deadline. Hybrid and direct image query paths publish the scoped details and recall-affecting degraded stage; an exhausted genuine small corpus does not emit a false warning. The `query` MCP op accepts `embedding_column` for per-call A/B; `search` (keyword-only) rejects it. Two post-fusion stages + evidence stamp: `applyTitleBoost(results, query, titleBoost, floorThreshold)` multiplies a result's score by the resolved `title_boost` when `isTitlePhraseMatch` fires, stamps `title_match_boost`, inherits the floor-ratio gate so a title match can't shove a much-stronger page below it; `applyAliasHop(engine, results, query, opts)` normalizes the query, calls `engine.resolveAliases`, and on exact normalized-alias match surfaces that page at top-of-organic + epsilon with `alias_hit=true`. Both identity injections (alias hop and exact-lookup tier) take one `IdentityTierOpts` built once per request and skip any slug `isExcludedIdentity` rejects: caller `exclude_slugs` plus the resolved prefix excludes (`resolveHardExcludes`: defaults, `GBRAIN_SEARCH_EXCLUDE`, per-call prefixes, minus `include_slug_prefixes`), on all three return paths. Opt-in single-token hop (#5428; per-call `aliasTokenHop` or brain config `search.alias_token_hop=true`, read in the mode snapshot): when the whole query is not an alias, a query token that is the alias of exactly one person/company identity page (`isIdentityEntity`) moves that page to the front or injects it, at most two pages, order-preserving for the rest. Both post-rerank identity tiers (alias hop, `applyExactLookupTier`) are ORDER-PRESERVING: identity rows move to the front and every other row keeps its input (reranked) order — never a global re-sort by `score`, which is still the fusion score after reranking; `stampEvidence(...)` runs LAST (after the alias hop, before slice) on every path — keyword-only, no-embed, and full hybrid — so MCP callers and `--explain` read the same `evidence` + `create_safety` contract. `title_boost` resolved from the mode bundle and threaded in. `runPostFusionStages` has a 4th stage (`graphSignalsEnabled`, `onGraphMeta`, `onScoreDistribution`). `base_score` stamped at function entry idempotently (captured ONCE before any boost stage mutates `score`). Each post-fusion stage stamps its multiplier: `applyBacklinkBoost`→`backlink_boost`, `applySalienceBoost`→`salience_boost`, `applyRecencyBoost`→`recency_boost`. `applyReranker` (earlier in the pipeline) stamps `reranker_delta` as a rank delta (positive = improved). `applyExactMatchBoost` in `src/core/search/intent-weights.ts` stamps `exact_match_boost` when fired — on an exact slug/title match OR a title / slug tail mentioned inside the query (`isTitleMentionedInQuery`), and `applyAliasMentionBoost` gives the same bounded boost to a present row whose declared alias occurs in the query (one batched `resolveAliases` over 1–5-token query n-grams, fail-open). **Fusion is page-grain:** `rrfFusion`/`rrfFusionWeighted` sum each list's vote per page `(source_id, slug)` (a list counts a page once, at its best rank) and the page's LEAD chunk (largest own vote; ties to the first list, a vector arm) carries the page's summed score while the page's other chunks keep their own votes — giving every chunk the page score let a page's second chunk crowd other pages out of chunk-limited results. Every arm is page-grain with its own representative chunk, so chunk-keyed fusion split a page's cross-arm agreement. **Detail:** only an EXPLICIT `detail: 'low'` hard-filters every arm to compiled truth (with the 2x boost and the zero-result escalation); an auto-detected `low` (entity intent) passes no SQL filter and applies `AUTO_LOW_COMPILED_TRUTH_TILT` (1.2x) via `compiledTruthFusionBoost`. The engine opts rebuild forwards `exclude_slugs`, `exclude_slug_prefixes` and `include_slug_prefixes` to every arm. A rejected keyword or title arm fails open and stamps `keyword_arm_failed` / `title_arm_failed` (reason `timeout | provider_error`) in `meta.degraded`, so MCP callers can tell a partial read from a clean miss. In `both` modality `cosineReScore` rescores image-arm rows in the image space (`embedding_image`, multimodal query vector); text rows keep the text column. The intent identity boosts (exact/mentioned title or slug, mentioned alias) run through one `applyIdentityBoosts` closure on the fused path and both keyword-only paths. Under unified multimodal routing the cosine rescore hydrates `embedding_multimodal` (the space the query was embedded in), and `cosineSimilarity` returns 0 for vectors of different lengths. Per-stage attribution powers `gbrain search --explain` — every boost surface carries its own field so `formatResultsExplain` reads them all without coupling to internal stage ordering. with `src/core/search/sql-ranking.ts` + `src/core/operations.ts` + `src/core/types.ts`: agent-warning channel. `SearchResult.content_flag?: {reason, detail}` (optional field in `types.ts`) is stamped post-fusion by `stampContentFlags` (the `stampEvidence` precedent) in `hybridSearch` AND in the keyword-only `search` MCP op so both retrieval paths surface the marker. `get_page` returns a top-level `content_flag` parallel field via `getContentFlag(page.frontmatter)`. `buildVisibilityClause` (sql-ranking.ts) ANDs in `QUARANTINE_FILTER_FRAGMENT` so quarantined pages are excluded from all six search call sites (alongside soft-delete + archived-source filters). Pinned by `test/sql-ranking.test.ts` + `test/e2e/quarantine-search-exclusion.test.ts`. Cross-modal routing at the embed step: `effectiveModality` resolves per-call `opts.crossModal` (literal `'auto'` → undefined) → `suggestions.suggestedModality` → `'text'`. Image route: `embedQueryMultimodal` + `searchVector({embeddingColumn: 'embedding_image'})`, skipping expansion + keyword. `'both'` route: parallel text + image vector searches merged via `rrfFusionWeighted` with `effectiveRrfK(baseRrfK, weight)` from the configured cross-modal weights. Unified routing fires when `search.unified_multimodal` is true — bypasses dual-column branching, runs `embedQueryMultimodal` + `searchVector({embeddingColumn: 'embedding_multimodal'})`, fail-open on zero rows (non-strict falls through to dual-column). LLM modality escalation fires only when no explicit per-call opt is set AND the regex returned `'text'` AND `search.cross_modal.llm_intent` is on AND `isAmbiguousModalityQuery` fires; fail-open on every error. `compiledTruthBoost(result, applyBoost)` is exported for direct predicate tests: a synthetic chunkless title row (`chunk_id === 0` AND blank `chunk_text`) never receives the 2x compiled-truth boost (`test/search/compiled-truth-boost.test.ts`). The reranker pass-through callback is typed with `RerankPassThroughReason` imported from `rerank.ts` — one union, not a re-declaration. RRF inputs are assembled by ONE `composeFusionLists` call (next entry) over role-tagged `vectorArms` built with `pushVectorList` at every assembly site (unified, image-only, text/both, and the `allSettled` salvage path — where the `original` role additionally requires the original's `searchVector` to have succeeded); after `expandFn`, `queries[0]` is re-enforced to be the caller's query and repeats are deduped, so a variant can never take the anchor role. `HybridSearchOpts.onRerankPool` (eval-only, best-effort) fires immediately before `applyAutocut` with the exact pre-autocut `returnPool` — post alias-hop / exact-lookup / adaptive-return, unscored injected rows included, even when autocut is off — plus the deduped pre-rerank order, so an offline autocut replay is byte-faithful. Immediately after `applyReranker` — only when it actually reordered (`reranked !== deduped`) and never for image modality — `pinRelationalRows` (`relational-rerank-pin.ts`) re-pins the relational arm's rows above the reranked text rows bounded by `resolvedMode.relational_rerank_pin`, stamps `relational_pinned`, and emits `HybridSearchMeta.relational_rerank_pin`; `ensureRelationalEvidenceSlot` still runs after autocut (usually a no-op on relational queries now — it remains the page-1 guarantee for pin 0, reranker fail-open, and arm rows dropped before the pin).`embedQueryBounded` preserves its own expired signal's timeout reason whenthe gateway wraps transport cancellation, keeping `embed_timeout` stable@@ -55,7 +56,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/search/projection-statistics.ts` — current-projection expression statistics, strict migration postconditions and owner-authorized batch refresh. Migration 160 verifies object identity and populated samples before advancing the ledger, distinguishing empty tables and row-security-hidden statistics. Import, sync, reindex and drained recovery refresh outside page locks; failures preserve completed writes and give a maintenance hint. Migration 161 adds the scoped pending-projection index.-- `src/core/search/query-cache.ts` — stored semantic-cache data and maintenance remain, but `semanticResultCacheAvailable()` is false. `hybridSearchCached` bypasses both result lookup and writes regardless of configuration or `useCache`; request-local query embeddings still work. Search metadata, cache_stats and the mode dashboard report effective caching as disabled. Historical hit counts and search_telemetry remain intact. Restoration requires complete response-dependency provenance.+- `src/core/search/query-cache.ts` — stored semantic-cache data and maintenance remain, but `semanticResultCacheAvailable()` is false. `hybridSearchCached` bypasses both result lookup and writes regardless of configuration or `useCache`, and skips the key/config setup (merged config, cache config, intent-pattern state) so the wrapper adds no engine round-trips; request-local query embeddings still work. Search metadata, cache_stats and the mode dashboard report effective caching as disabled. Historical hit counts and search_telemetry remain intact. Restoration requires complete response-dependency provenance.- `src/core/search/query-intent.ts` — Deterministic query classifiers (pure, no LLM): `classifyQuery`/`classifyQueryIntent` (entity/temporal/event/concept/general → auto-selects detail level, salience/recency/modality axes; `concept` fires on definitional-paraphrase OR landscape/quantifier cues with a proper-noun name-guard — capitalized names, quoted phrases, slugs, and sub-3-word queries never trigger — and ranks vector-lean via the RRF-k tilt in `intent-weights.ts`), `isAmbiguousModalityQuery` (LLM-escalation gate), and the concept-shape pair — `looksConceptShaped` (fuzzy-quantifier/landscape cues minus exact-identifier anti-signals, tuned to favor false-negatives; cues owned by other routers like "who are the"/find_experts and bare "anything"/salience are deliberately excluded) + `conceptNudge` (full one-line CLI hint string steering a concept-shaped `search` toward `query`; consumed by `maybePrintConceptNudge` in `src/cli.ts` on BOTH the local-engine and thin-client result paths, stderr-only, `--quiet`-gated). Pinned by `test/query-intent-concept.test.ts` + `test/cli-concept-nudge.test.ts`.@@ -65,6 +66,6 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/search/relational-rerank-pin.ts` — relational-arm rows bypass reranker DEMOTION (ranker wave, receipt R1 in `scripts/r1-namedthing-rerank-ab.ts`: on NamedThingBench's 39 graph-relationship questions the shipped `balanced` default lost hit@1 21/39 → 3/39 and hit@3 27/39 → 5/39 with the reranker on — 19 and 22 paired losses — because the cross-encoder scores chunk TEXT and an edge-derived answer's text need not mention the query's entity; with the pin at its default 3, measured with `--autocut on`, the shape that shipped before rule R2 turned autocut off, the same paired run shows 0 hit@1 / 0 hit@3 losses, 21/39 and 27/39, and the 11 non-relational core queries show 0 losses — one hard-negative gain, hit@1 10/11 → 11/11). `pinRelationalRows(reranked, relationalList, {max, fusedOrder?, onPin?})` is a pure PERMUTATION of the post-rerank pool: relational rows (page key `(source_id, slug)` in the arm's list; ONE row per page — its first, highest-ranked occurrence) claim `min(fused_rank, reranked_rank)` (fused rank = position among relational rows in `fusedOrder`, the pre-rerank `deduped` pool; arm order for rows absent from it), claims sort ascending with ties resolved to the FUSED order then the reranked position, the first `max` claimants form the top block in that order, every other row follows in reranked order (an unpinned row lands at its reranked position or up to `pinned.length` lower, never higher). Pinned rows are shallow copies stamped `relational_pinned: true`; no row is added or removed (re-injecting rows dropped upstream stays `ensureRelationalEvidenceSlot`'s job). Every no-op path (`max <= 0`, empty pool, empty arm, no relational page in the pool) returns the input array itself. `normalizeRelationalRerankPin` is the ONE range contract for the knob (non-negative integer `<= 10` or a string parsing to one → that integer; the literals `off` / `false` (any case) or boolean `false` → 0; anything else → `undefined` = fall through), shared by `mode.ts:loadOverridesFromConfig` and both per-call seams in `hybrid.ts`; `DEFAULT_RELATIONAL_RERANK_PIN` (3) and `RELATIONAL_RERANK_PIN_MAX` (10) are exported. `RelationalRerankPinDecision` (`{max, relational_in_pool, pinned:[{slug, source_id, from_rank, to_rank, fused_rank}], moved}`) is surfaced as `HybridSearchMeta.relational_rerank_pin` for `--explain`. Wired in `hybridSearch` immediately after `applyReranker` and before the alias hop, gated on the reranker having actually reordered (`reranked !== deduped` — `applyReranker` returns its input on every fail-open / skip / pass-through path, and the fused order already carries the arm) and on non-image modality; autocut's `scoreOf` ignores pinned rows and its preserve predicate keeps them, so text-row autocut is byte-identical to the pre-pin behavior. Known cost: a false-positive arm (relational shape parsed AND a real seed resolved, but wrong/stale edges) now puts up to `max` edge pages at ranks 1..max instead of one at `limit`; mitigations are the arm's `fallback_slugify` confidence gate, the tier-2 resolution-margin TODO, config `search.relational_rerank_pin off`, and per-call `SearchOpts.relationalRerankPin`. Pinned by `test/search/relational-rerank-pin.test.ts` (pure contract + tie policy) and `test/search/relational-rerank-pin-hybrid.serial.test.ts` (hermetic PGLite on the relational corpus through the REAL gateway rerank path behind `__setRerankTransportForTests` with an inverted-relevance stub: pin 0 reproduces the regression, pin 3 restores hit@1/hit@3 on all 8 who-invested questions, non-relational queries and reranker-off runs are byte-identical).-- `src/core/search/rerank.ts` — the call-site abstraction. `applyReranker(query, results, opts)` slots between `dedupResults()` and `enforceTokenBudget()` in `src/core/search/hybrid.ts`. Slices `opts.topNIn` (default 30) by current RRF order, caps each document via `capRerankDoc` (`RERANK_MAX_DOC_CHARS=6000` then a measured-ratio shrink to `RERANK_MAX_DOC_TOKENS=1400` — a 2048-ubatch llama-server minus query/template headroom minus a Qwen-tokenizer margin; every cut through `truncateUtf8` so no lone surrogate reaches the JSON body; docs under 1400 chars skip the tokenizer; applies to hosted providers too, so code/CJK chunks at the chunker ceiling lose part of their tail while prose is untouched), sends to `gateway.rerank()`, reorders by `relevanceScore` desc, appends the un-reranked tail unchanged (recall protection). Fail-open on every `RerankError.reason`: any error logs via `logRerankFailure` and returns the input array unchanged — except the SKIP class `no_key` (`RerankSkipReason`), which returns the input immediately WITHOUT a per-query audit row (the gateway already wrote the one per-process-per-model row) and fires `opts.onSkip(reason)`; every OTHER thrown failure (HTTP error, network, timeout, budget) is audited and fires `opts.onFailure(reason)` with `RerankFailedReason` `timeout | budget | provider_error`, which `hybrid.ts` stamps as `{stage: 'rerank_failed', reason}` (recall-affecting, like `rerank_passthrough`; the LongMemEval reranker gate and the R1 script count it as un-reranked); `hybrid.ts` passes an `onSkip` that stamps `{stage: 'reranker_skipped', reason}` into `HybridSearchMeta.degraded` (closed vocabulary in `types.ts`), which `--explain` renders as `degraded: reranker_skipped (no_key)` via `formatDegradedSummary` — the only place a silently skipped reranker is visible from the CLI. `types.ts` classifies the stage as ranking-only: `RANKING_ONLY_DEGRADED_STAGES` (= `{reranker_skipped}`) + `affectsRecall(entry)` — consumers that ask "was recall impaired?" filter through it (the CLI `No results.` line in `cli.ts:describeEmptyRetrieval` and the MCP empty-result block in `dispatch.ts:buildEmptyRetrievalBlock` keep saying "clean miss"; the degraded cache-TTL rule below uses the same predicate), while consumers that report what did not run (`--explain`, telemetry, eval rows) keep it; pinned by `test/degraded-stages-recall.test.ts`. `hybridSearchCached` excludes `reranker_skipped` from the short degraded-TTL rule (it is a config state, not a transient limp: a keyless balanced brain keeps the full `cache.ttl_seconds`, and the stored meta still carries the stamp). Stamps `rerank_score` onto reordered items so downstream telemetry sees the new ordering signal. `topNOut: null` is the explicit "don't truncate" signal — semantically distinct from `undefined` ("fall through to mode bundle"). Test seam: `opts.rerankerFn` stubs `gateway.rerank` without the network. Document cap pinned by `test/rerank-doc-cap.test.ts`.+- `src/core/search/rerank.ts` — the call-site abstraction. `applyReranker(query, results, opts)` slots between `dedupResults()` and `enforceTokenBudget()` in `src/core/search/hybrid.ts`. Slices `opts.topNIn` (default 30) by current RRF order, caps each document via `capRerankDoc` (`RERANK_MAX_DOC_CHARS=6000` then a measured-ratio shrink to `RERANK_MAX_DOC_TOKENS=1400` — a 2048-ubatch llama-server minus query/template headroom minus a Qwen-tokenizer margin; every cut through `truncateUtf8` so no lone surrogate reaches the JSON body; docs under 1400 chars skip the tokenizer; applies to hosted providers too, so code/CJK chunks at the chunker ceiling lose part of their tail while prose is untouched), sends to `gateway.rerank()`, reorders by `relevanceScore` desc (within a run of exactly equal finite scores the fused input order decides, so provider tie order never leaks; rows never cross a different score), appends the un-reranked tail unchanged (recall protection). Fail-open on every `RerankError.reason`: any error logs via `logRerankFailure` and returns the input array unchanged — except the SKIP class `no_key` (`RerankSkipReason`), which returns the input immediately WITHOUT a per-query audit row (the gateway already wrote the one per-process-per-model row) and fires `opts.onSkip(reason)`; every OTHER thrown failure (HTTP error, network, timeout, budget) is audited and fires `opts.onFailure(reason)` with `RerankFailedReason` `timeout | budget | provider_error`, which `hybrid.ts` stamps as `{stage: 'rerank_failed', reason}` (recall-affecting, like `rerank_passthrough`; the LongMemEval reranker gate and the R1 script count it as un-reranked); `hybrid.ts` passes an `onSkip` that stamps `{stage: 'reranker_skipped', reason}` into `HybridSearchMeta.degraded` (closed vocabulary in `types.ts`), which `--explain` renders as `degraded: reranker_skipped (no_key)` via `formatDegradedSummary` — the only place a silently skipped reranker is visible from the CLI. `types.ts` classifies the stage as ranking-only: `RANKING_ONLY_DEGRADED_STAGES` (= `{reranker_skipped}`) + `affectsRecall(entry)` — consumers that ask "was recall impaired?" filter through it (the CLI `No results.` line in `cli.ts:describeEmptyRetrieval` and the MCP empty-result block in `dispatch.ts:buildEmptyRetrievalBlock` keep saying "clean miss"; the degraded cache-TTL rule below uses the same predicate), while consumers that report what did not run (`--explain`, telemetry, eval rows) keep it; pinned by `test/degraded-stages-recall.test.ts`. `hybridSearchCached` excludes `reranker_skipped` from the short degraded-TTL rule (it is a config state, not a transient limp: a keyless balanced brain keeps the full `cache.ttl_seconds`, and the stored meta still carries the stamp). Stamps `rerank_score` onto reordered items so downstream telemetry sees the new ordering signal. `topNOut: null` is the explicit "don't truncate" signal — semantically distinct from `undefined` ("fall through to mode bundle"). Test seam: `opts.rerankerFn` stubs `gateway.rerank` without the network. Document cap pinned by `test/rerank-doc-cap.test.ts`.- `src/core/search/rrf-page-fusion.ts` — `accumulateRrf(lists)`, the one accumulation step behind `rrfFusion` / `rrfFusionWeighted` in `hybrid.ts`. Votes are keyed on the PAGE `(source_id, slug)`: each list adds `weight / (k + rank)` to a page once, at its best rank, chunks stay distinct rows keyed `(source_id, slug, chunk_id)` with their own vote (`own`) and an OR-propagated `keyword_hit`, and each page's lead chunk (largest `own`, first-seen on ties — a vector arm in `composeFusionLists` order) scores the page's summed vote while its other chunks score their own vote. Pure. Pinned by `test/search/rrf-page-grain.test.ts`.diff --git a/docs/architecture/key-files/core-search-2.md b/docs/architecture/key-files/core-search-2.mdindex 2dad45da35..ae7526a9ef 100644--- a/docs/architecture/key-files/core-search-2.md+++ b/docs/architecture/key-files/core-search-2.md@@ -9,7 +9,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/search/safe-chunks.ts` — shared current-revision and remote safe-chunk predicates. `currentTextProjectionFilter` emits `(text_projection_revision = knowledge_revision) IS TRUE`, preserving NULL exclusion while allowing expression statistics to guide the planner. Visibility and revision predicates stay inside candidate selection. Body/chunk changes invalidate the safe index until a guarded rebuild. `belowSafeChunkFence` is the page-level predicate shared by the importers' unchanged-content re-seal and the drain.-- `src/core/search/source-boost.ts` — Source-type boost map keyed by slug prefix. `DEFAULT_SOURCE_BOOSTS` (originals/ 1.5, concepts/ 1.3, writing/ 1.4, people/companies/deals/ 1.2, daily/ 0.8, media/x/ 0.7, <fork>/chat/ 0.5, archive/ 0.5, extracts/ 0.3) and `DEFAULT_HARD_EXCLUDES` (test/, attachments/, .raw/). `archive/` is DEMOTED (findable, ranked below curated), not hard-excluded — archive holds high-signal history users expect to retrieve; the demote is a prior at the SQL/fusion layer and the cross-encoder reranker can still promote a strongly-matching archive page. `parseSourceBoostEnv`/`parseHardExcludesEnv` parse comma-separated `prefix:factor` pairs from `GBRAIN_SOURCE_BOOST`/`GBRAIN_SEARCH_EXCLUDE`. `resolveBoostMap` and `resolveHardExcludes` merge defaults + env + caller `SearchOpts.exclude_slug_prefixes`/`include_slug_prefixes`. The surviving exclude policy is auditable via the `hidden_by_search_policy` doctor check (`src/commands/doctor.ts`, local + remote paths) which counts chunked pages withheld per active exclude prefix, reusing `resolveHardExcludes` + `buildVisibilityClause` + the exported `escapeLikePattern`.+- `src/core/search/source-boost.ts` — Source-type boost map keyed by slug prefix. `DEFAULT_SOURCE_BOOSTS` (originals/ 1.5, concepts/ 1.3, writing/ 1.4, people/companies/deals/ 1.2, daily/ 0.8, media/x/ 0.7, <fork>/chat/ 0.5, archive/ 0.5, extracts/ 0.3) and `DEFAULT_HARD_EXCLUDES` (test/, attachments/, .raw/). `archive/` is DEMOTED (findable, ranked below curated), not hard-excluded — archive holds high-signal history users expect to retrieve; the demote is a prior at the SQL/fusion layer and the cross-encoder reranker can still promote a strongly-matching archive page. `parseSourceBoostEnv`/`parseHardExcludesEnv` parse comma-separated `prefix:factor` pairs from `GBRAIN_SOURCE_BOOST`/`GBRAIN_SEARCH_EXCLUDE`. `resolveBoostMap(env, config)` layers defaults (dropped by a `none` entry), the brain's `search.source_boosts` config and the env override; hybridSearch resolves it once from the mode config snapshot and passes it to the engines as `SearchOpts.source_boosts` (engines fall back to defaults + env when absent; the keyword-only `search` op branch reads the key itself). `resolveHardExcludes` merges defaults + env + caller `SearchOpts.exclude_slug_prefixes`/`include_slug_prefixes`. The surviving exclude policy is auditable via the `hidden_by_search_policy` doctor check (`src/commands/doctor.ts`, local + remote paths) which counts chunked pages withheld per active exclude prefix, reusing `resolveHardExcludes` + `buildVisibilityClause` + the exported `escapeLikePattern`.- `src/core/search/sql-ranking.ts` — Pure SQL string builders. `buildSourceFactorCase(slugColumn, boostMap, detail)` emits a CASE with longest-prefix-match wins (returns literal `'1.0'` when `detail === 'high'` for temporal-bypass parity with COMPILED_TRUTH_BOOST). `buildHardExcludeClause(slugColumn, prefixes)` emits `NOT (col LIKE 'p1%' OR col LIKE 'p2%')` — OR-chain wrapped in NOT, NOT `NOT LIKE ALL/ANY` (those quantifiers don't express set-exclusion). LIKE meta-character escape covers all three of `%`, `_`, AND `\` (backslash is Postgres LIKE's default escape char). Single-quote doubling on SQL string literals so injection-style inputs are inert text. `buildBestPerPagePoolCte(...)` is the shared per-page max-pool CTE both engines' `searchVector` inject — instead of returning the single best chunk per page from an inner `ORDER BY embedding <=> vec LIMIT N` (which lets a page lose to a neighbor on ONE weak chunk while its strong chunk sits just below the inner cut), the CTE pools the BEST chunk score per `(source_id, slug)` composite key so a page surfaces on its strongest evidence; composite key (not bare slug) keeps multi-source brains correct; single source of truth so the two engines can't drift.diff --git a/docs/architecture/key-files/core-services-1.md b/docs/architecture/key-files/core-services-1.mdindex 8311138596..c308c9f22e 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 **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/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, Claude's `chat_conversations` paged with `limit`/`offset` across every chat-capable org (conversations fetched from the org that listed them; timestamps normalized with ChatGPT's `toIso`), a ChatGPT walk that steps back when `total` shrinks mid-walk (a removal shifts later items to lower offsets) and yields each id once across both passes, 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 OR ingest failures at one `updatedAt`; ingest outcomes are attributed per conversation by session id, a spool-file-level failure fails the batch; an edit or `--full` retries) BEFORE the `--limit` cap, so capped runs progress → fetch → spool → `runTranscriptsIngest` → record each successfully ingested conversation as synced → 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 7ac569d09c..5f3214b2a6 100644--- a/docs/architecture/key-files/core-services-2.md+++ b/docs/architecture/key-files/core-services-2.md@@ -3,11 +3,11 @@[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.-- `src/core/conversation-parser/` — 19-pattern built-in chat-format registry + opt-in LLM fallback. Modules: `types.ts` (PatternEntry + ParseResult + DateContext + CaptureMap + TimezonePolicy), `builtins.ts` (19 hand-vetted patterns sourced from public format docs — iMessage/Slack, Telegram bracket + text-export, bold-paren-time, bold-time-dash, bold-name-no-time, chatgpt-export-you-chatgpt, Discord classic + export, WhatsApp ISO + US, Signal, Matrix/Element, IRC classic + weechat, Teams export, markdown-heading-turn; module-load validation runs every `test_positive[]` + `test_negative[]` sample at startup so a typo in any built-in regex makes gbrain refuse to start; `DEFAULT_SPEAKER_CLEAN` exported as a module-level default), `parse.ts` (orchestrator with pattern-priority scoring across the first 10 lines + date derivation chain `explicit > frontmatter.date > effective_date > '1970-01-01'` + multi-line continuation + timezone warning; also populates `ParseResult.unrecognized_headings` — when the WINNING pattern is heading-anchored, heading-shaped lines whose label is outside the pattern's speaker set FOLD into the previous turn's body (or drop before the first anchor) while the parse still returns `regex_match`, silently crediting one speaker with another's words; detection is diagnostic-only and unconditional (not behind `opts.diagnostic` — the extractor's decline gate depends on it), fence-aware (a fence closes only on ITS OWN marker; an unclosed fence suppresses detection below it), labels deduped/capped at 10 entries ≤48 chars, undefined when empty so healthy-page JSON stays byte-identical; `gbrain conversation-parser scan` surfaces the field in both human and JSON output; `applyPattern` never DROPS a matched anchor whose date it cannot reconstruct (a localized month name, malformed digits) — dropping it would fold that speaker's body into the previous turn on a multi_line pattern, so the message opens anyway, inheriting the previous anchor's timestamp (page fallback date at midnight for the first), and the count surfaces as `ParseResult.date_fallback_count`, undefined when zero), `llm-base.ts` (shared `runLlmCall<T>` with content-hash cache in-process + DB-persistent via migration v97 + 4-strategy JSON repair + Anthropic-key probe; fallback is a thin wrapper), `llm-fallback.ts` (opt-IN; NO regex inference + NO persistence), `eval.ts` (`scoreFixture` + `aggregateScores` + `parseFixtureJsonl` for the fixture-corpus CI gate), `nightly-probe.ts` (DI-stubbed; mode-gated default tokenmax=ON, conservative/balanced opt-in; adversarial false-positive detection). Pattern `bold-name-no-time` (regex `/^\*\*(?!\[)(.+?):\*\*\s*(.*)$/`, ordered after the time-bearing bold patterns) parses `**Speaker:** text` with NO per-line timestamp (Circleback/Granola/Zoom), anchoring every message at `T00:00:00Z` of the frontmatter date (line order preserves sequence, same no-time convention as `irc-classic`); the `(?!\[)` lookahead rejects telegram-bracket `**[18:37] Name:**`; non-shadow is the colon-INSIDE-bold regex (NOT declaration order — `parse.ts` scores every candidate independently, order is only the tie-break). Because `**Label:** text` is a common prose idiom, the pattern sets optional `PatternEntry.score_full_body: true` so `parse.ts` recomputes the winner's acceptance score over the FULL body before the `SCORING_MIN_ACCEPTANCE` floor, keeping a bold-label notes page at `no_match`. Pattern `chatgpt-export-you-chatgpt` (regex `/^\*\*(You|ChatGPT):\*\*\s*(.*)$/`, declared just before `bold-name-no-time` so it wins the score tie on the two literal ChatGPT-export labels) parses ChatGPT's web-export → Markdown shape, where each turn's `**You:**` / `**ChatGPT:**` anchor is followed by a blank line and a multi-paragraph reply; `bold-name-no-time` alone cannot absorb that shape (`multi_line: false` scores a long reply's density near zero and falls below `SCORING_MIN_ACCEPTANCE`), so this pattern sets `multi_line: true` + `score_continuations_as_body: true` (excludes non-`**`-prefixed reply lines from the density denominator) + `score_full_body: true` (belt-and-suspenders full-body recompute of the winner). The speaker capture is a closed two-value enumeration (`You` or `ChatGPT` exactly, never an arbitrary `(.+?)` label), so it cannot reopen `bold-name-no-time`'s BROAD-REGEX GUARD against notes pages. Because a bare `**You:**`/`**ChatGPT:**` heading (unlike `bold-time-dash`'s bold-name+time+dash anchor) is a plausible label in ordinary prose ABOUT ChatGPT, the pattern also sets the optional `PatternEntry.score_continuations_min_distinct_speakers: 2`: `scoreFromLines` only grants the continuation-density-exclusion score when the anchor lines that fully match `regex` collectively capture at least that many DISTINCT `speaker_group` values, so a page with only a solitary `**You:**` heading (or several repeats of the SAME role) falls back to the ordinary flat-density score instead of getting the same acceptance immunity a genuine two-party exchange gets. It ALSO sets `PatternEntry.score_continuations_max_preamble_lines: 5`, because distinct-speaker count alone still lets ONE genuine `**You:**`/`**ChatGPT:**` pair embedded anywhere inside an otherwise unrelated long document (both roles present) through: `scoreFromLines` tracks the index of the FIRST fully-matching anchor line and only grants the immunity when that index is at or before the bound (tolerating a short title/heading preamble, not an arbitrary amount of unrelated prose before the transcript). Pattern `bold-paren-time` parses `**Speaker** (HH:MM): text` and `(HH:MM:SS)` (date_source: frontmatter). Fallback gates: `SCORING_HEAD_TRIGGER_THRESHOLD = 0.3` triggers a full-body re-score when the head pass scores below that; `SCORING_MIN_ACCEPTANCE = 0.05` blocks essay false-positives. Exported `scorePatternFull(body, entry)`; private `getNonBlankLines(body, headCap?)` + `scoreFromLines(lines, entry)` DRY the quick_reject+regex loop. CLI surfaces at `src/commands/eval-conversation-parser.ts` (`gbrain eval conversation-parser <fixture.jsonl>` exit 0/1/2, wired into `bun run verify` via `check:conversation-parser`) and `src/commands/conversation-parser.ts` (`scan <slug>` debug, `list-builtins`, `validate <file>`). Doctor checks: `conversation_format_coverage`, `progressive_batch_audit_health`, `conversation_parser_probe_health`. Pinned by `test/conversation-parser/{parse,llm-base,llm-fallback,nightly-probe}.test.ts` + the 27-case baseline at `test/extract-conversation-facts.test.ts` (back-compat invariant). Migration v97 (`conversation_parser_llm_cache_table`). Fixtures at `test/fixtures/conversation-formats/{imessage,imessage-time-only-12h,telegram-bracket,whatsapp-iso,whatsapp-us,signal-export,irc-classic,irc-weechat,matrix-element,teams-export,all,adversarial,bold-name-no-time,bold-time-dash,chatgpt-export-you-chatgpt}.jsonl` with `scripts/check-fixture-privacy.sh` banning real-name leaks. Maintainer guidance: [conversation parser patterns](../conversation-parser-patterns.md).+- `src/core/conversation-parser/` — 19-pattern built-in chat-format registry + opt-in LLM fallback. Modules: `types.ts` (PatternEntry + ParseResult + DateContext + CaptureMap + TimezonePolicy), `builtins.ts` (19 hand-vetted patterns sourced from public format docs — iMessage/Slack, Telegram bracket + text-export, bold-paren-time, bold-time-dash, bold-name-no-time, chatgpt-export-you-chatgpt, Discord classic + export, WhatsApp ISO + US, Signal, Matrix/Element, IRC classic + weechat, Teams export, markdown-heading-turn; module-load validation runs every `test_positive[]` + `test_negative[]` sample at startup so a typo in any built-in regex makes gbrain refuse to start; `DEFAULT_SPEAKER_CLEAN` exported as a module-level default), `parse.ts` (orchestrator with pattern-priority scoring across the first 10 lines + date derivation chain `explicit > frontmatter.date > effective_date > '1970-01-01'` + multi-line continuation + timezone warning; also populates `ParseResult.unrecognized_headings` — when the WINNING pattern is heading-anchored, heading-shaped lines whose label is outside the pattern's speaker set FOLD into the previous turn's body (or drop before the first anchor) while the parse still returns `regex_match`, silently crediting one speaker with another's words; detection is diagnostic-only and unconditional (not behind `opts.diagnostic` — the extractor's decline gate depends on it), fence-aware (a fence closes only on ITS OWN marker; an unclosed fence suppresses detection below it), labels deduped/capped at 10 entries ≤48 chars, undefined when empty so healthy-page JSON stays byte-identical; `gbrain conversation-parser scan` surfaces the field in both human and JSON output; `applyPattern` never DROPS a matched anchor whose date it cannot reconstruct (a localized month name, malformed digits) — dropping it would fold that speaker's body into the previous turn on a multi_line pattern, so the message opens anyway, inheriting the previous anchor's timestamp (page fallback date at midnight for the first), and the count surfaces as `ParseResult.date_fallback_count`, undefined when zero), `llm-base.ts` (shared `runLlmCall<T>` with content-hash cache in-process + DB-persistent via migration v97 + 4-strategy JSON repair + Anthropic-key probe; fallback is a thin wrapper), `llm-fallback.ts` (opt-IN; NO regex inference + NO persistence), `eval.ts` (`scoreFixture` + `aggregateScores` + `parseFixtureJsonl` for the fixture-corpus CI gate), `nightly-probe.ts` (DI-stubbed; mode-gated default tokenmax=ON, conservative/balanced opt-in; adversarial false-positive detection). Pattern `bold-name-no-time` (regex `/^\*\*(?!\[)(.+?):\*\*\s*(.*)$/`, ordered after the time-bearing bold patterns) parses `**Speaker:** text` with NO per-line timestamp (Circleback/Granola/Zoom), anchoring every message at `T00:00:00Z` of the frontmatter date (line order preserves sequence, same no-time convention as `irc-classic`); the `(?!\[)` lookahead rejects telegram-bracket `**[18:37] Name:**`; non-shadow is the colon-INSIDE-bold regex (NOT declaration order — `parse.ts` scores every candidate independently, order is only the tie-break). Because `**Label:** text` is a common prose idiom, the pattern sets optional `PatternEntry.score_full_body: true` so `parse.ts` recomputes the winner's acceptance score over the FULL body before the `SCORING_MIN_ACCEPTANCE` floor, keeping a bold-label notes page at `no_match`. Pattern `chatgpt-export-you-chatgpt` (regex `/^\*\*(You|ChatGPT):\*\*\s*(.*)$/`, declared just before `bold-name-no-time` so it wins the score tie on the two literal ChatGPT-export labels) parses ChatGPT's web-export → Markdown shape, where each turn's `**You:**` / `**ChatGPT:**` anchor is followed by a blank line and a multi-paragraph reply; `bold-name-no-time` alone cannot absorb that shape (`multi_line: false` scores a long reply's density near zero and falls below `SCORING_MIN_ACCEPTANCE`), so this pattern sets `multi_line: true` + `score_continuations_as_body: true` (excludes non-`**`-prefixed reply lines from the density denominator) + `score_full_body: true`. The speaker capture is a closed two-value enumeration (`You` or `ChatGPT` exactly, never an arbitrary `(.+?)` label), so it cannot reopen `bold-name-no-time`'s BROAD-REGEX GUARD against notes pages. Because a bare `**You:**`/`**ChatGPT:**` heading is plausible in prose ABOUT ChatGPT, the pattern also sets the optional `PatternEntry.score_continuations_min_distinct_speakers: 2`: `scoreFromLines` only grants the continuation-density-exclusion score when the anchor lines that fully match `regex` collectively capture at least that many DISTINCT `speaker_group` values, so a page with only one role falls back to the ordinary flat-density score. It ALSO sets `PatternEntry.score_continuations_max_preamble_lines: 5`, because one genuine pair embedded deep in an unrelated long document would otherwise pass: `scoreFromLines` tracks the index of the FIRST fully-matching anchor line and only grants the immunity when that index is at or before the bound (a short title preamble is tolerated). Pattern `bold-paren-time` parses `**Speaker** (HH:MM): text` and `(HH:MM:SS)` (date_source: frontmatter). Fallback gates: `SCORING_HEAD_TRIGGER_THRESHOLD = 0.3` triggers a full-body re-score when the head pass scores below that; `SCORING_MIN_ACCEPTANCE = 0.05` blocks essay false-positives. Exported `scorePatternFull(body, entry)`; private `getNonBlankLines(body, headCap?)` + `scoreFromLines(lines, entry)` DRY the quick_reject+regex loop. CLI surfaces at `src/commands/eval-conversation-parser.ts` (`gbrain eval conversation-parser <fixture.jsonl>` exit 0/1/2, wired into `bun run verify` via `check:conversation-parser`) and `src/commands/conversation-parser.ts` (`scan <slug>` debug, `list-builtins`, `validate <file>`). Doctor checks: `conversation_format_coverage`, `progressive_batch_audit_health`, `conversation_parser_probe_health`. Pinned by `test/conversation-parser/{parse,llm-base,llm-fallback,nightly-probe}.test.ts` + the 27-case baseline at `test/extract-conversation-facts.test.ts` (back-compat invariant). Migration v97 (`conversation_parser_llm_cache_table`). Fixtures at `test/fixtures/conversation-formats/{imessage,imessage-time-only-12h,telegram-bracket,whatsapp-iso,whatsapp-us,signal-export,irc-classic,irc-weechat,matrix-element,teams-export,all,adversarial,bold-name-no-time,bold-time-dash,chatgpt-export-you-chatgpt}.jsonl` with `scripts/check-fixture-privacy.sh` banning real-name leaks. Maintainer guidance: [conversation parser patterns](../conversation-parser-patterns.md).- `src/core/facts/conversation-types.ts` — single-source conversation-type allowlist (`ALLOWED_TYPES`: conversation, meeting, slack, email, imessage, imessage-daily + `AllowedType`). Every consumer derives from this frozen leaf module — `extract-conversation-facts.ts` (which re-exports both names verbatim for its existing importers), the cycle backfill phase, `doctor.ts` + `doctor/checks/search-eval.ts`, `sources.ts`, `jobs.ts` — so no hand-copied list can drift. It lives under `src/core/facts/` (not `src/commands/`) because `scripts/generate-flag-registry.ts` scans option-shaped literals one relative-import level deep — importing the constant straight from `extract-conversation-facts.ts` would transitively attribute that command's whole option surface to doctor/jobs/sources in the generated CLI_ONLY registry. Drift-guarded by `test/conversation-facts-type-allowlist-drift.test.ts`.-- `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/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 a genuine commitment); 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 can mint `entity_slug='null'` through the resolver's fallback slugify. 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) and `facts.extraction_junk_filter` (`false` disables the deterministic junk gate; default on), plus the opt-in `facts.extraction_missing_confidence` (stored when confidence is missing, null or non-numeric; unset keeps 1.0). A numeric-string confidence (`"0.3"`) is read as the stated value; unknown kinds are still stored as `fact` but counted in a stderr warning. 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?, 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`.@@ -15,7 +15,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `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, 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/withdrawal.ts` + `withdrawal-schema.ts` + `withdrawal-discovery.ts` — durable withdrawal key is `(source_id, visibility, subject, SHA256(normalized claim))`. `subject` is the forgotten row's `entity_slug`; '*' (all subjects) covers subjectless facts and rows recorded before v169. A withdrawal matches when `subject = '*' OR subject = entity_slug`, so forgetting one entity's claim never touches the same claim about another entity. Fence rows belong to their page's entity: the import overlay, prepared-import check (`preserveWithdrawnFenceRows` / `assertPreparedFactWithdrawals`), snapshot overlay and Markdown export match on the page slug. `updateSlug` (both engines, via `moveSlugBindings`) and the phantom-redirect merge move subjects to the new slug (`MOVE_WITHDRAWAL_SUBJECT_SQL`), so rename and index recreation do not restore a claim. Normalization (`gbrain_fact_normalize`, mirrored in JS by `normalizeLoweredClaim`) folds case, whitespace and an explicit punctuation set, not meaning (migration v174); `+`, `#` and in-word dots are kept ("C++" ≠ "C"); pre-v174 ledger rows keep their exact `gbrain_fact_fingerprint_v1` hash and every ledger match checks both. v174 adds a folded row wherever a fact row still holds the claim text, expires facts that became matching, and builds `idx_facts_withdrawal_fingerprint` (the fingerprint inlines normalization: index builds use a restricted search_path). Discovery (`withdrawal-discovery.ts`) is keyed on claim, subject and fingerprint: SQL shortlists pages and chunks whose lowercased text contains every normalized token of the claim (necessary for any match; nothing is normalized in SQL), streams them by keyset, then verifies exactly; a subject-scoped claim reads only its entity's page plus provenance of that entity's facts. There is no source-inventory limit (#5674): refusals come from the matched set (>256 pages, reported with the count and sample slugs), the 10s scan budget, per-batch input limits or matching malformed evidence. Only an existing withdrawal covering the same subject skips discovery. Only affected page revisions/chunks are invalidated. The source row lock serializes withdrawal with the facts trigger; the trigger prevents insert/update from reactivating a matching claim. Import and snapshot overlays cover every complete legacy fence, including inactive rows; withdrawal markers precede preserved context and retain earlier expiry dates before hashing/chunking; malformed fences retain their existing diagnostics and the DB trigger still protects derived facts. `writeSingleFact` refuses an identical withdrawn claim for the resolved entity before embedding, using the protocol error envelope. `writeFactsToFence` rechecks each input under the page lock and drops claims withdrawn for the page's entity (reporting `withdrawnSkipped`), and the backstop skips them in phase 1, so a withdrawn claim is never appended to Markdown as an active row (audit B-10). TTL/supersession expiry creates no withdrawal; backfill trusts only explicit `forgotten:` markers; Markdown-only copies do not preserve DB-only withdrawals. Pinned by `test/facts-withdrawal-subject.test.ts`, `test/fact-withdrawal-normalized.test.ts`, `test/withdrawal-bounded-safety.test.ts` (both engines) and the Postgres scale gate `test/e2e/fact-withdrawal-scope-postgres.test.ts`.- `src/core/facts/write-single.ts` — `writeSingleFact(fact, ctx)`: the zero-LLM single-fact seam behind `remember`. `runFactsPipeline` is extraction-first (LLM-gated) and cannot back a pre-formed fact; this reuses the pipeline's post-extraction stages directly: resolve → embedding-cosine dedup (same 0.95 threshold) → fence-first write with the same legacy DB-only fallbacks (thin-client, unparented, stub-guard). Supersession: deterministic rule — same entity_slug + same kind + similarity ≥ threshold + DIFFERENT text ⇒ the new fact supersedes (fence path: append new + `forgetFactInFence(old, { supersededBy })`, which strikes the old row with a page-local `#N` supersession reference and records no withdrawal, + superseded_by link; DB path: engine insertFact supersedeId). Pinned by `test/facts-supersede-not-withdrawal.test.ts`. Provenance lands on NewFact.source verbatim (no FactsBackstopCtx). No embedding provider ⇒ `degraded_dedup: true` (near-duplicates may insert — documented). `isNullLikeEntity(entity)` (exported) normalizes null-like entity tokens (`"null"`, `"undefined"`, `"none"`, `"n/a"`, `"nil"`, `"-"`, empty/whitespace) to ABSENT before resolution — applied here rather than only at the verb boundary so EVERY writeSingleFact caller gets the guard and the `resolved?.slug ?? entityRef` fallback can never adopt `"null"` as a slug.@@ -39,7 +39,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/ops/sources.ts` — `sources_remove` is confined to the caller's WRITE authority via `assertSourceInCallerWriteScope(ctx, id)` (context.ts): an untrusted caller may hard-remove only its own write source; a federated read grant naming a source does not make it removable; any other id answers `OperationError('not_found', 'Unknown source: <id>')`, byte-identical to a nonexistent source so the error is not an existence oracle. `sources_status` keeps the read-scope helper (`assertSourceInCallerScope`), so a federated grant can still diagnose a source it cannot remove. Trusted local CLI keeps the full operator view. Over HTTP every client carries a write source (registration default `default`) and its own `oauth_clients.source_id` row FK-RESTRICTs removing that source, so hard removal is effectively an operator action (`gbrain sources remove`); a source a remote `sources_admin` caller just created via `sources_add` stays outside its authority until the operator rescopes the client. There is no `sources_archive` op — archive lives in the CLI (`gbrain sources archive`). Pinned by `test/sources-mcp.test.ts` (federated-read-only id → not_found while status still answers; write-source id → removed; unbound → any; local → any; `remote: undefined` fail-closed) and `test/e2e/sources-remote-mcp.test.ts` (real server: not_found before AND after a read-grant widen; operator CLI completes; rescoping `--source` moves the authority).-- `src/core/page-state/` — Canonical page concurrency foundation shared by both engines. `schema.ts` (migration 150) adds source incarnation UUIDs, logical page revisions, text-projection revisions, and persistent guards for absent pages. `guards.ts` locks sorted sources then page identities in an existing transaction; callers lock sources before authority/request/fact rows. `snapshot.ts` reads page/tags/withdrawals in one MVCC statement and applies withdrawals using database-normalized text. `transactions.ts` makes helper transaction APIs compose through savepoints. `versions.ts` records the complete canonical snapshot; `rename-alias.ts` records `slug_aliases(old -> new)` inside both engines' `updateSlug` transaction, repoints aliases that named the old slug and drops one spelled like the new slug (`test/rename-slug-alias.test.ts`); `materialize.ts` persists only verified canonical overlay bytes without another logical revision. `types.ts` defines revision preconditions: missing revision is create-only, explicit force overwrites. Plain legacy `putPage` calls keep compatibility until their owning operation adopts the managed write protocol. `projection-schema.ts` (migration 153) invalidates unverified prior projections once and queues durable work; `projections.ts` rebuilds Markdown without a worktree/provider and installs only matching canonical revisions. Embedding installs also compare exact chunk identities/text. Source importers seal code/image projections; all read arms hide unsealed projections.+- `src/core/page-state/` — Canonical page concurrency foundation shared by both engines. `schema.ts` (migration 150) adds source incarnation UUIDs, logical page revisions, text-projection revisions, and persistent guards for absent pages. `guards.ts` locks sorted sources then page identities in an existing transaction; callers lock sources before authority/request/fact rows. `snapshot.ts` reads page/tags/withdrawals in one MVCC statement and applies withdrawals using database-normalized text. `transactions.ts` makes helper transaction APIs compose through savepoints. `versions.ts` records the complete canonical snapshot; `rename-alias.ts` records `slug_aliases(old -> new)` inside both engines' `updateSlug` transaction, repoints aliases that named the old slug and drops one spelled like the new slug; `moveSlugBindings` moves the page's facts (`entity_slug`, `source_markdown_slug`) and `page_aliases` in the same transaction, letting a purged page's leftovers at the new slug yield (`test/rename-slug-alias.test.ts`); `materialize.ts` persists only verified canonical overlay bytes without another logical revision. `types.ts` defines revision preconditions: missing revision is create-only, explicit force overwrites. Plain legacy `putPage` calls keep compatibility until their owning operation adopts the managed write protocol. `projection-schema.ts` (migration 153) invalidates unverified prior projections once and queues durable work; `projections.ts` rebuilds Markdown without a worktree/provider and installs only matching canonical revisions. Embedding installs also compare exact chunk identities/text. Source importers seal code/image projections; all read arms hide unsealed projections.- `src/core/page-state/projections.ts` — captures canonical revision, source incarnation, page identity, the complete raw chunk inventory and resolved indexing inputs before preparing derived work. Embedding reads require a current text seal; healing/rebuild capture can explicitly include unsealed pages. Projection installation compares its originating seal, chunk identities/text/source/completion state, chunker version and indexing context (including stored corpus generation) under the page guard before replacing any row. A same-revision re-chunk may replace the snapshot it actually captured; a delayed older installation cannot discard newer chunks or vectors. Rebuild also rechecks its queued job before capture so a completed job from an old listing stays completed. Chunkless healing sanitizes complete body/timeline fences before splitting, preserving withdrawn history in direct page reads while excluding it from retrieval. Tests: `page-projection-origin.test.ts`, `page-projection-vector-preservation.test.ts` (PGLite and isolated Postgres), `embed-stale-chunkless-pages.serial.test.ts` (public healing entry). Shared `markdown-chunks.ts` and `code-chunks.ts` preserve fenced code and source-language metadata. A preserving rebuild keeps a vector only when its `content_chunks.embedding_input_hash` (`src/core/embedding-input-hash.ts`) equals one recomputed from the current page, or, with no recorded hash, when the page is non-contextual and the legacy model/text-hash checks pass; a contextual chunk without provenance is nulled once. `installPageEmbeddings` records the hash in the vector's UPDATE (the plain re-embed tier by default, or the caller's `built` tier and corpus generation), and `stampEmbeddingInputs` does the same for full imports. `resealSafeChunks` re-seals a page below the safe-chunk fence from its unchanged body with no canonical write; `projectionBelowSafeFence` is its predicate. Tests add `projection-embedding-input-hash.test.ts` and `safe-chunk-reseal.test.ts`. It replaces outgoing code edges without deleting incoming edges to retained chunks and clears backfill watermarks. Failed jobs rotate with a retained diagnostic; successful drain refreshes planner statistics.diff --git a/docs/architecture/key-files/engines-1.md b/docs/architecture/key-files/engines-1.mdindex ea7fbe6f06..191aff39e4 100644--- a/docs/architecture/key-files/engines-1.md+++ b/docs/architecture/key-files/engines-1.md@@ -21,7 +21,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/embedding-migration.ts` — provider-agnostic embedding migration core; owns the schema-transition + env-gate primitives. `runSchemaTransition(engine, targetDim)`: ONE transaction rebuilds all three dim-pinned text-embedding-space columns (`content_chunks.embedding`, `query_cache.embedding`, `facts.embedding`) preserving each column's `vector`/`halfvec` type, HNSW gated on `hnswIndexExpected` (dims > 2000 skip the index; exact scans stay correct — 2048d targets work); image/multimodal columns deliberately untouched; AFTER commit it clears `embedded_at` in yielding 50k batches (belt-and-braces hygiene — read surfaces key on the vector itself). `planEmbeddingMigration`: workload via widened stale predicates (absent-column fallback counts every chunk), cost, `signature_census` (top-5 page signatures — DB-reality corroboration of From), `synopsis_tier_pages` (context-tier downgrade consent), bundle-aware `reranker_warning`, `dim_change` via the shared `schemaRebuildNeeded` (null ⇒ rebuild, same computation apply uses). `applyEmbeddingMigration`: env≠target refusal (`detectEnvOverride`; `detectEnvPresence` drives the ==target notice) → marker v2 write (same-target re-apply preserves `started_at`; retarget records `superseded` history) → full rebuild when the chunks column is off-width, else INDEPENDENT repair of stale dim-pinned columns (`readDimPinnedWidths`) → false-target-stamp clearing (chunk-model truth) + guarded NULL-signature-inclusive invalidation (embed_skip pages' retained vectors preserved; both via `embedding-invalidation.ts`) BEFORE config writes (same-dim-swap crash safety) → DB plane → file-plane callback → cache purge. `verifyMigrationComplete`: the ONLY basis for "nothing to migrate" — column + pinned widths, wide stale census, false-stamp census blocker (embedded chunks whose `model` contradicts a page already stamped with the target signature), `missing_embeddings` residue, chunkless-pages census, embed_skip-NULL visibility (report-only detail, never a blocker), marker state, un-merged file plane (or env-canonical), env-contradiction blocker; never trusts `from_model`. `completeEmbeddingMigration`: marker delete + completion stamp in ONE transaction (no lost-receipt crash window); accepts content-free `extra` (smoke-check outcome). `readMigrationState` (corrupt-safe), `readMigrationStatus` (read-only, spend-free, everything-degrades-to-null), `verifySearchRoundTrip` (completion smoke check: query-side `embedQuery` + `searchVector`, hit identity by page_id, NEVER throws, warn-don't-block, content-free samples), `resolveRerankerExposure`/`resolveRerankerPlan`/`applyRerankerAction` (D8 companion switch: bundle-resolved exposure; auto→target-provider default reranker, never a silent third provider; config write + cache purge in one tx), `reconcilePageSignatures` (batch-boundary stamp repair). Engine-pure; every step idempotent under crash + re-run — the NULL-embedding column is the checkpoint. Pinned by `test/embedding-migration.test.ts`, `test/migrate-embeddings-hardening.serial.test.ts`, `test/e2e/migrate-embeddings-postgres.test.ts`.-- `src/core/engine-constants.ts` — single source of truth for engine batch-sizing constants. Exports `DELETE_BATCH_SIZE = 500` consumed by both engines' `deletePages` + `resolveSlugsByPaths` and by the sync delete + rename loops. Lives outside `engine.ts` (the interface module) to avoid circular-import worry — bounded per-statement work for predictable lock hold time + write amplification. Also exports `TRAVERSE_PATH_ROW_CAP = 5000`, the raw-row bound on `traversePaths`/`traversePathsDetailed` (both engines `LIMIT CAP + 1`; the extra row is the truncation probe; counted before edge dedup).+- `src/core/engine-constants.ts` — single source of truth for engine batch-sizing constants. Exports `DELETE_BATCH_SIZE = 500` consumed by both engines' `deletePages` + `resolveSlugsByPaths` and by the sync delete + rename loops. Lives outside `engine.ts` (the interface module) to avoid circular-import worry — bounded per-statement work for predictable lock hold time + write amplification. Also exports `TRAVERSE_PATH_ROW_CAP = 5000`, the raw-row bound on `traversePaths`/`traversePathsDetailed` (both engines `LIMIT CAP + 1`; the extra row is the truncation probe; counted before edge dedup), and `TRAVERSE_WALK_ROW_CAP = 20000`, the bound on simple-path rows the recursive walks enumerate (`traverseGraph` and `traversePaths*`, both engines). The walk CTE is pulled through `LIMIT` so a dense hub stops enumerating, rows are deduped to `(page, depth)` before the edge join or the per-node link aggregation, and `traversePaths` stops recursing one layer early because the deepest layer only terminates edges. A capped walk sets `truncated` on `traversePathsDetailed`.- `src/core/engine-factory.ts` — Engine factory with dynamic imports (`'pglite'` | `'postgres'`).diff --git a/docs/architecture/key-files/evaluation.md b/docs/architecture/key-files/evaluation.mdindex 02ba87497f..0df8de56c5 100644--- a/docs/architecture/key-files/evaluation.md+++ b/docs/architecture/key-files/evaluation.md@@ -47,6 +47,6 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/eval/shared/autocut-replay.ts` + `scripts/replay-autocut-floor.ts` — pure replay of the autocut weak-top-floor sweep over captured rerank pools, and its CLI. INVARIANT: the replay uses the SAME `applyAutocut` the live path uses, over the SAME pre-autocut reranked pool (`gbrain eval longmemeval --capture-pool` → `rerank_pool`, unscored alias/exact-lookup rows included — dropping them would change `decision.total`), with the SAME preserve predicate (`alias_hit === true || exact_lookup === true`), and slices to k AFTER autocut exactly like hybrid.ts, so `validateLive(rows, floor)` can demand byte-for-byte agreement with the recorded live decision (`search_meta.autocut`, plus `autocut_kept_keys` when present) before any other floor cell is trusted. Every cell — including floor `off` — comes from ONE capture; no second reranker call. Metric semantics mirror the harness (`distinct` sessions among the first k kept chunk rows; `recall_all` = gold ⊆ distinct; `recall_any` = non-empty intersection), with the benefit metrics `mean_returned_results` / `mean_returned_est_tokens` (why autocut exists) and recall as the guardrail; `pairedDelta` gives wins/losses/net per type vs the first floor, `splitHalf(rows, seed)` gives a seeded half-A/half-B selection/confirmation split, `topScoreHistogram` publishes the reranker's top-score distribution. `normalizePoolRow` throws on a row without `slug`/`session_id` (a silently dropped row shifts every cliff). The script owns argv (`<capture.ndjson> --floors off,0.10,… [--k 5] [--validate-live F] [--split-half SEED] [--jump 0.2] [--min-keep 1] [--json]`; `--validate-live` takes exactly one floor), file I/O and printing; every metric it prints routes through `src/core/eval/metric-glossary.ts` (`REPLAY_GLOSSARY_KEYS`); exit 0 ok · 1 validate-live mismatch or bad input · 2 usage. Pinned by `test/replay-autocut-floor.test.ts`.-- `src/eval/shared/embed-cache.ts` — content-addressed embedding cache for fixed-corpus evals (dataset-agnostic; the LongMemEval harness is its first consumer). INVARIANT: a cached vector is served ONLY for the exact `(model@dims, text, side)` it was computed for, and every row is integrity-checked on read (declared dims == stored bytes / 4 == vector length); a mismatch is a HARD `EmbedCacheIntegrityError` naming the file and the key — never a silent re-embed, because a silently corrupted cache makes every arm's vectors non-comparable. Key = `${model}@${dims}` (+ `#query` for query-side asymmetric embeds, so asymmetric query vectors can never be served a document-side row) + `:` + sha256(text). Storage: `bun:sqlite`, WAL journal + `synchronous=NORMAL`, busy retry, one transaction per question's embeds; local filesystem only. `installEmbedCache` installs it through the gateway's `__setEmbedTransportForTests` seam (gateway.ts sits at its module-size ceiling; a named `setEmbedTransport()` hook is a filed follow-up) and restores the caller-supplied `realTransport ?? null` on uninstall. Stats: `hits`, `misses` (genuine misses PLUS every value of a batch that fell open on an infrastructure fault), `bypassed` (SDK model id ≠ the installed model — never cached), `infra_faults` (file deleted mid-run / table dropped / disk error → uncached re-embed or lost write-back, so a run that lost its cache can never show a clean `misses: 0`). The canonical hash (`PRAGMA wal_checkpoint(TRUNCATE)` then sha256 over the sorted `(key, dims, sha256(vector))` rows) goes into `run_config.cache.canonical_sha256` so two runs can prove they saw the same vectors. Pinned by `test/longmemeval-embed-cache.test.ts`.+- `src/eval/shared/embed-cache.ts` — content-addressed embedding cache for fixed-corpus evals (dataset-agnostic; the LongMemEval harness is its first consumer). INVARIANT: a cached vector is served ONLY for the exact `(model@dims, text, side)` it was computed for, and every row is integrity-checked on read (declared dims == stored bytes / 4 == vector length); a mismatch is a HARD `EmbedCacheIntegrityError` naming the file and the key — never a silent re-embed, because a silently corrupted cache makes every arm's vectors non-comparable. Key = `${model}@${dims}` (+ `#query` for query-side asymmetric embeds, so asymmetric query vectors can never be served a document-side row) + `:` + sha256(text). Storage: `bun:sqlite`, WAL journal + `synchronous=NORMAL`, busy retry; local filesystem only. A question's writes are buffered in memory (reads see them) and written in one short `BEGIN IMMEDIATE` transaction when its `withTransaction` unit ends, so no SQLite lock is held across embed round-trips and concurrent runs sharing one cache file neither lose writes to `SQLITE_BUSY_SNAPSHOT` nor stall behind each other's questions. `installEmbedCache` installs it through the gateway's `__setEmbedTransportForTests` seam (gateway.ts sits at its module-size ceiling; a named `setEmbedTransport()` hook is a filed follow-up) and restores the caller-supplied `realTransport ?? null` on uninstall. Stats: `hits`, `misses` (genuine misses PLUS every value of a batch that fell open on an infrastructure fault), `bypassed` (SDK model id ≠ the installed model — never cached), `infra_faults` (file deleted mid-run / table dropped / disk error → uncached re-embed or lost write-back, so a run that lost its cache can never show a clean `misses: 0`). The canonical hash (`PRAGMA wal_checkpoint(TRUNCATE)` then sha256 over the sorted `(key, dims, sha256(vector))` rows) goes into `run_config.cache.canonical_sha256` so two runs can prove they saw the same vectors. Pinned by `test/longmemeval-embed-cache.test.ts`.- `src/eval/shared/judge-runner.ts` + `src/eval/shared/bootstrap.ts` — dataset-agnostic judge mechanics shared by the LongMemEval lane and any later judged eval. **judge-runner.ts** owns the chat-client seam (`JudgeChatFn` — the gateway `chat` in production, a canned fn in tests), bounded retries with exponential backoff (default 2 retries, base 500 ms, `sleep` seam), the closed `judge_error` vocabulary (`timeout | rate_limit | empty | refusal | malformed | provider_error`, exported as `JUDGE_ERROR_CLASSES`), usage summed over every attempt, per-call cost through the ONE canonical pricing table (`canonicalLookup`; an unpriced model yields `cost_usd: null`, never 0, and `isJudgeModelPriced` lets a budget refuse it), and the `BudgetLedger` (`maxUsd === null` = no cap; `canAfford(next)` is PROJECTED so a run never overshoots by more than the calls already in flight; unpriced calls are counted, not summed; `snapshot()` for receipts). INVARIANT: a judge malfunction is an error outcome, never a `verdict: 'incorrect'` — `runJudge` never throws on a transport failure (only an already-aborted `AbortSignal` or a bug in the caller's `parse` can), classifies 429 / rate-limit prose → `rate_limit`, abort / timeout → `timeout`, everything else → `provider_error`, and maps a `refusal` / `content_filter` stop, an empty completion and a null from `parse` to `refusal` / `empty` / `malformed`; the caller decides how the headline scores them. It passes `temperature` and `maxTokens` through `ChatOpts` and records `ChatResult.responseModel` as `response_model`. **bootstrap.ts**: `bootstrapMeanCi(xs, {resamples = 10000, seed = 42, alpha = 0.05})` is a seeded (mulberry32) percentile bootstrap of the mean, byte-reproducible; n = 0 → nulls, n = 1 → a degenerate `[x, x]`. INVARIANT: every block carries `label: 'question-sampling only'` — the interval quantifies how much the number would move under a different draw of questions and says nothing about reader / judge nondeterminism, dataset revision or prompt drift. Pinned by `test/longmemeval-judge.test.ts`.diff --git a/docs/architecture/key-files/files-and-sync-1.md b/docs/architecture/key-files/files-and-sync-1.mdindex 56a96a3b98..f15454f895 100644--- a/docs/architecture/key-files/files-and-sync-1.md+++ b/docs/architecture/key-files/files-and-sync-1.md@@ -25,7 +25,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/import-checkpoint.ts` — `loadCheckpoint(brainDir)`, `saveCheckpoint(brainDir, completed)`, `resumeFilter(files, completed, brainDir)`, `clearCheckpoint()`, plus the `ImportCheckpoint` type. Path-set format `{schema_version, brainDir, completed: string[]}`. Atomic write via `.tmp` + `rename()` so a mid-write crash never leaves a partial JSON. `loadCheckpoint` returns `null` on: missing file, malformed JSON, brainDir mismatch (ran against a different brain), and the old positional format (logged to stderr before discard). `resumeFilter` returns `{toProcess, skippedCount}` — pure, no I/O, deterministic. `clearCheckpoint` is no-op-on-missing for clean-exit cleanup. Honors `GBRAIN_HOME` via `gbrainPath()` so `withEnv({GBRAIN_HOME: tmpdir})` test isolation works without monkey-patching fs. Best-effort persistence — `saveCheckpoint` logs warnings on write errors but never throws.-- `src/core/import-file.ts` — importFromFile + importFromContent (chunk + embed + tags). Unchanged markdown or code content whose page is below the safe-chunk fence is re-sealed projection-only (direct imports install it; coordinated `prepare` imports stay no-ops and queue a `safe_chunk_reseal` projection job), with no page write or admission. Freshly embedded chunks carry `embedding_input_hash` for the tier they were built under. The `beforeCommit` hook runs inside the guarded canonical transaction so a rejected file write rolls back its projections; optional legacy source-path repair uses a savepoint. Deferred importer embedding callbacks capture the committed text projection and indexing context, then install with an UPDATE-only revision/chunk/hash check. Tests: `test/import-publication-guards.test.ts`. Coordinated `prepare` imports resolve and atomically stamp the page/source/global contextual wrapping mode even with `noEmbed:true`; the durable outbox later embeds that revision. The existing paid-synopsis title fallback and mount trust gate remain in force, while embedding signatures only certify completed vectors. `test/persistence-contextual-embedding.test.ts` covers both engines, policy precedence, deferred provider execution, and a competing title replacement. `importFromContent` and `importCodeFile` stamp `pages.embedding_signature` via `setPageEmbeddingSignature(slug, {sourceId, signature: currentEmbeddingSignature()})` when the import actually embedded (not `--no-embed`) so a model/dims swap is detectable as stale; `importCodeFile` only stamps when every chunk was freshly embedded this call (`needsEmbedIndexes.length === chunks.length`), mixed reuse-by-hash pages stay unstamped (`reindex --code --force` / `embed --stale` handle those). `importFromContent`'s tag reconciliation is ADD-ONLY: it only `addTag` (idempotent, ON CONFLICT DO NOTHING). The `tags` table has no provenance column and frontmatter tags are stripped from stored `pages.frontmatter` (markdown.ts:118), so a frontmatter-origin tag can't be distinguished from a DB-enrichment tag (auto-tag / dream synthesize / signal-detector) at re-import — deletion is unsafe (would wipe enrichment under `gbrain reindex --markdown`). Accepted trade-off: removing a tag from frontmatter does not remove it from the DB on next sync (needs a `tag_source` provenance column). Pinned by `test/reindex-preserve-tags.test.ts` + `test/import-file.test.ts`. identity decisions live in `src/core/import-identity.ts` (`decideImportIdentity`, `collidingSlugOwner`; pure reads, the importer applies them). The dedup pre-check calls `engine.findDuplicatePage?.(sourceId, {hash, frontmatterId, excludeSlug})` (optional `?` so test doubles compile; the caller's own slug never matches, and a `frontmatter.id` match ranks ahead of a bare hash match). Posture: MOVE when the `frontmatter.id` matches and the other page's recorded `source_path` is gone under this import's root (`sourceRoot`, set by `importFromFile`): `updateSlug` carries the row (page id, links, facts, timeline, plus a rename alias) and the new content imports onto it, so a full sync's delete-reconcile has nothing live to remove; SKIP only when the id AND the content (`content_hash`, or title and body for a row written outside the importer) both match while the recorded file still exists (overlapping ingest roots); IMPORT with a warning when the id matches but content differs (templates, copy-paste; an edit is never frozen by the other page); WARN-ALWAYS on a bare content_hash collision; FAIL CLOSED on lookup error; bypass via `--force-rechunk`. Content-only callers (`put_page`, transcripts) never move a page. Soft-deleted pages excluded at the engine layer so tombstones don't block legitimate re-imports under new slugs. Slug collisions: when another live file (`existing.source_path`, realpath-distinct) already owns the slug, the incoming file is skipped with `skip_reason: 'slug_collision'` and a stderr warning, unless the incoming file is named exactly `<slug>.md` (the file the link extractor reads for that slug), so two spellings never overwrite each other. An embedding failure never blocks the text write: chunks commit with NULL vectors, no embedding signature is stamped, the result carries `embedding_deferred: true`, and the stale sweep embeds them later (a code file whose embed failed is not stamped either). `effective_date` for an undated page falls back to `fallbackCreatedAt` (stored fallback date, else the file's own timestamp via `fileTimes`, else now), never the latest write. Pinned by `test/import-dedup-frontmatter-id.test.ts`, `test/import-identity-move.test.ts`, `test/import-slug-collision.test.ts`, `test/import-embed-outage.test.ts` and `test/effective-date-calendar.test.ts`. `importFromContent` is the narrow waist every ingest path passes through (`gbrain import`, `gbrain sync`, `put_page` MCP, `/ingest` webhook). It runs a three-tier content-quality disposition via `assessContentSanity` from `src/core/content-sanity.ts` BEFORE chunking: (1) high-confidence junk (built-in Cloudflare/CAPTCHA interstitial patterns + operator literals) → QUARANTINE (stamps the `quarantine` frontmatter marker, writes ZERO chunks, hides the page from search) OR REJECT (throw → sync-failure) when `content_sanity.junk_disposition` is `reject`; (2) fuzzy markup-heavy (prose-vs-markup ratio above `content_sanity.max_markup_ratio`, warn-tier byte window, code pages exempt) → `content_flag:markup_heavy` marker (page stays fully searchable, marker rides search results + get_page to warn the agent); (3) oversize → `embed_skip` soft-block via `buildEmbedSkipMarker()` PLUS a `content_flag:oversized` marker, AND deletes any pre-existing chunks in the same transaction so search can't surface stale chunks. Gate-owned markers (`quarantine`, `content_flag`) are STRIPPED from untrusted (remote MCP, `ctx.remote !== false`) frontmatter so a write-scoped client can't hide pages or forge the warning channel; markers are excluded from `content_hash` so a flagged page doesn't re-embed every sync. `gbrain import` honors `errors > 0` for non-zero exit. `classifyErrorCode` in `src/core/sync.ts` recognizes the `PAGE_JUNK_PATTERN` code so sync-failures.jsonl grouping bins these. `extractEntityRefs` (canonical; matches both `[Name](../people/slug)` markdown links and Obsidian `[[people/slug|Name]]` wikilinks), `extractPageLinks`, `inferLinkType` heuristics (attended/works_at/invested_in/founded/advises/source/mentions), `parseTimelineEntries`, `isAutoLinkEnabled` config helper. Link candidates match any dir-shaped path (existence-checked at persist). Used by extract.ts, operations.ts auto-link post-hook, and backlinks.ts. Pinned by `test/import-file-content-sanity.test.ts`. `importImageFile` records `source_path` on every image page and skips an unchanged image only when its index is complete for the run: a visual vector when embedding is on, and OCR (`ocr_status: 'done'` in frontmatter, or legacy stored OCR text) when OCR is enabled, so an image first imported under `--no-embed` or an OCR skip is rebuilt on its next import (`test/import-image-retry.test.ts`). `importCodeFile` writes `source_path: relativePath` on every code page (the same repo-relative path markdown imports record) so the full-sync reconcile — which only considers `source_path IS NOT NULL` rows — can retire a deleted code file's page; `putPage` COALESCEs the column, so rows imported before this keep NULL until the file changes, `sync --force`, or `gbrain reindex-code --force`.+- `src/core/import-file.ts` — importFromFile + importFromContent (chunk + embed + tags). Unchanged markdown or code content whose page is below the safe-chunk fence is re-sealed projection-only (direct imports install it; coordinated `prepare` imports stay no-ops and queue a `safe_chunk_reseal` projection job), with no page write or admission. Freshly embedded chunks carry `embedding_input_hash` for the tier they were built under. The `beforeCommit` hook runs inside the guarded canonical transaction so a rejected file write rolls back its projections; optional legacy source-path repair uses a savepoint. Deferred importer embedding callbacks capture the committed text projection and indexing context, then install with an UPDATE-only revision/chunk/hash check. Tests: `test/import-publication-guards.test.ts`. Coordinated `prepare` imports resolve and atomically stamp the page/source/global contextual wrapping mode even with `noEmbed:true`; the durable outbox later embeds that revision. The existing paid-synopsis title fallback and mount trust gate remain in force, while embedding signatures only certify completed vectors. `test/persistence-contextual-embedding.test.ts` covers both engines, policy precedence, deferred provider execution, and a competing title replacement. `importFromContent` and `importCodeFile` stamp `pages.embedding_signature` via `setPageEmbeddingSignature(slug, {sourceId, signature: currentEmbeddingSignature()})` when the import actually embedded (not `--no-embed`) so a model/dims swap is detectable as stale; `importCodeFile` only stamps when every chunk was freshly embedded this call (`needsEmbedIndexes.length === chunks.length`), mixed reuse-by-hash pages stay unstamped (`reindex --code --force` / `embed --stale` handle those). `importFromContent` reconciles tags by provenance (`tags.tag_source`, migration v175): frontmatter tags go through `addTag(..., { tagSource: 'frontmatter' })`, and a row still marked 'frontmatter' whose tag left the frontmatter is deleted in the import transaction. Every other `addTag` stamps 'added' (add_tag, enrichment, the code importer) and is never import-deleted, so `gbrain reindex --markdown` keeps enrichment tags; legacy NULL rows are adopted only while the frontmatter still lists them; prepared (managed) imports keep add-only tags, matching the union their canonical file renders. Pinned by `test/reindex-preserve-tags.test.ts`, `test/import-frontmatter-tag-removal.test.ts` + `test/import-file.test.ts`. identity decisions live in `src/core/import-identity.ts` (`decideImportIdentity`, `collidingSlugOwner`; pure reads, the importer applies them). The dedup pre-check calls `engine.findDuplicatePage?.(sourceId, {hash, frontmatterId, excludeSlug})` (optional `?` so test doubles compile; the caller's own slug never matches, and a `frontmatter.id` match ranks ahead of a bare hash match). Posture: MOVE when the `frontmatter.id` matches and the other page's OWN origin proves it moved (#5675): that origin is the `file://` path `importFromFile` records in `pages.source_uri` (never replacing non-file provenance), else the source's configured root (`local_path`, or the default source's legacy `sync.repo_path`). An origin that still exists moves only when it is this very file under another relative path (overlapping roots converge); a gone origin needs this file under that same root, and differing content also needs the same file name or title, so a missing path under another root, or a new note reusing a deleted note's template id, never renames a live page. `updateSlug` carries the row (page id, links, facts incl. `entity_slug`/`source_markdown_slug`, `page_aliases`, timeline, plus a rename alias) and the new content imports onto it, so a full sync's delete-reconcile has nothing live to remove; SKIP only when the id AND the content (`content_hash`, or title and body for a row written outside the importer) both match while the recorded file still exists (overlapping ingest roots); IMPORT with a warning when the id matches but content differs (templates, copy-paste; an edit is never frozen by the other page); WARN-ALWAYS on a bare content_hash collision; FAIL CLOSED on lookup error; bypass via `--force-rechunk`. Content-only callers (`put_page`, transcripts) never move a page. Soft-deleted pages excluded at the engine layer so tombstones don't block legitimate re-imports under new slugs. Slug collisions: when another live file (`existing.source_path`, realpath-distinct) already owns the slug, the incoming file is skipped with `skip_reason: 'slug_collision'` and a stderr warning, unless the incoming file is named exactly `<slug>.md` (the file the link extractor reads for that slug), so two spellings never overwrite each other. An embedding failure never blocks the text write: chunks commit with NULL vectors, no embedding signature is stamped, the result carries `embedding_deferred: true`, and the stale sweep embeds them later (a code file whose embed failed is not stamped either). An inline markdown re-import embeds only chunks whose embedding input changed: `planEmbeddingReuse` (keyed on chunk source + exact text) reuses a stored vector when the old index is sealed (`requireSafeChunks`), the page's `embedding_signature`, contextual mode, `corpus_generation` and (under the title wrapper) sanitized title are unchanged, and neither the old nor the new body holds protected fences; prepared, `--no-embed`, `--force-rechunk` and post-commit-embedding imports reuse nothing (`test/import-markdown-embedding-reuse.test.ts`). Offset-less frontmatter datetimes are read in the brain's `brain.timezone` (IANA, validated by `gbrain config set`; unset or invalid = UTC; the YAML parser tags naive timestamps with `NAIVE_DATETIME` so the wall-clock reading survives), while date-only values stay UTC calendar dates (`test/effective-date-brain-timezone.test.ts`). `effective_date` for an undated page falls back to `fallbackCreatedAt` (stored fallback date, else the earliest of the file's birth/modification time and — when `sync.git_first_commit_dates` is on — its git first-commit date via `fileTimes`, else now; `src/core/git-first-commit.ts` maps paths in one `git log --diff-filter=A` pass per `runImport`, skipping shallow clones; `test/effective-date-git-first-commit.test.ts`), never the latest write. Pinned by `test/import-dedup-frontmatter-id.test.ts`, `test/import-identity-move.test.ts`, `test/import-slug-collision.test.ts`, `test/import-embed-outage.test.ts` and `test/effective-date-calendar.test.ts`. `importFromContent` is the narrow waist every ingest path passes through (`gbrain import`, `gbrain sync`, `put_page` MCP, `/ingest` webhook). It runs a three-tier content-quality disposition via `assessContentSanity` from `src/core/content-sanity.ts` BEFORE chunking: (1) high-confidence junk (built-in Cloudflare/CAPTCHA interstitial patterns + operator literals) → QUARANTINE (stamps the `quarantine` frontmatter marker, writes ZERO chunks, hides the page from search) OR REJECT (throw → sync-failure) when `content_sanity.junk_disposition` is `reject`; (2) fuzzy markup-heavy (prose-vs-markup ratio above `content_sanity.max_markup_ratio`, warn-tier byte window, code pages exempt) → `content_flag:markup_heavy` marker (page stays fully searchable, marker rides search results + get_page to warn the agent); (3) oversize → `embed_skip` soft-block via `buildEmbedSkipMarker()` PLUS a `content_flag:oversized` marker, AND deletes any pre-existing chunks in the same transaction so search can't surface stale chunks. Gate-owned markers (`quarantine`, `content_flag`) are STRIPPED from untrusted (remote MCP, `ctx.remote !== false`) frontmatter so a write-scoped client can't hide pages or forge the warning channel; markers are excluded from `content_hash` so a flagged page doesn't re-embed every sync. `gbrain import` honors `errors > 0` for non-zero exit. `classifyErrorCode` in `src/core/sync.ts` recognizes the `PAGE_JUNK_PATTERN` code so sync-failures.jsonl grouping bins these. `extractEntityRefs` (canonical; matches both `[Name](../people/slug)` markdown links and Obsidian `[[people/slug|Name]]` wikilinks), `extractPageLinks`, `inferLinkType` heuristics (attended/works_at/invested_in/founded/advises/source/mentions), `parseTimelineEntries`, `isAutoLinkEnabled` config helper. Link candidates match any dir-shaped path (existence-checked at persist). Used by extract.ts, operations.ts auto-link post-hook, and backlinks.ts. Pinned by `test/import-file-content-sanity.test.ts`. `importImageFile` records `source_path` on every image page and skips an unchanged image only when its index is complete for the run: a visual vector when embedding is on, and OCR (`ocr_status: 'done'` in frontmatter, or legacy stored OCR text) when OCR is enabled, so an image first imported under `--no-embed` or an OCR skip is rebuilt on its next import (`test/import-image-retry.test.ts`). `importCodeFile` writes `source_path: relativePath` on every code page (the same repo-relative path markdown imports record) so the full-sync reconcile — which only considers `source_path IS NOT NULL` rows — can retire a deleted code file's page; `putPage` COALESCEs the column, so rows imported before this keep NULL until the file changes, `sync --force`, or `gbrain reindex-code --force`.- `src/core/link-source-check-repair.ts` — schema-drift self-heal for the `links_link_source_check` CHECK constraint (third instance of the `timeline-dedup-repair.ts` / `pages-upsert-arbiter.ts` class). Migration v114 opened `link_source` from a closed allowlist to the kebab-case gate; the migrator trusts the version ledger, so a brain stamped >= 114 whose live constraint reverted to the pre-v114 allowlist (drifted restore, manual DDL) rejects every kebab provenance write (`atom-provenance`, `concept-provenance`) while the ledger reads current. `LINK_SOURCE_KEBAB_RE` is the ONE exported copy of the regex (a drift-guard test pins it to the literal in migrate.ts v114, `schema.sql`, `pglite-schema.ts`). `checkLinkSourceCheck(engine)` probes `pg_constraint` (`pg_get_constraintdef` + `convalidated`) and classifies the drift as `absent` / `wrong_def` / `not_validated` (read-only; powers the `links_link_source_check` doctor check in `doctor/checks/core-health.ts`, whose severity follows what writes do: only `wrong_def` rejects kebab writes → fail; `absent` / `not_validated` still accept them → warn). `repairLinkSourceCheck(engine)` first COUNTs rows that fail the gate and returns `reason: 'violations'` WITHOUT any DDL when there are any (the prior constraint survives; rows are never touched; a brain with a bad row never pays for a failing ALTER at every engine open), then restores v114's definition mirroring the migration's engine split: Postgres runs DROP + `ADD ... NOT VALID` in one `engine.transaction` (atomic, no scan) and `VALIDATE CONSTRAINT` as a separate `engine.runMigration` outside it (SHARE UPDATE EXCLUSIVE, never a plain ADD's ACCESS EXCLUSIVE + full-table scan), with a `not_validated` drift getting the VALIDATE only; PGLite keeps the one-shot DROP+ADD transaction. A DDL failure re-counts violators (a row written between probe and ALTER) and rethrows when there are none. `LINK_SOURCE_GATE_MIGRATION_VERSION` (114) is the ledger gate `runMigrations` applies before calling it. Pinned by `test/link-source-check-repair.test.ts` (PGLite, incl. a recording-engine assertion that violators trigger no DDL and that a sub-114 ledger never probes) and the DATABASE_URL-gated `test/e2e/link-source-check-repair-postgres.test.ts` (two-phase DDL sequence on real Postgres).diff --git a/docs/architecture/key-files/google-and-loops-continued.md b/docs/architecture/key-files/google-and-loops-continued.mdindex d637e69137..77dde6379d 100644--- a/docs/architecture/key-files/google-and-loops-continued.md+++ b/docs/architecture/key-files/google-and-loops-continued.md@@ -15,12 +15,13 @@- `src/core/persistence/diagnostics.ts` — trusted administrator counts for owners/epochs, queued bytes/age, outbox recovery, configured quota usage and actionable capacity warnings; bigint values are transport-safe strings and diagnostics exclude intent, credentials and private paths.-- **`src/core/persistence/sync-discovery.ts`** + **`sync-origin.ts`** — managed owner-only Git discovery with source-relative exclusions and one-statement page identity/revision snapshots. Nested full discovery filters source scope before slicing paths. Windows separator aliases retain their page identity; ambiguous aliases refuse, while POSIX backslashes/case remain exact. Under `source-root` mode a stored `<scope>/<path>` origin (the Git-root form older write-through minted from the slug, recognized because `<path>` names the page slug) is accepted as `<path>` at discovery, freeze, preparation and the page-origin query, and an import rewrites it in place; when both readings name existing files the stored origin refuses with `detail: ambiguous_source_path`. A genuine origin mismatch refuses with `detail: sync_origin_mismatch` and the filled paths. Deletions must be absent from the pinned Git target or their explicitly selected working tree. Existing cursors reuse their accepted manifests, with unknown old deletion provenance refused rather than rewritten.-- **`src/core/persistence/sync-run.ts`** + **`sync-authority.ts`** — one immutable request at a time, bounded fairness and pinned-target resumption. Cursors and requests freeze `noEmbed`, `noExtract` and `noSchemaPack`. A resume adopts the stored options for every option the caller did not set explicitly (`SyncOpts.explicitProcessing`: CLI flags, wire flags, job params; autopilot and the cycle set none); an explicit conflict refuses with `detail: cursor_processing_options_conflict`, the stored options and the exact resume command. Callers that omit `explicitProcessing` stay strict. Explicit idle ordinary-source retry creates fresh discovery/admission and retains terminal receipts; company consent retry retains its approved manifest/run. Active work blocks replacement. Claimed/inactive sync, including connector/company dispatch, remains refused: existing leases and native locks do not fence already-running engine-only legacy writers. No automatic activation or new transition protocol.-- **`src/core/persistence/sync-prepare.ts`** — guarded raw fingerprint/revision, source root and active coordinator checks before preparation and at locked publication. Old imports/checkpoints without durable processing consent refuse under their original IDs; old deletions require their immutable origin manifest and a still-matching page origin. `noEmbed` suppresses the effect itself; `noSchemaPack` bypasses pack loading; optional extraction stays disabled, but mandatory provider-free canonical projections remain. CRLF equivalence never weakens raw CAS. No uncoordinated filesystem writes. Tests: `persistence-sync-origin-native.serial.test.ts`, `persistence-sync-options.serial.test.ts`, `persistence-sync-company.serial.test.ts`.+- **`src/core/persistence/sync-discovery.ts`** + **`sync-origin.ts`** — managed owner-only Git discovery with source-relative exclusions and one-statement page identity/revision snapshots. Nested full discovery filters source scope before slicing paths. Windows separator aliases retain their page identity; ambiguous aliases refuse, while POSIX backslashes/case remain exact. Under `source-root` mode a stored `<scope>/<path>` origin (the Git-root form older write-through minted from the slug, recognized because `<path>` names the page slug) is accepted as `<path>` at discovery, freeze, preparation and the page-origin query, and an import rewrites it in place; when both readings name existing files the stored origin refuses with `detail: ambiguous_source_path`. A genuine origin mismatch refuses with `detail: sync_origin_mismatch` and the filled paths. Deletions must be absent from the pinned Git target or their explicitly selected working tree. Existing cursors reuse their accepted manifests, with unknown old deletion provenance refused rather than rewritten. Imports whose origin has no page claim their slug together: a live page whose own file is still in the tree keeps the slug, otherwise the file named like the slug (else the first path) wins, and the losers leave the manifest and are reported as `slugCollisions` (the library path's `slug_collision` skip) instead of failing the run. A winner whose slug is held by a page with a vanished or deleted origin takes that page over (`renameFrom`, same slug). A Git-detected rename to an unoccupied slug becomes one import carrying `renameFrom` in place of a delete plus a create. Origins for one slug that differ only by case or separator spelling refuse, except a case-only respelling whose old file the same sync removes. Code files keep exact per-origin identity.+- **`src/core/persistence/sync-run.ts`** + **`sync-authority.ts`** — one immutable request at a time, bounded fairness and pinned-target resumption. Cursors and requests freeze `noEmbed`, `noExtract` and `noSchemaPack`. A resume adopts the stored options for every option the caller did not set explicitly (`SyncOpts.explicitProcessing`: CLI flags, wire flags, job params; autopilot and the cycle set none); an explicit conflict refuses with `detail: cursor_processing_options_conflict`, the stored options and the exact resume command. Callers that omit `explicitProcessing` stay strict. Explicit idle ordinary-source retry creates fresh discovery/admission and retains terminal receipts; company consent retry retains its approved manifest/run. Active work blocks replacement. Claimed/inactive sync, including connector/company dispatch, remains refused: existing leases and native locks do not fence already-running engine-only legacy writers. No automatic activation or new transition protocol. `freezeEntry` checks a rename's source page (id, revision, origin) as well as its target slug, and a committed rename counts in `renamed`. After the checkpoint commits (and unless `noExtract`), the owner derives links for the source's stale pages through `links-maintenance.ts`, so a PGLite-delegated sync and a Postgres sync take the same path; the result carries `links`, and an extraction failure leaves pages stale without failing the committed sync.+- **`src/core/persistence/sync-prepare.ts`** — guarded raw fingerprint/revision, source root and active coordinator checks before preparation and at locked publication. Old imports/checkpoints without durable processing consent refuse under their original IDs; old deletions require their immutable origin manifest and a still-matching page origin. `noEmbed` suppresses the effect itself; `noSchemaPack` bypasses pack loading; optional extraction stays disabled, but mandatory provider-free canonical projections remain. CRLF equivalence never weakens raw CAS. No uncoordinated filesystem writes. Tests: `persistence-sync-origin-native.serial.test.ts`, `persistence-sync-options.serial.test.ts`, `persistence-sync-company.serial.test.ts`. A same-slug `renameFrom` accepts the page's recorded old origin. A different-slug rename prepares against the page where it stands, locks the old slug as an additional page key, and at publication moves the page with `updateSlug` (same id, inbound links and history, `old -> new` in `slug_aliases`, withdrawn claims follow), re-infers an implicit type from the new path, then re-prepares and applies the file content at the new slug, so the move never writes back to the file. Tests: `persistence-managed-lifecycle.test.ts`.+- **`src/core/persistence/links-maintenance.ts`** — `extractManagedStaleLinks` derives links for pages whose extraction watermark is stale with `prepareAutomaticLinks` (put_page's replace contract; other producers' edges stay) and adds the coordinator's unrecorded canonical timeline tuples (insert-only) and each page's watermark in the same `withCoordinatedWrite` transaction, bound to the revision it read; an edited page or unresolved attendance stays stale. It is the one managed extraction path: managed sync, `extractStaleFromDB` on a managed brain, and the owner delegation all run it. `runManagedStaleExtraction` backs `gbrain extract --stale` on managed brains, locally or through the `writer_extract_stale` administration operation inside a PGLite owner (`src/commands/extract-stale-delegate.ts`, trusted CLI registration only). `links-preparation.ts` retargets a link written against a renamed page's old slug to the live canonical page through `slug_aliases`, as `get_page` does. Tests: `persistence-managed-lifecycle.test.ts`, `persistence-sync-stdio-owner.serial.test.ts`.- **`src/core/persistence/sync-authority.ts`** — trusted CLI or original remote generic job authority; rejects stdio bulk privilege promotion and runtime option expansion, intersects original grants with current principal/source policy.-- `src/core/facts/withdrawal-overlay.ts` — pure legacy-fence enumeration and withdrawal rendering shared by coherent snapshots, stale imports and physical forget mirrors. The shared snapshot overlay and import pre-publication validator recognize canonical prefixed/inline markers and distinguish malformed live segments. Discovery refuses matching ambiguous claims before mutation. Fingerprints match independently in each fence, including inactive history; parser-recognized markers precede preserved evidence context and earlier expiry remains intact. Regression: `test/withdrawal-overlay-concurrency.test.ts` on both engines.+- `src/core/facts/withdrawal-overlay.ts` — pure legacy-fence enumeration and withdrawal rendering shared by coherent snapshots, stale imports and physical forget mirrors. The shared snapshot overlay and import pre-publication validator recognize canonical prefixed/inline markers and distinguish malformed live segments. Discovery refuses matching ambiguous claims before mutation. Fingerprints match independently in each fence, including inactive history, against both the folded (v174) and exact legacy hashes; parser-recognized markers precede preserved evidence context and earlier expiry remains intact. Regression: `test/withdrawal-overlay-concurrency.test.ts` on both engines.- **`src/commands/sync-persistence-delegate.ts` + `src/core/persistence/{sync-wire,sync-administration}.ts`** — pre-connect authenticated CLI sync ingress for any resident PGLite owner, including stdio MCP. The CLI JSON renderer shares the direct sync envelope. Strict options preserve source/brain selection and filtering; only current CLI credentials can advance bounded durable cursor slices. Unactivated delegation also forces import-only work and queues the owner embed drain, preserving the inline cost gate; backlogs are per-engine source sets and shutdown waits for actual provider settlement before releasing datastore ownership; the real serve E2E observes a committed receipt before SIGKILL and proves same-ID cursor recovery without breaking locks. Legacy shared-secret sync refuses managed brains. `test/persistence-sync-stdio-owner.serial.test.ts` starts a real stdio owner and exercises CLI import/read/admin, remote-lane denial and revocation without a competing datastore open.- `src/core/facts/backstop.ts` + `src/core/entities/resolve-on-save.ts` — saved facts retain their content and provenance but use a NULL entity target when resolution falls back to slugification. Legacy extraction uses the shared exact source/entity/visibility fingerprint decision before identity-gated cosine candidates, so old facts without vector provenance still deduplicate identical text without relabeling their vectors. The conversation save caller also clears the target on ordinary resolution errors, preserves diagnostic counters, and propagates abort/budget failures. It never treats an invented slug as a verified page.- `src/commands/migrations/v0_32_2.ts` — fences live legacy facts only onto an existing source-scoped page and its recorded canonical file. Missing pages/files are counted as `skipped_no_page`, never materialized as stubs. Dirty-tree checks stay inside the source subdirectory; fence row allocation respects both database-owned row numbers and the parsed fence, preserving idempotent recovery without collisions. Dry runs use the same eligibility checks, and historical drift remains visible rather than silently repaired.diff --git a/docs/architecture/key-files/graph-and-facts.md b/docs/architecture/key-files/graph-and-facts.mdindex 55c4ef6e5e..afc5d141a6 100644--- a/docs/architecture/key-files/graph-and-facts.md+++ b/docs/architecture/key-files/graph-and-facts.md@@ -74,9 +74,9 @@ rejection of serve-only flags before a brain opens.- `src/core/check-resolvable.ts` — Resolver validation: reachability, MECE overlap, DRY checks, structured fix objects. `CROSS_CUTTING_PATTERNS.conventions` is an array (notability gate accepts `conventions/quality.md` and `_brain-filing-rules.md`). `extractTriggers()` delegates to the shared SKILL.md parser, so MECE gap detection and the trigger index agree on block lists, single-line flow sequences, wrapped flow sequences, and CRLF input. `extractDelegationTargets()` parses `> **Convention:**`, `> **Filing rule:**`, and inline backtick references. DRY suppression is proximity-based via `DRY_PROXIMITY_LINES = 40`. `parseResolverEntries` accepts BOTH the markdown table AND a compact list format (`- **skill-name**: trigger1 | trigger2 | trigger3` or `- skill-name: trigger1 | trigger2`); shapes can mix in one file, folded by the multi-resolver merge. Skill name MUST be kebab-lowercase (regex `[a-z][a-z0-9-]+`) so prose bullets like `- **Note**:`/`- **Convention**:`/`- **TODO**:` don't false-match as skill rows. `skillPath` is ALWAYS derived as `skills/<name>/SKILL.md`: an optional `→ \`skills/path\`` (or ASCII `->`) suffix is stripped from the trigger but NOT honored as the path — two consumers (`routing-eval.ts:skillSlugFromPath`, the manifest lookup) assume the convention; use the table format for non-conventional paths. Multi-trigger rows fan out to one entry per trigger sharing the same `skillPath`; `checkResolvable` dedupes so the reachability count counts each skill once. Pinned by `test/check-resolvable.test.ts` (resolver shapes plus trigger array syntax cases) + `test/check-resolvable-openclaw-compact.test.ts` (8 cases over `test/fixtures/openclaw-compact-resolver/` and `test/fixtures/openclaw-mixed-merge/`). Tutorial: `docs/guides/scaling-skills.md` (three-tier scaling: ~300-skill agent to ~4K tokens/turn from ~25K). `checkResolvable(skillsDir, opts?)` takes an optional `skillsDirSource` (the detection tier from `autoDetectSkillsDir`, threaded by both callers: doctor.ts and the check-resolvable command; an explicit `--skills-dir` passes `null`). An `unreachable` issue downgrades from `error` to `warning` only when ALL hold: the directory was found via the ungated `cwd_walk_up` tier, no resolver file contributes rows (no `RESOLVER.md`; a generic `AGENTS.md` with zero table rows counts as absent), unreachable skills outnumber reachable ones, and no `manifest.json` exists on disk. This keeps a foreign tool's `skills/` dir walked up to from cwd from being scored as a broken gbrain skillpack, while a real skillpack (RESOLVER.md present, higher-confidence tier, dense trigger coverage, or any manifest.json, even a corrupted one) stays strict. A foreign dir with zero `triggers:` and no resolver file still hard-fails via the `missing_file` branch (separate follow-up).-- `src/core/entities/resolve.ts` — Free-form entity name → canonical slug resolution. `resolveEntitySlug(engine, source_id, raw)`: exact slug → alias-exact (an unambiguous `page_aliases` hit via `resolveAliases`, verified against LIVE pages since `page_aliases` has no FK — a stale alias row can never point at a deleted page; fail-open on pre-v110 brains missing the table; `ResolutionSource` reports `alias_exact`) → unique source-scoped full-basename match for multi-token names across people/companies/hosts/projects/concepts → unambiguous bare-name prefix expansion across `people/<token>-%` + `companies/<token>-%` → fuzzy candidates for multi-token input taken only when `sameEntityName` holds (same name tokens ignoring case, punctuation, order, accents and corporate suffixes), so a near-name such as "Alicia Example" never lands on Alice and a person without a page never lands on a meeting page → deterministic `slugify` holding fallback. Bare-name collisions never use popularity as confidence. `isIdentityEntity(slug, type)` (person/company/fund/organization types or their directories) and `sameEntityName` are shared with `makeResolver`. The phantom-redirect helper keeps the legacy 0.7 trigram rule. Two helpers for the phantom-redirect pass: `resolvePhantomCanonical(engine, sourceId, phantomSlug)` SKIPS the exact-slug step (a phantom slug `'alice'` would exact-match itself and no-op the redirect); returns the canonical only when non-null AND contains `/`. `findPrefixCandidates(engine, sourceId, token)` is a standalone SQL query returning ALL candidates across `PREFIX_EXPANSION_DIRS` (hardcoded `['people', 'companies']`) via `slug LIKE ANY($N::text[])` over patterns `dir/token` + `dir/token-%`, cap of 10 ordered by `connection_count DESC, slug ASC`. Pinned by `test/entity-resolve.test.ts` (explicit, unique, ambiguous-person, and shared-token-company cases) plus `test/phantom-redirect.test.ts` (resolvePhantomCanonical 3 cases + findPrefixCandidates 6 cases incl. multi-dir ambiguity and the `people/aliceberg`-doesn't-match-`alice` false-positive guard).+- `src/core/entities/resolve.ts` — Free-form entity name → canonical slug resolution. `resolveEntitySlug(engine, source_id, raw)`: exact slug → alias-exact (an unambiguous `page_aliases` hit via `resolveAliases`, verified against LIVE pages since `page_aliases` has no FK — a stale alias row can never point at a deleted page; fail-open on pre-v110 brains missing the table; `ResolutionSource` reports `alias_exact`) → unique source-scoped full-basename match for multi-token names across people/companies/hosts/projects/concepts → unambiguous bare-name prefix expansion across `people/<token>-%` + `companies/<token>-%` (tagged `prefix_expansion`, not `fuzzy_match`: the sole candidate is chosen by cardinality, so `facts/backstop.ts` appends an unverified-resolution note to the fact's context cell) → fuzzy candidates for multi-token input taken only when `sameEntityName` holds (same name tokens ignoring case, punctuation, order, accents and corporate suffixes), the candidate is an entity page (person/company/fund/org, host, project, concept or deal — never a meeting or note), and it is the only such candidate, so a near-name such as "Alicia Example" never lands on Alice and a person without a page never lands on a meeting page → deterministic `slugify` holding fallback. Bare-name collisions never use popularity as confidence. `isIdentityEntity(slug, type)` (person/company/fund/organization types or their directories) and `sameEntityName` are shared with `makeResolver`. The phantom-redirect helper takes a fuzzy hit only at trigram ≥ 0.7 with a 0.1 margin over the runner-up. Two helpers for the phantom-redirect pass: `resolvePhantomCanonical(engine, sourceId, phantomSlug)` SKIPS the exact-slug step (a phantom slug `'alice'` would exact-match itself and no-op the redirect); returns the canonical only when non-null AND contains `/`. `findPrefixCandidates(engine, sourceId, token)` is a standalone SQL query returning ALL candidates across `PREFIX_EXPANSION_DIRS` (hardcoded `['people', 'companies']`) via `slug LIKE ANY($N::text[])` over patterns `dir/token` + `dir/token-%`, cap of 10 ordered by `connection_count DESC, slug ASC`. Pinned by `test/entity-resolve.test.ts` (explicit, unique, ambiguous-person, and shared-token-company cases) plus `test/phantom-redirect.test.ts` (resolvePhantomCanonical 3 cases + findPrefixCandidates 6 cases incl. multi-dir ambiguity and the `people/aliceberg`-doesn't-match-`alice` false-positive guard).-- `src/core/entity-identity.ts` + `src/core/ops/entity-identity.ts` — cross-source entity identity (cross-source federation). THE IDENTITY KEY IS `(source_id, slug)`: the same real-world entity routinely exists as a different page per mounted source, and nothing else in gbrain asserts "these pages are the same entity". The `entity_identities` table (migration v137) records that assertion explicitly — member pages grouped under an opaque `entity_id` handle (`validateEntityId`: slug-flavored, lowercase, max 128 chars), one optional canonical member per group, a page belongs to at most one identity (`UNIQUE (source_id, page_id)`; re-linking MOVES it). Posture is MANUAL-ONLY by design: rows come exclusively from the `entity_identity_link` op — no auto-matching or name-similarity heuristics, because a wrong identity merge silently corrupts retrieval. Three ops: `entity_identity_link` / `entity_identity_unlink` (write, localOnly — merges change what retrieval unions across sources, too sharp for a remote surface) + `entity_identity_list` (read; restricts MEMBER visibility to a federated grant or remote scalar scope, while a trusted local caller sees the full cross-source group — cross-source IS the feature). Retrieval union is OFF by default behind the `entity_identity.union` config key; when on, get_links/get_backlinks merge edges from identity co-members (dedup'd), never widening past the caller's source grant. Same SQL text on both engines (parity by construction); pinned by the entity-identity test + the DATABASE_URL-gated engine-parity suite. Topology context: `docs/architecture/brains-and-sources.md`.+- `src/core/entity-identity.ts` + `src/core/ops/entity-identity.ts` — cross-source entity identity (cross-source federation). THE IDENTITY KEY IS `(source_id, slug)`: the same real-world entity routinely exists as a different page per mounted source, and nothing else in gbrain asserts "these pages are the same entity". The `entity_identities` table (migration v137) records that assertion explicitly — member pages grouped under an opaque `entity_id` handle (`validateEntityId`: slug-flavored, lowercase, max 128 chars), one optional canonical member per group, a page belongs to at most one identity (`UNIQUE (source_id, page_id)`; re-linking MOVES it). A link's canonical demotion and upsert run in one transaction, and re-linking with `canonical` omitted keeps the member's canonical flag within the same group (`canonical: false` demotes explicitly). Posture is MANUAL-ONLY by design: rows come exclusively from the `entity_identity_link` op — no auto-matching or name-similarity heuristics, because a wrong identity merge silently corrupts retrieval. Three ops: `entity_identity_link` / `entity_identity_unlink` (write, localOnly — merges change what retrieval unions across sources, too sharp for a remote surface) + `entity_identity_list` (read; restricts MEMBER visibility to a federated grant or remote scalar scope, while a trusted local caller sees the full cross-source group — cross-source IS the feature). Retrieval union is OFF by default behind the `entity_identity.union` config key; when on, get_links/get_backlinks merge edges from identity co-members (dedup'd), never widening past the caller's source grant. Same SQL text on both engines (parity by construction); pinned by the entity-identity test + the DATABASE_URL-gated engine-parity suite. Topology context: `docs/architecture/brains-and-sources.md`.- `src/core/extract-frontmatter.ts` — `resolveIncludeFrontmatter(engine, explicit?)`: the single answer for "extract `related:`/`sources:` frontmatter link edges too?" (`autopilot.incremental_extract_include_frontmatter`; explicit flag > file plane > DB plane via `isConfigTruthy` > false, fail-closed on an unreadable config table). Resolved INSIDE the shared helpers — `extractLinksForSlugs` and `extractStaleFromDB` default `opts.includeFrontmatter` through it, the same in-helper pattern as `isGlobalBasenameEnabled` — so sync's inline extract, the GitHub/Google source inline extracts, the `extract_stale` minion, `gbrain maintain`, the cycle's extract phase and `gbrain extract --stale` (flag absent → configured knob) all agree; no caller passes a literal `false`. Pinned by `test/extract-include-frontmatter-config.serial.test.ts` (resolver precedence + a source-text guard on the call sites + a PGLite link-row test through `extractLinksForSlugs`).@@ -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`; 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/facts-fence.ts` — the `## Facts` fence primitives: parse (`parseFactsFence`; a confidence cell outside 0..1 or not a plain number is `FACTS_TABLE_MALFORMED`, a `claim_value` cell parses strictly (plain/scientific numbers, `1,234,567` separators, a leading currency symbol, a k/M/B suffix that scales; anything else such as `1,5` or `0.9abc` is `FACTS_TABLE_MALFORMED`), `formatFenceDate` writes UTC-midnight dates as `YYYY-MM-DD` and any other instant as a UTC timestamp so TTLs and write-time `valid_from` round-trip, 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/docs/architecture/key-files/hindsight.md b/docs/architecture/key-files/hindsight.mdindex 224849d6fd..af47b68e2e 100644--- a/docs/architecture/key-files/hindsight.md+++ b/docs/architecture/key-files/hindsight.md@@ -22,7 +22,7 @@ round-trip suite (CHECK admits unresolvable+NULL, still rejects partial+true andunresolvable+true|false, pre-v80 NULL/NULL rows survive).- `src/core/cycle/base-phase.ts` — abstract `BaseCyclePhase` class. Enforces `sourceScopeOpts(ctx)` threading at the type level; rules out the source-isolation leak class structurally for every new phase. Inherits source-scope, budget meter, error envelope, progress reporter. propose_takes / grade_takes / calibration_profile all extend it. `run()` honors dry-run for every subclass at once: when `opts.dryRun` or `ctx.dryRun === true`, it returns `status: 'skipped'` / `reason: 'no_dry_run_support'` before `process()` (no LLM calls, no take_proposals / take_grade_cache / calibration_profiles writes) — the same skip shape extract and resolve_symbol_edges use; runCycle threads `dryRun` into all three call sites. The ONE home of `CYCLE_DEADLINE_RESERVE_MS` (60s carved out of the enclosing job's remaining wall-clock — wait-poll + worker force-evict grace + cleanup headroom; patterns.ts re-exports it) and of `BasePhaseOpts.deadlineAtMs` (the enclosing minion job's absolute deadline, threaded via runCycle; null/unset for direct `gbrain dream` callers — phases then fall back to their derived defaults).-- `src/core/cycle/propose-takes.ts` — LLM scans markdown prose, proposes gradeable claims to the `take_proposals` queue. Candidate discovery excludes `extract_receipt` pages before the LLM call so the phase never re-ingests its own operational receipts; nullable legacy page types remain eligible. Idempotency cache on `(source_id, page_slug, content_hash, prompt_version)` composite unique index. Fence-dedup: existing canonical takes passed to the extractor as context. Ships a stub prompt; tuned prompt arrives via the synthetic corpus build. Per-page extractor failures log a warning and continue, but a whole-run condition (per `classifyGlobalLlmError` in `src/core/ai/errors.ts`) breaks the page loop with a single combined warning line, sets `aborted_global_error`, and records a halt in the rollup — auth/billing on the first hit, bare rate_limit only after `RATE_LIMIT_HALT_STREAK` (3) consecutive hits (a successful call resets the streak). Status: `fail` when the halt happened with ZERO successful extractor calls (the whole LLM lane is down), otherwise any warnings fold into `warn` + ` (N warning(s))` summary suffix, so swallowed failures can't read as a clean `ok`. `llm_calls_succeeded`/`llm_calls_failed`/`halted` land in details. The phase wall-clock deadline is DERIVED, never a literal (a literal equal to the autopilot-cycle handler anchor, with non-co-started clocks, would make the clean `deadline_hit` partial-completion path structurally unreachable): explicit `opts.deadlineMs` wins (test seam), else `resolveProposeTakesDeadlineMs(deadlineAtMs, now)` = `PHASE_DEADLINE_FRACTION_OF_JOB` (0.8, headroom for grade_takes + calibration_profile which run after it with no deadline of their own) × (remaining job budget − `CYCLE_DEADLINE_RESERVE_MS`), clamped to the fallback (0.8 × the `autopilot-cycle` entry in `HANDLER_DEFAULT_TIMEOUT_MS` — a missing anchor throws at module LOAD, failing the whole cycle visibly). A fractioned value under `MIN_PROPOSE_TAKES_BUDGET_MS` (2 min) resolves to null and the phase returns an honest `skipped` with `reason: 'insufficient_cycle_budget'` (after the cheap provider probe, before any rollup/DB write — records neither a halt nor a completed round; next cycle retries with a fresh budget). Pinned by `test/propose-takes.test.ts` + `test/propose-takes-per-claim.test.ts` + `test/cycle-phase-deadline-drift.test.ts`. The kind vocabulary is `TAKE_KIND_VALUES` imported from `src/core/takes-fence.ts` (the fence enum — no hand-copied set); an unknown kind maps through the legacy-kind table, else `take`.+- `src/core/cycle/propose-takes.ts` — LLM scans markdown prose, proposes gradeable claims to the `take_proposals` queue. Candidate discovery excludes `extract_receipt` pages before the LLM call so the phase never re-ingests its own operational receipts; nullable legacy page types remain eligible. Idempotency cache on `(source_id, page_slug, content_hash, prompt_version)` composite unique index. Fence-dedup: existing canonical takes passed to the extractor as context. Opt-in `dream.propose_takes.attribution_rules=true` adds `EXTRACT_TAKES_ATTRIBUTION_RULES` (withdrawn claims, assistant-authored judgments not attributed to the user) under prompt version suffix `+attribution5425`; off by default because it measured lower cat15 recall. Ships a stub prompt; tuned prompt arrives via the synthetic corpus build. Per-page extractor failures log a warning and continue, but a whole-run condition (per `classifyGlobalLlmError` in `src/core/ai/errors.ts`) breaks the page loop with a single combined warning line, sets `aborted_global_error`, and records a halt in the rollup — auth/billing on the first hit, bare rate_limit only after `RATE_LIMIT_HALT_STREAK` (3) consecutive hits (a successful call resets the streak). Status: `fail` when the halt happened with ZERO successful extractor calls (the whole LLM lane is down), otherwise any warnings fold into `warn` + ` (N warning(s))` summary suffix, so swallowed failures can't read as a clean `ok`. `llm_calls_succeeded`/`llm_calls_failed`/`halted` land in details. The phase wall-clock deadline is DERIVED, never a literal (a literal equal to the autopilot-cycle handler anchor, with non-co-started clocks, would make the clean `deadline_hit` partial-completion path structurally unreachable): explicit `opts.deadlineMs` wins (test seam), else `resolveProposeTakesDeadlineMs(deadlineAtMs, now)` = `PHASE_DEADLINE_FRACTION_OF_JOB` (0.8, headroom for grade_takes + calibration_profile which run after it with no deadline of their own) × (remaining job budget − `CYCLE_DEADLINE_RESERVE_MS`), clamped to the fallback (0.8 × the `autopilot-cycle` entry in `HANDLER_DEFAULT_TIMEOUT_MS` — a missing anchor throws at module LOAD, failing the whole cycle visibly). A fractioned value under `MIN_PROPOSE_TAKES_BUDGET_MS` (2 min) resolves to null and the phase returns an honest `skipped` with `reason: 'insufficient_cycle_budget'` (after the cheap provider probe, before any rollup/DB write — records neither a halt nor a completed round; next cycle retries with a fresh budget). Pinned by `test/propose-takes.test.ts` + `test/propose-takes-per-claim.test.ts` + `test/cycle-phase-deadline-drift.test.ts`. The kind vocabulary is `TAKE_KIND_VALUES` imported from `src/core/takes-fence.ts` (the fence enum — no hand-copied set); an unknown kind maps through the legacy-kind table, else `take`.- `src/core/cycle/grade-takes.ts` — walks unresolved takes older than 6 months, retrieves evidence, asks judge model, caches verdict. Auto-resolve DISABLED by default. Conservative thresholds: >=0.95 single OR >=0.85 ensemble 3/3 unanimous. `aggregateEnsemble` reuses the cross-modal substrate; fires on the borderline 0.6-0.95 band. Writes to `take_grade_cache`. Same global-error posture as propose-takes: a judge failure that classifies as a whole-run condition breaks the take loop with `aborted_global_error` (auth/billing first hit; rate_limit after 3 consecutive takes; `fail` status when zero judge calls succeeded, else `warn` + warning count; `judge_calls_succeeded`/`judge_calls_failed`/`halted` in details). Rejected ensemble judges are classified the same way — `Promise.allSettled` never flattens a revoked key or exhausted spend limit into a silent null verdict. Per-take auto-apply failures stay per-take.- `src/core/cycle/calibration-profile.ts` — aggregates resolved takes into 2-4 narrative pattern statements + active bias tags. Voice-gated via `gateVoice()`. Cold-brain skip when <5 resolved. Writes to `calibration_profiles` with audit columns (`voice_gate_passed`, `voice_gate_attempts`, `grade_completion`).- `src/core/calibration/voice-gate.ts` — single `gateVoice()` function, mode parameter (`pattern_statement` | `nudge` | `forecast_blurb` | `dashboard_caption` | `morning_pulse`). 2 regens then template fallback from `src/core/calibration/templates.ts`. Haiku judge with mode-specific rubrics; all rubrics structurally forbid clinical/preachy voice.diff --git a/docs/architecture/key-files/providers.md b/docs/architecture/key-files/providers.mdindex f3ee9125ab..a32130920f 100644--- a/docs/architecture/key-files/providers.md+++ b/docs/architecture/key-files/providers.md@@ -24,6 +24,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/embed-skip.ts` — 5-site shared predicate for the soft-block embed-skip filter. Exports `shouldSkipEmbedding(frontmatter): boolean` (JS predicate for callers holding the page in memory), `EMBED_SKIP_SQL_FRAGMENT` (parameterized SQL clause shared by Postgres + PGLite via `executeRaw`), and `buildEmbedSkipMarker(reason: string)` (writes `frontmatter.embed_skip = {at: ISO_TIMESTAMP, reason}` so the JSONB shape stays uniform). The 5 sites: `embed.ts --stale`, `embed.ts --all`, the `embed-stale` Minion helper, plus both engines' `listStaleChunks` + `countStaleChunks`. Single source of truth so the filter cannot drift. Pinned by `test/embed-skip.test.ts` (cross-site invariant + JSONB shape).- `src/core/embed-stale.ts` — source-wide stale embedding and explicit-page completion keep vector installation, complete-provenance signature checks and title-tier demotion in one page-guarded transaction. The three `src/commands/embed.ts` paths use the same transaction boundary; providers run before it. Standalone/background projection recovery preserves NULL-signature grandfathering and existing stale eligibility; the job's deadline, abort signal and source lease fence recovery, invalidation and publication. Oversized-chunk healing checks ownership and stop conditions before and after its transaction, rolling back prepared changes on loss. The restamp always uses the captured page metadata, so a later same-revision contextual rebuild cannot retain its vectors while an older completion overwrites its mode or corpus generation. `persistence/effects.ts` also retains this atomic completion boundary. `test/embedding-completion-atomic.serial.test.ts` exercises all five completion paths; `test/e2e/migration-wave-healing-fence.test.ts` pins healing rollback on both engines.+- `src/core/embed-stale-images.ts` — `gbrain embed --stale --images [--source <id>] [--dry-run] [--json]` (requires `GBRAIN_EMBEDDING_MULTIMODAL=true`): selects live image pages whose index `importImageFile`'s hash-skip would call incomplete (unsealed or stale projection, no `embedding_image` chunk, or no OCR text/`ocr_status: done` while `GBRAIN_EMBEDDING_IMAGE_OCR=true`), resolves each file from the source's `local_path` (the `default` source falls back to `sync.repo_path`; a subpath-scoped `source_path` resolves against the checkout's git root) and hands it back to `importImageFile`, so OCR budget, protected-OCR refusal and the rebuild stay in the importer. Reports candidates, rebuilt, unchanged, missing source files and failures (`failures > 0` exits non-zero). Pinned by `test/embed-stale-images.test.ts`.- `src/core/embed-stall.ts` — progress-keyed stall watchdog for embed drains (mirror of sync's stall watchdog; bounds embed drains that hang without a pinned root cause). Two clocks, one trigger: LIVENESS ticks via `noteEmbedApiResponse()` on EVERY settled embed API attempt — success, error, or retry (hooked in `embed-retry.ts:embedBatchWithBackoff`; diagnostic only, distinguishes "fully wedged" from "live but failing" in the abort message, scoped to the armed run); the TRIGGER is no SUCCESSFUL forward progress (`readProgress()`, wired to chunks embedded) for `GBRAIN_EMBED_STALL_ABORT_SECONDS` (env-only knob; default 900 via `DEFAULT_EMBED_STALL_ABORT_SEC`, `<= 0` disables, garbage falls back to default) — a retry storm that never lands a chunk trips it BY DESIGN. A stall produces an ERROR RESULT (`reason: 'stall_timeout'`), never a `process.exit`: only the CLI wrapper (`src/commands/embed.ts:runEmbed`) maps it to a non-zero exit, and minion handlers and the cycle's embed phase (`cycle.ts:runPhaseEmbed`) convert it to a failure via `assertEmbedNotStalled`. The abort path runs an idempotent, deadline-bounded cleanup (`EMBED_STALL_CLEANUP_DEADLINE_MS`) that releases only the run's self-acquired single-flight locks and banks partial progress, so the next run resumes cleanly. The check interval is deliberately NOT unref'd — for non-single-flight callers it can be the only handle keeping a lost-promise hang loud; `stop()` clears it on every normal path. Pinned by `test/embed-stall.test.ts`.diff --git a/docs/architecture/key-files/runtime.md b/docs/architecture/key-files/runtime.mdindex bee23620ca..9e274b3918 100644--- a/docs/architecture/key-files/runtime.md+++ b/docs/architecture/key-files/runtime.md@@ -17,7 +17,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/console-prefix.ts` — `AsyncLocalStorage<string>`-backed per-source line-prefix helper. Exports `withSourcePrefix(id, fn)` (runs `fn` with `id` as active prefix; nested wraps replace then restore), `getSourcePrefix()` (read-only accessor; test seam), `slog(...)` / `serr(...)` (prefix-aware `console.log`/`console.error`), and `withHumanLogsToStderr(fn)` (runs `fn` with every `slog` line, prefixed or not, routed to stderr; `runSync` wraps its body in it under `--json` so stdout carries only the ONE JSON envelope (the cost-gate status object rides inside it as `cost_gate`, #4684) while `serr` and direct `console.log(JSON.stringify(..))` sites are unaffected; scoped via its own `AsyncLocalStorage`, never a process-wide console rebind). Embedded-newline-safe: a multi-line string under prefix `[foo]` emits `[foo] line1\n[foo] line2`. Outside a wrap, `slog`/`serr` fall through to bare `console.log`/`console.error` so single-source callers see identical output (back-compat invariant). Use `src.id` (slug-validated by `sources add`) NOT `src.name` (free-form) to defeat log-injection through newline/control-character names. Coverage: `src/commands/sync.ts` performSync + callees, `src/commands/embed.ts` runEmbedCore + helpers, `src/core/progress.ts` emitHumanLine, `src/commands/import.ts` runImport's human-only lines (`info()` + the end-of-run `Import complete` summary — so the first-sync full import under `sync --json` lands on stderr too).-- `src/core/mcp-client.ts` — the thin-client transport (trust boundary). `callRemoteTool(config, toolName, args, opts)` with `CallRemoteToolOptions {timeoutMs, signal}`; `buildAbortController` composes an external signal with the timeout. All transport errors normalize to `RemoteMcpError` via the `toRemoteMcpError` funnel: stable `RemoteMcpErrorReason` union, `RemoteMcpErrorDetail.kind` (`'timeout' | 'aborted' | 'unreachable'`) sub-tag, `RemoteMcpErrorDetail.code` carrying server-supplied error codes (e.g. `missing_scope`). `extractToolErrorCode` parses the operation `{error: string, message}` shape as well as legacy envelopes. Mutation arguments retain one request UUID before the first transport attempt, across OAuth refresh and caller retries. Mutation errors retain that UUID and distinguish unknown delivery from requests never submitted; the shared CLI renderer emits same-ID retry guidance without fabricating a receipt. Received pending or terminal error receipts and frozen verb metadata survive deadlines during client cleanup, including the refreshed attempt. Only the locked SDK’s typed `StreamableHTTPError` with numeric code 401 triggers one refresh and reconstructed client; application error text never causes authentication replay. The outer abort signal reaches discovery, minting, initialization, fetch and tool calls, with per-request limits retained and clients closed after failed initialization or abort. `unpackToolResult<T>(res)` parses tool-call JSON content. `_clearMcpClientTokenCache()` test escape. The CLI routing seam that consumes this lives in `src/cli.ts` (`runThinClientRouted`); see `docs/architecture/thin-client.md`.+- `src/core/mcp-client.ts` — the thin-client transport (trust boundary). `callRemoteTool(config, toolName, args, opts)` with `CallRemoteToolOptions {timeoutMs, signal}`; `buildAbortController` composes an external signal with the timeout, and `buildMcpRequestOptions` forwards `timeoutMs` as the SDK request deadline (otherwise its own 60s default wins); an SDK `RequestTimeout` classifies as `network`/`timeout`, never unreachable. All transport errors normalize to `RemoteMcpError` via the `toRemoteMcpError` funnel: stable `RemoteMcpErrorReason` union, `RemoteMcpErrorDetail.kind` (`'timeout' | 'aborted' | 'unreachable'`) sub-tag, `RemoteMcpErrorDetail.code` carrying server-supplied error codes (e.g. `missing_scope`). `extractToolErrorCode` parses the operation `{error: string, message}` shape as well as legacy envelopes. Mutation arguments retain one request UUID before the first transport attempt, across OAuth refresh and caller retries. Mutation errors retain that UUID and distinguish unknown delivery from requests never submitted; the shared CLI renderer emits same-ID retry guidance without fabricating a receipt. Received pending or terminal error receipts and frozen verb metadata survive deadlines during client cleanup, including the refreshed attempt. Only the locked SDK’s typed `StreamableHTTPError` with numeric code 401 triggers one refresh and reconstructed client; application error text never causes authentication replay. The outer abort signal reaches discovery, minting, initialization, fetch and tool calls, with per-request limits retained and clients closed after failed initialization or abort. `unpackToolResult<T>(res)` parses tool-call JSON content. `_clearMcpClientTokenCache()` test escape. The CLI routing seam that consumes this lives in `src/cli.ts` (`runThinClientRouted`); see `docs/architecture/thin-client.md`.- `src/core/op-checkpoint.ts` — DB-backed checkpoint primitive for long-running ops. Migration v67 introduces `op_checkpoints (op TEXT, fingerprint TEXT, completed_keys JSONB, updated_at TIMESTAMPTZ, PK(op, fingerprint))`. Per-op fingerprint helpers (`embedFingerprint`, `extractFingerprint`, `reindexFingerprint`, `integrityFingerprint`, `purgeFingerprint`) compute `sha8(canonical-JSON(relevant-params))` so re-running with the same params resumes from `completed_keys` and re-running with different params (e.g. `--limit 100` vs `--limit 200`) starts fresh. Cross-worker safe on Postgres (DB row, no file-lock race); PGLite degrades gracefully. The 7-day TTL GC runs in the cycle's `purge` phase. All writes (`recordCompleted`, `clearOpCheckpoint`) route through `engine.executeRawDirect` + `withRetry(BULK_RETRY_OPTS)` so they survive Supavisor pool exhaustion, and `recordCompleted` returns `boolean` (banked vs failed-after-retries) — the 9 non-sync consumers keep its REPLACE-into-`completed_keys` semantics. Resumable sync uses the additive `appendCompleted(key, deltaKeys)` / `appendCompletedOnce` (the latter no-retry for the SIGTERM path) which INSERT a delta into the `op_checkpoint_paths` child table (migration v115: `(op, fingerprint, path)` PK, FK to `op_checkpoints` ON DELETE CASCADE) via a single writable-CTE `unnest($3::text[])` write — O(delta), never an O(N²) full-set rewrite. `loadOpCheckpoint` returns the `UNION ALL` of legacy `completed_keys` + child-table paths (deduped in JS), so an in-flight upgrade loses nothing. The legacy arm is gated on `jsonb_typeof(completed_keys) = 'array'` so a non-array (scalar) parent row can't make `jsonb_array_elements_text` throw "cannot extract elements from a scalar" and take down the whole union (which would discard the valid child rows and lose all banked progress for the key); a third union arm flags the corruption so the loader logs it once and keeps the child rows. Migration v119 adds the `op_checkpoints_completed_keys_array` CHECK (`jsonb_typeof(completed_keys) = 'array'`) — a DB-enforced, always-on guard that makes the scalar-corruption class structurally impossible going forward; the migration repairs any pre-existing scalar to `'[]'` under `LOCK TABLE ... IN SHARE ROW EXCLUSIVE MODE` and `src/core/schema-embedded.generated.ts` + `src/core/pglite-schema.ts` ship the same CHECK on fresh installs (a loader hit implies schema drift, a disabled constraint, or an out-of-band writer). `recordCompleted` binds its array through `$3::text::jsonb` (NOT a bare `$3::jsonb`) so postgres.js `.unsafe()` doesn't double-encode `JSON.stringify(sorted)` into the scalar string that CHECK rejects (PGLite parses it silently, so only real Postgres surfaces the bug). A DATABASE_URL-gated `test/e2e/op-checkpoint-jsonb-parity.test.ts` (its own CI job) asserts the array shape on real Postgres. `syncFingerprint({sourceId, lastCommit})` keys the sync rows. Pinned by `test/op-checkpoint.test.ts` (incl. delta-append, union read, cascade clear, durable-write boolean, and the scalar-parent guard). `import-checkpoint.ts` stays a separate file-backed checkpoint — both systems coexist without conflict (unifying them would mean async-propagating the four sync call sites in `src/commands/import.ts`; deferred). TTL cleanup preserves unresolved managed cursors, their manifests and failure observations; a completed full cursor does not hide a different failed incremental cursor. Unfinished `managed-atoms` checkpoints survive ordinary seven-day GC so accepted output/retry state is not silently forgotten.diff --git a/docs/eval-bench.md b/docs/eval-bench.mdindex 9fa34e822c..0abafd56a5 100644--- a/docs/eval-bench.md+++ b/docs/eval-bench.md@@ -767,8 +767,12 @@ the per-miss rows, `--all` diagnoses every scored question. It is not a### Architecture (read this if you're touching the harness)-- One in-memory PGLite per benchmark run via `createBenchmarkBrain` +- `withBenchmarkBrain`. Your `~/.gbrain` is never opened.+- In-memory PGLite brains via `createBenchmarkBrain`. Your `~/.gbrain` is+ never opened. `TRUNCATE` never returns PGLite's WASM memory, which grows+ with each question's vectors, so a harness-owned brain is replaced with a+ fresh, re-configured one every `LME_BRAIN_RECYCLE_EVERY` (40) questions+ (`brainRecycler` in `src/eval/longmemeval/harness.ts`); without it a long+ single-process run stalls at 100% CPU around question 90-120.- Between questions: `TRUNCATE` over runtime-enumerated `pg_tables`, NOT ahardcoded list — schema migrations don't silently leak data acrossquestions. Infrastructure tables (`sources`, `config`,diff --git a/docs/guides/concurrent-writes.md b/docs/guides/concurrent-writes.mdindex 1eef79776f..ecabde61bd 100644--- a/docs/guides/concurrent-writes.md+++ b/docs/guides/concurrent-writes.md@@ -318,17 +318,46 @@ Take an engine-appropriate database backup first, not a Markdown export. Preferforward recovery: restoring an older database can discard committed withdrawalintent or intervening edits and can make withdrawn content active again.-Discovery has fixed safety limits: 12,000 source pages, 40,000 chunks, 40,000 fact-rows, 64 MiB of combined text and 256 affected pages in a target manifest no larger-than 1 MiB. It reads bodies in batches of 128 and refuses when its checked scan-budget exceeds 10 seconds; an individual matching batch also has a 16,384-row/8 MiB input limit.-Each body also has a 16,384-marker parsing limit, enforced during a linear scan.-These are capacity limits, not a latency guarantee or permission to spend on-providers. `withdrawal_capacity` or `withdrawal_provenance` refuses the attempt-before ledger, expiry, revision or chunk changes. Matching malformed fences need-canonical repair; capacity refusals need host-operator investigation and a-separately reviewed repair, not an unchanged retry, source deletion or a forced-cursor reset. There is no override that trades away complete discovery.+Discovery is keyed on the claim, its subject and its fingerprint, so its cost+and limits follow the pages that carry the claim, not the size of the source.+Every fence row or chunk whose fingerprint matches contains each of the claim's+normalized tokens in its lowercased text, because normalization only turns+punctuation and whitespace into token boundaries. The database shortlists+candidate pages and chunks that contain every token, and discovery streams the+shortlist in batches of 128 and verifies each row exactly. A subject-scoped withdrawal reads+only that entity's page plus the provenance of that entity's matching facts;+a subjectless (`*`) withdrawal shortlists across the source. Recorded+provenance uses the fact fingerprint index.++The limits are 256 affected pages in a target manifest no larger than 1 MiB, a+10-second checked scan budget, a 16,384-row/8 MiB input limit per matching+batch, and a 16,384-marker parsing limit per body, enforced during a linear+scan. These are capacity limits, not a latency guarantee or permission to spend+on providers. `withdrawal_capacity` or `withdrawal_provenance` refuses the+attempt before ledger, expiry, revision or chunk changes. Matching malformed+fences need canonical repair.++When the claim itself is carried by more than 256 pages, the refusal names the+matched count and up to 20 matched pages. Reduce the matched set, then retry:+forget the entity-scoped copies of the fact first (each withdrawal changes only+its own entity's pages), or edit the claim out of pages that should not carry+it. Time-budget refusals on a common claim need host-operator investigation,+not an unchanged retry, source deletion or a forced cursor reset. There is no+override that trades away complete discovery.++Queued legacy `source_scan` effects upgrade through the same discovery, keyed+on the request's own forgotten fact; only when that fact row is gone does the+upgrade fall back to the source's whole withdrawal ledger (at most 256 claims).++Fingerprints fold case, whitespace and punctuation (migration v174), so a+punctuation or casing variant re-extracted from unchanged prose stays+withdrawn. Symbols that carry meaning in names are kept: `+`, `#` and+in-word dots, so "C++", "C#", ".NET" and "Node.js" stay distinct from+"C", "NET" and "Nodejs"; a dot folds only when a space, another dot or the+end of the claim follows it. Rows recorded before v174 keep their exact fingerprint and keep+matching; v174 adds a folded row wherever a fact row still holds the claim text+and expires active facts that became matching. A paraphrase with different+words is a different claim.Already queued source-wide effects are converted using the same bounded exactdiscovery and retain their individual progress cursors. An over-capacity ordiff --git a/docs/guides/cron-schedule.md b/docs/guides/cron-schedule.mdindex ec7630e18d..090b9e05f2 100644--- a/docs/guides/cron-schedule.md+++ b/docs/guides/cron-schedule.md@@ -245,8 +245,11 @@ Three more fields answer "what did that cost and did it land":- `quote_verify` — what the post-write claim check touched: quotes checkedand repaired, sentences quarantined (with counts per reason:`quote_not_in_source`, `quote_crosses_speakers`, `speaker_mismatch`,- `number_not_in_source`), pre-existing pages checked by diff, and unbalanced- paragraphs.+ `number_not_in_source`, `decision_misattributed`), pre-existing pages+ checked by diff, and unbalanced paragraphs. `decision_misattributed` is a+ sentence saying a speaker decided, agreed or will do something whose+ numbers or dates only another speaker stated and the named speaker never+ explicitly accepted.Per-call spend also lands in the `chat_usage_log` ledger with a phase tag:the orchestrator's own calls under `phase:synthesize`, each drained childdiff --git a/docs/guides/search-modes.md b/docs/guides/search-modes.mdindex 4ffba1d775..94f987943d 100644--- a/docs/guides/search-modes.md+++ b/docs/guides/search-modes.md@@ -82,15 +82,21 @@ Seven of the knobs deserve a sentence:replayed at every budget): strict `recall_all@5` climbs monotonically asthe budget shrinks — 255/470 legacy → 394/470 at 0.25 — but even 0.25trails plain hybrid (439/470) by 43 questions on the held-out decision set,- so the bundles keep `null` and the knob is an operator lever; if you keep- expansion on, `0.25` recovers most of the loss. **Say to your agent:**+ so the bundles keep `null` and the knob is an operator lever. That receipt+ predates page-grain fusion and the relaxed-keyword demotion: on the current+ ranking (halfA430, 215 questions, frozen variants) legacy expansion scores+ 205/215, budget `1.0` 203/215, `0.25` 202/215 and no expansion 202/215, so+ capping the variants no longer helps. **Say to your agent:***"Cap how much query expansion can outvote my original query"* (no skill backs this; your agentruns `gbrain config set search.expansion_variant_budget <b>`, and`gbrain config set search.expansion_variant_budget legacy` restores thedefault).- **`relationalRetrieval`** adds a graph-walk recall arm for relational- questions ("who invested in X", "what connects A and B"); it's a pure- no-op for non-relational queries. The `query` op's `relational` flag+ questions ("who invested in X", "what connects A and B"). Common rewordings+ count too: "X's investors", "people who funded X", "who is the founder of+ X", "which companies has X backed", "relationship between A and B", "who+ can introduce me to X". It's a pure no-op for non-relational queries, and+ it only fires when the named entity resolves to a page in your brain. The `query` op's `relational` flagforces it on/off per call.- **`relational_rerank_pin`** (config key `search.relational_rerank_pin`;3 in every bundle) keeps those graph-walk answers from being buried by thediff --git a/docs/operations/spend-controls.md b/docs/operations/spend-controls.mdindex 33c1fb87f0..95593d4599 100644--- a/docs/operations/spend-controls.md+++ b/docs/operations/spend-controls.md@@ -63,6 +63,14 @@ The USD-limit knobs accept `off`, `unlimited`, or `none` (case-insensitive) to m| `enrich` / `onboard --auto` | `--max-usd` (per-call) | — | refuse without a cap (non-TTY) | `--max-usd off` | runs uncapped (still ledgered) || Image-OCR per-run ceiling | `embedding_image_ocr_max_images` / `embedding_image_ocr_max_usd` | `200` images / `$1.00` (estimated) | skips OCR over-cap (import continues; skips counted in `ocr_skipped_budget`, surfaced by doctor `ocr_health`) | `0` disables that cap | **not** bypassed (per-run cap, not a tracker gate) || Dream `extract_atoms` phase budget | `cycle.extract_atoms.budget_usd` | `0.30` | caps the phase's budget tracker | — | **not** consulted (phase budget enforces regardless) |+| Dream `synthesize` per-run budget | `dream.synthesize.budget_usd` | `5` | defers the transcript and the rest of the run before submission (estimate: prompt size + child output cap, x `max_turns` in agentic mode) | `unlimited` (`0` = submit nothing) | **not** consulted |+| Dream `synthesize` daily submission cap | `dream.synthesize.max_submissions_per_source_per_day` | `0` (off) | skips whole files; a failed count query submits nothing that run | `0` | **not** consulted |+| Dream `BudgetMeter` phases (auto_think, drift, propose/grade takes, calibration) | `dream.auto_think.budget`, `dream.drift.budget`, `cycle.<phase>.budget_usd` | per phase | refuses the next submit past the cap | `unlimited` (`0` = spend nothing) | **not** consulted |++Dream `BudgetMeter` phases meter a model missing from the pricing table at a+Sonnet-tier fallback rate instead of letting it run uncapped; local model+servers (Ollama, LM Studio, llama-server) count as $0. Set+`dream.budget.allow_unpriced=true` to let unpriced models bypass the meter.The `extract_atoms` cap is enforced only for models in the pricing maps. A modelthe tracker cannot price — e.g. a local Ollama model selected viadiff --git a/evals/title-mention/corpus/events/annual-holiday-party-budget.md b/evals/title-mention/corpus/events/annual-holiday-party-budget.mdnew file mode 100644index 0000000000..120e9852a8--- /dev/null+++ b/evals/title-mention/corpus/events/annual-holiday-party-budget.md@@ -0,0 +1,6 @@+---+title: "Annual Holiday Party Budget"+type: note+---++This document sets out the approved spending plan for the December holiday party, owned by Erin Mockwell. The total budget is $12,000 for roughly 90 guests. Venue rental at the Riverside Ballroom accounts for $4,500. Catering and beverages are $4,200, live music is $900, decorations are $600, employee gift cards are $1,200, and a contingency reserve is $600. The plan assumes a per-head catering cost of about $47, and any headcount above 95 requires a budget amendment. Invoices must be submitted to finance within ten days of the event. Last year the party ran about eight percent over plan because of late additions, so the contingency has been raised. Erin Mockwell will send a monthly spending summary to the events committee starting in September. Vendors are being chosen from quotes gathered in June.diff --git a/evals/title-mention/corpus/events/harbor-street-venue-contract.md b/evals/title-mention/corpus/events/harbor-street-venue-contract.mdnew file mode 100644index 0000000000..5a7f58971f--- /dev/null+++ b/evals/title-mention/corpus/events/harbor-street-venue-contract.md@@ -0,0 +1,6 @@+---+title: "Harbor Street Venue Contract"+type: note+---++This agreement covers the rental of the Harbor Street Conference Hall for the spring offsite on 14 and 15 May. It was signed by Bob Sample for Acme Example Co. The hall is reserved for up to 80 guests at a total fee of $18,400. A 30 percent deposit is due by 1 April, with the balance payable seven days before the event. Audio and video equipment, tables, and on-site parking for 20 vehicles are included. Catering is not included and must be arranged separately. Cancellation requires 21 days written notice for a full refund of the deposit; later cancellations forfeit it. Setup access begins at 7:00 on the first day, and the hall must be cleared by 17:00 on the second day. Any damage is billed to Acme Example Co. Questions about terms go to the venue manager, Grace Placeholder.diff --git a/evals/title-mention/corpus/events/lakeview-lodge-venue-contract.md b/evals/title-mention/corpus/events/lakeview-lodge-venue-contract.mdnew file mode 100644index 0000000000..7daf6f99e5--- /dev/null+++ b/evals/title-mention/corpus/events/lakeview-lodge-venue-contract.md@@ -0,0 +1,6 @@+---+title: "Lakeview Lodge Venue Contract"+type: note+---++This agreement covers a three-day, two-night stay at Lakeview Lodge for the autumn leadership retreat, 9 to 11 October. It was signed by Carol Placeholder for Acme Example Co. The lodge is booked for 45 guests at a total of $22,750, which includes lodging, all meals, and use of the lakeside meeting room. Audio and video equipment is not included and must be rented separately. A 50 percent deposit is due by 1 August, with the balance due 30 days before arrival. Cancellation needs 45 days written notice for a deposit refund. Parking is free but limited to 15 vehicles, so carpooling is expected. This was the alternative considered for the spring gathering but was judged too costly and too remote for a group of eighty. Contact the lodge coordinator, Henry Sample, with rooming questions.diff --git a/evals/title-mention/corpus/events/meeting-notes.md b/evals/title-mention/corpus/events/meeting-notes.mdnew file mode 100644index 0000000000..ac92376f5a--- /dev/null+++ b/evals/title-mention/corpus/events/meeting-notes.md@@ -0,0 +1,6 @@+---+title: "Meeting Notes"+type: note+---++Events committee session held on 12 March, attended by Alice Example, Bob Sample, Dan Testcase, and Erin Mockwell. The group compared two venue options for the spring offsite: the Harbor Street hall and the lakeside lodge. The lodge was rejected because of its higher price and distance, and Bob Sample was asked to finalize the Harbor Street paperwork. Alice Example presented the first version of the schedule, and members asked for fewer breakout sessions. Dan Testcase reported that shuttles would be needed because parking is limited. Erin Mockwell will collect dietary requirements after registration closes. Action items: send feedback on the schedule by 20 March, confirm the deposit payment date, and draft a transportation proposal. The next session is scheduled for 26 March at 10:00 in the small conference room.diff --git a/evals/title-mention/corpus/events/offsite-dietary-catering-menu.md b/evals/title-mention/corpus/events/offsite-dietary-catering-menu.mdnew file mode 100644index 0000000000..ad1824bf13--- /dev/null+++ b/evals/title-mention/corpus/events/offsite-dietary-catering-menu.md@@ -0,0 +1,6 @@+---+title: "Offsite Dietary Catering Menu"+type: note+---++This document lists the meals and dietary accommodations ordered for the spring offsite at Harbor Street. Catering comes from Fictional Fork Catering, coordinated by Erin Mockwell. Based on registration forms, the order includes 14 vegetarian meals, 6 vegan meals, 5 gluten-free meals, and 3 meals prepared without nuts for severe allergies. Day one lunch is a build-your-own grain bowl bar, and dinner is a choice of roasted chicken, mushroom risotto, or baked salmon. Day two lunch is sandwiches and salads. Coffee, tea, and snacks are refreshed at 10:00 and 15:00 each day. Allergy-safe meals will be labeled with attendee names and served from a separate table. Anyone whose needs changed after registration should email the events team by 5 May. The catering fee of $6,300 is separate from the venue rental and is paid on delivery.diff --git a/evals/title-mention/corpus/events/offsite-shuttle-transportation-plan.md b/evals/title-mention/corpus/events/offsite-shuttle-transportation-plan.mdnew file mode 100644index 0000000000..0cbb15b0b6--- /dev/null+++ b/evals/title-mention/corpus/events/offsite-shuttle-transportation-plan.md@@ -0,0 +1,6 @@+---+title: "Offsite Shuttle Transportation Plan"+type: note+---++This plan describes how attendees will travel between the main office and Harbor Street for the spring offsite. Dan Testcase is coordinating three shuttles, each with 25 seats. Departures from the office lot are at 7:30, 8:00, and 8:15 on 14 May, and return trips leave the venue at 16:30 on 15 May after the closing circle. Attendees are assigned to a shuttle by department, and the list is posted on the events page. Parking at the venue is limited to 20 vehicles, so only people with mobility needs or early departures may drive; they should register with Dan Testcase by 30 April. A luggage trailer will follow the third shuttle. The driver will wait ten minutes for latecomers only. Shuttle costs of $2,100 are billed separately from the rental fee and charged to the events budget.diff --git a/evals/title-mention/corpus/events/quarterly-town-hall-recap.md b/evals/title-mention/corpus/events/quarterly-town-hall-recap.mdnew file mode 100644index 0000000000..1e6da9c318--- /dev/null+++ b/evals/title-mention/corpus/events/quarterly-town-hall-recap.md@@ -0,0 +1,6 @@+---+title: "Quarterly Town Hall Recap"+type: note+---++This summary covers the second-quarter all-hands held on 11 June in the main auditorium and streamed to remote offices. Alice Example opened with company results, followed by a product roadmap presentation. On events, the committee announced that the summer picnic will take place on 20 July and that volunteers are needed. It also confirmed that planning for the December holiday party has started, with a budget approved in principle. Employees asked whether the next offsite could include partners for one dinner; the committee agreed to study the cost. Other questions covered remote travel stipends and parking near the office. Attendance was 212 in person and 148 online. The recording is available on the internal video page for 90 days. A short feedback survey remains open until 25 June, and results will be shared at the next gathering.diff --git a/evals/title-mention/corpus/events/spring-offsite-agenda-draft.md b/evals/title-mention/corpus/events/spring-offsite-agenda-draft.mdnew file mode 100644index 0000000000..84706f2c91--- /dev/null+++ b/evals/title-mention/corpus/events/spring-offsite-agenda-draft.md@@ -0,0 +1,6 @@+---+title: "Spring Offsite Agenda Draft"+type: note+---++This is the first working schedule for the spring offsite, prepared by Alice Example and circulated for comments on 3 March. Day one, 14 May at Harbor Street: registration at 9:00, opening keynote at 9:30, four parallel breakout sessions from 11:00, lunch at 12:30, a strategy workshop at 14:00, and a group dinner at 18:00. Day two, 15 May: a morning hike along the waterfront trail, a cross-team retrospective at 11:00, lunch, and a closing circle that ends at 16:00. Several items are still open, including who will lead the fourth breakout and whether the hike is realistic in spring weather. Department leads should send feedback to Alice Example by 10 March. Nothing in this schedule is approved, and times may shift once the venue and shuttle details are confirmed. Attendees should not book travel around these times yet.diff --git a/evals/title-mention/corpus/events/spring-offsite-agenda-final.md b/evals/title-mention/corpus/events/spring-offsite-agenda-final.mdnew file mode 100644index 0000000000..a98459d189--- /dev/null+++ b/evals/title-mention/corpus/events/spring-offsite-agenda-final.md@@ -0,0 +1,6 @@+---+title: "Spring Offsite Agenda Final"+type: note+---++This approved schedule replaces the earlier working version of the spring offsite plan and reflects all feedback gathered in March. Day one, 14 May at Harbor Street: registration at 9:00, the keynote moved to 10:00, three breakout sessions instead of four, lunch at 12:30, the strategy workshop at 14:00, and dinner at 18:30. Day two, 15 May: the waterfront hike was cancelled because of the rain forecast and replaced with an indoor design workshop led by Bob Sample. The retrospective stays at 11:00, and the closing circle now ends at 15:00 so shuttles can leave earlier. Alice Example signed off on the final version on 24 March. Any further changes must go through the events committee. Attendees can now book travel around these times, and room assignments will follow in a separate message from the events team.diff --git a/evals/title-mention/corpus/events/summer-picnic-volunteer-signup.md b/evals/title-mention/corpus/events/summer-picnic-volunteer-signup.mdnew file mode 100644index 0000000000..146dd6a02f--- /dev/null+++ b/evals/title-mention/corpus/events/summer-picnic-volunteer-signup.md@@ -0,0 +1,6 @@+---+title: "Summer Picnic Volunteer Signup"+type: note+---++Acme Example Co will hold its family picnic on 20 July at Maple Field, and the events committee needs about 24 volunteers. Roles include the setup crew, who arrive at 9:00 to place tents and tables; the grill team, who cook from 11:30 to 14:00; the children's games station; and the cleanup crew, who stay until 17:00. Each volunteer picks one shift of about three hours and receives a free lunch and an extra half day of paid time off. Sign-ups close on 30 June, and Frank Dummy will confirm assignments by email the following week. Volunteers should wear the orange event shirt, which will be delivered to each office. If you have food safety certification, please mention it, since the grill team needs at least two certified members. Rain plans will be announced 48 hours ahead.diff --git a/evals/title-mention/corpus/events/team-offsite.md b/evals/title-mention/corpus/events/team-offsite.mdnew file mode 100644index 0000000000..084463ed0e--- /dev/null+++ b/evals/title-mention/corpus/events/team-offsite.md@@ -0,0 +1,6 @@+---+title: "Team Offsite"+type: note+---++This overview introduces the spring gathering for Acme Example Co, held 14 and 15 May at Harbor Street. The purpose is to align teams on next year's priorities, build connections across departments, and reflect on recent projects. All full-time employees are invited, and managers should ensure coverage for urgent customer requests. Expect a mix of talks, workshops, and social time, with casual dress recommended. Bring a laptop, a reusable water bottle, and comfortable shoes. Shuttles leave from the main office, and meals are provided with dietary options. Rooms are not needed since everyone returns home each evening. Questions should go to Alice Example, who chairs the events committee. Detailed pages about the schedule, venue terms, transport, and catering are linked from the events section of the intranet. Please complete the registration form by 30 April so headcounts are accurate.diff --git a/evals/title-mention/corpus/events/weekly-update.md b/evals/title-mention/corpus/events/weekly-update.mdnew file mode 100644index 0000000000..1c2da832d1--- /dev/null+++ b/evals/title-mention/corpus/events/weekly-update.md@@ -0,0 +1,6 @@+---+title: "Weekly Update"+type: note+---++Events team progress for the week ending 18 April. The deposit for the Harbor Street hall was paid on 1 April and finance has confirmed receipt. Registration for the spring offsite stands at 72 of 80 seats, and a reminder will go out on Monday. Dan Testcase is finalizing shuttle routes and has asked for parking exception requests. Erin Mockwell shared the first draft of the December party spending plan, and the committee will review it next week. Sign-ups for summer picnic volunteers opened on Thursday, and eleven people have already joined. Risks this week include a possible rise in catering costs and a pending reply from the audio vendor. Next week's priorities are to send the room assignments, confirm the final headcount for meals, and post the travel instructions on the events page for all attendees.diff --git a/evals/title-mention/corpus/finance/budget-review.md b/evals/title-mention/corpus/finance/budget-review.mdnew file mode 100644index 0000000000..506002953d--- /dev/null+++ b/evals/title-mention/corpus/finance/budget-review.md@@ -0,0 +1,6 @@+---+title: "Budget Review"+type: note+---++This mid-year company-wide assessment compares actual results against the approved plan for Acme Example Co. Revenue reached $8.4 million against a plan of $8.1 million, helped by the widget price increase. Operating expenses were $6.2 million, about 2% above plan, driven by marketing event costs and engineering cloud hosting. Facilities costs are rising because of the higher headquarters rent and the warehouse renewal. Leadership, led by Alice Example, agreed to keep a contingency reserve of $150,000 and to hold departments to their current allocations for the remainder of the year. Discretionary capital purchases will be reviewed one at a time, with the hardware test bench deferred unless cash flow improves. Travel spending will be tracked against the new per diem limits. Department heads must submit revised forecasts within two weeks so finance can update the full-year outlook.diff --git a/evals/title-mention/corpus/finance/capital-equipment-purchase-forecast.md b/evals/title-mention/corpus/finance/capital-equipment-purchase-forecast.mdnew file mode 100644index 0000000000..2c37c355e2--- /dev/null+++ b/evals/title-mention/corpus/finance/capital-equipment-purchase-forecast.md@@ -0,0 +1,6 @@+---+title: "Capital Equipment Purchase Forecast"+type: note+---++This forecast lists planned capital purchases for the fiscal year, totaling $640,000. The largest item is a new packaging line at $310,000 for the Riverside Road warehouse. Also planned are two forklifts at $85,000, replacement laptops for the engineering team at $120,000, and a hardware test bench at $125,000. Jack Sample prepared the forecast and recommends deferring the test bench to the next fiscal year if cash flow tightens. All items are depreciated straight-line over five years, which adds about $128,000 per year to depreciation expense once everything is in service. Purchases above $100,000 need approval from the finance director. The forecast assumes vendor quotes remain valid through the third quarter and includes a 5% contingency on the packaging line. Cash timing is reviewed monthly.diff --git a/evals/title-mention/corpus/finance/harbor-street-lease-agreement.md b/evals/title-mention/corpus/finance/harbor-street-lease-agreement.mdnew file mode 100644index 0000000000..2b7fa3f100--- /dev/null+++ b/evals/title-mention/corpus/finance/harbor-street-lease-agreement.md@@ -0,0 +1,6 @@+---+title: "Harbor Street Lease Agreement"+type: note+---++This summary covers the original office lease for the Harbor Street headquarters, signed by Alice Example for Acme Example Co and Bob Sample for the landlord. The term is five years, covering floors one and two, a total of 18,000 square feet. Monthly base rent starts at $41,000 with a 3% annual escalation. The security deposit is $82,000. The tenant may terminate early after month 36 by giving six months of written notice and paying a fee equal to three months of rent. The tenant improvement allowance is $40,000. Parking is billed separately at $150 per space each month. Finance books rent as a fixed monthly expense in the facilities budget line and reviews occupancy accruals every quarter. Later changes to rent, space, or term are handled in separate documents and are not reflected in these original figures.diff --git a/evals/title-mention/corpus/finance/harbor-street-lease-amendment.md b/evals/title-mention/corpus/finance/harbor-street-lease-amendment.mdnew file mode 100644index 0000000000..fac070aa60--- /dev/null+++ b/evals/title-mention/corpus/finance/harbor-street-lease-amendment.md@@ -0,0 +1,6 @@+---+title: "Harbor Street Lease Amendment"+type: note+---++This document records the changes made to the office lease for the Harbor Street headquarters, signed by Alice Example for Acme Example Co and Bob Sample for the landlord. It supersedes the base rent schedule and the expansion clause of the original agreement. Effective January 1, monthly base rent rises from $41,000 to $46,500 in exchange for the addition of the third floor, which adds 6,200 square feet. The term is extended by two years. The security deposit increases by $18,000, and the tenant improvement allowance is set at $95,000, payable after the finance team submits contractor invoices. Parking fees are now bundled into rent. The early termination option from the earlier lease is removed. Finance should update the quarterly occupancy accrual and the fixed asset schedule, and Carol Placeholder will reconcile the revised rent against the Q3 facilities budget line.diff --git a/evals/title-mention/corpus/finance/meeting-notes.md b/evals/title-mention/corpus/finance/meeting-notes.mdnew file mode 100644index 0000000000..7b2af5c1a7--- /dev/null+++ b/evals/title-mention/corpus/finance/meeting-notes.md@@ -0,0 +1,6 @@+---+title: "Meeting Notes"+type: note+---++Finance team sync attended by Alice Example, Carol Placeholder, Grace Sample, and Ivy Example. The group reviewed quarter-end progress. Carol confirmed that the higher headquarters rent has been added to the facilities accrual. Grace explained the marketing overspend, mostly from the Lakeview Expo, and asked whether unused fourth-quarter brand funds could offset it. Alice said a transfer needs revised event estimates first. Ivy raised the per diem cap and asked whether international trips already booked should be grandfathered; the group agreed they should follow the new limits after October 1. The team also discussed the timing of customer notices for the price increase. Action items: Carol updates the accrual schedule by Friday, Grace sends event estimates, and Ivy circulates the revised travel rules. The next sync is scheduled for the following Tuesday morning.diff --git a/evals/title-mention/corpus/finance/q3-engineering-budget-variance.md b/evals/title-mention/corpus/finance/q3-engineering-budget-variance.mdnew file mode 100644index 0000000000..dab41f8681--- /dev/null+++ b/evals/title-mention/corpus/finance/q3-engineering-budget-variance.md@@ -0,0 +1,6 @@+---+title: "Q3 Engineering Budget Variance"+type: note+---++The engineering department finished the third quarter slightly over budget. The approved budget was $1,150,000 and actual spend was $1,213,000, an overspend of $63,000, or 5.5%. Cloud hosting was $88,000 over plan because of load testing for the new release. Contractor spend was $34,000 over after two short-term hires covered a sprint. These overruns were partly offset by $59,000 of savings from delayed permanent hiring. Henry Placeholder owns the department budget and has committed to reducing hosting costs by moving test environments to scheduled shutdowns. Finance will monitor monthly hosting invoices and review the run rate at the next close. The marketing and other departmental variances are reported separately, and this report covers engineering only. No transfer of funds from other departments is requested for the fourth quarter.diff --git a/evals/title-mention/corpus/finance/q3-marketing-budget-variance.md b/evals/title-mention/corpus/finance/q3-marketing-budget-variance.mdnew file mode 100644index 0000000000..c44411d82a--- /dev/null+++ b/evals/title-mention/corpus/finance/q3-marketing-budget-variance.md@@ -0,0 +1,6 @@+---+title: "Q3 Marketing Budget Variance"+type: note+---++The marketing department finished the third quarter over budget. The approved budget was $420,000 and actual spend was $468,000, an overspend of $48,000, or 11.4%. The main driver was the Lakeview Expo trade show, which cost $39,000 more than planned after booth upgrades and late shipping fees. Paid search spend was $9,000 over because of a promotion tied to the widget price change. Content production came in $6,000 under budget after a freelancer contract ended early. Grace Sample owns the department budget and explained the variance to finance. She proposes shifting $25,000 from the fourth-quarter brand campaign to cover part of the overrun. Finance asks for revised event estimates before approving any transfer. The engineering and other departmental variances are reported separately, and this report covers marketing only.diff --git a/evals/title-mention/corpus/finance/riverside-warehouse-lease-renewal.md b/evals/title-mention/corpus/finance/riverside-warehouse-lease-renewal.mdnew file mode 100644index 0000000000..b9c0369f54--- /dev/null+++ b/evals/title-mention/corpus/finance/riverside-warehouse-lease-renewal.md@@ -0,0 +1,6 @@+---+title: "Riverside Warehouse Lease Renewal"+type: note+---++Acme Example Co has agreed to renew the lease on the Riverside Road warehouse that stores widget inventory. The landlord, Dana Sample, offered a three-year renewal at 30,000 square feet. Monthly rent moves from $22,000 to $23,400, and common area maintenance charges are capped at 4% growth per year. Finance compared this with relocating to a new site and found that moving costs of about $210,000 outweighed the rent savings. The renewal removes the option to sublease part of the space. Frank Example will update the fixed cost forecast for the fourth quarter, and the added rent of roughly $4,200 per quarter will be charged to the operations budget. Signing is expected once legal confirms the insurance certificate. This lease is separate from the headquarters office lease and has different renewal dates and terms.diff --git a/evals/title-mention/corpus/finance/travel-expense-policy-update.md b/evals/title-mention/corpus/finance/travel-expense-policy-update.mdnew file mode 100644index 0000000000..ebf4f13bbd--- /dev/null+++ b/evals/title-mention/corpus/finance/travel-expense-policy-update.md@@ -0,0 +1,6 @@+---+title: "Travel Expense Policy Update"+type: note+---++Effective October 1, Acme Example Co is revising its rules for employee travel reimbursement. Daily meal per diem is capped at $75 for domestic trips and $110 for international trips. Hotel stays are capped at $210 per night unless a manager approves an exception. Airfare must be booked at least 14 days in advance, and receipts are required for any expense above $25. Ivy Example in finance will approve exceptions and review monthly reports of spend by department. The revision replaces the older flat allowance, which caused inconsistent claims and several disputes last year. Finance estimates annual savings of about $54,000, mostly from advance airfare booking and hotel caps. Departments that exceed their travel budget by more than 10% in a quarter must submit an explanation. Questions can be sent to the finance help desk.diff --git a/evals/title-mention/corpus/finance/weekly-update.md b/evals/title-mention/corpus/finance/weekly-update.mdnew file mode 100644index 0000000000..7943005c8f--- /dev/null+++ b/evals/title-mention/corpus/finance/weekly-update.md@@ -0,0 +1,6 @@+---+title: "Weekly Update"+type: note+---++Finance team summary for the week ending Friday. Quarter-end close is 70% complete; bank reconciliations are done and accrual entries are in progress. Carol Placeholder posted the revised rent for the Harbor Street office. The renewal of the Riverside Road warehouse is agreed in principle, and legal is waiting on an insurance certificate before signing. Customer notices for the widget price increase were sent to the first group of accounts. Marketing submitted revised event estimates after the trade show overrun. Engineering hosting invoices arrived higher than expected and are being reviewed. The capital purchase forecast was circulated for comment, with the test bench flagged as a possible deferral. Headcount is unchanged. Next week priorities include finalizing variance commentary, updating the cash forecast, and preparing materials for the mid-year discussion with leadership.diff --git a/evals/title-mention/corpus/finance/widget-pricing-review-q2.md b/evals/title-mention/corpus/finance/widget-pricing-review-q2.mdnew file mode 100644index 0000000000..f4255a480b--- /dev/null+++ b/evals/title-mention/corpus/finance/widget-pricing-review-q2.md@@ -0,0 +1,6 @@+---+title: "Widget Pricing Review Q2"+type: note+---++This paper documents the second-quarter pricing decision for the widget product line, prepared by Frank Example. The list price of the Standard Widget rises modestly from $46 to $48, while the Deluxe Widget stays at $85. Finance benchmarked prices against three competitors and found Acme Example Co about 5% below the median. Volume discount tiers are unchanged: orders above 500 units receive 9%. Price elasticity modeling suggests unit volume falls under 1%, with revenue improving by roughly $120,000 for the quarter. Customer notices go out 45 days before the effective date. Gross margin on the Standard Widget is projected at 38%. The review recommends revisiting Deluxe pricing in the next quarter if input costs continue to rise. Later pricing changes build on these figures and should be compared against them when measuring results.diff --git a/evals/title-mention/corpus/finance/widget-pricing-review-q3.md b/evals/title-mention/corpus/finance/widget-pricing-review-q3.mdnew file mode 100644index 0000000000..c987c161ab--- /dev/null+++ b/evals/title-mention/corpus/finance/widget-pricing-review-q3.md@@ -0,0 +1,6 @@+---+title: "Widget Pricing Review Q3"+type: note+---++This paper documents the third-quarter pricing decision for the widget product line, approved by Erin Placeholder. The list price of the Standard Widget rises from $48 to $52, and the Deluxe Widget rises from $85 to $91. Volume discount tiers are tightened so that orders above 500 units receive 6% instead of 9%. Finance modeled price elasticity using the last four quarters of order data and expects unit volume to fall about 3%, while revenue improves by roughly $310,000 for the quarter. Customer notices go out 30 days before the effective date. The analysis compares results against the earlier second-quarter changes and flags the enterprise segment as the most sensitive. Gross margin on the Standard Widget is projected to reach 41%. Results will be checked again at the end of the fiscal year.diff --git a/evals/title-mention/corpus/hiring/budget-review.md b/evals/title-mention/corpus/hiring/budget-review.mdnew file mode 100644index 0000000000..15a3d9207f--- /dev/null+++ b/evals/title-mention/corpus/hiring/budget-review.md@@ -0,0 +1,6 @@+---+title: "Budget Review"+type: note+---++Summary of recruiting spend against plan for the current half-year. Agency fees are 8,000 approved and 3,200 used so far, all tied to backend candidates. Meetup and event sponsorship is 3,000 approved with 1,000 committed. Referral bonuses are forecast at 22,000, which is 4,000 higher than earlier because senior payouts were raised. Job board subscriptions are flat at 5,400. The proposed recruiter position for the Harbor Street office is funded at the midpoint of its salary band, plus a placement bonus, for an annual cost near 95,000 with benefits. Support hiring shows a variance: the amended headcount raises incremental cost by 19,500. Dan Sample and Grace Sample recommend covering that variance from unused contractor conversion funds. Open questions include whether to renew the applicant tracking license at a higher tier and whether to prepay agency retainers. The final numbers will be presented to Erin Demo at month end.diff --git a/evals/title-mention/corpus/hiring/contractor-conversion-guidelines.md b/evals/title-mention/corpus/hiring/contractor-conversion-guidelines.mdnew file mode 100644index 0000000000..8b15fb70db--- /dev/null+++ b/evals/title-mention/corpus/hiring/contractor-conversion-guidelines.md@@ -0,0 +1,6 @@+---+title: "Contractor Conversion Guidelines"+type: note+---++These guidelines explain how a contractor at Acme Example Co can move onto payroll as a regular employee. A contractor becomes eligible after six months of continuous engagement and a written recommendation from the sponsoring manager. The manager must confirm that an approved headcount slot exists in the department's hiring plan; conversions cannot create new headcount. The recruiter runs a shortened interview loop of two conversations rather than the full process. Compensation is set on the internal ladder for the level of the work performed, not the contractor's previous hourly rate. A conversion fee is not paid to any agency after twelve months of engagement. Employment starts on the first day of a pay period, and benefits begin the following month. Erin Demo approves every conversion, and Grace Sample in Finance updates the headcount records. Managers should start the process at least 45 days before the contract end date.diff --git a/evals/title-mention/corpus/hiring/data-analyst-interview-rubric.md b/evals/title-mention/corpus/hiring/data-analyst-interview-rubric.mdnew file mode 100644index 0000000000..a14010453b--- /dev/null+++ b/evals/title-mention/corpus/hiring/data-analyst-interview-rubric.md@@ -0,0 +1,6 @@+---+title: "Data Analyst Interview Rubric"+type: note+---++This scorecard is used by every interviewer who meets a Data Analyst candidate at Acme Example Co. Each of four areas is scored from 1 to 4: SQL fluency, analytical reasoning, communication of findings, and collaboration with non-technical partners. The SQL round uses a live exercise with a messy orders table. The reasoning round asks the candidate to diagnose a sudden drop in weekly support volume. In the communication round, the candidate presents a two-slide summary to Frank Illustrative. Scores below 2 in any area are a no-hire unless the panel documents an exception. A total of 12 or higher moves the candidate to the offer discussion. Interviewers submit written feedback within 24 hours and must not read other scores before submitting their own. The recruiter compiles the results. The duties, level, and salary band for the position are described in its separate posting.diff --git a/evals/title-mention/corpus/hiring/data-analyst-role-description.md b/evals/title-mention/corpus/hiring/data-analyst-role-description.mdnew file mode 100644index 0000000000..3940553111--- /dev/null+++ b/evals/title-mention/corpus/hiring/data-analyst-role-description.md@@ -0,0 +1,6 @@+---+title: "Data Analyst Role Description"+type: note+---++The Data Analyst position supports the Finance and Operations group at Acme Example Co and reports to Frank Illustrative, Director of Operations. The analyst builds weekly dashboards, maintains revenue and support-volume reports, and answers ad hoc questions from department leads. Required experience: two years of analytics work, advanced spreadsheet skills, and fluent SQL. Preferred experience: a scripting language and a dashboard tool. The level is L3, with a salary band of 68,000 to 82,000. The position is based at the Harbor Street office with hybrid scheduling. Responsibilities include documenting data definitions, checking report accuracy, and presenting findings monthly. Success at ninety days means taking over the weekly operations dashboard and closing the open data quality tickets. Candidate evaluation criteria and the scoring scale live in a separate scorecard. Openings and timelines are handled by the recruiter, and this page covers duties and qualifications only.diff --git a/evals/title-mention/corpus/hiring/engineering-referral-bonus-policy.md b/evals/title-mention/corpus/hiring/engineering-referral-bonus-policy.mdnew file mode 100644index 0000000000..6ac41f0f7c--- /dev/null+++ b/evals/title-mention/corpus/hiring/engineering-referral-bonus-policy.md@@ -0,0 +1,6 @@+---+title: "Engineering Referral Bonus Policy"+type: note+---++Employees who refer a candidate hired into an engineering position earn a referral bonus. The amount is 2,500 for standard positions and 4,000 for senior positions, such as backend openings at level L5 or above. Payment is split: half is paid after the new hire's start date and half after ninety days of employment. The referrer must submit the candidate through the referral tracker before the first recruiter screen; later submissions do not qualify. Managers in the same reporting chain as the hire are not eligible, and recruiters cannot claim bonuses. Contractors who later convert to employees are not eligible for referral payouts on their own conversion, though the person who originally referred them may qualify. Bonuses are paid with the next monthly payroll after each milestone. Questions go to Erin Demo. The policy is reviewed each January, and any change to amounts is announced to all engineering staff by email.diff --git a/evals/title-mention/corpus/hiring/harbor-street-recruiter-job-description.md b/evals/title-mention/corpus/hiring/harbor-street-recruiter-job-description.mdnew file mode 100644index 0000000000..eb742f0456--- /dev/null+++ b/evals/title-mention/corpus/hiring/harbor-street-recruiter-job-description.md@@ -0,0 +1,6 @@+---+title: "Harbor Street Recruiter Job Description"+type: note+---++Acme Example Co is seeking a full-time technical recruiter for the Harbor Street office. The recruiter partners with hiring managers, writes postings, screens candidates, and coordinates interview loops. Requirements: three years of in-house or agency recruiting, comfort with applicant tracking systems, and clear written communication. The salary band is 72,000 to 88,000, plus a placement bonus paid after a hire completes ninety days. The recruiter reports to Erin Demo, Head of People. Core metrics are time to offer, offer acceptance rate, and candidate satisfaction survey score. First-quarter priorities include the backend engineer and data analyst openings and cleaning up stale requisitions in the tracking system. The recruiter also maintains the referral tracker and schedules quarterly reviews of each department's hiring plan with its lead. Occasional travel to meetups and campus events is expected, and the position includes two remote days per week.diff --git a/evals/title-mention/corpus/hiring/meeting-notes.md b/evals/title-mention/corpus/hiring/meeting-notes.mdnew file mode 100644index 0000000000..a1ea7a14b8--- /dev/null+++ b/evals/title-mention/corpus/hiring/meeting-notes.md@@ -0,0 +1,6 @@+---+title: "Meeting Notes"+type: note+---++Attendees: Erin Demo, Alice Example, Bob Sample, Carol Placeholder, and Dan Sample. This hiring sync covered four items. First, the two backend engineer openings remain on schedule; Alice reported six candidates in the take-home stage. Second, Carol asked to accelerate the tier-two support specialist hire and to add a fifth agent for the weekend shift. Dan will review the cost change before approving it. Third, the group agreed to raise senior referral payouts from 3,500 to 4,000, effective next quarter, with Erin to update the written policy. Fourth, Bob asked whether two long-serving contractors could convert to employees this year; Erin will check that headcount slots exist first. Action items: Alice sends the pipeline summary on Friday, Dan returns cost numbers by Wednesday, and Erin drafts the revised policy text. The next sync is scheduled for the second Tuesday of next month.diff --git a/evals/title-mention/corpus/hiring/senior-backend-engineer-hiring-plan.md b/evals/title-mention/corpus/hiring/senior-backend-engineer-hiring-plan.mdnew file mode 100644index 0000000000..96f1b8aebe--- /dev/null+++ b/evals/title-mention/corpus/hiring/senior-backend-engineer-hiring-plan.md@@ -0,0 +1,6 @@+---+title: "Senior Backend Engineer Hiring Plan"+type: note+---++This plan covers filling two Senior Backend Engineer openings in the Platform group during the second half of the year. Recruiter Alice Example opens both requisitions on the first of July. The interview stages are a recruiter screen, a take-home exercise, a system design interview, and a values conversation with Bob Sample. The target time to offer is 35 days. Sourcing channels are employee referrals, two engineering meetups, and an agency shortlist capped at ten candidates. The budget is 8,000 for agency fees and 3,000 for meetup sponsorship. Target start dates are mid-September and mid-October. Duties, level, salary band, and qualifications are documented in the position's role description, not here. Known risks include a competing offer cycle in August and limited interviewer availability during quarter close. Pipeline counts go to the hiring manager every Friday until both offers are accepted.diff --git a/evals/title-mention/corpus/hiring/senior-backend-engineer-role-description.md b/evals/title-mention/corpus/hiring/senior-backend-engineer-role-description.mdnew file mode 100644index 0000000000..dd889604a4--- /dev/null+++ b/evals/title-mention/corpus/hiring/senior-backend-engineer-role-description.md@@ -0,0 +1,6 @@+---+title: "Senior Backend Engineer Role Description"+type: note+---++The Senior Backend Engineer position sits in the Platform group at Acme Example Co and reports to Bob Sample, Engineering Manager. The engineer owns the order-processing services, designs internal APIs, and leads code reviews for two junior teammates. Required experience: six years building distributed services, strong SQL skills, and prior on-call ownership. Preferred experience: message queues and payment integrations. The level is L5, with a salary band of 128,000 to 152,000 on the internal ladder. The position is based at the Harbor Street office with two remote days per week. Responsibilities also include capacity planning, incident retrospectives, and mentoring. Success at ninety days means shipping one service improvement and joining the on-call rotation. The interview timeline, sourcing channels, and number of openings are tracked separately in the hiring plan for this position. This page covers duties, level, and qualifications only.diff --git a/evals/title-mention/corpus/hiring/support-team-headcount-plan-amendment.md b/evals/title-mention/corpus/hiring/support-team-headcount-plan-amendment.mdnew file mode 100644index 0000000000..c26233df02--- /dev/null+++ b/evals/title-mention/corpus/hiring/support-team-headcount-plan-amendment.md@@ -0,0 +1,6 @@+---+title: "Support Team Headcount Plan Amendment"+type: note+---++This amendment revises the support headcount numbers approved earlier in the fiscal year. Changes: the tier-two specialist hire moves up from June to April; the team lead requisition is cancelled and replaced with an internal promotion; and tier-one agent hires increase from four to five because of the new weekend shift. Training cohort seats rise from four to five per quarter. Incremental cost changes from 412,000 to 431,500 including benefits. Carol Placeholder requested the changes after the ticket volume review, and Dan Sample approved them. Everything not mentioned here, including salary assumptions, the 4 percent merit adjustment, and attrition backfills at 10 percent, remains as written in the original support headcount document. For the items listed above, the original figures are superseded by this revision. Recruiting should reopen the agent requisitions immediately and move the specialist posting to the front of the queue.diff --git a/evals/title-mention/corpus/hiring/support-team-headcount-plan-fy25.md b/evals/title-mention/corpus/hiring/support-team-headcount-plan-fy25.mdnew file mode 100644index 0000000000..2c654cebf5--- /dev/null+++ b/evals/title-mention/corpus/hiring/support-team-headcount-plan-fy25.md@@ -0,0 +1,6 @@+---+title: "Support Team Headcount Plan FY25"+type: note+---++This document sets headcount for the customer support organization in fiscal 2025. The current team is 14 agents across two shifts under Carol Placeholder. Approved growth is four tier-one agents, one tier-two specialist, and one team lead. Hiring waves: two agents in February, two agents in May, the specialist in June, and the team lead in August. Every agent requisition needs a seat in the training cohort, which is limited to four seats per quarter. Salary assumptions use the standard support ladder with a 4 percent merit adjustment. Total incremental cost is 412,000 including benefits. Backfills for attrition are handled separately and assumed at 10 percent per year. Dan Sample signed the approval during the original budget cycle. Any later changes to wave timing or counts are recorded in a follow-up document rather than edited here, so this page reflects the first approved numbers.diff --git a/evals/title-mention/corpus/hiring/weekly-update.md b/evals/title-mention/corpus/hiring/weekly-update.mdnew file mode 100644index 0000000000..9256fa9f34--- /dev/null+++ b/evals/title-mention/corpus/hiring/weekly-update.md@@ -0,0 +1,6 @@+---+title: "Weekly Update"+type: note+---++Recruiting pipeline for the week ending Friday. Backend engineer: 14 applicants, six in the take-home stage, two scheduled for system design interviews next week. Data analyst: three finalists completed their panels, and scores are being compiled. Support: five agent requisitions were reopened after the revised headcount was approved, and the tier-two specialist posting went live on Monday. Recruiter hire: two candidates remain for the Harbor Street office position, and final conversations are set for Thursday. Referrals: seven new submissions logged in the tracker, four of them for engineering. Blockers: interviewer availability is thin because of quarter close, and one agency invoice is awaiting approval from Dan Sample. Offers extended this week: one, to a support agent, and it has been accepted. Next week's goals are to schedule all remaining backend interviews, send data analyst decisions, and confirm the training cohort seats for new support agents.diff --git a/evals/title-mention/corpus/leases/budget-review.md b/evals/title-mention/corpus/leases/budget-review.mdnew file mode 100644index 0000000000..204762dc61--- /dev/null+++ b/evals/title-mention/corpus/leases/budget-review.md@@ -0,0 +1,6 @@+---+title: "Budget Review"+type: note+---++This session examined occupancy costs for the fiscal year across all leased properties. Total base rent is forecast at $1.42 million, with Harbor Street rising after the new term began and the Dock Road warehouse increasing under the fixed annual schedule. Sublease income from the Maple Court subtenant offsets about $78,000 of rent. Operating expense pass-throughs are expected to exceed the plan by four percent, driven by snow removal and higher property taxes; Grace Placeholder recommended a reserve of $35,000. Insurance premiums rose eleven percent, mostly from higher umbrella coverage requirements by landlords. The improvement allowance from the Harbor Street landlord is treated as a receivable until paid. Retail costs at Cedar Plaza include the marketing fund contribution and possible percentage rent, which is currently not triggered. Recommendations: negotiate cap language on controllable expenses in future renewals, audit common area charges at two sites, and evaluate consolidating storage space before the next expiration.diff --git a/evals/title-mention/corpus/leases/cedar-plaza-estoppel-certificate.md b/evals/title-mention/corpus/leases/cedar-plaza-estoppel-certificate.mdnew file mode 100644index 0000000000..ce56e92808--- /dev/null+++ b/evals/title-mention/corpus/leases/cedar-plaza-estoppel-certificate.md@@ -0,0 +1,6 @@+---+title: "Cedar Plaza Estoppel Certificate"+type: note+---++This estoppel statement was signed by Acme Example Co on May 20, 2024, at the request of Willow Ridge Holdings Example, which is refinancing the shopping center. Acme Example Co certifies that Unit 14 lease is in full force, unmodified, and that no amendments or side letters exist. It confirms base rent of $4,900 per month paid through May 31, 2024, no prepaid rent beyond that month, and a security deposit of $9,800 on hand. The tenant states it knows of no landlord defaults, no unresolved disputes, and no unpaid allowances. It also confirms that the commencement date was August 1, 2022, that the expiration is July 31, 2027, and that no renewal options were exercised. The lender, Bayview Credit Example, may rely on these statements for ninety days. Signed by Alice Example as authorized officer and delivered to Henry Sample. A copy is retained with the executed lease in the property file.diff --git a/evals/title-mention/corpus/leases/cedar-plaza-retail-lease.md b/evals/title-mention/corpus/leases/cedar-plaza-retail-lease.mdnew file mode 100644index 0000000000..ba4ad3837c--- /dev/null+++ b/evals/title-mention/corpus/leases/cedar-plaza-retail-lease.md@@ -0,0 +1,6 @@+---+title: "Cedar Plaza Retail Lease"+type: note+---++This lease covers Unit 14, a 1,850 square foot storefront at Cedar Plaza, rented by Acme Example Co from Willow Ridge Holdings Example for a demonstration showroom. The term is five years from August 1, 2022. Base rent is $4,900 monthly plus percentage rent of five percent of gross sales above a natural breakpoint of $1,176,000 per year. Tenant pays common area maintenance, a marketing fund contribution of $350 monthly, and its share of taxes. Operating hours must match the center's schedule of ten to eight on weekdays. Signage must follow the center's sign criteria and receive advance approval. The lease includes a co-tenancy clause: if the anchor grocer closes for more than 120 days, rent drops to fifty percent until a replacement opens. Radius restriction is three miles. Guarantor is not required. Contact for the landlord is Henry Sample, property manager. Requests for confirmation of lease status by lenders are answered through a separate certificate signed by the tenant.diff --git a/evals/title-mention/corpus/leases/harbor-street-lease-agreement.md b/evals/title-mention/corpus/leases/harbor-street-lease-agreement.mdnew file mode 100644index 0000000000..59f56f5a6f--- /dev/null+++ b/evals/title-mention/corpus/leases/harbor-street-lease-agreement.md@@ -0,0 +1,6 @@+---+title: "Harbor Street Lease Agreement"+type: note+---++This document records the original commercial lease between Acme Example Co, as tenant, and Northgate Holdings Example, as landlord, for the second and third floors of 41 Harbor Street. The term runs five years from March 1, 2021, with base rent of $18,500 per month, payable on the first business day. The tenant deposits a security amount equal to two months of rent. Permitted use is general office space; any change requires written landlord consent. The tenant pays a proportionate share of operating expenses and property taxes, estimated at 14.2 percent of the building. Two parking spaces are included at no additional charge. The tenant holds one option to renew for three years at ninety-five percent of prevailing market rent, exercised by written notice at least nine months before expiry. Early termination is not permitted except after casualty or condemnation. Notices go to Alice Example, Real Estate Manager. Later changes to rent, term, or parking are handled by separate written modifications rather than by editing this original.diff --git a/evals/title-mention/corpus/leases/harbor-street-lease-amendment.md b/evals/title-mention/corpus/leases/harbor-street-lease-amendment.mdnew file mode 100644index 0000000000..e60849ddb0--- /dev/null+++ b/evals/title-mention/corpus/leases/harbor-street-lease-amendment.md@@ -0,0 +1,6 @@+---+title: "Harbor Street Lease Amendment"+type: note+---++This amendment modifies the original Harbor Street lease signed in 2021 between Acme Example Co and Northgate Holdings Example. Effective January 1, 2024, base rent increases to $19,900 per month and the term is extended by two years, ending February 28, 2028. The amendment supersedes the renewal option in the original lease, replacing it with a single two-year option at market rent. Parking is expanded from two spaces to four at $150 per space monthly. The tenant's share of operating expenses remains 14.2 percent, but a cap of five percent applies to annual increases in controllable expenses. The landlord agrees to fund a $60,000 improvement allowance for repainting and new carpet on the third floor, payable after completion and receipt of invoices. All other terms of the original remain in force. Signed by Bob Sample for the landlord and Alice Example for the tenant, with Carol Placeholder as witness.diff --git a/evals/title-mention/corpus/leases/landlord-insurance-requirements-memo.md b/evals/title-mention/corpus/leases/landlord-insurance-requirements-memo.mdnew file mode 100644index 0000000000..4605c02326--- /dev/null+++ b/evals/title-mention/corpus/leases/landlord-insurance-requirements-memo.md@@ -0,0 +1,6 @@+---+title: "Landlord Insurance Requirements Memo"+type: note+---++This memo summarizes the insurance coverage that landlords require of Acme Example Co across its leased locations, prepared by Ivan Placeholder in Risk Management. Commercial general liability must be at least $2 million per occurrence and $4 million aggregate at every site. The Harbor Street and Maple Court landlords also require an umbrella policy of $5 million. The Riverside warehouse landlord requires property coverage on inventory and racking, with a maximum deductible of $25,000. Cedar Plaza requires plate glass coverage and business interruption insurance for twelve months. Each landlord must be named as additional insured, and certificates are due before commencement and at every policy renewal. Cancellation notice of thirty days must be provided to landlords. Subtenants must carry equivalent liability coverage. The memo lists renewal dates, brokers, and premium allocations by location. Questions about certificate requests go to the risk team, and missing certificates may trigger default notices.diff --git a/evals/title-mention/corpus/leases/maple-court-office-lease.md b/evals/title-mention/corpus/leases/maple-court-office-lease.mdnew file mode 100644index 0000000000..90e134b4de--- /dev/null+++ b/evals/title-mention/corpus/leases/maple-court-office-lease.md@@ -0,0 +1,6 @@+---+title: "Maple Court Office Lease"+type: note+---++This is the master lease for Suite 300 at 12 Maple Court, covering 8,200 rentable square feet leased by Acme Example Co from Linden Property Example. The term is seven years beginning July 1, 2022, with base rent of $27.50 per square foot annually, increasing three percent each July. Acme Example Co pays a security deposit of $45,000 and its pro rata share of taxes, insurance, and common area charges. Permitted use is office and training rooms only. The landlord provides eight reserved parking stalls and after-hours access through a key card system. Assignment or subletting requires landlord written consent, which may not be unreasonably withheld, and the landlord may recapture space in certain cases. The tenant must restore alterations at expiry unless waived in writing. Contact for lease administration is Dana Placeholder at Linden Property Example. Any partial subletting by the tenant is documented separately and remains subject to this master lease.diff --git a/evals/title-mention/corpus/leases/maple-court-sublease-agreement.md b/evals/title-mention/corpus/leases/maple-court-sublease-agreement.mdnew file mode 100644index 0000000000..c6718db8e2--- /dev/null+++ b/evals/title-mention/corpus/leases/maple-court-sublease-agreement.md@@ -0,0 +1,6 @@+---+title: "Maple Court Sublease Agreement"+type: note+---++Under this sublease, Acme Example Co, as sublandlord, sublets 2,600 square feet of Suite 300 at 12 Maple Court to Brightside Studio Example, as subtenant. The sublease term runs from October 1, 2023 through June 30, 2027, ending one day before the master lease expires. Subtenant rent is $29.00 per square foot annually, slightly above the rate Acme Example Co pays the master landlord, Linden Property Example. The subtenant deposits $12,000 and receives two reserved parking stalls and shared use of the conference room on a booking basis. The subtenant must follow every obligation in the master lease, carry its own liability coverage, and name both Acme Example Co and the master landlord as additional insureds. Linden Property Example gave written consent on September 12, 2023, signed by Dana Placeholder. Default by the subtenant does not release Acme Example Co from its own duties to the master landlord. Notices go to Erin Sample.diff --git a/evals/title-mention/corpus/leases/meeting-notes.md b/evals/title-mention/corpus/leases/meeting-notes.mdnew file mode 100644index 0000000000..5fbbc2f807--- /dev/null+++ b/evals/title-mention/corpus/leases/meeting-notes.md@@ -0,0 +1,6 @@+---+title: "Meeting Notes"+type: note+---++Attendees: Alice Example, Frank Example, Grace Placeholder, and Bob Sample. Topic: upcoming lease decisions. Alice reported that the Harbor Street landlord has agreed to the extended term and larger parking allotment, and the signed papers should arrive this month. Frank confirmed the Dock Road warehouse renewal is complete and asked Finance to load the fixed annual increases into the payment system. Grace noted that operating expense reconciliations are due in March for three locations and requested landlord statements early. The group discussed whether to reduce space at Cedar Plaza once the term ends in 2027; no decision was made and Bob will gather sales data for the showroom. Action items: Alice to request a sublease consent status from Maple Court's landlord; Frank to collect insurance certificates; Grace to draft a projected occupancy cost table. Next discussion is scheduled for the first Tuesday of next month at ten in the small conference room.diff --git a/evals/title-mention/corpus/leases/riverside-warehouse-lease-renewal.md b/evals/title-mention/corpus/leases/riverside-warehouse-lease-renewal.mdnew file mode 100644index 0000000000..124c71e236--- /dev/null+++ b/evals/title-mention/corpus/leases/riverside-warehouse-lease-renewal.md@@ -0,0 +1,6 @@+---+title: "Riverside Warehouse Lease Renewal"+type: note+---++This renewal extends the lease of the Riverside distribution facility at 900 Dock Road, comprising 32,000 square feet of warehouse space and 2,400 square feet of attached office. Acme Example Co exercised its renewal option on April 15, 2024, and the landlord, Tidewater Realty Example, accepted in writing. The new term is five years, from January 1, 2025 through December 31, 2029. Starting monthly rent is $21,333, reset to market under the option clause, with annual increases set out in a separate schedule attached as Exhibit B. The security deposit of $42,666 carries over unchanged. The landlord will replace two dock levelers and repair the roof membrane by June 30, 2025, at its own cost. The tenant keeps responsibility for forklift charging areas and interior racking. A one-time right to terminate after month 36 is available with 180 days notice and payment of unamortized concessions. Frank Example signed for the tenant.diff --git a/evals/title-mention/corpus/leases/riverside-warehouse-rent-escalation-schedule.md b/evals/title-mention/corpus/leases/riverside-warehouse-rent-escalation-schedule.mdnew file mode 100644index 0000000000..61d65470ce--- /dev/null+++ b/evals/title-mention/corpus/leases/riverside-warehouse-rent-escalation-schedule.md@@ -0,0 +1,6 @@+---+title: "Riverside Warehouse Rent Escalation Schedule"+type: note+---++This schedule, attached as Exhibit B to the renewed Dock Road lease, lists monthly base rent for each year of the five-year term starting January 1, 2025. Year one is $21,333. Years two through five increase by a fixed 3.25 percent each January, producing $22,026, $22,742, $23,481, and $24,244 respectively. The figures apply to 32,000 square feet of warehouse space and 2,400 square feet of office. Additional rent for taxes and common charges is not included and is billed monthly on an estimated basis, then reconciled each March. If the consumer price index rises more than six percent in any calendar year, the landlord, Tidewater Realty Example, may request a review, but the fixed schedule governs unless both parties sign a written change. A rent abatement of half of month one applies only if the dock repairs finish on time. Prepared by Grace Placeholder in Finance and reviewed by Frank Example for lease compliance.diff --git a/evals/title-mention/corpus/leases/weekly-update.md b/evals/title-mention/corpus/leases/weekly-update.mdnew file mode 100644index 0000000000..69019e1383--- /dev/null+++ b/evals/title-mention/corpus/leases/weekly-update.md@@ -0,0 +1,6 @@+---+title: "Weekly Update"+type: note+---++Real estate team highlights for the week. The landlord for Harbor Street returned the countersigned documents, and the improvement allowance invoices were submitted for repainting and carpet. Brightside Studio Example paid its October rent on the Maple Court sublet, but the deposit receipt is still outstanding. We received a request from the lender's counsel at Cedar Plaza for a tenant certificate and Alice Example is reviewing the draft before signature. At the Dock Road warehouse, roof repairs are scheduled to begin after the rainy season, and the landlord promised a written timeline by Friday. Insurance certificates for two sites expire in thirty days; Ivan Placeholder has contacted the broker. Open risks: a possible dispute over common area charges at one property, and a missing signature page in the file for a parking addendum. Priorities next week: finalize the rent tracker, confirm the sublease consent letter is filed, and prepare a summary of all lease expiration dates for leadership.diff --git a/evals/title-mention/corpus/postmortem/alert-fatigue-paging-review.md b/evals/title-mention/corpus/postmortem/alert-fatigue-paging-review.mdnew file mode 100644index 0000000000..84b0c90a4b--- /dev/null+++ b/evals/title-mention/corpus/postmortem/alert-fatigue-paging-review.md@@ -0,0 +1,6 @@+---+title: "Alert Fatigue Paging Review"+type: note+---++Over the third quarter the on-call rotation received an average of 46 pages per week, and only 18% needed human action. Karen Example analyzed pager data and found that three noisy rules, including the disk usage warning and the cache hit-rate flap, produced more than half of all pages. Engineers reported nearly missing real alerts during the certificate and cache problems because they had started muting notifications at night. Recommendations: convert informational alerts to tickets, require a runbook link on every paging rule, add a five-minute delay for flapping metrics, and review page counts monthly. The team set a goal of under 15 pages per week with at least 60% actionable. Follow-up progress will be reported in weekly updates and reviewed at the next quarterly incident forum.diff --git a/evals/title-mention/corpus/postmortem/cache-cluster-eviction-storm.md b/evals/title-mention/corpus/postmortem/cache-cluster-eviction-storm.mdnew file mode 100644index 0000000000..d4ac0c7944--- /dev/null+++ b/evals/title-mention/corpus/postmortem/cache-cluster-eviction-storm.md@@ -0,0 +1,6 @@+---+title: "Cache Cluster Eviction Storm"+type: note+---++In August the shared cache tier suffered a wave of mass evictions after a deploy raised the default entry size for the product catalog. Memory pressure caused the nodes to evict hot keys, the hit rate dropped from 97% to 41%, and the origin database absorbed several times its normal read load. Grace Example noticed rising query latency on the catalog API and traced it to eviction counters climbing. The team rolled back the serializer change and pre-warmed keys over 25 minutes. No data was lost, but search pages were slow for about an hour. Root cause: no memory headroom alert and no load test with realistic entry sizes. Actions: alert on eviction rate, keep 30% headroom, add entry size limits to code review checks, and stagger cache restarts. Database read replicas held up, unlike during the earlier failover problem.diff --git a/evals/title-mention/corpus/postmortem/certificate-expiry-login-outage.md b/evals/title-mention/corpus/postmortem/certificate-expiry-login-outage.mdnew file mode 100644index 0000000000..73dac6f710--- /dev/null+++ b/evals/title-mention/corpus/postmortem/certificate-expiry-login-outage.md@@ -0,0 +1,6 @@+---+title: "Certificate Expiry Login Outage"+type: note+---++On September 9 at 08:00 UTC the TLS certificate for the internal identity service expired, and every employee and customer login failed with a handshake error. The certificate had been issued manually two years earlier by Henry Example, who had since moved teams, and the renewal reminder went to a mailbox nobody read. Diagnosis took 25 minutes because the errors looked like a network problem in the Harbor Street office. Iris Example issued a replacement certificate and restarted the identity pods; logins recovered at 08:47. Root cause: manual certificate lifecycle with no monitoring on expiry dates. Remediation: inventory all certificates, alert at 30, 14, and 7 days before expiry, and move to automated renewal. The step-by-step procedure was written afterwards as a separate runbook for on-call engineers.diff --git a/evals/title-mention/corpus/postmortem/certificate-expiry-renewal-runbook.md b/evals/title-mention/corpus/postmortem/certificate-expiry-renewal-runbook.mdnew file mode 100644index 0000000000..bf8a65ea3b--- /dev/null+++ b/evals/title-mention/corpus/postmortem/certificate-expiry-renewal-runbook.md@@ -0,0 +1,6 @@+---+title: "Certificate Expiry Renewal Runbook"+type: note+---++Use this procedure when a monitoring alert warns that a TLS certificate will lapse within 30 days, or when a login failure suggests one already has. Step one: identify the certificate in the inventory and confirm its owner. Step two: generate a new key pair and request issuance from the internal authority. Step three: deploy to staging and verify the chain with the standard handshake check. Step four: roll the new certificate to production one region at a time, restarting the identity pods gradually. Step five: confirm the new dates in the dashboard and close the alert. Automated renewal is enabled for most services, but the identity service and legacy billing endpoints still need manual handling. If logins are already failing, page the security on-call, Iris Example, and skip staging only with approval. This document came out of the September review.diff --git a/evals/title-mention/corpus/postmortem/deployment-pipeline-rollback-failure.md b/evals/title-mention/corpus/postmortem/deployment-pipeline-rollback-failure.mdnew file mode 100644index 0000000000..14514c77a1--- /dev/null+++ b/evals/title-mention/corpus/postmortem/deployment-pipeline-rollback-failure.md@@ -0,0 +1,6 @@+---+title: "Deployment Pipeline Rollback Failure"+type: note+---++During the October release the automated rollback for the order service did not work. A bad schema migration made the new version crash, and the pipeline attempted to redeploy the previous image, but the migration had already dropped a column the older code required. Jack Example spent 70 minutes restoring the column from a snapshot before the service recovered. Customers saw errors on order history pages, though new checkouts still worked. Root cause: migrations ran before health checks and were not backward compatible, so reverting was never a safe option. Fixes: adopt expand-and-contract migrations, run schema changes as a separate gated stage, and rehearse rollbacks in staging every release. We also added a pipeline check that blocks column drops in the same release as the code change that stops using them.diff --git a/evals/title-mention/corpus/postmortem/meeting-notes.md b/evals/title-mention/corpus/postmortem/meeting-notes.mdnew file mode 100644index 0000000000..e4e67b32bb--- /dev/null+++ b/evals/title-mention/corpus/postmortem/meeting-notes.md@@ -0,0 +1,6 @@+---+title: "Meeting Notes"+type: note+---++Attendees: Alice Example, Jack Example, Carol Example, Karen Example. Agenda: October release problems and next steps. Jack summarized how the order service could not roll back after a schema migration dropped a column, and how restoring it from a snapshot took 70 minutes. Carol argued that migrations should run as a separate gated stage after health checks. Alice asked whether the revert path in the pipeline had ever been rehearsed; the answer was no. Decisions: adopt expand-and-contract migrations for all services, add a staging rehearsal to the release checklist, and block same-release column drops in the pipeline. Karen mentioned that paging noise during the outage delayed acknowledgement by six minutes. Action items: Jack drafts the migration guideline by Friday, Carol updates the pipeline stages, and Alice schedules a rehearsal for the next release. Next meeting: two weeks from today in the Harbor Street conference room.diff --git a/evals/title-mention/corpus/postmortem/payment-gateway-timeout-incident.md b/evals/title-mention/corpus/postmortem/payment-gateway-timeout-incident.mdnew file mode 100644index 0000000000..312be17f2f--- /dev/null+++ b/evals/title-mention/corpus/postmortem/payment-gateway-timeout-incident.md@@ -0,0 +1,6 @@+---+title: "Payment Gateway Timeout Incident"+type: note+---++On June 3 checkout latency rose sharply when the third-party payment vendor began responding in over 20 seconds. Our client library used a 30-second timeout with three automatic retries, so each stuck request held a worker thread for up to 90 seconds. Within eleven minutes the checkout service exhausted its thread pool and began rejecting all traffic, including carts that never reached payment. Erin Example declared the incident and disabled retries through a feature flag, which restored capacity. Impact lasted 37 minutes and affected about 12% of sessions. Root cause: unbounded retries with no circuit breaker. Fixes: reduce the timeout to five seconds, cap retries at one, add a circuit breaker, and isolate payment calls into their own thread pool. A broader discussion of what the team learned appears in the session held later that month.diff --git a/evals/title-mention/corpus/postmortem/payment-gateway-timeout-retrospective.md b/evals/title-mention/corpus/postmortem/payment-gateway-timeout-retrospective.mdnew file mode 100644index 0000000000..d8bacbe40f--- /dev/null+++ b/evals/title-mention/corpus/postmortem/payment-gateway-timeout-retrospective.md@@ -0,0 +1,6 @@+---+title: "Payment Gateway Timeout Retrospective"+type: note+---++Held on June 20 with Erin Example facilitating, this session looked back at the June checkout slowdown caused by the payment vendor. Participants said the on-call engineer spent eight minutes finding the right dashboard, because gateway latency was not on the main checkout board. We agreed to add p99 vendor latency panels and a synthetic payment probe. Frank Example pointed out that the vendor status page was updated 25 minutes late, so we should not rely on it. What went well: the feature flag worked quickly and communication with support was clear. What went poorly: nobody owned the retry configuration. Decisions: assign retry settings to the checkout team, run a quarterly game day simulating vendor slowness, and add a circuit breaker template to the service starter kit. The technical timeline and metrics live in the original incident report.diff --git a/evals/title-mention/corpus/postmortem/primary-database-failover-followup.md b/evals/title-mention/corpus/postmortem/primary-database-failover-followup.mdnew file mode 100644index 0000000000..dd342b1d23--- /dev/null+++ b/evals/title-mention/corpus/postmortem/primary-database-failover-followup.md@@ -0,0 +1,6 @@+---+title: "Primary Database Failover Followup"+type: note+---++This review tracks the action items that came out of the March database failover. Carol Example owns the failover controller change so that promotion is blocked when replication lag exceeds 60 seconds; it shipped in release 4.12. Dan Example reduced the replication lag alert from thirty minutes to five and verified it in a staging drill. The batch job scheduler now defers heavy jobs whenever a replica is behind. Two items remain open: a quarterly failover drill on the Harbor Street cluster, and a runbook rewrite covering manual promotion. We also measured a second drill in April: automatic failover completed in 22 seconds with zero failed requests. The original timeline, customer impact figures, and root cause analysis are in the earlier outage write-up, so this page only covers remediation status, owners, and due dates.diff --git a/evals/title-mention/corpus/postmortem/primary-database-failover-outage.md b/evals/title-mention/corpus/postmortem/primary-database-failover-outage.mdnew file mode 100644index 0000000000..dc8ee258ef--- /dev/null+++ b/evals/title-mention/corpus/postmortem/primary-database-failover-outage.md@@ -0,0 +1,6 @@+---+title: "Primary Database Failover Outage"+type: note+---++On March 14 at 02:10 UTC the primary database node in the Harbor Street data center lost its storage volume. Automatic failover to the replica was expected to finish within 30 seconds, but the replica lagged by 41 minutes because a long-running batch job started by Bob Example had saturated replication. Orders and login requests returned errors for 52 minutes. Engineers led by Alice Example promoted the replica manually after confirming the lag had cleared, then rebuilt the old primary as a new replica. Customer impact was roughly 8,400 failed checkouts. Root cause: the failover controller did not check replication lag before promotion, and the paging rule for lag only fired after 30 minutes. Immediate fixes: lower the lag alert threshold to five minutes and pause batch jobs during failover drills. Detailed action items and owners are tracked separately in the followup review.diff --git a/evals/title-mention/corpus/postmortem/status-report.md b/evals/title-mention/corpus/postmortem/status-report.mdnew file mode 100644index 0000000000..1a179752f8--- /dev/null+++ b/evals/title-mention/corpus/postmortem/status-report.md@@ -0,0 +1,6 @@+---+title: "Status Report"+type: note+---++Checkout resilience workstream, status as of the end of June. Green: the retry cap and five-second timeout shipped to production on June 10. The circuit breaker library is integrated in staging, with production rollout planned for next Tuesday. The synthetic payment probe is deployed and alerting to the checkout channel. Yellow: vendor latency dashboard panels are half built because the metrics exporter needs a schema change. Red: none. Owner Erin Example confirmed that retry configuration now lives in the checkout repository with named reviewers. Metrics: checkout error rate averaged 0.3% over the last two weeks, down from 1.1%. Upcoming: a game day simulating vendor slowness in July, and a review of thread pool isolation for refund calls. Dependencies: the platform team must approve the exporter change. Escalations: none needed at this time. Report prepared by Frank Example.diff --git a/evals/title-mention/corpus/postmortem/weekly-update.md b/evals/title-mention/corpus/postmortem/weekly-update.mdnew file mode 100644index 0000000000..4cf5948148--- /dev/null+++ b/evals/title-mention/corpus/postmortem/weekly-update.md@@ -0,0 +1,6 @@+---+title: "Weekly Update"+type: note+---++Highlights for the week ending October 18. Cache: the eviction rate alert is now live on the shared cluster, and headroom is holding at 32% after we raised node memory. Entry size checks are in code review for catalog changes. Certificates: the inventory is 80% complete, with 14 certificates flagged for automated renewal and two legacy billing endpoints still manual. Database: the quarterly failover drill is scheduled for November, and the lag alert stayed quiet all week. Paging: weekly pages fell to 31 from 46 after three noisy rules were converted to tickets. Risks: the migration guideline is late by a few days, and Dan Example is out next week. Next week: finish the certificate inventory, publish the guideline, and review the vendor latency dashboard with the checkout team.diff --git a/evals/title-mention/corpus/product/beacon-dock-power-design-doc.md b/evals/title-mention/corpus/product/beacon-dock-power-design-doc.mdnew file mode 100644index 0000000000..e1b2c0acc1--- /dev/null+++ b/evals/title-mention/corpus/product/beacon-dock-power-design-doc.md@@ -0,0 +1,6 @@+---+title: "Beacon Dock Power Design Doc"+type: note+---++The Beacon dock charges four handheld scanners at once from a single 65 W supply. Each bay has a dedicated charging rail rated at 12 W, with current limiting and a thermal cutoff at 60 degrees Celsius. Input is 100-240 V AC through a detachable cord. A power-path controller shares the budget: when all four bays are charging, each receives 12 W, and idle bays release budget to the others up to 20 W per bay. The efficiency target is 88 percent at full load, with standby draw under 0.3 W. Known issue: rail three shows a voltage sag of 0.4 V when a fast-charge scanner is docked alongside three others; this is tracked for the next board revision. Electrical design by Dan Prototype, reviewed by Erin Sample. Fan curves and enclosure venting are handled in a separate companion document.diff --git a/evals/title-mention/corpus/product/beacon-dock-thermal-design-doc.md b/evals/title-mention/corpus/product/beacon-dock-thermal-design-doc.mdnew file mode 100644index 0000000000..ea71a67b0c--- /dev/null+++ b/evals/title-mention/corpus/product/beacon-dock-thermal-design-doc.md@@ -0,0 +1,6 @@+---+title: "Beacon Dock Thermal Design Doc"+type: note+---++This document covers cooling for the four-bay Beacon dock. The enclosure is passively cooled up to 25 W total dissipation, with a single 40 mm fan enabled above 35 degrees Celsius measured at the board sensor. Fan curve: 30 percent duty at 35 C, 60 percent at 45 C, and 100 percent at 55 C. Vent slots on the rear and base are 2 mm wide to meet finger-safety rules. Chamber testing at 40 C ambient with four scanners fast-charging showed a peak bay temperature of 52 C, under the 60 C cutoff. The noise target is below 32 dBA at one meter. Thermal pads between the power stage and the aluminum plate are 1.5 mm thick. Open item: dust ingress test on the fan intake. Author: Erin Sample. Reviewer: Dan Prototype. The supply budget and charging rails are described in the companion power document.diff --git a/evals/title-mention/corpus/product/falcon-sensor-hub-spec-v1.md b/evals/title-mention/corpus/product/falcon-sensor-hub-spec-v1.mdnew file mode 100644index 0000000000..e93447dd21--- /dev/null+++ b/evals/title-mention/corpus/product/falcon-sensor-hub-spec-v1.md@@ -0,0 +1,6 @@+---+title: "Falcon Sensor Hub Spec v1"+type: note+---++This specification defines the first production release of the Falcon hub, a wall-mounted unit that aggregates temperature, humidity, and motion readings from up to 16 wireless sensors. The hub uses a dual-core microcontroller with 512 KB of flash and 128 KB of RAM. Sampling rate is fixed at one reading per 60 seconds per sensor, and data is buffered locally for up to 48 hours during network outages. The radio is sub-gigahertz with a rated indoor range of 40 meters. Power comes from a 5 V adapter, with a coin-cell backup that keeps the clock alive for 30 days. The enclosure is white polycarbonate, 90 by 90 by 25 millimeters. Firmware updates are delivered over Ethernet only. Known limitations: no encryption of the sensor link beyond a single shared key, and no support for battery-free sensors. Owner: Alice Example. Reviewers: Bob Sample and Carol Placeholder. Approved for the pilot build in the Harbor Street lab.diff --git a/evals/title-mention/corpus/product/falcon-sensor-hub-spec-v2.md b/evals/title-mention/corpus/product/falcon-sensor-hub-spec-v2.mdnew file mode 100644index 0000000000..f051021023--- /dev/null+++ b/evals/title-mention/corpus/product/falcon-sensor-hub-spec-v2.md@@ -0,0 +1,6 @@+---+title: "Falcon Sensor Hub Spec v2"+type: note+---++This revision replaces the earlier hub specification and raises capacity to 32 wireless sensors. Sampling rate is now configurable from one reading per 5 seconds to one per 300 seconds, with a default of 30 seconds. Local buffering extends to 96 hours using 8 MB of external flash. The sub-gigahertz radio gains per-device AES-128 keys, replacing the shared key used in v1. Firmware updates can now be delivered over Ethernet or wirelessly, using signed images and automatic rollback if the new image fails to boot. The microcontroller is unchanged, but RAM grows to 256 KB. Enclosure dimensions become 90 by 90 by 28 millimeters to fit the added antenna. The backup coin cell is retained. Battery-free sensors remain out of scope. Owner: Alice Example. Reviewers: Bob Sample and Carol Placeholder. Target pilot build: second quarter, in the Harbor Street lab, with the same sensor family as the first release.diff --git a/evals/title-mention/corpus/product/lantern-mobile-app-release-checklist.md b/evals/title-mention/corpus/product/lantern-mobile-app-release-checklist.mdnew file mode 100644index 0000000000..163b273c24--- /dev/null+++ b/evals/title-mention/corpus/product/lantern-mobile-app-release-checklist.md@@ -0,0 +1,6 @@+---+title: "Lantern Mobile App Release Checklist"+type: note+---++Steps to complete before each Lantern app release goes to the stores. 1. Freeze the release branch and confirm all requirement tickets are closed or deferred. 2. Run the full automated suite on three reference devices, including one low-memory phone. 3. Verify push alerts arrive within 10 seconds against the staging hub. 4. Check that cold start is under 2.5 seconds. 5. Confirm the accessibility audit passes with large text and a screen reader. 6. Update the version number, changelog, and privacy disclosure. 7. Get sign-off from Frank Placeholder and Grace Example. 8. Submit for store review at least five business days before the planned date. 9. Stage the rollout at 5, 25, then 100 percent, watching that the crash-free rate stays above 99.5 percent. 10. Archive build artifacts and symbols. Rollback owner: Henry Sample.diff --git a/evals/title-mention/corpus/product/lantern-mobile-app-requirements.md b/evals/title-mention/corpus/product/lantern-mobile-app-requirements.mdnew file mode 100644index 0000000000..58dad9f16f--- /dev/null+++ b/evals/title-mention/corpus/product/lantern-mobile-app-requirements.md@@ -0,0 +1,6 @@+---+title: "Lantern Mobile App Requirements"+type: note+---++Product requirements for the Lantern phone application, which lets warehouse staff view sensor alerts and dock status. It must support the two latest major versions of both mobile operating systems. Core features: push alerts within 10 seconds of a hub event, a floor map showing sensor locations, acknowledgement of an alert with a single tap, and offline viewing of the last 24 hours of readings. Login uses company single sign-on with optional biometric unlock. Accessibility: all screens must support large text and screen readers. Performance: cold start under 2.5 seconds on a mid-range device. Out of scope for the first release: editing hub settings and dark mode. Product owner: Frank Placeholder. Engineering lead: Grace Example. Open question: whether alerts from the newer hub should display per-device battery levels alongside the sensor name and floor location.diff --git a/evals/title-mention/corpus/product/meeting-notes.md b/evals/title-mention/corpus/product/meeting-notes.mdnew file mode 100644index 0000000000..facb0c218e--- /dev/null+++ b/evals/title-mention/corpus/product/meeting-notes.md@@ -0,0 +1,6 @@+---+title: "Meeting Notes"+type: note+---++Attendees: Liam Example, Maya Placeholder, and Nina Sample. Topic: shrinking the retail carton for the dock and hub. Liam presented drop-test results: the pulp trays passed five of six faces but failed the corner drop from 1.0 meter. Maya asked for a supplier quote for thicker corner pieces. The group agreed to keep the QR code plus fold card instead of the printed guide. Nina flagged that the smaller carton must still fit four scanner cables in the accessory bag. Action items: Liam to rerun drop tests with reinforced corners by the end of next week; Maya to obtain tooling quotes from two suppliers; Nina to confirm the accessory bag dimensions. The decision on the final carton size was deferred to the next session, pending the new test data and the cost comparison against the foam insert design.diff --git a/evals/title-mention/corpus/product/project-plan.md b/evals/title-mention/corpus/product/project-plan.mdnew file mode 100644index 0000000000..3378d4353f--- /dev/null+++ b/evals/title-mention/corpus/product/project-plan.md@@ -0,0 +1,6 @@+---+title: "Project Plan"+type: note+---++Goal: ship the first Lantern app release to both stores by the end of the quarter. Phase one, weeks 1-3: finalize requirements with Frank Placeholder and lock the alert payload format with the hub team. Phase two, weeks 4-8: build the alert feed, floor map, and offline cache; Grace Example leads a team of four engineers. Phase three, weeks 9-10: accessibility audit, performance tuning, and a beta with 20 warehouse staff. Phase four, weeks 11-12: store submission and staged rollout. Dependencies: hub firmware exposing per-device alerts, a single sign-on test tenant, and design assets from Olivia Sample. Risks: store review delays and late changes to the alert format. Weekly demos are held on Thursdays. Exit criteria: crash-free rate above 99.5 percent during the beta period, and no open accessibility defects.diff --git a/evals/title-mention/corpus/product/quartz-display-panel-calibration-guide.md b/evals/title-mention/corpus/product/quartz-display-panel-calibration-guide.mdnew file mode 100644index 0000000000..bf87ef4528--- /dev/null+++ b/evals/title-mention/corpus/product/quartz-display-panel-calibration-guide.md@@ -0,0 +1,6 @@+---+title: "Quartz Display Panel Calibration Guide"+type: note+---++Procedure for calibrating each Quartz screen after it passes incoming inspection. Warm the panel for 20 minutes at full brightness. Place the colorimeter at the center point and measure white, red, green, blue, and five gray levels. The target white point is 6500 K with delta-E below 3. Write the 256-entry gamma table to the panel controller through the service cable, then remeasure at nine points. If uniformity falls under 85 percent, apply the compensation map and repeat once; a second failure sends the unit to rework. Touch calibration uses a five-point grid with 1.5 mm tolerance. Record the serial number, results, and operator in the production log. The fixture is maintained by Jack Example, and the colorimeter is recalibrated every six months by Kara Sample. Sampling, burn-in, and environmental tests for incoming lots are covered elsewhere.diff --git a/evals/title-mention/corpus/product/quartz-display-panel-test-plan.md b/evals/title-mention/corpus/product/quartz-display-panel-test-plan.mdnew file mode 100644index 0000000000..117ee9f06c--- /dev/null+++ b/evals/title-mention/corpus/product/quartz-display-panel-test-plan.md@@ -0,0 +1,6 @@+---+title: "Quartz Display Panel Test Plan"+type: note+---++Test approach for the 7-inch Quartz screen used on the dock and hub fronts. Incoming inspection samples 32 panels from each lot of 1,000. Tests: brightness uniformity above 85 percent across nine points, minimum brightness of 450 nits, a dead pixel limit of zero in the central zone and two elsewhere, touch accuracy within 1.5 mm, and a 500-hour burn-in at 50 C. Environmental tests: thermal shock between -10 and 60 C for 50 cycles, and exposure to 85 percent humidity for 96 hours. A failure rate above 3 percent triggers lot rejection and notice to the supplier contact, Ivy Placeholder. Testing takes place in the Harbor Street lab. Owner: Jack Example. Color tuning for panels that pass is handled in a separate calibration procedure.diff --git a/evals/title-mention/corpus/product/status-report.md b/evals/title-mention/corpus/product/status-report.mdnew file mode 100644index 0000000000..b6fda05b2e--- /dev/null+++ b/evals/title-mention/corpus/product/status-report.md@@ -0,0 +1,6 @@+---+title: "Status Report"+type: note+---++Reporting period: the last two weeks. Overall status: yellow. Board revision B of the four-bay dock arrived and bring-up is complete. The voltage sag on charging rail three persists at 0.3 V, improved from 0.4 V after swapping the sense resistor; a layout change is proposed for revision C. The fan intake dust test is scheduled for next week. First shots from the enclosure tooling are due in ten days. Risks: supplier lead time for the power-path controller has slipped to 14 weeks; mitigation is buying a bridge lot of 500 units. Next milestones: revision C schematic review with Dan Prototype and Erin Sample, a chamber retest at 40 C, and a safety pre-scan. Budget is on track, with 4 percent of contingency used so far and no change to the launch date.diff --git a/evals/title-mention/corpus/product/widget-packaging-redesign-proposal.md b/evals/title-mention/corpus/product/widget-packaging-redesign-proposal.mdnew file mode 100644index 0000000000..58da47dba4--- /dev/null+++ b/evals/title-mention/corpus/product/widget-packaging-redesign-proposal.md@@ -0,0 +1,6 @@+---+title: "Widget Packaging Redesign Proposal"+type: note+---++Proposal to shrink and simplify retail packaging for the dock and hub. The current carton measures 320 by 240 by 110 mm and uses molded foam inserts. The new design uses a 260 by 200 by 95 mm carton with recycled pulp trays, cutting volume by about 32 percent and reducing pallet count per shipment by one fifth. Drop tests from 1.0 meter on all six faces must pass with no cosmetic damage. Estimated unit cost falls by 0.42 dollars, with a one-time tooling charge of 18,000 dollars that is paid back in about seven months at forecast volume. The printed quick-start guide is replaced with a QR code plus a single fold card. Proposed by Liam Example, pending review by Maya Placeholder. A decision is needed before the second-quarter pilot build so that tooling can be ordered in time.diff --git a/evals/title-mention/queries.jsonl b/evals/title-mention/queries.jsonlnew file mode 100644index 0000000000..1ae8357cbb--- /dev/null+++ b/evals/title-mention/queries.jsonl@@ -0,0 +1,144 @@+{"family": "title-substring", "query": "Harbor Street Lease Amendment", "relevant": ["leases/harbor-street-lease-amendment"]}+{"family": "question-wrapped-title", "query": "Which document is Harbor Street Lease Amendment?", "relevant": ["leases/harbor-street-lease-amendment"]}+{"family": "long-form-wrapper", "query": "Where can I find the Harbor Street Lease Amendment that extended the term and added parking spaces for our office floors?", "relevant": ["leases/harbor-street-lease-amendment"]}+{"family": "title-substring", "query": "Maple Court Sublease Agreement", "relevant": ["leases/maple-court-sublease-agreement"]}+{"family": "question-wrapped-title", "query": "Which document is Maple Court Sublease Agreement?", "relevant": ["leases/maple-court-sublease-agreement"]}+{"family": "long-form-wrapper", "query": "Can you show me the Maple Court Sublease Agreement with the subtenant rent, deposit, and the master landlord's consent details?", "relevant": ["leases/maple-court-sublease-agreement"]}+{"family": "title-substring", "query": "Riverside Warehouse Lease Renewal", "relevant": ["leases/riverside-warehouse-lease-renewal"]}+{"family": "question-wrapped-title", "query": "Which document is Riverside Warehouse Lease Renewal?", "relevant": ["leases/riverside-warehouse-lease-renewal"]}+{"family": "long-form-wrapper", "query": "What are the new five-year term, roof repair commitments, and early termination right in the Riverside Warehouse Lease Renewal for Dock Road?", "relevant": ["leases/riverside-warehouse-lease-renewal"]}+{"family": "title-substring", "query": "Cedar Plaza Retail Lease", "relevant": ["leases/cedar-plaza-retail-lease"]}+{"family": "question-wrapped-title", "query": "Which document is Cedar Plaza Retail Lease?", "relevant": ["leases/cedar-plaza-retail-lease"]}+{"family": "long-form-wrapper", "query": "Where is the Cedar Plaza Retail Lease that describes percentage rent, the co-tenancy clause, and the showroom's radius restriction?", "relevant": ["leases/cedar-plaza-retail-lease"]}+{"family": "title-substring", "query": "Cedar Plaza Estoppel Certificate", "relevant": ["leases/cedar-plaza-estoppel-certificate"]}+{"family": "question-wrapped-title", "query": "Which document is Cedar Plaza Estoppel Certificate?", "relevant": ["leases/cedar-plaza-estoppel-certificate"]}+{"family": "long-form-wrapper", "query": "Which file is the Cedar Plaza Estoppel Certificate we signed for the lender during the landlord's refinancing last spring?", "relevant": ["leases/cedar-plaza-estoppel-certificate"]}+{"family": "title-substring", "query": "Landlord Insurance Requirements Memo", "relevant": ["leases/landlord-insurance-requirements-memo"]}+{"family": "question-wrapped-title", "query": "Which document is Landlord Insurance Requirements Memo?", "relevant": ["leases/landlord-insurance-requirements-memo"]}+{"family": "long-form-wrapper", "query": "I need the Landlord Insurance Requirements Memo that lists liability limits, umbrella coverage, and certificate deadlines for each of our leased locations.", "relevant": ["leases/landlord-insurance-requirements-memo"]}+{"family": "mention-other-gold", "query": "Which amendment changed the rent and term originally set in the Harbor Street Lease Agreement?", "relevant": ["leases/harbor-street-lease-amendment"]}+{"family": "mention-other-gold", "query": "The Weekly Update flagged the sublease consent for the second-floor subtenant; where are the actual sublease terms and subtenant rent recorded?", "relevant": ["leases/maple-court-sublease-agreement"]}+{"family": "mention-other-gold", "query": "Which schedule lists the fixed yearly rent increases that apply after the Riverside Warehouse Lease Renewal took effect?", "relevant": ["leases/riverside-warehouse-rent-escalation-schedule"]}+{"family": "mention-other-gold", "query": "Which certificate confirms rent paid and no defaults for the landlord's lender under the Cedar Plaza Retail Lease?", "relevant": ["leases/cedar-plaza-estoppel-certificate"]}+{"family": "mention-other-gold", "query": "Which document lists the coverage limits behind the higher insurance premium line item discussed in the Budget Review?", "relevant": ["leases/landlord-insurance-requirements-memo"]}+{"family": "mention-other-gold", "query": "Which master lease sits above the Maple Court Sublease Agreement and sets the base rent and annual increases Acme pays?", "relevant": ["leases/maple-court-office-lease"]}+{"family": "title-substring", "query": "Falcon Sensor Hub Spec v1", "relevant": ["product/falcon-sensor-hub-spec-v1"]}+{"family": "question-wrapped-title", "query": "Which document is Falcon Sensor Hub Spec v1?", "relevant": ["product/falcon-sensor-hub-spec-v1"]}+{"family": "long-form-wrapper", "query": "Can you find the Falcon Sensor Hub Spec v1 that describes the first pilot hub with fixed sixty-second sampling and a shared radio key?", "relevant": ["product/falcon-sensor-hub-spec-v1"]}+{"family": "title-substring", "query": "Falcon Sensor Hub Spec v2", "relevant": ["product/falcon-sensor-hub-spec-v2"]}+{"family": "question-wrapped-title", "query": "Which document is Falcon Sensor Hub Spec v2?", "relevant": ["product/falcon-sensor-hub-spec-v2"]}+{"family": "long-form-wrapper", "query": "I need the Falcon Sensor Hub Spec v2 covering configurable sampling, per-device encryption keys, and the larger 32 sensor capacity for the pilot.", "relevant": ["product/falcon-sensor-hub-spec-v2"]}+{"family": "title-substring", "query": "Beacon Dock Power Design Doc", "relevant": ["product/beacon-dock-power-design-doc"]}+{"family": "question-wrapped-title", "query": "Which document is Beacon Dock Power Design Doc?", "relevant": ["product/beacon-dock-power-design-doc"]}+{"family": "long-form-wrapper", "query": "Where can I read the Beacon Dock Power Design Doc about the four-bay charging rails and the voltage sag issue on rail three?", "relevant": ["product/beacon-dock-power-design-doc"]}+{"family": "title-substring", "query": "Beacon Dock Thermal Design Doc", "relevant": ["product/beacon-dock-thermal-design-doc"]}+{"family": "question-wrapped-title", "query": "Which document is Beacon Dock Thermal Design Doc?", "relevant": ["product/beacon-dock-thermal-design-doc"]}+{"family": "long-form-wrapper", "query": "Please point me to the Beacon Dock Thermal Design Doc that lists the fan curve and vent slot dimensions for the four-bay charger.", "relevant": ["product/beacon-dock-thermal-design-doc"]}+{"family": "title-substring", "query": "Lantern Mobile App Requirements", "relevant": ["product/lantern-mobile-app-requirements"]}+{"family": "question-wrapped-title", "query": "Which document is Lantern Mobile App Requirements?", "relevant": ["product/lantern-mobile-app-requirements"]}+{"family": "long-form-wrapper", "query": "Which team owns the Lantern Mobile App Requirements covering push alerts, offline viewing, and single sign-on for warehouse staff?", "relevant": ["product/lantern-mobile-app-requirements"]}+{"family": "title-substring", "query": "Quartz Display Panel Test Plan", "relevant": ["product/quartz-display-panel-test-plan"]}+{"family": "question-wrapped-title", "query": "Which document is Quartz Display Panel Test Plan?", "relevant": ["product/quartz-display-panel-test-plan"]}+{"family": "long-form-wrapper", "query": "Show me the Quartz Display Panel Test Plan with the incoming inspection sample size, burn-in hours, and dead pixel limits.", "relevant": ["product/quartz-display-panel-test-plan"]}+{"family": "mention-other-gold", "query": "Which specification superseded the Falcon Sensor Hub Spec v1 and raised the sampling flexibility and sensor capacity?", "relevant": ["product/falcon-sensor-hub-spec-v2"]}+{"family": "mention-other-gold", "query": "Which document covers fan curves and venting, as opposed to the Beacon Dock Power Design Doc that covers charging rails?", "relevant": ["product/beacon-dock-thermal-design-doc"]}+{"family": "mention-other-gold", "query": "Where are the color and gamma calibration steps for panels that pass the Quartz Display Panel Test Plan?", "relevant": ["product/quartz-display-panel-calibration-guide"]}+{"family": "mention-other-gold", "query": "Which design document explains the charging rail three voltage sag mentioned in the Status Report?", "relevant": ["product/beacon-dock-power-design-doc"]}+{"family": "mention-other-gold", "query": "Which checklist should be followed before shipping the app release scheduled in the Project Plan?", "relevant": ["product/lantern-mobile-app-release-checklist"]}+{"family": "mention-other-gold", "query": "Which proposal was discussed in the Meeting Notes about shrinking the carton and using pulp trays?", "relevant": ["product/widget-packaging-redesign-proposal"]}+{"family": "title-substring", "query": "Senior Backend Engineer Role Description", "relevant": ["hiring/senior-backend-engineer-role-description"]}+{"family": "question-wrapped-title", "query": "Which document is Senior Backend Engineer Role Description?", "relevant": ["hiring/senior-backend-engineer-role-description"]}+{"family": "long-form-wrapper", "query": "Where can I find the Senior Backend Engineer Role Description that lists the level, salary band, and required qualifications for the Platform group?", "relevant": ["hiring/senior-backend-engineer-role-description"]}+{"family": "title-substring", "query": "Senior Backend Engineer Hiring Plan", "relevant": ["hiring/senior-backend-engineer-hiring-plan"]}+{"family": "question-wrapped-title", "query": "Which document is Senior Backend Engineer Hiring Plan?", "relevant": ["hiring/senior-backend-engineer-hiring-plan"]}+{"family": "long-form-wrapper", "query": "Can you point me to the Senior Backend Engineer Hiring Plan that describes interview stages, sourcing channels, and target start dates for the two openings?", "relevant": ["hiring/senior-backend-engineer-hiring-plan"]}+{"family": "title-substring", "query": "Support Team Headcount Plan FY25", "relevant": ["hiring/support-team-headcount-plan-fy25"]}+{"family": "question-wrapped-title", "query": "Which document is Support Team Headcount Plan FY25?", "relevant": ["hiring/support-team-headcount-plan-fy25"]}+{"family": "long-form-wrapper", "query": "I need the original Support Team Headcount Plan FY25 showing the first approved hiring waves and the incremental cost of 412,000 for the support agents.", "relevant": ["hiring/support-team-headcount-plan-fy25"]}+{"family": "title-substring", "query": "Support Team Headcount Plan Amendment", "relevant": ["hiring/support-team-headcount-plan-amendment"]}+{"family": "question-wrapped-title", "query": "Which document is Support Team Headcount Plan Amendment?", "relevant": ["hiring/support-team-headcount-plan-amendment"]}+{"family": "long-form-wrapper", "query": "Where is the Support Team Headcount Plan Amendment that moved the tier-two specialist to April and raised the cost to 431,500?", "relevant": ["hiring/support-team-headcount-plan-amendment"]}+{"family": "title-substring", "query": "Data Analyst Role Description", "relevant": ["hiring/data-analyst-role-description"]}+{"family": "question-wrapped-title", "query": "Which document is Data Analyst Role Description?", "relevant": ["hiring/data-analyst-role-description"]}+{"family": "long-form-wrapper", "query": "Where can I read the Data Analyst Role Description for the Finance and Operations group, including required experience and the salary band?", "relevant": ["hiring/data-analyst-role-description"]}+{"family": "title-substring", "query": "Engineering Referral Bonus Policy", "relevant": ["hiring/engineering-referral-bonus-policy"]}+{"family": "question-wrapped-title", "query": "Which document is Engineering Referral Bonus Policy?", "relevant": ["hiring/engineering-referral-bonus-policy"]}+{"family": "long-form-wrapper", "query": "What are the payout amounts and eligibility exclusions described in the Engineering Referral Bonus Policy for employees who refer hired candidates?", "relevant": ["hiring/engineering-referral-bonus-policy"]}+{"family": "mention-other-gold", "query": "Which amendment superseded the Support Team Headcount Plan FY25 numbers for the tier-two specialist and weekend shift?", "relevant": ["hiring/support-team-headcount-plan-amendment"]}+{"family": "mention-other-gold", "query": "Which document gives the interview stages and target time to offer for the openings covered by the Senior Backend Engineer Role Description?", "relevant": ["hiring/senior-backend-engineer-hiring-plan"]}+{"family": "mention-other-gold", "query": "Which document covers referral payouts, unlike the Contractor Conversion Guidelines, which apply to contractors moving onto payroll?", "relevant": ["hiring/engineering-referral-bonus-policy"]}+{"family": "mention-other-gold", "query": "Which guidelines did the group ask Erin Demo to check in the Meeting Notes before converting two long-serving contractors?", "relevant": ["hiring/contractor-conversion-guidelines"]}+{"family": "mention-other-gold", "query": "Where is the recruiter salary band and placement bonus explained that is funded in the Budget Review?", "relevant": ["hiring/harbor-street-recruiter-job-description"]}+{"family": "mention-other-gold", "query": "Which position do candidates get scored for with the Data Analyst Interview Rubric, and where are its duties listed?", "relevant": ["hiring/data-analyst-role-description"]}+{"family": "title-substring", "query": "Harbor Street Lease Amendment", "relevant": ["finance/harbor-street-lease-amendment"]}+{"family": "question-wrapped-title", "query": "Which document is Harbor Street Lease Amendment?", "relevant": ["finance/harbor-street-lease-amendment"]}+{"family": "long-form-wrapper", "query": "Where can I find the Harbor Street Lease Amendment that changed the monthly rent and added the third floor to our headquarters?", "relevant": ["finance/harbor-street-lease-amendment"]}+{"family": "title-substring", "query": "Harbor Street Lease Agreement", "relevant": ["finance/harbor-street-lease-agreement"]}+{"family": "question-wrapped-title", "query": "Which document is Harbor Street Lease Agreement?", "relevant": ["finance/harbor-street-lease-agreement"]}+{"family": "long-form-wrapper", "query": "Can you show me the Harbor Street Lease Agreement with the original five-year term, base rent, and early termination option?", "relevant": ["finance/harbor-street-lease-agreement"]}+{"family": "title-substring", "query": "Widget Pricing Review Q3", "relevant": ["finance/widget-pricing-review-q3"]}+{"family": "question-wrapped-title", "query": "Which document is Widget Pricing Review Q3?", "relevant": ["finance/widget-pricing-review-q3"]}+{"family": "long-form-wrapper", "query": "I need the Widget Pricing Review Q3 that shows the new Standard Widget list price and the projected revenue impact.", "relevant": ["finance/widget-pricing-review-q3"]}+{"family": "title-substring", "query": "Widget Pricing Review Q2", "relevant": ["finance/widget-pricing-review-q2"]}+{"family": "question-wrapped-title", "query": "Which document is Widget Pricing Review Q2?", "relevant": ["finance/widget-pricing-review-q2"]}+{"family": "long-form-wrapper", "query": "Where is the Widget Pricing Review Q2 that benchmarked our prices against three competitors and left Deluxe pricing unchanged?", "relevant": ["finance/widget-pricing-review-q2"]}+{"family": "title-substring", "query": "Q3 Marketing Budget Variance", "relevant": ["finance/q3-marketing-budget-variance"]}+{"family": "question-wrapped-title", "query": "Which document is Q3 Marketing Budget Variance?", "relevant": ["finance/q3-marketing-budget-variance"]}+{"family": "long-form-wrapper", "query": "Please find the Q3 Marketing Budget Variance report explaining the trade show overspend and the proposed transfer from the brand campaign.", "relevant": ["finance/q3-marketing-budget-variance"]}+{"family": "title-substring", "query": "Travel Expense Policy Update", "relevant": ["finance/travel-expense-policy-update"]}+{"family": "question-wrapped-title", "query": "Which document is Travel Expense Policy Update?", "relevant": ["finance/travel-expense-policy-update"]}+{"family": "long-form-wrapper", "query": "Where can I read the Travel Expense Policy Update covering per diem caps, hotel limits, and advance airfare booking rules?", "relevant": ["finance/travel-expense-policy-update"]}+{"family": "mention-other-gold", "query": "Which amendment superseded the Harbor Street Lease Agreement and raised the monthly rent?", "relevant": ["finance/harbor-street-lease-amendment"]}+{"family": "mention-other-gold", "query": "What does the Weekly Update say is pending before the Riverside Road warehouse renewal can be signed?", "relevant": ["finance/riverside-warehouse-lease-renewal"]}+{"family": "mention-other-gold", "query": "Which policy document sets the per diem cap that was discussed in the Meeting Notes?", "relevant": ["finance/travel-expense-policy-update"]}+{"family": "mention-other-gold", "query": "Which document holds the earlier Standard Widget price of $48 that preceded the Widget Pricing Review Q3 increase?", "relevant": ["finance/widget-pricing-review-q2"]}+{"family": "mention-other-gold", "query": "Which document lists the hardware test bench purchase that the Budget Review suggested deferring?", "relevant": ["finance/capital-equipment-purchase-forecast"]}+{"family": "mention-other-gold", "query": "Which variance report covers cloud hosting overruns, as opposed to the Q3 Marketing Budget Variance?", "relevant": ["finance/q3-engineering-budget-variance"]}+{"family": "title-substring", "query": "Primary Database Failover Outage", "relevant": ["postmortem/primary-database-failover-outage"]}+{"family": "question-wrapped-title", "query": "Which document is Primary Database Failover Outage?", "relevant": ["postmortem/primary-database-failover-outage"]}+{"family": "long-form-wrapper", "query": "Can you find the Primary Database Failover Outage write-up describing the March replication lag and the manual promotion led by Alice Example?", "relevant": ["postmortem/primary-database-failover-outage"]}+{"family": "title-substring", "query": "Payment Gateway Timeout Incident", "relevant": ["postmortem/payment-gateway-timeout-incident"]}+{"family": "question-wrapped-title", "query": "Which document is Payment Gateway Timeout Incident?", "relevant": ["postmortem/payment-gateway-timeout-incident"]}+{"family": "long-form-wrapper", "query": "Where can I read the Payment Gateway Timeout Incident report covering the exhausted thread pool and unbounded retries during checkout in June?", "relevant": ["postmortem/payment-gateway-timeout-incident"]}+{"family": "title-substring", "query": "Cache Cluster Eviction Storm", "relevant": ["postmortem/cache-cluster-eviction-storm"]}+{"family": "question-wrapped-title", "query": "Which document is Cache Cluster Eviction Storm?", "relevant": ["postmortem/cache-cluster-eviction-storm"]}+{"family": "long-form-wrapper", "query": "Which postmortem describes the Cache Cluster Eviction Storm in August when the hit rate dropped after a serializer change increased catalog entry sizes?", "relevant": ["postmortem/cache-cluster-eviction-storm"]}+{"family": "title-substring", "query": "Certificate Expiry Login Outage", "relevant": ["postmortem/certificate-expiry-login-outage"]}+{"family": "question-wrapped-title", "query": "Which document is Certificate Expiry Login Outage?", "relevant": ["postmortem/certificate-expiry-login-outage"]}+{"family": "long-form-wrapper", "query": "I need the analysis of the Certificate Expiry Login Outage in September where the identity service handshake failed for employees and customers alike.", "relevant": ["postmortem/certificate-expiry-login-outage"]}+{"family": "title-substring", "query": "Deployment Pipeline Rollback Failure", "relevant": ["postmortem/deployment-pipeline-rollback-failure"]}+{"family": "question-wrapped-title", "query": "Which document is Deployment Pipeline Rollback Failure?", "relevant": ["postmortem/deployment-pipeline-rollback-failure"]}+{"family": "long-form-wrapper", "query": "What was the root cause described in the Deployment Pipeline Rollback Failure postmortem about the dropped column and the order service in October?", "relevant": ["postmortem/deployment-pipeline-rollback-failure"]}+{"family": "title-substring", "query": "Alert Fatigue Paging Review", "relevant": ["postmortem/alert-fatigue-paging-review"]}+{"family": "question-wrapped-title", "query": "Which document is Alert Fatigue Paging Review?", "relevant": ["postmortem/alert-fatigue-paging-review"]}+{"family": "long-form-wrapper", "query": "Which document is the Alert Fatigue Paging Review that analyzed weekly page counts and noisy rules for the on-call rotation during the third quarter?", "relevant": ["postmortem/alert-fatigue-paging-review"]}+{"family": "mention-other-gold", "query": "Which followup tracks the remediation owners and due dates after the Primary Database Failover Outage?", "relevant": ["postmortem/primary-database-failover-followup"]}+{"family": "mention-other-gold", "query": "What lessons and decisions came out of the session held after the Payment Gateway Timeout Incident?", "relevant": ["postmortem/payment-gateway-timeout-retrospective"]}+{"family": "mention-other-gold", "query": "Which runbook gives the renewal steps that were written after the Certificate Expiry Login Outage?", "relevant": ["postmortem/certificate-expiry-renewal-runbook"]}+{"family": "mention-other-gold", "query": "What does the Weekly Update say about the eviction alert and headroom on the shared cache, and which postmortem explains why it was needed?", "relevant": ["postmortem/cache-cluster-eviction-storm"]}+{"family": "mention-other-gold", "query": "In the Meeting Notes, which outage was discussed regarding the schema migration that made reverting the order service impossible?", "relevant": ["postmortem/deployment-pipeline-rollback-failure"]}+{"family": "mention-other-gold", "query": "Where is the original root cause described for the checkout timeouts that the Status Report refers to?", "relevant": ["postmortem/payment-gateway-timeout-incident"]}+{"family": "title-substring", "query": "Spring Offsite Agenda Draft", "relevant": ["events/spring-offsite-agenda-draft"]}+{"family": "question-wrapped-title", "query": "Which document is Spring Offsite Agenda Draft?", "relevant": ["events/spring-offsite-agenda-draft"]}+{"family": "long-form-wrapper", "query": "Where can I find the Spring Offsite Agenda Draft that Alice Example circulated in March for department leads to comment on?", "relevant": ["events/spring-offsite-agenda-draft"]}+{"family": "title-substring", "query": "Spring Offsite Agenda Final", "relevant": ["events/spring-offsite-agenda-final"]}+{"family": "question-wrapped-title", "query": "Which document is Spring Offsite Agenda Final?", "relevant": ["events/spring-offsite-agenda-final"]}+{"family": "long-form-wrapper", "query": "Can you point me to the approved Spring Offsite Agenda Final that replaced the hike with an indoor design workshop on day two?", "relevant": ["events/spring-offsite-agenda-final"]}+{"family": "title-substring", "query": "Harbor Street Venue Contract", "relevant": ["events/harbor-street-venue-contract"]}+{"family": "question-wrapped-title", "query": "Which document is Harbor Street Venue Contract?", "relevant": ["events/harbor-street-venue-contract"]}+{"family": "long-form-wrapper", "query": "What are the deposit and cancellation terms written in the Harbor Street Venue Contract for the May spring gathering hall rental?", "relevant": ["events/harbor-street-venue-contract"]}+{"family": "title-substring", "query": "Lakeview Lodge Venue Contract", "relevant": ["events/lakeview-lodge-venue-contract"]}+{"family": "question-wrapped-title", "query": "Which document is Lakeview Lodge Venue Contract?", "relevant": ["events/lakeview-lodge-venue-contract"]}+{"family": "long-form-wrapper", "query": "How many guests and how much money does the Lakeview Lodge Venue Contract cover for the October autumn leadership retreat stay?", "relevant": ["events/lakeview-lodge-venue-contract"]}+{"family": "title-substring", "query": "Annual Holiday Party Budget", "relevant": ["events/annual-holiday-party-budget"]}+{"family": "question-wrapped-title", "query": "Which document is Annual Holiday Party Budget?", "relevant": ["events/annual-holiday-party-budget"]}+{"family": "long-form-wrapper", "query": "Which line items make up the total in the Annual Holiday Party Budget, including venue, catering, music, and the contingency reserve?", "relevant": ["events/annual-holiday-party-budget"]}+{"family": "title-substring", "query": "Offsite Shuttle Transportation Plan", "relevant": ["events/offsite-shuttle-transportation-plan"]}+{"family": "question-wrapped-title", "query": "Which document is Offsite Shuttle Transportation Plan?", "relevant": ["events/offsite-shuttle-transportation-plan"]}+{"family": "long-form-wrapper", "query": "What departure times and seat counts are listed in the Offsite Shuttle Transportation Plan for travel from the main office to the venue?", "relevant": ["events/offsite-shuttle-transportation-plan"]}+{"family": "mention-other-gold", "query": "Which final schedule superseded the Spring Offsite Agenda Draft after the weather forecast changed?", "relevant": ["events/spring-offsite-agenda-final"]}+{"family": "mention-other-gold", "query": "Which document describes the shuttle schedule that was discussed as a need in the Meeting Notes from March?", "relevant": ["events/offsite-shuttle-transportation-plan"]}+{"family": "mention-other-gold", "query": "Where is the full spending breakdown for the December party that the Weekly Update says the committee will review?", "relevant": ["events/annual-holiday-party-budget"]}+{"family": "mention-other-gold", "query": "Which contract was the costlier alternative that was rejected instead of the Harbor Street Venue Contract?", "relevant": ["events/lakeview-lodge-venue-contract"]}+{"family": "mention-other-gold", "query": "Which document lists vegan and gluten-free meal counts for the gathering described in the Team Offsite overview?", "relevant": ["events/offsite-dietary-catering-menu"]}+{"family": "mention-other-gold", "query": "Which document explains the grill and cleanup roles for the picnic announced in the Quarterly Town Hall Recap?", "relevant": ["events/summer-picnic-volunteer-signup"]}diff --git a/llms-full.txt b/llms-full.txtindex c3fcbc1300..a592332413 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -5086,8 +5086,11 @@ Three more fields answer "what did that cost and did it land":- `quote_verify` — what the post-write claim check touched: quotes checkedand repaired, sentences quarantined (with counts per reason:`quote_not_in_source`, `quote_crosses_speakers`, `speaker_mismatch`,- `number_not_in_source`), pre-existing pages checked by diff, and unbalanced- paragraphs.+ `number_not_in_source`, `decision_misattributed`), pre-existing pages+ checked by diff, and unbalanced paragraphs. `decision_misattributed` is a+ sentence saying a speaker decided, agreed or will do something whose+ numbers or dates only another speaker stated and the named speaker never+ explicitly accepted.Per-call spend also lands in the `chat_usage_log` ledger with a phase tag:the orchestrator's own calls under `phase:synthesize`, each drained childdiff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex 6151d5b4a9..1bf0cf0c76 100644--- a/openclaw.plugin.json+++ b/openclaw.plugin.json@@ -1,7 +1,7 @@{"id": "gbrain-context-engine","name": "gbrain",- "version": "0.60.5.0",+ "version": "0.60.6.0","description": "Personal knowledge brain with Postgres + pgvector hybrid search","family": "bundle-plugin","kind": "context-engine",diff --git a/package.json b/package.jsonindex 4617b6bb87..5a0b1db72b 100644--- a/package.json+++ b/package.json@@ -191,7 +191,7 @@"bun": ">=1.3.11"},"license": "MIT",- "version": "0.60.5.0",+ "version": "0.60.6.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 fec0c62f00..6cc0c85806 100644--- a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json+++ b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-coding",- "version": "0.60.5.0",+ "version": "0.60.6.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 9f100b45c8..4d9e31b04d 100644--- a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json+++ b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-coding",- "version": "0.60.5.0",+ "version": "0.60.6.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 5defd4041b..8f4d52ba7b 100644--- a/plugin-variants/gbrain-coding/README.md+++ b/plugin-variants/gbrain-coding/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.60.5.0 -->+<!-- gbrain-plugin-tree-stamp: 0.60.6.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 712c89e6bb..2d00452f9f 100644--- a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json+++ b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-daily",- "version": "0.60.5.0",+ "version": "0.60.6.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 b16f8ef178..957399ff42 100644--- a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json+++ b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-daily",- "version": "0.60.5.0",+ "version": "0.60.6.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 e07b1e98cb..725feb64ec 100644--- a/plugin-variants/gbrain-daily/README.md+++ b/plugin-variants/gbrain-daily/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.60.5.0 -->+<!-- gbrain-plugin-tree-stamp: 0.60.6.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 ed90957039..b071497915 100644--- a/plugin/README.md+++ b/plugin/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.60.5.0 -->+<!-- gbrain-plugin-tree-stamp: 0.60.6.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 3a39549641..08bc1f4d3c 100644--- a/scripts/e2e-test-map.ts+++ b/scripts/e2e-test-map.ts@@ -50,7 +50,7 @@ export const E2E_TEST_MAP: Record<string, string[]> = {"src/mcp/skill-resources.ts": ["test/e2e/shared-skills-transports.test.ts"],"src/core/scope.ts": ["test/e2e/client-grants.test.ts", "test/e2e/shared-skills-transports.test.ts"],"src/core/grants/**": ["test/e2e/client-grants.test.ts", "test/e2e/harness-access.test.ts", "test/e2e/delegated-grants-withdrawal.test.ts", "test/e2e/delegated-http-worker.test.ts"],- "src/core/facts/withdrawal*.ts": ["test/e2e/delegated-grants-withdrawal.test.ts", "test/e2e/withdrawal-bounded-safety-postgres.test.ts", "test/e2e/withdrawal-crash-postgres.test.ts", "test/e2e/memory-safety-wave-postgres.test.ts"],+ "src/core/facts/withdrawal*.ts": ["test/e2e/delegated-grants-withdrawal.test.ts", "test/e2e/withdrawal-bounded-safety-postgres.test.ts", "test/e2e/withdrawal-crash-postgres.test.ts", "test/e2e/memory-safety-wave-postgres.test.ts", "test/e2e/fact-withdrawal-scope-postgres.test.ts"],"src/commands/mcp*.ts": ["test/e2e/harness-access.test.ts"],// OpenRouter subagent-loop families: the family allowlist + recipe feed the// key-gated live DeepSeek replay (self-skips without OPENROUTER_API_KEY).@@ -185,9 +185,12 @@ export const E2E_TEST_MAP: Record<string, string[]> = {"src/core/connectors/**": ["test/e2e/connector-sync-handler-pglite.test.ts","test/e2e/connectors-sync-checkpoints-pglite.test.ts",+ "test/e2e/connectors-ingest-failure-pglite.test.ts","test/e2e/connectors-sync-pglite.test.ts","test/e2e/doctor-connectors-pglite.test.ts",],+ // C-19: timestamp-less sessions are reported skips, not watermark-freezing errors.+ "src/core/transcripts/ingest.ts": ["test/e2e/transcripts-no-timestamp-pglite.test.ts"],// Agent-job scope fences over real Postgres."src/core/ops/jobs.ts": ["test/e2e/jobs-agent-scope-postgres.test.ts", "test/e2e/delegated-grants-withdrawal.test.ts", "test/e2e/delegated-http-worker.test.ts"],// postgres.js bind paths + JSONB shapes + parity vs PGLite.diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 699f2a6848..030ba452a1 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -3,27 +3,27 @@# Raising a ceiling is a conscious, reviewer-visible act. Lower ceilings in# the same commit as any peel (the guard fails on >50 lines of stale slack).# Columns: path max_lines policy note-src/cli.ts 4136 ratchet +2 export engine-free detailed help dispatch; +48 fix wave: get_versions --json + honest ellipsis (#4692), boolean-flag literal true/false consume (#4602); grown v0.46.26.0 megawave: SIGCHLD reaper install, silent-failure surfacing, confirm-race gate (#2443 #2898 #2297); grown wave-g (#4488 #4508): in-band error exit codes + think --source validation; grown db-availability loop: engine/db-repair dispatch, degraded-serve catch, marker choke points (bottom handler + no-config exit + doctor fallback), engine-free config-set dispatch; fix cycle: static classifier imports, resolved-brain degraded gate, guarded reconnect, help rows; +chat-connectors wiring (master merge); wave-k +24 for #4083 auth self-help entry + top-level auth usage lines + takes self-help branch; +master-merge true-up; +20 gbrain backup pre-engine dispatch + startup backup nag rail (monthly backup check); wave-k: +24 for #4083 auth self-help entry + top-level auth usage lines + takes self-help branch; +3: doctor --no-migrate probeOnly seam (#4364); +37 v0.47 gmail-loops: google/creds dispatch + waiting/loops cases + self-help entries + OPEN LOOPS help section; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: CLI combines hosted access and explicit legacy queue review; lowered to 4077: GHSA wave v0.50.5.0 moved the #3688 guardrails block into core/cli-preflight.ts (-10); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; #5252 wave: partial-retrieval notices and resident code reindex delegation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared skills: parse typed object/array operation flags before resident-owner delegation; merged reliability/shared-skills source integration Explicit-policy thin recall routing before local engine connection; actual CLI subprocess regression coverage. Reject explicit thin recall brain selection before dispatch.; +10 A2 preview-bound attendance repair dispatch and help; integrated upstream provider retirement with thin recall and gated repair dispatch; +4 strict pre-engine rejection of unsupported brain-wide migration narrowing flags; merged upstream: 48 fix wave: get_versions --json + honest ellipsis (#4692), boolean-flag literal true/false consume (#4602); grown v0.46.26.0 megawave: SIGCHLD reaper install, silent-failure surfacing, confirm-race gate (#2443 #2898 #2297); grown wave-g (#4488 #4508): in-band error exit codes + think --source validation; grown db-availability loop: engine/db-repair dispatch, degraded-serve catch, marker choke points (bottom handler + no-config exit + doctor fallback), engine-free config-set dispatch; fix cycle: static classifier imports, resolved-brain degraded gate, guarded reconnect, help rows; +chat-connectors wiring (master merge); wave-k +24 for #4083 auth self-help entry + top-level auth usage lines + takes self-help branch; +master-merge true-up; +20 gbrain backup pre-engine dispatch + startup backup nag rail (monthly backup check); wave-k: +24 for #4083 auth self-help entry + top-level auth usage lines + takes self-help branch; +3: doctor --no-migrate probeOnly seam (#4364); +37 v0.47 gmail-loops: google/creds dispatch + waiting/loops cases + self-help entries + OPEN LOOPS help section; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: CLI combines hosted access and explicit legacy queue review; lowered to 4077: GHSA wave v0.50.5.0 moved the #3688 guardrails block into core/cli-preflight.ts (-10); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; #5252 wave: partial-retrieval notices and resident code reindex delegation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared skills: parse typed object/array operation flags before resident-owner delegation; merged reliability/shared-skills source integration Explicit-policy thin recall routing before local engine connection; actual CLI subprocess regression coverage. Reject explicit thin recall brain selection before dispatch.; +10 A2 preview-bound attendance repair dispatch and help; integrated upstream provider retirement with thin recall and gated repair dispatch; typed readiness, configuration-blocked lifecycle and bounded release; +12 wave-2 W3: gbrain repair dispatch, engine-free help, thin-client refusal and help row+src/cli.ts 4136 ratchet +2 export engine-free detailed help dispatch; +48 fix wave: get_versions --json + honest ellipsis (#4692), boolean-flag literal true/false consume (#4602); grown v0.46.26.0 megawave: SIGCHLD reaper install, silent-failure surfacing, confirm-race gate (#2443 #2898 #2297); grown wave-g (#4488 #4508): in-band error exit codes + think --source validation; grown db-availability loop: engine/db-repair dispatch, degraded-serve catch, marker choke points (bottom handler + no-config exit + doctor fallback), engine-free config-set dispatch; fix cycle: static classifier imports, resolved-brain degraded gate, guarded reconnect, help rows; +chat-connectors wiring (master merge); wave-k +24 for #4083 auth self-help entry + top-level auth usage lines + takes self-help branch; +master-merge true-up; +20 gbrain backup pre-engine dispatch + startup backup nag rail (monthly backup check); wave-k: +24 for #4083 auth self-help entry + top-level auth usage lines + takes self-help branch; +3: doctor --no-migrate probeOnly seam (#4364); +37 v0.47 gmail-loops: google/creds dispatch + waiting/loops cases + self-help entries + OPEN LOOPS help section; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: CLI combines hosted access and explicit legacy queue review; lowered to 4077: GHSA wave v0.50.5.0 moved the #3688 guardrails block into core/cli-preflight.ts (-10); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; #5252 wave: partial-retrieval notices and resident code reindex delegation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared skills: parse typed object/array operation flags before resident-owner delegation; merged reliability/shared-skills source integration Explicit-policy thin recall routing before local engine connection; actual CLI subprocess regression coverage. Reject explicit thin recall brain selection before dispatch.; +10 A2 preview-bound attendance repair dispatch and help; integrated upstream provider retirement with thin recall and gated repair dispatch; +4 strict pre-engine rejection of unsupported brain-wide migration narrowing flags; merged upstream: 48 fix wave: get_versions --json + honest ellipsis (#4692), boolean-flag literal true/false consume (#4602); grown v0.46.26.0 megawave: SIGCHLD reaper install, silent-failure surfacing, confirm-race gate (#2443 #2898 #2297); grown wave-g (#4488 #4508): in-band error exit codes + think --source validation; grown db-availability loop: engine/db-repair dispatch, degraded-serve catch, marker choke points (bottom handler + no-config exit + doctor fallback), engine-free config-set dispatch; fix cycle: static classifier imports, resolved-brain degraded gate, guarded reconnect, help rows; +chat-connectors wiring (master merge); wave-k +24 for #4083 auth self-help entry + top-level auth usage lines + takes self-help branch; +master-merge true-up; +20 gbrain backup pre-engine dispatch + startup backup nag rail (monthly backup check); wave-k: +24 for #4083 auth self-help entry + top-level auth usage lines + takes self-help branch; +3: doctor --no-migrate probeOnly seam (#4364); +37 v0.47 gmail-loops: google/creds dispatch + waiting/loops cases + self-help entries + OPEN LOOPS help section; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: CLI combines hosted access and explicit legacy queue review; lowered to 4077: GHSA wave v0.50.5.0 moved the #3688 guardrails block into core/cli-preflight.ts (-10); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; #5252 wave: partial-retrieval notices and resident code reindex delegation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared skills: parse typed object/array operation flags before resident-owner delegation; merged reliability/shared-skills source integration Explicit-policy thin recall routing before local engine connection; actual CLI subprocess regression coverage. Reject explicit thin recall brain selection before dispatch.; +10 A2 preview-bound attendance repair dispatch and help; integrated upstream provider retirement with thin recall and gated repair dispatch; typed readiness, configuration-blocked lifecycle and bounded release; +12 wave-2 W3: gbrain repair dispatch, engine-free help, thin-client refusal and help row; +1 managed extract --stale delegation to a live PGLite ownersrc/commands/autopilot.ts 2726 ratchet grown v0.46.26.0 megawave (#4300 #4285 #3696) + master v0.46.27.0 env-file lane + boot warning + reload-safe install (#2608 #4443) + 1 nosemgrep dataflow annotation (path-traversal audit); +chat-connectors wiring; +20 #4728 wrapper exec guard (baked CLI path gone -> PATH fallback / --install hint); +5 #4952 (refs #4399): syncEnabled=false skip in the freshness dispatch loop; typed readiness, configuration-blocked lifecycle and bounded release; +3 guard transaction callbacks and roll back on configuration block; +1 #5609: shared staleExtractionBlocked probe in the dispatch-plan context-src/commands/doctor.ts 4603 ratchet grown v0.46.26.0 megawave: silent-death checks, self-upgrade honesty, noise pruning (#3944 #3925 #3958); +21 lines (#4518: don't assert "supervisor not running" when the --fast mode DB-lock fallback was never attempted); +12 lines (#2036/#4484: schema_version warns on forward DB skew); +12 lines (#4476: oversized_pages excludes embed_skip pages via canonical EMBED_SKIP_FILTER_FRAGMENT); merged wave-g-prs (#4421 #4425 #4517 #4519): one in-branch live-column diff on detectMissingColumns + engine-aware superseded upgrade-error suppression (explicit ok); grown db-availability loop: classified connection check + synthesized total-outage entry + hoisted pgbouncer helper + engine-fit check wiring + report engine/db_url_source fields; +chat-connectors wiring (master merge); +12 lines (#2036/#4484: schema_version warns on forward DB skew via schemaVersionHealth); merged wave-g-prs (#4421 #4425 #4517 #4519): in-branch live-column diff + engine-aware superseded upgrade-error suppression; wave-k: schema_columns emitted as its own check inside the ledger-current branch (gbrain#4421), schema_version via schemaVersionHealth module, conversation_format_coverage peeled to doctor/checks/conversation-coverage.ts (#4193); +7 backup_coverage check registration (monthly backup check); +master-merge true-up; wave-k: schema_columns emitted as its own check inside the ledger-current branch (gbrain#4421), schema_version via schemaVersionHealth module, conversation_format_coverage peeled to doctor/checks/conversation-coverage.ts (#4193); +9 v0.47 gmail-loops: google_oauth vault-health check dispatch; +17 (#4712: git-root-pinned source skip note wiring + all-skipped warn-not-ok status for multi_source_drift); +8 memorable_relay_health wiring (check itself is a peel: doctor/checks/integrations-memorable.ts); +9 ambient-writeback WP6: memory_writeback check registration (logic lives in doctor/checks/memory-writeback.ts); +14 default_source_local_path registration (#4739 — check body peeled to doctor/checks/default-source-path.ts); +9 atom_provenance_drift registration (#4566 — check body lives in doctor/checks/extraction-sync.ts); master: | merged v0.48.1.0 true-up; #5252 wave: scoped projection readiness registration; shared content: register the separately scoped canonical publication/recovery check; merged reliability/shared-skills source integration; +10 fix wave 2 (v0.60.5.0) integration: timeline_history/derived_visibility (+9 W3/W4), parked_effects/persistence_capacity (+6 W5) and dream_paid_loop (+10 W7) registrations used the 15 lines of slack under the prior ceiling-src/commands/embed.ts 2169 ratchet lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment); #5105: guarded derived projection preparation and read seals; #5105: conditional embedding installer wiring; archived eligibility: active-only dispatch with honest stranded-work reporting; explicit archived admission: live-source snapshots and honest refused-installation failures+src/commands/doctor.ts 4609 ratchet grown v0.46.26.0 megawave: silent-death checks, self-upgrade honesty, noise pruning (#3944 #3925 #3958); +21 lines (#4518: don't assert "supervisor not running" when the --fast mode DB-lock fallback was never attempted); +12 lines (#2036/#4484: schema_version warns on forward DB skew); +12 lines (#4476: oversized_pages excludes embed_skip pages via canonical EMBED_SKIP_FILTER_FRAGMENT); merged wave-g-prs (#4421 #4425 #4517 #4519): one in-branch live-column diff on detectMissingColumns + engine-aware superseded upgrade-error suppression (explicit ok); grown db-availability loop: classified connection check + synthesized total-outage entry + hoisted pgbouncer helper + engine-fit check wiring + report engine/db_url_source fields; +chat-connectors wiring (master merge); +12 lines (#2036/#4484: schema_version warns on forward DB skew via schemaVersionHealth); merged wave-g-prs (#4421 #4425 #4517 #4519): in-branch live-column diff + engine-aware superseded upgrade-error suppression; wave-k: schema_columns emitted as its own check inside the ledger-current branch (gbrain#4421), schema_version via schemaVersionHealth module, conversation_format_coverage peeled to doctor/checks/conversation-coverage.ts (#4193); +7 backup_coverage check registration (monthly backup check); +master-merge true-up; wave-k: schema_columns emitted as its own check inside the ledger-current branch (gbrain#4421), schema_version via schemaVersionHealth module, conversation_format_coverage peeled to doctor/checks/conversation-coverage.ts (#4193); +9 v0.47 gmail-loops: google_oauth vault-health check dispatch; +17 (#4712: git-root-pinned source skip note wiring + all-skipped warn-not-ok status for multi_source_drift); +8 memorable_relay_health wiring (check itself is a peel: doctor/checks/integrations-memorable.ts); +9 ambient-writeback WP6: memory_writeback check registration (logic lives in doctor/checks/memory-writeback.ts); +14 default_source_local_path registration (#4739 — check body peeled to doctor/checks/default-source-path.ts); +9 atom_provenance_drift registration (#4566 — check body lives in doctor/checks/extraction-sync.ts); master: | merged v0.48.1.0 true-up; #5252 wave: scoped projection readiness registration; shared content: register the separately scoped canonical publication/recovery check; merged reliability/shared-skills source integration; +10 fix wave 2 (v0.60.5.0) integration: timeline_history/derived_visibility (+9 W3/W4), parked_effects/persistence_capacity (+6 W5) and dream_paid_loop (+10 W7) registrations used the 15 lines of slack under the prior ceiling; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +6 at the merge+src/commands/embed.ts 2171 ratchet lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment); #5105: guarded derived projection preparation and read seals; #5105: conditional embedding installer wiring; archived eligibility: active-only dispatch with honest stranded-work reporting; explicit archived admission: live-source snapshots and honest refused-installation failures; +2 fw3: embed --stale --images dispatch (sweep lives in core/embed-stale-images.ts)src/commands/extract-conversation-facts.ts 2125 ratchet grown v0.46.x per-provider gateway-unavailable copy; grown wave-g (#4482): expected budget/deadline caps classified apart from error halts; wave-k: save-time resolution caller (#4052/#3729 — supersedes wave-g's per-row resolveEntitySlug mapper); +1: key-aware llm-fallback default (#3813); +1: pricingOverrides wiring into the owned BudgetTracker (#4633 adoption); +3: #4869 snapshot-mismatch counts as pages_failed; merged reliability/shared-skills source integration; +19: additive skip reasons and model-free dry-run (#5364)-src/commands/extract.ts 2604 ratchet grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges; T2: source-qualified inference and atomic origin-scoped derived links; standard DB extraction fences captured endpoint revisions; shared authoritative attendance/source reconciliation moved to the core module; +7 A2 preview-bound attendance repair import, help and authority dispatch; bounded incomplete-attendance diagnostics and consistent basename resolution; fail closed before graph mutation when active ontology is unavailable; +16 source-selected ontology cache, type-scoped preflight and non-starving failed stale drain; +7 write-path wave: per-slug extractors replace page links + retract removed timeline rows + rename-alias resolution; +26 #5609: managed extract --stale publishes links, canonical timeline and watermark per page in one coordinated transaction+src/commands/extract.ts 2608 ratchet grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges; T2: source-qualified inference and atomic origin-scoped derived links; standard DB extraction fences captured endpoint revisions; shared authoritative attendance/source reconciliation moved to the core module; +7 A2 preview-bound attendance repair import, help and authority dispatch; bounded incomplete-attendance diagnostics and consistent basename resolution; fail closed before graph mutation when active ontology is unavailable; +16 source-selected ontology cache, type-scoped preflight and non-starving failed stale drain; +7 write-path wave: per-slug extractors replace page links + retract removed timeline rows + rename-alias resolution; +5 fw3 derived-sync: timeline --prune-orphans CLI (#4649) and full-walk page link replacement; +13 fw3 A16/A15: sync link hook reads scoped page metadata and reports per-page extraction errors; +1 fw3 managed-lifecycle: extract --stale dispatches managed brains to the coordinator-safe path; +4 fw3 integration: managed brains refuse the direct timeline orphan prune; +26 #5609: managed extract --stale publishes links, canonical timeline and watermark per page in one coordinated transaction; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +4 at the mergesrc/commands/jobs.ts 3262 ratchet grown v0.46.26.0 megawave (#4098 #2308) + master v0.46.26.0 worker startup recovery + stats gating; +typed provider-failure logging on the facts-absorb catch (#4308); +chat-connectors wiring (master merge); +16 v0.47 gmail-loops: loops_extract handler + gateway-refresh entry; +8 refs #4599: embed + embed-catch-up handlers fail the job on a stall_timeout result (assertEmbedNotStalled); security: durable queued authority and confined filesystem dispatch; drained cancellation and lease-safe partial results; queued import failures remain failures; master integration: grown v0.46.26.0 megawave (#4098 #2308) + master v0.46.26.0 worker startup recovery + stats gating; +typed provider-failure logging on the facts-absorb catch (#4308); +chat-connectors wiring (master merge); +16 v0.47 gmail-loops: loops_extract handler + gateway-refresh entry; +8 refs #4599: embed + embed-catch-up handlers fail the job on a stall_timeout result (assertEmbedNotStalled); #5105: two-line delegate validates revision and durable authority before fact backstop execution; upstream integration: preserve independently reviewed master additions with branch facade extraction; +13 v0.50.5.0 security merge (upstream delta; coordinated facade retained); merged reliability/shared-skills source integration; +1 #5584: skillopt job reflect_max_tokens (validated + clamped via skillopt/output-cap.ts); lowered #5585: skillopt handler body peeled to skillopt/job.ts (execution-time model re-resolution + strict re-check); typed readiness, configuration-blocked lifecycle and bounded release (issue #5560 merge); +2 #5632: sync job passes its explicitly set processing optionssrc/commands/serve-http.ts 3108 ratchet registration and grant routes extracted; owner authentication and configured discovery remain in the HTTP facade; one shared bootstrap-token-shape import from serve-service; merged scoped shared-skill resources and named capability checks; +10 #5222 resource canonicalizer wiring (issuer/resource declared before the provider, shared verifier) + #5277 read write challenge hintsrc/core/ai/gateway.ts 4441 ratchet +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings-src/commands/sync.ts 6002 ratchet +1 #4786/#3068 pre-landing: pullFailed early return reports the sweep count (comment line); +1 #4786 x #2139 pre-landing: both embed-backfill submit gates require syncProducedEmbeddableContent (import line); re-summed after merging master v0.50.0.0 with the wave (include_hidden, sweep count, cost-gate envelope); +1 wave review: sync trigger --json emits {job_id} JSON; grown v0.46.26.0 megawave: image sync, ingest-log gating, dry-run purity, checkpoint honesty (#2683 #4342 #3875) + 3 nosemgrep dataflow annotations (path-traversal audit); +#2683 residual: status-error failure recording at both import sites; +143 wave G #3974: working-tree drift surfacing + opt-in --working-tree import; grown wave-g (#4412 #4543): break-lock ambient source resolution + named failing files; grown db-availability loop: GBRAIN_DB_ACCESS marker on checkpoint-dead aborts; fix cycle: marker via shared DB_ACCESS_MARKER_PREFIX + shouldEmitDbAccessMarker; wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +master-merge true-up; +25 post-sync backup-coverage stale-only refresh (monthly backup check); wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +1: #4412 refinement — explicit --source stays resolver-free (deleted-source locks breakable); +10 v0.47 gmail-loops: google source-kind dispatch branch; +48 #4667 adoption: persisted sync.exclude config union hoisted above the performFullSync early returns; +22 #4587: all 7 delete lanes swapped to softDeletePages (72h recovery window), decompose comments + summary wording; +16 #4583: seed_default write refusal on bulk-non-default brains (assessDefaultWriteGuard call site + escape-hatch comment); composition true-up (fix-wave multi-train); +33 #4597: trackedSlugIndex.anchorOnlyPaths (slug -> anchor paths that alone proved it) + the self-referential from-path rule in slugLiveness so a fallback rename's own pre-rename duplicate converges under incremental sync; +12 #4888: runSync wraps runSyncInner in withHumanLogsToStderr under --json (stdout = JSON lines only) + help text; wave composition: #4903 stored-strategy honor + #4597 fallback-rename duplicate convergence + #4888 --json stdout purity summed; security: durable queued authority and confined filesystem dispatch; drained cancellation and lease-safe partial results; master integration: +1 wave review: sync trigger --json emits {job_id} JSON; grown v0.46.26.0 megawave: image sync, ingest-log gating, dry-run purity, checkpoint honesty (#2683 #4342 #3875) + 3 nosemgrep dataflow annotations (path-traversal audit); +#2683 residual: status-error failure recording at both import sites; +143 wave G #3974: working-tree drift surfacing + opt-in --working-tree import; grown wave-g (#4412 #4543): break-lock ambient source resolution + named failing files; grown db-availability loop: GBRAIN_DB_ACCESS marker on checkpoint-dead aborts; fix cycle: marker via shared DB_ACCESS_MARKER_PREFIX + shouldEmitDbAccessMarker; wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +master-merge true-up; +25 post-sync backup-coverage stale-only refresh (monthly backup check); wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +1: #4412 refinement — explicit --source stays resolver-free (deleted-source locks breakable); +10 v0.47 gmail-loops: google source-kind dispatch branch; +48 #4667 adoption: persisted sync.exclude config union hoisted above the performFullSync early returns; +22 #4587: all 7 delete lanes swapped to softDeletePages (72h recovery window), decompose comments + summary wording; +16 #4583: seed_default write refusal on bulk-non-default brains (assessDefaultWriteGuard call site + escape-hatch comment); composition true-up (fix-wave multi-train); +33 #4597: trackedSlugIndex.anchorOnlyPaths (slug -> anchor paths that alone proved it) + the self-referential from-path rule in slugLiveness so a fallback rename's own pre-rename duplicate converges under incremental sync; +12 #4888: runSync wraps runSyncInner in withHumanLogsToStderr under --json (stdout = JSON lines only) + help text; wave composition: #4903 stored-strategy honor + #4597 fallback-rename duplicate convergence + #4888 --json stdout purity summed; #5252 wave: post-batch planner statistics refresh; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; merged reliability/shared-skills source integration; +1 cancellation guard before company dispatch; +3 wave-2 W4: full sync carries the safe-chunk re-seal count and embedding cost (#5050); +4 #5632: CLI passes explicitly set processing options so a flagless resume adopts the cursor options-src/core/cycle.ts 3209 ratchet grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options-src/core/cycle/synthesize.ts 3241 ratchet merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack-src/core/cycle/extract-atoms.ts 1755 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +3 #5525: effectiveVisibility stamped on non-managed atoms-src/core/engine.ts 2665 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract-src/core/import-file.ts 2252 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count+src/commands/sync.ts 6016 ratchet +1 #4786/#3068 pre-landing: pullFailed early return reports the sweep count (comment line); +1 #4786 x #2139 pre-landing: both embed-backfill submit gates require syncProducedEmbeddableContent (import line); re-summed after merging master v0.50.0.0 with the wave (include_hidden, sweep count, cost-gate envelope); +1 wave review: sync trigger --json emits {job_id} JSON; grown v0.46.26.0 megawave: image sync, ingest-log gating, dry-run purity, checkpoint honesty (#2683 #4342 #3875) + 3 nosemgrep dataflow annotations (path-traversal audit); +#2683 residual: status-error failure recording at both import sites; +143 wave G #3974: working-tree drift surfacing + opt-in --working-tree import; grown wave-g (#4412 #4543): break-lock ambient source resolution + named failing files; grown db-availability loop: GBRAIN_DB_ACCESS marker on checkpoint-dead aborts; fix cycle: marker via shared DB_ACCESS_MARKER_PREFIX + shouldEmitDbAccessMarker; wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +master-merge true-up; +25 post-sync backup-coverage stale-only refresh (monthly backup check); wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +1: #4412 refinement — explicit --source stays resolver-free (deleted-source locks breakable); +10 v0.47 gmail-loops: google source-kind dispatch branch; +48 #4667 adoption: persisted sync.exclude config union hoisted above the performFullSync early returns; +22 #4587: all 7 delete lanes swapped to softDeletePages (72h recovery window), decompose comments + summary wording; +16 #4583: seed_default write refusal on bulk-non-default brains (assessDefaultWriteGuard call site + escape-hatch comment); composition true-up (fix-wave multi-train); +33 #4597: trackedSlugIndex.anchorOnlyPaths (slug -> anchor paths that alone proved it) + the self-referential from-path rule in slugLiveness so a fallback rename's own pre-rename duplicate converges under incremental sync; +12 #4888: runSync wraps runSyncInner in withHumanLogsToStderr under --json (stdout = JSON lines only) + help text; wave composition: #4903 stored-strategy honor + #4597 fallback-rename duplicate convergence + #4888 --json stdout purity summed; security: durable queued authority and confined filesystem dispatch; drained cancellation and lease-safe partial results; master integration: +1 wave review: sync trigger --json emits {job_id} JSON; grown v0.46.26.0 megawave: image sync, ingest-log gating, dry-run purity, checkpoint honesty (#2683 #4342 #3875) + 3 nosemgrep dataflow annotations (path-traversal audit); +#2683 residual: status-error failure recording at both import sites; +143 wave G #3974: working-tree drift surfacing + opt-in --working-tree import; grown wave-g (#4412 #4543): break-lock ambient source resolution + named failing files; grown db-availability loop: GBRAIN_DB_ACCESS marker on checkpoint-dead aborts; fix cycle: marker via shared DB_ACCESS_MARKER_PREFIX + shouldEmitDbAccessMarker; wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +master-merge true-up; +25 post-sync backup-coverage stale-only refresh (monthly backup check); wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +1: #4412 refinement — explicit --source stays resolver-free (deleted-source locks breakable); +10 v0.47 gmail-loops: google source-kind dispatch branch; +48 #4667 adoption: persisted sync.exclude config union hoisted above the performFullSync early returns; +22 #4587: all 7 delete lanes swapped to softDeletePages (72h recovery window), decompose comments + summary wording; +16 #4583: seed_default write refusal on bulk-non-default brains (assessDefaultWriteGuard call site + escape-hatch comment); composition true-up (fix-wave multi-train); +33 #4597: trackedSlugIndex.anchorOnlyPaths (slug -> anchor paths that alone proved it) + the self-referential from-path rule in slugLiveness so a fallback rename's own pre-rename duplicate converges under incremental sync; +12 #4888: runSync wraps runSyncInner in withHumanLogsToStderr under --json (stdout = JSON lines only) + help text; wave composition: #4903 stored-strategy honor + #4597 fallback-rename duplicate convergence + #4888 --json stdout purity summed; #5252 wave: post-batch planner statistics refresh; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; merged reliability/shared-skills source integration; +1 cancellation guard before company dispatch; +3 managed sync result fields and notes line (slug collisions, derived links; printing lives in sync-diagnostics.ts); +11 fw3 A15: post-sync extraction failures logged and returned as extract_error; fw3 integration: derived-sync +11 and managed-lifecycle +3 compose (5995 + 14); +3 wave-2 W4: full sync carries the safe-chunk re-seal count and embedding cost (#5050); +4 #5632: CLI passes explicitly set processing options so a flagless resume adopts the cursor options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +7 at the merge+src/core/cycle.ts 3217 ratchet grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge+src/core/cycle/synthesize.ts 3317 ratchet merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge+src/core/cycle/extract-atoms.ts 1792 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge+src/core/engine.ts 2667 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract+src/core/import-file.ts 2283 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the mergesrc/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 6167 ratchet +6 #4881: ontology provenance-page visibility gate (getOntology/findOntologyConflicts); grown v0.46.26.0 megawave parity twins + master v0.46.26.0 private-queue columns; +#3754 traverseGraph soft-delete filters; grown wave-g (#4524 #4527): canonical islanded orphans + timestamp-preserving migrate; wave-k: +1 semantic takes retrieval delegate (#3776), +5 NUL-sanitize shared chunk_text local (#3998), +7 getAllConfig bulk read (#3980); +22: pre-close WAL CHECKPOINT in disconnect (#3893); +10: #4109 atomic link/timeline mutation + typed per-endpoint miss (parity); +1: getBacklinkCounts page-id keying comment (#4380); +14: dream-verdict TTL expiry predicate + sweep (#4069); +7 test-gap-wave merge true-up; +23: softDeletePages batch soft-delete primitive (#4587, parity twin); +51: #4592 source-scoped getStats/getHealth (bound $1 scope, both-endpoint link rule); +5 file-bytes snapshot hash (coverage-immune — CI shards were silently cold-initting); +7 2026-09 fix wave (#3617 follow-up): OR-fallback rows tagged keyword_relaxed in searchKeyword + title arm (fusion demotion reads it); cold-initting); +11: #4280 orphan/health served-memory denominators (quarantine + leaf-type metadata); composition true-up (fix-wave multi-train); +14: traversePathsDetailed row cap (LIMIT + truncated probe, parity twin); +7: resolveSlugWithAliasDetailed (owning source_id, parity twin) | merged v0.48.1.0 true-up; corrective release: shared batched enrichment peel; concrete content and Chronicle authorization; +2: #4681 listPages projects updated_at_iso (microsecond keyset cursor); master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: grant and authority schema bootstrap parity; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; upstream integration: preserve independently reviewed master additions with branch facade extraction; +1 v0.50.5.0 security merge (upstream delta; coordinated facade retained); +7 ceiling: bounded in-memory create retry with attached-database exclusion and second-failure diagnostics; #5252 bounded candidate recovery and statistics snapshot dependency; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared-skills integration on company-ingestion base; shared skills: include explicit access DDL in snapshot invalidation; archived eligibility: source-locked drift and raw signature mutations; +6 write-path wave: updateSlug records its rename alias in one transaction; +11 read-path wave: searchKeyword type/exclude_slugs Postgres parity + getTags private/deleted filters; +5: updateSlug carries entity-scoped fact withdrawals; +12 wave-2 W4: upsertChunks writes content_chunks.embedding_input_hash with the vector (#5553, parity twin); +6 #5449 outermost-transaction WAL checkpoint guard admitted into the shutdown drain, reset per attached database (logic in pglite-engine/checkpoint-guard.ts)-src/core/postgres-engine.ts 5587 ratchet +6 #4881: ontology provenance-page visibility gate (parity twin); lowered wave-g: #4477 bootstrap peel to src/core/postgres-engine/ modules (ratchet holds the win); +2 on wave-g-prs merge true-up; wave-k: +2 semantic takes retrieval (#3776), +5 NUL-sanitize shared chunk_text local (#3998), +11 getAllConfig bulk read (#3980); +13: #4109 atomic FOR KEY SHARE link/timeline mutation + typed per-endpoint miss; +2: getBacklinkCounts page-id keying comment (#4380); +12: dream-verdict TTL expiry predicate + sweep (#4069); +23: softDeletePages batch soft-delete primitive (#4587, parity twin); +61: #4592 source-scoped getStats/getHealth (scope predicate, both-endpoint link rule); +11 2026-09 fix wave (#3617 follow-up): OR-fallback rows tagged keyword_relaxed in searchKeyword + title arm (fusion demotion reads it); rule); +12: #4280 orphan/health served-memory denominators (quarantine + leaf-type metadata, parity twin); composition true-up (fix-wave multi-train); +14: traversePathsDetailed row cap (LIMIT + truncated probe, parity twin); +7: resolveSlugWithAliasDetailed (owning source_id, parity twin) | merged v0.48.1.0 true-up; corrective release: shared batched enrichment peel; concrete content and Chronicle authorization; +3: #4681 listPages projects updated_at_iso (microsecond keyset cursor, parity twin); #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop barrier and direct transaction route; upstream integration: preserve independently reviewed master additions with branch facade extraction; +1 v0.50.5.0 security merge (upstream delta; coordinated facade retained); +3 wave-2 W4: upsertChunks writes content_chunks.embedding_input_hash with the vector (#5553, parity twin); +2 fix wave 2 (v0.60.5.0) integration: master grew 2 lines under the old ceiling while W4 raised it from its older base; +5 v0.60.5.0 master-merge true-up: W4 +12 re-summed over master v0.59.18.0 at 5575 lines-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 removed-src/core/types.ts 2078 ratchet +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553)+src/core/pglite-engine.ts 6175 ratchet +6 #4881: ontology provenance-page visibility gate (getOntology/findOntologyConflicts); grown v0.46.26.0 megawave parity twins + master v0.46.26.0 private-queue columns; +#3754 traverseGraph soft-delete filters; grown wave-g (#4524 #4527): canonical islanded orphans + timestamp-preserving migrate; wave-k: +1 semantic takes retrieval delegate (#3776), +5 NUL-sanitize shared chunk_text local (#3998), +7 getAllConfig bulk read (#3980); +22: pre-close WAL CHECKPOINT in disconnect (#3893); +10: #4109 atomic link/timeline mutation + typed per-endpoint miss (parity); +1: getBacklinkCounts page-id keying comment (#4380); +14: dream-verdict TTL expiry predicate + sweep (#4069); +7 test-gap-wave merge true-up; +23: softDeletePages batch soft-delete primitive (#4587, parity twin); +51: #4592 source-scoped getStats/getHealth (bound $1 scope, both-endpoint link rule); +5 file-bytes snapshot hash (coverage-immune — CI shards were silently cold-initting); +7 2026-09 fix wave (#3617 follow-up): OR-fallback rows tagged keyword_relaxed in searchKeyword + title arm (fusion demotion reads it); cold-initting); +11: #4280 orphan/health served-memory denominators (quarantine + leaf-type metadata); composition true-up (fix-wave multi-train); +14: traversePathsDetailed row cap (LIMIT + truncated probe, parity twin); +7: resolveSlugWithAliasDetailed (owning source_id, parity twin) | merged v0.48.1.0 true-up; corrective release: shared batched enrichment peel; concrete content and Chronicle authorization; +2: #4681 listPages projects updated_at_iso (microsecond keyset cursor); master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: grant and authority schema bootstrap parity; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; upstream integration: preserve independently reviewed master additions with branch facade extraction; +1 v0.50.5.0 security merge (upstream delta; coordinated facade retained); +7 ceiling: bounded in-memory create retry with attached-database exclusion and second-failure diagnostics; #5252 bounded candidate recovery and statistics snapshot dependency; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared-skills integration on company-ingestion base; shared skills: include explicit access DDL in snapshot invalidation; archived eligibility: source-locked drift and raw signature mutations; +6 write-path wave: updateSlug records its rename alias in one transaction; +11 read-path wave: searchKeyword type/exclude_slugs Postgres parity + getTags private/deleted filters; +5: updateSlug carries entity-scoped fact withdrawals; +12 wave-2 W4: upsertChunks writes content_chunks.embedding_input_hash with the vector (#5553, parity twin); +6 #5449 outermost-transaction WAL checkpoint guard admitted into the shutdown drain, reset per attached database (logic in pglite-engine/checkpoint-guard.ts); +10 fw3-search: traversal walk row cap + (page, depth) dedupe (parity twin), source_boosts opt; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +8 at the merge+src/core/postgres-engine.ts 5590 ratchet +6 #4881: ontology provenance-page visibility gate (parity twin); lowered wave-g: #4477 bootstrap peel to src/core/postgres-engine/ modules (ratchet holds the win); +2 on wave-g-prs merge true-up; wave-k: +2 semantic takes retrieval (#3776), +5 NUL-sanitize shared chunk_text local (#3998), +11 getAllConfig bulk read (#3980); +13: #4109 atomic FOR KEY SHARE link/timeline mutation + typed per-endpoint miss; +2: getBacklinkCounts page-id keying comment (#4380); +12: dream-verdict TTL expiry predicate + sweep (#4069); +23: softDeletePages batch soft-delete primitive (#4587, parity twin); +61: #4592 source-scoped getStats/getHealth (scope predicate, both-endpoint link rule); +11 2026-09 fix wave (#3617 follow-up): OR-fallback rows tagged keyword_relaxed in searchKeyword + title arm (fusion demotion reads it); rule); +12: #4280 orphan/health served-memory denominators (quarantine + leaf-type metadata, parity twin); composition true-up (fix-wave multi-train); +14: traversePathsDetailed row cap (LIMIT + truncated probe, parity twin); +7: resolveSlugWithAliasDetailed (owning source_id, parity twin) | merged v0.48.1.0 true-up; corrective release: shared batched enrichment peel; concrete content and Chronicle authorization; +3: #4681 listPages projects updated_at_iso (microsecond keyset cursor, parity twin); #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop barrier and direct transaction route; upstream integration: preserve independently reviewed master additions with branch facade extraction; +1 v0.50.5.0 security merge (upstream delta; coordinated facade retained); +3 wave-2 W4: upsertChunks writes content_chunks.embedding_input_hash with the vector (#5553, parity twin); +2 fix wave 2 (v0.60.5.0) integration: master grew 2 lines under the old ceiling while W4 raised it from its older base; +5 v0.60.5.0 master-merge true-up: W4 +12 re-summed over master v0.59.18.0 at 5575 lines; +8 fw3-search: traversal walk row cap + (page, depth) dedupe (parity twin), source_boosts opt; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge+src/core/search/hybrid.ts 3125 ratchet +2: preserve local query-deadline classification through gateway error wrapping; grown v0.46.26.0 megawave: CRAG escalation seam, degradation visibility, excludePrivate knobs-fold v23 (#1663 #3873 #4352); grown #4356: semantic-cache-hit slice honors resolved mode searchLimit (double-resolution caveat); grown #4414: offset!==0 cache-skip widening + knobs-hash v24; grown #4487: chunkless rows join the cosine blend (no raw-score head start); grown wave-g (#4480 #4415): shared salience/recency resolution + pattern-aware cache keying; grown db-availability loop: all-lexical-arms-dead access-error rethrow (a dead DB must never return an empty success) — refined to both-arms-FAILED (a succeeded-but-empty arm proves the DB is alive); grown v0.46.26.0 megawave: CRAG escalation seam, degradation visibility, excludePrivate knobs-fold v23 (#1663 #3873 #4352); grown #4356: semantic-cache-hit slice honors resolved mode searchLimit (double-resolution caveat); grown #4414: offset!==0 cache-skip widening + knobs-hash v24; grown #4487: chunkless rows join the cosine blend (no raw-score head start); grown wave-g (#4480 #4415): shared salience/recency resolution + pattern-aware cache keying; +2: backlink-boost counts page-id keying doc (#4380); +59 2026-09 adversarial batch 2: both-mode text-only demotion gate (textVectorArmNonEmpty) + relaxed_dropped meta + keyword_relaxed_carried degraded stamp + intent-skew caveat docs; +35 #3617 follow-up: relaxed-row fusion demotion (vectorArmNonEmpty gate + keywordFusionList/titleFusionList) with the LongMemEval 51.3%-vs-93.8% receipt comment; +24 2026-08 eval fix wave (E5b/D8): adaptive-return knobs-hash v27 fold (resolved gate + intent class threaded to the cache key), adaptive-on skipCache removal, dedupOpts cache-skip honesty, explicit-maxPerPage min() precedence under walk widening; (#4380); +20 wave #4256: compiledTruthBoost helper — synthetic chunkless title rows (chunk_id 0 + empty chunk_text) never gain the 2x compiled-truth boost (#3695); composition true-up (fix-wave multi-train) | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: read-policy propagation and semantic result-cache containment; ranker wave v0.48.4.0: role-tagged fusion arms, relational rerank pin, metadata boost gate, per-call knob seams, onRerankPool hook (+150) merged over master's read-policy plumbing (+31); +11 #4359 (#4972): thread the loaded search-mode config snapshot from hybridSearchCached into the inner hybridSearch call (INTERNAL _searchModeInput opt) so both resolve from the same one DB-plane config read instead of two independent ones — closes the cache-key/result desync window and removes the second config-table round trip on every hybridSearchCached call; #5252 wave: inclusive date bounds and public vector incompleteness; shared date-bounds peel retains exports; merged company ingestion/schema routing changes; retired provider integration removed; lowered fw3-search: alias hop peeled to search/alias-hop.ts; +5 fw3-search: general title-mention boost skips concept intent and relational questions; fix wave 3 x fix wave 2 (v0.60.5.0) composition: -90 at the merge (hybrid.ts: alias hop lives in search/alias-hop.ts)+src/core/types.ts 2086 ratchet +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the mergesrc/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)@@ -36,8 +36,9 @@ src/core/embedding-migration.ts 1513 ratchet new row: crossed 1500 in v0.46.25.0src/core/github-source.ts 1576 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrappersrc/commands/hook.ts 1892 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcriptssrc/core/chunkers/code.ts 1582 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES-src/core/config.ts 1794 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave+src/core/config.ts 1795 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the mergesrc/core/bootstrap/harness.ts 2656 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion basesrc/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl optionsrc/core/ops/pages.ts 613 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter-src/core/search/mode.ts 1495 ratchet +5 #3617 follow-up: v27 same-knobs behavioral-change note (relaxed-row fusion demotion rides the bump); new row: crossed the 1500 unlisted cap in the 2026-08 eval fix wave — KNOBS_HASH v=27 adaptive-return fold (ar/arem/arom/armk/ari parts + KnobsHashContext.adaptiveReturn field + contamination rationale comments) | merged v0.48.1.0 (+#4787) true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: four knobs (expansion_variant_budget, relational_rerank_pin, keyword_arm_confidence_floor, metadata_boost_gate) + v29 hash parts + doc receipts (+218); #4781 loadSearchModeConfig reads the config table once via loadConfigSnapshot (+6); +4 #4359: update loadSearchModeConfig docstring — the cached path now reads config once (threaded snapshot), not twice; retired provider integration removed+src/core/search/mode.ts 1507 ratchet +5 #3617 follow-up: v27 same-knobs behavioral-change note (relaxed-row fusion demotion rides the bump); new row: crossed the 1500 unlisted cap in the 2026-08 eval fix wave — KNOBS_HASH v=27 adaptive-return fold (ar/arem/arom/armk/ari parts + KnobsHashContext.adaptiveReturn field + contamination rationale comments) | merged v0.48.1.0 (+#4787) true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: four knobs (expansion_variant_budget, relational_rerank_pin, keyword_arm_confidence_floor, metadata_boost_gate) + v29 hash parts + doc receipts (+218); #4781 loadSearchModeConfig reads the config table once via loadConfigSnapshot (+6); +4 #4359: update loadSearchModeConfig docstring — the cached path now reads config once (threaded snapshot), not twice; retired provider integration removed; +12 fw3-search: search.source_boosts + search.alias_token_hop read in the mode snapshot+src/commands/eval-longmemeval.ts 1518 ratchet new row: crossed the 1500 unlisted cap in fw3-search (#5092 benchmark-brain recycling: configureBrain split + recycler wiring + test seams; the recycler itself lives in src/eval/longmemeval/harness.ts)diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsvindex baee8fde6e..623ac60b06 100644--- a/scripts/structural-suites.tsv+++ b/scripts/structural-suites.tsv@@ -138,6 +138,7 @@ test/extract-atoms-drain.test.ts extract-atoms-drain Minion handler retries on ptest/extract-atoms-drain.test.ts protected-names register comment names the real trust mechanism 1 readFileSynctest/extract-atoms-drain.test.ts shared wiring helper holds the cycle lock (5A) 2 readFileSynctest/extract-include-frontmatter-config.serial.test.ts no extraction path hardcodes includeFrontmatter 1 readFileSync+test/fact-withdrawal-prepare-wiring.test.ts (file-level) 2 readFileSynctest/facts-backstop-remedy-verb.test.ts facts backstop thin-client-fallback remedy verb (#4489) 3 readFileSynctest/features.test.ts CLI routing 2 bun-filetest/fence-extraction.test.ts Layer 8 D2 — markdown fence extraction 18 readFileSyncdiff --git a/src/cli.ts b/src/cli.tsindex 826d0bc3ef..8cc015f9af 100755--- a/src/cli.ts+++ b/src/cli.ts@@ -2903,6 +2903,7 @@ async function handleCliOnly(command: string, args: string[]) {if (command === 'reindex-code') {if (await (await import('./commands/reindex-code-delegate.ts')).maybeDelegateReindexCode(loadConfig(), args)) return;}+ if (command === 'extract' && args.includes('--stale') && !hasHelpFlag(args) && await (await import('./commands/extract-stale-delegate.ts')).maybeDelegateExtractStale(loadConfig(), args)) return;if (command === 'embed' && args.includes('--facts')) {if (await (await import('./commands/embed-facts-delegate.ts')).maybeDelegateFactEmbed(loadConfig(), args)) return;diff --git a/src/commands/config.ts b/src/commands/config.tsindex bcda406046..7e386eeb7c 100644--- a/src/commands/config.ts+++ b/src/commands/config.ts@@ -846,11 +846,11 @@ export async function runConfig(engine: BrainEngine, args: string[]) {// #4348: validate cycle.timezone at set time — resolveCycleDate falls// back loudly at run time, but the typo should be rejected here, at the// moment the operator can fix it.- if (key === 'cycle.timezone') {+ if (key === 'cycle.timezone' || key === 'brain.timezone') {const { isValidTimeZone } = await import('../core/cycle/cycle-date.ts');if (!isValidTimeZone(value)) {console.error(- `[config] cycle.timezone must be a valid IANA timezone ` ++ `[config] ${key} must be a valid IANA timezone ` +`(for example Asia/Kolkata or America/Los_Angeles; got '${value}').`,);process.exit(1);diff --git a/src/commands/doctor.ts b/src/commands/doctor.tsindex 2e99efade8..b6c5461dbd 100644--- a/src/commands/doctor.ts+++ b/src/commands/doctor.ts@@ -2675,6 +2675,12 @@ export async function buildChecks(} finally {staleMentionsHb();}+ progress.heartbeat('timeline_orphans');+ const { timelineOrphansCheck } = await import('./doctor/checks/timeline-orphans.ts');+ checks.push(await timelineOrphansCheck(engine));+ progress.heartbeat('slug_collisions');+ const { slugCollisionsCheck } = await import('./doctor/checks/slug-collisions.ts');+ checks.push(await slugCollisionsCheck(engine));// 9d. Wave 2 residual-state signals (#5567, #5525): database-only timeline// rows and derived pages without explicit visibility. Bounded, never throw.diff --git a/src/commands/doctor/checks/slug-collisions.ts b/src/commands/doctor/checks/slug-collisions.tsnew file mode 100644index 0000000000..b799772e89--- /dev/null+++ b/src/commands/doctor/checks/slug-collisions.ts@@ -0,0 +1,55 @@+/**+ * slug_collisions doctor check (A3): files in a source checkout that map to+ * the same page slug (`notes/Foo Bar.md` and `notes/foo-bar.md`, or two+ * spellings that differ only by case). Sync imports only one of them and+ * skips the other with a stderr warning, so the loser never reaches the brain.+ *+ * Read-only. Walks each live source's local checkout with the sync walker (no+ * file reads) and groups the paths by the slug the importer would give them.+ * Sources without a local checkout are skipped.+ */++import { existsSync } from 'fs';+import { relative } from 'path';+import type { BrainEngine } from '../../../core/engine.ts';+import type { Check } from '../../doctor.ts';+import { collectSyncableFiles } from '../../import.ts';+import { resolveSlugForPath, type SyncStrategy } from '../../../core/sync.ts';+import { isImageFilePath } from '../../../core/import-file.ts';++export async function slugCollisionsCheck(engine: BrainEngine): Promise<Check> {+ try {+ const sources = await engine.executeRaw<{ id: string; local_path: string | null; config: { strategy?: SyncStrategy } | null }>(+ `SELECT id, local_path, config FROM sources WHERE archived IS NOT TRUE AND local_path IS NOT NULL ORDER BY id`);+ const groups: Array<{ source: string; slug: string; paths: string[]; indexed?: string }> = [];+ let walked = 0;+ for (const source of sources) {+ if (!source.local_path || !existsSync(source.local_path)) continue;+ walked++;+ const bySlug = new Map<string, string[]>();+ for (const file of collectSyncableFiles(source.local_path, { strategy: source.config?.strategy ?? 'markdown' })) {+ const rel = relative(source.local_path, file).replace(/\\/g, '/');+ const slug = isImageFilePath(rel) ? rel.toLowerCase() : resolveSlugForPath(rel);+ bySlug.set(slug, [...(bySlug.get(slug) ?? []), rel]);+ }+ for (const [slug, paths] of bySlug) {+ if (paths.length < 2) continue;+ const [owner] = await engine.executeRaw<{ source_path: string }>(+ 'SELECT source_path FROM pages WHERE source_id = $1 AND source_path = ANY($2::text[]) AND deleted_at IS NULL LIMIT 1', [source.id, paths]);+ groups.push({ source: source.id, slug, paths, indexed: owner?.source_path });+ }+ }+ if (groups.length === 0) {+ return { name: 'slug_collisions', status: 'ok', message: `No slug collisions across ${walked} source checkout(s).` };+ }+ const eg = groups.slice(0, 5).map(g => `${g.source}:${g.slug} <- ${g.paths.join(' | ')}${g.indexed ? ` (indexed: ${g.indexed})` : ''}`).join('; ');+ return {+ name: 'slug_collisions',+ status: 'warn',+ message: `${groups.length} slug collision(s): two or more files map to one page, and only one is indexed. ` ++ `Rename all but one file in each group, then sync. ${eg}`,+ };+ } catch (e) {+ return { name: 'slug_collisions', status: 'warn', message: `slug collision scan skipped: ${e instanceof Error ? e.message : String(e)}` };+ }+}diff --git a/src/commands/doctor/checks/timeline-orphans.ts b/src/commands/doctor/checks/timeline-orphans.tsnew file mode 100644index 0000000000..34370e8003--- /dev/null+++ b/src/commands/doctor/checks/timeline-orphans.ts@@ -0,0 +1,36 @@+/**+ * timeline_orphans doctor check (#4649, #5170): timeline rows an earlier+ * version of a page produced that its current text no longer does.+ *+ * Extraction was insert-only before v0.59.11 (and `extract --stale` / the+ * full-walk extract until this check shipped), so a corrected or deleted dated+ * bullet left its old row behind. Extraction now retracts them page by page;+ * rows orphaned earlier stay until the page is re-extracted or the one-time+ * prune runs. Read-only and sampled; the write is the explicit+ * `gbrain extract timeline --prune-orphans` command.+ */++import type { BrainEngine } from '../../../core/engine.ts';+import type { Check } from '../../doctor.ts';+import { pruneTimelineOrphans } from '../../../core/timeline-extract.ts';++const SAMPLE_PAGES = 500;++export async function timelineOrphansCheck(engine: BrainEngine): Promise<Check> {+ try {+ const res = await pruneTimelineOrphans(engine, { dryRun: true, limit: SAMPLE_PAGES });+ const coverage = res.pagesScanned >= SAMPLE_PAGES ? ` (sampled the first ${SAMPLE_PAGES} pages with timeline rows)` : '';+ if (res.orphans === 0) {+ return { name: 'timeline_orphans', status: 'ok', message: `No orphaned timeline rows across ${res.pagesScanned} page(s)${coverage}.` };+ }+ const eg = res.examples.map(e => `${e.source_id}:${e.slug} ${e.date} "${e.summary.slice(0, 60)}"`).join('; ');+ return {+ name: 'timeline_orphans',+ status: 'warn',+ message: `${res.orphans} timeline row(s) came from an earlier version of their page and are no longer in its text${coverage}. ` ++ `Preview with: gbrain extract timeline --prune-orphans --dry-run, then remove with: gbrain extract timeline --prune-orphans. e.g. ${eg}`,+ };+ } catch (e) {+ return { name: 'timeline_orphans', status: 'warn', message: `timeline orphan scan skipped: ${e instanceof Error ? e.message : String(e)}` };+ }+}diff --git a/src/commands/embed.ts b/src/commands/embed.tsindex 7dfc552468..7911422a7f 100644--- a/src/commands/embed.ts+++ b/src/commands/embed.ts@@ -8,6 +8,7 @@ import type { BrainEngine } from '../core/engine.ts';import { currentEmbeddingSignature } from '../core/embedding.ts';import type { ChunkInput } from '../core/types.ts';import { carryChunkMetadata, probeEmbedder, resolveProvenanceStamp, stampIfPageProvenanceComplete } from '../core/embed-stale.ts';+import type { StaleImageSweepResult } from '../core/embed-stale-images.ts';import { chunkText } from '../core/chunkers/recursive.ts';import { resolveMaxChunkTokens } from '../core/embedding-input-limit.ts';import { healOversizedPageChunks, healedChunksToStaleRows } from '../core/embed-oversize-heal.ts';@@ -835,7 +836,7 @@ export function isKeylessStaleRefusal(args: string[], embeddingDisabled: boolean&& embeddingDisabled === true;}-export async function runEmbed(engine: BrainEngine, args: string[], selectedConfig: GBrainConfig | null = null): Promise<EmbedResult | EmbedFactsResult | undefined> {+export async function runEmbed(engine: BrainEngine, args: string[], selectedConfig: GBrainConfig | null = null): Promise<EmbedResult | EmbedFactsResult | StaleImageSweepResult | undefined> {if (args.includes('--facts')) {const result = await embedStaleFacts(engine, parseFactEmbedArgs(args), selectedConfig);console.log(JSON.stringify(result, null, 2));@@ -858,6 +859,7 @@ export async function runEmbed(engine: BrainEngine, args: string[], selectedConf};}+ if (args.includes('--images')) return (await import('../core/embed-stale-images.ts')).runEmbedStaleImagesCli(engine, args); // lazy: keeps import-file out of embed's graph// v0.36+ T7: --background submits via Minion queue, returns job_id to// stdout, exits. Same semantics in TTY and cron (D9).if (args.includes('--background')) {@@ -924,7 +926,7 @@ export async function runEmbed(engine: BrainEngine, args: string[], selectedConf} else {const slug = args.find(a => !a.startsWith('--'));if (!slug) {- serr('Usage: gbrain embed [<slug>|--all|--stale|--slugs s1 s2 ...] [--dry-run] [--batch-size N] [--priority recent] [--catch-up] [--include-null-signature]');+ serr('Usage: gbrain embed [<slug>|--all|--stale|--slugs s1 s2 ...] [--dry-run] [--batch-size N] [--priority recent] [--catch-up] [--include-null-signature] | --stale --images');process.exit(1);}opts = { slug, dryRun, sourceId, batchSize, priority, catchUp };diff --git a/src/commands/eval-longmemeval.ts b/src/commands/eval-longmemeval.tsindex e1815b6db4..7b5c8615a3 100644--- a/src/commands/eval-longmemeval.ts+++ b/src/commands/eval-longmemeval.ts@@ -40,7 +40,8 @@import { homedir } from 'os';import { join } from 'path';import { execFileSync } from 'child_process';-import { withBenchmarkBrain, resetTables } from '../eval/longmemeval/harness.ts';+import { brainRecycler, createBenchmarkBrain, LME_BRAIN_RECYCLE_EVERY, resetTables } from '../eval/longmemeval/harness.ts';+export { LME_BRAIN_RECYCLE_EVERY };import { haystackToPages, normalizeSessions } from '../eval/longmemeval/adapter.ts';import {generateAnswer,@@ -488,6 +489,9 @@ export interface RunOpts {* the result of createBenchmarkBrain(); the caller owns lifecycle.*/engine?: PGLiteEngine;+ /** #5092 test seams: brain recycle interval and factory (harness-owned brain only). */+ brainRecycleEvery?: number;+ createBrain?: () => Promise<PGLiteEngine>;/*** Live nightly-probe search-mode/reranker settings copied into the isolated* benchmark brain (#3676). Explicit pin flags (--mode/--reranker/--autocut/@@ -1127,7 +1131,7 @@ export async function runEvalLongMemEval(args: string[], runOpts: RunOpts = {}):embedTxn: (fn) => fn(),};- const work = async (engine: PGLiteEngine): Promise<void> => {+ const configureBrain = async (engine: PGLiteEngine): Promise<void> => {// #3676: nightly probe callers may copy audited live search config into// this isolated engine. Data tables stay hermetic.for (const [key, value] of Object.entries(runOpts.searchConfigSnapshot ?? {})) {@@ -1146,6 +1150,10 @@ export async function runEvalLongMemEval(args: string[], runOpts: RunOpts = {}):if (opts.expansionVariantBudget !== undefined) {await engine.setConfig('search.expansion_variant_budget', opts.expansionVariantBudget === null ? 'legacy' : String(opts.expansionVariantBudget));}+ };++ const work = async (engine: PGLiteEngine): Promise<void> => {+ await configureBrain(engine);// Resolved reranker pin on (flag, --search-pin, snapshot or bundle):// preflight. A reranker that cannot run would silently turn every row@@ -1191,6 +1199,9 @@ export async function runEvalLongMemEval(args: string[], runOpts: RunOpts = {}):// below; a fresh output path (no resume, or a resume into a different// file) is truncated and the prior rows are carried forward explicitly.const emitter = makeEmitter(opts.outputPath, appendOutput);+ // #5092: a harness-owned brain is replaced on a fixed cadence (see brainRecycler).+ const brains = brainRecycler(engine, runOpts.engine ? 0 : (runOpts.brainRecycleEvery ?? LME_BRAIN_RECYCLE_EVERY),+ runOpts.createBrain ?? createBenchmarkBrain, configureBrain);progress.start('eval.longmemeval', backfill.length + questions.length);try {// Judge-only backfill first (prior rows, no reader call), then re-emit@@ -1216,9 +1227,10 @@ export async function runEvalLongMemEval(args: string[], runOpts: RunOpts = {}):if (opts.judge && !appendOutput) emitter.emit(row);}for (const q of questions) {+ const brain = await brains.next();const qStart = Date.now();try {- const outcome = await runOneQuestion(engine, q, ctx);+ const outcome = await runOneQuestion(brain, q, ctx);if (judgeCtx && typeof outcome.row.error !== 'string') {// Judge inline from the row's hypothesis (the same path the backfill// takes). A judge THROW (judgeRow never throws for a transport@@ -1281,6 +1293,7 @@ export async function runEvalLongMemEval(args: string[], runOpts: RunOpts = {}):}}} finally {+ await brains.close();progress.finish();emitter.close();if (appendOutput && opts.outputPath) {@@ -1306,7 +1319,12 @@ export async function runEvalLongMemEval(args: string[], runOpts: RunOpts = {}):// Caller owns engine lifecycle (typically a test beforeAll/afterAll).await work(runOpts.engine);} else {- await withBenchmarkBrain(work);+ const first = await (runOpts.createBrain ?? createBenchmarkBrain)();+ try {+ await work(first);+ } finally {+ await first.disconnect();+ }}if (trajectoryEnabled) {diff --git a/src/commands/extract-stale-delegate.ts b/src/commands/extract-stale-delegate.tsnew file mode 100644index 0000000000..abb9f69d88--- /dev/null+++ b/src/commands/extract-stale-delegate.ts@@ -0,0 +1,43 @@+import type { GBrainConfig } from '../core/config.ts';+import { loadMounts } from '../core/brain-registry.ts';+import { resolveBrainId } from '../core/brain-resolver.ts';+import { getCliOptions } from '../core/cli-options.ts';+import { maybeDelegateLocalAdministration, persistenceConfigForBrain } from '../core/persistence/local-client.ts';+import { inspectLockHolder } from '../core/pglite-lock.ts';+import { OperationError } from '../core/ops/contract.ts';+import { reportPersistenceCliError } from './persistence-delegate.ts';+import { writeStdoutFinal } from '../core/cli-force-exit.ts';+import { formatManagedStaleExtraction, type ManagedLinkExtraction } from '../core/persistence/links-maintenance.ts';++/** A live PGLite owner holds the database; `extract --stale` runs inside it instead of failing on the lock. */+export async function maybeDelegateExtractStale(hostConfig: GBrainConfig | null, args: string[]): Promise<boolean> {+ const brainId = resolveBrainId(getCliOptions().brain, process.cwd());+ const config = persistenceConfigForBrain(hostConfig, brainId, brainId === 'host' ? [] : loadMounts());+ if (config?.engine !== 'pglite' || !config.database_path || config.database_url || !inspectLockHolder(config.database_path).held) return false;+ const json = args.includes('--json');+ try {+ const params: Record<string, unknown> = {};+ for (let i = 0; i < args.length; i++) {+ const arg = args[i];+ if (arg === '--dry-run') params.dry_run = true;+ else if (arg === '--source-id') {+ const value = args[++i];+ if (!value || value.startsWith('-')) throw new OperationError('invalid_params', '--source-id requires a value.');+ params.source_id = value;+ } else if (arg === '--source') {+ if (args[++i] !== 'db') throw new OperationError('invalid_params', "extract --stale is DB-source only; drop '--source fs'.");+ } else if (!['--stale', '--json', '--include-frontmatter', '--catch-up', 'all'].includes(arg)) {+ throw new OperationError('invalid_params', `Unsupported owner-delegated extract --stale option: ${arg}.`);+ }+ }+ const delegated = await maybeDelegateLocalAdministration('writer_extract_stale', params, config, { timeoutMs: 86_400_000 });+ if (!delegated.handled) throw new OperationError('owner_unavailable', 'The registered owner stopped before extraction. Retry the same command.');+ const result = delegated.result as ManagedLinkExtraction;+ const dryRun = params.dry_run === true;+ await writeStdoutFinal(formatManagedStaleExtraction(result, dryRun, json) + '\n');+ return true;+ } catch (error) {+ if (await reportPersistenceCliError(error, json)) return true;+ throw error;+ }+}diff --git a/src/commands/extract.ts b/src/commands/extract.tsindex 9239e8e557..857783a1c9 100644--- a/src/commands/extract.ts+++ b/src/commands/extract.ts@@ -64,12 +64,8 @@ import { resolveIncludeFrontmatter } from '../core/extract-frontmatter.ts';import { inferLinkTypeFromPack } from '../core/schema-pack/link-inference.ts';import { PageRegexBudget } from '../core/schema-pack/redos-guard.ts';export { extractTimelineFromContent, type ExtractedTimelineEntry } from '../core/timeline-extract.ts';-import { extractTimelineFromContent, retractRemovedTimelineEntries, type ExtractedTimelineEntry } from '../core/timeline-extract.ts';+import { extractTimelineFromContent, pruneTimelineOrphans, retractRemovedTimelineEntries, type ExtractedTimelineEntry } from '../core/timeline-extract.ts';import { managedPersistenceEnabled } from '../core/persistence/ownership.ts';-import { withCoordinatedWrite } from '../core/persistence/context.ts';-import { unrecordedCanonicalTimeline } from '../core/persistence/canonical-projections.ts';-import { PageRevisionConflictError } from '../core/page-state/types.ts';-import { DerivedLinkEndpointChangedError } from '../core/derived-links.ts';import { createProgress } from '../core/progress.ts';import { getCliOptions, cliOptsToProgressOptions } from '../core/cli-options.ts';import { pathToSlug, slugifyPath, slugifySegment, pruneDir, isSyncable } from '../core/sync.ts';@@ -816,6 +812,10 @@ Extraction:one transaction (typed_ner rows whose target is still derivablesurvive). Fixes drift the stale_mentions doctor check reports (#3674).gbrain extract <links|timeline|all> --ner --source db+ gbrain extract timeline --prune-orphans [--source-id <id>] [--dry-run] [--json]+ One-time prune: delete timeline rows an earlier version of a page+ produced that its current text no longer does. Rows no version ever+ produced (enrichment, meeting fan-out) are kept (#4649).gbrain extract <timeline|all> --from-meetings --source dbScans only meeting pages (type 'meeting', or 'note' withfrontmatter.legacy_type 'meeting'). REPLACES the default timeline@@ -901,6 +901,30 @@ export async function runExtract(engine: BrainEngine, args: string[], authority?return;}+ // #4649: one-time prune of timeline rows an earlier page version produced+ // that the current text no longer does (orphaned while extraction was+ // insert-only). DB-source; never inserts; --dry-run previews.+ if (args.includes('--prune-orphans')) {+ if (subcommand !== 'timeline') {+ console.error('--prune-orphans applies to timeline rows only: gbrain extract timeline --prune-orphans [--source-id <id>] [--dry-run] [--json]');+ process.exit(1);+ }+ const sidIdx = args.indexOf('--source-id');+ const pruneDryRun = args.includes('--dry-run');+ const r = await pruneTimelineOrphans(engine, {+ coordinated: await managedPersistenceEnabled(engine),+ sourceId: (sidIdx >= 0 && sidIdx + 1 < args.length) ? args[sidIdx + 1] : undefined,+ dryRun: pruneDryRun,+ });+ if (args.includes('--json')) {+ process.stdout.write(JSON.stringify({ action: 'timeline_prune_orphans', dry_run: pruneDryRun, pages_scanned: r.pagesScanned,+ orphans: r.orphans, removed: r.removed, examples: r.examples }) + '\n');+ } else {+ console.log(`Timeline orphans: ${pruneDryRun ? `${r.orphans} would be removed` : `removed ${r.removed}`} across ${r.pagesScanned} page(s) with timeline rows.`);+ }+ return;+ }+const dirIdx = args.indexOf('--dir');const explicitDir = dirIdx >= 0 && dirIdx + 1 < args.length;// When --dir is not passed, resolve from the configured brain source@@ -1368,7 +1392,7 @@ async function extractForSlugs(if (doTimeline) {const entries = extractTimelineFromContent(content, slug);- if (!dryRun) await retractRemovedTimelineEntries(engine, slug, sourceId ?? 'default', entries);+ if (!dryRun) await retractRemovedTimelineEntries(engine, slug, sourceId ?? 'default', content);for (const entry of entries) {if (dryRun) {if (!stdoutQuiet) console.log(` ${entry.slug}: ${entry.date} — ${entry.summary}`);@@ -1412,8 +1436,7 @@ async function extractLinksFromDir(// v0.41.15.0 (T7): in-process worker count. Default 1.workers: number = 1,signal?: AbortSignal,- // #1747/#1503: stamp resolved brain source id on batch rows so the- // addLinksBatch JOIN matches non-'default' source pages.+ // #1747/#1503: the resolved brain source whose pages' links are replaced.sourceId?: string,// Embedded callers own the report: nothing on stdout (see ExtractOpts.quiet).quiet: boolean = false,@@ -1439,27 +1462,10 @@ async function extractLinksFromDir(const progress = createProgress(cliOptsToProgressOptions(getCliOptions()));progress.start('extract.links_fs', files.length);- // Dedup in dry-run only — DB enforces uniqueness via ON CONFLICT in batch writes.- // Without this, the same link extracted from N files would print N times in --dry-run.+ // Dedup in dry-run only, so the same link extracted from N files prints once.const dryRunSeen = dryRun ? new Set<string>() : null;let created = 0;- const batch: LinkBatchInput[] = [];- async function flush() {- if (batch.length === 0) return;- const snapshot = batch.slice();- batch.length = 0;- try {- created += await engine.addLinksBatch(snapshot, { auditSite: 'extract.links_fs' }); // gbrain-allow-direct-insert: gbrain extract command — canonical link reconciliation from markdown body- } catch (e) {- const msg = e instanceof Error ? e.message : String(e);- if (jsonMode) {- process.stderr.write(JSON.stringify({ event: 'batch_error', size: snapshot.length, error: msg }) + '\n');- } else {- console.error(` batch error (${snapshot.length} link rows lost): ${msg}`);- }- }- }await runSlidingPool({items: files,@@ -1467,7 +1473,7 @@ async function extractLinksFromDir(signal,failureLabel: (f) => f.relPath,onItem: async (file) => {- // #1972: bail before this file on abort; trailing flush() commits the batch.+ // #1972: bail before this file on abort; each page's links are replaced in its own transaction.if (isAborted(signal)) return;try {const slug = pathToSlug(file.relPath);@@ -1475,34 +1481,29 @@ async function extractLinksFromDir(? await engine.readPageSnapshot(slug, { sourceId: sourceId ?? 'default' }) : null;const content = readFileSync(file.path, 'utf-8');const links = await extractLinksFromFile(content, file.relPath, allSlugs, { globalBasename, pack, pageTypes });- let reconciled = false;- if (ownership && (snapshot?.page.type === 'meeting' || ownership.origins.has(slug) || links.some(link => link.link_type === 'attended' && link.origin_slug === slug && link.to_slug === slug))) {- if (!snapshot) throw new Error('Link extraction origin is missing');- const written = await replaceFileLinks(engine, slug, sourceId ?? 'default', links, false, snapshot, ownership, content, { pack, globalBasename });- if (written === null) return;- reconciled = written !== undefined;- created += written ?? 0;- }- if (!reconciled) for (const link of links) {- if (dryRunSeen) {- const key = `${link.from_slug}::${link.to_slug}::${link.link_type}`;- if (dryRunSeen.has(key)) continue;- dryRunSeen.add(key);- if (!stdoutQuiet) console.log(` ${link.from_slug} → ${link.to_slug} (${link.link_type})`);- created++;- } else {- batch.push(sourceId- ? { ...link, from_source_id: sourceId, to_source_id: sourceId, origin_source_id: sourceId }- : link);- if (batch.length >= BATCH_SIZE) await flush();+ if (ownership) {+ let written: number | null | undefined;+ if (snapshot?.page.type === 'meeting' || ownership.origins.has(slug) || links.some(link => link.link_type === 'attended' && link.origin_slug === slug && link.to_slug === slug)) {+ if (!snapshot) throw new Error('Link extraction origin is missing');+ written = await replaceFileLinks(engine, slug, sourceId ?? 'default', links, false, snapshot, ownership, content, { pack, globalBasename });+ if (written === null) return;}+ // A file with no page row yet has nothing to reconcile; it is not processed.+ written ??= await replacePageFileLinks(engine, slug, sourceId ?? 'default', links, false, ownership);+ if (written === null) return;+ created += written;+ } else for (const link of links) {+ const key = `${link.from_slug}::${link.to_slug}::${link.link_type}`;+ if (dryRunSeen?.has(key)) continue;+ dryRunSeen?.add(key);+ if (!stdoutQuiet) console.log(` ${link.from_slug} → ${link.to_slug} (${link.link_type})`);+ created++;}processed.push(slug);} catch { /* skip unreadable */ }progress.tick(1);},});- await flush();progress.finish();if (!stdoutQuiet) {@@ -1561,6 +1562,7 @@ async function extractTimelineFromDir(try {const content = readFileSync(file.path, 'utf-8');const slug = pathToSlug(file.relPath);+ if (!dryRunSeen) await retractRemovedTimelineEntries(engine, slug, sourceId ?? 'default', content);for (const entry of extractTimelineFromContent(content, slug)) {if (dryRunSeen) {const key = `${entry.slug}::${entry.date}::${entry.summary}`;@@ -1602,6 +1604,8 @@ async function extractTimelineFromDir(export interface ExtractForSlugsResult {created: number;processed: string[];+ /** Pages whose read or write failed; they stay stale for `extract --stale`. */+ errors?: Array<{ slug: string; error: string }>;}/**@@ -1641,7 +1645,6 @@ export async function extractLinksForSlugs(const pack = (await loadActivePackForLocalEngine(engine, { sourceId }))?.manifest ?? null;if (!pack) throw new Error('Cannot extract links: active schema pack is unavailable.');const pageTypes = loadFsPageTypes(allFiles, pack);- const ownership = await fileLinkOwnership(engine, sourceId);const aliases = await loadSlugAliasTargets(engine, sourceId, allSlugs);// #4999: resolved HERE, like isGlobalBasenameEnabled above, so every caller// (sync, GitHub/Google source inline extracts) honours the configured@@ -1653,27 +1656,38 @@ export async function extractLinksForSlugs(// caller stamps the watermark for these and no others, so a silent skip// leaves the page stale and `extract --stale` picks it up next run.const processed: string[] = [];+ const errors: Array<{ slug: string; error: string }> = [];+ const reads: Array<{ slug: string; relPath: string; content: string; links: LinkBatchInput[] }> = [];for (const slug of slugs) {const relPath = resolveSlugRelPath(slugToPath, repoPath, slug);if (relPath === undefined) continue;- // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- relPath comes from the slug→path index built by walkMarkdownFiles(repoPath) (repo-relative entries of that walk) or the validated-slug legacy fallback, never from a caller- const filePath = join(repoPath, relPath);+ try {+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- relPath comes from the slug→path index built by walkMarkdownFiles(repoPath) (repo-relative entries of that walk) or the validated-slug legacy fallback, never from a caller+ const content = readFileSync(join(repoPath, relPath), 'utf-8');+ reads.push({ slug, relPath, content, links: await extractLinksFromFile(content, relPath, allSlugs, { globalBasename, includeFrontmatter, pack, pageTypes, aliases }) });+ } catch (e) { errors.push({ slug, error: e instanceof Error ? e.message : String(e) }); }+ }+ // A16: metadata for the changed pages and their link endpoints only; the+ // whole-brain load is deferred to the rare attendance (meeting) page.+ const ownership = await fileLinkOwnership(engine, sourceId, { slugs: [...new Set(reads.flatMap(read =>+ [read.slug, ...read.links.flatMap(link => [link.from_slug, link.to_slug])]))] });+ let attendanceOwnership: Awaited<ReturnType<typeof fileLinkOwnership>> | undefined;+ for (const { slug, content, links } of reads) {try {const snapshot = ownership.metadata.get(`${sourceId}\0${slug}`)?.type === 'meeting' || ownership.origins.has(slug)? await engine.readPageSnapshot(slug, { sourceId }) : null;- const content = readFileSync(filePath, 'utf-8');- const links = await extractLinksFromFile(content, relPath, allSlugs, { globalBasename, includeFrontmatter, pack, pageTypes, aliases });let written: number | null | undefined;if (snapshot?.page.type === 'meeting' || ownership.origins.has(slug) || links.some(link => link.link_type === 'attended' && link.origin_slug === slug && link.to_slug === slug)) {if (!snapshot) throw new Error('Link extraction origin is missing');- written = await replaceFileLinks(engine, slug, sourceId, links, includeFrontmatter, snapshot, ownership, content, { pack, globalBasename });+ attendanceOwnership ??= await fileLinkOwnership(engine, sourceId);+ written = await replaceFileLinks(engine, slug, sourceId, links, includeFrontmatter, snapshot, attendanceOwnership, content, { pack, globalBasename });if (written === null) continue;}created += written ?? await replacePageFileLinks(engine, slug, sourceId, links, includeFrontmatter, ownership) ?? 0;processed.push(slug);- } catch { /* skip: unreadable — not processed, stays stale */ }+ } catch (e) { errors.push({ slug, error: e instanceof Error ? e.message : String(e) }); }}- return { created, processed };+ return { created, processed, ...(errors.length ? { errors } : {}) };}export async function extractTimelineForSlugs(@@ -1691,6 +1705,7 @@ export async function extractTimelineForSlugs(const entryOpts = opts?.sourceId ? { sourceId: opts.sourceId } : undefined;let created = 0;const processed: string[] = [];+ const errors: Array<{ slug: string; error: string }> = [];for (const slug of slugs) {const relPath = resolveSlugRelPath(slugToPath, repoPath, slug);if (relPath === undefined) continue;@@ -1699,14 +1714,14 @@ export async function extractTimelineForSlugs(try {const content = readFileSync(filePath, 'utf-8');const entries = extractTimelineFromContent(content, slug);- await retractRemovedTimelineEntries(engine, slug, opts?.sourceId ?? 'default', entries);+ await retractRemovedTimelineEntries(engine, slug, opts?.sourceId ?? 'default', content);processed.push(slug);for (const entry of entries) {try { await engine.addTimelineEntry(entry.slug, { date: entry.date, source: entry.source, summary: entry.summary, detail: entry.detail }, entryOpts); created++; } catch { /* skip */ } // gbrain-allow-direct-insert: gbrain extract single-row fallback for timeline entries}- } catch { /* skip: unreadable — not processed, stays stale */ }+ } catch (e) { errors.push({ slug, error: e instanceof Error ? e.message : String(e) }); }}- return { created, processed };+ return { created, processed, ...(errors.length ? { errors } : {}) };}// ─── DB-source extractors (v0.10.3 graph layer) ────────────────────────────@@ -2006,6 +2021,7 @@ async function extractTimelineFromDB(if (typeFilter && page.type !== typeFilter) continue;const fullContent = page.compiled_truth + '\n' + page.timeline;+ if (!dryRun) await retractRemovedTimelineEntries(engine, slug, source_id, fullContent);let entries = parseTimelineEntries(fullContent);// --infer-dates: pages with no in-body timeline line but a trustworthy// content date (frontmatter / filename) get one anchor entry at that date.@@ -2111,6 +2127,15 @@ export async function extractStaleFromDB(if (!jsonMode) log('No stale pages — extraction is up to date.');return { linksCreated: 0, timelineCreated: 0, pagesProcessed: 0, staleRemaining: 0 };}+ // Managed brains: the writer guard owns canonical rows, so links, missing+ // canonical timeline rows and the watermark publish on the one managed path.+ if (await managedPersistenceEnabled(engine)) {+ const { extractManagedStaleLinks, formatManagedStaleExtraction } = await import('../core/persistence/links-maintenance.ts');+ const r = await extractManagedStaleLinks(engine, { sourceId: sourceIdFilter, ...(catchUp ? {} : { timeBudgetMs }) });+ if (!jsonMode) log(formatManagedStaleExtraction(r, false, false));+ else if (!opts.quiet) process.stdout.write(formatManagedStaleExtraction(r, false, true) + '\n');+ return { linksCreated: r.created, timelineCreated: r.timeline, pagesProcessed: r.pages, staleRemaining: r.remaining, ...(r.skipped ? { skippedChanged: r.skipped } : {}) };+ }// Resolver + cross-source resolution map built ONCE before the loop (the// extractLinksFromDB:1069 precedent — avoids O(pages) rebuild per batch).@@ -2156,10 +2181,8 @@ export async function extractStaleFromDB(let afterPageId = 0;let linksCreated = 0, timelineCreated = 0, pagesProcessed = 0;let skippedAttendanceIncomplete = 0;- let skippedChanged = 0;let budgetHit = false;let packUnavailable = false;- const managed = await managedPersistenceEnabled(engine);// #2576: candidates whose endpoint pages don't exist are skipped, not// persisted. Counted so a dropped reference is observable in the summary// instead of vanishing silently (the failure mode that hid bug 2).@@ -2179,7 +2202,6 @@ export async function extractStaleFromDB(const timelineRows: TimelineBatchInput[] = [];const processedRefs: Array<{ slug: string; source_id: string; extractedAt: string }> = [];- let coordinated = 0;for (const page of rows) {const pack = packs.get(page.source_id);@@ -2219,28 +2241,9 @@ export async function extractStaleFromDB(const origin = { slug: page.slug, sourceId: page.source_id, expectedRevision: snapshot.revision, sourceIncarnation: snapshot.sourceIncarnation };const linkOpts = { includeFrontmatter, expectedEndpoints: capturedLinkEndpoints(linkRows, targetMetadata) };const stampIso = page.updated_at.getTime() >= Date.parse(versionTs) ? page.updated_at_iso : versionTs;- if (managed) {- // #5609: the coordinator owns canonical projections. Derived links, the- // canonical timeline tuples and the watermark publish in one- // revision-bound coordinated transaction; a page edited since the- // read stays stale for the next run.- const published = await engine.transaction(tx => withCoordinatedWrite(tx, [page.source_id], async () => {- const written = await tx.replaceDerivedLinks(origin, linkRows, linkOpts);- const timeline = (await unrecordedCanonicalTimeline(tx, snapshot.page.id, snapshot.page, page.slug)).map(entry => ({ slug: page.slug, date: entry.date,- source: entry.source, summary: entry.summary, detail: entry.detail || '', source_id: page.source_id }));- const created = timeline.length ? await tx.addTimelineEntriesBatch(timeline, { auditSite: 'extract.stale' }) : 0;- await tx.markPagesExtractedBatch([{ slug: page.slug, source_id: page.source_id }], stampIso);- return { links: written.created, timeline: created };- })).catch(error => {- if (error instanceof PageRevisionConflictError || error instanceof DerivedLinkEndpointChangedError) return null;- throw error;- });- if (!published) { skippedChanged++; continue; }- linksCreated += published.links; timelineCreated += published.timeline; coordinated++;- continue;- }const written = await engine.replaceDerivedLinks(origin, linkRows, linkOpts);linksCreated += written.created;+ await retractRemovedTimelineEntries(engine, page.slug, page.source_id, fullContent);for (const entry of parseTimelineEntries(fullContent)) {// #3957: carry the parsed source label — omitting it wrote source=''// while the FS path wrote the split label, so the same bullet@@ -2276,8 +2279,8 @@ export async function extractStaleFromDB(// failure surfaces instead of looping forever.await engine.markPagesExtractedBatch(processedRefs, new Date().toISOString());- pagesProcessed += processedRefs.length + coordinated;- progress.tick(processedRefs.length + coordinated);+ pagesProcessed += processedRefs.length;+ progress.tick(processedRefs.length);afterPageId = rows[rows.length - 1]!.id;if (!catchUp && Date.now() - startMs > timeBudgetMs) { budgetHit = true; break; }@@ -2290,7 +2293,6 @@ export async function extractStaleFromDB(if (!jsonMode) {log(`Extract --stale: ${linksCreated} link(s) + ${timelineCreated} timeline entr(ies) from ${pagesProcessed} page(s).`);if (skippedAttendanceIncomplete) log(`Skipped ${skippedAttendanceIncomplete} page(s) with unresolved attendance; prior links and extraction watermarks were preserved.`);- if (skippedChanged) log(`Skipped ${skippedChanged} page(s) edited during extraction; they stay stale for the next run.`);if (skippedMissingTarget > 0) {log(`Skipped ${skippedMissingTarget} candidate(s) whose target page doesn't exist (references to non-pages are never persisted).`);}@@ -2306,11 +2308,10 @@ export async function extractStaleFromDB(pages_processed: pagesProcessed, stale_remaining: staleRemaining, budget_hit: budgetHit,skipped_missing_target: skippedMissingTarget, skipped_cross_source: skippedCrossSource,...(skippedAttendanceIncomplete ? { skipped_attendance_incomplete: skippedAttendanceIncomplete } : {}),- ...(skippedChanged ? { skipped_changed: skippedChanged } : {}),}) + '\n');}return { linksCreated, timelineCreated, pagesProcessed, staleRemaining, skippedMissingTarget, skippedCrossSource,- ...(skippedAttendanceIncomplete ? { skippedAttendanceIncomplete } : {}), ...(skippedChanged ? { skippedChanged } : {}) };+ ...(skippedAttendanceIncomplete ? { skippedAttendanceIncomplete } : {}) };}/**diff --git a/src/commands/import.ts b/src/commands/import.tsindex e5c8b24db3..4246727cf9 100644--- a/src/commands/import.ts+++ b/src/commands/import.ts@@ -5,6 +5,7 @@ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'patimport { cpus, totalmem } from 'os';import type { BrainEngine } from '../core/engine.ts';import { importFile, importImageFile, isImageFilePath } from '../core/import-file.ts';+import { gitFirstCommitDates } from '../core/git-first-commit.ts';import { currentCompanyBrainSync, getCompanyBrainProfile, importCompanyBrainFile } from '../core/company-brain/profile.ts';import { loadConfig, gbrainPath } from '../core/config.ts';import { createProgress } from '../core/progress.ts';@@ -632,6 +633,10 @@ export async function runImport(progress.tick(1, `imported=${imported} skipped=${skipped} errors=${errors}`);}+ // A12 (opt-in): git first-commit dates anchor undated new pages instead of clone-time mtimes.+ const firstCommits = !singleFile && await engine.getConfig('sync.git_first_commit_dates').catch(() => null) === 'true'+ ? gitFirstCommitDates(dir) : null;+async function processFile(eng: BrainEngine, filePath: string) {if (signal?.aborted) return;const relativePath = singleFile ? basename(filePath) : relative(dir, filePath);@@ -653,7 +658,7 @@ export async function runImport(? await importManagedFile(eng, filePath, importRelPath, { noEmbed, sourceId, activePack: importActivePack, signal, slugRoot: opts.slugRoot }): isImageFilePath(relativePath) && process.env.GBRAIN_EMBEDDING_MULTIMODAL === 'true'? await importImageFile(eng, filePath, importRelPath, { noEmbed, sourceId })- : await importFile(eng, filePath, importRelPath, { noEmbed, sourceId, activePack: importActivePack });+ : await importFile(eng, filePath, importRelPath, { noEmbed, sourceId, activePack: importActivePack, firstCommitAt: firstCommits?.get(filePath) });// An import that landed while cancellation arrived is still complete.// Account for it before stopping, so resume never loses a successful path.noteTypeWarning((result as { type_warning?: Parameters<typeof noteTypeWarning>[0] }).type_warning);diff --git a/src/commands/sync-diagnostics.ts b/src/commands/sync-diagnostics.tsindex 5fc6173af2..4634493aac 100644--- a/src/commands/sync-diagnostics.ts+++ b/src/commands/sync-diagnostics.ts@@ -14,3 +14,15 @@ export function printManagedSyncDiagnostic(result: SyncResult, sink: NodeJS.Writif (d.ledger_recorded === false) write(' Local failure ledger unavailable; the durable receipt above remains authoritative.');return true;}++/** Informational managed-sync lines: skipped slug collisions and the links derived after the checkpoint. */+export function printManagedSyncNotes(result: SyncResult, write: (line: string) => void): void {+ for (const collision of result.slugCollisions ?? []) {+ write(` Slug collision: ${collision.skipped.join(', ')} and ${collision.kept} map to ${collision.slug}; kept ${collision.kept}. Rename one file to import both.`);+ }+ const links = result.links;+ if (links && (links.created || links.removed || links.remaining)) {+ write(` Links: ${links.created} created, ${links.removed} removed across ${links.pages} page(s)` ++ (links.remaining ? `; ${links.remaining} page(s) still owe extraction — run 'gbrain extract --stale'.` : '.'));+ }+}diff --git a/src/commands/sync.ts b/src/commands/sync.tsindex 2d1828493b..0e70a643c9 100644--- a/src/commands/sync.ts+++ b/src/commands/sync.ts@@ -74,7 +74,7 @@ import { loadStorageConfig, findDbOnlyCollisions } from '../core/storage-config.// time. integrations.ts is side-effect-free at module load (pure recipe I/O// helpers), so a static import is safe here.import { getConfiguredCollectorOutputs } from './integrations.ts';-import { printManagedSyncDiagnostic } from './sync-diagnostics.ts';+import { printManagedSyncDiagnostic, printManagedSyncNotes } from './sync-diagnostics.ts';import { getDefaultSourcePath } from '../core/source-resolver.ts';// v0.41.32.0: stamp the durable newest-COMMIT timestamp at sync time so the// remote staleness path reads a column instead of shelling out to git.@@ -277,6 +277,8 @@ export interface SyncResult {* bookmark advancement; rename the files to import them.*/malformedSkipped?: number;+ /** Managed sync: files skipped because another origin keeps their slug, and links derived after the checkpoint. */+ slugCollisions?: import('../core/persistence/sync-discovery.ts').SyncSlugCollision[]; links?: import('../core/persistence/links-maintenance.ts').ManagedLinkExtraction;/*** Aggregated alias/undeclared explicit-type warnings (schema.type_warnings,* default on) — one entry per distinct non-canonical type this run.@@ -292,6 +294,8 @@ export interface SyncResult {* the working tree was imported (detached HEAD or --working-tree).*/uncommitted?: { added: number; modified: number; deleted: number };+ /** Post-sync link/timeline extraction failure (A15); the affected pages stay stale. */+ extract_error?: string;/** #5050: full sync re-sealed unchanged pages at the safe-chunk fence (see RunImportResult.resealed). */resealed?: import('./import.ts').RunImportResult['resealed'];/**@@ -3905,6 +3909,7 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<Sy` Run 'gbrain extract --stale${opts.sourceId ? ` --source-id ${opts.sourceId}` : ''}' to extract now.`,);}+ let extractError: string | undefined;if (!opts.noExtract && totalChanges <= 100 && pagesAffected.length > 0) {try {const { extractLinksForSlugs, extractTimelineForSlugs, stampExtracted, slugsSafeToStamp } = await import('./extract.ts');@@ -3928,7 +3933,14 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<SyslugsSafeToStamp(linksResult, timelineResult).map((slug) => ({ slug, source_id: opts.sourceId ?? 'default' })),);- } catch { /* extraction is best-effort */ }+ const failed = [...(linksResult.errors ?? []), ...(timelineResult.errors ?? [])];+ if (failed.length > 0) extractError = `${failed.length} page(s) not extracted, e.g. ${failed[0]!.slug}: ${failed[0]!.error}`;+ } catch (e) {+ extractError = e instanceof Error ? e.message : String(e);+ }+ // A15: best-effort (the import stands and failed pages stay stale for+ // `extract --stale`), but never silent.+ if (extractError) serr(` Link/timeline extraction failed: ${extractError}. Run 'gbrain extract --stale${opts.sourceId ? ` --source-id ${opts.sourceId}` : ''}' after fixing it.`);}// v0.31.2: facts extraction now routes through the shared@@ -4037,6 +4049,7 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<SymalformedSkipped: malformedSkipped.length,...(typeWarningsEnabled && typeWarnings.length > 0 ? { type_warnings: typeWarnings } : {}),...(uncommittedDrift ? { uncommitted: uncommittedDrift } : {}),+ ...(extractError ? { extract_error: extractError } : {}),};}@@ -5999,4 +6012,5 @@ export function printSyncResult(result: SyncResult, sink: NodeJS.WriteStream = pwrite(` Re-run 'gbrain sync' to continue (last_commit unchanged; safe to retry).`);break;}+ printManagedSyncNotes(result, write);}diff --git a/src/commands/takes.ts b/src/commands/takes.tsindex b661f86257..8f46ba859d 100644--- a/src/commands/takes.ts+++ b/src/commands/takes.ts@@ -588,14 +588,29 @@ async function cmdExtract(engine: BrainEngine, rest: string[]): Promise<void> {}// #4473: takes are markdown-canonical — pages the fence writer refused are// skipped (never written DB-only). Say so instead of silently undercounting.- if (result.pages_skipped > 0) {- const reasons = [...new Set(result.skipped.map((s) => s.reason))].join(', ');+ const unlocatable = result.skipped.filter((s) => !s.reason.startsWith('llm_error:'));+ if (unlocatable.length > 0) {+ const reasons = [...new Set(unlocatable.map((s) => s.reason))].join(', ');process.stderr.write(- `[takes extract] ${result.pages_skipped} page(s) skipped (${reasons}) — takes are ` ++ `[takes extract] ${unlocatable.length} page(s) skipped (${reasons}) — takes are ` +`markdown-canonical; a page with no locatable .md file is not written. ` +`Configure sync.repo_path (or the source's local_path) and re-run.\n`,);}+ const llmErrors = result.skipped.filter((s) => s.reason.startsWith('llm_error:'));+ if (llmErrors.length > 0) {+ const reasons = [...new Set(llmErrors.map((s) => s.reason))].join(', ');+ process.stderr.write(`[takes extract] ${llmErrors.length} page(s) skipped because the model call failed (${reasons}).\n`);+ }+ if (result.budget_exhausted) {+ process.stderr.write(+ `[takes extract] stopped at the USD budget; raise it with ` ++ `\`gbrain config set takes.bootstrap_budget_usd <usd>\` and re-run to continue.\n`,+ );+ }+ if (result.duplicates_skipped > 0) {+ process.stderr.write(`[takes extract] ${result.duplicates_skipped} claim(s) already in the page's takes fence were not re-added.\n`);+ }process.stdout.write(`takes extract --from-pages: ${result.claims_extracted} claim(s) from ${result.pages_scanned} page(s)` +(dryRun ? ' (dry-run)' : '') + '\n',diff --git a/src/commands/transcripts.ts b/src/commands/transcripts.tsindex a73b2709c4..09e20bcfda 100644--- a/src/commands/transcripts.ts+++ b/src/commands/transcripts.ts@@ -306,14 +306,16 @@ export function fmtSummary(r: TranscriptsIngestResult): string {const byHarness = new Map<string, number>();for (const f of r.files) {for (const s of f.sessions) {- if (!s.error) byHarness.set(s.harness, (byHarness.get(s.harness) ?? 0) + 1);+ if (!s.error && !s.skipped) byHarness.set(s.harness, (byHarness.get(s.harness) ?? 0) + 1);}}const lines: string[] = [];const counts = [...byHarness.entries()].map(([h, n]) => `${h}: ${n}`).join(', ');lines.push(`sessions: ${r.sessionsImported} imported (${counts || 'none'}), ` +- `${r.sessionsFiltered} filtered, ${r.sessionsErrored} errored, ${r.sessionsSeen} seen`,+ `${r.sessionsFiltered} filtered, ${r.sessionsErrored} errored, ` ++ (r.sessionsSkippedNoTimestamp ? `${r.sessionsSkippedNoTimestamp} skipped (no timestamps), ` : '') ++ `${r.sessionsSeen} seen`,);lines.push(`pages: ${r.pages.imported} imported, ${r.pages.skipped} unchanged` +diff --git a/src/core/backfill-effective-date.ts b/src/core/backfill-effective-date.tsindex b25676cf22..722d691835 100644--- a/src/core/backfill-effective-date.ts+++ b/src/core/backfill-effective-date.ts@@ -146,6 +146,8 @@ export async function backfillEffectiveDate(// batch otherwise; PGLite ignores SET LOCAL outside transactions but// doesn't have the timeout problem in the first place (single writer).const isPostgres = engine.kind === 'postgres';+ // Same zone the importer reads offset-less datetimes in (brain.timezone).+ const timeZone = (await engine.getConfig('brain.timezone').catch(() => null))?.trim() || undefined;while (true) {if (opts.maxRows && examined >= opts.maxRows) break;@@ -197,6 +199,7 @@ export async function backfillEffectiveDate(slug: r.slug,frontmatter: fm,filename,+ timeZone,updatedAt: new Date(r.updated_at),createdAt: fallbackCreatedAt({ existing: r, now: new Date(r.created_at) }),});@@ -228,6 +231,7 @@ export async function backfillEffectiveDate(slug: r.slug,frontmatter: fm,filename,+ timeZone,updatedAt: new Date(r.updated_at),createdAt: fallbackCreatedAt({ existing: r, now: new Date(r.created_at) }),});diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex ea90e64f43..233c0732aa 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -45,17 +45,17 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'conversation-parser': ['--brain', '--help', '--json', '--source'],'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--entity', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--prefer-postgres', '--provenance', '--provider', '--schema-pack', '--scopes', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--to', '--url', '--version'],'db-repair': ['--apply-rewrites', '--brain', '--break-lock', '--db-url', '--dry-run', '--filter', '--force', '--force-retry', '--format', '--help', '--json', '--locks', '--name', '--path', '--prefer-postgres', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--undo-last-rewrite', '--url', '--version', '--yes'],- 'doctor': ['--abbrev-ref', '--abort', '--all', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--check', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--delete-brain', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--env', '--exclude-standard', '--explain', '--fast', '--federated-read', '--file', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--fresh', '--from-pages', '--full', '--gbrain-bin', '--get', '--git-dir', '--git-path', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--include-flagged', '--include-gitignored', '--include-pseudo', '--index-audit', '--init', '--install', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--link-source', '--link-type', '--local', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--mcp-only', '--migrate-only', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-capture', '--no-cron', '--no-embed', '--no-embedding', '--no-hooks', '--no-migrate', '--no-pull', '--no-verify', '--older-than', '--once', '--others', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--prefer-postgres', '--preset', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--pure', '--push-only', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--refresh', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--repo', '--request-id', '--reranker', '--reset', '--restore-only', '--resume', '--retry-failed', '--review-lower', '--scope', '--scopes', '--session', '--set', '--short', '--show-current', '--show-token', '--show-toplevel', '--since', '--skills', '--skills-dir', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slugs', '--source', '--source-id', '--stale', '--status', '--strict', '--supabase', '--surface', '--symbol-kind', '--target', '--target-score', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--type', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--verbose', '--verify', '--version', '--window', '--workers', '--yes'],+ 'doctor': ['--abbrev-ref', '--abort', '--all', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--check', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--delete-brain', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--env', '--exclude', '--exclude-standard', '--explain', '--fast', '--federated-read', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-pages', '--full', '--gbrain-bin', '--get', '--git-dir', '--git-path', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--include-flagged', '--include-gitignored', '--include-pseudo', '--index-audit', '--init', '--install', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--link-source', '--link-type', '--local', '--locks', '--log-noop', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--mcp-only', '--migrate-only', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-capture', '--no-cron', '--no-embed', '--no-embedding', '--no-hooks', '--no-migrate', '--no-pull', '--no-verify', '--older-than', '--once', '--others', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--prefer-postgres', '--preset', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--prune-orphans', '--pure', '--push-only', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--refresh', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--repo', '--request-id', '--reranker', '--reset', '--restore-only', '--resume', '--retry-failed', '--review-lower', '--scope', '--scopes', '--session', '--set', '--short', '--show-current', '--show-token', '--show-toplevel', '--since', '--skills', '--skills-dir', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slugs', '--source', '--source-id', '--stale', '--status', '--strict', '--supabase', '--surface', '--symbol-kind', '--target', '--target-score', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--type', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--verbose', '--verify', '--version', '--window', '--workers', '--yes'],'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--force', '--force-retry', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],- 'embed': ['--all', '--background', '--batch-size', '--brain', '--break-lock', '--budget-ms', '--catch-up', '--db-url', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--help', '--include-null-signature', '--json', '--max-cost-usd', '--max-facts', '--no-embed', '--no-embedding', '--pace', '--pace-max-concurrency', '--path', '--pglite', '--priority', '--progress-interval', '--progress-json', '--quiet', '--slugs', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--yes'],+ 'embed': ['--all', '--background', '--batch-size', '--brain', '--break-lock', '--budget-ms', '--catch-up', '--db-url', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--help', '--images', '--include-null-signature', '--json', '--max-cost-usd', '--max-facts', '--no-embed', '--no-embedding', '--pace', '--pace-max-concurrency', '--path', '--pglite', '--priority', '--progress-interval', '--progress-json', '--quiet', '--show-toplevel', '--slugs', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--yes'],'engine': ['--apply-rewrites', '--brain', '--break-lock', '--db-url', '--help', '--json', '--path', '--prefer-postgres', '--probe', '--source', '--supabase', '--url', '--yes'],'enrich': ['--access', '--asof', '--background', '--bound-slug-prefixes', '--brain', '--concurrency', '--confirm-destructive', '--date', '--days', '--dry-run', '--embedding-dimensions', '--embedding-model', '--entities', '--explain', '--file', '--follow', '--force', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--min-context', '--mode', '--model', '--multimodal', '--once', '--order', '--page', '--path', '--progress-interval', '--progress-json', '--quiet', '--reenrich-after', '--resume', '--session', '--since', '--slug', '--slugs', '--source', '--source-id', '--stats', '--status', '--surface', '--thin', '--thin-threshold', '--timeout', '--trusted-extraction', '--types', '--url', '--workers', '--yes'],'eval': ['--ab-relational', '--against', '--allow-incomplete-judgments', '--allow-mixed-run-config', '--allow-regression', '--asof', '--autocut', '--background', '--baseline', '--batch', '--brain', '--budget-usd', '--budget-usd-answer', '--budget-usd-retrieval', '--by-type', '--by-type-floor', '--by-type-floor-metric', '--candidate', '--capture-pool', '--committed-baseline', '--compare', '--compare-limit', '--concurrent', '--config-a', '--config-b', '--corpus', '--cycles', '--days', '--dedup-cosine', '--dedup-max-per-page', '--dedup-type-ratio', '--dimensions', '--distance-min', '--draws', '--embed-cache', '--embedder', '--embedding-dimensions', '--embedding-model', '--expand', '--expansion', '--expansion-replay', '--expansion-variant-budget', '--explain', '--fixtures', '--follow', '--force-rechunk', '--format', '--from-capture', '--from-db', '--gold', '--grounding-min', '--harness', '--help', '--include-abstention', '--include-holdout', '--input', '--json', '--judge', '--judge-concurrency', '--judge-model', '--justification', '--k', '--keyword-only', '--limit', '--llm', '--max-pair-chars', '--max-tokens', '--max-usd', '--mcp-only', '--md', '--metric', '--min-recall', '--mode', '--model', '--models', '--modes', '--name-only', '--no-cache', '--no-embed-cache', '--no-expand', '--no-llm', '--no-trajectory', '--older-than', '--out', '--output', '--output-dir', '--parallel', '--parity-baseline', '--pglite', '--progress-interval', '--progress-json', '--qrels', '--queries-file', '--query', '--question-ids', '--questions', '--quiet', '--reader-max-tokens', '--reader-mode', '--receipt-dir', '--record', '--refresh-cache', '--reranker', '--resume-from', '--retrieval-only', '--rrf-k', '--rubric-version', '--runs', '--sample', '--sampling', '--save', '--search-pin', '--seed', '--severity', '--short', '--show-toplevel', '--since', '--skip-replay', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slug-prefix', '--source', '--stale', '--status', '--strategy', '--suite', '--suites', '--supabase', '--task', '--threshold', '--threshold-expected-top1', '--threshold-first-relevant-hit', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-recall-at-k', '--threshold-top1', '--timeout', '--tool', '--top-k', '--top-regressions', '--until', '--update-baseline', '--usefulness-min', '--verbose', '--verify', '--with-code-intel', '--yes'],'export': ['--background', '--brain', '--dir', '--explain', '--fix', '--follow', '--help', '--json', '--progress-interval', '--progress-json', '--quiet', '--repo', '--restore-only', '--slug-prefix', '--source', '--timeout', '--type'],- 'extract': ['--admin-intent', '--after-slug', '--apply-preview', '--background', '--backup-verified', '--brain', '--by-mention', '--catch-up', '--checkpoint', '--concurrency', '--confirm', '--dir', '--dry-run', '--expected-epoch', '--expected-state', '--explain', '--follow', '--from-meetings', '--help', '--include-frontmatter', '--infer-dates', '--json', '--kind', '--limit', '--manifest', '--ner', '--pack', '--path', '--progress-interval', '--progress-json', '--quiet', '--rebuild', '--repair-attendance', '--self-transfer', '--since', '--source', '--source-id', '--stale', '--timeout', '--type', '--verbose', '--workers', '--yes'],+ 'extract': ['--admin-intent', '--after-slug', '--apply-preview', '--background', '--backup-verified', '--brain', '--break-lock', '--by-mention', '--catch-up', '--checkpoint', '--concurrency', '--confirm', '--db-url', '--dir', '--dry-run', '--expected-epoch', '--expected-state', '--explain', '--follow', '--from-meetings', '--help', '--include-frontmatter', '--infer-dates', '--json', '--kind', '--limit', '--manifest', '--ner', '--pack', '--path', '--progress-interval', '--progress-json', '--prune-orphans', '--quiet', '--rebuild', '--repair-attendance', '--self-transfer', '--since', '--source', '--source-id', '--stale', '--timeout', '--type', '--verbose', '--workers', '--yes'],'extract-conversation-facts': ['--background', '--brain', '--concurrency', '--confirm-destructive', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--help', '--json', '--limit', '--max-cost', '--max-cost-usd', '--max-runtime', '--no-embedding', '--override-disabled', '--path', '--pglite', '--progress-interval', '--progress-json', '--quiet', '--segment-limit', '--since', '--sleep', '--slug', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--types', '--url', '--workers', '--yes'],- 'features': ['--all', '--auto', '--auto-fix', '--background', '--batch-size', '--brain', '--by-mention', '--catch-up', '--concurrency', '--dir', '--explain', '--facts', '--from-meetings', '--help', '--include-frontmatter', '--include-null-signature', '--infer-dates', '--json', '--kind', '--ner', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--path', '--priority', '--rebuild', '--refresh', '--repo', '--since', '--slugs', '--source', '--source-id', '--stale', '--target', '--type', '--verbose', '--workers'],+ 'features': ['--all', '--auto', '--auto-fix', '--background', '--batch-size', '--brain', '--by-mention', '--catch-up', '--concurrency', '--dir', '--explain', '--facts', '--from-meetings', '--help', '--images', '--include-frontmatter', '--include-null-signature', '--infer-dates', '--json', '--kind', '--ner', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--path', '--priority', '--prune-orphans', '--rebuild', '--refresh', '--repo', '--since', '--slugs', '--source', '--source-id', '--stale', '--target', '--type', '--verbose', '--workers'],'files': ['--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-pointer', '--page', '--progress-interval', '--progress-json', '--quiet', '--retry-failed', '--source', '--timeout', '--type', '--yes'],'forget': ['--brain', '--help', '--json', '--reason', '--request-id', '--source'],'founder': ['--brain', '--help', '--json', '--mcp-only', '--since', '--source', '--until'],@@ -64,17 +64,17 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'google': ['--access', '--account', '--allow-create-db', '--allow-docker', '--brain', '--calendar-id', '--chat-model', '--client-id', '--client-json', '--client-secret', '--code', '--consent-state', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--entity', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--history-days', '--http', '--issuer-url', '--json', '--key', '--kind', '--limit', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-browser', '--no-embedding', '--no-git', '--no-probe', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--paste', '--path', '--pglite', '--port', '--prefer-postgres', '--provenance', '--purge-client', '--reauth', '--retry-failed', '--schema-pack', '--scopes', '--services', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--sync-budget-ms', '--timeout-ms', '--to', '--token-command', '--url', '--version', '--via', '--yes'],'graph-query': ['--brain', '--depth', '--direction', '--help', '--include-foreign', '--json', '--mcp-only', '--source', '--type'],'hook': ['--allow-unverified-remote', '--auto', '--brain', '--cached', '--count', '--diff-filter', '--end-of-options', '--env', '--exclude-standard', '--get', '--harness', '--help', '--jq', '--json', '--name-only', '--others', '--path', '--porcelain', '--pure', '--quiet', '--session', '--show-current', '--show-toplevel', '--source'],- 'import': ['--allow-empty', '--allow-noncanonical-root', '--background', '--brain', '--cached', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--explain', '--follow', '--force', '--force-rechunk', '--fresh', '--help', '--include-gitignored', '--json', '--log-noop', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-verify', '--others', '--path', '--pglite', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--url', '--verify', '--workers'],+ 'import': ['--allow-empty', '--allow-noncanonical-root', '--background', '--brain', '--cached', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--log-noop', '--name-only', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-renames', '--no-verify', '--others', '--path', '--pglite', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--url', '--verify', '--workers'],'init': ['--all', '--allow-create-db', '--allow-docker', '--brain', '--break-lock', '--chat-model', '--check', '--content-root', '--db-only', '--dim', '--embedding-dimensions', '--embedding-model', '--entity', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-expand', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--path', '--pglite', '--prefer-postgres', '--probe', '--provenance', '--quiet', '--schema-pack', '--scopes', '--show-toplevel', '--skip-embed-check', '--source', '--stale', '--status', '--supabase', '--surface', '--to', '--touchpoint', '--url', '--version', '--yes'],'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],'integrity': ['--auto', '--backend', '--background', '--brain', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--supabase', '--timeout', '--type', '--url'],- 'jobs': ['--abbrev-ref', '--access', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--cli-path', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--cost-estimate', '--date', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--explain', '--facts', '--file', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--hard-deadline', '--health-interval', '--help', '--http', '--idempotency-key', '--ids', '--image', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--limit', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--no-worker', '--now', '--older-than', '--once', '--order', '--others', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--phase', '--pid-file', '--priority', '--queue', '--quiet', '--rebuild', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--repo', '--resume', '--retry-failed', '--review-lower', '--segment-limit', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--stats', '--status', '--strategy', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--trusted-extraction', '--type', '--types', '--uninstall', '--url', '--user', '--verbose', '--verify', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],+ 'jobs': ['--abbrev-ref', '--access', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--cli-path', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--cost-estimate', '--date', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--explain', '--facts', '--file', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--hard-deadline', '--health-interval', '--help', '--http', '--idempotency-key', '--ids', '--image', '--images', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--limit', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--no-worker', '--now', '--older-than', '--once', '--order', '--others', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--phase', '--pid-file', '--priority', '--prune-orphans', '--queue', '--quiet', '--rebuild', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--repo', '--resume', '--retry-failed', '--review-lower', '--segment-limit', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--stats', '--status', '--strategy', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--trusted-extraction', '--type', '--types', '--uninstall', '--url', '--user', '--verbose', '--verify', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],'lint': ['--abbrev-ref', '--abort', '--background', '--brain', '--branch', '--cached', '--dry-run', '--exclude', '--explain', '--file', '--fix', '--follow', '--get', '--git-dir', '--git-path', '--help', '--is-inside-work-tree', '--json', '--local', '--name-only', '--no-cron', '--no-verify', '--pat-file', '--path', '--progress-interval', '--progress-json', '--push-only', '--quiet', '--rebase', '--short', '--show-toplevel', '--source', '--timeout', '--unset-all'],'loops': ['--all', '--brain', '--help', '--json', '--source', '--stale-ok', '--status', '--top', '--type'],'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],- 'maintain': ['--all', '--apply', '--background', '--brain', '--break-lock', '--by-mention', '--catch-up', '--concurrency', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--explain', '--fast', '--fix', '--force', '--force-retry', '--force-schema', '--from-meetings', '--full', '--harness', '--help', '--http', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-only', '--multimodal', '--ner', '--no-embed', '--no-pull', '--older-than', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--probe-pglite', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--request-id', '--reset', '--resume', '--retry-failed', '--safe', '--scope', '--scopes', '--show-current', '--since', '--skills-dir', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--symbol-kind', '--target', '--target-score', '--to', '--top-k', '--type', '--url', '--verbose', '--version', '--window', '--workers', '--yes'],+ 'maintain': ['--all', '--apply', '--background', '--brain', '--break-lock', '--by-mention', '--catch-up', '--concurrency', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--explain', '--fast', '--fix', '--force', '--force-retry', '--force-schema', '--from-meetings', '--full', '--harness', '--help', '--http', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-only', '--multimodal', '--ner', '--no-embed', '--no-pull', '--older-than', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--probe-pglite', '--prune-orphans', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--request-id', '--reset', '--resume', '--retry-failed', '--safe', '--scope', '--scopes', '--show-current', '--since', '--skills-dir', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--symbol-kind', '--target', '--target-score', '--to', '--top-k', '--type', '--url', '--verbose', '--version', '--window', '--workers', '--yes'],'mcp': ['--admin-token-file', '--agent', '--arg', '--bearer-token-env-var', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--credentials-file', '--credentials-out', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr', '--federated-read', '--flow', '--force', '--funnel', '--harness', '--header', '--help', '--if-version', '--install', '--issuer-url', '--json', '--limit', '--mcp-only', '--mcp-url', '--no-install', '--no-service', '--no-tailscale', '--oauth-client-id', '--oauth-client-secret', '--oauth-request', '--port', '--profile', '--queue', '--redirect-uri', '--remove', '--resume', '--root', '--scope', '--scopes', '--skills', '--source', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'],- 'migrate': ['--all', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--force-retry', '--help', '--ignore-env-override', '--include-null-signature', '--json', '--locks', '--max-cost-usd', '--no-embed', '--non-interactive', '--pace', '--pace-max-concurrency', '--path', '--priority', '--progress-interval', '--progress-json', '--quiet', '--reranker', '--retarget', '--skip-verify', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--url', '--yes'],+ 'migrate': ['--all', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--force-retry', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--locks', '--max-cost-usd', '--no-embed', '--non-interactive', '--pace', '--pace-max-concurrency', '--path', '--priority', '--progress-interval', '--progress-json', '--quiet', '--reranker', '--retarget', '--skip-verify', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--url', '--yes'],'models': ['--brain', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--skip', '--source', '--status'],'mounts': ['--alias', '--brain', '--database-path', '--database-url', '--db-path', '--db-url', '--engine', '--help', '--id', '--json', '--mcp-url', '--path', '--skills-dir', '--source'],'notability-eval': ['--brain', '--embedding-dimensions', '--embedding-model', '--help', '--in', '--json', '--out', '--repo', '--skip-llm', '--source', '--status', '--target-high', '--target-low', '--target-medium'],@@ -100,7 +100,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'report': ['--brain', '--content', '--dir', '--help', '--json', '--source', '--title', '--type'],'repos': ['--abbrev-ref', '--abort', '--access', '--account', '--admin-intent', '--after', '--all', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--budget-usd-per-day', '--cached', '--calendar-id', '--cleanup-dead-local-locks', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--count', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--detect', '--diff-filter', '--dir', '--dry-run', '--exclude', '--exclude-standard', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--file', '--fix', '--force', '--format', '--from', '--get', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--history-days', '--http', '--id', '--include', '--include-warns', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--limit', '--local', '--manifest', '--max-cost-usd', '--message', '--name', '--name-only', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-pull', '--no-verify', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--preview', '--probe', '--profile', '--push-only', '--quiet', '--rebase', '--redirect-uri', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--stale', '--status', '--surface', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--url', '--usage', '--yes'],'resolvers': ['--backend', '--brain', '--cost', '--help', '--json', '--source'],- 'retrieval-upgrade': ['--all', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--help', '--ignore-env-override', '--include-null-signature', '--json', '--max-cost-usd', '--no-embed', '--non-interactive', '--pace', '--pace-max-concurrency', '--priority', '--progress-interval', '--progress-json', '--quiet', '--reranker', '--retarget', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--yes'],+ 'retrieval-upgrade': ['--all', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--max-cost-usd', '--no-embed', '--non-interactive', '--pace', '--pace-max-concurrency', '--priority', '--progress-interval', '--progress-json', '--quiet', '--reranker', '--retarget', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--yes'],'routing-eval': ['--brain', '--help', '--json', '--llm', '--skills-dir', '--source'],'salience': ['--brain', '--days', '--help', '--json', '--kind', '--limit', '--mcp-only', '--slug-prefix', '--source'],'schema': ['--alias', '--apply', '--as-filing-rules', '--brain', '--dims', '--expert', '--expert-routing', '--extractable', '--force', '--help', '--inverse', '--json', '--kind', '--pack', '--page-type', '--prefix', '--primitive', '--schema-pack', '--since', '--source', '--source-id', '--target-type', '--to', '--with-db'],@@ -115,7 +115,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'status': ['--abbrev-ref', '--all', '--allow-empty', '--brain', '--break-lock', '--cached', '--concurrency', '--confirm-destructive', '--deadline-ms', '--diff-filter', '--empty', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--hard-deadline', '--help', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--others', '--parallel', '--path', '--priority', '--quiet', '--repo', '--retry-failed', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],'storage': ['--brain', '--fix', '--help', '--json', '--repo', '--restore-only', '--source', '--to'],'sweep': ['--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-delegate', '--once', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout'],- 'sync': ['--abbrev-ref', '--abort', '--account', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--auto', '--background', '--batch-size', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--catch-up', '--concurrency', '--confirm-destructive', '--content-audit', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--hard-deadline', '--harness', '--help', '--home', '--http', '--ids', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--log-noop', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-only', '--missing-path', '--multimodal', '--name-only', '--name-status', '--ner', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-recurse-submodules', '--no-renames', '--no-schema-pack', '--no-verify', '--older-than', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--prefer-postgres', '--priority', '--probe-pglite', '--progress-interval', '--progress-json', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--repo', '--request-id', '--reset', '--restore-only', '--resume', '--retry-failed', '--scope', '--scopes', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--target', '--target-score', '--timeout', '--to', '--top-k', '--type', '--url', '--verbose', '--verify', '--version', '--watch', '--window', '--workers', '--working-tree', '--yes'],+ 'sync': ['--abbrev-ref', '--abort', '--account', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--auto', '--background', '--batch-size', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--catch-up', '--concurrency', '--confirm-destructive', '--content-audit', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--hard-deadline', '--harness', '--help', '--home', '--http', '--ids', '--images', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--log-noop', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-only', '--missing-path', '--multimodal', '--name-only', '--name-status', '--ner', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-recurse-submodules', '--no-renames', '--no-schema-pack', '--no-verify', '--older-than', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--prefer-postgres', '--priority', '--probe-pglite', '--progress-interval', '--progress-json', '--prune-orphans', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--repo', '--request-id', '--reset', '--restore-only', '--resume', '--retry-failed', '--scope', '--scopes', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--target', '--target-score', '--timeout', '--to', '--top-k', '--type', '--url', '--verbose', '--verify', '--version', '--watch', '--window', '--workers', '--working-tree', '--yes'],'takes': ['--accept', '--batch-size', '--brain', '--bucket-size', '--by', '--claim', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--force', '--from-pages', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--no-embed', '--no-embedding', '--offset', '--outcome', '--pglite', '--quality', '--reject', '--request-id', '--row', '--semantic', '--since', '--sort', '--source', '--source-id', '--stale', '--status', '--supabase', '--to', '--unit', '--until', '--value', '--weight', '--who', '--yes'],'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--json', '--mcp-only', '--model', '--rounds', '--save', '--since', '--source', '--take', '--until', '--with-calibration'],'transcripts': ['--all', '--all-discovery', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--progress-interval', '--progress-json', '--quiet', '--since', '--source', '--source-id', '--timeout'],diff --git a/src/core/config.ts b/src/core/config.tsindex 93c747549b..46f9c6764e 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -1305,6 +1305,12 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [// #4415: per-brain query-intent pattern extensions (JSON bank→regex[]),// merged over the shipped banks in src/core/search/query-intent.ts.'search.intent_patterns',+ // Per-brain source-boost map (`prefix:factor,...`; `none` drops the+ // defaults), read by search/mode.ts loadSearchModeConfig and ops/search.ts.+ 'search.source_boosts',+ // #5428 opt-in single-token alias hop (`true` enables), read by+ // search/mode.ts loadSearchModeConfig.+ 'search.alias_token_hop',// 2026-08 fix wave (E5a): the adaptive-return / autocut / CRAG knobs were// read by the search path but never registered — `gbrain config set`// rejected them, making the documented config plane a no-op. Read sites:@@ -1388,6 +1394,9 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [// #3852: kill-switch for the deterministic junk gate on extracted fact text// (plan narration / provider error strings / meta-chatter). Default on.'facts.extraction_junk_filter',+ // B-16: confidence stored for an extracted candidate whose confidence is+ // missing or non-numeric (a number in 0..1). Unset keeps the legacy 1.0.+ 'facts.extraction_missing_confidence',// [ENG-8] Brain-level default visibility for facts writes when the caller// didn't specify one: 'private' (default) | 'world'. Resolved by// src/core/facts/visibility.ts; explicit caller values always win.@@ -1469,6 +1478,12 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [// #4348: IANA timezone that owns the dream-cycle calendar day (summary// bucketing). Unset → host timezone → UTC. Validated at set time.'cycle.timezone',+ // A11: IANA timezone for offset-less frontmatter datetimes in effective_date.+ // Unset → UTC (date-only values are always UTC calendar dates). Validated at set time.+ 'brain.timezone',+ // A12 (opt-in, default off): undated new pages in git-backed sources take the+ // file's git first-commit date as their effective-date fallback on full import.+ 'sync.git_first_commit_dates','cycle.grade_takes.write_gstack_learnings',// #4102: off switch for the propose_takes LLM phase (default ON; the// phase ships in the default list). Read by src/core/cycle/propose-takes.ts.@@ -1544,6 +1559,9 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [// consent reads this key, and enabling it is the documented path to// `gbrain takes extract --from-pages` — same unregistered-key class.'takes.bootstrap_enabled',+ // B-14: USD cap for one takes-bootstrap run's classifier calls (default 5.0;+ // 0 disables). Read by src/core/extract-takes-from-pages.ts.+ 'takes.bootstrap_budget_usd',// Orphan reporting scope. These are consumed by core/orphan-policy.ts and// documented there as the per-brain override path.'orphans.exclude_prefixes',diff --git a/src/core/connectors/providers/chatgpt.ts b/src/core/connectors/providers/chatgpt.tsindex 98ba29161f..9992e68225 100644--- a/src/core/connectors/providers/chatgpt.ts+++ b/src/core/connectors/providers/chatgpt.ts@@ -96,15 +96,23 @@ export function toIso(v: unknown): string {* newest-first; breaks early once a stub is at/before `stopBefore` (the* watermark minus the trailing window) since `order=updated` guarantees the* rest are older.+ *+ * C-18: the ordering is live. A conversation archived or deleted mid-walk+ * shifts every later item to a lower offset, so the next page would start one+ * item late; when `total` shrinks the walk steps back by the shrinkage and+ * re-reads. `seen` (shared across passes) yields each id once, so an item+ * that shifted the other way, or moved to the archived pass, is not repeated.*/async function* listPass(client: ConnectorClient,archived: boolean,stopBefore: string | undefined,+ seen: Set<string>,signal?: AbortSignal,): AsyncGenerator<ConversationStub> {let offset = 0;let pages = 0;+ let lastTotal: number | undefined;for (;;) {const q = new URLSearchParams({offset: String(offset),@@ -120,11 +128,23 @@ async function* listPass(`chatgpt: conversations list${archived ? ' (archived)' : ''} returned no items array (shape drift)`,);}+ const total = typeof res.total === 'number' ? res.total : offset + res.items.length;+ if (lastTotal !== undefined && total < lastTotal && offset > 0) {+ offset = Math.max(0, offset - (lastTotal - total));+ lastTotal = total;+ if (++pages >= MAX_LIST_PAGES) {+ throw new Error(`chatgpt: list pass hit the ${MAX_LIST_PAGES}-page cap; refusing to treat a truncated list as complete`);+ }+ continue;+ }+ lastTotal = total;for (const it of res.items) {const id = typeof it.id === 'string' ? it.id : '';if (!id) continue;const updatedAt = toIso(it.update_time) || toIso(it.create_time);if (stopBefore && updatedAt && updatedAt <= stopBefore) return; // rest are older+ if (seen.has(id)) continue;+ seen.add(id);yield {id,title: typeof it.title === 'string' ? it.title : undefined,@@ -132,7 +152,6 @@ async function* listPass(createdAt: toIso(it.create_time) || undefined,};}- const total = typeof res.total === 'number' ? res.total : offset + res.items.length;offset += res.items.length;if (res.items.length === 0 || offset >= total) break;pages++;@@ -205,8 +224,9 @@ export const chatgptProvider: ChatHistoryProvider = {// Pass 1: active threads. Pass 2: archived (D3.1). Each pass breaks at its// own since-bound; the run watermark is the max updatedAt seen across BOTH// passes (the orchestrator tracks it).- yield* listPass(client, false, opts.stopBefore, opts.signal);- yield* listPass(client, true, opts.stopBefore, opts.signal);+ const seen = new Set<string>();+ yield* listPass(client, false, opts.stopBefore, seen, opts.signal);+ yield* listPass(client, true, opts.stopBefore, seen, opts.signal);},async fetchConversation(diff --git a/src/core/connectors/providers/claude.ts b/src/core/connectors/providers/claude.tsindex 620cd6f652..1319d2e6a2 100644--- a/src/core/connectors/providers/claude.ts+++ b/src/core/connectors/providers/claude.ts@@ -7,17 +7,20 @@* `{uuid, name, created_at, chat_messages:[{uuid, sender, created_at, text}]}`).** Endpoints (provisional — see CLAUDE_WEB_API_SPEC_TARGET):- * GET /api/organizations → [{uuid, ...}]- * GET /api/organizations/{org}/chat_conversations → [{uuid, name, created_at, updated_at}]+ * GET /api/organizations → [{uuid, capabilities, ...}]+ * GET /api/organizations/{org}/chat_conversations?limit&offset → [{uuid, name, created_at, updated_at}]* GET /api/organizations/{org}/chat_conversations/{id}?tree=True&rendering_mode=messages** No bearer re-mint: the sessionKey cookie IS the auth, so a 401 is terminal- * (→ auth_required, no refreshAccessToken). The org id is discovered lazily and- * memoized per client instance (each sync builds a fresh client → account-safe).+ * (→ auth_required, no refreshAccessToken). Chat-capable orgs are discovered+ * lazily and memoized per client instance (each sync builds a fresh client →+ * account-safe); every one is listed, and each conversation is fetched from+ * the org that listed it. The list is paged with limit/offset (C-17).*/import type { HostSpecTarget } from '../../bootstrap/host-specs.ts';import type { ConnectorClient } from '../client.ts';+import { toIso } from './chatgpt.ts';import type {ChatHistoryProvider,ConnectorCredential,@@ -37,18 +40,26 @@ export const CLAUDE_WEB_API_SPEC_TARGET: HostSpecTarget = {'test/fixtures/connectors/claude-*.json',],note:- 'Cookie-auth (sessionKey). Org discovered via GET /api/organizations (first uuid). ' +- 'chat_conversations lists {uuid,name,created_at,updated_at}; the detail ' ++ 'Cookie-auth (sessionKey). Orgs discovered via GET /api/organizations; every org ' ++ 'whose capabilities include chat (or that declares none) is listed. ' ++ 'chat_conversations?limit&offset pages {uuid,name,created_at,updated_at} as a flat ' ++ 'array (an unpaged request is capped); the detail ' +'(?tree=True&rendering_mode=messages) returns chat_messages[] whose text is ' +'assembled from content blocks when a flat text is absent; sender human/assistant. ' +'PROVISIONAL: shapes from public documentation + the export adapter fixtures, ' +'not probed live in this repo; drift alarm (no array / no chat_messages) is the backstop.',};-const memoOrg = new WeakMap<ConnectorClient, string>();+const memoOrgs = new WeakMap<ConnectorClient, string[]>();+/** Conversation id → the org that listed it, per client. */+const memoConversationOrg = new WeakMap<ConnectorClient, Map<string, string>>();++const LIST_PAGE_LIMIT = 100;+const MAX_LIST_PAGES = 500; // per org; never treat a truncated list as completeinterface OrgRow {uuid?: string;+ capabilities?: unknown;}interface ConvRow {uuid?: string;@@ -64,16 +75,19 @@ interface MsgRow {content?: Array<{ type?: string; text?: string }>;}-async function resolveOrg(client: ConnectorClient, signal?: AbortSignal): Promise<string> {- const cached = memoOrg.get(client);+/** Every chat-capable org (an org that declares no capabilities counts). */+async function resolveOrgs(client: ConnectorClient, signal?: AbortSignal): Promise<string[]> {+ const cached = memoOrgs.get(client);if (cached) return cached;const orgs = await client.fetchJSON<OrgRow[]>('/api/organizations', { signal });- if (!Array.isArray(orgs) || !orgs.length || typeof orgs[0].uuid !== 'string') {- throw new Error('claude: /api/organizations returned no org (shape drift)');- }- const org = orgs[0].uuid;- memoOrg.set(client, org);- return org;+ const ids = Array.isArray(orgs)+ ? orgs+ .filter((o) => typeof o?.uuid === 'string' && (!Array.isArray(o.capabilities) || o.capabilities.includes('chat')))+ .map((o) => o.uuid as string)+ : [];+ if (!ids.length) throw new Error('claude: /api/organizations returned no chat-capable org (shape drift)');+ memoOrgs.set(client, ids);+ return ids;}/** Assemble message text: prefer flat `text`, else join text-type content blocks. */@@ -108,7 +122,7 @@ export const claudeProvider: ChatHistoryProvider = {async probe(client: ConnectorClient, signal?: AbortSignal): Promise<ProbeResult> {try {- const org = await resolveOrg(client, signal);+ const [org] = await resolveOrgs(client, signal);const list = await client.fetchJSON<ConvRow[]>(`/api/organizations/${encodeURIComponent(org)}/chat_conversations?limit=1`,{ signal },@@ -130,24 +144,47 @@ export const claudeProvider: ChatHistoryProvider = {client: ConnectorClient,opts: { signal?: AbortSignal; stopBefore?: string } = {},): AsyncGenerator<ConversationStub> {- const org = await resolveOrg(client, opts.signal);- const rows = await client.fetchJSON<ConvRow[]>(- `/api/organizations/${encodeURIComponent(org)}/chat_conversations`,- { signal: opts.signal },- );- if (!Array.isArray(rows)) {- throw new Error('claude: chat_conversations returned a non-array (shape drift)');+ const orgs = await resolveOrgs(client, opts.signal);+ const conversationOrg = new Map<string, string>();+ memoConversationOrg.set(client, conversationOrg);+ const stubs: ConversationStub[] = [];+ for (const org of orgs) {+ // Page until an empty page or a page with nothing new (an endpoint that+ // ignores offset returns the same rows again). A whole page at/before+ // the since-bound ends the walk early: the list is newest-first.+ let offset = 0;+ for (let page = 0; ; page++) {+ if (page >= MAX_LIST_PAGES) {+ throw new Error(`claude: list hit the ${MAX_LIST_PAGES}-page cap; refusing to treat a truncated list as complete`);+ }+ const rows = await client.fetchJSON<ConvRow[]>(+ `/api/organizations/${encodeURIComponent(org)}/chat_conversations?limit=${LIST_PAGE_LIMIT}&offset=${offset}`,+ { signal: opts.signal },+ );+ if (!Array.isArray(rows)) {+ throw new Error('claude: chat_conversations returned a non-array (shape drift)');+ }+ let fresh = 0;+ let allOlder = rows.length > 0;+ for (const r of rows) {+ if (typeof r.uuid !== 'string' || conversationOrg.has(r.uuid)) continue;+ fresh++;+ conversationOrg.set(r.uuid, org);+ const updatedAt = toIso(r.updated_at) || toIso(r.created_at);+ if (!opts.stopBefore || !updatedAt || updatedAt > opts.stopBefore) allOlder = false;+ stubs.push({+ id: r.uuid,+ title: typeof r.name === 'string' ? r.name : undefined,+ updatedAt,+ createdAt: toIso(r.created_at) || undefined,+ });+ }+ if (fresh === 0 || allOlder) break;+ offset += rows.length;+ }}// Sort newest-first by updated_at (the API order is not guaranteed).- const stubs: ConversationStub[] = rows- .filter((r): r is ConvRow & { uuid: string } => typeof r.uuid === 'string')- .map((r) => ({- id: r.uuid,- title: typeof r.name === 'string' ? r.name : undefined,- updatedAt: (r.updated_at && String(r.updated_at)) || (r.created_at && String(r.created_at)) || '',- createdAt: r.created_at ? String(r.created_at) : undefined,- }))- .sort((a, b) => (a.updatedAt < b.updatedAt ? 1 : a.updatedAt > b.updatedAt ? -1 : 0));+ stubs.sort((a, b) => (a.updatedAt < b.updatedAt ? 1 : a.updatedAt > b.updatedAt ? -1 : 0));for (const s of stubs) {if (opts.stopBefore && s.updatedAt && s.updatedAt <= opts.stopBefore) return; // rest are olderyield s;@@ -159,7 +196,7 @@ export const claudeProvider: ChatHistoryProvider = {id: string,opts: { signal?: AbortSignal } = {},): Promise<Record<string, unknown>> {- const org = await resolveOrg(client, opts.signal);+ const org = memoConversationOrg.get(client)?.get(id) ?? (await resolveOrgs(client, opts.signal))[0];const conv = await client.fetchJSON<Record<string, unknown>>(`/api/organizations/${encodeURIComponent(org)}/chat_conversations/${encodeURIComponent(id)}?tree=True&rendering_mode=messages`,{ signal: opts.signal },diff --git a/src/core/connectors/sync.ts b/src/core/connectors/sync.tsindex b3d2f829bd..e4820d359d 100644--- a/src/core/connectors/sync.ts+++ b/src/core/connectors/sync.ts@@ -13,9 +13,11 @@* 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.+ * conversation that fails to fetch OR to ingest 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. Ingest outcomes are attributed per conversation (session id =+ * conversation id), so one failing conversation never blocks its batch.** STATE LIVES IN CONFIG SCALARS (`connectors.<p>.source.<id>.*`), NOT* op_checkpoint: op_checkpoint stores a completed-KEY set with no scalar since,@@ -45,7 +47,7 @@ import {} from './config-keys.ts';export const CONNECTOR_SYNC_VERSION = 1;-/** Failed fetches at one updatedAt before a conversation is quarantined. */+/** Failed fetches or ingests at one updatedAt before a conversation is quarantined. */export const QUARANTINE_ATTEMPTS = 3;export type ConnectorSyncStatus =@@ -84,7 +86,7 @@ export interface ConnectorSyncResult {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). */+ /** Conversation ids quarantined after repeated fetch or ingest failures (not re-fetched until edited). */quarantined: string[];spoolPaths: string[];embedKickoff: EmbedKickoffOutcome;@@ -281,7 +283,7 @@ export async function runConnectorSync(const spoolPaths: string[] = [];let fetched = 0;let fetchErrors = 0;- let blockingFetchErrors = 0;+ let blockingFailures = 0;let importedTotal = 0;let skippedTotal = 0;let erroredTotal = 0;@@ -318,17 +320,23 @@ export async function runConnectorSync(return { ...base, status: 'forbidden', listed: stubs.length, fetched, fetchErrors, spoolPaths };}fetchErrors++;- 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++;+ const attempts = recordFailure(stub);log(`[connector] fetch error for ${stub.id} (attempt ${attempts}): ${e instanceof Error ? e.message : String(e)}`);}}if (convs.length) await ingestBatch();await saveLedgers();+ /** Count one failure; quarantined conversations stop blocking the watermark. */+ function recordFailure(stub: ConversationStub): number {+ 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 blockingFailures++;+ return attempts;+ }+async function ingestBatch(): Promise<void> {const stamp = `${new Date(now()).toISOString().replace(/[:.]/g, '-')}-b${bi}`;const spoolPath = writeSpool(opts.provider, convs, stamp);@@ -346,11 +354,20 @@ 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];+ // A file-level problem (unreadable spool, drift, dropped lines) fails+ // the whole batch; otherwise each conversation stands on its own+ // session outcome. A conversation with no session had nothing to import.+ const fileFailed = r.files.some(f => f.error || f.drift || f.truncated || f.skippedLines > 0);+ const sessions = new Map(r.files.flatMap(f => f.sessions).map(s => [s.sessionId, s]));+ for (const stub of convStubs) {+ const session = sessions.get(stub.id);+ if (fileFailed || session?.error) {+ const attempts = recordFailure(stub);+ log(`[connector] ingest error for ${stub.id} (attempt ${attempts}): ${session?.error ?? 'spool file failed to ingest'}`);+ continue;}+ 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 });@@ -375,7 +392,7 @@ export async function runConnectorSync(base.quarantined = quarantined;// Quarantined conversations no longer hold the watermark back.- const clean = !listErrored && blockingFetchErrors === 0 && !capped && allBatchesClean && !opts.signal?.aborted;+ const clean = !listErrored && blockingFailures === 0 && !capped && !opts.signal?.aborted;// Advance the watermark ONLY on a clean run.if (clean && maxUpdatedAt && maxUpdatedAt !== watermark) {diff --git a/src/core/cycle.ts b/src/core/cycle.tsindex ec5dd75683..8cf1b797c6 100644--- a/src/core/cycle.ts+++ b/src/core/cycle.ts@@ -1872,6 +1872,11 @@ export async function runCycle(const dryRun = !!opts.dryRun;const pull = !!opts.pull;const timestamp = new Date().toISOString();+ // C-15: one calendar date for every dated phase of this cycle (a run that+ // crosses midnight, or a UTC host, must not split the cycle across days).+ const cycleDate = engine+ ? await import('./cycle/cycle-date.ts').then(m => m.resolveCycleDate(engine)).catch(() => undefined)+ : undefined;const phaseResults: PhaseResult[] = excludedPhases.map((phase) => ({phase,status: 'skipped',@@ -2247,6 +2252,7 @@ export async function runCycle(yieldDuringPhase: buildYieldDuringPhase(lock, opts.yieldDuringPhase, onStolen),inputFile: opts.synthInputFile,date: opts.synthDate,+ cycleDate,from: opts.synthFrom,to: opts.synthTo,bypassDreamGuard: opts.synthBypassDreamGuard,@@ -2470,6 +2476,7 @@ export async function runCycle(// always-undefined — hook, so long phases never refreshed).yieldDuringPhase: buildYieldDuringPhase(lock, opts.yieldDuringPhase, onStolen),once: opts.onceForPhase === 'patterns',+ cycleDate,deadlineAtMs: opts.deadlineAtMs ?? null,privateQueueOwnerJobId: opts.privateQueueOwnerJobId ?? null,// #1586: scope pattern writes to the cycle's resolved source, same as@@ -2720,6 +2727,7 @@ export async function runCycle(dryRun,brainDir: brainDir ?? undefined,forceEnabled: opts.onceForPhase === 'drift',+ cycleDate,});const status: PhaseStatus =r.status === 'complete' ? 'ok' :diff --git a/src/core/cycle/auto-think.ts b/src/core/cycle/auto-think.tsindex 5b65915eb0..1ea74cbd06 100644--- a/src/core/cycle/auto-think.ts+++ b/src/core/cycle/auto-think.ts@@ -18,7 +18,7 @@ import type { BrainEngine } from '../engine.ts';import { runThink, persistSynthesis, type ThinkLLMClient } from '../think/index.ts';import { resolveModel } from '../model-config.ts';import { embedQuery } from '../embedding.ts';-import { BudgetMeter } from './budget-meter.ts';+import { BudgetMeter, loadAllowUnpriced, parseBudgetUsd } from './budget-meter.ts';/*** Local phase-result type for auto-think/drift. These phases are not yet@@ -49,6 +49,7 @@ export interface AutoThinkConfig {questions: string[];maxPerCycle: number;budgetUsd: number;+ allowUnpriced: boolean;cooldownDays: number;autoCommit: boolean;}@@ -71,7 +72,7 @@ async function loadConfig(engine: BrainEngine): Promise<AutoThinkConfig> {// `|| N` coerces an explicit 0 back to the default (budget 0 = "spend nothing",// cooldown 0 = "no cooldown"). max_per_cycle stays inline: its Math.max(1, ...)// floor already makes 0 invalid there, so no configured value is lost.- const budgetUsd = Math.max(0, await getNumberConfig(engine, 'dream.auto_think.budget', 2.0));+ const budgetUsd = parseBudgetUsd(await engine.getConfig('dream.auto_think.budget'), 2.0);const cooldownDays = Math.max(0, await getNumberConfig(engine, 'dream.auto_think.cooldown_days', 30));return {@@ -79,6 +80,7 @@ async function loadConfig(engine: BrainEngine): Promise<AutoThinkConfig> {questions,maxPerCycle: maxPerStr ? Math.max(1, parseInt(maxPerStr, 10) || 5) : 5,budgetUsd,+ allowUnpriced: await loadAllowUnpriced(engine),cooldownDays,autoCommit: autoCommitStr === 'true',};@@ -123,6 +125,7 @@ export async function runPhaseAutoThink(const meter = new BudgetMeter({budgetUsd: config.budgetUsd,+ allowUnpriced: config.allowUnpriced,phase: 'auto_think',auditPath: opts.auditPath,});diff --git a/src/core/cycle/base-phase.ts b/src/core/cycle/base-phase.tsindex cdfb06f9bd..52d7975e43 100644--- a/src/core/cycle/base-phase.ts+++ b/src/core/cycle/base-phase.ts@@ -30,7 +30,7 @@* by default.*/-import { BudgetMeter, type SubmitEstimate, type BudgetCheckResult } from './budget-meter.ts';+import { BudgetMeter, loadAllowUnpriced, parseBudgetUsd, type SubmitEstimate, type BudgetCheckResult } from './budget-meter.ts';import { sourceScopeOpts, type OperationContext } from '../operations.ts';import type { BrainEngine } from '../engine.ts';import type { CyclePhase, PhaseResult, PhaseStatus, PhaseError } from '../cycle.ts';@@ -184,12 +184,7 @@ export abstract class BaseCyclePhase {private resolveBudgetUsd(ctx: OperationContext, opts: BasePhaseOpts): number {if (typeof opts.budgetUsd === 'number') return opts.budgetUsd;const raw = (ctx.config as unknown as Record<string, unknown>)[this.budgetUsdKey];- if (typeof raw === 'number' && Number.isFinite(raw) && raw >= 0) return raw;- if (typeof raw === 'string') {- const parsed = Number.parseFloat(raw);- if (Number.isFinite(parsed) && parsed >= 0) return parsed;- }- return this.budgetUsdDefault;+ return parseBudgetUsd(typeof raw === 'number' || typeof raw === 'string' ? raw : undefined, this.budgetUsdDefault);}/**@@ -221,7 +216,7 @@ export abstract class BaseCyclePhase {// Budget meter construction. The default path reads config; tests inject.if (!opts.meter) {const budgetUsd = this.resolveBudgetUsd(ctx, opts);- this.meter = new BudgetMeter({ budgetUsd, phase: this.name });+ this.meter = new BudgetMeter({ budgetUsd, phase: this.name, allowUnpriced: await loadAllowUnpriced(ctx.engine) });} else {this.meter = opts.meter;}diff --git a/src/core/cycle/budget-meter.ts b/src/core/cycle/budget-meter.tsindex c0b61ebfb8..31b9a51589 100644--- a/src/core/cycle/budget-meter.ts+++ b/src/core/cycle/budget-meter.ts@@ -12,9 +12,13 @@* Per Codex P1 #10: each subagent submit estimates max-cost from* `model + max_output_tokens`, accumulates per-cycle, refuses next submit* if cumulative > budget. Pricing resolves through the canonical chat table- * (`canonicalLookup`), so any provider carried there is gated. Only a model- * absent from canonical too bypasses the gate, with a- * `BUDGET_METER_NO_PRICING` warn (once per process).+ * (`canonicalLookup`), so any provider carried there is gated. A model absent+ * from canonical (a router or proxy alias) is metered at a conservative+ * Sonnet-tier fallback rate with a `BUDGET_METER_NO_PRICING` warn (once per+ * process); `dream.budget.allow_unpriced=true` restores the old bypass.+ * Local model servers (Ollama, LM Studio, llama-server) cost $0.+ *+ * Budget values: 0 spends nothing, `Infinity` (config `unlimited`) is no cap.** Ledger lives at `~/.gbrain/audit/dream-budget-YYYY-Www.jsonl` (ISO-week* rotation, same pattern as shell-audit; filename math now goes through@@ -26,11 +30,40 @@ import { mkdirSync, appendFileSync } from 'node:fs';import { dirname, join } from 'node:path';import { isoWeekFilename, resolveAuditDir } from '../audit-week-file.ts';import { estimateMaxCostUsd, ANTHROPIC_PRICING } from '../anthropic-pricing.ts';-import { canonicalLookup } from '../model-pricing.ts';+import { canonicalLookup, type ModelPricing } from '../model-pricing.ts';+import type { BrainEngine } from '../engine.ts';+import { splitProviderModelId } from '../model-id.ts';++/** Local model servers bill nothing; their models are priced at $0, never at the fallback. */+const LOCAL_MODEL_PROVIDERS = new Set(['ollama', 'lmstudio', 'llama-server']);++/** Rate for models absent from the canonical table: Sonnet tier, derived from canonical. */+const FALLBACK_PRICING: ModelPricing = canonicalLookup('anthropic:claude-sonnet-4-6') ?? { input: 3.0, output: 15.0 };++/**+ * Parse a dream budget config value. `0` (or a negative value) spends+ * nothing, `unlimited` is no cap (Infinity); an empty or non-numeric value+ * uses `fallback`.+ */+export function parseBudgetUsd(raw: string | number | null | undefined, fallback: number): number {+ if (typeof raw === 'string' && raw.trim().toLowerCase() === 'unlimited') return Infinity;+ if (raw === null || raw === undefined || (typeof raw === 'string' && raw.trim() === '')) return fallback;+ const value = Number(raw);+ return Number.isFinite(value) ? Math.max(0, value) : fallback;+}++/** `dream.budget.allow_unpriced=true` lets unpriced models bypass the gate. */+export async function loadAllowUnpriced(engine: Pick<BrainEngine, 'getConfig'>): Promise<boolean> {+ // An unreadable config keeps the default: unpriced models are metered.+ const raw = await Promise.resolve(engine.getConfig?.('dream.budget.allow_unpriced')).catch(() => null);+ return typeof raw === 'string' && ['true', '1', 'yes', 'on'].includes(raw.trim().toLowerCase());+}export interface BudgetMeterOpts {- /** USD cap for the whole cycle. 0 or negative disables the gate. */+ /** USD cap for the whole cycle. 0 (or negative) spends nothing; Infinity is no cap. */budgetUsd: number;+ /** Let models absent from the pricing table bypass the gate (default: meter them at the fallback rate). */+ allowUnpriced?: boolean;/** Phase label for telemetry: 'auto_think' | 'drift'. */phase: string;/** Optional override for the audit file path (tests). */@@ -54,7 +87,7 @@ export interface BudgetCheckResult {cumulativeCostUsd: number;budgetUsd: number;reason?: string;- /** True when the model wasn't in the pricing map (cycle runs unbounded for that submit). */+ /** True when the model wasn't in the pricing map (metered at the fallback rate, or bypassed when allowed). */unpriced?: boolean;}@@ -99,6 +132,7 @@ export class BudgetMeter {* caller keeps the existing warn-and-allow behaviour for those.*/private estimateCost(estimate: SubmitEstimate): number | null {+ if (LOCAL_MODEL_PROVIDERS.has(splitProviderModelId(estimate.modelId).provider ?? '')) return 0;const p = canonicalLookup(estimate.modelId);const raw = p? (estimate.estimatedInputTokens / 1_000_000) * p.input +@@ -127,18 +161,23 @@ export class BudgetMeter {* Caller is responsible for skipping the actual LLM call when allowed=false.*/check(estimate: SubmitEstimate): BudgetCheckResult {- const cost = this.estimateCost(estimate);+ const priced = this.estimateCost(estimate);+ const budgetUsd = Math.max(0, this.opts.budgetUsd);- // Codex P1 #10: models absent from the canonical table bypass the gate.- if (cost === null) {+ if (priced === null) {this.unpricedSubmitsThisCycle++;if (!_unpricedWarnings.has(estimate.modelId)) {_unpricedWarnings.add(estimate.modelId);process.stderr.write(`[budget] BUDGET_METER_NO_PRICING: model "${estimate.modelId}" has no canonical pricing. ` +- `Budget gate disabled for this submit. (Per-provider pricing modules: TODO v0.29.)\n`,+ (this.opts.allowUnpriced+ ? `Budget gate disabled for this model (dream.budget.allow_unpriced=true).\n`+ : `Metering it at the Sonnet-tier fallback rate; set dream.budget.allow_unpriced=true to bypass.\n`),);}+ }+ // An unpriced model bypasses the gate only when the operator opted in.+ if (priced === null && this.opts.allowUnpriced) {writeLedgerLine(this.auditPath, {schema_version: 1,phase: this.opts.phase,@@ -146,6 +185,7 @@ export class BudgetMeter {event: 'submit_unpriced',model: estimate.modelId,label: estimate.label,+ allowed: true,estimated_input_tokens: estimate.estimatedInputTokens,max_output_tokens: estimate.maxOutputTokens,});@@ -153,30 +193,44 @@ export class BudgetMeter {allowed: true,estimatedCostUsd: 0,cumulativeCostUsd: this.cumulativeUsd,- budgetUsd: this.opts.budgetUsd,+ budgetUsd,unpriced: true,};}+ const cost = priced ?? (+ (estimate.estimatedInputTokens / 1_000_000) * FALLBACK_PRICING.input ++ (estimate.maxOutputTokens / 1_000_000) * FALLBACK_PRICING.output+ );- // Budget disabled (<= 0)- if (this.opts.budgetUsd <= 0) {- this.cumulativeUsd += cost;+ if (priced === null) {+ const allowed = this.cumulativeUsd + cost <= budgetUsd;+ if (allowed) this.cumulativeUsd += cost;writeLedgerLine(this.auditPath, {schema_version: 1,phase: this.opts.phase,ts: new Date().toISOString(),- event: 'submit',+ event: 'submit_unpriced',model: estimate.modelId,label: estimate.label,+ allowed,+ estimated_input_tokens: estimate.estimatedInputTokens,+ max_output_tokens: estimate.maxOutputTokens,estimated_cost_usd: cost,cumulative_cost_usd: this.cumulativeUsd,- budget_usd: this.opts.budgetUsd,+ budget_usd: budgetUsd,});- return { allowed: true, estimatedCostUsd: cost, cumulativeCostUsd: this.cumulativeUsd, budgetUsd: this.opts.budgetUsd };+ return {+ allowed,+ estimatedCostUsd: cost,+ cumulativeCostUsd: this.cumulativeUsd,+ budgetUsd,+ unpriced: true,+ ...(allowed ? {} : { reason: `BUDGET_EXHAUSTED: projected $${(this.cumulativeUsd + cost).toFixed(4)} > cap $${budgetUsd.toFixed(2)} (unpriced model at fallback rate)` }),+ };}const projected = this.cumulativeUsd + cost;- if (projected > this.opts.budgetUsd) {+ if (projected > budgetUsd) {writeLedgerLine(this.auditPath, {schema_version: 1,phase: this.opts.phase,@@ -186,14 +240,14 @@ export class BudgetMeter {label: estimate.label,estimated_cost_usd: cost,cumulative_cost_usd: this.cumulativeUsd,- budget_usd: this.opts.budgetUsd,+ budget_usd: budgetUsd,});return {allowed: false,estimatedCostUsd: cost,cumulativeCostUsd: this.cumulativeUsd,- budgetUsd: this.opts.budgetUsd,- reason: `BUDGET_EXHAUSTED: projected $${projected.toFixed(4)} > cap $${this.opts.budgetUsd.toFixed(2)}`,+ budgetUsd,+ reason: `BUDGET_EXHAUSTED: projected $${projected.toFixed(4)} > cap $${budgetUsd.toFixed(2)}`,};}@@ -207,15 +261,15 @@ export class BudgetMeter {label: estimate.label,estimated_cost_usd: cost,cumulative_cost_usd: this.cumulativeUsd,- budget_usd: this.opts.budgetUsd,+ budget_usd: budgetUsd,});- return { allowed: true, estimatedCostUsd: cost, cumulativeCostUsd: this.cumulativeUsd, budgetUsd: this.opts.budgetUsd };+ return { allowed: true, estimatedCostUsd: cost, cumulativeCostUsd: this.cumulativeUsd, budgetUsd };}/** Cumulative cost spent so far this cycle. */get totalSpent(): number { return this.cumulativeUsd; }- /** Count of submits that bypassed the gate due to missing pricing. */+ /** Count of submits whose model had no canonical pricing. */get unpricedSubmits(): number { return this.unpricedSubmitsThisCycle; }}diff --git a/src/core/cycle/cycle-date.ts b/src/core/cycle/cycle-date.tsindex fc952dd93a..3dab89cc39 100644--- a/src/core/cycle/cycle-date.ts+++ b/src/core/cycle/cycle-date.ts@@ -37,6 +37,12 @@ export function utcDate(instant = new Date()): string {return instant.toISOString().slice(0, 10);}+/** Calendar arithmetic on a YYYY-MM-DD date string (no timezone involved). */+export function shiftCalendarDate(date: string, days: number): string {+ const [y, m, d] = date.split('-').map(Number);+ return new Date(Date.UTC(y!, m! - 1, d! + days)).toISOString().slice(0, 10);+}+function formatDateInTimeZone(instant: Date, timeZone: string): string {const parts = new Intl.DateTimeFormat('en-US', {timeZone,diff --git a/src/core/cycle/drift.ts b/src/core/cycle/drift.tsindex 971a9e7896..16ad8b3649 100644--- a/src/core/cycle/drift.ts+++ b/src/core/cycle/drift.ts@@ -23,7 +23,9 @@*/import type { BrainEngine } from '../engine.ts';-import { BudgetMeter } from './budget-meter.ts';+import { BudgetMeter, loadAllowUnpriced, parseBudgetUsd } from './budget-meter.ts';+import { resolveSynthMaxOutputTokens } from './synthesize-concepts.ts';+import { resolveCycleDate, shiftCalendarDate } from './cycle-date.ts';import { resolveModel } from '../model-config.ts';import type { DreamPhaseResult } from './auto-think.ts';@@ -36,12 +38,15 @@ export interface DriftPhaseOpts {forceEnabled?: boolean;/** Inject the judge model call (tests). Defaults to gateway chat. */judge?: DriftJudgeFn;+ /** C-15: the cycle's calendar date (runCycle resolves one per cycle). */+ cycleDate?: string;}export interface DriftConfig {enabled: boolean;lookbackDays: number;budgetUsd: number;+ allowUnpriced: boolean;autoUpdate: boolean;maxPerCycle: number;}@@ -55,7 +60,8 @@ async function loadDriftConfig(engine: BrainEngine): Promise<DriftConfig> {return {enabled: enabledStr === 'true',lookbackDays: lookbackStr ? Math.max(1, parseInt(lookbackStr, 10) || 30) : 30,- budgetUsd: budgetStr ? Math.max(0, parseFloat(budgetStr) || 1.0) : 1.0,+ budgetUsd: parseBudgetUsd(budgetStr, 1.0),+ allowUnpriced: await loadAllowUnpriced(engine),autoUpdate: autoStr === 'true',maxPerCycle: maxPerStr ? Math.max(1, parseInt(maxPerStr, 10) || 20) : 20,};@@ -86,6 +92,7 @@ export type DriftJudgeFn = (input: {candidate: DriftCandidate;evidence: string;modelHint?: string;+ maxOutputTokens?: number;}) => Promise<DriftVerdict>;export const DRIFT_JUDGE_PROMPT = `You are auditing a knowledge-base "take" (a weighted claim) for drift:@@ -112,6 +119,15 @@ RECENT EVIDENCE (timeline entries on the same page):{EVIDENCE_BLOCK}`;+/** The judge prompt for one candidate; also the basis of its budget estimate. */+export function buildDriftPrompt(candidate: Pick<DriftCandidate, 'claim' | 'weight' | 'pageSlug'>, evidence: string): string {+ return DRIFT_JUDGE_PROMPT+ .replace('{CLAIM}', candidate.claim)+ .replace('{WEIGHT}', String(candidate.weight))+ .replace('{PAGE}', candidate.pageSlug)+ .replace('{EVIDENCE_BLOCK}', evidence);+}+/*** Parse the judge model's JSON output. Tolerant of fence wrapping and* leading prose; returns null on unrecoverable parse failure.@@ -149,17 +165,13 @@ export async function defaultDriftJudge(input: {candidate: DriftCandidate;evidence: string;modelHint?: string;+ maxOutputTokens?: number;}): Promise<DriftVerdict> {const { chat } = await import('../ai/gateway.ts');- const prompt = DRIFT_JUDGE_PROMPT- .replace('{CLAIM}', input.candidate.claim)- .replace('{WEIGHT}', String(input.candidate.weight))- .replace('{PAGE}', input.candidate.pageSlug)- .replace('{EVIDENCE_BLOCK}', input.evidence);const result = await chat({- messages: [{ role: 'user', content: prompt }],+ messages: [{ role: 'user', content: buildDriftPrompt(input.candidate, input.evidence) }],...(input.modelHint ? { model: input.modelHint } : {}),- maxTokens: 400,+ maxTokens: input.maxOutputTokens ?? resolveSynthMaxOutputTokens(input.modelHint ?? ''),});const parsed = parseDriftOutput(result.text);if (!parsed) {@@ -178,8 +190,9 @@ export async function defaultDriftJudge(input: {async function findDriftCandidates(engine: BrainEngine,lookbackDays: number,+ cycleDate?: string,): Promise<DriftCandidate[]> {- const cutoffIso = lookbackCutoffIso(lookbackDays);+ const cutoffIso = shiftCalendarDate(cycleDate ?? await resolveCycleDate(engine), -lookbackDays);// Only consider takes with weight in the "soft" middle band (0.3..0.85)// — facts (1.0) don't drift, very-low hunches (<0.3) aren't actionable yet.const rows = await engine.executeRaw<{@@ -213,10 +226,6 @@ async function findDriftCandidates(}));}-function lookbackCutoffIso(lookbackDays: number): string {- return new Date(Date.now() - lookbackDays * 86_400_000).toISOString().slice(0, 10);-}-/** Format the candidate page's recent timeline entries as judge evidence. */async function loadEvidence(engine: BrainEngine,@@ -279,7 +288,8 @@ export async function runPhaseDrift(return skipped('not_configured', 'dream.drift.enabled is false');}- const candidates = await findDriftCandidates(engine, config.lookbackDays);+ const cycleDate = opts.cycleDate ?? await resolveCycleDate(engine);+ const candidates = await findDriftCandidates(engine, config.lookbackDays, cycleDate);if (candidates.length === 0) {return {name: 'drift',@@ -308,29 +318,32 @@ export async function runPhaseDrift(});const meter = new BudgetMeter({budgetUsd: config.budgetUsd,+ allowUnpriced: config.allowUnpriced,phase: 'drift',auditPath: opts.auditPath,});+ const maxOutputTokens = resolveSynthMaxOutputTokens(modelId);const judge = opts.judge ?? defaultDriftJudge;- const cutoffIso = lookbackCutoffIso(config.lookbackDays);+ const cutoffIso = shiftCalendarDate(cycleDate, -config.lookbackDays);const judged: JudgedCandidate[] = [];let budgetExhausted = false;let failed = 0;for (const candidate of candidates.slice(0, config.maxPerCycle)) {+ const evidence = await loadEvidence(engine, candidate.pageId, cutoffIso);const check = meter.check({modelId,- estimatedInputTokens: 1500,- maxOutputTokens: 400,+ // ~4 chars per token over the prompt the judge actually sends.+ estimatedInputTokens: Math.ceil(buildDriftPrompt(candidate, evidence).length / 4),+ maxOutputTokens,label: `drift:${candidate.pageSlug}#${candidate.rowNum}`,});if (!check.allowed) {budgetExhausted = true;break;}- const evidence = await loadEvidence(engine, candidate.pageId, cutoffIso);try {- const verdict = await judge({ candidate, evidence, modelHint: modelId });+ const verdict = await judge({ candidate, evidence, modelHint: modelId, maxOutputTokens });judged.push({ candidate, verdict });} catch (e) {failed += 1;@@ -341,14 +354,13 @@ export async function runPhaseDrift(const driftedCount = judged.filter(j => j.verdict.drifted).length;let reportSlug: string | undefined;if (judged.length > 0) {- const date = new Date().toISOString().slice(0, 10);- reportSlug = `reports/drift-${date}`;+ reportSlug = `reports/drift-${cycleDate}`;// Report-only v1: the report page is the ONLY write this phase makes.// Lands in the default source (brain-global artifact, same-day re-runs// upsert the same slug).await engine.putPage(reportSlug, {type: 'report',- title: `Drift report ${date}`,+ title: `Drift report ${cycleDate}`,compiled_truth: buildReportBody(judged, config, modelId),});}diff --git a/src/core/cycle/extract-atoms.ts b/src/core/cycle/extract-atoms.tsindex e32e180e25..a317a3c2cc 100644--- a/src/core/cycle/extract-atoms.ts+++ b/src/core/cycle/extract-atoms.ts@@ -76,6 +76,7 @@ import { createHash } from 'crypto';import { slugifySegment } from '../sync.ts';import { resolveTierDefault } from '../model-config.ts';import { isUndefinedTableError, warnOncePerProcess } from '../utils.ts';+import { utcDate } from './cycle-date.ts';import { normalizeForGrounding } from './synthesize-verify.ts';import type { TranscriptPageIndex } from '../transcripts/discover.ts';import { managedAtomSession, readAtomOrigin, resumeManagedAtoms, publishManagedAtoms, MANAGED_ATOM_DISCOVERY_SQL, type AtomOrigin } from '../persistence/atom-maintenance.ts';@@ -1190,12 +1191,14 @@ export async function runPhaseExtractAtoms(// write below). Page-kind items only — transcripts are files, not// pages, so there is no from-endpoint to link.const provenanceLinks: LinkBatchInput[] = [];+ const sourcePage = item.kind === 'page' ? await engine.getPage(item.slug, { sourceId }) : null;+ const undatedDate = sourcePage?.created_at ? utcDate(new Date(sourcePage.created_at)) : 'undated';for (const atom of atoms) {const srcRef = item.kind === 'transcript' ? item.filePath : item.slug;const slug =item.kind === 'page'- ? await resolvePageAtomSlug(engine, atom.title, item.slug, sourceId)- : atomSlug(atom.title, srcRef);+ ? await resolvePageAtomSlug(engine, atom.title, item.slug, sourceId, undatedDate)+ : atomSlug(atom.title, srcRef, undefined, undatedDate);const originFrontmatter =item.kind === 'transcript'? { source_path: item.filePath }@@ -1308,6 +1311,11 @@ export async function runPhaseExtractAtoms(// source page. A crash between flip and stamp degrades to the legacy// atom-rows-mean-done semantics — safe, not lossy.await completeAtomReceipts(engine, sourceId, importedSlugs, hash16, item.kind === 'page' ? item : undefined);+ // C-14: atoms are keyed by LLM-chosen titles, which drift between+ // extractions. Once this extraction is complete, retire the atoms an+ // earlier extraction of the same source produced that this one did not.+ await retireStaleAtoms(engine, sourceId, item.kind === 'page'+ ? { key: 'source_slug', value: item.slug } : { key: 'source_path', value: item.filePath }, hash16, importedSlugs);if (item.kind === 'page') {await stampAtomsScanHash(item);}@@ -1621,8 +1629,35 @@ function atomsFromParsedArray(parsed: unknown[]): ExtractedAtom[] {return atoms;}-function todayDate(): string {- return new Date().toISOString().slice(0, 10);+/**+ * Soft-delete a source's atoms from earlier extractions (a different or+ * provisional source_hash) that the current, completed extraction did not+ * re-produce. Imported atoms (`imported_from`) and managed atoms are left+ * alone. Best-effort: a failure leaves duplicates, never loses current atoms.+ */+async function retireStaleAtoms(+ engine: BrainEngine,+ sourceId: string,+ origin: { key: 'source_slug' | 'source_path'; value: string },+ hash16: string,+ currentSlugs: string[],+): Promise<void> {+ try {+ const rows = await engine.executeRaw<{ slug: string }>(+ `SELECT slug FROM pages+ WHERE source_id = $1 AND type = 'atom' AND deleted_at IS NULL+ AND frontmatter->>'${origin.key}' = $2+ AND COALESCE(frontmatter->>'source_hash', '') <> $3+ AND (frontmatter->>'imported_from') IS NULL+ AND COALESCE(frontmatter->>'managed_extraction', '') <> 'true'+ AND NOT (slug = ANY($4::text[]))`,+ [sourceId, origin.value, hash16, currentSlugs],+ );+ const stale = rows.map(r => r.slug);+ for (let i = 0; i < stale.length; i += 500) await engine.softDeletePages(stale.slice(i, i + 500), { sourceId });+ } catch (err) {+ console.error(`[extract_atoms] stale atom cleanup failed for ${origin.value} (non-fatal): ${err instanceof Error ? err.message : String(err)}`);+ }}/**@@ -1639,13 +1674,14 @@ function atomSlugStem(title: string): string {/*** Pull a YYYY-MM-DD date from a source reference — a transcript file path like* `…/2026-06-11-telegram.md`, or a dated page slug. Checks the basename first- * to avoid matching a date in a parent directory. Falls back to the run date- * only when the source carries no date, so dated sources are fully deterministic.+ * to avoid matching a date in a parent directory. An undated source uses+ * `undatedDate` (C-14: the source page's creation date, or `undated`), never+ * the run date, so re-extraction on a later day upserts the same slugs.*/-function sourceDate(ref: string): string {+function sourceDate(ref: string, undatedDate: string): string {const base = ref.split('/').pop() ?? ref;const m = base.match(/(\d{4}-\d{2}-\d{2})/) ?? ref.match(/(\d{4}-\d{2}-\d{2})/);- return m ? m[1] : todayDate();+ return m ? m[1] : undatedDate;}/**@@ -1668,11 +1704,11 @@ function sourceDate(ref: string): string {* chars on separate slugs, so a deterministic slug never silently clobbers* a *different* atom.*/-function atomSlug(title: string, srcRef: string, sourcePageSlug?: string): string {+function atomSlug(title: string, srcRef: string, sourcePageSlug?: string, undatedDate = 'undated'): string {const hash = sourcePageSlug !== undefined? createHash('sha256').update(`${sourcePageSlug}\0${title}`).digest('hex').slice(0, 8): createHash('sha256').update(title).digest('hex').slice(0, 6);- return `atoms/${sourceDate(srcRef)}/${atomSlugStem(title)}-${hash}`;+ return `atoms/${sourceDate(srcRef, undatedDate)}/${atomSlugStem(title)}-${hash}`;}/**@@ -1699,10 +1735,11 @@ async function resolvePageAtomSlug(title: string,sourcePageSlug: string,sourceId: string,+ undatedDate: string,): Promise<string> {- const slug = atomSlug(title, sourcePageSlug, sourcePageSlug);+ const slug = atomSlug(title, sourcePageSlug, sourcePageSlug, undatedDate);if (await engine.getPage(slug, { sourceId })) return slug;- const legacySlug = atomSlug(title, sourcePageSlug);+ const legacySlug = atomSlug(title, sourcePageSlug, undefined, undatedDate);const legacy = await engine.getPage(legacySlug, { sourceId });if (legacy && legacy.type === 'atom' && isCompatibleAtomBinding(legacy.frontmatter, sourcePageSlug)) {return legacySlug;diff --git a/src/core/cycle/extract-facts.ts b/src/core/cycle/extract-facts.tsindex 998d91de07..347639bee1 100644--- a/src/core/cycle/extract-facts.ts+++ b/src/core/cycle/extract-facts.ts@@ -11,18 +11,17 @@* 1. Reads the markdown body (DB-side fetch via engine.getPage).* 2. Parses the `## Facts` fence with parseFactsFence.* 3. Maps ParsedFact → FenceExtractedFact via extractFactsFromFenceText.- * 4. De-dupes rows by canonical (claim, source) content key.- * 5. Reconciles the page-scoped DB index: no-op when already in sync,- * insert only missing keys when possible, or wipe/reinsert when stale- * DB rows need cleanup (#1781 — the unconditional wipe-and-reinsert- * made every cycle non-idempotent, re-appending duplicate rows).+ * 4. Collapses duplicate ACTIVE rows with the same (claim, source).+ * 5. Reconciles the page-scoped DB index by fence row number: matched+ * (row_num, claim) rows are updated in place (ids stay stable), rows+ * that left the fence are expired and detached (never deleted), and+ * only new row numbers insert. No-op when already in sync (#1781).*- * After the phase, the DB index for every cleanly parsed affected page- * matches the fence's canonical (claim, source) row set (modulo embeddings- * + runtime-derived fields). Warning-bearing parses are non-authoritative- * and preserve that page's existing index. Pages with no fence wipe DB rows- * for that page coordinate only; legacy NULL-source_markdown_slug rows- * survive because deleteFactsForPage targets source_markdown_slug = slug only.+ * Warning-bearing parses are non-authoritative and preserve that page's+ * existing index. A page with no fence expires and detaches its fence-owned+ * rows; `cli:` conversation facts and soft-expired legacy rows are not+ * fence-owned and are left alone. Active fence-owned rows of soft-deleted+ * pages are expired at the start of each run.** Empty-fence guard (Codex R2-#7; #2484; #2646): the phase refuses to do* its destructive reconciliation pass when genuinely-backfillable legacy@@ -57,13 +56,17 @@ import { existsSync, readFileSync } from 'node:fs';import type { BrainEngine } from '../engine.ts';import { assertUnmanagedCanonicalWriter } from '../persistence/maintenance.ts';-import { resolveSupersededByRow, type SupersedeTarget } from '../facts/supersede-resolve.ts';+import {+ resolveSupersededByRow,+ supersessionChainOf,+ type SupersedeTarget,+ type SupersessionChain,+} from '../facts/supersede-resolve.ts';import { writeReceipt } from '../extract/receipt-writer.ts';import { classifyRunStop, upsertExtractRollup } from '../extract/rollup-writer.ts';import { parseFactsFence, FACTS_FENCE_BEGIN } from '../facts-fence.ts';import {extractFactsFromFenceText,- FENCE_SOURCE_DEFAULT,type FenceExtractedFact,} from '../facts/extract-from-fence.ts';import {@@ -78,40 +81,108 @@ import { isWriteThroughDisabled, resolvePageWriteTarget } from '../write-throughimport { acquirePageLock } from '../page-lock.ts';interface ExistingPageFact {- // v0.46 (#3014) — the row's own fact id. Read so the supersession-drift- // check can compare the DB's stored `superseded_by` (a fact id) against- // the fence reference re-resolved to the target row's current id.id: number | string;fact: string;source: string | null;row_num: number | string | null;- // v0.46 (#3014) — supersession columns, read so a struck row whose- // fence says "superseded" but whose DB columns are still NULL counts as- // drifted and re-heals through the wipe+reinsert fallback.superseded_by: number | string | null;expired_at: Date | string | null;- // #4870 — fence cells the reconcile must honor. Both columns are NOT NULL- // enums whose CHECK matches the fence's validated values, so a plain- // equality compare cannot churn on case/format/NULL.+ kind: string;visibility: string;notability: string;+ context: string | null;+ valid_from: Date | string | null;+ valid_until: Date | string | null;+ confidence: number | string;+ claim_metric: string | null;+ claim_value: number | string | null;+ claim_unit: string | null;+ claim_period: string | null;has_embedding: boolean;}-function factContentKey(fact: string, source: string | null | undefined): string {- return `${fact}\u0000${source ?? FENCE_SOURCE_DEFAULT}`;+function timeOf(value: Date | string | null | undefined): number | null {+ return value == null ? null : new Date(value).getTime();+}++function numbersDiffer(stored: number | string | null, desired: number | null | undefined): boolean {+ if (stored == null || desired == null) return (stored == null) !== (desired == null);+ const a = Number(stored);+ return Math.abs(a - desired) > 1e-6 * Math.max(1, Math.abs(desired));+}++/**+ * Whether a DB row matched to its fence row by (row_num, claim) needs an+ * in-place update. Expiry compares NULL-ness only: the mapper stamps a struck+ * row's `expired_at` (and a forgotten row's `valid_until`) with today, so a+ * value compare would churn the page every day. `valid_until` is compared+ * exactly for active rows, where it only ever comes from the fence cell.+ * Confidence and claim values are REAL / DOUBLE columns, compared with a+ * tolerance so float rounding never churns.+ */+function factCellsDiffer(stored: ExistingPageFact, desired: FenceExtractedFact): boolean {+ const desiredActive = desired.expired_at == null;+ return stored.kind !== (desired.kind ?? 'fact')+ || stored.visibility !== (desired.visibility ?? 'private')+ || stored.notability !== (desired.notability ?? 'medium')+ || (stored.context ?? null) !== (desired.context ?? null)+ || stored.source !== desired.source+ || numbersDiffer(stored.confidence, desired.confidence ?? 1.0)+ || (stored.claim_metric ?? null) !== (desired.claim_metric ?? null)+ || numbersDiffer(stored.claim_value, desired.claim_value)+ || (stored.claim_unit ?? null) !== (desired.claim_unit ?? null)+ || (stored.claim_period ?? null) !== (desired.claim_period ?? null)+ || (desired.valid_from != null && timeOf(stored.valid_from) !== desired.valid_from.getTime())+ || (stored.expired_at == null) !== desiredActive+ || (desiredActive && timeOf(stored.valid_until) !== timeOf(desired.valid_until));+}++/** Resolve one fence row's `superseded by #N` against the page's row -> id map. */+function resolveSupersession(+ desired: FenceExtractedFact,+ byRow: ReadonlyMap<number, SupersedeTarget>,+ chain: SupersessionChain,+ slug: string,+): { superseded_by: number | null; warning: string | null } {+ if (desired.superseded_by_row === undefined) return { superseded_by: null, warning: null };+ return resolveSupersededByRow(desired.row_num, desired.superseded_by_row, byRow.get(desired.superseded_by_row), slug, chain);}-function dedupeFactsByContentKey(facts: FenceExtractedFact[]): FenceExtractedFact[] {- const seen = new Set<string>();- const deduped: FenceExtractedFact[] = [];- for (const fact of facts) {- const key = factContentKey(fact.fact, fact.source);- if (seen.has(key)) continue;- seen.add(key);- deduped.push(fact);+/**+ * Bring every fence row's `superseded_by` in line with its resolved+ * `superseded by #N` reference, inside the reconcile transaction. Warns only+ * for rows inserted by this run or whose link changes, so a permanently+ * unresolvable reference does not repeat its warning every cycle. Returns the+ * row numbers whose link changed.+ */+async function syncSupersession(+ tx: BrainEngine,+ sourceId: string,+ slug: string,+ desired: FenceExtractedFact[],+ chain: SupersessionChain,+ inserted: ReadonlySet<number>,+): Promise<{ warnings: string[]; changed: number[] }> {+ const current = await tx.executeRaw<{ id: number | string; row_num: number | string; expired_at: Date | string | null; superseded_by: number | string | null }>(+ `SELECT id, row_num, expired_at, superseded_by FROM facts+ WHERE source_id = $1 AND source_markdown_slug = $2 AND row_num IS NOT NULL`,+ [sourceId, slug],+ );+ const rows = new Map(current.map(r => [Number(r.row_num), r]));+ const byRow = new Map([...rows].map(([row, r]) => [row, { id: Number(r.id), struck: r.expired_at != null }]));+ const warnings: string[] = [];+ const changed: number[] = [];+ for (const f of desired) {+ const row = rows.get(f.row_num);+ if (!row) continue;+ const { superseded_by, warning } = resolveSupersession(f, byRow, chain, slug);+ const differs = superseded_by !== (row.superseded_by == null ? null : Number(row.superseded_by));+ if (warning && (differs || inserted.has(f.row_num))) warnings.push(warning);+ if (!differs) continue;+ changed.push(f.row_num);+ await tx.executeRaw('UPDATE facts SET superseded_by = $1 WHERE id = $2 AND source_id = $3', [superseded_by, row.id, sourceId]);}- return deduped;+ return { warnings, changed };}/**@@ -225,7 +296,8 @@ async function listExistingFactsForPage(sourceId: string,): Promise<ExistingPageFact[]> {return engine.executeRaw<ExistingPageFact>(- `SELECT id, fact, source, row_num, superseded_by, expired_at, visibility, notability,+ `SELECT id, fact, source, row_num, superseded_by, expired_at, kind, visibility, notability, context,+ valid_from, valid_until, confidence, claim_metric, claim_value, claim_unit, claim_period,embedding IS NOT NULL AS has_embeddingFROM factsWHERE source_id = $1@@ -268,8 +340,13 @@ export interface ExtractFactsResult {pagesScanned: number;pagesWithFacts: number;factsInserted: number;+ /** Fence-owned rows whose cells were updated in place (ids kept). */+ factsUpdated: number;+ /** Fence-owned rows expired and detached because their row left the fence. */factsDeleted: number;legacyRowsPending: number;+ /** Active fence-owned rows expired because their page was soft-deleted. */+ factsExpiredForDeletedPages: number;guardTriggered: boolean;/** Pages whose reconcile threw and rolled back; later pages still ran. */pagesFailed: number;@@ -367,8 +444,10 @@ export async function runExtractFacts(pagesScanned: 0,pagesWithFacts: 0,factsInserted: 0,+ factsUpdated: 0,factsDeleted: 0,legacyRowsPending: 0,+ factsExpiredForDeletedPages: 0,pagesFailed: 0,guardTriggered: false,warnings: [],@@ -512,6 +591,28 @@ export async function runExtractFacts(result.phantomsLockBusy = phantomResult.lock_busy;result.phantomsMorePending = phantomResult.more_pending;+ // ── Facts of soft-deleted pages ────────────────────────────────+ // Deleting a page removes the fence that is the facts' system of record,+ // and a full walk never visits a deleted slug, so its derived rows would+ // stay active in recall indefinitely. Expire (never delete or detach) the+ // fence-owned rows of every soft-deleted page in this source: restoring the+ // page brings its fence back, and the next reconcile of that slug+ // re-activates the rows that are still in it (the withdrawal trigger keeps+ // forgotten claims expired). Rows of a page that simply has no DB row yet+ // (a fence write ahead of sync) are untouched.+ if (!opts.dryRun) {+ const expired = await engine.executeRaw<{ id: number }>(+ `UPDATE facts f SET expired_at = now()+ WHERE f.source_id = $1 AND f.row_num IS NOT NULL AND f.expired_at IS NULL+ AND EXISTS (SELECT 1 FROM pages p+ WHERE p.source_id = f.source_id AND p.slug = f.source_markdown_slug+ AND p.deleted_at IS NOT NULL)+ RETURNING f.id`,+ [sourceId],+ );+ result.factsExpiredForDeletedPages = expired.length;+ }+// ── Resolve target slug set ───────────────────────────────────// v0.36.x #1096: presence — not length — distinguishes the modes.// `slugs: []` from an incremental sync no-op was previously treated@@ -603,189 +704,59 @@ export async function runExtractFacts(// trajectory query against the page returns import dates instead of// claim dates.const pageEffectiveDate = page.effective_date ? new Date(page.effective_date) : null;- const extracted = dedupeFactsByContentKey(- extractFactsFromFenceText(parsed.facts, slug, sourceId, { pageEffectiveDate }),- );+ // #1781: duplicate ACTIVE rows (same claim and source) index once. A+ // struck history row never collapses with an active row that carries the+ // same text, so a claim that reverts to an earlier value stays active.+ const activeKeys = new Set<string>();+ const extracted = extractFactsFromFenceText(parsed.facts, slug, sourceId, { pageEffectiveDate }).filter(f => {+ if (f.expired_at != null) return true;+ const key = `${f.fact}\u0000${f.source}`;+ if (activeKeys.has(key)) return false;+ activeKeys.add(key);+ return true;+ });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- // fence-owned DB rows: no-op when already in sync, insert only missing- // keys when possible, wipe/reinsert only when stale rows need cleanup.+ // Reconcile by row number, the fence's own unique identity (the parser+ // refuses duplicate row numbers). A DB row whose (row_num, claim) is still+ // in the fence keeps its id and has its other cells updated in place, so+ // ids handed out by recall keep working for forget and consolidation,+ // source_session, created_at and embeddings survive an edit. A row whose+ // number disappeared or whose claim was rewritten is expired and detached+ // (row_num NULL), never deleted: the same rule the managed projection+ // applies. Keying on row number also keeps a claim that reverts to an+ // earlier value (NYC -> SF -> NYC) active instead of folding it onto the+ // struck history row with the same text.const existing = await listExistingFactsForPage(engine, slug, sourceId);- const existingKeys = new Set(existing.map(f => factContentKey(f.fact, f.source)));- const desiredByKey = new Map(extracted.map(f => [factContentKey(f.fact, f.source), f]));-- const restrictions = existing.filter(fact => {- const desired = desiredByKey.get(factContentKey(fact.fact, fact.source));- return (fact.expired_at == null && (!desired || desired.expired_at != null))- || (fact.visibility !== 'private' && desired?.visibility === 'private');- });- if (restrictions.length > 0) {- const restricted = await underPageLock(slug, async () => {- if (await refuseDestructiveReconcileOnStaleCache(- engine, slug, sourceId, page.compiled_truth ?? '', page.timeline ?? '', result.warnings,- )) return null;- return engine.transaction(async tx => {- const current = await tx.getPage(slug, { sourceId });- if (!current || current.compiled_truth !== page.compiled_truth || current.timeline !== page.timeline) return null;- for (const fact of restrictions) {- const desired = desiredByKey.get(factContentKey(fact.fact, fact.source));- await tx.executeRaw(- `UPDATE facts SET expired_at=COALESCE(expired_at,$5::timestamptz),- visibility=CASE WHEN $6 THEN 'private' ELSE visibility END- WHERE id=$1 AND source_id=$2 AND fact=$3 AND source IS NOT DISTINCT FROM $4`,- [fact.id, sourceId, fact.fact, fact.source,- !desired ? new Date() : desired.expired_at ?? null, desired?.visibility === 'private'],- );- }- return true;- });- }, opts, result.warnings);- if (!restricted) return 'next';+ const desiredByRow = new Map(extracted.map(f => [f.row_num, f]));+ const matched = new Map<number, ExistingPageFact>();+ const stale: ExistingPageFact[] = [];+ for (const fact of existing) {+ const desired = fact.row_num == null ? undefined : desiredByRow.get(Number(fact.row_num));+ if (desired && desired.fact === fact.fact) matched.set(desired.row_num, fact);+ else stale.push(fact);}-- if (extracted.length === 0) {- if (existing.length > 0) {- const deletion = await underPageLock(slug, async () => {- if (await refuseDestructiveReconcileOnStaleCache(- engine,- slug,- sourceId,- page.compiled_truth ?? '',- page.timeline ?? '',- result.warnings,- )) {- return null;- }- // The delete targets source_markdown_slug = slug only, so- // NULL-source_markdown_slug legacy rows survive (the- // partial-UNIQUE-index keyspace). #1928: `cli:`-origin facts- // (conversation facts from extract-conversation-facts) are NOT- // fence-owned — the page carries no `## Facts` fence to recreate- // them — so they MUST survive this reconcile. #2646: soft-expired- // legacy rows (forget_fact's record of the forget) likewise- // survive via preserveExpiredLegacy.- return engine.deleteFactsForPage(slug, sourceId, {- excludeSourcePrefixes: ['cli:'],- preserveExpiredLegacy: true,- });- }, opts, result.warnings);- if (!deletion) {- return 'next';- }- result.factsDeleted += deletion.deleted;- }- return 'next';- }-- const hasStaleExisting = existing.some(f => !desiredByKey.has(factContentKey(f.fact, f.source)));- const hasDuplicateExisting = existing.length !== existingKeys.size;- const hasRowNumDrift = existing.some(f => {- const desired = desiredByKey.get(factContentKey(f.fact, f.source));- return desired !== undefined && Number(f.row_num) !== desired.row_num;- });- // v0.46 (#3014) — a struck row whose fence says "superseded" (or- // otherwise inactive) but whose DB columns are still NULL has an- // identical content key + row_num, so the checks above miss it. Treat- // a mismatch between the fence-desired supersession/expiry state and- // the DB columns as drift so the wipe+reinsert fallback re-heals the- // row (transports superseded_by + expired_at that a pre-fix cycle- // dropped).- //- // The supersession term keys off the RESOLVED reference, not merely- // "the fence carries a reference": we re-resolve the fence's- // `superseded by #N` against the current DB rows with the SAME resolver- // insertFacts uses, then compare the resolved target id to the id the- // DB stored. A permanently-unresolvable reference (self / dangling /- // chain) resolves to NULL every cycle and matches the DB's NULL, so it- // never churns; a pre-fix NULL, or a CHANGED reference (even between two- // resolvable targets), still differs and re-heals. Resolution stays- // page-local — `superseded by #N` only ever points within this page —- // so a row_num → id lookup over `existing` is a faithful mirror of the- // insert-time SELECT.- const existingByRowNum = new Map<number, ExistingPageFact>();- for (const f of existing) {- const rn = f.row_num == null ? NaN : Number(f.row_num);- if (Number.isFinite(rn)) existingByRowNum.set(rn, f);- }- const hasSupersessionDrift = existing.some(f => {- const desired = desiredByKey.get(factContentKey(f.fact, f.source));- if (desired === undefined) return false;-- // Expiry dimension: a struck row must carry expired_at; a pre-fix row- // (both columns NULL) drifts here and re-heals. Compare NULL-ness, NOT- // the timestamp value: the mapper stamps `expired_at = valid_until ??- // today`, so a value comparison would see the stored timestamp differ- // from a freshly-recomputed `today` every day and churn the page each- // cycle. NULL-ness is the stable "is this row struck?" signal.- const desiredExpired = desired.expired_at != null;- const dbExpired = f.expired_at != null;- if (desiredExpired !== dbExpired) return true;-- // Supersession dimension: resolve the fence reference against the- // current DB rows and compare the resolved target id to what the DB- // stored.- const desiredRow = desired.superseded_by_row;- let resolvedTargetId: number | null = null;- if (desiredRow !== undefined) {- const targetExisting = existingByRowNum.get(desiredRow);- const target: SupersedeTarget | undefined = targetExisting- ? { id: Number(targetExisting.id), struck: targetExisting.expired_at != null }- : undefined;- resolvedTargetId = resolveSupersededByRow(Number(f.row_num), desiredRow, target, slug).superseded_by;- }- const dbTargetId = f.superseded_by == null ? null : Number(f.superseded_by);- return resolvedTargetId !== dbTargetId;+ const updates = extracted.filter(f => {+ const fact = matched.get(f.row_num);+ return fact !== undefined && factCellsDiffer(fact, f);});- // #4870 — a visibility / notability edit on an existing row leaves the- // content key, row_num and struck-state untouched, so none of the terms- // above fire and the edit was a silent no-op. Compare the two fence- // cells the parser already validates; the wipe+reinsert transports them.- // ponytail: confidence is skipped — it is a REAL column, so an equality- // compare would need the fence formatter to avoid float-noise churn;- // route it through formatConfidence if a confidence-edit report lands.- const hasAttributeDrift = existing.some(f => {- const desired = desiredByKey.get(factContentKey(f.fact, f.source));- return desired !== undefined- && (desired.visibility !== f.visibility || desired.notability !== f.notability);- });-- if (- existing.length === extracted.length &&- !hasStaleExisting &&- !hasDuplicateExisting &&- !hasRowNumDrift &&- !hasSupersessionDrift &&- !hasAttributeDrift- ) {- return 'next';- }-- let toInsert = extracted.filter(f => !existingKeys.has(factContentKey(f.fact, f.source)));- // v0.46 (#3014) — when old DB rows must be removed, defer the wipe into- // insertFacts' own transaction (deleteForPageFirst) rather than calling- // deleteFactsForPage here. A standalone delete self-commits, so a- // failing insert afterward left the page permanently emptied; running- // the delete as the first statement of the insert transaction makes the- // reconcile atomic — a failed insert rolls the delete back. Same delete- // scoping as before: legacy NULL-source_markdown_slug rows, `cli:`-origin- // conversation facts (#1928), and soft-expired legacy rows (#2646)- // survive.- let deleteForPageFirst: { slug: string; excludeSourcePrefixes: string[]; preserveExpiredLegacy: boolean } | undefined;- if (hasStaleExisting || hasDuplicateExisting || hasRowNumDrift || hasSupersessionDrift || hasAttributeDrift) {- deleteForPageFirst = { slug, excludeSourcePrefixes: ['cli:'], preserveExpiredLegacy: true };- toInsert = extracted;+ const toInsert = extracted.filter(f => !matched.has(f.row_num));+ const chain = supersessionChainOf(extracted, slug);++ if (stale.length === 0 && updates.length === 0 && toInsert.length === 0) {+ const byRow = new Map([...matched].map(([row, fact]) => [row, { id: Number(fact.id), struck: fact.expired_at != null }]));+ const inSync = extracted.every(f => {+ const stored = matched.get(f.row_num)!.superseded_by;+ return resolveSupersession(f, byRow, chain, slug).superseded_by === (stored == null ? null : Number(stored));+ });+ if (inSync) return 'next';}- // v0.35.4 (D-CDX-3) — batch-embed before insert. Without this,- // cycle-inserted facts land with `embedding = NULL`, which breaks- // consolidate's cosine clustering AND the drift_score formula in- // find_trajectory. Falls open: if the embedding gateway is- // unavailable (no API key configured), facts still insert with- // NULL embeddings — drift_score gracefully returns null and- // clustering falls back to recency.+ // v0.35.4 (D-CDX-3) — batch-embed new rows before insert so+ // consolidate's cosine clustering and find_trajectory's drift_score see+ // them. Rows updated in place keep their vectors: the claim text is+ // unchanged. Falls open without an embedding provider, with a warning.if (toInsert.length > 0) {if (isAvailable('embedding')) {try {@@ -804,20 +775,14 @@ export async function runExtractFacts(toInsert[i].embedding_model = embeddingModel;}} catch (err) {- // Embedding failure is non-fatal — facts still get inserted, just- // without embeddings. The warning is NOT swallowed (#3044): the cycle- // wrapper folds result.warnings into a 'warn' phase status with a- // warning count, so a billing/auth/rate-limit embed failure surfaces- // in the cycle report instead of hiding behind a green 'ok'.+ // #3044: non-fatal, but never silent — the cycle folds warnings+ // into a 'warn' phase status.result.warnings.push(`${slug}: extract_facts batch embed failed: ${err instanceof Error ? err.message : String(err)}`,);}} else {- // #2821: same fail-open contract, but never silently. Pre-fix only- // the embed() FAILURE path warned — an UNAVAILABLE gateway inserted- // NULL-embedding rows with a clean green 'ok', hiding the degraded- // consolidate/drift_score behavior until someone diffed the DB.+ // #2821: same fail-open contract, never silently.result.warnings.push(`${slug}: embedding gateway unavailable — ${toInsert.length} fact(s) need embeddings (NULL embeddings won't cluster in consolidate until re-embedded)`,);@@ -828,25 +793,65 @@ export async function runExtractFacts(result.warnings.push(`${slug}: fact reconciliation deferred after cancellation; existing rows preserved`);return 'stop';}- if (deleteForPageFirst && existing.some(fact => fact.has_embedding)- && toInsert.some(fact => !fact.embedding)) {++ // A vector-bearing row is never replaced by a row that could not be+ // embedded. Until embedding succeeds, rows keep their positions: stale+ // rows whose claim is still active in the fence stay as they are, others+ // are expired in place, and new rows wait. In-place updates (privacy,+ // notability, strikes) still apply.+ const deferInserts = toInsert.some(f => !f.embedding) && stale.some(f => f.has_embedding);+ const activeClaims = new Set(extracted.filter(f => f.expired_at == null).map(f => `${f.fact}\u0000${f.source}`));+ const detach = deferInserts ? [] : stale;+ const expireInPlace = deferInserts+ ? stale.filter(f => f.expired_at == null && !activeClaims.has(`${f.fact}\u0000${f.source}`))+ : [];+ const inserts = deferInserts ? [] : toInsert;+ if (deferInserts) {result.warnings.push(`${slug}: destructive fact reconciliation deferred; existing vectors preserved until embedding succeeds`);- return 'next';}- if (toInsert.length === 0) return 'next';-- const insert = async () => {+ const apply = async () => {try {return await engine.transaction(async tx => {opts.signal?.throwIfAborted();- const inserted = await tx.insertFacts( // gbrain-allow-direct-insert: extract_facts cycle phase reconciles fence → DB- toInsert,- { source_id: sourceId },- deleteForPageFirst ? { deleteForPageFirst } : undefined,- );+ const current = await tx.getPage(slug, { sourceId });+ if (!current || current.compiled_truth !== page.compiled_truth || current.timeline !== page.timeline) return null;+ for (const fact of expireInPlace) {+ await tx.executeRaw('UPDATE facts SET expired_at = COALESCE(expired_at, now()) WHERE id = $1 AND source_id = $2', [fact.id, sourceId]);+ }+ for (const fact of detach) {+ await tx.executeRaw(+ `UPDATE facts SET expired_at = COALESCE(expired_at, now()), row_num = NULL+ WHERE id = $1 AND source_id = $2`,+ [fact.id, sourceId],+ );+ }+ for (const f of updates) {+ await tx.executeRaw(+ `UPDATE facts SET kind = $3, visibility = $4, notability = $5, context = $6,+ valid_from = COALESCE($7::timestamptz, valid_from),+ valid_until = CASE WHEN $8::boolean THEN $9::timestamptz ELSE valid_until END,+ expired_at = CASE WHEN $10::timestamptz IS NULL THEN NULL ELSE COALESCE(expired_at, $10::timestamptz) END,+ source = $11, confidence = $12,+ claim_metric = $13, claim_value = $14, claim_unit = $15, claim_period = $16+ WHERE id = $1 AND source_id = $2`,+ [matched.get(f.row_num)!.id, sourceId, f.kind ?? 'fact', f.visibility ?? 'private', f.notability ?? 'medium',+ f.context ?? null, f.valid_from?.toISOString() ?? null, f.expired_at == null,+ f.valid_until?.toISOString() ?? null, f.expired_at?.toISOString() ?? null, f.source, f.confidence ?? 1.0,+ f.claim_metric ?? null, f.claim_value ?? null, f.claim_unit ?? null, f.claim_period ?? null],+ );+ }+ const inserted = inserts.length === 0+ ? { inserted: 0 }+ : await tx.insertFacts( // gbrain-allow-direct-insert: extract_facts cycle phase reconciles fence → DB+ inserts.map(f => ({ ...f, superseded_by_row: undefined })),+ { source_id: sourceId },+ );+ const insertedRows = new Set(inserts.map(f => f.row_num));+ const linked = await syncSupersession(tx, sourceId, slug, extracted, chain, insertedRows);opts.signal?.throwIfAborted();- return inserted;+ const updated = new Set([...updates.map(f => f.row_num), ...linked.changed.filter(row => !insertedRows.has(row))]);+ return { inserted: inserted.inserted, updated: updated.size, warnings: linked.warnings };});} catch (error) {if (!isAborted(opts.signal)) throw error;@@ -854,34 +859,21 @@ export async function runExtractFacts(return null;}};- const inserted = deleteForPageFirst- ? await underPageLock(slug, async () => {- if (isAborted(opts.signal)) return null;+ const outcome = detach.length === 0 && expireInPlace.length === 0 && updates.length === 0+ ? await apply()+ : await underPageLock(slug, async () => {if (await refuseDestructiveReconcileOnStaleCache(- engine,- slug,- sourceId,- page.compiled_truth ?? '',- page.timeline ?? '',- result.warnings,- )) {- return null;- }+ engine, slug, sourceId, page.compiled_truth ?? '', page.timeline ?? '', result.warnings,+ )) return null;if (isAborted(opts.signal)) return null;- return insert();- }, opts, result.warnings)- : await insert();- 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.- result.factsDeleted += inserted.deleted;- // v0.46 (#3014) — surface unresolvable `superseded by #N` references- // (self / dangling / struck target) as cycle warnings; the row still- // inserts with superseded_by NULL + expired_at set (never a guessed FK).- // 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 apply();+ }, opts, result.warnings);+ if (!outcome) return 'next';+ result.factsInserted += outcome.inserted;+ result.factsUpdated += outcome.updated;+ result.factsDeleted += detach.length + expireInPlace.length;+ // resolveSupersededByRow prefixes each message with the slug + row.+ for (const w of outcome.warnings) result.warnings.push(w);return 'next';};diff --git a/src/core/cycle/extract-takes.ts b/src/core/cycle/extract-takes.tsindex ee059f296b..4395cc90f2 100644--- a/src/core/cycle/extract-takes.ts+++ b/src/core/cycle/extract-takes.ts@@ -22,7 +22,7 @@import { readFileSync } from 'node:fs';import { join, relative, sep } from 'node:path';import type { BrainEngine, TakeBatchInput } from '../engine.ts';-import { parseTakesFence, type ParsedTake } from '../takes-fence.ts';+import { parseTakesFence, TAKES_FENCE_BEGIN, type ParsedTake } from '../takes-fence.ts';import { walkMarkdownFiles } from '../../commands/extract.ts';export interface ExtractTakesOpts {@@ -69,14 +69,34 @@ export interface ExtractTakesResult {* Resolve a slug to its DB page_id. Returns null when no row exists for* that slug (e.g. file on disk that hasn't been imported yet).*/-async function getPageIdForSlug(engine: BrainEngine, slug: string): Promise<number | null> {+async function getPageIdForSlug(engine: BrainEngine, slug: string, sourceId: string): Promise<number | null> {const rows = await engine.executeRaw<{ id: number }>(- `SELECT id FROM pages WHERE slug = $1 LIMIT 1`,- [slug],+ `SELECT id FROM pages WHERE slug = $1 AND source_id = $2 AND deleted_at IS NULL LIMIT 1`,+ [slug, sourceId],);return rows[0]?.id ?? null;}+/**+ * Remove takes whose rows left the page's fence. Only a fence that parsed+ * cleanly is authoritative (a skipped malformed row is not a deletion), and a+ * page without a fence keeps whatever the index holds.+ */+async function pruneRemovedTakes(+ engine: BrainEngine,+ pageId: number,+ body: string,+ takes: ParsedTake[],+ warnings: string[],+ dryRun: boolean,+): Promise<void> {+ if (dryRun || warnings.length > 0 || !body.includes(TAKES_FENCE_BEGIN)) return;+ await engine.executeRaw(+ 'DELETE FROM takes WHERE page_id = $1 AND NOT (row_num = ANY($2::integer[]))',+ [pageId, takes.map(t => t.rowNum)],+ );+}+function parsedTakeToBatchInput(pageId: number, t: ParsedTake): TakeBatchInput {return {page_id: pageId,@@ -117,8 +137,9 @@ async function flushBatch(*/export async function extractTakesFromFs(engine: BrainEngine,- opts: { repoPath: string; slugs?: string[]; dryRun?: boolean; rebuild?: boolean },+ opts: { repoPath: string; slugs?: string[]; dryRun?: boolean; rebuild?: boolean; sourceId?: string },): Promise<ExtractTakesResult> {+ const sourceId = opts.sourceId ?? 'default';const result: ExtractTakesResult = {pagesScanned: 0, pagesWithTakes: 0, takesUpserted: 0, warnings: [], failedFiles: [],};@@ -150,13 +171,15 @@ export async function extractTakesFromFs(}}}- if (takes.length === 0) continue;+ if (takes.length === 0 && !body.includes(TAKES_FENCE_BEGIN)) continue;- const pageId = await getPageIdForSlug(engine, slug);+ const pageId = await getPageIdForSlug(engine, slug, sourceId);if (pageId === null) {- result.warnings.push(`TAKES_PAGE_NOT_IN_DB: slug=${slug} has takes fence but no page row; run 'gbrain sync' first`);+ if (takes.length > 0) result.warnings.push(`TAKES_PAGE_NOT_IN_DB: slug=${slug} has takes fence but no page row; run 'gbrain sync' first`);continue;}+ await pruneRemovedTakes(engine, pageId, body, takes, warnings, dryRun);+ if (takes.length === 0) continue;if (opts.rebuild && !dryRun) {await engine.executeRaw(`DELETE FROM takes WHERE page_id = $1`, [pageId]);@@ -191,12 +214,10 @@ export async function extractTakesFromDb(pagesScanned: 0, pagesWithTakes: 0, takesUpserted: 0, warnings: [], failedFiles: [],};const dryRun = opts.dryRun ?? false;- // v0.32.8: when caller supplies bare slugs, default sourceId='default'- // (back-compat with pre-v0.32.8 callers). When no slugs supplied, enumerate- // every (slug, source_id) pair across all sources.- const refs: Array<{ slug: string; source_id: string }> = opts.slugs && opts.slugs.length > 0- ? opts.slugs.map(slug => ({ slug, source_id: 'default' }))- : await engine.listAllPageRefs();+ // Every (slug, source_id) pair across all sources; bare slugs re-extract+ // the page in every source that holds that slug.+ const slugFilter = opts.slugs && opts.slugs.length > 0 ? new Set(opts.slugs) : null;+ const refs = (await engine.listAllPageRefs()).filter(ref => !slugFilter || slugFilter.has(ref.slug));const buffer: TakeBatchInput[] = [];for (const { slug, source_id } of refs) {@@ -216,6 +237,7 @@ export async function extractTakesFromDb(}}}+ await pruneRemovedTakes(engine, page.id, body, takes, warnings, dryRun);if (takes.length === 0) continue;if (opts.rebuild && !dryRun) {diff --git a/src/core/cycle/patterns.ts b/src/core/cycle/patterns.tsindex 7b05eb9a45..8b2da5b2c7 100644--- a/src/core/cycle/patterns.ts+++ b/src/core/cycle/patterns.ts@@ -45,11 +45,14 @@ import { loadAllowedSlugPrefixes, loadOutputRoot, runSubagentsInline } from './simport { probeChatModel } from '../ai/gateway.ts';import { normalizeModelId } from '../model-id.ts';import { throwIfAborted } from '../abort-check.ts';+import { resolveCycleDate } from './cycle-date.ts';import { dreamBreakerRefusal, loadDreamBreaker } from './dream-breaker.ts';export interface PatternsPhaseOpts {brainDir: string;dryRun: boolean;+ /** C-15: the cycle's calendar date (runCycle resolves one per cycle). */+ cycleDate?: string;/** #4077: cooperative cancellation from the enclosing cycle/minion job. A* cancelled cycle must stop the inline child and every derived-state* write instead of running out the force-evict grace. Mirrors@@ -253,7 +256,8 @@ export async function runPhasePatterns(childQueueName, privateQueueOwnerToken, opts.yieldDuringPhase,);const data: SubagentHandlerData = {- prompt: buildPatternsPrompt(reflections, config.minEvidence, config.sourceSlugPrefix, config.outputSlugPrefix),+ prompt: buildPatternsPrompt(reflections, config.minEvidence, config.sourceSlugPrefix, config.outputSlugPrefix,+ opts.cycleDate ?? await resolveCycleDate(engine)),model: config.model,max_turns: 30,// #4217/CDX-12: a patterns child whose every put_page failed must@@ -576,8 +580,8 @@ function buildPatternsPrompt(minEvidence: number,sourceSlugPrefix = 'wiki/personal/reflections',outputSlugPrefix = 'wiki/personal/patterns',+ today: string,): string {- const today = new Date().toISOString().slice(0, 10);const corpus = reflections.map((r, i) => `### ${i + 1}. [[${r.slug}]] — ${r.title}\n${r.excerpt}`).join('\n\n---\n\n');diff --git a/src/core/cycle/phantom-redirect.ts b/src/core/cycle/phantom-redirect.tsindex 8489532a5a..189be43f88 100644--- a/src/core/cycle/phantom-redirect.ts+++ b/src/core/cycle/phantom-redirect.ts@@ -9,20 +9,18 @@ import { assertUnmanagedCanonicalWriter } from '../persistence/maintenance.ts';* fence, soft-deletes the phantom, unlinks the `.md`. Bounded at 50* phantoms per cycle (configurable via `GBRAIN_PHANTOM_REDIRECT_LIMIT`).*- * Reuses existing infrastructure where it can: `softDeletePage`,- * `rewriteLinks`, `deleteFactsForPage`, fence parser. Adds TWO new- * primitives (codex outside-voice round of /plan-eng-review):- *- * 1. `resolvePhantomCanonical` (src/core/entities/resolve.ts) bypasses- * `resolveEntitySlug`'s exact-self-match step, which would have- * returned the phantom slug itself and made the whole pass a no-op.- *- * 2. `engine.migrateFactsToCanonical` (BrainEngine) is a DB-side- * UPDATE that preserves every fact-row column (embedding,- * validUntil, kind, status, source_session, ...). `writeFactsToFence`- * was tempting to reuse but is APPEND-only-with-new-row-numbers and- * drops embeddings + supersession metadata, so migrating through it- * would resurrect forgotten facts and lose embeddings.+ * Reuses existing infrastructure where it can: `softDeletePage`, the shared+ * write-target resolver (`resolvePageWriteTarget`, so the canonical fence+ * lands in the page's file of record), `recordRenameAlias`, fence parser.+ * The merge is lossless: `resolvePhantomCanonical` bypasses+ * `resolveEntitySlug`'s exact-self-match step and takes a fuzzy hit only+ * with a clear margin, a canonical that disagrees with the single prefix+ * candidate is ambiguous, every phantom fact row moves to the canonical by+ * id (rows appended to the canonical fence take exactly the row numbers+ * written to disk; history and duplicates move expired and detached, never+ * deleted), `superseded by #N` references follow the renumber, the+ * phantom's links move to the canonical page id, and the phantom slug is+ * recorded in `slug_aliases`.** Lock contract: single `gbrain-sync` writer-lock acquisition at the top* of the pass, held across all up-to-50 phantoms. Single 30s timeout.@@ -59,6 +57,8 @@ 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';+import { resolvePageWriteTarget } from '../write-through.ts';+import { recordRenameAlias } from '../page-state/rename-alias.ts';/** Tagged-union outcome of a single phantom-redirect attempt. */export type RedirectOutcome =@@ -204,7 +204,13 @@ async function acquireLockWithRetry(* Append the phantom's fact rows to the canonical's disk fence, dedup-* guarded by (claim, valid_from). Atomic via `.tmp` + rename.*- * Returns the count of rows actually appended (i.e. NOT counting dedupped).+ * New rows number from past both the file's and the DB's highest row number+ * (the DB may hold numbers the file lost), and `superseded by #N` references+ * are rewritten to the canonical numbering. Returns the phantom row number+ * -> canonical row number map, including rows that dedup onto an existing+ * canonical fence row (a retry after a crash between the disk write and the+ * DB move finds every row already on disk).+ ** The disk write happens BEFORE the DB migration in the redirect handler,* so if this throws (rename fails, disk full, parse-validation rejects)* the DB migration won't run and the cycle can retry next run.@@ -212,8 +218,10 @@ async function acquireLockWithRetry(function appendPhantomFenceRowsToCanonical(canonicalPath: string,phantomFacts: ParsedFact[],-): number {- if (phantomFacts.length === 0) return 0;+ dbMaxRowNum: number,+): Map<number, number> {+ const renumber = new Map<number, number>();+ if (phantomFacts.length === 0) return renumber;const body = fs.readFileSync(canonicalPath, 'utf-8');const { facts: existingFacts } = parseFactsFence(body);@@ -222,25 +230,30 @@ function appendPhantomFenceRowsToCanonical(// present at canonical doesn't get duplicated even if the strike-through// state differs between phantom and canonical (the operator can// reconcile manually after redirect).- const existingKeys = new Set(- existingFacts.map((f) => `${f.claim}|${f.validFrom ?? ''}`),- );- let nextRowNum = existingFacts.length > 0- ? Math.max(...existingFacts.map((f) => f.rowNum)) + 1- : 1;+ const existingByKey = new Map(existingFacts.map((f) => [`${f.claim}|${f.validFrom ?? ''}`, f.rowNum]));+ let nextRowNum = Math.max(dbMaxRowNum, 0, ...existingFacts.map((f) => f.rowNum)) + 1;- let appended = 0;- const merged: ParsedFact[] = [...existingFacts];+ const pending: ParsedFact[] = [];for (const pf of phantomFacts) {const key = `${pf.claim}|${pf.validFrom ?? ''}`;- if (existingKeys.has(key)) continue;- merged.push({ ...pf, rowNum: nextRowNum });- existingKeys.add(key);+ const existing = existingByKey.get(key);+ if (existing !== undefined) {+ renumber.set(pf.rowNum, existing);+ continue;+ }+ renumber.set(pf.rowNum, nextRowNum);+ existingByKey.set(key, nextRowNum);+ pending.push({ ...pf, rowNum: nextRowNum });nextRowNum += 1;- appended += 1;}- if (appended === 0) return 0;+ if (pending.length === 0) return renumber;++ const merged: ParsedFact[] = [...existingFacts, ...pending.map((f) => {+ const target = f.supersededBy === undefined ? undefined : renumber.get(f.supersededBy);+ if (target === undefined) return f;+ return { ...f, supersededBy: target, context: f.context?.replace(/superseded by #\d+/i, `superseded by #${target}`) };+ })];// Shared placement rule (#4756): replace in place, else insert ABOVE the// timeline sentinel — never a blind EOF append below `## Timeline`.@@ -257,7 +270,78 @@ function appendPhantomFenceRowsToCanonical();}fs.renameSync(tmpPath, canonicalPath);- return appended;+ return renumber;+}++/**+ * Move every phantom fact row to the canonical in one transaction, keeping+ * ids, embeddings and history. A row takes exactly the canonical row number+ * its fence row has on disk, so the canonical's next reconcile matches it+ * instead of replacing it. A row whose number the canonical index already+ * holds (a duplicate of a canonical fact) or that is absent from the fence+ * moves expired and detached (row_num NULL) instead of being deleted.+ * Returns the number of rows that moved into the canonical fence.+ */+async function migratePhantomFacts(+ engine: BrainEngine,+ sourceId: string,+ phantomSlug: string,+ canonicalSlug: string,+ rowMap: ReadonlyMap<number, number>,+): Promise<number> {+ return engine.transaction(async (tx) => {+ const rows = await tx.executeRaw<{ id: number; row_num: number | null }>(+ 'SELECT id, row_num FROM facts WHERE source_id = $1 AND source_markdown_slug = $2',+ [sourceId, phantomSlug],+ );+ const taken = new Set((await tx.executeRaw<{ row_num: number }>(+ 'SELECT row_num FROM facts WHERE source_id = $1 AND source_markdown_slug = $2 AND row_num IS NOT NULL',+ [sourceId, canonicalSlug],+ )).map(r => Number(r.row_num)));+ let moved = 0;+ for (const row of rows) {+ const mapped = row.row_num == null ? undefined : rowMap.get(Number(row.row_num));+ const target = mapped !== undefined && !taken.has(mapped) ? mapped : undefined;+ if (target !== undefined) {+ taken.add(target);+ moved += 1;+ }+ await tx.executeRaw(+ `UPDATE facts SET entity_slug = $3, source_markdown_slug = $3, row_num = $4::integer,+ expired_at = CASE WHEN $4::integer IS NULL THEN COALESCE(expired_at, now()) ELSE expired_at END+ WHERE id = $1 AND source_id = $2`,+ [row.id, sourceId, canonicalSlug, target ?? null],+ );+ }+ return moved;+ });+}++/**+ * Point the phantom's links at the canonical page (a merge between two page+ * ids, not a rename, so nothing else moves them). A link the canonical+ * already carries, or one that would become a self-link, stays on the+ * soft-deleted phantom.+ */+async function mergePhantomLinks(engine: BrainEngine, phantomId: number, canonicalId: number): Promise<void> {+ await engine.executeRaw(+ `UPDATE links l SET to_page_id = $2+ WHERE l.to_page_id = $1 AND l.from_page_id <> $2+ AND NOT EXISTS (SELECT 1 FROM links d+ WHERE d.from_page_id = l.from_page_id AND d.to_page_id = $2 AND d.link_type = l.link_type+ AND d.link_source IS NOT DISTINCT FROM l.link_source+ AND d.origin_page_id IS NOT DISTINCT FROM l.origin_page_id)`,+ [phantomId, canonicalId],+ );+ await engine.executeRaw(+ `UPDATE links l SET from_page_id = $2+ WHERE l.from_page_id = $1 AND l.to_page_id <> $2+ AND NOT EXISTS (SELECT 1 FROM links d+ WHERE d.from_page_id = $2 AND d.to_page_id = l.to_page_id AND d.link_type = l.link_type+ AND d.link_source IS NOT DISTINCT FROM l.link_source+ AND d.origin_page_id IS NOT DISTINCT FROM l.origin_page_id)`,+ [phantomId, canonicalId],+ );}/**@@ -392,9 +476,11 @@ export async function tryRedirectPhantom(return { outcome: 'no_canonical' };}- // D5 + codex #11: standalone ambiguity query.+ // D5 + codex #11: standalone ambiguity query. A canonical that is not the+ // single prefix candidate (e.g. a fuzzy hit on another page) is ambiguous+ // too.const candidates = await findPrefixCandidates(engine, sourceId, page.slug);- if (candidates.length > 1) {+ if (candidates.length > 1 || (candidates.length === 1 && candidates[0].slug !== canonical)) {logPhantomEvent({phantom_slug: page.slug,outcome: 'ambiguous',@@ -420,24 +506,38 @@ export async function tryRedirectPhantom(await assertUnmanagedCanonicalWriter(engine, 'phantom canonical redirect');// ─── Commit phase (codex #3/#4/#6/#7) ─────────────────────────────- const canonicalPath = path.join(brainDir, `${canonical}.md`);+ // The canonical file is the page's file of record (recorded source_path,+ // own-local_path roots), resolved like every other fence writer. Only a+ // brain with no configured root falls back to the pass's brainDir.+ const writeTarget = await resolvePageWriteTarget(engine, canonical, sourceId);+ if (!writeTarget.ok && writeTarget.skipped !== 'no_repo_configured') {+ logPhantomEvent({+ phantom_slug: page.slug,+ outcome: 'drift',+ source_id: sourceId,+ reason: `canonical write target unavailable: ${writeTarget.skipped}`,+ });+ return { outcome: 'drift', canonical };+ }+ const canonicalPath = writeTarget.ok ? writeTarget.filePath : path.join(brainDir, `${canonical}.md`);await materializeCanonicalToDisk(engine, canonical, sourceId, canonicalPath);// Disk-side first: parse phantom's fence and append to canonical's// disk fence (dedup-guarded). If this throws, no DB state has moved// and the cycle can retry next run.const phantomFence = parseFactsFence(page.compiled_truth ?? '');- appendPhantomFenceRowsToCanonical(canonicalPath, phantomFence.facts);+ const [dbMax] = await engine.executeRaw<{ n: number | string | null }>(+ 'SELECT MAX(row_num) AS n FROM facts WHERE source_id = $1 AND source_markdown_slug = $2',+ [sourceId, canonical],+ );+ const rowMap = appendPhantomFenceRowsToCanonical(canonicalPath, phantomFence.facts, Number(dbMax?.n ?? 0));// Codex #7: refresh canonical's compiled_truth + content_hash so the// next `gbrain sync` sees the canonical as unchanged. We re-parse the// disk body and recompute the hash with the SHARED canonical helper// (`utils.ts:contentHash` — the #3694 single formula: ephemeral// frontmatter keys stripped, tags-key deleted, timeline||''), so the- // idempotency check round-trips byte-for-byte. A private copy of the- // shape lived here before and drifted (no ephemeral strip), so any- // captured canonical got a hash the importer never reproduced and the- // next sync re-chunked + re-embedded it.+ // idempotency check round-trips byte-for-byte.const newCanonicalBody = fs.readFileSync(canonicalPath, 'utf-8');const reparsed = parseMarkdown(newCanonicalBody, `${canonical}.md`);const canonicalTags = await engine.getTags(canonical, { sourceId });@@ -457,22 +557,20 @@ export async function tryRedirectPhantom(newContentHash,);- // 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.+ // Withdrawals are scoped to the entity; the phantom was the canonical+ // entity. Moved first, so the withdrawal trigger honors them as the+ // phantom's rows take the canonical subject.await engine.executeRaw(MOVE_WITHDRAWAL_SUBJECT_SQL, [sourceId, page.slug, canonical]);+ const migrated = await migratePhantomFacts(engine, sourceId, page.slug, canonical, rowMap);- // D6: DB FK rewrite for the links table (wiki-link text rewrite is a- // documented follow-up — codex #5).- await engine.rewriteLinks(page.slug, canonical);+ const canonicalPage = await engine.getPage(canonical, { sourceId });+ if (canonicalPage) await mergePhantomLinks(engine, page.id, canonicalPage.id);+ await recordRenameAlias(engine, sourceId, page.slug, canonical);// Round 19/20: soft-delete + unlink. Order matters — softDelete first// so a concurrent sync that observes the phantom .md gone treats it as// a normal deletion (not a regression).await engine.softDeletePage(page.slug, { sourceId });- // Wipe any stale phantom DB facts that may have escaped the migration- // (e.g. expired rows that the migration WHERE clause skipped).- await engine.deleteFactsForPage(page.slug, sourceId);const phantomPath = path.join(brainDir, `${page.slug}.md`);if (fs.existsSync(phantomPath)) {try {@@ -495,7 +593,7 @@ export async function tryRedirectPhantom(phantom_slug: page.slug,canonical_slug: canonical,outcome: 'redirected',- fact_count: migrated.migrated,+ fact_count: migrated,source_id: sourceId,});return { outcome: 'redirected', canonical };diff --git a/src/core/cycle/propose-takes.ts b/src/core/cycle/propose-takes.tsindex b65671bf6a..ae8f0a492f 100644--- a/src/core/cycle/propose-takes.ts+++ b/src/core/cycle/propose-takes.ts@@ -155,6 +155,25 @@ export interface ProposedTake {served_model?: string;}+/**+ * #5425 (opt-in, `dream.propose_takes.attribution_rules=true`): speaker and+ * withdrawal rules for conversation pages, proposed by @clatyceo. Off by+ * default: a matched cat15-corpus run (Sonnet 4.6, 9 labeled pages x 3)+ * measured F1 0.896 → 0.876 (recall 0.924 → 0.882) with no attribution error+ * in either arm to fix. A separate prompt version keeps the two caches apart.+ */+export const EXTRACT_TAKES_ATTRIBUTION_RULES = `NOT gradeable either:+- Claims later withdrawn, corrected, or narrowed in the same page; omit them,+ or express only the final narrowed scope if it remains gradeable++Attribution: an assistant-authored gradeable judgment may use holder 'brain';+do not attribute it to the user or another person/company unless that speaker+explicitly endorses it. Assistant-added plans or deadlines are not user+commitments by default.++`;+export const PROPOSE_TAKES_ATTRIBUTION_PROMPT_SUFFIX = '+attribution5425';+/** Extractor function signature — injected for tests; production calls gateway. */export type ProposeTakesExtractor = (input: {pagePath: string;@@ -172,6 +191,8 @@ export type ProposeTakesExtractor = (input: {/** #4494: escalated cap for the one truncation retry (default* PROPOSE_TAKES_RETRY_MAX_TOKENS; clamped to >= maxTokens). */retryMaxTokens?: number;+ /** #5425: include EXTRACT_TAKES_ATTRIBUTION_RULES (opt-in). */+ attributionRules?: boolean;}) => Promise<ProposedTake[]>;export interface ProposeTakesOpts extends BasePhaseOpts {@@ -375,7 +396,9 @@ export const EXTRACTOR_FAILURE_HALT_STREAK = 5;export async function defaultExtractor(input: Parameters<ProposeTakesExtractor>[0],): Promise<ProposedTake[]> {- const prompt = EXTRACT_TAKES_PROMPT+ const prompt = (input.attributionRules+ ? EXTRACT_TAKES_PROMPT.replace('For each gradeable claim,', `${EXTRACT_TAKES_ATTRIBUTION_RULES}For each gradeable claim,`)+ : EXTRACT_TAKES_PROMPT).replace('{EXISTING_TAKES_JSON}', JSON.stringify(input.existingTakes, null, 2)).replace('{PAGE_BODY}', input.pageBody);@@ -658,7 +681,8 @@ class ProposeTakesPhase extends BaseCyclePhase {}const extractor = opts.extractor ?? defaultExtractor;- const promptVersion = opts.promptVersion ?? PROPOSE_TAKES_PROMPT_VERSION;+ const attributionRules = String(await Promise.resolve(engine.getConfig?.('dream.propose_takes.attribution_rules')).catch(() => null) ?? '').trim() === 'true';+ const promptVersion = opts.promptVersion ?? `${PROPOSE_TAKES_PROMPT_VERSION}${attributionRules ? PROPOSE_TAKES_ATTRIBUTION_PROMPT_SUFFIX : ''}`;const pageLimit = opts.pageLimit ?? 100;const skipPagesWithFence = opts.skipPagesWithFence ?? false;// gbrain#4168: explicit test override wins; otherwise the REAL remaining@@ -863,6 +887,7 @@ class ProposeTakesPhase extends BaseCyclePhase {// #4494: configurable output caps (see resolution above).maxTokens: extractorMaxTokens,retryMaxTokens: extractorRetryMaxTokens,+ attributionRules,});} catch (err) {result.llm_calls_failed += 1;diff --git a/src/core/cycle/synthesize-concepts.ts b/src/core/cycle/synthesize-concepts.tsindex 7c83704dfb..10be63e4ca 100644--- a/src/core/cycle/synthesize-concepts.ts+++ b/src/core/cycle/synthesize-concepts.ts@@ -35,6 +35,9 @@ import { createGlobalLlmHaltTracker, haltedClassOf, type GlobalLlmErrorClass } fimport { importFromContent } from '../import-file.ts';import { serializeMarkdown } from '../markdown.ts';import { canonicalLookup, type ModelPricing } from '../model-pricing.ts';+import { createHash } from 'node:crypto';+import { slugifySegment } from '../sync.ts';+import { validatePageSlug } from '../ops/context.ts';import { privatePagesFilterFragment, strictestVisibility, type Visibility } from '../search/private-visibility.ts';const DEFAULT_BUDGET_USD = 1.5;@@ -181,10 +184,11 @@ export async function runPhaseSynthesizeConcepts(};}- // 2. Group atoms by concept slug+ // 2. Group atoms by normalized concept slug; one atom counts once per concept.const groups = new Map<string, { slugs: string[]; titles: string[]; bodies: string[]; visibilities: Visibility[] }>();for (const atom of atoms) {- for (const conceptSlug of atom.concept_refs) {+ const conceptSlugs = new Set(atom.concept_refs.map(conceptStemFor).filter((s): s is string => s !== null));+ for (const conceptSlug of conceptSlugs) {const existing = groups.get(conceptSlug) ?? { slugs: [], titles: [], bodies: [], visibilities: [] };existing.slugs.push(atom.slug);existing.titles.push(atom.title);@@ -284,8 +288,10 @@ export async function runPhaseSynthesizeConcepts(});const synthMaxOutputTokens = resolveSynthMaxOutputTokens(synthModel);const skippedHumanOwned: string[] = [];+ const skippedUnchanged: string[] = [];+ const keptExistingNarrative: string[] = [];for (const group of atomGroups) {- const conceptSlug = `concepts/${group.conceptSlug.split('/').pop() ?? group.conceptSlug}`;+ const conceptSlug = `concepts/${group.conceptSlug}`;// A concept page this phase did not write belongs to a human (or another// writer). Check before any spend; never replace its body.const existing = await engine.getPage(conceptSlug, { sourceId: opts.sourceId ?? 'default' });@@ -293,6 +299,18 @@ export async function runPhaseSynthesizeConcepts(skippedHumanOwned.push(conceptSlug);continue;}+ // The narrative is a function of the member atoms, their strictest+ // visibility and the model. When none changed and the page holds a real+ // narrative, there is nothing to spend or rewrite; a fallback page is retried.+ const memberHash = createHash('sha256')+ .update(JSON.stringify([synthModel, group.visibility, group.atomSlugs.map((s, i) => [s, group.atomTitles[i], group.atomBodies[i]])+ .sort((a, b) => a[0].localeCompare(b[0]))]))+ .digest('hex').slice(0, 16);+ const priorMode = existing?.frontmatter?.synthesis_mode;+ if (existing?.frontmatter?.member_hash === memberHash && (priorMode === 'llm' || priorMode === 'deterministic_tier')) {+ skippedUnchanged.push(conceptSlug);+ continue;+ }tierCounts[group.tier]++;let narrative: string;let synthesisMode: ConceptSynthesisMode;@@ -369,6 +387,11 @@ export async function runPhaseSynthesizeConcepts(narrative = deterministicNarrative(group);synthesisMode = 'deterministic_tier';}+ // Never replace an LLM narrative with a template stub; the next cycle retries.+ if (priorMode === 'llm' && (synthesisMode === 'budget_fallback' || synthesisMode === 'error_fallback')) {+ keptExistingNarrative.push(conceptSlug);+ continue;+ }synthesisModeCounts[synthesisMode]++;if (!opts.dryRun) {@@ -386,6 +409,7 @@ export async function runPhaseSynthesizeConcepts(mention_count: group.atomTitles.length,composite_score: group.atomTitles.length,synthesis_mode: synthesisMode,+ member_hash: memberHash,synthesized_at: synthesizedAt,synthesized_by: 'synthesize_concepts-v0.41',visibility: pageVisibility,@@ -497,7 +521,9 @@ export async function runPhaseSynthesizeConcepts(`(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))` : '') +- (skippedHumanOwned.length > 0 ? ` (${skippedHumanOwned.length} human-owned page(s) left untouched)` : ''),+ (skippedHumanOwned.length > 0 ? ` (${skippedHumanOwned.length} human-owned page(s) left untouched)` : '') ++ (skippedUnchanged.length > 0 ? ` (${skippedUnchanged.length} unchanged)` : '') ++ (keptExistingNarrative.length > 0 ? ` (${keptExistingNarrative.length} existing narrative(s) kept)` : ''),details: {concepts_written: conceptsWritten,tier_counts: tierCounts,@@ -507,6 +533,8 @@ export async function runPhaseSynthesizeConcepts(failures,link_warnings: linkWarnings,skipped_human_owned: skippedHumanOwned,+ skipped_unchanged: skippedUnchanged,+ kept_existing_narrative: keptExistingNarrative,...(abortedGlobalError ? { aborted_global_error: abortedGlobalError } : {}),estimated_spend_usd: estimatedSpendUsd,budget_usd: budgetCap,@@ -515,6 +543,23 @@ export async function runPhaseSynthesizeConcepts(};}+/**+ * The concept an atom's concept ref names, as the stem of its `concepts/`+ * slug. LLM refs vary in case, spacing and prefix ("Network Effects",+ * "concepts/network-effects"); they all name `network-effects`. A ref with no+ * valid slug is dropped.+ */+function conceptStemFor(ref: string): string | null {+ const stem = slugifySegment(String(ref).trim().split('/').pop() ?? '');+ if (!stem) return null;+ try {+ validatePageSlug(`concepts/${stem}`);+ } catch {+ return null;+ }+ return stem;+}+/*** Deterministic fallback narrative for T3/T4 concepts and budget-exhausted* T1/T2 groups. No LLM call. v0.41 minimal shape — v0.42 enriches withdiff --git a/src/core/cycle/synthesize-postprocess.ts b/src/core/cycle/synthesize-postprocess.tsindex 49c0758df7..f8f36cc53e 100644--- a/src/core/cycle/synthesize-postprocess.ts+++ b/src/core/cycle/synthesize-postprocess.ts@@ -9,9 +9,9 @@ import type { WriteRequest } from '../persistence/model.ts';import { publishMaintenancePage, type MaintenanceAuthority } from '../persistence/prepared-maintenance.ts';import { writeResponse } from '../persistence/service.ts';import type { DiscoveredTranscript } from './transcript-discovery.ts';-import { emptyQuoteVerifyStats, groundSource, resolveVerifyPrior, verifyDreamPage, type GroundedSource } from './synthesize-verify.ts';+import { emptyQuoteVerifyStats, groundSource, isDreamOwnedPage, resolveVerifyPrior, verifyDreamPage, type GroundedSource } from './synthesize-verify.ts';-interface OutputRef { slug: string; source_id: string; raw_source?: string; }+interface OutputRef { slug: string; source_id: string; raw_source?: string; first_write_at?: Date; }interface RetainedOutput { job_id: number | bigint; job_key: string; request: WriteRequest; }export async function postprocessManagedSynthesis(@@ -71,10 +71,10 @@ export async function postprocessManagedSynthesis(throw new OperationError('revision_conflict', 'The synthesis output changed after the child committed.');}const firstDate = snapshot.page.frontmatter.dream_created_cycle_date || snapshot.page.frontmatter.dream_cycle_date || opts.cycleDate;- let page = { ...snapshot.page, frontmatter: { ...snapshot.page.frontmatter, dream_generated: true,- dream_cycle_date: firstDate, dream_created_cycle_date: firstDate, raw_source: path } };+ const since = ref.first_write_at ?? opts.sinceByTranscript.get(transcript.filePath);+ let page = isDreamOwnedPage(snapshot.page, since) ? { ...snapshot.page, frontmatter: { ...snapshot.page.frontmatter, dream_generated: true,+ dream_cycle_date: firstDate, dream_created_cycle_date: firstDate, raw_source: path } } : snapshot.page;if (opts.quoteVerify) {- const since = opts.sinceByTranscript.get(transcript.filePath);const prior = since ? await resolveVerifyPrior(engine, snapshot.page, ref.source_id, since) : null;if (prior === 'unchanged') stats.skipped_unchanged++;else {diff --git a/src/core/cycle/synthesize-verify.ts b/src/core/cycle/synthesize-verify.tsindex 467cb98a54..39d0c23acf 100644--- a/src/core/cycle/synthesize-verify.ts+++ b/src/core/cycle/synthesize-verify.ts@@ -23,6 +23,10 @@* attribution → the named speaker must* be the turn's speaker* numbers → must occur in a source+ * decisions → a speaker's decision or+ * commitment carries only numbers and+ * dates from that speaker's turns or a+ * turn they explicitly accepted (#5425)* any failure → the WHOLE unit leaves the* body and is kept in frontmatter* `unverified_claims`@@ -64,6 +68,7 @@ import type { Page } from '../types.ts';import { materializedHistoryRanges, prepareCanonicalProjections } from '../persistence/canonical-projections.ts';import { prepareAutomaticLinks } from '../persistence/links-preparation.ts';import { isAutoLinkEnabled } from '../link-extraction.ts';+import { resolveCycleDate, utcDate } from './cycle-date.ts';/** Minimum quoted-span inner length considered a "quote" (shorter spans are* scare quotes / titles, not transcript quotations). */@@ -141,6 +146,8 @@ export interface QuoteVerifyStats {speaker_mismatch: number;/** Numeric/date claims found in no source transcript. */number_not_in_source: number;+ /** A speaker's decision or commitment whose numbers/dates only another speaker stated (#5425). */+ decision_misattributed: number;skipped_no_transcript: number;/** Pages where read-back or write-back failed (fail-open, logged). */errors: number;@@ -163,6 +170,7 @@ export function emptyQuoteVerifyStats(): QuoteVerifyStats {quote_crosses_speakers: 0,speaker_mismatch: 0,number_not_in_source: 0,+ decision_misattributed: 0,skipped_no_transcript: 0,errors: 0,};@@ -271,6 +279,9 @@ export interface GroundedSource extends GroundedTranscript {path: string;turns: SpeakerTurn[];numbers: Set<string>;+ /** Speaker key → numbers/dates from that speaker's turns, plus those of a+ * turn the speaker explicitly accepted in the next turn (#5425). */+ numbersBySpeaker: Map<string, Set<string>>;nameNorm: string;speakers: Array<{ key: string; label: string; re: RegExp }>;}@@ -430,6 +441,25 @@ export function numericFacts(text: string): Set<string> {return out;}+/** A turn that opens by accepting the previous turn's proposal. */+const ACCEPTANCE_RE = /^\W*(?:yes|yep|yeah|sure|ok(?:ay)?|agreed|sounds good|perfect|great|do (?:it|that)|go ahead|let'?s do (?:it|that)|approved)\b/i;++function numbersBySpeaker(content: string, turns: SpeakerTurn[]): Map<string, Set<string>> {+ const out = new Map<string, Set<string>>();+ let previous: { key: string; numbers: Set<string> } | null = null;+ turns.forEach((turn, i) => {+ const text = content.slice(turn.labelEnd, turns[i + 1]?.labelStart ?? content.length);+ const key = speakerKey(turn.speaker);+ const numbers = numericFacts(text);+ const own = out.get(key) ?? new Set<string>();+ for (const n of numbers) own.add(n);+ if (previous && previous.key !== key && ACCEPTANCE_RE.test(text)) for (const n of previous.numbers) own.add(n);+ out.set(key, own);+ previous = { key, numbers };+ });+ return out;+}+/** Prepare one transcript for verification. */export function groundSource(path: string, content: string): GroundedSource {const { norm, map } = normalizeForGrounding(content);@@ -442,6 +472,7 @@ export function groundSource(path: string, content: string): GroundedSource {map,turns,numbers: numericFacts(`${content}\n${name}`),+ numbersBySpeaker: numbersBySpeaker(content, turns),nameNorm: normForGrounding(name),speakers: speakerMentionPatterns(turns),};@@ -652,14 +683,9 @@ const NUMERIC_CLAIM_RES: Array<{ re: RegExp; key: (m: RegExpMatchArray) => strin{ re: /\b\d{1,3}(?:,\d{3})+(?:\.\d+)?\b|\b\d{4,}\b/g, key: m => [canonNumber(Number.parseFloat(m[0].replace(/,/g, '')))] },];-/**- * Numeric and date claims in `text` that no source states. `text` must- * already be masked (code, links) and have grounded quotes blanked. A claim- * is supported when any of its canonical keys appears among a source's- * numbers, or its normalized text occurs in a source or its file name.- */-export function unsupportedNumericClaims(text: string, sources: GroundedSource[]): string[] {- const out: string[] = [];+/** Numeric and date claims in `text`, each once, with its canonical keys. */+function numericClaims(text: string): Array<{ raw: string; claim: string; keys: string[] }> {+ const out: Array<{ raw: string; claim: string; keys: string[] }> = [];const seen = new Set<string>();const covered: Array<[number, number]> = [];for (const { re, key } of NUMERIC_CLAIM_RES) {@@ -670,15 +696,50 @@ export function unsupportedNumericClaims(text: string, sources: GroundedSource[]const claim = normForGrounding(m[0]);if (!claim || seen.has(claim) || seen.size >= MAX_NUMERIC_CLAIMS_PER_PAGE) continue;seen.add(claim);- const keys = key(m);- const supported = sources.some(src =>- keys.some(k => src.numbers.has(k)) || src.norm.includes(claim) || src.nameNorm.includes(claim));- if (!supported) out.push(m[0].trim());+ out.push({ raw: m[0].trim(), claim, keys: key(m) });}}return out;}+/**+ * Numeric and date claims in `text` that no source states. `text` must+ * already be masked (code, links) and have grounded quotes blanked. A claim+ * is supported when any of its canonical keys appears among a source's+ * numbers, or its normalized text occurs in a source or its file name.+ */+export function unsupportedNumericClaims(text: string, sources: GroundedSource[]): string[] {+ return numericClaims(text)+ .filter(({ claim, keys }) => !sources.some(src =>+ keys.some(k => src.numbers.has(k)) || src.norm.includes(claim) || src.nameNorm.includes(claim)))+ .map(({ raw }) => raw);+}++/** A claim that a speaker decided, agreed, accepted, committed or will act. */+const DECISION_RE = /\b(?:decid(?:e|ed|es)|agree(?:d|s)?|accept(?:ed|s)?|approv(?:e|ed|es)|ch(?:o|oo)se|chosen|commit(?:ted|s)?|promis(?:e|ed|es)|confirm(?:ed|s)?|settled on|opted|signed off|will|plans? to|intends? to|going to)\b/i;++/** A unit that records a proposal, a refusal or a negation is not asserting agreement. */+const PROPOSAL_OR_REFUSAL_RE = /\b(?:(?:suggest|propos|recommend|offer|advis|declin|reject|refus)\w*|turned down|instead|rather than|not|no|never)\b|n't\b/i;+/** A bare year names when, not what was decided; it is never attributed. */+const YEAR_KEY_RE = /^(?:19|20|21)\d\d$/;++/**+ * #5425: numbers and dates in a decision claim that some speaker stated but+ * none of the speakers the claim names stated (or explicitly accepted).+ * Sources without turns cannot attribute anything and are ignored; numbers+ * no turn states (a file-name date, say) are not attributable either.+ */+function misattributedDecisionClaims(text: string, attribution: string, sources: GroundedSource[], speakers: string[]): string[] {+ if (speakers.length === 0 || !DECISION_RE.test(attribution) || PROPOSAL_OR_REFUSAL_RE.test(attribution)) return [];+ const turned = sources.filter(src => src.turns.length > 0);+ const statedBy = (keys: string[], who: (sp: string) => boolean) =>+ turned.some(src => [...src.numbersBySpeaker].some(([sp, nums]) => who(sp) && keys.some(k => nums.has(k))));+ return numericClaims(text)+ .filter(({ keys }) => !keys.every(k => YEAR_KEY_RE.test(k)))+ .filter(({ keys }) => statedBy(keys, () => true) && !statedBy(keys, sp => speakers.includes(sp)))+ .map(({ raw }) => raw);+}+const LIST_MARKER_RE = /^(?:[-*+]|\d+[.)]|>|#{1,6})[ \t]+/;const EMPTY_LINE_AFTER_REMOVAL_RE = /^\s*(?:[-*+]|\d+[.)]|>|#{1,6})?\s*$/;const REMOVED = '\uFFFF';@@ -728,7 +789,7 @@ export function claimUnits(body: string, spans: Array<{ start: number; end: numbreturn units;}-export type ClaimFailure = 'quote_not_in_source' | 'quote_crosses_speakers' | 'speaker_mismatch' | 'number_not_in_source';+export type ClaimFailure = 'quote_not_in_source' | 'quote_crosses_speakers' | 'speaker_mismatch' | 'number_not_in_source' | 'decision_misattributed';export interface QuarantinedClaim {text: string;@@ -789,7 +850,7 @@ function clip(s: string, n = PROVENANCE_TEXT_CHARS): string {export function verifyBody(body: string, sources: GroundedSource[], opts: { priorNorm?: string } = {}): BodyVerification {const { spans, unbalanced } = extractQuoteSpans(body);const masked = maskNonProse(body);- const failures: Record<ClaimFailure, number> = { quote_not_in_source: 0, quote_crosses_speakers: 0, speaker_mismatch: 0, number_not_in_source: 0 };+ const failures: Record<ClaimFailure, number> = { quote_not_in_source: 0, quote_crosses_speakers: 0, speaker_mismatch: 0, number_not_in_source: 0, decision_misattributed: 0 };const edits: Array<{ start: number; end: number; text: string }> = [];const quarantined: QuarantinedClaim[] = [];const provenance: QuoteProvenance[] = [];@@ -843,8 +904,14 @@ export function verifyBody(body: string, sources: GroundedSource[], opts: { priospeaker: speakers[0] ?? null,});}- const numbers = unsupportedNumericClaims(blank(masked.slice(u.start, u.end), quoteRanges), sources);+ const unquoted = blank(masked.slice(u.start, u.end), quoteRanges);+ const numbers = unsupportedNumericClaims(unquoted, sources);for (const n of numbers) fail('number_not_in_source', n);+ if (numbers.length === 0) {+ for (const n of misattributedDecisionClaims(unquoted, attribution, sources, [...mentioned.keys()])) {+ fail('decision_misattributed', `${[...mentioned.values()].join(', ')}: ${n} was stated only by another speaker`);+ }+ }if (unitFailures.length > 0) {quarantined.push({ text: clip(text, 2000), reason: unitFailures[0].reason, detail: unitFailures.map(f => f.detail).join('; ') });@@ -998,6 +1065,16 @@ export async function loadPreRunRevision(engine: BrainEngine, slug: string, sourreturn { compiled_truth: row.compiled_truth ?? '', timeline: row.timeline ?? '', frontmatter: (fm ?? {}) as Record<string, unknown> };}+/**+ * C-8: dream output is a page a child created (or one already stamped). A page+ * that existed before the child's first write keeps its own identity. Refs+ * without a first-write time (legacy callers) count as dream output.+ */+export function isDreamOwnedPage(page: Pick<Page, 'created_at' | 'frontmatter'>, firstWriteAt?: Date): boolean {+ if (!firstWriteAt || page.frontmatter?.dream_generated === true) return true;+ return new Date(page.created_at).getTime() >= firstWriteAt.getTime();+}+/*** The verification scope of one written page: null prior for a page created* at or after `since`, the pre-run revision for an older page, or 'unchanged'@@ -1019,18 +1096,19 @@ export async function resolveVerifyPrior(engine: BrainEngine, page: Pick<Page, '*/export async function verifyAndRepairDreamPages(engine: BrainEngine,- refs: Array<{ slug: string; source_id: string; raw_source?: string }>,+ refs: Array<{ slug: string; source_id: string; raw_source?: string; first_write_at?: Date }>,transcriptsByPath: Map<string, TranscriptForVerify>,opts: { since: Date; sinceByTranscript?: Map<string, Date>; checkedAt?: string; signal?: AbortSignal },): Promise<QuoteVerifyStats> {const stats = emptyQuoteVerifyStats();- const checkedAt = opts.checkedAt ?? new Date().toISOString().slice(0, 10);- const pages = new Map<string, { slug: string; source_id: string; paths: string[] }>();+ const checkedAt = opts.checkedAt ?? await resolveCycleDate(engine).catch(() => utcDate());+ const pages = new Map<string, { slug: string; source_id: string; paths: string[]; first_write_at?: Date }>();for (const ref of refs) {const key = `${ref.source_id} ${ref.slug}`;const known = ref.raw_source && transcriptsByPath.has(ref.raw_source) ? ref.raw_source : undefined;const entry = pages.get(key) ?? { slug: ref.slug, source_id: ref.source_id, paths: [] };if (known && !entry.paths.includes(known)) entry.paths.push(known);+ if (ref.first_write_at && (!entry.first_write_at || ref.first_write_at < entry.first_write_at)) entry.first_write_at = ref.first_write_at;pages.set(key, entry);}const cache = new Map<string, GroundedSource>();@@ -1050,7 +1128,9 @@ export async function verifyAndRepairDreamPages(try {const page = await engine.getPage(ref.slug, { sourceId: ref.source_id });if (!page) { stats.errors++; continue; }- const since = ref.paths.reduce((min, p) => {+ // The child's first write to this page is the ownership boundary: a+ // page another writer created before it is not the run's own.+ const since = ref.first_write_at ?? ref.paths.reduce((min, p) => {const at = opts.sinceByTranscript?.get(p);return at && at < min ? at : min;}, opts.since);diff --git a/src/core/cycle/synthesize.ts b/src/core/cycle/synthesize.tsindex 30c859c108..c90b32016c 100644--- a/src/core/cycle/synthesize.ts+++ b/src/core/cycle/synthesize.ts@@ -67,6 +67,8 @@ import { claudeCliSelfSessionIds } from '../ai/providers/claude-cli-scratch.ts';import { isQueueQuotaExceededError } from '../minions/admission.ts';import { waitForCompletionRenewing, TimeoutError } from '../minions/wait-for-completion.ts';import type { MinionJobInput, SubagentHandlerData } from '../minions/types.ts';+import { resolveMaxOutputTokens } from '../minions/handlers/subagent.ts';+import { BudgetMeter, loadAllowUnpriced, parseBudgetUsd } from './budget-meter.ts';import { runSubagentsInline, runDrainRenewalTick, percentile, INLINE_LOCK_MS } from './inline-drain.ts';import { buildManifestContext, buildLinkManifest, type ManifestContext } from './link-manifest.ts';import { resolveCycleDate, utcDate } from './cycle-date.ts';@@ -86,7 +88,7 @@ import { validateSourceId } from '../utils.ts';import { safeSplitIndex } from '../text-safe.ts';import { PAGE_SLUG_SEG } from '../cjk.ts';import { withChatPhase, estimateChatCostUsd } from '../ai/chat-usage.ts';-import { verifyAndRepairDreamPages, normForGrounding, readVerifyEpoch, loadChildWriteEpochs, type QuoteVerifyStats, type TranscriptForVerify } from './synthesize-verify.ts';+import { verifyAndRepairDreamPages, normForGrounding, readVerifyEpoch, loadChildWriteEpochs, isDreamOwnedPage, type QuoteVerifyStats, type TranscriptForVerify } from './synthesize-verify.ts';import { dreamBreakerRefusal, loadDreamBreaker } from './dream-breaker.ts';import { passesTriageGate, rescueConfigOf, DEFAULT_RESCUE_FLOOR, DEFAULT_RESCUE_MIN_SEGMENTS, DEFAULT_RESCUE_CONTENT_TYPES, DEFAULT_RESCUE_CONFIG, type RescueConfig, type RescueVerdictLike } from './triage-rescue.ts';@@ -146,6 +148,18 @@ const DEFAULT_TRIAGE_CONCURRENCY = 4;* page counts drop; `details.synthesis.avg_turns` telemetry shows cap pressure.*/const DEFAULT_MAX_TURNS = 16;+/**+ * #5425 (opt-in via dream.synthesize.attribution_rules, text by @clatyceo):+ * keep who-proposed-what and later corrections explicit. Off by default: a+ * matched run (Sonnet 4.6, 6 assistant-proposal transcripts x 4) found no+ * misattribution to fix in either arm (0 vs 1 flagged sentences, accepted+ * proposals kept 4/4 in both). The grounding gate's decision_misattributed+ * check is the default, mechanical guard.+ */+const SYNTH_ATTRIBUTION_RULE = '8. Keep the speaker and source timing explicit: distinguish what the user requested, decided, or accepted from what the assistant proposed, reported, inferred, or planned. A later correction, withdrawal, or scope narrowing overrides earlier text; express only the final scope when it is clear. Do not merge assistant-added evidence fields, recovery notes, deadlines, or next steps into user agreement unless the user explicitly accepted them.';++/** C-13: per-run USD cap on child submissions (`dream.synthesize.budget_usd`; `unlimited` removes it). */+const DEFAULT_SYNTH_BUDGET_USD = 5;/*** Compute per-chunk character budget for the resolved model + config override.@@ -327,6 +341,8 @@ export interface SynthesizePhaseOpts {to?: string;/** #4348: clock seam for deterministic cycle-date bucketing (tests). */now?: () => Date;+ /** C-15: the cycle's calendar date (runCycle resolves one per cycle); --date still wins. */+ cycleDate?: string;/** #4168 sibling: absolute wall-clock deadline (epoch ms) of the enclosing* minion job. When set, child-subagent timeout_ms/wait are clamped via the* clampSubagentBudgets template so a child submitted late in the cycle@@ -403,7 +419,7 @@ async function runPhaseSynthesizeInner(// phase start so a run that crosses midnight stays in one bucket.// Pre-fix this was UTC toISOString().slice(0,10), so a run after local// midnight but before UTC midnight rewrote the previous day's summary.- const summaryDate = await resolveCycleDate(engine, { explicitDate: opts.date, now: opts.now });+ const summaryDate = await resolveCycleDate(engine, { explicitDate: opts.date ?? opts.cycleDate, now: opts.now });// #4168 sibling: clamp the child-subagent budgets to the REAL remaining// job time (patterns.ts clampSubagentBudgets template). Pre-fix,@@ -662,23 +678,28 @@ async function runPhaseSynthesizeInner(// Per-source daily submission cap (D2D: default 0 = disabled; opt-in// backstop via dream.synthesize.max_submissions_per_source_per_day).// Bypassed for explicit --input/--date/--from/--to runs, same rule as the- // cooldown. Fail-open: if the count query throws (pool reap mid-phase),- // warn and skip the cap for this run — backstop availability must never- // cost phase availability (db-pacer posture).+ // cooldown. Fail-closed (C-13): an operator who set a spend cap gets no+ // uncounted submissions; if the count query throws, this run submits+ // nothing and the next run retries.const dailyCap = config.maxSubmissionsPerSourcePerDay;- let capActive = dailyCap > 0 && !explicitTarget;+ const capActive = dailyCap > 0 && !explicitTarget;let submittedToday = 0;+ let capUnavailable = false;if (capActive) {try {submittedToday = await countRecentSynthSubmissions(engine, cycleSourceId);} catch (e) {- capActive = false;+ capUnavailable = true;process.stderr.write(`[dream] daily-cap count query failed (${e instanceof Error ? e.message : String(e)}); ` +- `skipping the cap for this run\n`,+ `submitting nothing this run\n`,);}}+ // C-13: USD gate checked before every submission, from the prompt size and+ // the child's output cap (one call in oneshot mode, max_turns in agentic).+ const synthMeter = new BudgetMeter({ budgetUsd: config.budgetUsd, allowUnpriced: config.allowUnpriced, phase: 'synthesize' });+ const childMaxOutputTokens = resolveMaxOutputTokens(undefined, await engine.getConfig('agent.max_output_tokens').catch(() => null), config.model);const breaker = await loadDreamBreaker(engine);// Admission-quota latch: once a submit is rejected, every later transcript@@ -697,6 +718,10 @@ async function runPhaseSynthesizeInner(skipReports.push({ filePath: t.filePath, reason: 'admission_quota: submission stopped this run' });continue;}+ if (capUnavailable) {+ skipReports.push({ filePath: t.filePath, reason: 'daily_cap_unavailable: count query failed' });+ continue;+ }if (budgetExhaustedDeferrals.length > 0) {budgetExhaustedDeferrals.push(basename(t.filePath));continue; // budget gone — defer the rest, don't submit more children@@ -840,18 +865,34 @@ async function runPhaseSynthesizeInner(// (adversarial finding). Coalesced rows are another run's bookkeeping// and must not be cancelled.const transcriptFreshIds: number[] = [];+ const prompts = chunks.map((chunk, i) => buildSynthesisPrompt(+ t, chunk, i, chunks.length, priorContradictionsBlock, config.outputRoot,+ buildTriageMapBlock(triageVerdict, chunk, chunks.length),+ manifestBlock,+ allowedSlugPrefixes,+ // #4117: validated per-lane namespaces.+ config.reflectionsPrefix,+ config.originalsPrefix,+ config.mode,+ summaryDate,+ config.attributionRules,+ ));+ // One check for the whole chunk set: a transcript never half-submits.+ const callsPerChild = config.mode === 'agentic' ? config.maxTurns : 1;+ const spend = synthMeter.check({+ modelId: subagentModel,+ estimatedInputTokens: callsPerChild * prompts.reduce((n, p) => n + Math.ceil(p.length / 4), 0),+ maxOutputTokens: callsPerChild * chunks.length * childMaxOutputTokens,+ label: `synthesize:${basename(t.filePath)}`,+ });+ if (!spend.allowed) {+ process.stderr.write(`[dream] synthesize budget: ${spend.reason}; deferring ${basename(t.filePath)} and the rest of this run\n`);+ budgetExhaustedDeferrals.push(basename(t.filePath));+ continue;+ }for (let i = 0; i < chunks.length; i++) {const childData: SubagentHandlerData = {- prompt: buildSynthesisPrompt(- t, chunks[i], i, chunks.length, priorContradictionsBlock, config.outputRoot,- buildTriageMapBlock(triageVerdict, chunks[i], chunks.length),- manifestBlock,- allowedSlugPrefixes,- // #4117: validated per-lane namespaces.- config.reflectionsPrefix,- config.originalsPrefix,- config.mode,- ),+ prompt: prompts[i],model: subagentModel,max_turns: config.maxTurns,allowed_slug_prefixes: allowedSlugPrefixes,@@ -978,6 +1019,9 @@ async function runPhaseSynthesizeInner(transcripts_processed: 0,pages_written: 0,children_submitted: 0,+ budget_deferred_transcripts: budgetExhaustedDeferrals,+ budget_usd: config.budgetUsd,+ estimated_spend_usd: synthMeter.totalSpent,skips: skipReports,verdicts,triage: triageDetails,@@ -1253,6 +1297,9 @@ async function runPhaseSynthesizeInner(transcripts_discovered: transcripts.length,children_submitted: childIds.length,child_outcomes: childOutcomes,+ budget_deferred_transcripts: budgetExhaustedDeferrals,+ budget_usd: config.budgetUsd,+ estimated_spend_usd: synthMeter.totalSpent,skips: skipReports,verdicts,triage: triageDetails,@@ -1307,6 +1354,8 @@ async function runPhaseSynthesizeInner(// when chunking is in play.children_submitted: childIds.length,budget_deferred_transcripts: budgetExhaustedDeferrals,+ budget_usd: config.budgetUsd,+ estimated_spend_usd: synthMeter.totalSpent,// D5 cap hits + D8 legacy-key skips + daily_cap_reached. Empty when nothing skipped.skips: skipReports,summary_slug: summarySlug,@@ -1418,6 +1467,12 @@ export interface SynthConfig {maxTurns: number;/** dream.synthesize.max_submissions_per_source_per_day, default 0 = disabled (D2D). Docs recommend 200 for busy deployments. */maxSubmissionsPerSourcePerDay: number;+ /** dream.synthesize.budget_usd, default 5. 0 submits nothing; `unlimited` removes the cap (C-13). */+ budgetUsd: number;+ /** dream.budget.allow_unpriced: unpriced models bypass the budget gate. */+ allowUnpriced: boolean;+ /** dream.synthesize.attribution_rules: add SYNTH_ATTRIBUTION_RULE to the prompt (#5425, opt-in). */+ attributionRules: boolean;cooldownHours: number;/*** D1: Override the per-chunk token budget (model_context × HEADROOM_RATIO@@ -1681,6 +1736,9 @@ export async function loadSynthConfig(engine: BrainEngine): Promise<SynthConfig>},maxTurns,maxSubmissionsPerSourcePerDay,+ budgetUsd: parseBudgetUsd(await engine.getConfig('dream.synthesize.budget_usd'), DEFAULT_SYNTH_BUDGET_USD),+ allowUnpriced: await loadAllowUnpriced(engine),+ attributionRules: (await engine.getConfig('dream.synthesize.attribution_rules'))?.trim() === 'true',cooldownHours,maxPromptTokens,maxChunksPerTranscript,@@ -2675,10 +2733,13 @@ function buildSynthesisPrompt(reflectionsPrefix = `${outputRoot}/personal/reflections`,originalsPrefix = `${outputRoot}/originals/ideas`,mode: 'agentic' | 'oneshot' = 'agentic',+ // C-15: the child dates undated originals from this hint, so it is the+ // cycle's calendar date, not the UTC day.+ cycleDate: string = utcDate(),+ // #5425: opt-in speaker/withdrawal rule (dream.synthesize.attribution_rules).+ attributionRules = false,): string {- // #4348: UTC projection retained here on purpose — this is a slug-name- // hint for undated sources, not calendar provenance.- const dateHint = t.inferredDate ?? utcDate();+ const dateHint = t.inferredDate ?? cycleDate;const baseSlugSegment = sanitizeForSlug(t.basename) || `session-${dateHint}`;const isChunked = chunkTotal > 1;const hashSuffix = isChunked@@ -2722,7 +2783,8 @@ OUTPUT POLICY (ALL of these are required)4. Slug discipline: lowercase alphanumeric and hyphens only, slash-separated segments. NO underscores, NO file extensions.5. Self-contained opening: begin every new page's body with a 2-3 sentence summary that a reader unfamiliar with this transcript could understand on its own, before any quotes or detail. Do not assume the reader has the source conversation for context.6. Preserve concrete facts: carry the specific numbers, dates, dollar amounts, names, and who-decided-what OF the salient content you write about, exactly as the transcript states them. Do not add routine logistics for their own sake.-7. Ground every claim in the transcript. Attribute speculation as speculation ("the user wondered whether..."), and never state a completion state or outcome the transcript does not show.+7. Ground every claim in the transcript. Attribute speculation as speculation ("the user wondered whether..."), and never state a completion state or outcome the transcript does not show.${attributionRules ? `+${SYNTH_ATTRIBUTION_RULE}` : ''}TASKSA. Reflections (self-knowledge, pattern recognition, emotional processing):@@ -2778,7 +2840,7 @@ async function collectChildPutPageSlugs(// collects the job ids that produced ≥1 put_page write, so the caller can// count zero-page children without a second subagent_tool_executions scan.outJobsWithPages?: Set<number>,-): Promise<Array<{ slug: string; source_id: string; raw_source?: string }>> {+): Promise<Array<{ slug: string; source_id: string; raw_source?: string; first_write_at?: Date }>> {if (childIds.length === 0) return [];// Raw fetch — NO SELECT DISTINCT. Preserves per-child slug duplicates so// the orchestrator sees what each child wrote. COALESCE handles both@@ -2791,9 +2853,10 @@ async function collectChildPutPageSlugs(// cycle's resolved source via SubagentHandlerData.source_id, and stamps// the SAME source here so reverseWriteRefs / provenance reads target the// correct (source_id, slug) row. Unset → legacy 'default'.- const rows = await engine.executeRaw<{ job_id: number | bigint; slug: string }>(+ const rows = await engine.executeRaw<{ job_id: number | bigint; slug: string; started_at?: Date | string }>(`SELECT job_id,- COALESCE(input->>'slug', (input #>> '{}')::jsonb->>'slug') AS slug+ COALESCE(input->>'slug', (input #>> '{}')::jsonb->>'slug') AS slug,+ started_atFROM subagent_tool_executionsWHERE job_id = ANY($1::int[])AND tool_name = 'brain_put_page'@@ -2803,6 +2866,9 @@ async function collectChildPutPageSlugs(// #1978: slug → source transcript path (first writer wins) so the// provenance stamp can record WHERE the synthesized content came from.const rewritten = new Map<string, string | undefined>();+ // Ownership: a page is the run's own only if it did not exist before the+ // child's first write to it (C-8, #5685 follow-up).+ const firstWriteAt = new Map<string, Date>();for (const r of rows) {if (typeof r.slug !== 'string' || r.slug.length === 0) continue;// Postgres decodes the BIGINT FK as bigint; both metadata maps are keyed@@ -2814,10 +2880,14 @@ async function collectChildPutPageSlugs(if (!rewritten.has(slug) || rewritten.get(slug) === undefined) {rewritten.set(slug, jobRawSource?.get(jobId));}+ const at = r.started_at ? new Date(r.started_at) : null;+ const known = firstWriteAt.get(slug);+ if (at && !Number.isNaN(at.getTime()) && (!known || at < known)) firstWriteAt.set(slug, at);}return Array.from(rewritten.keys()).sort().map(slug => {const raw_source = rewritten.get(slug);- return { slug, source_id: sourceId, ...(raw_source ? { raw_source } : {}) };+ const first_write_at = firstWriteAt.get(slug);+ return { slug, source_id: sourceId, ...(raw_source ? { raw_source } : {}), ...(first_write_at ? { first_write_at } : {}) };});}@@ -2938,13 +3008,13 @@ function findLegacyCompletion(async function stampDreamProvenance(engine: BrainEngine,- refs: Array<{ slug: string; source_id: string; raw_source?: string }>,+ refs: Array<{ slug: string; source_id: string; raw_source?: string; first_write_at?: Date }>,cycleDate: string,signal?: AbortSignal,): Promise<void> {if (refs.length === 0) return;const { executeRawJsonb } = await import('../sql-query.ts');- for (const { slug, source_id, raw_source } of refs) {+ for (const { slug, source_id, raw_source, first_write_at } of refs) {// #4077: per-row abort check — the per-row try below is only for stamp// failures and must not swallow the cancellation unwind.throwIfAborted(signal, '[dream] synthesize provenance');@@ -2953,15 +3023,21 @@ async function stampDreamProvenance(engine,`UPDATE pagesSET frontmatter = COALESCE(frontmatter, '{}'::jsonb)- || $4::jsonb+ || $5::jsonb|| jsonb_build_object('dream_cycle_date',COALESCE(NULLIF(frontmatter->>'dream_created_cycle_date', ''), NULLIF(frontmatter->>'dream_cycle_date', ''), $3),'dream_created_cycle_date',COALESCE(NULLIF(frontmatter->>'dream_created_cycle_date', ''), NULLIF(frontmatter->>'dream_cycle_date', ''), $3))- WHERE slug = $1 AND source_id = $2`,- [slug, source_id, cycleDate],+ WHERE slug = $1 AND source_id = $2+ AND ($4::timestamptz IS NULL+ OR frontmatter->>'dream_generated' = 'true'+ OR created_at >= $4::timestamptz)`,+ // C-8: a page that existed before the child's first write to it is+ // not dream output; stamping it would hide it from extract_facts+ // and transcript discovery forever.+ [slug, source_id, cycleDate, first_write_at?.toISOString() ?? null],// #1978 raw-source persistence: record the transcript path the// synthesis was derived from, so `gbrain doctor` (raw_provenance// check) can verify every generated page carries a raw trace.@@ -2982,12 +3058,12 @@ async function stampDreamProvenance(async function reverseWriteRefs(engine: BrainEngine,brainDir: string,- refs: Array<{ slug: string; source_id: string }>,+ refs: Array<{ slug: string; source_id: string; first_write_at?: Date }>,nativeSourceId = 'default',signal?: AbortSignal,): Promise<number> {let count = 0;- for (const { slug, source_id } of refs) {+ for (const { slug, source_id, first_write_at } of refs) {throwIfAborted(signal, '[dream] synthesize reverse-write');// v0.32.8 F6: validate source_id is filesystem-safe before any join().validateSourceId(source_id);@@ -2998,7 +3074,7 @@ async function reverseWriteRefs(// getPage/getTags must not reach this ref's file write.throwIfAborted(signal, '[dream] synthesize reverse-write');try {- const md = renderPageToMarkdown(page, tags);+ const md = isDreamOwnedPage(page, first_write_at) ? renderPageToMarkdown(page, tags) : serializePageToMarkdown(page, tags);// v0.32.8 F6: foreign-source pages land at brainDir/.sources/<id>/<slug>.md// so same-slug-different-source pages don't collide. Pages belonging to// the cycle's own source (#1586: brainDir IS that source's checkout —diff --git a/src/core/data-frontmatter.ts b/src/core/data-frontmatter.tsindex db3717890f..3b2f8ebcbd 100644--- a/src/core/data-frontmatter.ts+++ b/src/core/data-frontmatter.ts@@ -1,4 +1,5 @@import { safeLoad, safeDump, Schema, Type, DEFAULT_SAFE_SCHEMA } from 'js-yaml';+import { NAIVE_DATETIME } from './effective-date.ts';// js-yaml's timestamp type builds `2024-02-30` as March 1 (Date.UTC rolls the// day over). A calendar-invalid timestamp stays the string the author wrote,@@ -15,7 +16,14 @@ const calendarTimestamp = new Type('tag:yaml.org,2002:timestamp', {const d = new Date(Date.UTC(+m[1], +m[2] - 1, +m[3]));return d.getUTCFullYear() === +m[1] && d.getUTCMonth() === +m[2] - 1 && d.getUTCDate() === +m[3];},- construct: baseTimestamp.construct,+ // An offset-less datetime keeps its wall-clock reading for brain.timezone.+ construct: (data: string) => {+ const date = baseTimestamp.construct(data);+ if (/^\d{4}-\d{1,2}-\d{1,2}(?:[Tt]|[ \t]+)\d/.test(data) && !/(?:[Zz]|[+-]\d{1,2}(?::?\d{2})?)\s*$/.test(data)) {+ Object.defineProperty(date, NAIVE_DATETIME, { value: true });+ }+ return date;+ },instanceOf: Date,represent: baseTimestamp.represent,});diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex 01980c7ef3..794f6ad492 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -119,6 +119,7 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set(['flagged_pages','salience_health','scraper_junk_pages',+ 'slug_collisions','source_config_shape','source_routing_health','stale_mentions',@@ -129,6 +130,7 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set(['takes_weight_grid','text_projection_readiness','timeline_coverage',+ 'timeline_orphans','timeline_history','undeclared_db_only_pages','unified_multimodal_coverage',diff --git a/src/core/effective-date.ts b/src/core/effective-date.tsindex 0da945471d..08bfa5504d 100644--- a/src/core/effective-date.ts+++ b/src/core/effective-date.ts@@ -40,6 +40,8 @@ export interface EffectiveDateResult {export interface ComputeEffectiveDateOpts {slug: string;frontmatter: Record<string, unknown>;+ /** `brain.timezone`: IANA zone for offset-less datetimes. Unset or invalid = UTC. */+ timeZone?: string;/** Basename without extension, e.g. "2024-03-15-acme-call". May be null/empty. */filename?: string | null;updatedAt: Date;@@ -63,19 +65,20 @@ const CREATED_KEYS = ['created', 'created_at', 'date_created', 'date created'];/*** The fallback anchor for an undated page: a page that already fell back- * keeps its stored date, a new file-backed page takes its file's timestamp- * (the earlier of birth and modification time), and anything else takes the- * row's creation time. Never the time of the latest write.+ * keeps its stored date, a new file-backed page takes the earliest of its+ * file's birth time, modification time and (when opted in) git first-commit+ * date, and anything else takes the row's creation time. Never the time of+ * the latest write.*/export function fallbackCreatedAt(opts: {existing?: { effective_date?: Date | string | null; effective_date_source?: string | null; created_at?: Date | string | null } | null;- fileTimes?: { birthtime?: Date; mtime?: Date } | null;+ fileTimes?: { birthtime?: Date; mtime?: Date; firstCommit?: Date } | null;now: Date;}): Date {const { existing, fileTimes, now } = opts;if (existing?.effective_date_source === 'fallback' && existing.effective_date) return new Date(existing.effective_date);if (existing?.created_at) return new Date(existing.created_at);- const times = [fileTimes?.birthtime, fileTimes?.mtime]+ const times = [fileTimes?.birthtime, fileTimes?.mtime, fileTimes?.firstCommit].filter((d): d is Date => d instanceof Date && d.getTime() > 0).map(d => d.getTime());return times.length ? new Date(Math.min(...times)) : now;@@ -107,19 +110,50 @@ function utcCalendarDate(year: number, month: number, day: number, h = 0, m = 0,return d.getUTCFullYear() === year && d.getUTCMonth() === month - 1 && d.getUTCDate() === day ? d : null;}+/**+ * Marks a frontmatter Date the YAML parser built from an offset-less datetime+ * (`2024-03-15T10:00:00`): its UTC fields hold the author's wall-clock time.+ */+export const NAIVE_DATETIME = Symbol.for('gbrain.naive-datetime');++/** Whether `timeZone` names an IANA zone this runtime knows. */+export function isValidTimeZone(timeZone: string): boolean {+ try {+ new Intl.DateTimeFormat('en-US', { timeZone }).format();+ return true;+ } catch {+ return false;+ }+}++/** The instant a wall-clock time (held in `wall`'s UTC fields) names in `timeZone`, DST included. */+function zonedWallTime(wall: Date, timeZone: string): Date {+ const format = new Intl.DateTimeFormat('en-US', { timeZone, hourCycle: 'h23', year: 'numeric', month: 'numeric',+ day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric' });+ const offsetAt = (instant: number) => {+ const part = (type: string) => +format.formatToParts(instant).find(p => p.type === type)!.value;+ return Date.UTC(part('year'), part('month') - 1, part('day'), part('hour'), part('minute'), part('second')) - (instant - instant % 1000);+ };+ const first = wall.getTime() - offsetAt(wall.getTime());+ return new Date(wall.getTime() - offsetAt(first));+}+/*** Parse a frontmatter value as a Date. Returns null on any failure.** Calendar shapes never depend on the syncing host's timezone: date-only* values (`2024-03-15`, `2024/03/15`, `March 5, 2024`, `5 March 2024`) are UTC- * calendar dates, and a datetime without an offset is read as UTC. A- * calendar-invalid date (`2024-02-30`) is rejected rather than rolled over.- * Other strings fall back to Date.parse.+ * calendar dates, and a datetime without an offset is read in `timeZone`+ * (the brain's `brain.timezone`; UTC when unset). A calendar-invalid date+ * (`2024-02-30`) is rejected rather than rolled over. Other strings fall back+ * to Date.parse.*/-export function parseDateLoose(value: unknown): Date | null {+export function parseDateLoose(value: unknown, timeZone?: string): Date | null {if (value == null) return null;+ const zone = timeZone && timeZone !== 'UTC' ? timeZone : null;if (value instanceof Date) {- return Number.isFinite(value.getTime()) ? value : null;+ if (!Number.isFinite(value.getTime())) return null;+ return zone && (value as Date & { [NAIVE_DATETIME]?: boolean })[NAIVE_DATETIME] ? zonedWallTime(value, zone) : value;}if (typeof value === 'string') {const trimmed = value.trim();@@ -128,12 +162,13 @@ export function parseDateLoose(value: unknown): Date | null {if (numeric) return utcCalendarDate(+numeric[1], +numeric[2], +numeric[3]);const datetime = DATETIME_RE.exec(trimmed);if (datetime) {- const [, y, mo, d, h, mi, sec, frac, zone] = datetime;+ const [, y, mo, d, h, mi, sec, frac, offset] = datetime;const wall = utcCalendarDate(+y, +mo, +d, +h, +mi, +(sec ?? 0), frac ? Math.round(+frac * 1000) : 0);if (!wall || +h > 23 || +mi > 59 || +(sec ?? 0) > 59) return null;- if (!zone || zone.toUpperCase() === 'Z') return wall;- const sign = zone.startsWith('-') ? -1 : 1;- const [zh, zm] = [+zone.slice(1, 3), +zone.slice(-2)];+ if (!offset) return zone ? zonedWallTime(wall, zone) : wall;+ if (offset.toUpperCase() === 'Z') return wall;+ const sign = offset.startsWith('-') ? -1 : 1;+ const [zh, zm] = [+offset.slice(1, 3), +offset.slice(-2)];return new Date(wall.getTime() - sign * (zh * 60 + zm) * 60_000);}const mdy = MONTH_DAY_YEAR_RE.exec(trimmed);@@ -184,12 +219,13 @@ function hasFilenameFirstPrefix(slug: string): boolean {export function computeEffectiveDate(opts: ComputeEffectiveDateOpts): EffectiveDateResult {const { slug, frontmatter, filename, updatedAt, createdAt } = opts;const filenameFirst = hasFilenameFirstPrefix(slug);+ const timeZone = opts.timeZone && isValidTimeZone(opts.timeZone) ? opts.timeZone : undefined;- const fmEvent = validateInRange(parseDateLoose(frontmatter.event_date));- const fmDate = validateInRange(parseDateLoose(frontmatter.date));- const fmPublished = validateInRange(parseDateLoose(frontmatter.published));+ const fmEvent = validateInRange(parseDateLoose(frontmatter.event_date, timeZone));+ const fmDate = validateInRange(parseDateLoose(frontmatter.date, timeZone));+ const fmPublished = validateInRange(parseDateLoose(frontmatter.published, timeZone));const filenameDate = extractFilenameDate(filename);- const fmCreated = CREATED_KEYS.map(key => validateInRange(parseDateLoose(frontmatter[key]))).find(d => d !== null) ?? null;+ const fmCreated = CREATED_KEYS.map(key => validateInRange(parseDateLoose(frontmatter[key], timeZone))).find(d => d !== null) ?? null;// Build the ordered candidate list. For filename-first prefixes// (daily/, meetings/) the filename moves to the head of the chain.diff --git a/src/core/embed-reuse.ts b/src/core/embed-reuse.tsindex ba1224bb17..d4e6d79773 100644--- a/src/core/embed-reuse.ts+++ b/src/core/embed-reuse.ts@@ -26,10 +26,16 @@ export interface EmbeddingReusePlan {needsEmbedIndexes: number[];}-/** Match new chunks against stored ones by header-stripped body. */+/**+ * Match new chunks against stored ones by header-stripped body (code), or by+ * the caller's `key` (markdown keys on chunk source + exact text).+ */+type ChunkKey = (chunk: { chunk_text: string; chunk_source?: string | null }) => string;+export function planEmbeddingReuse(- existing: readonly ReusableChunk[],- next: readonly { chunk_text: string }[],+ existing: readonly (ReusableChunk & { chunk_source?: string | null })[],+ next: readonly { chunk_text: string; chunk_source?: string | null }[],+ key: ChunkKey = chunk => stripChunkHeader(chunk.chunk_text),): EmbeddingReusePlan {const reuse = new Map<number, ReusableChunk>();const needsEmbedIndexes: number[] = [];@@ -38,13 +44,13 @@ export function planEmbeddingReuse(const byBody = new Map<string, ReusableChunk[]>();for (const ec of existing) {if (!ec.embedding) continue;- const body = stripChunkHeader(ec.chunk_text);+ const body = key(ec);const bucket = byBody.get(body);if (bucket) bucket.push(ec);else byBody.set(body, [ec]);}for (let i = 0; i < next.length; i++) {- const matched = byBody.get(stripChunkHeader(next[i]!.chunk_text))?.shift();+ const matched = byBody.get(key(next[i]!))?.shift();if (matched) reuse.set(i, matched);else needsEmbedIndexes.push(i);}diff --git a/src/core/embed-stale-images.ts b/src/core/embed-stale-images.tsnew file mode 100644index 0000000000..98335c5cda--- /dev/null+++ b/src/core/embed-stale-images.ts@@ -0,0 +1,101 @@+/**+ * `gbrain embed --stale --images`: rebuild image pages whose index is+ * incomplete (no visual vector, missing OCR text while OCR is enabled, or an+ * unsealed/stale projection) from their source files, without `sync --full`.+ *+ * An unchanged image is only re-read by a full sync, so an image first+ * imported under --no-embed, an OCR budget skip or a provider error stayed+ * filename-only until its bytes changed or someone ran `sync --full`. The+ * sweep selects the same incompleteness `importImageFile`'s hash-skip checks+ * and hands each file back to it, so the rebuild, the OCR budget and the+ * protected-OCR refusal all stay in one place.+ */++import { existsSync } from 'fs';+import { execFileSync } from 'child_process';+import { join } from 'path';+import type { BrainEngine } from './engine.ts';+import { importImageFile } from './import-file.ts';+import { safeChunksFilter } from './search/safe-chunks.ts';+import { serr } from './console-prefix.ts';++export interface StaleImageSweepResult {+ candidates: number;+ rebuilt: number;+ /** Candidates the importer left unchanged (complete by its own check, or refused). */+ skipped: number;+ missingFile: number;+ failures: number;+ failure_samples: string[];+}++export async function embedStaleImages(+ engine: BrainEngine,+ opts: { sourceId?: string; dryRun: boolean },+): Promise<StaleImageSweepResult> {+ const ocrWanted = process.env.GBRAIN_EMBEDDING_IMAGE_OCR === 'true';+ const params: unknown[] = [ocrWanted];+ if (opts.sourceId) params.push(opts.sourceId);+ const rows = await engine.executeRaw<{ slug: string; source_id: string; source_path: string | null; local_path: string | null }>(+ `SELECT p.slug, p.source_id, p.source_path, s.local_path FROM pages p JOIN sources s ON s.id = p.source_id+ WHERE p.page_kind = 'image' AND p.deleted_at IS NULL${opts.sourceId ? ' AND p.source_id = $2' : ''}+ AND (NOT (${safeChunksFilter('p')})+ OR p.text_projection_revision IS DISTINCT FROM p.knowledge_revision+ OR NOT EXISTS (SELECT 1 FROM content_chunks c WHERE c.page_id = p.id AND c.embedding_image IS NOT NULL)+ OR ($1 AND COALESCE(p.frontmatter->>'ocr_status', '') <> 'done' AND btrim(p.compiled_truth) = ''))+ ORDER BY p.id`, params);+ const result: StaleImageSweepResult = { candidates: rows.length, rebuilt: 0, skipped: 0, missingFile: 0, failures: 0, failure_samples: [] };+ const fail = (row: { source_id: string; slug: string }, error: string) => {+ result.failures++;+ if (result.failure_samples.length < 5) result.failure_samples.push(`${row.source_id}:${row.slug}: ${error}`);+ };+ if (opts.dryRun) return result;+ const repoPath = await engine.getConfig('sync.repo_path').catch(() => null);+ const gitRoots = new Map<string, string | null>();+ for (const row of rows) {+ const root = row.local_path ?? (row.source_id === 'default' ? repoPath : null);+ const file = root && row.source_path ? locateSourceFile(root, row.source_path, gitRoots) : null;+ if (!file) { result.missingFile++; continue; }+ try {+ const imported = await importImageFile(engine, file, row.source_path!, { sourceId: row.source_id });+ if (imported.status === 'imported') result.rebuilt++;+ else if (imported.status === 'error') fail(row, imported.error ?? 'import failed');+ else result.skipped++;+ } catch (e) {+ fail(row, e instanceof Error ? e.message : String(e));+ }+ }+ return result;+}++/** The `gbrain embed --stale --images` CLI surface (dispatched from commands/embed.ts). */+export async function runEmbedStaleImagesCli(engine: BrainEngine, args: string[]): Promise<StaleImageSweepResult> {+ if (!args.includes('--stale') || process.env.GBRAIN_EMBEDDING_MULTIMODAL !== 'true') {+ serr('Usage: gbrain embed --stale --images [--source <id>] [--dry-run] [--json] (requires GBRAIN_EMBEDDING_MULTIMODAL=true)');+ process.exit(1);+ }+ const srcI = args.indexOf('--source');+ const dryRun = args.includes('--dry-run');+ const result = await embedStaleImages(engine, { sourceId: srcI >= 0 ? args[srcI + 1] : undefined, dryRun });+ if (args.includes('--json')) console.log(JSON.stringify(result));+ else console.log(`[embed] images: ${result.candidates} incomplete, ${dryRun ? '(dry run) nothing rebuilt'+ : `${result.rebuilt} rebuilt, ${result.skipped} unchanged, ${result.missingFile} missing source file, ${result.failures} failed`}`);+ if (result.failures > 0) serr(`[embed] first image failure: ${result.failure_samples[0]}`);+ return result;+}++/** A page's source_path is relative to its source checkout, or to the git root for subpath-scoped syncs. */+function locateSourceFile(root: string, sourcePath: string, gitRoots: Map<string, string | null>): string | null {+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- source_path is the repo-relative path the importer recorded for this page, joined under the source's own checkout+ const direct = join(root, sourcePath);+ if (existsSync(direct)) return direct;+ if (!gitRoots.has(root)) {+ try {+ gitRoots.set(root, execFileSync('git', ['-C', root, 'rev-parse', '--show-toplevel'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim());+ } catch { gitRoots.set(root, null); }+ }+ const gitRoot = gitRoots.get(root);+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- same recorded repo-relative path, joined under the checkout's git root+ const viaGit = gitRoot ? join(gitRoot, sourcePath) : null;+ return viaGit && existsSync(viaGit) ? viaGit : null;+}diff --git a/src/core/engine-constants.ts b/src/core/engine-constants.tsindex 13d3034cb3..da6056cae0 100644--- a/src/core/engine-constants.ts+++ b/src/core/engine-constants.ts@@ -36,3 +36,13 @@ export const DELETE_BATCH_SIZE = 500;* `paths.length` can be well under the cap on a truncated walk.*/export const TRAVERSE_PATH_ROW_CAP = 5000;++/**+ * Cap on the simple-path rows the graph walks (`traverseGraph`,+ * `traversePaths*`, both engines) enumerate before projecting. The walk keeps+ * a per-path visited array, so a dense hub has combinatorially many simple+ * paths (a 12-page clique at depth 5 took 22 s); the recursive CTE is pulled+ * lazily, so a LIMIT on it stops the enumeration. Rows arrive breadth-first,+ * so a capped walk keeps the complete shallow neighbourhood.+ */+export const TRAVERSE_WALK_ROW_CAP = 20000;diff --git a/src/core/engine.ts b/src/core/engine.tsindex 58834b13e2..2c40fc9975 100644--- a/src/core/engine.ts+++ b/src/core/engine.ts@@ -1692,8 +1692,10 @@ export interface BrainEngine {* omitted, the schema DEFAULT 'default' applies; in multi-source brains* with the same slug across sources the bare-slug lookup returns >1 row* and the INSERT/DELETE fails with Postgres 21000.+ * `tagSource: 'frontmatter'` marks an import-owned row a later import may+ * delete (A14); every other add stamps 'added', which no import deletes.*/- addTag(slug: string, tag: string, opts?: { sourceId?: string }): Promise<void>;+ addTag(slug: string, tag: string, opts?: { sourceId?: string; tagSource?: 'frontmatter' }): Promise<void>;removeTag(slug: string, tag: string, opts?: { sourceId?: string }): Promise<void>;/*** #2200: getTags ALSO accepts a federated `sourceIds[]` read grant (precedencediff --git a/src/core/entities/resolve-on-save.ts b/src/core/entities/resolve-on-save.tsindex 21b9203afe..f72b4f5e6d 100644--- a/src/core/entities/resolve-on-save.ts+++ b/src/core/entities/resolve-on-save.ts@@ -23,6 +23,7 @@ import {export const SAVE_TIME_RESOLUTION_SOURCES = ['exact_page','alias_exact',+ 'prefix_expansion','fuzzy_match','fallback_slugify',] as const satisfies readonly ResolutionSource[];diff --git a/src/core/entities/resolve.ts b/src/core/entities/resolve.tsindex bcd0173998..ced660d3ff 100644--- a/src/core/entities/resolve.ts+++ b/src/core/entities/resolve.ts@@ -115,6 +115,15 @@ export function isIdentityEntity(slug: string, type?: string | null): boolean {return (type != null && IDENTITY_TYPES.has(type)) || IDENTITY_DIRS.some(dir => slug.startsWith(dir));}+const FACT_ENTITY_TYPES = new Set(['concept', 'project', 'deal']);+const FACT_ENTITY_DIRS = ['hosts/', 'projects/', 'concepts/', 'deals/'];++/** Pages a fuzzy fact attribution may land on: entities, never meetings, notes or other documents. */+function isFactEntityPage(slug: string, type: string | null): boolean {+ return isIdentityEntity(slug, type) || (type != null && FACT_ENTITY_TYPES.has(type))+ || FACT_ENTITY_DIRS.some(dir => slug.startsWith(dir));+}+function nameTokens(value: string): string {const folded = foldNonDecomposingLatin(value).normalize('NFKD').replace(/\p{M}/gu, '').toLowerCase();const tokens = folded.split(/[^\p{L}\p{N}]+/u).filter(token => token && !NAME_NOISE_TOKENS.has(token));@@ -215,16 +224,23 @@ async function findExactBasenameCandidates(* v0.40.2.0 — resolution-source-tagged variant for trajectory routing.** Same resolution chain as `resolveEntitySlug` but returns the source- * (`exact_page` | `fuzzy_match` | `fallback_slugify`) alongside the slug- * so trajectory callers can gate on `resolution_source !==- * 'fallback_slugify'` — querying findTrajectory on an invented slug- * always returns [] and wastes a SQL round-trip. Codex Problem 5 from- * v0.40.2.0 outside-voice review.+ * (`exact_page` | `alias_exact` | `prefix_expansion` | `fuzzy_match` |+ * `fallback_slugify`) alongside the slug so trajectory callers can gate on+ * `resolution_source !== 'fallback_slugify'` — querying findTrajectory on an+ * invented slug always returns [] and wastes a SQL round-trip.+ *+ * `prefix_expansion` is the bare single-token branch: it picks the sole+ * `<dir>/<token>-*` page because it is the only candidate, not because+ * anything confirms the mention is the same person or company (a bare+ * "Victor" in an unrelated transcript landed on the brain's one+ * `people/victor-*` page). It still verifies a live page, so+ * `!== 'fallback_slugify'` gates are unaffected; `facts/backstop.ts` flags+ * facts written through it as unverified.** The original `resolveEntitySlug` keeps its existing contract (returns* just the slug) for all pre-v0.40 call sites — no caller-side churn.*/-export type ResolutionSource = 'exact_page' | 'alias_exact' | 'fuzzy_match' | 'fallback_slugify';+export type ResolutionSource = 'exact_page' | 'alias_exact' | 'prefix_expansion' | 'fuzzy_match' | 'fallback_slugify';export interface ResolveResult {slug: string;@@ -255,7 +271,7 @@ export async function resolveEntitySlugWithSource(if (isBareName(trimmed)) {const expanded = await tryUnambiguousPrefixExpansion(engine, source_id, slugify(trimmed));- if (expanded) return { slug: expanded, source: 'fuzzy_match' };+ if (expanded) return { slug: expanded, source: 'prefix_expansion' };} else {const fuzzy = await tryFuzzyMatch(engine, source_id, trimmed);if (fuzzy) return { slug: fuzzy, source: 'fuzzy_match' };@@ -426,7 +442,9 @@ async function tryPrefixExpansion(if (rows.length === 1) return rows[0].slug;// Multiple matches: the top row (sorted by connection_count desc)// wins. The slug-ASC secondary key makes ties deterministic when- // connection counts collide — important for test pinning.+ // connection counts collide — important for test pinning. The+ // phantom pass's findPrefixCandidates gate refuses any multi-candidate+ // redirect, so this top row is never taken on its own.return rows[0].slug;} catch {// Defensive: a missing table or index shouldn't crash extraction.@@ -450,16 +468,13 @@ async function tryExactSlug(source_id: string,candidate: string,): Promise<string | null> {- try {- const rows = await engine.executeRaw<{ slug: string }>(- `SELECT slug FROM pages WHERE source_id = $1 AND slug = $2 AND deleted_at IS NULL LIMIT 1`,- [source_id, candidate],- );- if (rows.length > 0) return rows[0].slug;- } catch {- // Defensive: fail open. Caller still gets a slug from the fallback.- }- return null;+ // A database error propagates: degrading to the fallback slug would+ // silently attribute the caller's facts to a different entity.+ const rows = await engine.executeRaw<{ slug: string }>(+ `SELECT slug FROM pages WHERE source_id = $1 AND slug = $2 AND deleted_at IS NULL LIMIT 1`,+ [source_id, candidate],+ );+ return rows[0]?.slug ?? null;}async function tryFuzzyMatch(@@ -474,8 +489,8 @@ async function tryFuzzyMatch(// tends to be display-name-shaped ("Alice Example" vs "alice-example"). Cap at// 3 candidates; pick the first deterministic one.try {- const rows = await engine.executeRaw<{ slug: string; title: string; score: number }>(- `SELECT slug, title,+ const rows = await engine.executeRaw<{ slug: string; title: string; type: string | null; score: number }>(+ `SELECT slug, title, type,GREATEST(similarity(lower(title), $2),similarity(slug, $3)@@ -495,15 +510,30 @@ async function tryFuzzyMatch(// and facts about a person with no page to a meeting page that carries// their name. Entity resolution takes a candidate only when it names the// same entity; anything else falls back to the reference's own slug.- if (sameNameOnly) return rows.find(row => sameEntityName(raw, row.title, row.slug))?.slug ?? null;- if (rows.length > 0 && rows[0].score >= 0.7) return rows[0].slug;- } catch {- // pg_trgm functions might not be available on every engine config;- // fall through to slugify.+ // Only entity pages are candidates (a meeting titled "Dana Jones Example"+ // is not Dana), and two entity pages carrying the same name are+ // ambiguous: neither wins by trigram score.+ if (sameNameOnly) {+ const named = rows.filter(row => isFactEntityPage(row.slug, row.type) && sameEntityName(raw, row.title, row.slug));+ return named.length === 1 ? named[0].slug : null;+ }+ // Phantom canonicals: a clear winner only, with a margin over the runner-up.+ if (rows.length > 0 && rows[0].score >= 0.7 && (rows.length === 1 || rows[0].score - rows[1].score >= 0.1)) return rows[0].slug;+ } catch (err) {+ // pg_trgm might not be installed on every engine config: that brain has+ // no fuzzy arm and falls through to slugify. Any other database error+ // propagates rather than becoming a silent misattribution.+ if (!isMissingTrigramError(err)) throw err;}return null;}+function isMissingTrigramError(err: unknown): boolean {+ const code = typeof err === 'object' && err !== null && 'code' in err ? String((err as { code?: unknown }).code) : '';+ const message = err instanceof Error ? err.message : String(err);+ return code === '42883' || /function similarity|operator does not exist: text %/i.test(message);+}+/*** Deterministic slugify: lowercase, fold accents and stroke letters to their* base letter, replace non-alphanumerics with hyphens, collapse repeateddiff --git a/src/core/entity-identity.ts b/src/core/entity-identity.tsindex a9cddcf2fc..bfc81df3cb 100644--- a/src/core/entity-identity.ts+++ b/src/core/entity-identity.ts@@ -79,8 +79,12 @@ async function resolvePageId(/*** Link a page into an identity group (upsert on the page: re-linking MOVES* the page to the new identity — explicit manual intent). `canonical: true`- * demotes the group's previous canonical member first; the partial unique- * index is the backstop against a race leaving two canonicals.+ * demotes the group's previous canonical member first, in the same+ * transaction as the link, so a failed link never leaves the group without+ * its canonical. Omitting `canonical` keeps a re-linked member's canonical+ * flag within the same group (a confidence update must not demote it);+ * `canonical: false` demotes explicitly. The partial unique index is the+ * backstop against a race leaving two canonicals.*/export async function linkEntityIdentity(engine: BrainEngine,@@ -99,26 +103,30 @@ export async function linkEntityIdentity(throw new Error(`confidence must be in [0,1], got ${opts.confidence}`);}const establishedBy = (opts.establishedBy ?? 'manual').trim() || 'manual';- const canonical = opts.canonical === true;+ const canonical = typeof opts.canonical === 'boolean' ? opts.canonical : null;const pageId = await resolvePageId(engine, opts.slug, opts.sourceId);- if (canonical) {- await engine.executeRaw(- `UPDATE entity_identities SET canonical = false WHERE entity_id = $1 AND canonical`,- [entityId],+ await engine.transaction(async (tx) => {+ if (canonical === true) {+ await tx.executeRaw(+ `UPDATE entity_identities SET canonical = false WHERE entity_id = $1 AND canonical`,+ [entityId],+ );+ }+ await tx.executeRaw(+ `INSERT INTO entity_identities (entity_id, source_id, page_id, confidence, established_by, canonical)+ VALUES ($1, $2, $3, $4, $5, COALESCE($6::boolean, false))+ ON CONFLICT (source_id, page_id) DO UPDATE SET+ entity_id = EXCLUDED.entity_id,+ confidence = EXCLUDED.confidence,+ established_by = EXCLUDED.established_by,+ canonical = CASE WHEN $6::boolean IS NULL+ THEN entity_identities.canonical AND entity_identities.entity_id = EXCLUDED.entity_id+ ELSE EXCLUDED.canonical END,+ established_at = now()`,+ [entityId, opts.sourceId, pageId, confidence, establishedBy, canonical],);- }- await engine.executeRaw(- `INSERT INTO entity_identities (entity_id, source_id, page_id, confidence, established_by, canonical)- VALUES ($1, $2, $3, $4, $5, $6)- ON CONFLICT (source_id, page_id) DO UPDATE SET- entity_id = EXCLUDED.entity_id,- confidence = EXCLUDED.confidence,- established_by = EXCLUDED.established_by,- canonical = EXCLUDED.canonical,- established_at = now()`,- [entityId, opts.sourceId, pageId, confidence, establishedBy, canonical],- );+ });const members = await listEntityIdentities(engine, { entityId });const me = members.find(m => m.slug === opts.slug && m.source_id === opts.sourceId);diff --git a/src/core/eval-contradictions/auto-supersession.ts b/src/core/eval-contradictions/auto-supersession.tsindex 002a9f251c..66ca85e9d5 100644--- a/src/core/eval-contradictions/auto-supersession.ts+++ b/src/core/eval-contradictions/auto-supersession.ts@@ -23,6 +23,7 @@* field when present — the judge has signal we don't.*/+import { parseDateLoose } from '../effective-date.ts';import type {ContradictionFinding,ContradictionPair,@@ -166,12 +167,16 @@ export function renderResolutionCommand(// supersede command on the older-dated side. If both sides have takes// we prefer the take that's NOT on the newer page. Falls back to a// hint with both slugs when the dates can't be ordered.+ // Dates order by instant (a timezone-bearing date compares correctly+ // against a date-only one); equal or unparseable dates have no winner.const aDate = pair.a.effective_date;const bDate = pair.b.effective_date;- if (aDate && bDate) {- const olderSide = aDate < bDate ? pair.a : pair.b;- const newerSide = aDate < bDate ? pair.b : pair.a;- const newerDate = aDate < bDate ? bDate : aDate;+ const aMs = parseDateLoose(aDate)?.getTime();+ const bMs = parseDateLoose(bDate)?.getTime();+ if (aDate && bDate && aMs !== undefined && bMs !== undefined && aMs !== bMs) {+ const olderSide = aMs < bMs ? pair.a : pair.b;+ const newerSide = aMs < bMs ? pair.b : pair.a;+ const newerDate = aMs < bMs ? bDate : aDate;if (olderSide.take_id !== null && olderSide.take_row_num !== null) {// gbrain#4169: temporal supersession has a REAL winner (the// newer-dated side). When that side is itself a take, its claim is@@ -183,7 +188,7 @@ export function renderResolutionCommand(: `'<replacement claim — see contradiction report>'`;return `gbrain takes supersede ${shellQuote(olderSide.slug)} --row ${olderSide.take_row_num} --claim ${claim} --since ${newerDate}`;}- return `# temporal_supersession: ${olderSide.slug} (${aDate < bDate ? aDate : bDate}) superseded by ${newerDate}`;+ return `# temporal_supersession: ${olderSide.slug} (${aMs < bMs ? aDate : bDate}) superseded by ${newerDate}`;}return `# temporal_supersession: ${pair.a.slug} vs ${pair.b.slug} (date order unclear)`;}diff --git a/src/core/extract-takes-from-pages.ts b/src/core/extract-takes-from-pages.tsindex 5693693952..8d3108e01a 100644--- a/src/core/extract-takes-from-pages.ts+++ b/src/core/extract-takes-from-pages.ts@@ -13,7 +13,7 @@// 100+-case eval suite. v0.42 ships the classifier + CLI; autopilot stays// blocked until eval coverage catches up.-import { existsSync } from 'node:fs';+import { existsSync, readFileSync } from 'node:fs';import type { BrainEngine } from './engine.ts';import type { TakeKind } from './engine.ts';import { chat, getChatModel, isAvailable } from './ai/gateway.ts';@@ -24,6 +24,8 @@ import {resolveTakesWritePath,TakesWriteError,} from './takes-write.ts';+import { BudgetMeter } from './cycle/budget-meter.ts';+import { parseTakesFence } from './takes-fence.ts';export const ALLOWED_PAGE_TYPES = ['concept', 'atom', 'lore', 'briefing', 'writing', 'originals',@@ -65,6 +67,12 @@ export interface ExtractTakesFromPagesOpts {holder?: string;/** Model override; defaults to facts.extraction_model. */model?: string;+ /**+ * USD cap for the run's classifier calls. Default: config+ * `takes.bootstrap_budget_usd`, else 5.0 (the propose_takes default).+ * 0 disables the cap.+ */+ budgetUsd?: number;/** Progress hook called per page. */onProgress?: (done: number, total: number, claims: number) => void;}@@ -85,6 +93,22 @@ export interface ExtractTakesFromPagesResult {skipped: Array<{ slug: string; reason: string }>;/** Count of pages whose md write landed but whose DB mirror warned (reconcile heals). */mirror_warnings: number;+ /** True when the run stopped because the next classifier call would exceed the USD budget. */+ budget_exhausted: boolean;+ /** Extracted claims dropped because the page's takes fence already holds them. */+ duplicates_skipped: number;+}++/** Duplicate key for a take claim: case, whitespace and trailing punctuation aside. */+function claimKey(claim: string, holder: string): string {+ return `${holder}\u0000${claim.toLowerCase().replace(/\s+/g, ' ').trim().replace(/[.!?;:,]+$/, '')}`;+}++async function resolveBudgetUsd(engine: BrainEngine, explicit: number | undefined): Promise<number> {+ if (typeof explicit === 'number' && Number.isFinite(explicit) && explicit >= 0) return explicit;+ const raw = await engine.getConfig('takes.bootstrap_budget_usd').catch(() => null);+ const parsed = raw == null ? NaN : Number.parseFloat(raw);+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : 5.0;}interface PageRow {@@ -128,7 +152,7 @@ export async function extractTakesFromPages(engine: BrainEngine,opts: ExtractTakesFromPagesOpts,): Promise<ExtractTakesFromPagesResult> {- const emptyTail = { pages_skipped: 0, skipped: [], mirror_warnings: 0 };+ const emptyTail = { pages_skipped: 0, skipped: [], mirror_warnings: 0, budget_exhausted: false, duplicates_skipped: 0 };// A12 consent gate: refuse without bootstrap_enabled even on manual call.if (!opts.bootstrapEnabled) {return {@@ -184,7 +208,11 @@ export async function extractTakesFromPages(let claimsExtracted = 0;let pagesSkipped = 0;let mirrorWarnings = 0;+ let budgetExhausted = false;+ let duplicatesSkipped = 0;const skipped: Array<{ slug: string; reason: string }> = [];+ const model = opts.model || getChatModel();+ const meter = new BudgetMeter({ budgetUsd: await resolveBudgetUsd(engine, opts.budgetUsd), phase: 'takes_bootstrap' });// #4473: takes are markdown-canonical (takes-write.ts contract), so the// bootstrap routes every write through the fence writer instead of minting// DB-only rows the next reconcile/extract would clobber.@@ -204,15 +232,15 @@ export async function extractTakesFromPages(// #4473: locate the page's markdown home BEFORE the LLM call — a page the// fence writer would refuse must not burn classifier budget (skipped pages// hold no takes, so every future run would re-classify them).+ let mdPath: string | null = null;if (!dryRun) {- let locatable = false;try {const { path } = await resolveTakesWritePath(engine, repoDir, page.slug, page.source_id);- locatable = existsSync(path);+ if (existsSync(path)) mdPath = path;} catch {- locatable = false; // mirror_unavailable (no repo dir + no source local_path)+ // mirror_unavailable (no repo dir + no source local_path)}- if (!locatable) {+ if (!mdPath) {skipPage(page.slug, 'mirror_unavailable');continue;}@@ -221,6 +249,17 @@ export async function extractTakesFromPages(// Truncate to keep per-page cost bounded (~20K chars → ~5K input tokens).const text = page.compiled_truth.slice(0, 20_000);+ const budget = meter.check({+ modelId: model,+ estimatedInputTokens: Math.ceil((CLASSIFIER_SYSTEM.length + text.length) / 4) + 50,+ maxOutputTokens: 2000,+ label: 'takes_bootstrap',+ });+ if (!budget.allowed) {+ budgetExhausted = true;+ break;+ }+let response: { text: string };try {response = await chat({@@ -228,7 +267,7 @@ export async function extractTakesFromPages(// config, same idiom as enrich.ts) instead of hardcoded cloud Haiku.// On OAuth/local-only installs the hardcoded model made every takes// extraction die with llm_unavailable despite a working chat_model.- model: opts.model || getChatModel(),+ model,system: CLASSIFIER_SYSTEM,messages: [{@@ -238,9 +277,14 @@ export async function extractTakesFromPages(],maxTokens: 2000,});- } catch {- // Skip pages whose chat call fails (rate limit, content filter,- // transient error). Per-page progress continues.+ } catch (err) {+ // Skip pages whose chat call fails (rate limit, content filter, auth,+ // transient error) with the reason, so an outage is distinguishable+ // from "nothing to extract". Per-page progress continues.+ const code = (err as { code?: unknown; status?: unknown } | null)?.code+ ?? (err as { status?: unknown } | null)?.status+ ?? (err instanceof Error ? err.name : 'unknown');+ skipPage(page.slug, `llm_error:${String(code)}`);continue;}@@ -257,7 +301,21 @@ export async function extractTakesFromPages(// collision posture is gone). LLM output is pre-filtered against the// fence-cell guards so one garbled claim drops alone instead of sinking// the page's other claims.- const safeClaims = claims.filter((c) => isSafeFenceCellText(c.claim));+ // Never append a claim the page's takes fence already holds (a rerun with+ // includeCovered, or a hand-added take): duplicate gradeable takes skew+ // calibration. The fence is canonical, so dedupe against its active rows.+ const held = new Set(parseTakesFence(readFileSync(mdPath!, 'utf-8')).takes+ .filter((t) => t.active).map((t) => claimKey(t.claim, t.holder)));+ const safeClaims = claims.filter((c) => {+ if (!isSafeFenceCellText(c.claim)) return false;+ const key = claimKey(c.claim, holder);+ if (held.has(key)) {+ duplicatesSkipped++;+ return false;+ }+ held.add(key);+ return true;+ });if (safeClaims.length === 0) continue;try {const { rowNums, mirror } = await appendTakesToPageMdFirst(@@ -291,5 +349,7 @@ export async function extractTakesFromPages(pages_skipped: pagesSkipped,skipped,mirror_warnings: mirrorWarnings,+ budget_exhausted: budgetExhausted,+ duplicates_skipped: duplicatesSkipped,};}diff --git a/src/core/facts-fence.ts b/src/core/facts-fence.tsindex e83007fac3..2d4afb4340 100644--- a/src/core/facts-fence.ts+++ b/src/core/facts-fence.ts@@ -108,7 +108,8 @@ export interface ParsedFact {* - `claimMetric`: lowercase snake_case after normalization* (`mrr`, `arr`, `team_size`, …). Free-text labels accepted; the* parser does not enforce the seed-map allow-list.- * - `claimValue`: numeric, finite. Empty cell → undefined.+ * - `claimValue`: numeric, finite. Empty cell → undefined; `2.5M` /+ * `900k` / `$1.2B` scale; an unparseable cell is a malformed row.* - `claimUnit`: free-form unit string (`USD`, `people`, `pct`, …).* - `claimPeriod`: free-form period string (`monthly`, `annual`, …)* or undefined for non-periodic metrics.@@ -124,25 +125,34 @@ export interface FactsFenceParseResult {warnings: string[];}+const PLAIN_NUMBER_RE = /^[+-]?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?$/;+function parseConfidenceCell(raw: string): number | undefined {const trimmed = raw.trim();- if (!trimmed) return undefined;- const n = parseFloat(trimmed);+ if (!PLAIN_NUMBER_RE.test(trimmed)) return undefined;+ const n = Number(trimmed);return Number.isFinite(n) ? n : undefined;}/**- * v0.35.4 — parse a free-form numeric cell for typed-claim values.- * Empty / non-numeric → undefined (caller decides whether to drop or warn).- * Tolerates plain numbers and standard scientific notation. Locale-dependent- * thousand separators (`,`) are stripped so `50,000` parses to `50000`.+ * Strict numeric cell for typed-claim values: a plain or scientific number,+ * comma thousands separators only in the `1,234,567` shape, an optional+ * leading currency symbol, and an optional k / M / B magnitude suffix+ * (`2.5M` is 2,500,000). Empty → undefined; any other shape → null, which+ * the parser reports as FACTS_TABLE_MALFORMED rather than storing a wrong+ * numeric prefix (`1,5` → 15, `0.9abc` → 0.9).*/-function parseNumericCell(raw: string): number | undefined {+const NUMERIC_CELL_RE = /^([+-]?)[$€£]?((?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?|\.\d+)((?:[eE][+-]?\d+)?)\s*([kmb]?)$/i;+const MAGNITUDE: Record<string, number> = { '': 1, k: 1e3, m: 1e6, b: 1e9 };++function parseNumericCell(raw: string): number | undefined | null {const trimmed = raw.trim();if (!trimmed) return undefined;- const stripped = trimmed.replace(/,/g, '');- const n = parseFloat(stripped);- return Number.isFinite(n) ? n : undefined;+ const m = NUMERIC_CELL_RE.exec(trimmed);+ if (!m) return null;+ const [, sign, digits, exponent, suffix] = m;+ const n = Number(`${sign}${digits.replace(/,/g, '')}${exponent}`) * MAGNITUDE[suffix.toLowerCase()];+ return Number.isFinite(n) ? n : null;}function parseSupersededByFromContext(context: string | undefined): number | undefined {@@ -270,6 +280,12 @@ export function parseFactsFence(body: string): FactsFenceParseResult {continue;}+ const claimValue = parseNumericCell(claimValueRaw);+ if (claimValue === null) {+ warnings.push(`FACTS_TABLE_MALFORMED: non-numeric claim_value "${claimValueRaw.trim()}" in row ${rowNumStr} (expected a number, optionally 1,234 separators or a k/M/B suffix)`);+ continue;+ }+const { text: claimText, struck } = stripStrikethrough(claimRaw);const context = parseStringCell(contextRaw);const supersededBy = parseSupersededByFromContext(context);@@ -291,7 +307,7 @@ export function parseFactsFence(body: string): FactsFenceParseResult {forgotten: struck ? forgotten : false,// v0.35.4 — typed-claim fields, all optional.claimMetric: parseStringCell(claimMetricRaw),- claimValue: parseNumericCell(claimValueRaw),+ claimValue,claimUnit: parseStringCell(claimUnitRaw),claimPeriod: parseStringCell(claimPeriodRaw),});@@ -304,6 +320,20 @@ export function parseFactsFence(body: string): FactsFenceParseResult {return { facts, warnings };}+/**+ * Render an instant for a `valid_from` / `valid_until` cell. A UTC-midnight+ * value keeps the `YYYY-MM-DD` shape (date-only cells never churn); any other+ * instant is written as a UTC timestamp to the second, so a TTL or a default+ * "now" valid_from survives a re-read of the fence instead of being truncated+ * to the UTC date (which expired same-day TTLs and stamped evening writes west+ * of UTC with tomorrow's date). The parser already accepts both shapes.+ */+export function formatFenceDate(d: Date): string {+ const iso = d.toISOString();+ if (iso.endsWith('T00:00:00.000Z')) return iso.slice(0, 10);+ return iso.replace(/\.\d{3}Z$/, 'Z');+}+function formatConfidence(c: number): string {if (Number.isInteger(c)) return c.toFixed(1);return String(parseFloat(c.toFixed(2)));diff --git a/src/core/facts/backstop.ts b/src/core/facts/backstop.tsindex 952a3b773b..fc4ca85e88 100644--- a/src/core/facts/backstop.ts+++ b/src/core/facts/backstop.ts@@ -61,6 +61,22 @@ export function coerceNotabilityFilter(v: unknown): FactNotabilityFilter {return (NOTABILITY_FILTERS as readonly unknown[]).includes(v) ? (v as FactNotabilityFilter) : 'all';}+/**+ * Context cell for a fact whose entity came from the bare-name+ * `prefix_expansion` branch of `resolveEntitySlugWithSource`: the sole+ * `<dir>/<token>-*` page was chosen by cardinality, not identity. The fact is+ * still written (most such hits are right); the note keeps the uncertainty+ * visible instead of reading like a confirmed fact.+ */+function annotateUnverifiedResolution(+ context: string | null,+ resolutionSource: ResolutionSource | null,+): string | null {+ if (resolutionSource !== 'prefix_expansion') return context;+ const note = 'entity matched by bare name only (prefix expansion) — unverified, please confirm';+ return context ? `${context} — ${note}` : note;+}+export interface FactsBackstopCtx {engine: BrainEngine;config?: GBrainConfig;@@ -564,6 +580,7 @@ async function runPipelineBodyInner(const { resolveEntitySlugWithSource } = await import('../entities/resolve.ts');const { cosineSimilarity } = await import('./classify.ts');const { writeFactsToFence, lookupSourceLocalPath } = await import('./fence-write.ts');+ const { isFactWithdrawn } = await import('./withdrawal.ts');if (abortSignal?.aborted) {return { inserted: 0, duplicate: 0, superseded: 0, fact_ids: [], entity_slugs: [] };@@ -669,6 +686,10 @@ async function runPipelineBodyInner(const resolvedSlug = resolved?.source === 'fallback_slugify' ? null : resolved?.slug ?? null;const resolutionSource = resolved?.source ?? null;+ // B-10: a withdrawn claim for this entity is never re-written; the+ // fence writer rechecks under its page lock.+ if (await isFactWithdrawn(ctx.engine, ctx.sourceId, visibility, f.fact, resolvedSlug)) continue;+// Dedup against DB candidates (correct per Codex Q7: fence rows// have no embeddings; FS lock + sync invariant means DB == fence// at write time). Threshold 0.95 unchanged.@@ -754,7 +775,7 @@ async function runPipelineBodyInner(for (const s of unparented) legacyBucket.push(s);}- for (const { f, resolvedSlug } of legacyBucket) {+ for (const { f, resolvedSlug, resolutionSource } of legacyBucket) {const newFact: NewFact = {fact: f.fact,kind: f.kind,@@ -770,7 +791,7 @@ async function runPipelineBodyInner(// DB-only row has no fence to name the page it came from, so the page// path's slug fills context when the caller passed no sourceSlug.valid_from: f.valid_from ?? ctx.validFrom,- context: ctx.sourceSlug ?? input.pageSlug ?? null,+ context: annotateUnverifiedResolution(ctx.sourceSlug ?? input.pageSlug ?? null, resolutionSource),};const result = await ctx.engine.insertFact(newFact, { source_id: ctx.sourceId }); // gbrain-allow-direct-insert: legacy DB-only fallback for unparented / thin-client facts (no entity page to fence onto)fact_ids.push(result.id);@@ -791,14 +812,14 @@ async function runPipelineBodyInner(for (const [slug, group] of byEntity) {if (abortSignal?.aborted) break;- const inputFacts = group.map(({ f }) => ({+ const inputFacts = group.map(({ f, resolutionSource }) => ({fact: f.fact,kind: f.kind,notability: f.notability,source: f.source,// #4206: the caller's source_slug (which page/transcript the turn came// from) lands in the fence context cell — visible in recall projections.- context: ctx.sourceSlug ?? null,+ context: annotateUnverifiedResolution(ctx.sourceSlug ?? null, resolutionSource),visibility,confidence: f.confidence,// #4206: extractor-derived date wins; then the caller's event timediff --git a/src/core/facts/embedding-identity.ts b/src/core/facts/embedding-identity.tsindex 8e05d70dd4..6b2a76158a 100644--- a/src/core/facts/embedding-identity.ts+++ b/src/core/facts/embedding-identity.ts@@ -6,7 +6,7 @@ export const retainedFactEmbedding = `f.expired_at IS NULL AND f.superseded_by IAND NOT (f.source = ANY($2::text[]))AND NOT EXISTS (SELECT 1 FROM fact_withdrawals w WHERE w.source_id=f.source_idAND w.visibility=f.visibility AND (w.subject = '*' OR w.subject = f.entity_slug)- AND w.fact_hash=gbrain_fact_fingerprint(f.fact))`;+ AND w.fact_hash IN (gbrain_fact_fingerprint(f.fact),gbrain_fact_fingerprint_v1(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/extract.ts b/src/core/facts/extract.tsindex 6afdaa2e7b..c25f29cf5c 100644--- a/src/core/facts/extract.ts+++ b/src/core/facts/extract.ts@@ -165,6 +165,19 @@ export async function isJunkFilterEnabled(engine?: BrainEngine): Promise<booleanreturn !['false', '0', 'no', 'off'].includes(raw.trim().toLowerCase());}+/**+ * Confidence stored for a candidate whose confidence is missing, null or not+ * a number. Legacy default 1.0; `facts.extraction_missing_confidence` (a+ * number in 0..1) opts into a less certain value. Opt-in because confidence+ * feeds hot-memory ordering and decay, and no matched eval has measured a+ * different default.+ */+export async function getMissingConfidence(engine?: BrainEngine): Promise<number> {+ const raw = engine ? await engine.getConfig('facts.extraction_missing_confidence').catch(() => null) : null;+ const n = raw == null || raw.trim() === '' ? NaN : Number(raw.trim());+ return Number.isFinite(n) && n >= 0 && n <= 1 ? n : 1.0;+}+export const ALL_EXTRACT_KINDS: readonly FactKind[] = ['event', 'preference', 'commitment', 'belief', 'fact', 'idea',] as const;@@ -498,9 +511,10 @@ export async function extractFactsFromTurnWithOutcome(// because those reuse `extractorSystem`. Read AFTER the availability gate —// a chat_unavailable early return must not pay config round-trips (#4298// resolved the model/gate ordering; these reads sit behind it).- const [promptAppendix, junkFilterOn] = await Promise.all([+ const [promptAppendix, junkFilterOn, missingConfidence] = await Promise.all([getFactsExtractionPromptAppendix(input.engine),isJunkFilterEnabled(input.engine),+ getMissingConfidence(input.engine),]);const extractorSystem = promptAppendix? `${buildExtractorSystem(admitsLow)}\n\n${promptAppendix}`@@ -611,6 +625,10 @@ export async function extractFactsFromTurnWithOutcome(`kept ${parsedShape.facts.length}\n`,);}+ const unknownKinds = parsedShape.facts.filter(f => !ALL_EXTRACT_KINDS.includes(f.kind as FactKind)).length;+ if (unknownKinds > 0) {+ process.stderr.write(`[facts-extract] WARN: ${unknownKinds} candidate(s) carried an unknown kind; stored as 'fact'\n`);+ }const parsedRaw = parsedShape.facts;const facts: ExtractedFact[] = [];@@ -637,7 +655,7 @@ export async function extractFactsFromTurnWithOutcome(continue;}- const confidence = clampConfidence(candidate.confidence);+ const confidence = clampConfidence(candidate.confidence, missingConfidence);const validTier = ['high', 'medium', 'low'].includes(candidate.notability ?? '');if (input.notabilityAdmission) {const tier = validTier ? candidate.notability as FactNotability : null;@@ -814,7 +832,14 @@ function tryArrayShapeDetailed(s: string): ParsedExtractorShape | null {fact: o.fact,kind: o.kind,entity: typeof o.entity === 'string' ? o.entity : null,- confidence: typeof o.confidence === 'number' ? o.confidence : 1.0,+ // A missing / null / non-numeric confidence stays undefined here;+ // clampConfidence applies the configured missing-confidence value. A+ // numeric string ("0.3") is the model's stated confidence.+ confidence: typeof o.confidence === 'number'+ ? o.confidence+ : typeof o.confidence === 'string' && /^\s*(?:\d+(?:\.\d+)?|\.\d+)\s*$/.test(o.confidence)+ ? Number(o.confidence)+ : undefined,notability: typeof o.notability === 'string' ? o.notability : undefined,// v0.35.4 (D-CDX-2) — typed-claim fields. Strict shape: metric/unit/period// must be string-or-null; value must be a finite number-or-null. Anything@@ -832,8 +857,8 @@ function tryArrayShapeDetailed(s: string): ParsedExtractorShape | null {}}-function clampConfidence(x: number | undefined): number {- if (typeof x !== 'number' || !Number.isFinite(x)) return 1.0;+function clampConfidence(x: number | undefined, missing: number): number {+ if (typeof x !== 'number' || !Number.isFinite(x)) return missing;if (x < 0) return 0;if (x > 1) return 1;return x;diff --git a/src/core/facts/fence-write.ts b/src/core/facts/fence-write.tsindex d28423fb38..087eb7a7c0 100644--- a/src/core/facts/fence-write.ts+++ b/src/core/facts/fence-write.ts@@ -48,10 +48,11 @@ import { assertSourceFilesystemActive, hasSourceFilesystemLock, withSourceFilesyimport { gbrainPath } from '../config.ts';import { isWriteThroughDisabled, resolvePageWriteTarget } from '../write-through.ts';import { isDurabilityHardened, commitWriteThroughFile } from '../brain-repo-durability.ts';-import { upsertFactRow, parseFactsFence } from '../facts-fence.ts';+import { upsertFactRow, parseFactsFence, formatFenceDate } from '../facts-fence.ts';import { contentHash } from '../utils.ts';import { extractFactsFromFenceText } from './extract-from-fence.ts';import { logStubGuardEvent } from './stub-guard-audit.ts';+import { isFactWithdrawn } from './withdrawal.ts';import { assertUnmanagedCanonicalWriter } from '../persistence/maintenance.ts';/** Resolved source binding for the entity page. */@@ -86,8 +87,9 @@ export interface FenceInputFact {confidence?: number;validFrom?: Date;/**- * MEMORY_VERBS v1 (c5): remember's ttl → valid_until. Date-only in the- * fence cell; the DB column derives from it on the stamp step.+ * MEMORY_VERBS v1 (c5): remember's ttl → valid_until. Written to the+ * fence cell losslessly (formatFenceDate); the DB column derives from it on+ * the stamp step.* Undefined/null = never expires (pre-v1 behavior unchanged).*/validUntil?: Date | null;@@ -117,6 +119,12 @@ export interface FenceWriteResult {* `jared.md` stub.*/stubGuardBlocked?: true;+ /**+ * Input facts dropped because their claim is withdrawn for this page's+ * entity (write-path audit B-10): a withdrawn claim is never appended to+ * the Markdown fence as an active row.+ */+ withdrawnSkipped?: number;/*** True when the shared page-target resolver could not produce a usable* fence file path (source tree missing / not a directory, or a hostile@@ -321,6 +329,14 @@ export async function writeFactsToFence(return withPageLock(target.slug,async () => {+ const kept: FenceInputFact[] = [];+ for (const f of facts) {+ if (!await isFactWithdrawn(engine, target.sourceId, f.visibility, f.fact, target.slug)) kept.push(f);+ }+ const withdrawnSkipped = facts.length - kept.length ? { withdrawnSkipped: facts.length - kept.length } : {};+ facts = kept;+ if (!facts.length) return { inserted: 0, ids: [], ...withdrawnSkipped };+// 1. Read existing body or stub-create.let body: string;if (existsSync(filePath)) {@@ -376,7 +392,7 @@ export async function writeFactsToFence(? `[facts] refusing to stub-create unprefixed entity page slug=${target.slug} — routing to legacy DB-only path. Provide a directory prefix (people/, companies/, etc.) to opt into fence writes.`: `[facts] refusing to stub-create entity page slug=${target.slug} from a fallback-resolved reference (no live page verified) — routing to legacy DB-only path.`,);- return { inserted: 0, ids: [], stubGuardBlocked: true };+ return { inserted: 0, ids: [], stubGuardBlocked: true, ...withdrawnSkipped };}// Stub-create the parent directory if it doesn't exist.mkdirSync(dirname(filePath), { recursive: true });@@ -408,7 +424,8 @@ export async function writeFactsToFence(// Degrades to the previous file-only behaviour if the lookup fails// (pre-v51 brain without the fence columns, or a transient DB error):// a fence write must not become impossible just because the counter- // hint is unavailable.+ // hint is unavailable. The degradation is reported, never silent,+ // because file-only numbering is the duplicate-key class above.let dbMaxRowNum = 0;try {const rows = await engine.executeRaw<{ max_row_num: number | null }>(@@ -417,8 +434,8 @@ export async function writeFactsToFence([target.sourceId, target.slug],);dbMaxRowNum = Number(rows[0]?.max_row_num ?? 0);- } catch {- dbMaxRowNum = 0;+ } catch (err) {+ console.warn(`[facts.fence] FACTS_ROW_NUM_HINT_UNAVAILABLE: ${target.slug} (source ${target.sourceId}): ${err instanceof Error ? err.message : String(err)}; numbering from the file alone`);}const { facts: existingFenceFacts } = parseFactsFence(body);const fileMaxRowNum = existingFenceFacts.length > 0@@ -428,7 +445,6 @@ export async function writeFactsToFence(const assignedRowNums: number[] = [];for (const f of facts) {- const validFromStr = (f.validFrom ?? new Date()).toISOString().slice(0, 10);const { body: updated, rowNum } = upsertFactRow(body, {rowNum: nextRowNum++,claim: f.fact,@@ -436,11 +452,11 @@ export async function writeFactsToFence(confidence: f.confidence ?? 1.0,visibility: f.visibility,notability: f.notability ?? 'medium',- validFrom: validFromStr,+ validFrom: formatFenceDate(f.validFrom ?? new Date()),// MEMORY_VERBS v1 (c5): remember's ttl threads through to the fence// cell — was hard-coded undefined, which silently dropped expiry on// this path. extractFactsFromFenceText derives the DB column from it.- validUntil: f.validUntil ? f.validUntil.toISOString().slice(0, 10) : undefined,+ validUntil: f.validUntil ? formatFenceDate(f.validUntil) : undefined,source: f.source,context: f.context ?? undefined,});@@ -494,7 +510,11 @@ export async function writeFactsToFence(sanitizeText(reparsed.compiled_truth), sanitizeText(reparsed.timeline),existing.content_hash || contentHash(existing));}- } catch { /* degrades to the pre-#4872 window (stale until the next sync) */ }+ } catch (err) {+ // The file is committed; the page cache stays stale until the next+ // sync (reconcile refuses destructive work meanwhile). Say so.+ console.warn(`[facts.fence] FACTS_PAGE_MIRROR_FAILED: ${target.slug} (source ${target.sourceId}): ${err instanceof Error ? err.message : String(err)}; pages cache stale until the next sync`);+ }// 6. Stamp the DB. extractFactsFromFenceText handles the// validFrom/validUntil date derivation + the strikethrough@@ -535,7 +555,7 @@ export async function writeFactsToFence(durabilityPrewriteState,);}- return { inserted: result.inserted, ids: result.ids };+ return { inserted: result.inserted, ids: result.ids, ...withdrawnSkipped };},{ timeoutMs: 5_000 },);diff --git a/src/core/facts/supersede-resolve.ts b/src/core/facts/supersede-resolve.tsindex a51a4c84a2..0167c23e67 100644--- a/src/core/facts/supersede-resolve.ts+++ b/src/core/facts/supersede-resolve.ts@@ -22,7 +22,7 @@ export interface SupersedeTarget {/*** true when the target row is itself inactive (its `expired_at` is set)* — e.g. `#N` points at a forgotten row or an already-superseded row. A- * supersession target must be a live row, so a struck target is rejected.+ * struck target resolves only when it is itself superseded (a chain).*/struck: boolean;}@@ -51,6 +51,13 @@ export function isInt4RowRef(n: number): boolean {return Number.isInteger(n) && n >= 1 && n <= PG_INT4_MAX;}+/**+ * Page-local supersession links: row number -> the row it is+ * `superseded by #N`, for struck rows only. Active, forgotten and+ * unrecognized-inactive rows are absent.+ */+export type SupersessionChain = ReadonlyMap<number, number>;+/*** Resolve a struck row's `superseded by #N` page-local reference to a* fact id. Pure: the caller supplies the already-looked-up `target`@@ -62,14 +69,19 @@ export function isInt4RowRef(n: number): boolean {* regardless of the outcome so the struck row still exits active views:* - self-reference (`#N` == the row's own number)* - dangling (`#N` names a row absent from the page)- * - struck target (`#N` names a row that is itself inactive — a- * supersession chain, or a forgotten target)+ * - struck target that is not itself superseded (forgotten or+ * unrecognized-inactive), or a chain that cycles back+ *+ * A struck target that is itself superseded is the normal A -> B -> C+ * history and resolves: every hop keeps its link. `chain` carries the+ * page's struck-row links for that check.*/export function resolveSupersededByRow(ownRowNum: number,supersededByRow: number,target: SupersedeTarget | undefined,slug: string,+ chain: SupersessionChain = new Map(),): SupersedeResolution {if (supersededByRow === ownRowNum) {return {@@ -83,11 +95,35 @@ export function resolveSupersededByRow(warning: `${slug} row ${ownRowNum}: "superseded by #${supersededByRow}" names a row absent from the fence — leaving superseded_by NULL`,};}- if (target.struck) {+ if (target.struck && !chain.has(supersededByRow)) {return {superseded_by: null,- warning: `${slug} row ${ownRowNum}: "superseded by #${supersededByRow}" names a row that is itself struck (inactive) — a supersession target must be a live row; leaving superseded_by NULL`,+ warning: `${slug} row ${ownRowNum}: "superseded by #${supersededByRow}" names a row that is itself struck (inactive) without being superseded — a supersession target must be a live or superseded row; leaving superseded_by NULL`,};}+ const seen = new Set([ownRowNum]);+ for (let row: number | undefined = supersededByRow; row !== undefined; row = chain.get(row)) {+ if (seen.has(row)) {+ return {+ superseded_by: null,+ warning: `${slug} row ${ownRowNum}: "superseded by #${supersededByRow}" forms a supersession cycle — leaving superseded_by NULL`,+ };+ }+ seen.add(row);+ }return { superseded_by: target.id, warning: null };}++/** The struck-row supersession links a batch of fence rows declares for one page. */+export function supersessionChainOf(+ rows: ReadonlyArray<{ row_num: number; source_markdown_slug: string; superseded_by_row?: number; expired_at?: Date | null }>,+ slug: string,+): Map<number, number> {+ const chain = new Map<number, number>();+ for (const row of rows) {+ if (row.source_markdown_slug === slug && row.expired_at != null && row.superseded_by_row !== undefined) {+ chain.set(row.row_num, row.superseded_by_row);+ }+ }+ return chain;+}diff --git a/src/core/facts/withdrawal-discovery.ts b/src/core/facts/withdrawal-discovery.tsindex 8b6d5977cd..3be3d74686 100644--- a/src/core/facts/withdrawal-discovery.ts+++ b/src/core/facts/withdrawal-discovery.ts@@ -4,13 +4,25 @@ import { getCode } from '../retry-matcher.ts';import { parseRowCells, isSeparatorRow, stripStrikethrough } from '../fence-shared.ts';import { withdrawalFenceBlocks, ambiguousWithdrawalFenceSegments } from './withdrawal-overlay.ts';-export const WITHDRAWAL_LIMITS = { pages: 12_000, chunks: 40_000, facts: 40_000, bytes: 64 * 1024 * 1024, targets: 256, targetBytes: 1024 * 1024, scanMs: 10_000, batch: 128 } as const;+export const WITHDRAWAL_LIMITS = { targets: 256, targetBytes: 1024 * 1024, scanMs: 10_000, batch: 128 } as const;export interface WithdrawalTarget { slug: string; page_id: number; revision: string }-export interface WithdrawalClaim { visibility: string; fact_hash: string }+/** `subject` is the ledger subject ('*' = every entity); `claim` is the fact text when the caller already holds it. */+export interface WithdrawalClaim { visibility: string; fact_hash: string; subject?: string | null; claim?: string | null }+interface KeyedClaim { visibility: string; fact_hash: string; subject: string; norm: string | null }++const RECOVERY = 'See docs/guides/concurrent-writes.md#withdrawal-recovery.';function refuse(code = 'withdrawal_capacity'): never {throw new OperationError(code, 'Withdrawal discovery could not prove a bounded complete target set. This attempt committed no withdrawal or page changes; earlier durable intent remains retained.',- 'Do not retry unchanged or split/delete the source. Keep mutation workers quiesced and inspect the source with the host operator; repair malformed fact fences before retrying. See docs/guides/concurrent-writes.md#withdrawal-recovery.');+ `Do not retry unchanged or split/delete the source. Keep mutation workers quiesced and inspect the source with the host operator; repair malformed fact fences before retrying. ${RECOVERY}`);+}++async function refuseAffected(engine: BrainEngine, sourceId: string, affected: Set<number>): Promise<never> {+ const sample = await engine.executeRaw<{ slug: string }>('SELECT slug FROM pages WHERE source_id=$1 AND id=ANY($2::int[]) ORDER BY slug LIMIT 20',+ [sourceId, [...affected]]);+ throw new OperationError('withdrawal_capacity',+ `This claim is carried by more than ${WITHDRAWAL_LIMITS.targets} pages (${affected.size} matched before discovery stopped), the bound for one atomic withdrawal. Source size is not the limit. Nothing was committed; earlier durable intent remains retained.`,+ `Reduce the pages that carry this claim, then retry: forget the entity-scoped copies of the fact first (each changes only its own entity's pages), or edit the claim out of pages that should not carry it. Matched pages include: ${sample.map(row => row.slug).join(', ')}. ${RECOVERY}`);}export function ambiguousFenceClaims(body: string): Array<{ claim: string; visibility: string | null }> {@@ -24,62 +36,85 @@ export function ambiguousFenceClaims(body: string): Array<{ claim: string; visibreturn claims;}+/**+ * Claim-keyed discovery. Every fence row, chunk row or whole chunk whose+ * fingerprint equals the claim contains each of the claim's normalized tokens+ * as a substring of its lowercased text (normalization only turns punctuation+ * and whitespace into token boundaries), so pages and chunks are shortlisted+ * in SQL by those tokens, streamed by keyset, then verified exactly. Work and+ * the target bound scale with the claim's affected set, never with source size.+ */export async function discoverWithdrawalTargets(engine: BrainEngine, sourceId: string, claims: readonly WithdrawalClaim[]): Promise<WithdrawalTarget[]> {if (!claims.length) return [];if (claims.length > WITHDRAWAL_LIMITS.targets) refuse();const deadline = performance.now() + WITHDRAWAL_LIMITS.scanMs;- const pageSizes = await engine.executeRaw<{ id: number; bytes: number }>(`SELECT id,octet_length(compiled_truth)+octet_length(timeline) AS bytes- FROM pages WHERE source_id=$1 ORDER BY id LIMIT $2`, [sourceId, WITHDRAWAL_LIMITS.pages + 1]);- const chunkSizes = await engine.executeRaw<{ id: number; bytes: number }>(`SELECT c.id,octet_length(c.chunk_text) AS bytes FROM content_chunks c- JOIN pages p ON p.id=c.page_id WHERE p.source_id=$1 ORDER BY c.id LIMIT $2`, [sourceId, WITHDRAWAL_LIMITS.chunks + 1]);- const factSizes = await engine.executeRaw<{ id: number; bytes: number }>(`SELECT id,octet_length(fact) AS bytes FROM facts- WHERE source_id=$1 ORDER BY id LIMIT $2`, [sourceId, WITHDRAWAL_LIMITS.facts + 1]);- if (pageSizes.length > WITHDRAWAL_LIMITS.pages || chunkSizes.length > WITHDRAWAL_LIMITS.chunks || factSizes.length > WITHDRAWAL_LIMITS.facts ||- [...pageSizes, ...chunkSizes, ...factSizes].reduce((sum, row) => sum + Number(row.bytes), 0) > WITHDRAWAL_LIMITS.bytes) refuse();+ const keyed = await engine.executeRaw<KeyedClaim>(`WITH w AS (+ SELECT w.visibility,w.fact_hash,COALESCE(w.subject,'*') AS subject,gbrain_fact_normalize(COALESCE(w.claim,+ (SELECT f.fact FROM facts f WHERE f.source_id=$1 AND f.visibility=w.visibility AND gbrain_fact_fingerprint(f.fact)=w.fact_hash LIMIT 1),+ (SELECT f.fact FROM facts f WHERE f.source_id=$1 AND f.visibility=w.visibility AND gbrain_fact_fingerprint_v1(f.fact)=w.fact_hash LIMIT 1))) AS norm+ FROM jsonb_to_recordset($2::text::jsonb) w(visibility text,fact_hash text,subject text,claim text)+ ) SELECT * FROM w`,+ [sourceId, JSON.stringify(claims.map(c => ({ visibility: c.visibility, fact_hash: c.fact_hash, subject: c.subject ?? '*', claim: c.claim ?? null })))]);+ const keys = JSON.stringify(keyed.map(k => ({ ...k, tokens: k.norm ? k.norm.split(' ').filter(Boolean) : [] })));+ const subjects = keyed.some(k => k.subject === '*') ? null : [...new Set(keyed.map(k => k.subject))];const affected = new Set<number>();- const provenance = await engine.executeRaw<{ id: number }>(`SELECT DISTINCT p.id FROM facts f- JOIN pages p ON p.source_id=f.source_id AND p.slug=COALESCE(f.source_markdown_slug,f.entity_slug)- JOIN jsonb_to_recordset($2::text::jsonb) w(visibility text,fact_hash text)- ON w.visibility=f.visibility AND w.fact_hash=gbrain_fact_fingerprint(f.fact) WHERE f.source_id=$1`, [sourceId, JSON.stringify(claims)]);+ const provenance = await engine.executeRaw<{ id: number }>(`SELECT DISTINCT p.id+ FROM jsonb_to_recordset($2::text::jsonb) k(visibility text,fact_hash text,subject text,norm text)+ JOIN facts f ON f.source_id=$1 AND f.visibility=k.visibility+ AND gbrain_fact_fingerprint(f.fact)=COALESCE(encode(sha256(convert_to(k.norm,'UTF8')),'hex'),k.fact_hash)+ AND (k.subject='*' OR f.entity_slug=k.subject)+ JOIN pages p ON p.source_id=f.source_id AND p.slug=COALESCE(f.source_markdown_slug,f.entity_slug)`, [sourceId, keys]);for (const row of provenance) affected.add(row.id);- if (affected.size > WITHDRAWAL_LIMITS.targets) refuse();- const match = async (incoming: Array<{ id: number; claim: string; visibility: string | null; ambiguous: boolean }>) => {+ if (affected.size > WITHDRAWAL_LIMITS.targets) await refuseAffected(engine, sourceId, affected);+ const match = async (incoming: Array<{ id: number; slug: string; claim: string; visibility: string | null; ambiguous: boolean }>) => {if (!incoming.length) return;if (incoming.length > 16_384 || Buffer.byteLength(JSON.stringify(incoming)) > 8 * 1024 * 1024) refuse();const matches = await engine.executeRaw<{ id: number; ambiguous: boolean }>(`SELECT DISTINCT i.id,i.ambiguous- FROM jsonb_to_recordset($1::text::jsonb) i(id integer,claim text,visibility text,ambiguous boolean)- JOIN jsonb_to_recordset($2::text::jsonb) w(visibility text,fact_hash text)- ON (i.visibility IS NULL OR i.visibility=w.visibility) AND gbrain_fact_fingerprint(i.claim)=w.fact_hash`, [JSON.stringify(incoming), JSON.stringify(claims)]);+ FROM jsonb_to_recordset($1::text::jsonb) i(id integer,slug text,claim text,visibility text,ambiguous boolean)+ JOIN jsonb_to_recordset($2::text::jsonb) w(visibility text,fact_hash text,subject text)+ ON (i.visibility IS NULL OR i.visibility=w.visibility) AND (w.subject='*' OR w.subject=i.slug)+ AND w.fact_hash IN (gbrain_fact_fingerprint(i.claim),gbrain_fact_fingerprint_v1(i.claim))`, [JSON.stringify(incoming), keys]);if (matches.some(row => row.ambiguous)) refuse('withdrawal_provenance');for (const row of matches) affected.add(row.id);- if (affected.size > WITHDRAWAL_LIMITS.targets) refuse();+ if (affected.size > WITHDRAWAL_LIMITS.targets) await refuseAffected(engine, sourceId, affected);};- for (let offset = 0; offset < pageSizes.length; offset += WITHDRAWAL_LIMITS.batch) {+ const shortlist = (text: string) => `NOT EXISTS (SELECT 1 FROM jsonb_array_elements_text(k.tokens) t(v) WHERE strpos(lower(${text}),t.v)=0)`;+ for (let after = 0; ;) {if (performance.now() > deadline) refuse();- const pages = await engine.executeRaw<{ id: number; compiled_truth: string; timeline: string }>(- 'SELECT id,compiled_truth,timeline FROM pages WHERE source_id=$1 AND id=ANY($2::int[])', [sourceId, pageSizes.slice(offset, offset + WITHDRAWAL_LIMITS.batch).map(row => row.id)]);- const incoming = pages.flatMap(page => [page.compiled_truth, page.timeline].flatMap(body => [- ...withdrawalFenceBlocks(body).filter(block => !block.parsed.warnings.length).flatMap(block => block.parsed.facts.map(f => ({ id: page.id, claim: f.claim, visibility: f.visibility, ambiguous: false }))),- ...ambiguousFenceClaims(body).map(f => ({ id: page.id, ...f, ambiguous: true })),- ]));- await match(incoming);+ const pages = await engine.executeRaw<{ id: number; slug: string; compiled_truth: string; timeline: string }>(`SELECT p.id,p.slug,p.compiled_truth,p.timeline FROM pages p+ WHERE p.source_id=$1 AND p.id>$3 AND ($5::text[] IS NULL OR p.slug=ANY($5::text[]))+ AND (strpos(p.compiled_truth,'gbrain:facts:')>0 OR strpos(p.timeline,'gbrain:facts:')>0)+ AND EXISTS (SELECT 1 FROM jsonb_to_recordset($2::text::jsonb) k(subject text,tokens jsonb)+ WHERE (k.subject='*' OR k.subject=p.slug) AND ((${shortlist('p.compiled_truth')}) OR (${shortlist('p.timeline')})))+ ORDER BY p.id LIMIT $4`, [sourceId, keys, after, WITHDRAWAL_LIMITS.batch, subjects]);+ await match(pages.flatMap(page => [page.compiled_truth, page.timeline].flatMap(body => [+ ...withdrawalFenceBlocks(body).filter(block => !block.parsed.warnings.length).flatMap(block => block.parsed.facts.map(f => ({ id: page.id, slug: page.slug, claim: f.claim, visibility: f.visibility, ambiguous: false }))),+ ...ambiguousFenceClaims(body).map(f => ({ id: page.id, slug: page.slug, ...f, ambiguous: true })),+ ])));+ if (pages.length < WITHDRAWAL_LIMITS.batch) break;+ after = pages[pages.length - 1].id;}- for (let offset = 0; offset < chunkSizes.length; offset += WITHDRAWAL_LIMITS.batch) {+ for (let after = 0; ;) {if (performance.now() > deadline) refuse();- const chunks = await engine.executeRaw<{ page_id: number; chunk_text: string }>(- 'SELECT page_id,chunk_text FROM content_chunks WHERE id=ANY($1::int[])', [chunkSizes.slice(offset, offset + WITHDRAWAL_LIMITS.batch).map(row => row.id)]);+ const chunks = await engine.executeRaw<{ id: number; page_id: number; slug: string; chunk_text: string }>(`SELECT c.id,c.page_id,p.slug,c.chunk_text+ FROM content_chunks c JOIN pages p ON p.id=c.page_id+ WHERE p.source_id=$1 AND c.id>$3 AND ($5::text[] IS NULL OR p.slug=ANY($5::text[]))+ AND EXISTS (SELECT 1 FROM jsonb_to_recordset($2::text::jsonb) k(subject text,tokens jsonb)+ WHERE (k.subject='*' OR k.subject=p.slug) AND ${shortlist('c.chunk_text')})+ ORDER BY c.id LIMIT $4`, [sourceId, keys, after, WITHDRAWAL_LIMITS.batch, subjects]);await match(chunks.flatMap(chunk => {- const rows = [{ id: chunk.page_id, claim: chunk.chunk_text, visibility: null as string | null, ambiguous: false }];+ const rows = [{ id: chunk.page_id, slug: chunk.slug, claim: chunk.chunk_text, visibility: null as string | null, ambiguous: false }];for (const line of chunk.chunk_text.split('\n')) {const cells = parseRowCells(line.slice(Math.max(0, line.indexOf('|'))));if (!cells || isSeparatorRow(cells) || !cells[1]) continue;const { text, struck } = stripStrikethrough(cells[1]);- if (!struck) rows.push({ id: chunk.page_id, claim: text, visibility: ['private', 'world'].includes(cells[4]) ? cells[4] : null, ambiguous: false });+ if (!struck) rows.push({ id: chunk.page_id, slug: chunk.slug, claim: text, visibility: ['private', 'world'].includes(cells[4]) ? cells[4] : null, ambiguous: false });}return rows;}));+ if (chunks.length < WITHDRAWAL_LIMITS.batch) break;+ after = chunks[chunks.length - 1].id;}- if (affected.size > WITHDRAWAL_LIMITS.targets) refuse();const targets = await engine.executeRaw<WithdrawalTarget>('SELECT slug,id AS page_id,knowledge_revision AS revision FROM pages WHERE source_id=$1 AND id=ANY($2::int[])', [sourceId, [...affected]]);if (performance.now() > deadline || Buffer.byteLength(JSON.stringify(targets)) > WITHDRAWAL_LIMITS.targetBytes) refuse();return targets.sort((a, b) => a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : 0);diff --git a/src/core/facts/withdrawal-overlay.ts b/src/core/facts/withdrawal-overlay.tsindex de9a59e353..0de7a9b7a5 100644--- a/src/core/facts/withdrawal-overlay.ts+++ b/src/core/facts/withdrawal-overlay.ts@@ -2,6 +2,7 @@ import { createHash } from 'node:crypto';import { FACTS_FENCE_BEGIN, FACTS_FENCE_END, parseFactsFence, renderFactsTable, type ParsedFact } from '../facts-fence.ts';import type { PageWithdrawal } from '../page-state/types.ts';import { OperationError } from '../ops/contract.ts';+import { normalizeLoweredClaim } from './withdrawal-schema.ts';export const WITHDRAWAL_MARKER_LIMIT = 16_384;@@ -122,7 +123,8 @@ export function overlayWithdrawalBody(body: string, normalizedBody: string, withconst facts = block.parsed.facts.map(f => {const claim = claims.get(f.rowNum);if (claim === undefined) return f;- const at = ledger.get(`${f.visibility}:${createHash('sha256').update(claim).digest('hex')}`);+ const at = ledger.get(`${f.visibility}:${createHash('sha256').update(normalizeLoweredClaim(claim)).digest('hex')}`)+ ?? ledger.get(`${f.visibility}:${createHash('sha256').update(claim).digest('hex')}`);if (!at) return f;changed = true;return withdrawnFact(f, new Date(at).toISOString().slice(0, 10));diff --git a/src/core/facts/withdrawal-schema.ts b/src/core/facts/withdrawal-schema.tsindex 234a59f95c..0c5f8c6fbc 100644--- a/src/core/facts/withdrawal-schema.ts+++ b/src/core/facts/withdrawal-schema.ts@@ -1,3 +1,22 @@+/**+ * Characters folded to a space before hashing, so punctuation variants of one+ * claim share a fingerprint. Explicit (not [[:punct:]]) so the SQL and the JS+ * overlay agree regardless of database locale; non-ASCII letters survive.+ * `+` and `#` are kept ("C++", "C#", "F#" never collide with "C" or "F"), and a+ * dot folds only when a space, another dot or the end follows it, so sentence+ * periods fold while ".NET", "Node.js" and "3.5" keep theirs.+ */+export const FINGERPRINT_PUNCTUATION = '!"$%&\'()*,-/:;<=>?@[\\]^_`{|}~\u2018\u2019\u201a\u201c\u201d\u201e\u00ab\u00bb\u2039\u203a\u2013\u2014\u2015\u2026\u00b7\u2022\u00a1\u00bf';++/** JS twin of gbrain_fact_normalize for text the database already lowercased and space-collapsed. */+export function normalizeLoweredClaim(claim: string): string {+ let out = '';+ for (const char of claim) out += FINGERPRINT_PUNCTUATION.includes(char) ? ' ' : char;+ return out.replace(/ +/g, ' ').replace(/\.(?=[. ]|$)/g, ' ').replace(/ +/g, ' ').replace(/^ | $/g, '');+}++const NORMALIZE_CLAIM_SQL = `btrim(regexp_replace(regexp_replace(regexp_replace(translate(lower(claim), '${FINGERPRINT_PUNCTUATION.replace(/'/g, "''")}', '${' '.repeat([...FINGERPRINT_PUNCTUATION].length)}'), '[[:space:]]+', ' ', 'g'), '\\.(?=[. ]|$)', ' ', 'g'), ' +', ' ', 'g'), ' ')`;+/*** Durable withdrawal survives deletion/recreation of the derived facts index.*@@ -6,7 +25,9 @@* 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`.+ * entity_slug`. Fingerprints fold case, whitespace and punctuation (v174);+ * ledger rows written earlier carry the exact v1 fingerprint and keep+ * matching through gbrain_fact_fingerprint_v1.*/export const FACT_WITHDRAWAL_SCHEMA_STATEMENTS = [`CREATE TABLE IF NOT EXISTS fact_withdrawals (@@ -17,10 +38,17 @@ export const FACT_WITHDRAWAL_SCHEMA_STATEMENTS = [withdrawn_at TIMESTAMPTZ NOT NULL DEFAULT now(),PRIMARY KEY (source_id, visibility, subject, fact_hash))`,- `CREATE OR REPLACE FUNCTION gbrain_fact_fingerprint(claim TEXT) RETURNS TEXT+ `CREATE OR REPLACE FUNCTION gbrain_fact_fingerprint_v1(claim TEXT) RETURNS TEXTLANGUAGE SQL IMMUTABLE STRICT AS $fn$SELECT encode(sha256(convert_to(regexp_replace(lower(btrim(claim)), '[[:space:]]+', ' ', 'g'), 'UTF8')), 'hex')$fn$`,+ `CREATE OR REPLACE FUNCTION gbrain_fact_normalize(claim TEXT) RETURNS TEXT+ LANGUAGE SQL IMMUTABLE STRICT AS $fn$ SELECT ${NORMALIZE_CLAIM_SQL} $fn$`,+ // Inlined rather than calling gbrain_fact_normalize: index builds resolve+ // functions with a restricted search_path, so the index expression must+ // reference only built-ins.+ `CREATE OR REPLACE FUNCTION gbrain_fact_fingerprint(claim TEXT) RETURNS TEXT+ LANGUAGE SQL IMMUTABLE STRICT AS $fn$ SELECT encode(sha256(convert_to(${NORMALIZE_CLAIM_SQL}, 'UTF8')), 'hex') $fn$`,`CREATE OR REPLACE FUNCTION gbrain_preserve_fact_withdrawal() RETURNS triggerLANGUAGE plpgsql AS $fn$DECLARE withdrawn TIMESTAMPTZ;@@ -32,7 +60,7 @@ export const FACT_WITHDRAWAL_SCHEMA_STATEMENTS = [SELECT min(withdrawn_at) INTO withdrawn FROM fact_withdrawalsWHERE source_id = NEW.source_id AND visibility = NEW.visibilityAND (subject = '*' OR subject = NEW.entity_slug)- AND fact_hash = gbrain_fact_fingerprint(NEW.fact);+ AND fact_hash IN (gbrain_fact_fingerprint(NEW.fact), gbrain_fact_fingerprint_v1(NEW.fact));IF withdrawn IS NOT NULL THENNEW.expired_at := withdrawn;NEW.valid_until := LEAST(COALESCE(NEW.valid_until, withdrawn), withdrawn);@@ -61,6 +89,27 @@ 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;+/**+ * Punctuation-folded fingerprints (migration v174). Existing rows keep their+ * exact (v1) hash and still match; a v2 row is added wherever a fact row still+ * carries the claim text, facts that became matching are expired like the+ * trigger would, and the fingerprint index keys claim lookups.+ */+export const FACT_WITHDRAWAL_NORMALIZED_SQL = FACT_WITHDRAWAL_SCHEMA_SQL + `+INSERT INTO fact_withdrawals(source_id, visibility, subject, fact_hash, withdrawn_at)+ SELECT DISTINCT w.source_id, w.visibility, w.subject, gbrain_fact_fingerprint(f.fact), w.withdrawn_at+ FROM fact_withdrawals w JOIN facts f ON f.source_id = w.source_id AND f.visibility = w.visibility+ AND gbrain_fact_fingerprint_v1(f.fact) = w.fact_hash+ ON CONFLICT DO NOTHING;+DROP INDEX IF EXISTS idx_facts_withdrawal_fingerprint;+CREATE INDEX idx_facts_withdrawal_fingerprint ON facts (source_id, visibility, gbrain_fact_fingerprint(fact));+UPDATE facts f SET expired_at = w.withdrawn_at, valid_until = LEAST(COALESCE(f.valid_until, w.withdrawn_at), w.withdrawn_at)+ FROM (SELECT source_id, visibility, subject, fact_hash, min(withdrawn_at) AS withdrawn_at FROM fact_withdrawals+ GROUP BY source_id, visibility, subject, fact_hash) w+ WHERE f.expired_at IS NULL AND f.source_id = w.source_id AND f.visibility = w.visibility+ AND (w.subject = '*' OR w.subject = f.entity_slug) AND gbrain_fact_fingerprint(f.fact) = w.fact_hash;+`;+/** 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 <> $3diff --git a/src/core/facts/withdrawal.ts b/src/core/facts/withdrawal.tsindex 1281168f2f..8af7d70059 100644--- a/src/core/facts/withdrawal.ts+++ b/src/core/facts/withdrawal.ts@@ -18,17 +18,18 @@ 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_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=$2+ const visible = await tx.executeRaw<{ visibility: 'private' | 'world'; fact: string; fact_hash: string; subject: string }>(+ `SELECT visibility,fact,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 { 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 { visibility, fact, fact_hash, subject } = visible[0];+ // Discovery is keyed on the claim and its subject: a subject-scoped+ // withdrawal changes only that entity's pages and its facts' provenance.+ // 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 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);+ WHERE source_id=$1 AND visibility=$2 AND fact_hash IN ($3,gbrain_fact_fingerprint_v1($5)) AND (subject='*' OR subject=$4) LIMIT 1`,+ [sourceId, visibility, fact_hash, subject, fact]);+ const affected = existing.length ? [] : await discoverWithdrawalTargets(tx, sourceId, [{ visibility, fact_hash, subject, claim: fact }]).catch(withdrawalDiscoveryFailure);await tx.lockPageKeys(affected.map(({ slug }) => ({ sourceId, slug })));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=$2@@ -65,7 +66,7 @@ async function ambiguousFenceMatchesWithdrawal(engine: BrainEngine, sourceId: stconst 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)+ JOIN fact_withdrawals w ON w.source_id=$1 AND w.fact_hash IN (gbrain_fact_fingerprint(incoming.claim),gbrain_fact_fingerprint_v1(incoming.claim))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]);@@ -78,7 +79,7 @@ async function withdrawalDates(engine: BrainEngine, sourceId: string, facts: rea`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)+ AND w.fact_hash IN (gbrain_fact_fingerprint(incoming.claim),gbrain_fact_fingerprint_v1(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],@@ -132,7 +133,7 @@ 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)+ WHERE source_id=$1 AND visibility=$2 AND fact_hash IN (gbrain_fact_fingerprint($3),gbrain_fact_fingerprint_v1($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 af81f0a87b..a290dafe7b 100644--- a/src/core/facts/write-single.ts+++ b/src/core/facts/write-single.ts@@ -253,9 +253,13 @@ export async function writeSingleFact(* `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.+ * written; a partial supersede is an audit gap, not data loss — but a+ * failure is logged with both ids, never swallowed.*/async function expireSuperseded(engine: BrainEngine, oldId: number, newId: number): Promise<void> {+ const report = (step: string, err: unknown) => console.warn(+ `[facts.supersede] FACTS_SUPERSEDE_BOOKKEEPING_FAILED: ${step} for fact ${oldId} -> ${newId}: ${err instanceof Error ? err.message : String(err)}`,+ );try {const { forgetFactInFence } = await import('./forget.ts');const [replacement] = await engine.executeRaw<{ row_num: number | null; same_page: boolean }>(@@ -263,13 +267,13 @@ async function expireSuperseded(engine: BrainEngine, oldId: number, newId: numbeFROM 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 */+ } catch (err) {+ report('fence strike', err);}try {await engine.executeRaw(`UPDATE facts SET superseded_by = $1 WHERE id = $2`, [newId, oldId]);- } catch {- /* best-effort */+ } catch (err) {+ report('superseded_by link', err);}}diff --git a/src/core/git-first-commit.ts b/src/core/git-first-commit.tsnew file mode 100644index 0000000000..9402d20460--- /dev/null+++ b/src/core/git-first-commit.ts@@ -0,0 +1,40 @@+/**+ * Git first-commit dates as the creation anchor for undated files (A12).+ *+ * A fresh clone stamps every file with the clone time, so an undated note in+ * a ten-year-old vault got today's date as its effective-date fallback. One+ * `git log --diff-filter=A` pass per import run maps each path to the date its+ * oldest adding commit was authored. Opt-in (`sync.git_first_commit_dates`)+ * because effective_date feeds recency-intent ranking and since/until+ * filters. Shallow clones and git failures return null: the file timestamps+ * stay the fallback.+ */++import { execFileSync } from 'child_process';+import { realpathSync } from 'fs';+import { relative } from 'path';++export interface GitFirstCommitDates {+ /** The first-commit date for a file under the repo, if git recorded one. */+ get(filePath: string): Date | undefined;+}++export function gitFirstCommitDates(dir: string): GitFirstCommitDates | null {+ try {+ const git = (args: string[], cwd: string) => execFileSync('git', ['-C', cwd, ...args],+ { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], maxBuffer: 256 * 1024 * 1024, timeout: 120_000 });+ const top = git(['rev-parse', '--show-toplevel'], dir).trim();+ if (git(['rev-parse', '--is-shallow-repository'], top).trim() === 'true') return null;+ const dates = new Map<string, Date>();+ // Newest first, so the oldest adding commit is written last and wins.+ for (const entry of git(['-c', 'core.quotePath=false', 'log', '--diff-filter=A', '--no-renames', '--format=%x00%at', '--name-only'], top).split('\0')) {+ const [stamp, ...paths] = entry.split('\n');+ const at = new Date(Number(stamp) * 1000);+ if (!Number.isFinite(at.getTime())) continue;+ for (const path of paths) if (path) dates.set(path, at);+ }+ return { get: filePath => { try { return dates.get(relative(top, realpathSync(filePath)).replace(/\\/g, '/')); } catch { return undefined; } } };+ } catch {+ return null;+ }+}diff --git a/src/core/import-file.ts b/src/core/import-file.tsindex 0cffb138cb..fc63015c00 100644--- a/src/core/import-file.ts+++ b/src/core/import-file.ts@@ -1,7 +1,7 @@import { assertUnmanagedCanonicalWriter } from './persistence/maintenance.ts';import { assertImportBase, sameCanonicalImport } from './page-state/import-guard.ts';import { stabilizeSafetyAssessments } from './persistence/reconcile-safety.ts';-import { decideImportIdentity, collidingSlugOwner } from './import-identity.ts';+import { decideImportIdentity, collidingSlugOwner, fileOriginUri } from './import-identity.ts';import { readSourceFileSync } from './minions/source-filesystem.ts';import { readFileSync, statSync, lstatSync } from 'fs';import { basename, extname, resolve } from 'path';@@ -14,7 +14,8 @@ import { prepareCodeChunks, installCodeChunkEdges } from './code-chunks.ts';import { detectCodeLanguage, CHUNKER_VERSION } from './chunkers/code.ts';import { sanitizeRemoteBody } from './remote-body.ts';import { installPageEmbeddings, installPageProjection, preparePageProjection, projectionBelowSafeFence, queuePageProjection, readProjectionSnapshot, resealSafeChunks,- sealPageTextProjection, stampEmbeddingInputs, type ProjectionSnapshot } from './page-state/projections.ts';+ sealPageTextProjection, stampEmbeddingInputs, embeddingWriteTarget, embeddingInputContext, type ProjectionSnapshot } from './page-state/projections.ts';+import { embeddingInputHash } from './embedding-input-hash.ts';import { sanitizeText } from './batch-rows.ts';import { hasProtectedBody, safeChunksFilter } from './search/safe-chunks.ts';import { findChunkForOffset } from './chunkers/edge-extractor.ts';@@ -27,8 +28,8 @@ import { embedMultimodal, currentEmbeddingSignature } from './embedding.ts';// precedent as embed-stale.ts.import { embedBatchWithBackoff } from './embed-retry.ts';import { slugifyPath, slugifyCodePath, isCodeFilePath, hasMalformedPathSegment } from './sync.ts';-import type { ChunkInput, PageInput, PageType } from './types.ts';-import { computeEffectiveDate, fallbackCreatedAt } from './effective-date.ts';+import type { ChunkInput, Page, PageInput, PageType } from './types.ts';+import { computeEffectiveDate, fallbackCreatedAt, isValidTimeZone } from './effective-date.ts';import { MARKDOWN_CHUNKER_VERSION } from './chunkers/recursive.ts';import { logSlugFallback } from './audit-slug-fallback.ts';import { resolveContextualRetrievalMode } from './contextual-retrieval-resolver.ts';@@ -185,16 +186,19 @@ function invalidYamlFrontmatterError(parsed: ReturnType<typeof parseMarkdown>):* zero-row UPDATEs, each firing the generation-clock trigger); undefined* (projection-less engine) falls through and `IS DISTINCT FROM` keeps the* UPDATE zero-row. brainstorm passes `${slug}.md`, the value putPage writes on- * its own path. Bookkeeping only — never fails the import.+ * its own path. It also records the file origin move inference binds to+ * (#5675). Bookkeeping only — never fails the import.*/-async function refreshSourcePath(engine: BrainEngine, slug: string, sourceId: string | undefined, sourcePath: string | undefined, current: string | null | undefined): Promise<void> {- if (!sourcePath || current === sourcePath) return;+async function refreshSourcePath(engine: BrainEngine, slug: string, sourceId: string | undefined, sourcePath: string | undefined,+ current: Pick<Page, 'source_path' | 'source_uri'> | null, originUri: string | null): Promise<void> {+ if (!sourcePath || (current?.source_path === sourcePath && (originUri === null || current.source_uri === originUri))) return;try {// Keep this optional legacy repair inside a savepoint: a rejected SQL// statement must not poison the surrounding canonical transaction.await engine.transaction(tx => tx.executeRaw(- 'UPDATE pages SET source_path = $1 WHERE source_id = $2 AND slug = $3 AND deleted_at IS NULL AND source_path IS DISTINCT FROM $1',- [sourcePath, sourceId ?? 'default', slug],+ `UPDATE pages SET source_path = $1, source_uri = COALESCE($4::text, source_uri) WHERE source_id = $2 AND slug = $3+ AND deleted_at IS NULL AND (source_path IS DISTINCT FROM $1 OR source_uri IS DISTINCT FROM COALESCE($4::text, source_uri))`,+ [sourcePath, sourceId ?? 'default', slug, originUri],));} catch { /* bookkeeping only — never fail the import over it */ }}@@ -244,7 +248,7 @@ export async function importFromContent(*/sourceRoot?: string;/** The source file's timestamps: the date of a new page that carries no date of its own. */- fileTimes?: { birthtime?: Date; mtime?: Date };+ fileTimes?: { birthtime?: Date; mtime?: Date; firstCommit?: Date };/*** v0.32.7 CJK wave (codex post-merge F1): bypass the* `existing.content_hash === hash` short-circuit and ALWAYS re-chunk +@@ -675,11 +679,12 @@ export async function importFromContent(tags: parsed.tags,};+ const originUri = fileOriginUri(existing?.source_uri, opts.sourceRoot, opts.sourcePath);const persistUnchanged = async (refreshBody = false) => {await engine.transaction(async tx => {await assertImportBase(tx, slug, sourceId ?? 'default', existing);if (refreshBody) await tx.refreshPageBody(slug, sourceId ?? 'default', parsed.compiled_truth, parsed.timeline || '', hash);- await refreshSourcePath(tx, slug, sourceId, opts.sourcePath, existing?.source_path);+ await refreshSourcePath(tx, slug, sourceId, opts.sourcePath, existing, originUri);if (opts.beforeCommit) await verifyPageReadable(tx, slug, hash, sourceId, 'importFromContent');await opts.beforeCommit?.(tx, slug);});@@ -831,22 +836,68 @@ export async function importFromContent(effectiveCRMode = resolution.mode === 'per_chunk_synopsis' ? 'title' : resolution.mode;}+ // v0.40.3.0: corpus_generation hash for D27 P1-5 cache invalidation.+ // Record the selected wrapper generation for inline or deferred embedding;+ // 'none' writes NULL. The separate embedding signature certifies vectors.+ const corpusGeneration =+ effectiveCRMode === 'none' || !prepareEmbeddingContext+ ? null+ : computeCorpusGeneration({+ crMode: effectiveCRMode,+ synopsisModel: DEFAULT_SYNOPSIS_MODEL,+ // Inline import-file path never uses per_chunk_synopsis (refuses+ // upstream); pass undefined so the doc-cap field stays out of+ // the hash here. Per_chunk_synopsis runs through the Minion+ // backfill handler which threads SYNOPSIS_DOC_MAX_CHARS through+ // the service layer.+ });++ // A13: an edit re-embeds only chunks whose embedding input changed. A stored+ // vector is reused for a chunk with the same source and text when its+ // recorded embedding input (#5553: column, model, dimensions, wrapper tier+ // and exact input) equals the one this import would embed, or, for a vector+ // recorded before provenance existed, when the input is the raw chunk text+ // under the same model. The old index must be sealed and neither body may+ // hold protected fences, so no reused vector can carry a private sibling.+ const reused = new Set<number>();+ if (existing && !existing.deleted_at && !opts.noEmbed && !opts.forceRechunk && !opts.prepare && !opts.onPostCommitEmbedding && chunks.length > 0+ && !hasProtectedBody(`${existing.compiled_truth}\n${existing.timeline ?? ''}`) && !hasProtectedBody(`${parsed.compiled_truth}\n${parsed.timeline ?? ''}`)) {+ const target = await embeddingWriteTarget(engine);+ const provenance = embeddingInputContext(target, parsed.title, corpusGeneration, chunks);+ const tier = effectiveCRMode === 'title' ? 'title' : 'none';+ const recorded = new Map((await engine.executeRaw<{ chunk_index: number; embedding_input_hash: string | null }>(+ `SELECT c.chunk_index, c.embedding_input_hash FROM content_chunks c JOIN pages p ON p.id = c.page_id+ WHERE p.source_id = $1 AND p.slug = $2`, [sourceId ?? 'default', slug])).map(row => [Number(row.chunk_index), row.embedding_input_hash]));+ // Reuse is keyed on chunk source + text, so a stored chunk's current-input+ // hash is the hash its matching new chunk would record.+ const stored = (await engine.getChunks(slug, { sourceId: sourceId ?? 'default', includeEmbedding: true, requireSafeChunks: true }))+ .filter(chunk => {+ const hash = recorded.get(chunk.chunk_index);+ return hash == null ? tier === 'none' && chunk.model === target.provenanceModel : hash === embeddingInputHash(provenance, tier, chunk);+ });+ for (const [i, matched] of planEmbeddingReuse(stored, chunks, c => `${c.chunk_source}\0${c.chunk_text}`).reuse) {+ chunks[i].embedding = matched.embedding as Float32Array;+ chunks[i].token_count = matched.token_count ?? undefined;+ if (matched.model) chunks[i].model = matched.model;+ reused.add(i);+ }+ }+const embedChunks = async () => {- if (opts.noEmbed || chunks.length === 0) return;+ const pending = chunks.map((_, i) => i).filter(i => !reused.has(i));+ if (opts.noEmbed || pending.length === 0) return;const prefix =modeRequiresWrapper(effectiveCRMode) && !modeRequiresSynopsis(effectiveCRMode)? buildContextualPrefix(parsed.title, null): null;- const wrappedTexts = prefix- ? chunks.map((c) => wrapChunkForEmbedding(c.chunk_text, prefix, c.chunk_source))- : chunks.map((c) => c.chunk_text);+ const wrappedTexts = pending.map(i => prefix ? wrapChunkForEmbedding(chunks[i].chunk_text, prefix, chunks[i].chunk_source) : chunks[i].chunk_text);const embeddings = await embedBatchWithBackoff(wrappedTexts);- for (let i = 0; i < chunks.length; i++) {- chunks[i].embedding = embeddings[i];+ pending.forEach((i, j) => {+ chunks[i].embedding = embeddings[j];// token_count tracks the wrapped string length so cost reporting// reflects what we actually sent to the embedder.- chunks[i].token_count = Math.ceil(wrappedTexts[i].length / 4);- }+ chunks[i].token_count = Math.ceil(wrappedTexts[j].length / 4);+ });};// An embedding outage never blocks the text write: the page and its chunks// commit with NULL vectors and no embedding signature, and the stale sweep@@ -858,7 +909,7 @@ export async function importFromContent(await embedChunks();} catch (err) {embeddingDeferred = true;- for (const c of chunks) { c.embedding = undefined; c.token_count = undefined; }+ chunks.forEach((c, i) => { if (!reused.has(i)) { c.embedding = undefined; c.token_count = undefined; } });process.stderr.write(`[import] ${slug}: embedding failed (${err instanceof Error ? err.message : String(err)}); ` +`text saved, chunks queued for \`gbrain embed --stale\`.\n`@@ -866,28 +917,13 @@ export async function importFromContent(}}- // v0.40.3.0: corpus_generation hash for D27 P1-5 cache invalidation.- // Record the selected wrapper generation for inline or deferred embedding;- // 'none' writes NULL. The separate embedding signature certifies vectors.- const corpusGeneration =- effectiveCRMode === 'none' || !prepareEmbeddingContext- ? null- : computeCorpusGeneration({- crMode: effectiveCRMode,- synopsisModel: DEFAULT_SYNOPSIS_MODEL,- // Inline import-file path never uses per_chunk_synopsis (refuses- // upstream); pass undefined so the doc-cap field stays out of- // the hash here. Per_chunk_synopsis runs through the Minion- // backfill handler which threads SYNOPSIS_DOC_MAX_CHARS through- // the service layer.- });-// Transaction wraps the canonical DB writes. Every per-page tx call carries the// caller's sourceId so writes target (sourceId, slug) rather than the// schema DEFAULT — required for multi-source brains; harmless ('default')// for single-source callers.const txOpts = { sourceId: sourceId ?? 'default' };let persistedProjection: ProjectionSnapshot | null = null;+ const timeZone = await loadBrainTimeZone(engine);const applyPrepared = async (tx: BrainEngine) => {await assertImportBase(tx, slug, txOpts.sourceId, existing);await assertPreparedFactWithdrawals(tx, txOpts.sourceId, parsed.compiled_truth, parsed.timeline || '', slug);@@ -906,6 +942,7 @@ export async function importFromContent(slug,frontmatter: parsed.frontmatter,filename: filenameForChain,+ timeZone,updatedAt: existing?.updated_at ?? nowDate,createdAt: fallbackCreatedAt({ existing, fileTimes: opts.fileTimes, now: nowDate }),});@@ -926,7 +963,7 @@ export async function importFromContent(// COALESCE-preserve UPDATE so omitting these on a later put_page// doesn't erase the original ingestion's audit trail.source_kind: opts.source_kind ?? null,- source_uri: opts.source_uri ?? null,+ source_uri: opts.source_uri ?? originUri,ingested_via: opts.ingested_via ?? null,// ingested_at is server-stamped at the engine layer when any// provenance write fires; never client-controlled.@@ -949,32 +986,23 @@ export async function importFromContent();}- // Tag reconciliation: ADD-ONLY (v0.41.37.0 #1621).- //- // We deliberately do NOT delete existing tags here. The `tags` table has- // no provenance column, and frontmatter tags are stripped from the stored- // `pages.frontmatter` (markdown.ts:118) — so at re-import time we cannot- // distinguish a frontmatter-origin tag from a DB-side enrichment tag- // (auto-tag / dream synthesize / signal-detector writes to the same- // table). The pre-v0.41.37.0 "delete every existing tag not in the current- // frontmatter" logic wiped ALL enrichment tags on every re-import — most- // visibly under `gbrain reindex --markdown` (#1621), which re-imports every- // page with forceRechunk. reindex is a re-chunk/re-embed op; it must not- // destroy tags.- //- // Trade-off (accepted): removing a tag from a page's frontmatter no longer- // removes it from the DB on the next sync. That staleness is minor (tags- // are additive metadata) and far preferable to silently losing enrichment- // tags. Frontmatter-tag REMOVAL would require a `tag_source` provenance- // column (deferred — see TODOS.md #1621-followup). addTag is idempotent- // (ON CONFLICT DO NOTHING), so re-adding existing tags is a no-op.+ // Tag reconciliation (A14): frontmatter tags carry tag_source='frontmatter'.+ // A frontmatter-owned row whose tag left the frontmatter is deleted; rows+ // explicit adds own ('added': add_tag, enrichment, the code importer) and+ // legacy NULL rows are never deleted here (#1621: reindex must not wipe+ // enrichment). A legacy row still in the frontmatter is adopted. Prepared+ // (managed) imports keep the add-only union their canonical file renders.+ if (!opts.prepare) {+ await tx.executeRaw(`DELETE FROM tags t USING pages p WHERE p.id = t.page_id AND p.source_id = $1 AND p.slug = $2+ AND t.tag_source = 'frontmatter' AND NOT (t.tag = ANY($3::text[]))`, [txOpts.sourceId, slug, parsed.tags]);+ }for (const tag of parsed.tags) {- await tx.addTag(slug, tag, txOpts);+ await tx.addTag(slug, tag, opts.prepare ? txOpts : { ...txOpts, tagSource: 'frontmatter' });}- // A new seal cannot inherit vectors or metadata from an older index, even- // when a public fragment is unchanged: its old contextual vector may have- // included a private sibling fragment. Replace every derived row atomically.+ // Replace every derived row atomically. Only vectors the A13 reuse gate+ // above admitted carry over; a new seal otherwise inherits nothing from an+ // older index, whose contextual vector may have included a private sibling.await tx.deleteChunks(slug, txOpts);if (chunks.length > 0) {const embeddingColumn = await stampEmbeddingInputs(tx, chunks, null,@@ -1185,6 +1213,8 @@ export async function importFromFile(* never per file (codex perf finding #7).*/activePack?: { page_types: ReadonlyArray<{ name: string; path_prefixes: ReadonlyArray<string>; aliases?: ReadonlyArray<string> }> };+ /** Git first-commit date of the file (opt-in, see git-first-commit.ts); an undated page's fallback anchor. */+ firstCommitAt?: Date;} = {},): Promise<ImportResult> {// Defense-in-depth: reject symlinks before reading content.@@ -1351,7 +1381,7 @@ export async function importFromFile(sourcePath: relativePath,// nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- walks up from the caller's own file path by the depth of its own relative path to recover the import root; import-identity confines every probe under that rootsourceRoot: resolve(filePath, ...relativePath.split(/[\\/]/).map(() => '..')),- fileTimes: { birthtime: stat.birthtime, mtime: stat.mtime },+ fileTimes: { birthtime: stat.birthtime, mtime: stat.mtime, firstCommit: opts.firstCommitAt },// The disk file IS the source of truth: a file the user emptied is a// deliberate clear, so it passes putPage's empty-overwrite guard.allowEmptyOverwrite: true,@@ -2234,6 +2264,16 @@ export async function importImageFile(return { slug: imageSlug, status: 'imported', chunks: 1 };}+let warnedBrainTimeZone = false;+/** `brain.timezone` (IANA) for offset-less frontmatter datetimes; unset or invalid reads them as UTC. */+async function loadBrainTimeZone(engine: BrainEngine): Promise<string | undefined> {+ const configured = (await engine.getConfig('brain.timezone').catch(() => null))?.trim();+ if (!configured || isValidTimeZone(configured)) return configured || undefined;+ if (!warnedBrainTimeZone) process.stderr.write(`[import] invalid brain.timezone "${configured}"; reading naive datetimes as UTC\n`);+ warnedBrainTimeZone = true;+ return undefined;+}+/** Used by sync.isSyncable + import.ts walker. */export function isImageFilePath(relativePath: string): boolean {const ext = extname(relativePath).toLowerCase();diff --git a/src/core/import-identity.ts b/src/core/import-identity.tsindex 2cec593d54..56163eb02f 100644--- a/src/core/import-identity.ts+++ b/src/core/import-identity.ts@@ -4,7 +4,7 @@*/import { existsSync, realpathSync } from 'fs';-import { resolve, sep } from 'path';+import { basename, resolve, sep } from 'path';import type { BrainEngine } from './engine.ts';import type { Page } from './types.ts';import { slugifyPath } from './sync.ts';@@ -32,8 +32,8 @@ export type ImportIdentityDecision =* Identity-based cross-slug dedup (#1309, overlapping ingest roots): find* another page with this content_hash or external frontmatter.id.*- * - move: the id matches and that page's recorded source file is gone under- * this import's root. The importer renames the row in place (page id,+ * - move: the id matches and the other page's own origin proves it moved+ * (see hasMoveEvidence). The importer renames the row in place (page id,* links, facts and timeline survive) and imports the new content onto it,* so a full sync's delete-reconcile has nothing live to remove.* - duplicate: the id matches and so does the content (hash, or title and@@ -62,16 +62,82 @@ export async function decideImportIdentity(engine: BrainEngine, input: ImportIdeconst dupFmId = (dupPage?.frontmatter as Record<string, unknown> | undefined)?.id;const sameExternalId = input.frontmatterId !== null && dupFmId === input.frontmatterId;if (!sameExternalId) return { kind: 'shared_hash', dupSlug: dup.slug };+ const sameContent = dupPage?.content_hash === input.hash || (!!dupPage && dupPage.title === input.body.title+ && dupPage.compiled_truth === input.body.compiled_truth && (dupPage.timeline ?? '') === input.body.timeline);const dupSourcePath = dupPage?.source_path ?? null;- const dupFile = input.sourceRoot !== undefined && dupSourcePath !== null ? pathUnderRoot(input.sourceRoot, dupSourcePath) : null;- if (dupFile !== null && dupSourcePath !== null && input.sourcePath !== undefined && dupSourcePath !== input.sourcePath && !existsSync(dupFile)) {+ if (dupPage && dupSourcePath !== null && input.sourceRoot !== undefined && input.sourcePath !== undefined && dupSourcePath !== input.sourcePath+ && await hasMoveEvidence(engine, input.sourceId, dupPage, dupSourcePath, input.sourceRoot, input.sourcePath, sameContent, input.body.title)) {return { kind: 'move', dupSlug: dup.slug, dupSourcePath };}- const sameContent = dupPage?.content_hash === input.hash || (!!dupPage && dupPage.title === input.body.title- && dupPage.compiled_truth === input.body.compiled_truth && (dupPage.timeline ?? '') === input.body.timeline);return sameContent ? { kind: 'duplicate', dupSlug: dup.slug } : { kind: 'shared_id', dupSlug: dup.slug };}+/**+ * Move evidence is bound to the filesystem root the other page was imported+ * from (#5675), never to this import's root: a path that is missing under a+ * different root proves nothing.+ *+ * - Its origin still exists: a move only when it is this very file, reached+ * through another relative path (overlapping import roots converge).+ * - Its origin is gone: this file must live under that same root. Differing+ * content also needs continuity (the same file name or the same title), so+ * a new note that reuses a deleted note's template id stays its own page.+ */+async function hasMoveEvidence(engine: BrainEngine, sourceId: string, dup: Page, dupSourcePath: string,+ sourceRoot: string, sourcePath: string, sameContent: boolean, title: string): Promise<boolean> {+ const origin = await recordedOrigin(engine, sourceId, dup, dupSourcePath);+ const incoming = pathUnderRoot(sourceRoot, sourcePath);+ if (!origin || !incoming) return false;+ if (existsSync(origin.file)) return canonicalPath(origin.file) === canonicalPath(incoming);+ if (canonicalPath(origin.root) !== canonicalPath(sourceRoot)) return false;+ return sameContent || basename(dupSourcePath) === basename(sourcePath) || dup.title === title;+}++/**+ * The root and file a page was imported from: the `file://` origin+ * importFromFile records in `source_uri`, else the source's configured root+ * (`local_path`, or the legacy `sync.repo_path` anchor of the default source).+ * Null when neither is known.+ */+async function recordedOrigin(engine: BrainEngine, sourceId: string, page: Page, sourcePath: string): Promise<{ root: string; file: string } | null> {+ if (page.source_uri?.startsWith(FILE_URI)) {+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- normalizes the file:// origin importFromFile recorded; it is only compared with other paths and accepted when rejoining the relative path under the derived root lands on it+ const file = resolve(page.source_uri.slice(FILE_URI.length));+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- walks up from the recorded origin by the depth of its own relative path; the result is only accepted when rejoining the relative path lands on the same file+ const root = resolve(file, ...sourcePath.split(/[\\/]/).map(() => '..'));+ if (pathUnderRoot(root, sourcePath) === file) return { root, file };+ }+ const [source] = await engine.executeRaw<{ local_path: string | null }>('SELECT local_path FROM sources WHERE id = $1', [sourceId]);+ const configured = source?.local_path || (sourceId === 'default' ? await engine.getConfig('sync.repo_path') : null);+ if (!configured) return null;+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- the operator's configured source root (sources.local_path or sync.repo_path); every probe under it goes through pathUnderRoot confinement+ const root = resolve(configured);+ const file = pathUnderRoot(root, sourcePath);+ return file ? { root, file } : null;+}++const FILE_URI = 'file://';++/**+ * The `source_uri` recording where a file import came from, so a later import+ * can bind move inference to it. Non-file provenance (a capture URI, a message+ * id) is never replaced.+ */+export function fileOriginUri(existingUri: string | null | undefined, sourceRoot: string | undefined, sourcePath: string | undefined): string | null {+ if (sourceRoot === undefined || sourcePath === undefined || (existingUri && !existingUri.startsWith(FILE_URI))) return null;+ const file = pathUnderRoot(sourceRoot, sourcePath);+ return file ? FILE_URI + file : null;+}++function canonicalPath(path: string): string {+ try {+ return realpathSync.native(path);+ } catch {+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- normalizes an already-derived path for equality comparison only; nothing is read or written through it+ return resolve(path);+ }+}+/*** The live file that already owns `slug`, when it is not the file being* imported. Two files that slugify to one slug (`notes/Foo Bar.md`,diff --git a/src/core/link-reconciliation.ts b/src/core/link-reconciliation.tsindex 9990431d04..4f67278ec2 100644--- a/src/core/link-reconciliation.ts+++ b/src/core/link-reconciliation.ts@@ -184,8 +184,18 @@ export async function replacePageFileLinks(engine: BrainEngine, slug: string, soreturn result.created;}-export async function fileLinkOwnership(engine: BrainEngine, sourceId: string) {- const pages = await loadLinkPageMetadata(engine);+/**+ * Page metadata, resolver and attendance origins for replacing file links.+ * With `slugs`, only those pages of the source are loaded (a sync hook passes+ * its changed pages plus their link endpoints) — enough for+ * `replacePageFileLinks`; the resolver then only knows those pages, so+ * attendance reconciliation (`replaceFileLinks`) needs the unscoped form.+ */+export async function fileLinkOwnership(engine: BrainEngine, sourceId: string, scope?: { slugs: readonly string[] }) {+ const pages = scope+ ? await engine.executeRaw<LinkPageMetadata>(`SELECT slug, source_id, type, title, frontmatter->'aliases' AS aliases, knowledge_revision+ FROM pages WHERE deleted_at IS NULL AND source_id = $1 AND slug = ANY($2::text[]) ORDER BY slug`, [sourceId, [...scope.slugs]])+ : await loadLinkPageMetadata(engine);const metadata = new Map(pages.map(row => [`${row.source_id}\0${row.slug}`, row]));const resolver = makeIndexedLinkResolver(pages, sourceId);const { allSlugs, slugToSources } = indexLinkSources(pages);@@ -194,7 +204,8 @@ export async function fileLinkOwnership(engine: BrainEngine, sourceId: string) {allSlugs, slugToSources, policy.allowCrossSource, policy);const origins = await engine.executeRaw<{ slug: string }>(`SELECT DISTINCT o.slug FROM links lJOIN pages o ON o.id=l.origin_page_id WHERE o.source_id=$1 AND l.link_source IN ('markdown','wikilink-resolved','frontmatter')- AND l.link_type='attended' AND l.to_page_id=l.origin_page_id`, [sourceId]);+ AND l.link_type='attended' AND l.to_page_id=l.origin_page_id${scope ? ' AND o.slug = ANY($2::text[])' : ''}`,+ scope ? [sourceId, [...scope.slugs]] : [sourceId]);return { metadata, resolver, resolve, origins: new Set(origins.map(row => row.slug)) };}diff --git a/src/core/mcp-client.ts b/src/core/mcp-client.tsindex 91bb148e50..ae2b406d34 100644--- a/src/core/mcp-client.ts+++ b/src/core/mcp-client.ts@@ -21,6 +21,7 @@ import { randomUUID } from 'node:crypto';import { isPersistenceIpcMutation } from './persistence/ipc.ts';import { Client } from '@modelcontextprotocol/sdk/client/index.js';import { StreamableHTTPClientTransport, StreamableHTTPError } from '@modelcontextprotocol/sdk/client/streamableHttp.js';+import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';import { anySignal } from './abort-check.ts';import type { GBrainConfig } from './config.ts';import { discoverOAuth, mintClientCredentialsToken } from './remote-mcp-probe.ts';@@ -139,6 +140,11 @@ export function toRemoteMcpError(e: unknown, mcpUrl: string, signal?: AbortSigna);}if (e instanceof RemoteMcpError) return e;+ // The SDK's own request timer can fire while our composed signal is still+ // live. A slow operation on a reachable server is a timeout, not unreachable.+ if (e instanceof McpError && e.code === ErrorCode.RequestTimeout) {+ return new RemoteMcpError('network', `Request to ${mcpUrl} timed out`, { mcp_url: mcpUrl, kind: 'timeout' });+ }if (e instanceof Error) {if (e.name === 'AbortError' || e.name === 'TimeoutError') {return new RemoteMcpError(@@ -311,7 +317,8 @@ async function buildClient(mcpUrl: string, accessToken: string, signal?: AbortSi/*** Options for `callRemoteTool`. When absent, discovery/token requests retain- * their own caps and MCP requests inherit the SDK's timeout.+ * their own caps and MCP requests inherit the SDK's timeout. A `timeoutMs`+ * also becomes the SDK request deadline (see buildMcpRequestOptions).*/export interface CallRemoteToolOptions {/** Hard wall-clock cap for the whole call (token mint + tool call). Aborts on expiry. */@@ -320,6 +327,17 @@ export interface CallRemoteToolOptions {signal?: AbortSignal;}+/**+ * The SDK request options for one tool call. Passing only `signal` leaves the+ * SDK's independent 60s default deadline in force, so a caller's longer+ * timeout would still die at 60s; forward it.+ *+ * @internal Exported for test access (test/mcp-client-hardening.test.ts).+ */+export function buildMcpRequestOptions(opts: CallRemoteToolOptions, signal: AbortSignal): { signal: AbortSignal; timeout?: number } {+ return { signal, ...(opts.timeoutMs !== undefined && opts.timeoutMs > 0 ? { timeout: opts.timeoutMs } : {}) };+}+/*** Compose an external signal with a timeout into a single AbortController.* Returns the controller (so callers can pass `controller.signal` to@@ -393,7 +411,7 @@ export async function callRemoteTool(try {signal.throwIfAborted();submitted = true;- const res = await client.callTool({ name: toolName, arguments: args }, undefined, { signal });+ const res = await client.callTool({ name: toolName, arguments: args }, undefined, buildMcpRequestOptions(opts, signal));if (res.isError) {const message = Array.isArray(res.content)? res.content.map((c: unknown) => (c as { text?: string }).text ?? '').join('\n')diff --git a/src/core/migrate.ts b/src/core/migrate.tsindex 2f0086d6f3..9a8f995d62 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, FACT_WITHDRAWAL_SUBJECT_SQL } from './facts/withdrawal-schema.ts';+import { FACT_WITHDRAWAL_SCHEMA_SQL, FACT_WITHDRAWAL_BACKFILL_SQL, FACT_WITHDRAWAL_SUBJECT_SQL, FACT_WITHDRAWAL_NORMALIZED_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';@@ -6758,6 +6758,25 @@ CREATE TRIGGER minion_queue_protocol BEFORE INSERT OR UPDATE ON minion_jobsON minion_jobs (finished_at) WHERE name = 'subagent' AND status = 'dead'`);},},+ {+ // Exact-text fingerprints let a punctuation or casing variant of a+ // forgotten claim come back on re-extraction (write-path audit B-9).+ // Fingerprints now fold punctuation; legacy exact rows keep matching.+ version: 174,+ name: 'fact_withdrawal_normalized_fingerprint',+ idempotent: true,+ sql: FACT_WITHDRAWAL_NORMALIZED_SQL,+ },+ {+ // Frontmatter tags were add-only because a tag row carried no provenance:+ // removing a tag from frontmatter never removed it. The importer stamps+ // 'frontmatter' and deletes only those rows; explicit adds stamp 'added'+ // and legacy rows stay NULL — neither is ever deleted by an import.+ version: 175,+ name: 'tags_tag_source',+ idempotent: true,+ sql: `ALTER TABLE tags ADD COLUMN IF NOT EXISTS tag_source TEXT;`,+ },];export const LATEST_VERSION = MIGRATIONS.length > 0diff --git a/src/core/ops/search.ts b/src/core/ops/search.tsindex 54311cb11a..1371ebe828 100644--- a/src/core/ops/search.ts+++ b/src/core/ops/search.ts@@ -9,7 +9,7 @@ import { readHolders } from './context.ts';import { hybridSearchCached, stampContentFlags, stampUnverifiedExtractions } from '../search/hybrid.ts';import { resolveSearchDateBounds } from '../search/date-bounds.ts';-import { loadSearchModeConfig, resolveSearchMode } from '../search/mode.ts';+import { loadSearchModeConfig, resolveSearchMode, SOURCE_BOOSTS_KEY } from '../search/mode.ts';import { looksConceptShaped, classifyQueryShape } from '../search/query-intent.ts';import {gradeRetrievalConfidence,@@ -29,7 +29,7 @@ import { resolveExcludePrivatePages } from '../search/private-visibility.ts';import { SAFE_FENCE_CHUNKER_VERSION } from '../search/safe-chunks.ts';import { expandEngineTypeFilters } from '../schema-pack/query-types.ts';import { probeProjectionReadiness } from '../search/projection-readiness.ts';-import { resolveHardExcludes } from '../search/source-boost.ts';+import { resolveBoostMap, resolveHardExcludes } from '../search/source-boost.ts';import { pageReadFilter } from '../search/read-policy-sql.ts';import { QUERY_DESCRIPTION, SEARCH_DESCRIPTION } from '../operations-descriptions.ts';import { OperationError } from './contract.ts';@@ -310,7 +310,8 @@ const search: Operation = {types = (await expandEngineTypeFilters(ctx.engine, { types, ...scope })).types;if (types?.length === 0) return [];}- const raw = await ctx.engine.searchKeyword(queryText, { limit, offset, excludePrivate, requireSafeChunks: ctx.remote !== false, ...(types ? { types } : {}), ...scope });+ const sourceBoosts = resolveBoostMap(undefined, await ctx.engine.getConfig(SOURCE_BOOSTS_KEY));+ const raw = await ctx.engine.searchKeyword(queryText, { limit, offset, excludePrivate, requireSafeChunks: ctx.remote !== false, source_boosts: sourceBoosts, ...(types ? { types } : {}), ...scope });const results = dedupResults(raw).map(r => ({ ...r }));// #3783 — every row here IS a keyword hit (direct FTS path); mark// before stamping so evidence still reads keyword_exact.diff --git a/src/core/page-state/rename-alias.ts b/src/core/page-state/rename-alias.tsindex 425ad1e60e..826ad05f90 100644--- a/src/core/page-state/rename-alias.ts+++ b/src/core/page-state/rename-alias.ts@@ -1,5 +1,6 @@import type { BrainEngine } from '../engine.ts';import { isUndefinedTableError } from '../utils.ts';+import { MOVE_WITHDRAWAL_SUBJECT_SQL } from '../facts/withdrawal-schema.ts';/*** Record `old -> new` in slug_aliases when a page is renamed, inside the@@ -30,3 +31,39 @@ export async function recordRenameAlias(if (!isUndefinedTableError(error)) throw error;}}++/**+ * Move the slug-keyed rows that belong to a renamed page (#5431): facts about+ * it (`entity_slug`), facts read from its `## Facts` fence+ * (`source_markdown_slug`), its free-text search aliases (`page_aliases`), and+ * its fact withdrawals (a forgotten claim stays forgotten). Runs inside the+ * caller's rename transaction. The new slug is free (the page UPDATE+ * succeeded), so fence rows or aliases still keyed to it belong to a purged+ * page and yield to the moved ones. A brain whose schema predates the facts or+ * alias tables skips them inside a savepoint.+ */+export async function moveSlugBindings(+ tx: Pick<BrainEngine, 'transaction' | 'executeRaw'>,+ sourceId: string,+ oldSlug: string,+ newSlug: string,+): Promise<void> {+ if (oldSlug === newSlug) return;+ await tx.executeRaw(MOVE_WITHDRAWAL_SUBJECT_SQL, [sourceId, oldSlug, newSlug]);+ const statements = [+ `UPDATE facts SET entity_slug = $3 WHERE source_id = $1 AND entity_slug = $2`,+ `DELETE FROM facts f WHERE f.source_id = $1 AND f.source_markdown_slug = $3 AND f.row_num IS NOT NULL+ AND EXISTS (SELECT 1 FROM facts o WHERE o.source_id = $1 AND o.source_markdown_slug = $2 AND o.row_num = f.row_num)`,+ `UPDATE facts SET source_markdown_slug = $3 WHERE source_id = $1 AND source_markdown_slug = $2`,+ `DELETE FROM page_aliases a WHERE a.source_id = $1 AND a.slug = $3+ AND EXISTS (SELECT 1 FROM page_aliases o WHERE o.source_id = $1 AND o.slug = $2 AND o.alias_norm = a.alias_norm)`,+ `UPDATE page_aliases SET slug = $3 WHERE source_id = $1 AND slug = $2`,+ ];+ for (const sql of statements) {+ try {+ await tx.transaction(savepoint => savepoint.executeRaw(sql, [sourceId, oldSlug, newSlug]));+ } catch (error) {+ if (!isUndefinedTableError(error)) throw error;+ }+ }+}diff --git a/src/core/page-state/tags.ts b/src/core/page-state/tags.tsindex 1bf79c2c33..614cb0c340 100644--- a/src/core/page-state/tags.ts+++ b/src/core/page-state/tags.ts@@ -2,13 +2,19 @@ import type { BrainEngine } from '../engine.ts';import type { PageKey } from './types.ts';/** Page-before-tag ordering matches canonical writers and avoids trigger inversions. */-export async function mutatePageTag(engine: BrainEngine, key: PageKey, tag: string, add: boolean): Promise<void> {+export async function mutatePageTag(engine: BrainEngine, key: PageKey, tag: string, add: boolean, tagSource?: 'frontmatter'): Promise<void> {await engine.transaction(async tx => {await tx.lockPageKeys([key]);if (add) {const rows = await tx.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id=$1 AND slug=$2', [key.sourceId, key.slug]);if (!rows.length) throw new Error(`addTag failed: page "${key.slug}" (source=${key.sourceId}) not found`);- await tx.executeRaw('INSERT INTO tags(page_id,tag) VALUES ($1,$2) ON CONFLICT DO NOTHING', [rows[0].id, tag]);+ // A14: an explicit add claims the tag, so no import deletes it; the+ // importer's frontmatter claim only adopts an unclaimed legacy row.+ await tx.executeRaw(tagSource === 'frontmatter'+ ? `INSERT INTO tags(page_id,tag,tag_source) VALUES ($1,$2,'frontmatter')+ ON CONFLICT (page_id,tag) DO UPDATE SET tag_source = 'frontmatter' WHERE tags.tag_source IS NULL`+ : `INSERT INTO tags(page_id,tag,tag_source) VALUES ($1,$2,'added')+ ON CONFLICT (page_id,tag) DO UPDATE SET tag_source = 'added'`, [rows[0].id, tag]);} else {await tx.executeRaw('DELETE FROM tags WHERE page_id=(SELECT id FROM pages WHERE source_id=$1 AND slug=$2) AND tag=$3', [key.sourceId, key.slug, tag]);}diff --git a/src/core/persistence/admin-contract.ts b/src/core/persistence/admin-contract.tsindex c6d181c327..727515e895 100644--- a/src/core/persistence/admin-contract.ts+++ b/src/core/persistence/admin-contract.ts@@ -1,6 +1,6 @@/** Local administration is deliberately absent from the public operation registry. */export const PERSISTENCE_ADMIN_OPERATIONS = [- 'writer_status', 'writer_sync', 'writer_reindex_code', 'writer_retry_effects', 'writer_embed_facts', 'writer_claim', 'writer_activate', 'writer_transfer_prepare', 'writer_transfer_accept',+ 'writer_status', 'writer_sync', 'writer_extract_stale', 'writer_reindex_code', 'writer_retry_effects', 'writer_embed_facts', 'writer_claim', 'writer_activate', 'writer_transfer_prepare', 'writer_transfer_accept','local_writer_list', 'local_writer_register', 'local_writer_revoke','source_lifecycle', 'source_add', 'company_brain_preview', 'company_brain_connect', 'company_brain_resume','writer_reconcile_preview', 'writer_reconcile_apply', 'writer_reconcile_audit', 'writer_reconcile_backups',diff --git a/src/core/persistence/administration.ts b/src/core/persistence/administration.tsindex 69207c90a3..5d6250def4 100644--- a/src/core/persistence/administration.ts+++ b/src/core/persistence/administration.ts@@ -83,6 +83,15 @@ export async function runPersistenceAdministration(engine: BrainEngine, operatio}if (currentVerifiedLocalWriter()?.remote) throw new OperationError('permission_denied', 'Writer administration requires a trusted local CLI caller.');if (operation === 'writer_sync') return (await import('./sync-administration.ts')).runAuthenticatedSyncSlice(engine, params);+ if (operation === 'writer_extract_stale') {+ keys(params, ['source_id', 'dry_run']);+ const writer = currentVerifiedLocalWriter();+ if (!writer || writer.remote || writer.principal.kind !== 'local_cli') throw new OperationError('permission_denied', 'Stale extraction requires a trusted CLI registration.');+ const { managedPersistenceEnabled } = await import('./ownership.ts');+ if (!await managedPersistenceEnabled(engine)) throw new OperationError('writer_coordinator_required', 'Owner-delegated stale extraction requires activated managed persistence.', WRITER_INSPECTION_HINT);+ return { ...await (await import('./links-maintenance.ts')).runManagedStaleExtraction(engine,+ { sourceId: params.source_id === undefined ? undefined : source(params.source_id), dryRun: params.dry_run === true }) };+ }if (operation === 'writer_reindex_code') return (await import('./reindex-administration.ts')).runAuthenticatedCodeReindex(engine, params);if (operation === 'writer_embed_facts') return (await import('./embed-facts-administration.ts')).runAuthenticatedFactEmbedding(engine, params, config);if (operation === 'writer_retry_effects') {diff --git a/src/core/persistence/canonical-projections.ts b/src/core/persistence/canonical-projections.tsindex fa8fcf4603..902824a31d 100644--- a/src/core/persistence/canonical-projections.ts+++ b/src/core/persistence/canonical-projections.ts@@ -200,12 +200,12 @@ export async function materializeTimeline(engine: BrainEngine, body: CanonicalBo}/** Database-only timeline rows on one page, split by whether they can be materialized. */-export async function pendingTimelineRows(engine: BrainEngine, page: { id: number; slug: string } & CanonicalBody) {+export async function pendingTimelineRows(engine: BrainEngine, page: { id: number; slug: string } & CanonicalBody, exclude: ReadonlySet<number> = new Set()) {const { pinned } = classifyTimeline(await storedTimeline(engine, page.id), page, page, page.slug, 'editing');const renderable = new Set<string>();let unrenderable = 0;for (const row of pinned) {- if (row.action !== 'materialize') continue;+ if (row.action !== 'materialize' || exclude.has(Number(row.id))) continue;if (renderMaterializedBullet(row, page.slug)) renderable.add(row.key);else unrenderable++;}diff --git a/src/core/persistence/effect-targets.ts b/src/core/persistence/effect-targets.tsindex b17ab29764..b418bd1f15 100644--- a/src/core/persistence/effect-targets.ts+++ b/src/core/persistence/effect-targets.ts@@ -28,8 +28,16 @@ export async function upgradeWithdrawalEffect(engine: BrainEngine, effect: Persiif (effect.worktree_id) await tx.executeRaw('SELECT id FROM persistence_worktrees WHERE id=$1::uuid FOR SHARE', [effect.worktree_id]);await tx.executeRaw('SELECT id FROM sources WHERE id=$1 FOR UPDATE', [effect.source_id]);await guardEffectSource(tx, effect, hostId);- const claims = await tx.executeRaw<WithdrawalClaim>('SELECT visibility,fact_hash FROM fact_withdrawals WHERE source_id=$1 ORDER BY visibility,fact_hash LIMIT $2',- [effect.source_id, WITHDRAWAL_LIMITS.targets + 1]);+ // Key discovery on the request's own forgotten fact; fall back to the+ // whole ledger only when that fact row no longer exists.+ const requested = await tx.executeRaw<WithdrawalClaim>(`SELECT w.visibility,w.fact_hash,w.subject,f.fact AS claim+ FROM persistence_requests r JOIN facts f ON r.intent->>'id' ~ '^[0-9]+$' AND f.id=(r.intent->>'id')::bigint AND f.source_id=$1+ JOIN fact_withdrawals w ON w.source_id=f.source_id AND w.visibility=f.visibility+ AND w.fact_hash IN (gbrain_fact_fingerprint(f.fact),gbrain_fact_fingerprint_v1(f.fact))+ AND (w.subject='*' OR w.subject=COALESCE(f.entity_slug,'*'))+ WHERE r.id=$2::uuid ORDER BY w.visibility,w.fact_hash,w.subject`, [effect.source_id, effect.request_id]);+ const claims = requested.length ? requested : await tx.executeRaw<WithdrawalClaim>(`SELECT visibility,fact_hash,subject FROM fact_withdrawals+ WHERE source_id=$1 ORDER BY visibility,fact_hash,subject LIMIT $2`, [effect.source_id, WITHDRAWAL_LIMITS.targets + 1]);if (!claims.length) throw new OperationError('withdrawal_provenance', 'Legacy withdrawal intent has no verifiable ledger. Its queued work remains retained.');const discovered = await discoverWithdrawalTargets(tx, effect.source_id, claims).catch(withdrawalDiscoveryFailure);const remaining = await tx.executeRaw<{ id: number }>(`SELECT id FROM pages WHERE source_id=$1 AND id=ANY($2::int[])diff --git a/src/core/persistence/facts-prepare.ts b/src/core/persistence/facts-prepare.tsindex a6692796d7..2cc0c31e5d 100644--- a/src/core/persistence/facts-prepare.ts+++ b/src/core/persistence/facts-prepare.ts@@ -1,7 +1,7 @@import type { BrainEngine, NewFact } from '../engine.ts';import type { GBrainConfig } from '../config.ts';import { OperationError } from '../ops/contract.ts';-import { parseFactsFence, upsertFactRow } from '../facts-fence.ts';+import { parseFactsFence, upsertFactRow, formatFenceDate } from '../facts-fence.ts';import { serializePageToMarkdown } from '../markdown.ts';import { assertFactNotWithdrawn, decideSingleFact } from '../facts/single-prepare.ts';import { extractFactsFromFenceText } from '../facts/extract-from-fence.ts';@@ -95,7 +95,7 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writconst rowNum = fact.entity_slug !== null ? nextRow++ : undefined;if (rowNum !== undefined) body = upsertFactRow(body, { rowNum, claim: fact.fact, kind: fact.kind, visibility: fact.visibility,confidence: fact.confidence ?? 1, notability: fact.notability ?? 'medium', source: fact.source, context: fact.context ?? undefined,- validFrom: fact.valid_from!.toISOString().slice(0, 10), validUntil: fact.valid_until?.toISOString().slice(0, 10),+ validFrom: formatFenceDate(fact.valid_from!), validUntil: fact.valid_until ? formatFenceDate(fact.valid_until) : undefined,claimMetric: fact.claim_metric ?? undefined, claimValue: fact.claim_value ?? undefined,claimUnit: fact.claim_unit ?? undefined, claimPeriod: fact.claim_period ?? undefined }).body;entries.push({ fact, duplicateId: null, rowNum });diff --git a/src/core/persistence/links-maintenance.ts b/src/core/persistence/links-maintenance.tsnew file mode 100644index 0000000000..7c1195ea01--- /dev/null+++ b/src/core/persistence/links-maintenance.ts@@ -0,0 +1,93 @@+import type { BrainEngine } from '../engine.ts';+import { LINK_EXTRACTOR_VERSION_TS } from '../link-extraction.ts';+import { prepareAutomaticLinks } from './links-preparation.ts';+import { withCoordinatedWrite } from './context.ts';+import { unrecordedCanonicalTimeline } from './canonical-projections.ts';++export interface ManagedLinkExtraction { pages: number; created: number; removed: number; timeline: number; skipped: number; remaining: number; }++/** `gbrain extract --stale` on a managed brain, locally or inside the PGLite owner. */+export async function runManagedStaleExtraction(engine: BrainEngine, opts: { sourceId?: string; dryRun?: boolean }): Promise<ManagedLinkExtraction> {+ if (!opts.dryRun) return extractManagedStaleLinks(engine, { sourceId: opts.sourceId });+ const remaining = await engine.countStalePagesForExtraction({ sourceId: opts.sourceId, versionTs: LINK_EXTRACTOR_VERSION_TS });+ return { pages: 0, created: 0, removed: 0, timeline: 0, skipped: 0, remaining };+}++/** The `extract --stale` report for a managed brain, in the same text and JSON shapes as the unmanaged sweep. */+export function formatManagedStaleExtraction(result: ManagedLinkExtraction, dryRun: boolean, json: boolean): string {+ if (json) {+ return JSON.stringify(dryRun ? { action: 'extract_stale_dry_run', stale_pages: result.remaining } : {+ action: 'extract_stale_done', links_created: result.created, links_removed: result.removed, timeline_created: result.timeline,+ pages_processed: result.pages, stale_remaining: result.remaining, ...(result.skipped ? { skipped_changed: result.skipped } : {}),+ });+ }+ if (dryRun) return `(dry run) ${result.remaining} page(s) need link/timeline extraction. Run without --dry-run to extract.`;+ return `Extract --stale: ${result.created} link(s) created, ${result.removed} removed, ${result.timeline} timeline entr(ies) from ${result.pages} page(s).` ++ (result.skipped ? ` Skipped ${result.skipped} page(s) edited during extraction or with unresolved attendance; they stay stale.` : '') ++ (result.remaining ? ` ${result.remaining} page(s) remain stale.` : '');+}++/**+ * Derive markdown links with put_page's contract: the page's own derived edges+ * are replaced by what its current text supports, other producers' edges stay.+ * `slugs` (a sync's committed imports) are re-derived regardless of their+ * watermark, because a concurrent sweep may have stamped them mid-sync before+ * their link targets existed; then pages whose watermark is stale follow. Each+ * page's links and watermark commit together, bound to the revision that was+ * read; a page edited meanwhile, or with unresolved attendance, stays stale.+ * Timeline tuples the coordinator projects from the page body but has no stored+ * row for (a page published before timeline projection) are added in the same+ * coordinated transaction, insert-only. This is the one managed extraction+ * path: sync, `extract --stale` (every caller of extractStaleFromDB) and the+ * PGLite owner delegation all run it, in the process that owns the brain.+ */+export async function extractManagedStaleLinks(engine: BrainEngine,+ opts: { sourceId?: string; slugs?: readonly string[]; maxPages?: number; timeBudgetMs?: number; signal?: AbortSignal } = {}): Promise<ManagedLinkExtraction> {+ const result: ManagedLinkExtraction = { pages: 0, created: 0, removed: 0, timeline: 0, skipped: 0, remaining: 0 };+ const deadline = opts.timeBudgetMs === undefined ? Infinity : Date.now() + opts.timeBudgetMs;+ const versionTs = LINK_EXTRACTOR_VERSION_TS;+ const maxPages = opts.maxPages ?? Infinity;+ const done = new Set<string>();+ const derive = async (slug: string, sourceId: string, stamp?: string) => {+ opts.signal?.throwIfAborted();+ done.add(`${sourceId}\0${slug}`);+ const snapshot = await engine.readPageSnapshot(slug, { sourceId });+ if (!snapshot) return;+ const prepared = await prepareAutomaticLinks(engine, slug, snapshot.page, sourceId);+ const outcome = await engine.transaction(async tx => withCoordinatedWrite(tx, [sourceId], async () => {+ await tx.lockPageKeys(prepared.pageKeys);+ const current = await tx.readPageSnapshot(slug, { sourceId });+ if (current?.revision !== snapshot.revision) return null;+ const written = await prepared.apply(tx);+ if (written.errors) return null;+ const timeline = (await unrecordedCanonicalTimeline(tx, current.page.id, current.page, slug)).map(entry => ({ slug, date: entry.date,+ source: entry.source, summary: entry.summary, detail: entry.detail || '', source_id: sourceId }));+ const added = timeline.length ? await tx.addTimelineEntriesBatch(timeline, { auditSite: 'extract.stale' }) : 0;+ const at = stamp ?? new Date().toISOString();+ await tx.markPagesExtractedBatch([{ slug, source_id: sourceId, extractedAt: at }], at);+ return { ...written, timeline: added };+ }));+ if (!outcome) { result.skipped++; return; }+ result.pages++;+ result.created += outcome.created;+ result.removed += outcome.removed;+ result.timeline += outcome.timeline;+ };+ const budget = () => result.pages + result.skipped < maxPages && Date.now() < deadline;+ if (opts.slugs?.length && opts.sourceId) {+ for (const slug of new Set(opts.slugs)) { if (!budget()) break; await derive(slug, opts.sourceId); }+ }+ let afterPageId = 0;+ while (budget()) {+ const rows = await engine.listStalePagesForExtraction({ batchSize: 25, afterPageId, sourceId: opts.sourceId, versionTs });+ if (!rows.length) break;+ for (const row of rows) {+ if (!budget()) break;+ afterPageId = row.id;+ if (done.has(`${row.source_id}\0${row.slug}`)) continue;+ await derive(row.slug, row.source_id, row.updated_at.getTime() >= Date.parse(versionTs) ? row.updated_at_iso : versionTs);+ }+ }+ result.remaining = await engine.countStalePagesForExtraction({ sourceId: opts.sourceId, versionTs });+ return result;+}diff --git a/src/core/persistence/links-preparation.ts b/src/core/persistence/links-preparation.tsindex fe87ea6709..e7a2ca7b31 100644--- a/src/core/persistence/links-preparation.ts+++ b/src/core/persistence/links-preparation.ts@@ -1,10 +1,25 @@import type { BrainEngine } from '../engine.ts';+import { isUndefinedTableError } from '../utils.ts';import type { ParsedPage } from '../import-file.ts';import { extractPageLinks, isGlobalBasenameEnabled, makeResolver, resolvedLinkCandidate } from '../link-extraction.ts';import { loadActivePackForLocalEngine } from '../schema-pack/best-effort.ts';import { DerivedLinkEndpointChangedError } from '../derived-links.ts';import { capturedLinkEndpoints, indexLinkSources, loadLinkSourcePolicy, resolveCandidateSources } from '../link-reconciliation.ts';+async function liveSlugAliases(engine: BrainEngine, sourceId: string, targets: string[]): Promise<Map<string, string>> {+ if (!targets.length) return new Map();+ try {+ const rows = await engine.executeRaw<{ alias_slug: string; canonical_slug: string }>(`SELECT a.alias_slug, a.canonical_slug FROM slug_aliases a+ WHERE a.source_id=$1 AND a.alias_slug IN (SELECT unnest($2::text[]))+ AND NOT EXISTS (SELECT 1 FROM pages p WHERE p.source_id=a.source_id AND p.slug=a.alias_slug AND p.deleted_at IS NULL)+ AND EXISTS (SELECT 1 FROM pages c WHERE c.source_id=a.source_id AND c.slug=a.canonical_slug AND c.deleted_at IS NULL)`, [sourceId, [...new Set(targets)]]);+ return new Map(rows.map(row => [row.alias_slug, row.canonical_slug]));+ } catch (error) {+ if (isUndefinedTableError(error)) return new Map();+ throw error;+ }+}+export async function prepareAutomaticLinks(engine: BrainEngine, slug: string,page: Pick<ParsedPage, 'type' | 'compiled_truth' | 'timeline' | 'frontmatter'>, sourceId: string) {const resolver = makeResolver(engine, { mode: 'live', sourceId });@@ -16,7 +31,11 @@ export async function prepareAutomaticLinks(engine: BrainEngine, slug: string,const referenced = new Set([slug]);const initial = await extractPageLinks(slug, content, page.frontmatter, page.type, resolver,{ ...opts, onResolvedFrontmatterTarget: target => referenced.add(target) });- const keys = [...new Set([...referenced, ...initial.candidates.flatMap(c => [c.targetSlug, c.fromSlug ?? slug])])].sort();+ // A link written against a renamed page's old slug follows its slug alias, like get_page does.+ const aliases = await liveSlugAliases(engine, sourceId, initial.candidates.map(c => c.targetSlug));+ const retarget = <T extends { targetSlug: string; targetSourceId?: string }>(c: T): T =>+ aliases.has(c.targetSlug) && (c.targetSourceId ?? sourceId) === sourceId ? { ...c, targetSlug: aliases.get(c.targetSlug)! } : c;+ const keys = [...new Set([...referenced, ...initial.candidates.map(retarget).flatMap(c => [c.targetSlug, c.fromSlug ?? slug])])].sort();const endpointRows = await engine.executeRaw<{ slug: string; source_id: string; type: string; knowledge_revision: string }>('SELECT slug, source_id, type, knowledge_revision FROM pages WHERE slug=ANY($1::text[]) AND deleted_at IS NULL', [keys]);const endpoints = indexLinkSources(endpointRows);@@ -32,7 +51,7 @@ export async function prepareAutomaticLinks(engine: BrainEngine, slug: string,return resolved.ok ? (targetSlug === slug && resolved.toSourceId === sourceId ? page.type: metadata.get(`${resolved.toSourceId}\0${targetSlug}`)?.type) : undefined;} });- const rows = candidates.flatMap(candidate => {+ const rows = candidates.map(retarget).flatMap(candidate => {const resolved = resolve(candidate);if (!resolved.ok) return [];if (!candidate.canonicalAttendance && (resolved.fromSourceId !== sourceId || resolved.toSourceId !== sourceId)) return [];diff --git a/src/core/persistence/memory-prepare.ts b/src/core/persistence/memory-prepare.tsindex 23f76f286e..179c92ac70 100644--- a/src/core/persistence/memory-prepare.ts+++ b/src/core/persistence/memory-prepare.ts@@ -2,7 +2,7 @@ import type { BrainEngine, NewFact } from '../engine.ts';import type { GBrainConfig } from '../config.ts';import { OperationError } from '../ops/contract.ts';import { assertPageRevision } from '../page-state/types.ts';-import { parseFactsFence, renderFactsTable, replaceOrInsertFactsFence, upsertFactRow } from '../facts-fence.ts';+import { parseFactsFence, renderFactsTable, replaceOrInsertFactsFence, upsertFactRow, formatFenceDate } from '../facts-fence.ts';import { serializePageToMarkdown } from '../markdown.ts';import { assertFactNotWithdrawn, decideSingleFact, prepareFactEmbedding, type SingleFactIntent } from '../facts/single-prepare.ts';import { engineMutationPrecondition, parseMutationPrecondition } from './preconditions.ts';@@ -62,8 +62,8 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteRequeconst parsed = parseFactsFence(snapshot.page.compiled_truth);if (parsed.warnings.length) throw new OperationError('storage_error', 'The entity facts fence is malformed; repair it before appending memory.');const appended = upsertFactRow(snapshot.page.compiled_truth, { claim: input.fact, kind: input.kind, visibility: input.visibility,- confidence: 1, notability: 'medium', validFrom: validFrom.toISOString().slice(0, 10),- validUntil: validUntil?.toISOString().slice(0, 10), source: fact.source });+ confidence: 1, notability: 'medium', validFrom: formatFenceDate(validFrom),+ validUntil: validUntil ? formatFenceDate(validUntil) : undefined, source: fact.source });rowNum = appended.rowNum;let body = appended.body;const old = decision.candidate;diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.tsindex 6ce4493079..9f2e8e7fe5 100644--- a/src/core/persistence/page-prepare.ts+++ b/src/core/persistence/page-prepare.ts@@ -251,7 +251,10 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequestconst project = projected ? await prepareCanonicalProjections(engine,ready.parsedPage,row.slug,row.source_id,snapshot,writer) : undefined;const ordinaryPage = ['put_page','capture','restore_page','revert_version'].includes(row.operation);const advisories = noop || targetDeleted ? pageNoopAdvisories(row) : !ordinaryPage ? remoteLinkHint(row) : await preparePageAdvisories(engine,row,ready.parsedPage);- const links = !noop && !targetDeleted && ordinaryPage && (row.authority.autoLinkTrusted ?? !row.authority.remote) && await isAutoLinkEnabled(engine)+ // A managed maintenance page (e.g. the dream write-back after grounding+ // quarantine) republishes a body; its automatic links follow that body.+ const autoLinkedPage = ordinaryPage || p.kind === 'managed_maintenance_page';+ const links = !noop && !targetDeleted && autoLinkedPage && (row.authority.autoLinkTrusted ?? !row.authority.remote) && await isAutoLinkEnabled(engine)? await prepareAutomaticLinks(engine,row.slug,ready.parsedPage,row.source_id) : undefined;const capture = row.operation === 'capture' && typeof p.capture_path === 'string' && typeof p.capture_file_hash === 'string'? { path: p.capture_path, hash: p.capture_file_hash } : undefined;diff --git a/src/core/persistence/sync-discovery.ts b/src/core/persistence/sync-discovery.tsindex a97eb00489..55c5a5ec8d 100644--- a/src/core/persistence/sync-discovery.ts+++ b/src/core/persistence/sync-discovery.ts@@ -17,9 +17,14 @@ import type { CompanyBrainPlan } from '../company-brain/types.ts';import { assertDistinctSyncOrigins, legacySyncOrigin, sameSyncOrigin, syncOriginPath, type SyncOriginScope } from './sync-origin.ts';import { assertManagedSyncActive } from './sync-authority.ts';-export interface SyncEntry { path: string; sourcePath: string; action: 'import' | 'delete'; working: boolean; slug?: string; pageId?: number | null; revision?: string | null; }+/** The page an import takes over from its previous origin: a Git rename, or a file that replaced a vanished origin at the same slug. */+export interface SyncRename { sourcePath: string; slug: string; pageId: number; revision: string; }+export interface SyncEntry { path: string; sourcePath: string; action: 'import' | 'delete'; working: boolean; slug?: string; pageId?: number | null; revision?: string | null;+ renameFrom?: SyncRename; }+/** Files that map to a slug another origin keeps; they are left out of the manifest until one is renamed. */+export interface SyncSlugCollision { slug: string; kept: string; skipped: string[]; }export interface SyncDiscovery { binding: WorktreeBinding; root: string; gitRoot: string; sourceId: string; incarnation: string;- companyPlan?: CompanyBrainPlan;+ companyPlan?: CompanyBrainPlan; slugCollisions?: SyncSlugCollision[];from: string | null; target: string; entries: SyncEntry[]; uncommitted?: { added: number; modified: number; deleted: number }; slugMode: 'git-root' | 'source-root'; }export interface ManagedSyncContext { binding: WorktreeBinding; root: string; gitRoot: string; sourceId: string; incarnation: string;source: { last_commit: string | null; config: Record<string, unknown> }; }@@ -127,6 +132,7 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, cconst dirty = company ? { added: [], modified: [], deleted: [], renamed: [] } : buildDetachedWorkingTreeManifest(gitRoot);const delta = !opts.full && source.last_commit ? computeSyncDelta(gitRoot, source.last_commit, target) : null;const entries = new Map<string, SyncEntry>();+ const renamedFrom = new Map<string, string>();const put = (path: string, action: SyncEntry['action'], working = false) => {if (process.platform === 'win32' && path.includes('\\')) throw new OperationError('page_identity_changed', 'Git paths containing literal backslashes are not safe Windows sync targets.');if (eligible(path)) entries.set(path, { path: relative(nativeRoot, join(nativeGitRoot, path)).split(sep).join('/'), sourcePath: sourcePath(path), action, working });@@ -134,7 +140,7 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, cif (delta?.status === 'ok') {for (const path of [...delta.manifest.added, ...delta.manifest.modified]) put(path, 'import');for (const path of delta.manifest.deleted) put(path, 'delete');- for (const rename of delta.manifest.renamed) { put(rename.from, 'delete'); put(rename.to, 'import'); }+ for (const rename of delta.manifest.renamed) { put(rename.from, 'delete'); put(rename.to, 'import'); renamedFrom.set(rename.to, rename.from); }} else {const paths = syncGit(gitRoot, ['ls-tree', '-r', '--name-only', '-z', target]).split('\0').filter(path => path && (!scope || path.startsWith(`${scope}/`)));@@ -153,10 +159,11 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, cif (working) {for (const path of [...dirty.added, ...dirty.modified]) put(path, 'import', true);for (const path of dirty.deleted) put(path, 'delete', true);- for (const rename of dirty.renamed) { put(rename.from, 'delete', true); put(rename.to, 'import', true); }+ for (const rename of dirty.renamed) { put(rename.from, 'delete', true); put(rename.to, 'import', true); renamedFrom.set(rename.to, rename.from); }}if (company) {entries.clear();+ renamedFrom.clear();const included = company.plan.manifest.filter(entry => entry.disposition === 'included');const present = new Set(included.map(entry => syncOriginPath(entry.path)));for (const entry of included) entries.set(entry.path, { path: entry.path, sourcePath: entry.path, action: 'import', working: false, slug: entry.page!.slug });@@ -182,6 +189,8 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, cconst origin = syncOriginPath(page.source_path);byPath.set(origin, [...(byPath.get(origin) ?? []), page]);}+ // Imports whose origin has no page yet claim their slug; claims are settled after every entry has one.+ const claims = new Map<string, SyncEntry[]>();for (const entry of selected) {const legacy = legacySyncOrigin(originScope, syncOriginPath(entry.sourcePath));const origins = [...byPath.get(syncOriginPath(entry.sourcePath)) ?? [],@@ -190,6 +199,11 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, clet slug = entry.slug ?? origins[0]?.slug ?? resolveSlugForPath(entry.sourcePath);if (!slug && entry.action === 'import') slug = parseMarkdown(readSyncContent(discovered, entry), '').slug;if (!slug) throw new OperationError('invalid_params', 'The imported file has no usable page slug.');+ if (!company && entry.action === 'import' && !origins.length && !isCodeFilePath(entry.sourcePath)) {+ entry.slug = slug;+ claims.set(slug, [...(claims.get(slug) ?? []), entry]);+ continue;+ }const page = origins[0] ?? bySlug.get(slug);if (page?.source_path != null && !sameSyncOrigin(page.source_path, entry.sourcePath, originScope, page.slug)) {const error = new OperationError('page_identity_changed', 'A different origin occupies the imported slug.',@@ -199,6 +213,54 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, c}Object.assign(entry, { slug, pageId: page?.id ?? null, revision: page?.knowledge_revision ?? null });}+ const deletions = new Map(selected.filter(entry => entry.action === 'delete').map(entry => [syncOriginPath(entry.sourcePath), entry]));+ // A soft-delete advances knowledge_revision, so the frozen revisions still guard this read.+ const deleted = new Set(claims.size ? (await engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id=$1 AND deleted_at IS NOT NULL', [sourceId])).map(row => row.id) : []);+ // Origins that differ only by case or separator spelling may be one file on another platform; refuse rather than+ // guess. The one exception is a case-only respelling whose old file this very sync removes.+ const spelling = (origin: string) => origin.replaceAll('\\', '/').toLowerCase();+ const retired = new Set<SyncEntry>();+ const collisions: SyncSlugCollision[] = [];+ const gitPath = (entry: SyncEntry) => relative(nativeGitRoot, join(nativeRoot, entry.path)).split(sep).join('/');+ for (const [slug, candidates] of claims) {+ const holder = bySlug.get(slug);+ // A legacy Git-root spelling of a source-root origin (#5610) is matched against this sync's deletions by its source-relative form.+ const recorded = holder?.source_path == null ? null : syncOriginPath(holder.source_path);+ const prefix = originScope?.slugMode === 'source-root' && originScope.scope ? `${originScope.scope}/` : null;+ const holderOrigin = recorded !== null && prefix && recorded.startsWith(prefix) && sameSyncOrigin(recorded, recorded.slice(prefix.length), originScope, holder!.slug)+ ? recorded.slice(prefix.length) : recorded;+ const respelled = holderOrigin !== null && !holderOrigin.includes('\\') && deletions.has(holderOrigin);+ const spellings = [...(holderOrigin === null || respelled ? [] : [holderOrigin]), ...candidates.map(entry => syncOriginPath(entry.sourcePath))].map(spelling);+ if (new Set(spellings).size !== spellings.length) throw new OperationError('page_identity_changed', 'Sync origins for one slug differ only by case or separator spelling.');+ // A live page keeps its slug while its own file is still in the tree; the newcomer is the collision.+ const kept = holder && !deleted.has(holder.id) && holderOrigin !== null && !deletions.has(holderOrigin) ? holderOrigin : null;+ const winner = kept === null ? candidates.find(entry => /\.mdx?$/i.test(entry.sourcePath) && entry.sourcePath.replace(/\.mdx?$/i, '') === slug) ?? candidates[0] : null;+ const losers = candidates.filter(entry => entry !== winner);+ for (const entry of losers) retired.add(entry);+ if (losers.length) collisions.push({ slug, kept: kept ?? winner!.sourcePath, skipped: losers.map(entry => entry.sourcePath) });+ if (!winner) continue;+ if (holder) {+ // Same slug, vanished origin: the file takes over the page (and its history) instead of racing a deletion.+ Object.assign(winner, { pageId: holder.id, revision: holder.knowledge_revision });+ if (holderOrigin !== null) {+ winner.renameFrom = { sourcePath: holder.source_path!, slug, pageId: holder.id, revision: holder.knowledge_revision };+ const deletion = deletions.get(holderOrigin);+ if (deletion) retired.add(deletion);+ }+ continue;+ }+ Object.assign(winner, { pageId: null, revision: null });+ const from = renamedFrom.get(gitPath(winner));+ const deletion = from === undefined ? undefined : [...deletions.values()].find(entry => gitPath(entry) === from);+ const moved = deletion?.pageId == null ? undefined : identities.find(page => page.id === deletion.pageId);+ if (deletion && moved && !deleted.has(moved.id) && moved.source_path != null) {+ // A Git rename moves the page to its new slug, like the library path's updateSlug: same page id, inbound links and an alias.+ winner.renameFrom = { sourcePath: moved.source_path, slug: moved.slug, pageId: moved.id, revision: moved.knowledge_revision };+ retired.add(deletion);+ }+ }+ if (retired.size) discovered.entries = selected.filter(entry => !retired.has(entry));+ if (collisions.length) discovered.slugCollisions = collisions;if (!working) {const uncommitted = { added: new Set([...dirty.added,...dirty.renamed.map(r=>r.to)].filter(eligible)).size,modified: new Set(dirty.modified.filter(eligible)).size,diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.tsindex f508dc3420..0734b109ef 100644--- a/src/core/persistence/sync-prepare.ts+++ b/src/core/persistence/sync-prepare.ts@@ -15,7 +15,7 @@ import { prepareCanonicalProjections } from './canonical-projections.ts';import { digest, sha256 } from './digest.ts';import { preserveProtectedTakes } from './protected-takes.ts';import { getWorktreeBinding } from './ownership.ts';-import { assertConfiguredSyncRoot, assertSyncEntryOrigin, syncGit, syncRawHash } from './sync-discovery.ts';+import { assertConfiguredSyncRoot, assertSyncEntryOrigin, syncGit, syncRawHash, type SyncRename } from './sync-discovery.ts';import { assertSyncPageOrigin, sameSyncOrigin, syncOriginPath, syncOriginScope, type SyncOriginScope } from './sync-origin.ts';import { assertManagedSyncActive, validateSyncAuthority, type SyncAuthority, type SyncProcessingOptions } from './sync-authority.ts';import type { PreparedContentImport } from './prepared-import.ts';@@ -34,6 +34,7 @@ export interface SyncIntent extends Record<string, unknown> {rawHash: string | null; content: string | null; ownerEpoch: string;lineEndingOnly?: boolean;working?: boolean;+ renameFrom?: SyncRename;processingOptions?: SyncProcessingOptions;syncAuthority: SyncAuthority; cursorKey: string; runId: string; index: number;from: string | null; target: string; total: number; slugMode: 'git-root' | 'source-root';@@ -77,7 +78,16 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: WriteassertSyncEntryOrigin(originContext, origin);originScope = syncOriginScope({ ...originContext, sourceId: row.source_id });await assertSyncPageOrigin(engine, row.source_id, p.sourcePath, row.page_id, p.kind === 'managed_sync_delete', originScope);+ if (p.renameFrom) await assertSyncPageOrigin(engine, row.source_id, p.renameFrom.sourcePath, p.renameFrom.pageId, true, originScope);}+ const moved = p.kind === 'managed_sync_import' ? p.renameFrom : undefined;+ const assertRenameSource = async (tx: BrainEngine) => {+ if (!moved || moved.slug === row.slug) return;+ const previous = await tx.readPageSnapshot(moved.slug, { sourceId: row.source_id, includeDeleted: true });+ if (previous?.page.id !== moved.pageId || previous.revision !== moved.revision || previous.page.deleted_at != null) {+ throw new OperationError('revision_conflict', 'The renamed page changed after sync admission.');+ }+ };const validate = async (tx: BrainEngine) => {await assertManagedSyncActive(tx, true);await validateSyncAuthority(tx, p.syncAuthority, row.slug);@@ -94,6 +104,8 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Writeif (origin && originContext) {assertSyncEntryOrigin(originContext, origin);await assertSyncPageOrigin(tx, row.source_id, origin.sourcePath, row.page_id, p.kind === 'managed_sync_delete', originScope);+ if (moved) await assertSyncPageOrigin(tx, row.source_id, moved.sourcePath, moved.pageId, true, originScope);+ await assertRenameSource(tx);}if (p.companyApproval) {const [source] = await tx.executeRaw<{ config: unknown }>('SELECT config FROM sources WHERE id=$1', [row.source_id]);@@ -131,7 +143,8 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Writeconst source = { sourceId: row.source_id };const snapshot = await engine.readPageSnapshot(row.slug, { ...source, includeDeleted: true });assertPageRevision(snapshot, p.expected_revision === null ? {} : { expectedRevision: p.expected_revision });- if ((snapshot?.page.id ?? null) !== row.page_id || (snapshot?.page.source_path != null && !sameSyncOrigin(snapshot.page.source_path, p.sourcePath!, originScope, snapshot.page.slug))) {+ const recordedOrigin = moved?.slug === row.slug ? moved.sourcePath : p.sourcePath!;+ if ((snapshot?.page.id ?? null) !== row.page_id || (snapshot?.page.source_path != null && !sameSyncOrigin(snapshot.page.source_path, recordedOrigin, originScope, snapshot.page.slug))) {throw new OperationError('page_identity_changed', 'The imported path no longer names the accepted page.');}if (p.kind === 'managed_sync_delete') return { observedRevision: snapshot?.revision ?? null, noop: !snapshot || snapshot.page.deleted_at != null,@@ -163,6 +176,12 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Writeif (schema && p.processingOptions?.noSchemaPack) throw new OperationError('profile_incompatible', 'Company source approval requires its pinned schema pack.');const activePack = p.processingOptions?.noSchemaPack ? undefined : schema ? (await checkApprovedSchemaForEngine(engine, { name: schema.name, identity: schema.identity, resolvedManifestHash: schema.resolved_digest },{ remote: false, sourceId: row.source_id })).pack.manifest : (await loadActivePackForEngine(engine, { remote: row.authority.remote, sourceId: row.source_id }).catch(() => null))?.manifest;+ // A renamed page is prepared where it stands; publication moves it, then re-prepares at the new slug.+ const renamed = moved && moved.slug !== row.slug ? moved : undefined;+ const base = renamed ? await engine.readPageSnapshot(renamed.slug, { ...source, includeDeleted: true }) : snapshot;+ if (renamed && (base?.page.id !== renamed.pageId || base.revision !== renamed.revision || base.page.deleted_at != null)) {+ throw new OperationError('revision_conflict', 'The renamed page changed after sync admission.');+ }const parsedInput = parseMarkdown(p.content, row.slug, { activePack });const expectedSlug = resolveSlugForPath(p.sourcePath);const retainedWindowsOrigin = process.platform === 'win32' && snapshot?.page.source_path != null &&@@ -170,50 +189,68 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Writeif (expectedSlug && parsedInput.slug !== expectedSlug && slugifyPath(parsedInput.slug) !== expectedSlug && !retainedWindowsOrigin) {throw new OperationError('invalid_params', 'The file frontmatter slug conflicts with its physical origin.');}- if (!p.companyApproval && snapshot && !p.lineEndingOnly && p.rawHash !== sha256(p.content) && !sameCanonicalImport(snapshot, parsedInput)) {+ if (!p.companyApproval && base && !p.lineEndingOnly && p.rawHash !== sha256(p.content) && !sameCanonicalImport(base, parsedInput)) {throw new OperationError('source_changed', 'Newer working-tree bytes and the current page disagree with this pinned Git import.');}let importContent = p.content;if (row.authority.remote) {- const compiled_truth = preserveProtectedTakes(parsedInput.compiled_truth, snapshot?.page.compiled_truth ?? '');- const timeline = preserveProtectedTakes(parsedInput.timeline ?? '', snapshot?.page.timeline ?? '');+ const compiled_truth = preserveProtectedTakes(parsedInput.compiled_truth, base?.page.compiled_truth ?? '');+ const timeline = preserveProtectedTakes(parsedInput.timeline ?? '', base?.page.timeline ?? '');if (compiled_truth !== parsedInput.compiled_truth || timeline !== (parsedInput.timeline ?? '')) {- importContent = serializePageToMarkdown({ ...(snapshot?.page ?? { id: 0, source_id: row.source_id, created_at: new Date(), updated_at: new Date() }),+ importContent = serializePageToMarkdown({ ...(base?.page ?? { id: 0, source_id: row.source_id, created_at: new Date(), updated_at: new Date() }),...parsedInput, compiled_truth, timeline } as Page, parsedInput.tags);}}let prepared: PreparedContentImport | undefined;- const result = await importFromContent(engine, row.slug, importContent, { ...source, noEmbed: true, remote: row.authority.remote, activePack,- filename: basename(p.sourcePath).replace(/\.mdx?$/i, ''), sourcePath: p.sourcePath, allowEmptyOverwrite: true,+ const importOptions = { ...source, noEmbed: true, remote: row.authority.remote, activePack,+ filename: basename(p.sourcePath).replace(/\.mdx?$/i, ''), sourcePath: p.sourcePath, allowEmptyOverwrite: true };+ const result = await importFromContent(engine, renamed?.slug ?? row.slug, importContent, { ...importOptions,prepare: async value => { prepared = value; return value.result; } });if (!prepared) throw new OperationError('invalid_params', result.error ?? 'The sync file could not be prepared.');const ready = prepared;- if (ready.observedRevision !== (snapshot?.revision ?? null)) throw new OperationError('revision_conflict', 'The page changed during sync preparation.');- if (ready.slug !== row.slug) {+ if (ready.observedRevision !== (base?.revision ?? null)) throw new OperationError('revision_conflict', 'The page changed during sync preparation.');+ if (ready.slug !== (renamed?.slug ?? row.slug)) {// Cross-slug dedup must never advance the origin's checkpoint without a// guarded proof about the other identity. Keep the cursor explicitly blocked.throw new OperationError('revision_conflict', 'A different page already owns this file identity; resolve the duplicate before syncing.');}const parsed = parseMarkdown(p.content, row.slug, { activePack });- const tags = [...new Set([...(snapshot?.tags ?? []), ...ready.parsedPage.tags])].sort();- const renderedPage = { ...(snapshot?.page ?? { id: 0, source_id: row.source_id, created_at: new Date(), updated_at: new Date() }), ...ready.parsedPage } as Page;+ const tags = [...new Set([...(base?.tags ?? []), ...ready.parsedPage.tags])].sort();+ const renderedPage = { ...(base?.page ?? { id: 0, source_id: row.source_id, created_at: new Date(), updated_at: new Date() }), ...ready.parsedPage } as Page;+ if (renamed && parsedInput.typeExplicit !== true) renderedPage.type = parsedInput.type;const canonical = (page: Pick<typeof parsed, 'type' | 'title' | 'compiled_truth' | 'timeline' | 'frontmatter'>, tags: string[]) => ({ type: page.type, title: page.title, body: page.compiled_truth,timeline: page.timeline ?? '', frontmatter: page.frontmatter, tags: [...new Set(tags)].sort() });- const overlay = digest(canonical(parsed, parsed.tags)) !== digest(canonical(ready.parsedPage, tags));+ // A move re-infers an implicit type from the new location, as a fresh import there would.+ const renamedType = renamed && parsedInput.typeExplicit !== true ? parsedInput.type : undefined;+ const overlay = digest(canonical(parsed, parsed.tags)) !== digest(canonical({ ...ready.parsedPage, type: renamedType ?? ready.parsedPage.type }, tags));if (overlay && p.companyApproval) throw new OperationError('source_writeback_required', 'Canonical preparation requires a source-content correction; this profile never writes repository files.');if (overlay && !p.lineEndingOnly && p.rawHash !== sha256(p.content)) throw new OperationError('source_changed', 'Canonical sanitization cannot overwrite newer working-tree bytes.');- const project = await prepareCanonicalProjections(engine, ready.parsedPage, row.slug, row.source_id, snapshot, p.companyApproval ? 'immutable' : 'file');+ // A rename projects against the moved page (same id), so its pinned timeline rows carry over.+ const project = await prepareCanonicalProjections(engine, ready.parsedPage, row.slug, row.source_id, base, p.companyApproval ? 'immutable' : 'file');return { observedRevision: snapshot?.revision ?? null,+ ...(renamed ? { additionalPageKeys: [{ sourceId: row.source_id, slug: renamed.slug }] } : {}),validate: async tx => { await validate(tx); await ready.validate(tx); },deferEmbedding: p.processingOptions?.noEmbed,...(overlay ? { file: { root, path: join(root, p.path), content: serializePageToMarkdown(renderedPage, tags), expectedBeforeHash: p.rawHash } } : {}),apply: async tx => {- await ready.apply(tx);+ let applied = ready;+ if (renamed) {+ // The page moves first, keeping its id, inbound links and history and leaving+ // `old -> new` in slug_aliases; the file content is then prepared against it.+ if (await tx.updateSlug(renamed.slug, row.slug, source) !== 1) throw new OperationError('page_identity_changed', 'The renamed page could not move to its new slug.');+ if (renamedType) await tx.executeRaw('UPDATE pages SET type=$3 WHERE source_id=$1 AND slug=$2', [row.source_id, row.slug, renamedType]);+ let movedImport: PreparedContentImport | undefined;+ await importFromContent(tx, row.slug, importContent, { ...importOptions, prepare: async value => { movedImport = value; return value.result; } });+ if (!movedImport || movedImport.slug !== row.slug) throw new OperationError('page_identity_changed', 'The renamed page could not be prepared at its new slug.');+ await movedImport.validate(tx);+ applied = movedImport;+ }+ await applied.apply(tx);// Hash no-ops still repair a missing physical origin under the same guard.await tx.executeRaw('UPDATE pages SET source_path=$3 WHERE source_id=$1 AND slug=$2 AND source_path IS DISTINCT FROM $3', [row.source_id, row.slug, p.sourcePath]);- if (!ready.noop || p.companyApproval) await project(tx);- if (!ready.noop) await sealPageTextProjection(tx, row.slug, row.source_id);- return { status: ready.noop ? 'skipped' : snapshot ? 'updated' : 'created', slug: row.slug, source_id: row.source_id,- chunks: result.chunks, noop: ready.noop, imported_file: true };+ if (!applied.noop || p.companyApproval) await project(tx);+ if (!applied.noop) await sealPageTextProjection(tx, row.slug, row.source_id);+ return { status: moved ? 'renamed' : applied.noop ? 'skipped' : snapshot ? 'updated' : 'created', slug: row.slug, source_id: row.source_id,+ chunks: applied.result.chunks, noop: applied.noop && !moved, imported_file: true, ...(moved ? { renamed_from: moved.slug } : {}) };} };}diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.tsindex 7523ccfbae..79a3ca6688 100644--- a/src/core/persistence/sync-run.ts+++ b/src/core/persistence/sync-run.ts@@ -18,6 +18,7 @@ import { readCommittedBlob } from '../company-brain/revision.ts';import { refreshProjectionStatistics } from '../search/projection-statistics.ts';import { recordManagedSyncFailure, clearManagedSyncFailureAfterSuccess, formatManagedSyncFailure, type ManagedSyncFailure } from './sync-failures.ts';import { writeFailureDiagnostic } from './verb-errors.ts';+import { extractManagedStaleLinks } from './links-maintenance.ts';import { isTerminalWriteState, publicWriteReceipt, type WriteReceipt } from './types.ts';import type { WriteRequest } from './model.ts';@@ -37,7 +38,7 @@ export interface ManagedSyncWriteDiagnostic {interface Pending { requestId: string; slug: string; pageId: number | null; intent: SyncIntent; }interface Cursor extends SyncDiscovery { runId: string; index: number; authority: SyncAuthority; pending?: Pending; done?: boolean; companyReceiptId?: string;processingOptions?: SyncProcessingOptions;- counts: { added: number; modified: number; deleted: number; chunks: number }; }+ counts: { added: number; modified: number; deleted: number; chunks: number; renamed?: number }; }const OP = 'managed-sync';type CursorHeader = Omit<Cursor, 'entries' | 'companyPlan'> & { total: number };const header = ({ entries, companyPlan: _plan, ...value }: Cursor): CursorHeader => ({ ...value, total: entries.length });@@ -106,7 +107,8 @@ async function replaceCursor(engine: BrainEngine, key: string, before: CursorHeafunction result(cursor: Cursor | CursorHeader, status: SyncResult['status'], reason?: SyncResult['reason']): SyncResult {return { status, ...(cursor.authority.writer.remote ? {} : { runId: cursor.runId }), fromCommit: cursor.authority.writer.remote ? null : cursor.from,toCommit: cursor.authority.writer.remote ? '' : cursor.target, added: cursor.counts.added, modified: cursor.counts.modified,- deleted: cursor.counts.deleted, renamed: 0, chunksCreated: cursor.counts.chunks, embedded: 0, pagesAffected: [],+ deleted: cursor.counts.deleted, renamed: cursor.counts.renamed ?? 0, chunksCreated: cursor.counts.chunks, embedded: 0, pagesAffected: [],+ ...(cursor.slugCollisions?.length ? { slugCollisions: cursor.slugCollisions } : {}),filesImported: cursor.index, bankedFiles: cursor.index, ...(cursor.uncommitted ? { uncommitted: cursor.uncommitted } : {}), ...(reason ? { reason } : {}) };}function writeDiagnostic(cursor: Cursor, pending: Pending, row: WriteRequest): ManagedSyncWriteDiagnostic {@@ -159,15 +161,26 @@ async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string, assslug = entry.slug!; pageId = entry.pageId ?? null; revision = entry.revision ?? null;const snapshot = await engine.readPageSnapshot(slug, { sourceId: cursor.sourceId, includeDeleted: true });assertActive();+ const moved = entry.renameFrom;+ const recorded = moved?.slug === slug ? moved.sourcePath : entry.sourcePath;if ((snapshot?.page.id ?? null) !== pageId || (snapshot?.revision ?? null) !== revision ||- (snapshot?.page.source_path != null && !sameSyncOrigin(snapshot.page.source_path, entry.sourcePath, originScope, snapshot.page.slug))) {+ (snapshot?.page.source_path != null && !sameSyncOrigin(snapshot.page.source_path, recorded, originScope, snapshot.page.slug))) {throw new OperationError('revision_conflict', 'A page changed after this sync cursor was enumerated.');}+ if (moved && moved.slug !== slug) {+ const previous = await engine.readPageSnapshot(moved.slug, { sourceId: cursor.sourceId, includeDeleted: true });+ assertActive();+ if (previous?.page.id !== moved.pageId || previous.revision !== moved.revision || previous.page.deleted_at != null ||+ previous.page.source_path == null || !sameSyncOrigin(previous.page.source_path, moved.sourcePath, originScope, previous.page.slug)) {+ throw new OperationError('revision_conflict', 'A renamed page changed after this sync cursor was enumerated.');+ }+ }}await validateSyncAuthority(engine, cursor.authority, slug);assertActive();return { requestId: randomUUID(), slug, pageId, intent: { kind: !entry ? 'managed_sync_checkpoint' : entry.action === 'import' ? 'managed_sync_import' : 'managed_sync_delete',expected_revision: revision, sourcePath: entry?.sourcePath ?? null, path: entry?.path ?? null, rawHash, content, lineEndingOnly,+ ...(entry?.renameFrom ? { renameFrom: entry.renameFrom } : {}),processingOptions: cursor.processingOptions,ownerEpoch: String(cursor.binding.owner_epoch), syncAuthority: cursor.authority, cursorKey: key, runId: cursor.runId,slugMode: cursor.slugMode, index: cursor.index, total: cursor.entries.length, from: cursor.from, target: cursor.target, working: entry?.working ?? false,@@ -202,6 +215,16 @@ export async function performManagedSync(engine: BrainEngine, opts: SyncOpts, slthrowIfAborted(signal);assertPersistenceAccepting(engine);};+ // Links derive from committed pages once the checkpoint lands, in this owner+ // process, so forward references inside one run resolve and PGLite-delegated+ // syncs match Postgres. Content is already committed: a failure here leaves+ // the pages stale for `gbrain extract --stale` instead of failing the sync.+ const withLinks = async (done: Cursor, synced: SyncResult): Promise<SyncResult> => {+ if (company || (done.processingOptions ?? processingOptions).noExtract) return synced;+ try { return { ...synced, links: await extractManagedStaleLinks(engine, { sourceId: done.sourceId, maxPages: 1000, signal,+ slugs: done.entries.flatMap(entry => entry.action === 'import' && entry.slug ? [entry.slug] : []) }) }; }+ catch { return synced; }+ };try {assertActive();try { cursor = await readCursor(engine, key); }@@ -374,12 +397,13 @@ export async function performManagedSync(engine: BrainEngine, opts: SyncOpts, slawait clearManagedSyncFailureAfterSuccess(engine, key);if (cursor.counts.added + cursor.counts.modified + cursor.counts.deleted > 0) await refreshProjectionStatistics(engine);assertActive();- return result(cursor, cursor.from === null ? 'first_sync' : 'synced');+ return withLinks(cursor, result(cursor, cursor.from === null ? 'first_sync' : 'synced'));}// The frozen manifest is shared; only the cursor header changes per page.const next: Cursor = { ...cursor, index: cursor.index + 1, counts: { ...cursor.counts } }; delete next.pending;if (done.outcome?.noop !== true) {if (pending.intent.kind === 'managed_sync_delete') next.counts.deleted++;+ else if (pending.intent.renameFrom) next.counts.renamed = (next.counts.renamed ?? 0) + 1;else if (pending.pageId === null) next.counts.added++; else next.counts.modified++;}next.counts.chunks += Number(done.outcome?.chunks ?? 0);@@ -395,7 +419,7 @@ export async function performManagedSync(engine: BrainEngine, opts: SyncOpts, slbatchPages = 0; batchStart = performance.now();}}- return result(cursor, cursor.from === null ? 'first_sync' : 'synced');+ return withLinks(cursor, result(cursor, cursor.from === null ? 'first_sync' : 'synced'));} catch (error) {assertSyncDispatchActive();if (signal?.aborted && error instanceof Error && error.name === 'AbortError') {diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.tsindex 7a1ddd6f53..7ed06a8219 100644--- a/src/core/pglite-engine.ts+++ b/src/core/pglite-engine.ts@@ -7,7 +7,7 @@ import { assertPageRevision } from './page-state/types.ts';import { lockPageKeys as acquirePageKeys } from './page-state/guards.ts';import { readPageSnapshot as readCanonicalPageSnapshot } from './page-state/snapshot.ts';import { createPageVersion } from './page-state/versions.ts';-import { recordRenameAlias } from './page-state/rename-alias.ts';+import { moveSlugBindings, recordRenameAlias } from './page-state/rename-alias.ts';import { composablePgliteTransaction } from './page-state/transactions.ts';import { GRANT_COLUMNS_SQL } from './grants/schema.ts';import type { PageReadScope } from './types.ts';@@ -75,7 +75,7 @@ import { withVectorSettings } from './search/vector-settings.ts';import { PGLITE_SCHEMA_SQL, getPGLiteSchema } from './pglite-schema.ts';import { DEFAULT_EMBEDDING_MODEL, DEFAULT_EMBEDDING_DIMENSIONS } from './ai/defaults.ts';import { readStoredEmbeddingIdentity } from './stored-embedding-identity.ts';-import { DELETE_BATCH_SIZE, TRAVERSE_PATH_ROW_CAP } from './engine-constants.ts';+import { DELETE_BATCH_SIZE, TRAVERSE_PATH_ROW_CAP, TRAVERSE_WALK_ROW_CAP } from './engine-constants.ts';import { PageMissingError } from './engine-errors.ts';import { SOURCE_CONFIG_OBJECT_SQL } from './source-config-sql.ts';import { SAFE_FENCE_CHUNKER_VERSION, bodyWriteChunkVersion, chunkWriteInvalidation, currentTextProjectionFilter, requiresSafeChunks, safeChunksFilter } from './search/safe-chunks.ts';@@ -140,7 +140,6 @@ 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@@ -2458,7 +2457,7 @@ export class PGLiteEngine implements BrainEngine {const innerLimit = Math.min(limit * 3, MAX_SEARCH_LIMIT * 3);// Source-aware ranking (v0.22): see postgres-engine.ts for rationale.- const boostMap = resolveBoostMap();+ const boostMap = opts?.source_boosts ?? resolveBoostMap();const sourceFactorCase = buildSourceFactorCase('p.slug', boostMap, opts?.detail);const hardExcludePrefixes = resolveHardExcludes(opts?.exclude_slug_prefixes, opts?.include_slug_prefixes);const hardExcludeClause = buildHardExcludeClause('p.slug', hardExcludePrefixes);@@ -2609,7 +2608,7 @@ export class PGLiteEngine implements BrainEngine {console.warn(`[gbrain] Warning: search limit clamped from ${opts.limit} to ${MAX_SEARCH_LIMIT}`);}- const boostMap = resolveBoostMap();+ const boostMap = opts?.source_boosts ?? resolveBoostMap();const sourceFactorCase = buildSourceFactorCase('p.slug', boostMap, opts?.detail);const hardExcludePrefixes = resolveHardExcludes(opts?.exclude_slug_prefixes, opts?.include_slug_prefixes);const hardExcludeClause = buildHardExcludeClause('p.slug', hardExcludePrefixes);@@ -2769,7 +2768,7 @@ export class PGLiteEngine implements BrainEngine {// Source-aware ranking applied here too — searchKeywordChunks is the// chunk-grain anchor primitive that two-pass retrieval (Layer 7) uses.- const boostMap = resolveBoostMap();+ const boostMap = opts?.source_boosts ?? resolveBoostMap();const sourceFactorCase = buildSourceFactorCase('p.slug', boostMap, opts?.detail);const hardExcludePrefixes = resolveHardExcludes(opts?.exclude_slug_prefixes, opts?.include_slug_prefixes);const hardExcludeClause = buildHardExcludeClause('p.slug', hardExcludePrefixes);@@ -2860,7 +2859,7 @@ export class PGLiteEngine implements BrainEngine {// HNSW; outer SELECT re-ranks by raw_score * source_factor over the// narrow candidate pool. innerLimit scales with offset to preserve the// pagination contract. See postgres-engine.ts searchVector for rationale.- const boostMap = resolveBoostMap();+ const boostMap = opts?.source_boosts ?? resolveBoostMap();// Outer SELECT references the aliased CTE column. Aliasing the CTE as `hc`// disambiguates the correlated subquery (`te.page_id = hc.page_id`) from// the inner column. Without the alias, an unqualified `page_id` in the@@ -4282,7 +4281,8 @@ export class PGLiteEngine implements BrainEngine {WHERE l2.from_page_id = g.id AND p3.deleted_at IS NULL ${privacy('p3', 'l2')} ${aggScope}),'[]'::jsonb) as links- FROM graph g+ FROM (SELECT DISTINCT id, slug, title, type, depth+ FROM (SELECT id, slug, title, type, depth FROM graph LIMIT ${TRAVERSE_WALK_ROW_CAP}) capped) gORDER BY g.depth, g.slug`,params);@@ -4357,15 +4357,18 @@ export class PGLiteEngine implements BrainEngine {FROM walk wJOIN links l ON l.from_page_id = w.idJOIN pages p2 ON p2.id = l.to_page_id- WHERE w.depth < $2+ WHERE w.depth + 1 < $2AND NOT (p2.id = ANY(w.visited))AND p2.deleted_at IS NULL ${privacy('p2', 'l')}${linkTypeWhere}${stepScope}- )- SELECT w.slug AS from_slug, p2.slug AS to_slug,+ ),+ capped AS (SELECT id, slug, depth FROM walk LIMIT ${TRAVERSE_WALK_ROW_CAP + 1}),+ nodes AS (SELECT DISTINCT id, slug, depth FROM capped)+ SELECT (SELECT count(*) FROM capped) > ${TRAVERSE_WALK_ROW_CAP} AS walk_truncated,+ w.slug AS from_slug, p2.slug AS to_slug,l.link_type, l.context, w.depth + 1 AS depth- FROM walk w+ FROM nodes wJOIN links l ON l.from_page_id = w.idJOIN pages p2 ON p2.id = l.to_page_idWHERE w.depth < $2@@ -4385,15 +4388,18 @@ export class PGLiteEngine implements BrainEngine {FROM walk wJOIN links l ON l.to_page_id = w.idJOIN pages p2 ON p2.id = l.from_page_id- WHERE w.depth < $2+ WHERE w.depth + 1 < $2AND NOT (p2.id = ANY(w.visited))AND p2.deleted_at IS NULL ${privacy('p2', 'l')}${linkTypeWhere}${stepScope}- )- SELECT p2.slug AS from_slug, w.slug AS to_slug,+ ),+ capped AS (SELECT id, slug, depth FROM walk LIMIT ${TRAVERSE_WALK_ROW_CAP + 1}),+ nodes AS (SELECT DISTINCT id, slug, depth FROM capped)+ SELECT (SELECT count(*) FROM capped) > ${TRAVERSE_WALK_ROW_CAP} AS walk_truncated,+ p2.slug AS from_slug, w.slug AS to_slug,l.link_type, l.context, w.depth + 1 AS depth- FROM walk w+ FROM nodes wJOIN links l ON l.to_page_id = w.idJOIN pages p2 ON p2.id = l.from_page_idWHERE w.depth < $2@@ -4415,15 +4421,18 @@ export class PGLiteEngine implements BrainEngine {FROM walk wJOIN links l ON (l.from_page_id = w.id OR l.to_page_id = w.id)JOIN pages p2 ON p2.id = CASE WHEN l.from_page_id = w.id THEN l.to_page_id ELSE l.from_page_id END- WHERE w.depth < $2+ WHERE w.depth + 1 < $2AND NOT (p2.id = ANY(w.visited))AND p2.deleted_at IS NULL ${privacy('p2', 'l')}${linkTypeWhere}${stepScope}- )- SELECT pf.slug AS from_slug, pt.slug AS to_slug,+ ),+ capped AS (SELECT id, depth FROM walk LIMIT ${TRAVERSE_WALK_ROW_CAP + 1}),+ nodes AS (SELECT DISTINCT id, depth FROM capped)+ SELECT (SELECT count(*) FROM capped) > ${TRAVERSE_WALK_ROW_CAP} AS walk_truncated,+ pf.slug AS from_slug, pt.slug AS to_slug,l.link_type, l.context, w.depth + 1 AS depth- FROM walk w+ FROM nodes wJOIN links l ON (l.from_page_id = w.id OR l.to_page_id = w.id)JOIN pages pf ON pf.id = l.from_page_idJOIN pages pt ON pt.id = l.to_page_id@@ -4441,7 +4450,7 @@ export class PGLiteEngine implements BrainEngine {const { rows } = await this.db.query(sql, params);// Row cap: the LIMIT above fetched CAP + 1 rows; the probe row only tells// us the walk overflowed and is dropped with everything past the cap.- const truncated = rows.length > TRAVERSE_PATH_ROW_CAP;+ const truncated = rows.length > TRAVERSE_PATH_ROW_CAP || (rows as Array<{ walk_truncated?: boolean }>).some((r) => r.walk_truncated === true);const bounded = (truncated ? rows.slice(0, TRAVERSE_PATH_ROW_CAP) : rows) as Record<string, unknown>[];// Dedup edges (same from/to/type/depth can appear via multiple visited paths).const seen = new Set<string>();@@ -4567,8 +4576,8 @@ export class PGLiteEngine implements BrainEngine {}// Tags- async addTag(slug: string, tag: string, opts?: { sourceId?: string }): Promise<void> {- return mutatePageTag(this, { sourceId: opts?.sourceId ?? 'default', slug }, tag, true);+ async addTag(slug: string, tag: string, opts?: { sourceId?: string; tagSource?: 'frontmatter' }): Promise<void> {+ return mutatePageTag(this, { sourceId: opts?.sourceId ?? 'default', slug }, tag, true, opts?.tagSource);}async removeTag(slug: string, tag: string, opts?: { sourceId?: string }): Promise<void> {@@ -5826,8 +5835,7 @@ export class PGLiteEngine implements BrainEngine {);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]);+ await moveSlugBindings(tx, 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.diff --git a/src/core/pglite-engine/facts.ts b/src/core/pglite-engine/facts.tsindex 6b75ec0171..54bdfaaeab 100644--- a/src/core/pglite-engine/facts.ts+++ b/src/core/pglite-engine/facts.ts@@ -10,7 +10,7 @@ import type {} from '../engine.ts';import { MAX_SEARCH_LIMIT, clampSearchLimit } from '../engine.ts';import { AUDIT_ROW_SOURCES } from '../facts/audit-sources.ts';-import { resolveSupersededByRow, isInt4RowRef, type SupersedeTarget } from '../facts/supersede-resolve.ts';+import { resolveSupersededByRow, isInt4RowRef, supersessionChainOf, type SupersedeTarget } from '../facts/supersede-resolve.ts';import { escapeLikePattern } from '../cjk.ts';/** Narrow slice of PGLiteEngine the facts operations use. */@@ -256,11 +256,14 @@ export async function insertFacts(// above is visible. Keyed on (source_id, source_markdown_slug,// row_num) — the v51 unique index — so a reference also resolves// against a target that already existed before this batch. A target- // whose `expired_at` is set is itself struck (chain) and rejected.+ // whose `expired_at` is set resolves only when it is itself superseded+ // (an A -> B -> C chain), declared in this batch or already linked in+ // the DB.for (let i = 0; i < rows.length; i++) {const targetRow = rows[i].superseded_by_row;if (targetRow === undefined || rowIds[i] === null) continue;const slug = rows[i].source_markdown_slug;+ const chain = supersessionChainOf(rows, slug);// Only look up an int4-safe target. An absurd `#N` (11+ digits)// would overflow the `row_num` comparison and abort the cycle;// skipping the lookup leaves `target` undefined, so@@ -268,9 +271,10 @@ export async function insertFacts(// warning) instead of throwing.let target: SupersedeTarget | undefined;if (isInt4RowRef(targetRow)) {- const found = await tx.query<{ id: number; expired_at: Date | string | null }>(- `SELECT id, expired_at FROM facts- WHERE source_id = $1 AND source_markdown_slug = $2 AND row_num = $3+ const found = await tx.query<{ id: number; expired_at: Date | string | null; next_row: number | null }>(+ `SELECT f.id, f.expired_at, n.row_num AS next_row FROM facts f+ LEFT JOIN facts n ON n.id = f.superseded_by+ WHERE f.source_id = $1 AND f.source_markdown_slug = $2 AND f.row_num = $3LIMIT 1`,[ctx.source_id, slug, targetRow],);@@ -278,8 +282,9 @@ export async function insertFacts(target = hit? { id: Number(hit.id), struck: hit.expired_at != null }: undefined;+ if (hit?.next_row != null && !chain.has(targetRow)) chain.set(targetRow, Number(hit.next_row));}- const { superseded_by, warning } = resolveSupersededByRow(rows[i].row_num, targetRow, target, slug);+ const { superseded_by, warning } = resolveSupersededByRow(rows[i].row_num, targetRow, target, slug, chain);if (warning) warnings.push(warning);if (superseded_by !== null) {await tx.query(`UPDATE facts SET superseded_by = $1 WHERE id = $2`, [superseded_by, rowIds[i]]);diff --git a/src/core/pglite-schema.ts b/src/core/pglite-schema.tsindex 5f80868f6c..1f9eaf8351 100644--- a/src/core/pglite-schema.ts+++ b/src/core/pglite-schema.ts@@ -331,6 +331,8 @@ CREATE TABLE IF NOT EXISTS tags (id SERIAL PRIMARY KEY,page_id INTEGER NOT NULL REFERENCES pages(id) ON DELETE CASCADE,tag TEXT NOT NULL,+ -- 'frontmatter' (import-owned, deleted when it leaves the frontmatter), 'added', or NULL (legacy).+ tag_source TEXT,UNIQUE(page_id, tag));diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex 564ba9abe3..4be1934191 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -6,7 +6,7 @@ import { assertPageRevision } from './page-state/types.ts';import { lockPageKeys as acquirePageKeys } from './page-state/guards.ts';import { readPageSnapshot as readCanonicalPageSnapshot } from './page-state/snapshot.ts';import { createPageVersion } from './page-state/versions.ts';-import { recordRenameAlias } from './page-state/rename-alias.ts';+import { moveSlugBindings, recordRenameAlias } from './page-state/rename-alias.ts';import { composablePostgresTransaction } from './page-state/transactions.ts';import type { PageReadScope } from './types.ts';import type { PageReadPolicy } from './types.ts';@@ -107,7 +107,7 @@ import { privatePagesFilterFragment, privateSnapshotFilterFragment, privateLinkOimport { unverifiedExtractionFragment } from './extraction-review.ts';import { DEFAULT_EMBEDDING_MODEL, DEFAULT_EMBEDDING_DIMENSIONS } from './ai/defaults.ts';import { readStoredEmbeddingIdentity } from './stored-embedding-identity.ts';-import { DELETE_BATCH_SIZE, TRAVERSE_PATH_ROW_CAP } from './engine-constants.ts';+import { DELETE_BATCH_SIZE, TRAVERSE_PATH_ROW_CAP, TRAVERSE_WALK_ROW_CAP } from './engine-constants.ts';import { PageMissingError } from './engine-errors.ts';import { SOURCE_CONFIG_OBJECT_SQL } from './source-config-sql.ts';import { shouldExcludeFromOrphanReporting, loadOrphanPolicyOverrides } from './orphan-policy.ts';@@ -127,7 +127,6 @@ 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, "''");@@ -1443,7 +1442,7 @@ export class PostgresEngine implements BrainEngine {// (test/, attachments/, .raw/ by default) filter at the chunk-rank stage// so they never enter the candidate set. (archive/ is demoted, not// excluded — issue #1777.)- const boostMap = resolveBoostMap();+ const boostMap = opts?.source_boosts ?? resolveBoostMap();const sourceFactorCase = buildSourceFactorCase('p.slug', boostMap, opts?.detail);const hardExcludePrefixes = resolveHardExcludes(opts?.exclude_slug_prefixes, opts?.include_slug_prefixes);const hardExcludeClause = buildHardExcludeClause('p.slug', hardExcludePrefixes);@@ -1640,7 +1639,7 @@ export class PostgresEngine implements BrainEngine {console.warn(`[gbrain] Warning: search limit clamped from ${opts.limit} to ${MAX_SEARCH_LIMIT}`);}- const boostMap = resolveBoostMap();+ const boostMap = opts?.source_boosts ?? resolveBoostMap();const sourceFactorCase = buildSourceFactorCase('p.slug', boostMap, opts?.detail);const hardExcludePrefixes = resolveHardExcludes(opts?.exclude_slug_prefixes, opts?.include_slug_prefixes);const hardExcludeClause = buildHardExcludeClause('p.slug', hardExcludePrefixes);@@ -1792,7 +1791,7 @@ export class PostgresEngine implements BrainEngine {// chunk-grain anchor primitive that two-pass retrieval (Layer 7) uses,// so curated-vs-bulk dampening should affect the anchor pool. Same// detail-gate, same hard-exclude behavior as searchKeyword.- const boostMap = resolveBoostMap();+ const boostMap = opts?.source_boosts ?? resolveBoostMap();const sourceFactorCase = buildSourceFactorCase('p.slug', boostMap, opts?.detail);const hardExcludePrefixes = resolveHardExcludes(opts?.exclude_slug_prefixes, opts?.include_slug_prefixes);const hardExcludeClause = buildHardExcludeClause('p.slug', hardExcludePrefixes);@@ -1953,7 +1952,7 @@ export class PostgresEngine implements BrainEngine {//// innerLimit scales with offset to preserve the pagination contract:// a fixed cap of 100 would silently empty offset > 100.- const boostMap = resolveBoostMap();+ const boostMap = opts?.source_boosts ?? resolveBoostMap();// issue #160: the guard predicate is projected as `unverified_stub` in// hnsw_candidates (frontmatter isn't otherwise available at re-rank), so// unverified auto-extracted stubs get factor 1.0, not the people/ 1.2x.@@ -3476,7 +3475,8 @@ export class PostgresEngine implements BrainEngine {WHERE l2.from_page_id = g.id AND p3.deleted_at IS NULL ${privacy('p3', 'l2')} ${aggScope}),'[]'::jsonb) as links- FROM graph g+ FROM (SELECT DISTINCT id, slug, title, type, depth+ FROM (SELECT id, slug, title, type, depth FROM graph LIMIT ${TRAVERSE_WALK_ROW_CAP}) capped) gORDER BY g.depth, g.slug`;@@ -3555,15 +3555,18 @@ export class PostgresEngine implements BrainEngine {FROM walk wJOIN links l ON l.from_page_id = w.idJOIN pages p2 ON p2.id = l.to_page_id- WHERE w.depth < ${depth}+ WHERE w.depth + 1 < ${depth}AND NOT (p2.id = ANY(w.visited))AND p2.deleted_at IS NULL ${privacy('p2', 'l')}AND (${!linkTypeMatches} OR l.link_type = ${linkType ?? ''})${stepScope}- )- SELECT w.slug as from_slug, p2.slug as to_slug,+ ),+ capped AS (SELECT id, slug, depth FROM walk LIMIT ${TRAVERSE_WALK_ROW_CAP + 1}),+ nodes AS (SELECT DISTINCT id, slug, depth FROM capped)+ SELECT (SELECT count(*) FROM capped) > ${TRAVERSE_WALK_ROW_CAP} AS walk_truncated,+ w.slug as from_slug, p2.slug as to_slug,l.link_type, l.context, w.depth + 1 as depth- FROM walk w+ FROM nodes wJOIN links l ON l.from_page_id = w.idJOIN pages p2 ON p2.id = l.to_page_idWHERE w.depth < ${depth}@@ -3583,15 +3586,18 @@ export class PostgresEngine implements BrainEngine {FROM walk wJOIN links l ON l.to_page_id = w.idJOIN pages p2 ON p2.id = l.from_page_id- WHERE w.depth < ${depth}+ WHERE w.depth + 1 < ${depth}AND NOT (p2.id = ANY(w.visited))AND p2.deleted_at IS NULL ${privacy('p2', 'l')}AND (${!linkTypeMatches} OR l.link_type = ${linkType ?? ''})${stepScope}- )- SELECT p2.slug as from_slug, w.slug as to_slug,+ ),+ capped AS (SELECT id, slug, depth FROM walk LIMIT ${TRAVERSE_WALK_ROW_CAP + 1}),+ nodes AS (SELECT DISTINCT id, slug, depth FROM capped)+ SELECT (SELECT count(*) FROM capped) > ${TRAVERSE_WALK_ROW_CAP} AS walk_truncated,+ p2.slug as from_slug, w.slug as to_slug,l.link_type, l.context, w.depth + 1 as depth- FROM walk w+ FROM nodes wJOIN links l ON l.to_page_id = w.idJOIN pages p2 ON p2.id = l.from_page_idWHERE w.depth < ${depth}@@ -3611,15 +3617,18 @@ export class PostgresEngine implements BrainEngine {FROM walk wJOIN links l ON (l.from_page_id = w.id OR l.to_page_id = w.id)JOIN pages p2 ON p2.id = CASE WHEN l.from_page_id = w.id THEN l.to_page_id ELSE l.from_page_id END- WHERE w.depth < ${depth}+ WHERE w.depth + 1 < ${depth}AND NOT (p2.id = ANY(w.visited))AND p2.deleted_at IS NULL ${privacy('p2', 'l')}AND (${!linkTypeMatches} OR l.link_type = ${linkType ?? ''})${stepScope}- )- SELECT pf.slug as from_slug, pt.slug as to_slug,+ ),+ capped AS (SELECT id, depth FROM walk LIMIT ${TRAVERSE_WALK_ROW_CAP + 1}),+ nodes AS (SELECT DISTINCT id, depth FROM capped)+ SELECT (SELECT count(*) FROM capped) > ${TRAVERSE_WALK_ROW_CAP} AS walk_truncated,+ pf.slug as from_slug, pt.slug as to_slug,l.link_type, l.context, w.depth + 1 as depth- FROM walk w+ FROM nodes wJOIN links l ON (l.from_page_id = w.id OR l.to_page_id = w.id)JOIN pages pf ON pf.id = l.from_page_idJOIN pages pt ON pt.id = l.to_page_id@@ -3636,7 +3645,7 @@ export class PostgresEngine implements BrainEngine {// Row cap: the LIMIT above fetched CAP + 1 rows; the probe row only tells// us the walk overflowed and is dropped with everything past the cap.- const truncated = rows.length > TRAVERSE_PATH_ROW_CAP;+ const truncated = rows.length > TRAVERSE_PATH_ROW_CAP || (rows as Array<{ walk_truncated?: boolean }>).some((r) => r.walk_truncated === true);const bounded = (truncated ? rows.slice(0, TRAVERSE_PATH_ROW_CAP) : rows) as Record<string, unknown>[];// Dedup edges (same edge can appear via multiple visited paths).const seen = new Set<string>();@@ -3759,8 +3768,8 @@ export class PostgresEngine implements BrainEngine {}// Tags- async addTag(slug: string, tag: string, opts?: { sourceId?: string }): Promise<void> {- return mutatePageTag(this, { sourceId: opts?.sourceId ?? 'default', slug }, tag, true);+ async addTag(slug: string, tag: string, opts?: { sourceId?: string; tagSource?: 'frontmatter' }): Promise<void> {+ return mutatePageTag(this, { sourceId: opts?.sourceId ?? 'default', slug }, tag, true, opts?.tagSource);}async removeTag(slug: string, tag: string, opts?: { sourceId?: string }): Promise<void> {@@ -5041,8 +5050,7 @@ export class PostgresEngine implements BrainEngine {);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]);+ await moveSlugBindings(tx, 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.diff --git a/src/core/postgres-engine/facts.ts b/src/core/postgres-engine/facts.tsindex bb00628f62..7cd929e414 100644--- a/src/core/postgres-engine/facts.ts+++ b/src/core/postgres-engine/facts.ts@@ -15,7 +15,7 @@ import type {import { MAX_SEARCH_LIMIT, clampSearchLimit } from '../engine.ts';import { tryParseEmbedding } from '../utils.ts';import { AUDIT_ROW_SOURCES } from '../facts/audit-sources.ts';-import { resolveSupersededByRow, isInt4RowRef, type SupersedeTarget } from '../facts/supersede-resolve.ts';+import { resolveSupersededByRow, isInt4RowRef, supersessionChainOf, type SupersedeTarget } from '../facts/supersede-resolve.ts';import { escapeLikePattern } from '../cjk.ts';/**@@ -242,11 +242,14 @@ export async function insertFacts(// above is visible. Keyed on (source_id, source_markdown_slug,// row_num) — the v51 unique index — so a reference also resolves// against a target that already existed before this batch. A target- // whose `expired_at` is set is itself struck (chain) and rejected.+ // whose `expired_at` is set resolves only when it is itself superseded+ // (an A -> B -> C chain), declared in this batch or already linked in+ // the DB.for (let i = 0; i < rows.length; i++) {const targetRow = rows[i].superseded_by_row;if (targetRow === undefined || rowIds[i] === null) continue;const slug = rows[i].source_markdown_slug;+ const chain = supersessionChainOf(rows, slug);// Only look up an int4-safe target. An absurd `#N` (11+ digits)// would overflow the `row_num` comparison and abort the cycle;// skipping the lookup leaves `target` undefined, so@@ -254,18 +257,20 @@ export async function insertFacts(// warning) instead of throwing.let target: SupersedeTarget | undefined;if (isInt4RowRef(targetRow)) {- const found = await tx<Array<{ id: number; expired_at: Date | null }>>`- SELECT id, expired_at FROM facts- WHERE source_id = ${ctx.source_id}- AND source_markdown_slug = ${slug}- AND row_num = ${targetRow}+ const found = await tx<Array<{ id: number; expired_at: Date | null; next_row: number | null }>>`+ SELECT f.id, f.expired_at, n.row_num AS next_row FROM facts f+ LEFT JOIN facts n ON n.id = f.superseded_by+ WHERE f.source_id = ${ctx.source_id}+ AND f.source_markdown_slug = ${slug}+ AND f.row_num = ${targetRow}LIMIT 1`;target = found[0]? { id: Number(found[0].id), struck: found[0].expired_at != null }: undefined;+ if (found[0]?.next_row != null && !chain.has(targetRow)) chain.set(targetRow, Number(found[0].next_row));}- const { superseded_by, warning } = resolveSupersededByRow(rows[i].row_num, targetRow, target, slug);+ const { superseded_by, warning } = resolveSupersededByRow(rows[i].row_num, targetRow, target, slug, chain);if (warning) warnings.push(warning);if (superseded_by !== null) {await tx`UPDATE facts SET superseded_by = ${superseded_by} WHERE id = ${rowIds[i]}`;diff --git a/src/core/repair/timeline.ts b/src/core/repair/timeline.tsindex 0aff6dc353..88b801937a 100644--- a/src/core/repair/timeline.ts+++ b/src/core/repair/timeline.ts@@ -3,18 +3,28 @@* pages that are never written again. Each page is re-published with its own* current body through a revision-bound `put_page`; preparation writes every* round-trippable bullet-less row back into the page as a marked bullet.- * Rows that cannot round-trip are kept and reported, never deleted.+ * Rows that cannot round-trip are kept and reported, never deleted. Rows an+ * earlier stored version of the page produced and its current text dropped+ * are removals, not history (`timeline_orphans`, `extract timeline+ * --prune-orphans`), so they are not counted or materialized here.*/import type { BrainEngine } from '../engine.ts';import { serializePageToMarkdown } from '../markdown.ts';import { pendingTimelineRows } from '../persistence/canonical-projections.ts';import { submitPageMutation } from '../persistence/page-mutations.ts';+import { retractRemovedTimelineEntries } from '../timeline-extract.ts';import { repairRequestId, type RepairHandler, type RepairItem, type RepairScope, type RepairCursor } from './core.ts';interface TimelinePage { id: number; source_id: string; slug: string; compiled_truth: string; timeline: string | null }const BATCH = 200;+/** Timeline rows of the page that an earlier stored version produced and its current text no longer does. */+async function removedRowIds(engine: BrainEngine, page: TimelinePage): Promise<Set<number>> {+ const removed = await retractRemovedTimelineEntries(engine, page.slug, page.source_id, `${page.compiled_truth}\n${page.timeline ?? ''}`, { dryRun: true });+ return new Set(removed.map(row => Number(row.id)));+}+/*** Pages carrying non-event timeline rows, in id order after `afterId`, each* classified exactly. `budget` caps the pages inspected (doctor's bound).@@ -35,7 +45,7 @@ export async function scanTimelineHistory(engine: BrainEngine, sourceIds: string}inspected++;cursor = page.id;- const counts = await pendingTimelineRows(engine, { ...page, timeline: page.timeline ?? '' });+ const counts = await pendingTimelineRows(engine, { ...page, timeline: page.timeline ?? '' }, await removedRowIds(engine, page));if (counts.materializable || counts.unrenderable) pages.push({ ...page, ...counts });}if (batch.length < BATCH) return { pages, inspected, truncated };@@ -56,7 +66,7 @@ export const timelineRepair: RepairHandler = {async apply(ctx, item) {const snapshot = await ctx.engine.readPageSnapshot(item.slug, { sourceId: item.source_id });if (!snapshot) return false;- const counts = await pendingTimelineRows(ctx.engine, { ...snapshot.page, timeline: snapshot.page.timeline ?? '' });+ const counts = await pendingTimelineRows(ctx.engine, { ...snapshot.page, timeline: snapshot.page.timeline ?? '' }, await removedRowIds(ctx.engine, snapshot.page));if (!counts.materializable) return false;await submitPageMutation(ctx, { operation: 'put_page', params: { slug: item.slug, source_id: item.source_id,content: serializePageToMarkdown(snapshot.page, snapshot.tags), expected_revision: snapshot.revision,diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.tsindex 8feba4ce91..736001e7cd 100644--- a/src/core/schema-embedded.generated.ts+++ b/src/core/schema-embedded.generated.ts@@ -517,6 +517,8 @@ CREATE TABLE IF NOT EXISTS tags (id SERIAL PRIMARY KEY,page_id INTEGER NOT NULL REFERENCES pages(id) ON DELETE CASCADE,tag TEXT NOT NULL,+ -- 'frontmatter' (import-owned, deleted when it leaves the frontmatter), 'added', or NULL (legacy).+ tag_source TEXT,UNIQUE(page_id, tag));diff --git a/src/core/search/alias-hop.ts b/src/core/search/alias-hop.tsnew file mode 100644index 0000000000..a854f9616f--- /dev/null+++ b/src/core/search/alias-hop.ts@@ -0,0 +1,209 @@+/**+ * Post-rerank identity injection by declared alias (T3 alias hop) plus the+ * opt-in single-token hop (#5428), and the exclude contract shared with the+ * exact-lookup tier. Split out of hybrid.ts; hybrid.ts re-exports the API.+ */++import type { SearchResult } from '../types.ts';+import { sanitizeRemoteBody } from '../remote-body.ts';+import { isIdentityEntity } from '../entities/resolve.ts';+import { normalizeAlias } from './alias-normalize.ts';+import { isPrivatePage } from './private-visibility.ts';++// T3 — free-text alias hop tuning.+const ALIAS_HOP_PRESENT_BOOST = 1.10; // bounded boost when canonical already in results+const MAX_ALIAS_QUERY_TOKENS = 6; // skip long queries (clearly not a chosen name)+const MAX_ALIAS_INJECT = 3; // cap injected pages per query (collision safety)++/**+ * T3 — free-text alias hop (retrieval-maxpool incident, the named-thing fix).+ *+ * When the normalized query EXACTLY matches a page's declared alias+ * ("Hall of Light" / "明堂" -> the Mingtang page), make sure that page is in+ * the result set: boost it if already present, inject it at top-of-organic ++ * epsilon if absent. This is the only layer that bridges true synonyms with+ * zero surface overlap — neither max-pool nor title-boost can.+ *+ * Precision guards (Codex#7/#10):+ * - FULL normalized-query exact match only (not substring / not n-grams) —+ * "light" won't fire unless the whole query normalizes to a stored alias.+ * - skip queries longer than MAX_ALIAS_QUERY_TOKENS (clearly prose, not a name).+ * - bounded: present-boost is 1.10x; inject score is top-of-organic + ε,+ * never an absolute 1.0 (D3 — aliases are not a ranking sledgehammer).+ * - order-preserving: injected rows go to the front and a boosted row only+ * climbs past lower-scored rows directly above it; every other row keeps+ * its input (reranked) order.+ * - collisions (two pages claim one alias): deterministic alpha order, capped.+ *+ * Fail-open: pre-v110 brains (no page_aliases table) and any lookup error+ * degrade to the input unchanged (D9). Returns a NEW array; caller re-slices.+ */+/**+ * Read-policy + exclude contract shared by the post-arm identity injections+ * (alias hop, exact-lookup tier). They add pages the engine arms never+ * filtered, so they re-apply the arms' exact-slug and prefix excludes.+ * `excludeSlugPrefixes` is the RESOLVED list (defaults + GBRAIN_SEARCH_EXCLUDE+ * + per-call, minus include_slug_prefixes — see resolveHardExcludes).+ */+export interface IdentityTierOpts {+ sourceId?: string;+ sourceIds?: string[];+ excludePrivate?: boolean;+ requireSafeChunks?: boolean;+ excludeSlugs?: string[];+ excludeSlugPrefixes?: string[];+}++/** True when an identity injection must skip `slug` under the caller's excludes. */+export function isExcludedIdentity(slug: string, opts: Pick<IdentityTierOpts, 'excludeSlugs' | 'excludeSlugPrefixes'>): boolean {+ if (opts.excludeSlugs?.includes(slug)) return true;+ return opts.excludeSlugPrefixes?.some((p) => slug.startsWith(p)) ?? false;+}++export async function applyAliasHop(+ engine: import('../engine.ts').BrainEngine,+ results: SearchResult[],+ query: string,+ opts: IdentityTierOpts & { tokenHop?: boolean },+): Promise<SearchResult[]> {+ if (!query) return results;+ const qNorm = normalizeAlias(query);+ if (!qNorm || qNorm.split(' ').length > MAX_ALIAS_QUERY_TOKENS) return results;+ const tokens = opts.tokenHop+ ? [...new Set(qNorm.split(' '))].filter((t) => t.length >= 2 && t !== qNorm)+ : [];++ let aliasMap: Map<string, Array<{ slug: string; source_id: string }>>;+ try {+ aliasMap = await engine.resolveAliases([qNorm, ...tokens], opts);+ } catch {+ return results; // pre-v110 table-missing OR transient error -> fail-open+ }+ const refs = aliasMap.get(qNorm);+ if (!refs || refs.length === 0) {+ return tokens.length > 0 ? applyAliasTokenHop(engine, results, tokens, aliasMap, opts) : results;+ }++ // Deterministic + capped. Source-scoped: each canonical is a (source_id, slug)+ // pair so a federated caller boosts/injects the RIGHT source's page, never+ // collapsing or cross-injecting (P0 source-isolation contract).+ const ordered = [...refs]+ .filter(ref => !isExcludedIdentity(ref.slug, opts))+ .sort((a, b) => (a.source_id === b.source_id ? a.slug.localeCompare(b.slug) : a.source_id.localeCompare(b.source_id)))+ .slice(0, MAX_ALIAS_INJECT);+ const out = [...results];+ let injectScore = topOrganicScore(out);++ for (const ref of ordered) {+ let idx = out.findIndex(r => r.slug === ref.slug && (r.source_id ?? 'default') === ref.source_id);+ if (idx >= 0) {+ const hit = out[idx];+ if (Number.isFinite(hit.score)) hit.score *= ALIAS_HOP_PRESENT_BOOST;+ hit.alias_hit = true;+ // Bubble the boosted row past lower-scored rows directly above it; never+ // re-sort the list, which would discard a reranked order (post-rerank+ // `score` is still the fusion score, not the rerank order).+ while (idx > 0 && out[idx - 1].score < hit.score) {+ out[idx] = out[idx - 1];+ idx--;+ }+ out[idx] = hit;+ continue;+ }+ const page = await fetchAliasCanonical(engine, ref, opts);+ if (!page) continue;+ injectScore += 1e-6;+ out.unshift(aliasInjectedRow(page, ref, injectScore));+ }+ return out;+}++/** Cap on pages the single-token alias hop moves or injects per query. */+const MAX_ALIAS_TOKEN_HOP = 2;++/**+ * #5428 — opt-in single-token alias hop (`tokenHop`). A query token that is+ * the alias of exactly ONE page, and that page is a person/company identity+ * page (`isIdentityEntity`), moves that page to the front — or injects it+ * when absent. Ambiguous tokens and excluded pages are skipped; at most+ * MAX_ALIAS_TOKEN_HOP pages; every other row keeps its input order.+ */+async function applyAliasTokenHop(+ engine: import('../engine.ts').BrainEngine,+ results: SearchResult[],+ tokens: string[],+ aliasMap: Map<string, Array<{ slug: string; source_id: string }>>,+ opts: IdentityTierOpts,+): Promise<SearchResult[]> {+ const out = [...results];+ let injectScore = topOrganicScore(out);+ const hopped = new Set<string>();+ for (const token of tokens) {+ if (hopped.size >= MAX_ALIAS_TOKEN_HOP) break;+ const refs = (aliasMap.get(token) ?? []).filter((ref) => !isExcludedIdentity(ref.slug, opts));+ if (refs.length !== 1) continue;+ const ref = refs[0];+ const key = `${ref.source_id}:${ref.slug}`;+ if (hopped.has(key)) continue;+ injectScore += 1e-6;+ const idx = out.findIndex((r) => r.slug === ref.slug && (r.source_id ?? 'default') === ref.source_id);+ if (idx >= 0) {+ const hit = out[idx];+ if (!isIdentityEntity(hit.slug, hit.type)) continue;+ out.splice(idx, 1);+ out.unshift({ ...hit, score: injectScore, alias_hit: true });+ hopped.add(key);+ continue;+ }+ const page = await fetchAliasCanonical(engine, ref, opts);+ if (!page || !isIdentityEntity(page.slug, page.type)) continue;+ out.unshift(aliasInjectedRow(page, ref, injectScore));+ hopped.add(key);+ }+ return out;+}++function topOrganicScore(results: SearchResult[]): number {+ const top = results.reduce((m, r) => (Number.isFinite(r.score) && r.score > m ? r.score : m), 0);+ return top > 0 ? top : 1.0;+}++/** Fetch an alias canonical in its OWN source, re-applying the private predicate. */+async function fetchAliasCanonical(+ engine: import('../engine.ts').BrainEngine,+ ref: { slug: string; source_id: string },+ opts: IdentityTierOpts,+): Promise<import('../types.ts').Page | null> {+ let page;+ try {+ page = await engine.getPage(ref.slug, { sourceId: ref.source_id, excludePrivate: opts.excludePrivate });+ } catch {+ return null;+ }+ if (!page) return null;+ // #4352 — the alias inject path bypasses the engines' SQL visibility+ // clause (getPage, not search); re-apply the private predicate here so+ // an untrusted caller can't hop into a `visibility: private` page.+ if (opts.excludePrivate && isPrivatePage(page)) return null;+ return page;+}++function aliasInjectedRow(page: import('../types.ts').Page, ref: { source_id: string }, score: number): SearchResult {+ return {+ // #2339-sibling: include page_id. The `as SearchResult` cast hid its+ // absence, so any consumer reading page_id off an alias-injected result got+ // undefined — e.g. listActiveTakesForPages bound undefined/NaN into+ // ANY($1::int[]) and crashed the contradiction probe on real Postgres.+ page_id: page.id,+ slug: page.slug,+ title: page.title,+ type: page.type,+ source_id: page.source_id ?? ref.source_id,+ chunk_text: sanitizeRemoteBody(page.compiled_truth ?? '').slice(0, 200),+ chunk_index: 0,+ chunk_id: 0,+ score,+ base_score: score,+ alias_hit: true,+ } as SearchResult;+}diff --git a/src/core/search/exact-lookup.ts b/src/core/search/exact-lookup.tsindex fabb7bd16e..1d23732add 100644--- a/src/core/search/exact-lookup.ts+++ b/src/core/search/exact-lookup.ts@@ -38,6 +38,7 @@ import type { SearchResult, PageReadPolicy } from '../types.ts';import { normalizeAlias } from './alias-normalize.ts';import { isLookupShapedQuery } from './query-intent.ts';import { applySupersedeDownrank } from './hybrid.ts';+import { isExcludedIdentity } from './alias-hop.ts';/** Cap on tier injections per query (mirrors the alias hop's discipline). */export const MAX_EXACT_LOOKUP_INJECT = 3;@@ -70,6 +71,8 @@ export interface ExactLookupOpts extends PageReadPolicy {type?: string;types?: string[];excludeSlugs?: string[];+ /** Resolved prefix excludes (see IdentityTierOpts in hybrid.ts). */+ excludeSlugPrefixes?: string[];}/** Max distinct sources probed for a slug-shaped query on a federated call. */@@ -92,14 +95,13 @@ export async function structuralExactLookup(const seen = new Set<string>();// #4480 — mirror the scored arms' shape filters so the tier can never// inject a page the caller explicitly filtered out.- const excluded = new Set(opts.excludeSlugs ?? []);const typeGate = (t: string | undefined | null): boolean => {if (opts.type && t !== opts.type) return false;if (opts.types && opts.types.length > 0 && (t == null || !opts.types.includes(t))) return false;return true;};const push = (r: SearchResult) => {- if (excluded.has(r.slug)) return;+ if (isExcludedIdentity(r.slug, opts)) return;if (!typeGate(r.type)) return;const key = `${r.source_id ?? 'default'}::${r.slug}`;if (seen.has(key)) return;diff --git a/src/core/search/hybrid.ts b/src/core/search/hybrid.tsindex a674f094a7..6bf0810bda 100644--- a/src/core/search/hybrid.ts+++ b/src/core/search/hybrid.ts@@ -9,7 +9,6 @@* Cosine re-score: blend 0.7*rrf + 0.3*cosine for query-specific ranking*/-import { sanitizeRemoteBody } from '../remote-body.ts';import type { BrainEngine } from '../engine.ts';import { MAX_SEARCH_LIMIT, clampSearchLimit } from '../engine.ts';// Type-only (erased at compile time — mode.ts stays a runtime dynamic import@@ -33,7 +32,9 @@ import { embed, embedQuery } from '../embedding.ts';import { registerBackgroundWorkDrainer } from '../background-work.ts';import { isDbAccessFailure } from '../pg-access-classify.ts';import { resolveEmbeddingColumn, isCacheSafe } from './embedding-column.ts';-import { resolveHardExcludes } from './source-boost.ts';+import { resolveBoostMap, resolveHardExcludes } from './source-boost.ts';+import { applyAliasHop, isExcludedIdentity, type IdentityTierOpts } from './alias-hop.ts';+export { applyAliasHop, isExcludedIdentity, type IdentityTierOpts };import {resolveAdaptiveReturn,applyAdaptiveReturn,@@ -66,9 +67,8 @@ import {type VectorArm,type FusionListEntry,} from './fusion-lists.ts';-import { normalizeAlias } from './alias-normalize.ts';import { stampEvidence, markKeywordHits } from './evidence.ts';-import { applyExactLookupTier } from './exact-lookup.ts';+import { applyExactLookupTier, type ExactLookupOpts } from './exact-lookup.ts';import { pinRelationalRows, normalizeRelationalRerankPin, type RelationalRerankPinDecision } from './relational-rerank-pin.ts';import { normalizeKeywordArmConfidenceFloor, type KeywordArmConfidenceDecision } from './arm-confidence.ts';import { decideMetadataBoosts, lexicalArmsVoted, normalizeMetadataBoostGate, type MetadataBoostGate } from './metadata-boost-gate.ts';@@ -77,12 +77,12 @@ import { expandAnchors, hydrateChunks } from './two-pass.ts';import { enforceTokenBudget, searchSalvageEnabled, type TokenBudgetMeta } from './token-budget.ts';import { warnOncePerProcess } from '../utils.ts';import { recordSearchTelemetry } from './telemetry.ts';-import { isPrivatePage } from './private-visibility.ts';import {weightsForIntent,effectiveRrfK,applyExactMatchBoost,applyAliasMentionBoost,+ applyTitleMentionBoost,} from './intent-weights.ts';import {SemanticQueryCache,@@ -891,116 +891,13 @@ async function applyAliasResolvedBoost(}}-// T3 — free-text alias hop tuning.-const ALIAS_HOP_PRESENT_BOOST = 1.10; // bounded boost when canonical already in results-const MAX_ALIAS_QUERY_TOKENS = 6; // skip long queries (clearly not a chosen name)-const MAX_ALIAS_INJECT = 3; // cap injected pages per query (collision safety)--/**- * T3 — free-text alias hop (retrieval-maxpool incident, the named-thing fix).- *- * When the normalized query EXACTLY matches a page's declared alias- * ("Hall of Light" / "明堂" -> the Mingtang page), make sure that page is in- * the result set: boost it if already present, inject it at top-of-organic +- * epsilon if absent. This is the only layer that bridges true synonyms with- * zero surface overlap — neither max-pool nor title-boost can.- *- * Precision guards (Codex#7/#10):- * - FULL normalized-query exact match only (not substring / not n-grams) —- * "light" won't fire unless the whole query normalizes to a stored alias.- * - skip queries longer than MAX_ALIAS_QUERY_TOKENS (clearly prose, not a name).- * - bounded: present-boost is 1.10x; inject score is top-of-organic + ε,- * never an absolute 1.0 (D3 — aliases are not a ranking sledgehammer).- * - order-preserving: injected rows go to the front and a boosted row only- * climbs past lower-scored rows directly above it; every other row keeps- * its input (reranked) order.- * - collisions (two pages claim one alias): deterministic alpha order, capped.- *- * Fail-open: pre-v110 brains (no page_aliases table) and any lookup error- * degrade to the input unchanged (D9). Returns a NEW array; caller re-slices.- */-export async function applyAliasHop(- engine: import('../engine.ts').BrainEngine,- results: SearchResult[],- query: string,- opts: { sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean; requireSafeChunks?: boolean; excludeSlugs?: string[] },-): Promise<SearchResult[]> {- if (!query) return results;- const qNorm = normalizeAlias(query);- if (!qNorm || qNorm.split(' ').length > MAX_ALIAS_QUERY_TOKENS) return results;-- let aliasMap: Map<string, Array<{ slug: string; source_id: string }>>;- try {- aliasMap = await engine.resolveAliases([qNorm], opts);- } catch {- return results; // pre-v110 table-missing OR transient error -> fail-open- }- const refs = aliasMap.get(qNorm);- if (!refs || refs.length === 0) return results;-- // Deterministic + capped. Source-scoped: each canonical is a (source_id, slug)- // pair so a federated caller boosts/injects the RIGHT source's page, never- // collapsing or cross-injecting (P0 source-isolation contract).- const ordered = [...refs]- .filter(ref => !opts.excludeSlugs?.includes(ref.slug))- .sort((a, b) => (a.source_id === b.source_id ? a.slug.localeCompare(b.slug) : a.source_id.localeCompare(b.source_id)))- .slice(0, MAX_ALIAS_INJECT);- const out = [...results];- const topScore = out.reduce((m, r) => (Number.isFinite(r.score) && r.score > m ? r.score : m), 0);- let injectScore = topScore > 0 ? topScore : 1.0;-- for (const ref of ordered) {- let idx = out.findIndex(r => r.slug === ref.slug && (r.source_id ?? 'default') === ref.source_id);- if (idx >= 0) {- const hit = out[idx];- if (Number.isFinite(hit.score)) hit.score *= ALIAS_HOP_PRESENT_BOOST;- hit.alias_hit = true;- // Bubble the boosted row past lower-scored rows directly above it; never- // re-sort the list, which would discard a reranked order (post-rerank- // `score` is still the fusion score, not the rerank order).- while (idx > 0 && out[idx - 1].score < hit.score) {- out[idx] = out[idx - 1];- idx--;- }- out[idx] = hit;- continue;- }- // Absent canonical: fetch (in its OWN source) + inject at top-of-organic + epsilon.- let page;- try {- page = await engine.getPage(ref.slug, { sourceId: ref.source_id, excludePrivate: opts.excludePrivate });- } catch {- continue;- }- if (!page) continue;- // #4352 — the alias inject path bypasses the engines' SQL visibility- // clause (getPage, not search); re-apply the private predicate here so- // an untrusted caller can't hop into a `visibility: private` page.- if (opts.excludePrivate && isPrivatePage(page)) continue;- injectScore += 1e-6;- out.unshift({- // #2339-sibling: include page_id. The `as SearchResult` cast hid its- // absence, so any consumer reading page_id off an alias-injected result got- // undefined — e.g. listActiveTakesForPages bound undefined/NaN into- // ANY($1::int[]) and crashed the contradiction probe on real Postgres.- page_id: page.id,- slug: page.slug,- title: page.title,- type: page.type,- source_id: page.source_id ?? ref.source_id,- chunk_text: sanitizeRemoteBody(page.compiled_truth ?? '').slice(0, 200),- chunk_index: 0,- chunk_id: 0,- score: injectScore,- base_score: injectScore,- alias_hit: true,- } as SearchResult);- }- return out;-}-export interface HybridSearchOpts extends SearchOpts {expansion?: boolean;+ /**+ * #5428 — opt-in single-token alias hop (see applyAliasTokenHop). Per-call+ * wins; otherwise brain config `search.alias_token_hop=true`. Default off.+ */+ aliasTokenHop?: boolean;/** v0.43 — observability sink for the relational recall arm (fired/no-op,* kind, seeds resolved, candidates, errored). Best-effort. */onRelationalMeta?: (meta: import('./relational-recall.ts').RelationalArmMeta) => void;@@ -1349,6 +1246,9 @@ export async function hybridSearch(exclude_slugs: opts?.exclude_slugs,exclude_slug_prefixes: opts?.exclude_slug_prefixes,include_slug_prefixes: opts?.include_slug_prefixes,+ // Per-brain `search.source_boosts` (read in the mode snapshot) over the+ // defaults; the env override still wins inside resolveBoostMap.+ source_boosts: resolveBoostMap(undefined, modeInput.sourceBoosts),// v0.29.1: since/until take precedence over deprecated afterDate/beforeDate.// The engine still consumes the legacy field names; this aliasing keeps// PR #618 callers compiling while the new names are the public surface.@@ -1395,6 +1295,38 @@ export async function hybridSearch(},};let vectorPoolUnderfill: HybridSearchMeta['vector_pool_underfilled'];+ // Post-arm identity injections re-apply the arms' exclude contract.+ const identityTierOpts: IdentityTierOpts = {+ sourceId: opts?.sourceId,+ sourceIds: opts?.sourceIds,+ excludePrivate: opts?.excludePrivate,+ requireSafeChunks: opts?.requireSafeChunks,+ excludeSlugs: opts?.exclude_slugs,+ excludeSlugPrefixes: resolveHardExcludes(opts?.exclude_slug_prefixes, opts?.include_slug_prefixes),+ };+ const aliasHopOpts = {+ ...identityTierOpts,+ tokenHop: opts?.aliasTokenHop ?? modeInput.aliasTokenHop === 'true',+ };+ // Intent identity boosts (exact/mentioned title or slug, mentioned alias),+ // shared by the fused path and both keyword-only paths. Caller re-sorts.+ const applyIdentityBoosts = async (list: SearchResult[]): Promise<void> => {+ if (intentWeights.exactMatchBoost === 1.0) {+ // #4694: general and temporal questions still honor a multi-token+ // title that is the query's subject. Not concept intent (Cat 13: a+ // lexical title decoy is exactly what paraphrase probes must not+ // reward) and not a relational question ("who invested in <title>"),+ // whose answer is the pages linked to that title, not the title page.+ if (intentWeightingOn && suggestions.intent !== 'concept' && parseRelationalQuery(query) === null) {+ applyTitleMentionBoost(list, query);+ }+ return;+ }+ applyExactMatchBoost(list, query, intentWeights);+ await applyAliasMentionBoost(list, query, intentWeights, (aliases) => engine.resolveAliases(aliases, {+ sourceId: opts?.sourceId, sourceIds: opts?.sourceIds, excludePrivate: opts?.excludePrivate,+ }));+ };// Track what actually ran for the optional onMeta callback (v0.25.0).// Caller leaves onMeta undefined → these flags are computed but never// surfaced. Capture wrapper passes a closure to receive the meta and@@ -1482,6 +1414,7 @@ export async function hybridSearch(: await Promise.all([engine.searchKeyword(query, searchOpts).catch((err: unknown) => {if (isDbAccessFailure(err)) keywordAccessError = err;+ pushDegraded(degraded, 'keyword_arm_failed', isTimeoutError(err) ? 'timeout' : 'provider_error');warnOncePerProcess('search-keyword-arm-failed',`[gbrain] searchKeyword arm failed (fail-open, keyword candidates skipped): ` +@@ -1491,6 +1424,7 @@ export async function hybridSearch(}),engine.searchTitles(query, searchOpts).catch((err: unknown) => {if (isDbAccessFailure(err)) titleAccessError = err;+ pushDegraded(degraded, 'title_arm_failed', isTimeoutError(err) ? 'timeout' : 'provider_error');warnOncePerProcess('search-titles-arm-failed',`[gbrain] searchTitles arm failed (fail-open, title candidates skipped): ` +@@ -1502,6 +1436,14 @@ export async function hybridSearch(if (keywordAccessError && titleAccessError) {throw keywordAccessError;}+ const exactLookupOpts: ExactLookupOpts = {+ ...identityTierOpts,+ titleCandidates: titleResults,+ takesHoldersAllowList: opts?.takesHoldersAllowList,+ // #4480: gate tier injections on the caller's shape filters.+ type: opts?.type,+ types: opts?.types,+ };// #3783 — stamp lexical-arm membership pre-fusion so evidence's// keyword_exact label is earned by an actual FTS hit, never by a solid// blended score alone. Both arms are the lexical-evidence class (chunk@@ -1613,29 +1555,14 @@ export async function hybridSearch(}if (noEmbedResults.length > 0) {await runPostFusionStages(engine, noEmbedResults, postFusionOpts);+ await applyIdentityBoosts(noEmbedResults);noEmbedResults.sort((a, b) => b.score - a.score);}// T3/T4 — alias hop + evidence stamp even without an embedding provider// (the named-thing fix is most valuable exactly when vector is unavailable).- const noEmbedPreExact = await applyAliasHop(engine, dedupResults(noEmbedResults), query, {- sourceId: opts?.sourceId,- sourceIds: opts?.sourceIds,- excludePrivate: opts?.excludePrivate,- requireSafeChunks: opts?.requireSafeChunks,- });+ const noEmbedPreExact = await applyAliasHop(engine, dedupResults(noEmbedResults), query, aliasHopOpts);// #1663 — structural exact-lookup tier (slug / exact-title identity).- const noEmbedHopped = await applyExactLookupTier(engine, noEmbedPreExact, query, {- sourceId: opts?.sourceId,- sourceIds: opts?.sourceIds,- titleCandidates: titleResults,- excludePrivate: opts?.excludePrivate,- requireSafeChunks: opts?.requireSafeChunks,- takesHoldersAllowList: opts?.takesHoldersAllowList,- // #4480: gate tier injections on the caller's shape filters.- type: opts?.type,- types: opts?.types,- excludeSlugs: opts?.exclude_slugs,- });+ const noEmbedHopped = await applyExactLookupTier(engine, noEmbedPreExact, query, exactLookupOpts);stampEvidence(noEmbedHopped, { cosineFloor: resolvedMode.evidence_cosine_floor });// #3995 — guaranteed page-1 relational evidence: a fired arm's answer is// often lexically unrecoverable, so its single-arm fused row can land@@ -1810,6 +1737,7 @@ export async function hybridSearch(}}+ let imageQueryEmbedding: Float32Array | null = null;if (!unifiedDone && (effectiveModality === 'image' || effectiveModality === 'both')) {// Attempt image-side embedding. Fail-open: if multimodal is unconfigured// OR the embed throws, log a structured warning and fall through to text.@@ -1822,6 +1750,7 @@ export async function hybridSearch(throw new Error('gateway not configured for embedding — multimodal would also fail');}const imageEmbedding = await embedQueryMultimodal(query);+ imageQueryEmbedding = imageEmbedding;const imageSearchOpts: SearchOpts = {...searchOpts,embeddingColumn: 'embedding_image',@@ -2010,27 +1939,12 @@ export async function hybridSearch(}if (fallbackResults.length > 0) {await runPostFusionStages(engine, fallbackResults, postFusionOpts);+ await applyIdentityBoosts(fallbackResults);fallbackResults.sort((a, b) => b.score - a.score);}- const kwPreExact = await applyAliasHop(engine, dedupResults(fallbackResults), query, {- sourceId: opts?.sourceId,- sourceIds: opts?.sourceIds,- excludePrivate: opts?.excludePrivate,- requireSafeChunks: opts?.requireSafeChunks,- });+ const kwPreExact = await applyAliasHop(engine, dedupResults(fallbackResults), query, aliasHopOpts);// #1663 — structural exact-lookup tier (slug / exact-title identity).- const kwHopped = await applyExactLookupTier(engine, kwPreExact, query, {- sourceId: opts?.sourceId,- sourceIds: opts?.sourceIds,- titleCandidates: titleResults,- excludePrivate: opts?.excludePrivate,- requireSafeChunks: opts?.requireSafeChunks,- takesHoldersAllowList: opts?.takesHoldersAllowList,- // #4480: gate tier injections on the caller's shape filters.- type: opts?.type,- types: opts?.types,- excludeSlugs: opts?.exclude_slugs,- });+ const kwHopped = await applyExactLookupTier(engine, kwPreExact, query, exactLookupOpts);stampEvidence(kwHopped, { cosineFloor: resolvedMode.evidence_cosine_floor });const kwSliced = kwHopped.slice(offset, offset + limit);// v0.32.3 search-lite: budget enforcement on the keyword-fallback path too.@@ -2164,7 +2078,10 @@ export async function hybridSearch(if (queryEmbedding) {// Unified routing embedded the query with the multimodal model, so the// rescore must hydrate the multimodal column, not the text column.- fused = await cosineReScore(engine, fused, queryEmbedding, unifiedDone ? 'embedding_multimodal' : resolvedCol.name);+ fused = await cosineReScore(+ engine, fused, queryEmbedding, unifiedDone ? 'embedding_multimodal' : resolvedCol.name,+ imageQueryEmbedding && !unifiedDone ? { queryEmbedding: imageQueryEmbedding, column: 'embedding_image' } : undefined,+ );}// Phase E3 (Cat 13): metadata boost gate — decided from the SAME lexical@@ -2187,12 +2104,7 @@ export async function hybridSearch(});// v0.32.x search-lite: intent exact-match boost (entity/event intents).// No-op when boost factor is 1.0 (general intent or weighting disabled).- if (intentWeights.exactMatchBoost !== 1.0) {- applyExactMatchBoost(fused, query, intentWeights);- await applyAliasMentionBoost(fused, query, intentWeights, (aliases) => engine.resolveAliases(aliases, {- sourceId: opts?.sourceId, sourceIds: opts?.sourceIds, excludePrivate: opts?.excludePrivate,- }));- }+ await applyIdentityBoosts(fused);fused.sort((a, b) => b.score - a.score);}@@ -2313,13 +2225,7 @@ export async function hybridSearch(// T3 — free-text alias hop. Runs AFTER rerank so a query that is a page's// declared chosen name reliably surfaces that page regardless of how the// reranker scored body chunks. Fail-open on pre-v110 brains.- const preExact = await applyAliasHop(engine, rerankPinned, query, {- sourceId: opts?.sourceId,- sourceIds: opts?.sourceIds,- excludePrivate: opts?.excludePrivate,- requireSafeChunks: opts?.requireSafeChunks,- excludeSlugs: opts?.exclude_slugs,- });+ const preExact = await applyAliasHop(engine, rerankPinned, query, aliasHopOpts);// #1663 — structural exact-lookup tier: a query that IS a page identity// (slug / exact normalized title) gets that page at rank-1 regardless of@@ -2327,18 +2233,7 @@ export async function hybridSearch(// the already-fetched title arm (no extra queries); pure no-op for// non-lookup-shaped queries. Runs after the alias hop so all three// identity surfaces (alias, slug, title) share the same injection shape.- const aliasHopped = await applyExactLookupTier(engine, preExact, query, {- sourceId: opts?.sourceId,- sourceIds: opts?.sourceIds,- titleCandidates: titleResults,- excludePrivate: opts?.excludePrivate,- requireSafeChunks: opts?.requireSafeChunks,- takesHoldersAllowList: opts?.takesHoldersAllowList,- // #4480: gate tier injections on the caller's shape filters.- type: opts?.type,- types: opts?.types,- excludeSlugs: opts?.exclude_slugs,- });+ const aliasHopped = await applyExactLookupTier(engine, preExact, query, exactLookupOpts);// T4 — stamp evidence + create_safety so the agent's don't-duplicate// decision keys off WHY a page matched, not a raw blended score. Stamp on@@ -2592,89 +2487,94 @@ export async function hybridSearchCached(metadata_boost_gate: normalizeMetadataBoostGate(opts?.metadataBoostGate),},});- const mergedCfgCached = await loadConfigWithEngine(engine).catch(() => null);- const cfgCached = mergedCfgCached ?? ((await import('../config.ts')).loadConfig()) ?? { engine: 'pglite' as const };- const resolvedColCached = resolveEmbeddingColumn(opts, cfgCached);- const isNonDefaultColumn = !isCacheSafe(resolvedColCached, cfgCached);-- // wave-g (#4415): classify ONCE with the brain's `search.intent_patterns`- // applied (loadEngineIntentPatterns is per-engine + TTL-cached) so the- // det=/sal=/rec= key parts reflect the SAME classification bare- // hybridSearch resolves. Pre-fix, det= was computed via the pattern-less- // global classifier, so a fresh process keyed its first cache row under a- // pattern-less detail while the stored results used the pattern-aware one.- const intentStateForCache = await loadEngineIntentPatterns(engine);- const cacheSuggestions = classifyQuery(query, intentStateForCache.banks);-- // 2026-08 fix wave (E5b): resolve the adaptive-return gate ONCE for both- // the cache key and the (former) skip decision. Adaptive-on calls now- // cache — the gate params + the query's resolved intent class fold into- // knobsHash (v=27) so gate-off/-on and cross-intent rows never cross-serve.- // Known-narrow residual (adversarial review, 2026-09): bare hybridSearch- // re-classifies intent for the applied trim, so a `search.intent_patterns`- // write (or bank-TTL expiry) landing BETWEEN the two loads can store a set- // trimmed under intent X beneath a key claiming intent Y for up to- // ttl_seconds — same class as the documented #4356 double-resolution- // caveat: cache-only, self-healing, accepted.- const adaptiveResolvedForCache = resolveAdaptiveReturn(- opts?.adaptiveReturn,- adaptiveReturnFromConfig(cfgCached as unknown as Record<string, unknown> | null),- );+ // Result caching is off (semanticResultCacheAvailable() === false): skip the+ // key/config setup entirely so the wrapper costs no round-trips of its own.+ const semanticCache = semanticResultCacheAvailable() ? await (async () => {+ const mergedCfgCached = await loadConfigWithEngine(engine).catch(() => null);+ const cfgCached = mergedCfgCached ?? ((await import('../config.ts')).loadConfig()) ?? { engine: 'pglite' as const };+ const resolvedColCached = resolveEmbeddingColumn(opts, cfgCached);+ const isNonDefaultColumn = !isCacheSafe(resolvedColCached, cfgCached);++ // wave-g (#4415): classify ONCE with the brain's `search.intent_patterns`+ // applied (loadEngineIntentPatterns is per-engine + TTL-cached) so the+ // det=/sal=/rec= key parts reflect the SAME classification bare+ // hybridSearch resolves. Pre-fix, det= was computed via the pattern-less+ // global classifier, so a fresh process keyed its first cache row under a+ // pattern-less detail while the stored results used the pattern-aware one.+ const intentStateForCache = await loadEngineIntentPatterns(engine);+ const cacheSuggestions = classifyQuery(query, intentStateForCache.banks);++ // 2026-08 fix wave (E5b): resolve the adaptive-return gate ONCE for both+ // the cache key and the (former) skip decision. Adaptive-on calls now+ // cache — the gate params + the query's resolved intent class fold into+ // knobsHash (v=27) so gate-off/-on and cross-intent rows never cross-serve.+ // Known-narrow residual (adversarial review, 2026-09): bare hybridSearch+ // re-classifies intent for the applied trim, so a `search.intent_patterns`+ // write (or bank-TTL expiry) landing BETWEEN the two loads can store a set+ // trimmed under intent X beneath a key claiming intent Y for up to+ // ttl_seconds — same class as the documented #4356 double-resolution+ // caveat: cache-only, self-healing, accepted.+ const adaptiveResolvedForCache = resolveAdaptiveReturn(+ opts?.adaptiveReturn,+ adaptiveReturnFromConfig(cfgCached as unknown as Record<string, unknown> | null),+ );- // Cache key carries the column + provider so different embedding spaces- // never collide on the same `(source_id, query_text)` row.- const cacheKnobsHash = knobsHash(resolvedForCache, {- embeddingColumn: resolvedColCached.name,- embeddingModel: resolvedColCached.embeddingModel,- // #2825 — fold the resolved hard-exclude prefix list (defaults ∪- // GBRAIN_SEARCH_EXCLUDE ∪ per-call exclude_slug_prefixes, minus- // include_slug_prefixes — exactly what the engines' query-build path- // resolves) into the cache key so a row written under one exclude- // policy can't be served to a lookup under another.- hardExcludes: resolveHardExcludes(opts?.exclude_slug_prefixes, opts?.include_slug_prefixes),- // #3515 — fold the EFFECTIVE detail level into the cache key. detail- // gates dedup, chunk-source filtering, and the compiled_truth boost, so- // a `--detail low` write (compiled-truth-only result set) must never be- // served to a default `medium` lookup. Resolve auto-detect the same way- // bare hybridSearch does (opts.detail ?? pattern-aware suggestion) so an- // auto-detected `high` query keys like an explicit `high` one.- detail: opts?.detail ?? cacheSuggestions.suggestedDetail,- // #4415 (wave-g, v=24) — fold the EFFECTIVE salience/recency modes.- // Both reorder the post-fusion result set, and #4415 put the per-call- // overrides on the default MCP `search` surface, so a salience:'strong'- // write must never serve a salience:'off' lookup of the same query.- // Resolved by the SAME chain bare hybridSearch uses (helpers above).- salience: resolveEffectiveSalience(opts, cacheSuggestions),- recency: resolveEffectiveRecency(opts, cacheSuggestions, resolvedForCache.intentWeighting),- // #4415 (wave-g, v=24) — fold the applied intent-pattern config- // fingerprint: a `search.intent_patterns` edit changes classification- // (and thus results), so it must change the key immediately instead of- // serving old-classification rows for the rest of the cache TTL.- intentPatterns: intentStateForCache.fingerprint,- // Retained storage-key shape; semantic response reuse is disabled below.- excludePrivate: opts?.excludePrivate === true,- // v=27 (E5b) — the resolved gate + this query's intent class, classified- // by the SAME pattern-aware banks bare hybridSearch resolves (above).- adaptiveReturn: {- enabled: adaptiveResolvedForCache.enabled,- entityMax: adaptiveResolvedForCache.entityMax,- otherMax: adaptiveResolvedForCache.otherMax,- minKeep: adaptiveResolvedForCache.minKeep,- intent: cacheSuggestions.intent,- },- });+ // Cache key carries the column + provider so different embedding spaces+ // never collide on the same `(source_id, query_text)` row.+ const cacheKnobsHash = knobsHash(resolvedForCache, {+ embeddingColumn: resolvedColCached.name,+ embeddingModel: resolvedColCached.embeddingModel,+ // #2825 — fold the resolved hard-exclude prefix list (defaults ∪+ // GBRAIN_SEARCH_EXCLUDE ∪ per-call exclude_slug_prefixes, minus+ // include_slug_prefixes — exactly what the engines' query-build path+ // resolves) into the cache key so a row written under one exclude+ // policy can't be served to a lookup under another.+ hardExcludes: resolveHardExcludes(opts?.exclude_slug_prefixes, opts?.include_slug_prefixes),+ // #3515 — fold the EFFECTIVE detail level into the cache key. detail+ // gates dedup, chunk-source filtering, and the compiled_truth boost, so+ // a `--detail low` write (compiled-truth-only result set) must never be+ // served to a default `medium` lookup. Resolve auto-detect the same way+ // bare hybridSearch does (opts.detail ?? pattern-aware suggestion) so an+ // auto-detected `high` query keys like an explicit `high` one.+ detail: opts?.detail ?? cacheSuggestions.suggestedDetail,+ // #4415 (wave-g, v=24) — fold the EFFECTIVE salience/recency modes.+ // Both reorder the post-fusion result set, and #4415 put the per-call+ // overrides on the default MCP `search` surface, so a salience:'strong'+ // write must never serve a salience:'off' lookup of the same query.+ // Resolved by the SAME chain bare hybridSearch uses (helpers above).+ salience: resolveEffectiveSalience(opts, cacheSuggestions),+ recency: resolveEffectiveRecency(opts, cacheSuggestions, resolvedForCache.intentWeighting),+ // #4415 (wave-g, v=24) — fold the applied intent-pattern config+ // fingerprint: a `search.intent_patterns` edit changes classification+ // (and thus results), so it must change the key immediately instead of+ // serving old-classification rows for the rest of the cache TTL.+ intentPatterns: intentStateForCache.fingerprint,+ // Retained storage-key shape; semantic response reuse is disabled below.+ excludePrivate: opts?.excludePrivate === true,+ // v=27 (E5b) — the resolved gate + this query's intent class, classified+ // by the SAME pattern-aware banks bare hybridSearch resolves (above).+ adaptiveReturn: {+ enabled: adaptiveResolvedForCache.enabled,+ entityMax: adaptiveResolvedForCache.entityMax,+ otherMax: adaptiveResolvedForCache.otherMax,+ minKeep: adaptiveResolvedForCache.minKeep,+ intent: cacheSuggestions.intent,+ },+ });- // Cache decision: opts.useCache (explicit) wins over global config; global- // config wins over mode bundle default. Mode bundle is on for all 3 modes- // today; the resolver already folded everything through.- const cacheCfg = await loadCacheConfig(engine);- const cacheEnabled = resolvedForCache.cache_enabled;- const cache = new SemanticQueryCache(engine, {- ...cacheCfg,- enabled: cacheEnabled,- similarityThreshold: resolvedForCache.cache_similarity_threshold,- ttlSeconds: resolvedForCache.cache_ttl_seconds,- });+ // Cache decision: opts.useCache (explicit) wins over global config; global+ // config wins over mode bundle default. Mode bundle is on for all 3 modes+ // today; the resolver already folded everything through.+ const cacheCfg = await loadCacheConfig(engine);+ const cacheEnabled = resolvedForCache.cache_enabled;+ const cache = new SemanticQueryCache(engine, {+ ...cacheCfg,+ enabled: cacheEnabled,+ similarityThreshold: resolvedForCache.cache_similarity_threshold,+ ttlSeconds: resolvedForCache.cache_ttl_seconds,+ });+ return { cache, cacheKnobsHash, isNonDefaultColumn, providerProbe: resolvedColCached.embeddingModel || undefined };+ })() : null;// Skip cache entirely when the request asks for two-pass walks, has// a non-default embedding column (per-call or via config default —@@ -2721,11 +2621,11 @@ export async function hybridSearchCached(// Hard availability gate: no persisted result is read or written until// every response dependency can be authorized at reuse time.const skipCache =- !semanticResultCacheAvailable() ||- !cache.isEnabled() ||+ !semanticCache ||+ !semanticCache.cache.isEnabled() ||(opts?.walkDepth ?? 0) > 0 ||Boolean(opts?.nearSymbol) ||- isNonDefaultColumn ||+ semanticCache.isNonDefaultColumn ||opts?.dedupOpts !== undefined ||dateFiltered ||typeFiltered ||@@ -2748,7 +2648,7 @@ export async function hybridSearchCached(// sees the already-elapsed budget and fails fast → keyword fallback. Worst// case ~one timeout (~6s), comfortably under the CLI 10s force-exit.const queryEmbedDl = makeQueryEmbedDeadline();- if (!skipCache) {+ if (semanticCache && !skipCache) {try {const { isAvailable } = await import('../ai/gateway.ts');// v0.36 (D10): for the cache-lookup embedding, also use the resolved@@ -2756,8 +2656,7 @@ export async function hybridSearchCached(// 'embedding' column (skipCache short-circuits non-default above),// so this is the default embeddingModel — but threading it keeps// the provider probe consistent with the bare hybridSearch path.- const providerProbeCached = resolvedColCached.embeddingModel || undefined;- if (isAvailable('embedding', providerProbeCached)) {+ if (isAvailable('embedding', semanticCache.providerProbe)) {// v0.35.0.0+: query-side embedding (cache lookup path).// v0.42.20.0 (Fix 3) — bounded by the shared deadline; on timeout this// throws → caught below → cacheStatus 'disabled' → falls through to the@@ -2772,8 +2671,8 @@ export async function hybridSearchCached(}}- if (!skipCache && queryEmbedding && cacheStatus !== 'disabled') {- const hit = await cache.lookup(queryEmbedding, { sourceId: cacheScopeKey(opts), knobsHash: cacheKnobsHash, queryText: query }); // queryText → #1469 text guard+ if (semanticCache && !skipCache && queryEmbedding && cacheStatus !== 'disabled') {+ const hit = await semanticCache.cache.lookup(queryEmbedding, { sourceId: cacheScopeKey(opts), knobsHash: semanticCache.cacheKnobsHash, queryText: query }); // queryText → #1469 text guardif (hit.hit && hit.results) {cacheStatus = 'hit';cacheSimilarity = hit.similarity;@@ -2941,6 +2840,7 @@ export async function hybridSearchCached(// queryEmbedding (store() no-ops on null) and vector_enabled=false, so it// is uncacheable by construction.if (+ semanticCache &&cacheStatus === 'miss' &&queryEmbedding &&results.length > 0 &&@@ -2954,10 +2854,10 @@ export async function hybridSearchCached(// Stale unreranked rows after a key appears expire within one TTL.const isDegraded = (finalMeta.degraded ?? []).some(affectsRecall);trackCacheWrite(- cache+ semanticCache.cache.store(query, queryEmbedding, results, finalMeta, {sourceId: cacheScopeKey(opts),- knobsHash: cacheKnobsHash,+ knobsHash: semanticCache.cacheKnobsHash,...(isDegraded ? { ttlSeconds: DEGRADED_CACHE_TTL_SECONDS } : {}),}).catch(() => { /* swallow */ }),@@ -3148,26 +3048,37 @@ export async function cosineReScore(results: SearchResult[],queryEmbedding: Float32Array,column: string = 'embedding',+ imageSpace?: { queryEmbedding: Float32Array; column: string },): Promise<SearchResult[]> {- const chunkIds = results+ // 'both' mode: image-arm rows live in the image space (image column,+ // multimodal query vector); everything else in the text space.+ const inImageSpace = (r: SearchResult): boolean => imageSpace !== undefined && r.modality === 'image';+ const idsFor = (image: boolean) => results+ .filter(r => inImageSpace(r) === image).map(r => r.chunk_id).filter((id): id is number => id != null);+ const chunkIds = idsFor(false);+ const imageChunkIds = idsFor(true);- if (chunkIds.length === 0) return results;+ if (chunkIds.length === 0 && imageChunkIds.length === 0) return results;let embeddingMap: Map<number, Float32Array>;+ let imageEmbeddingMap = new Map<number, Float32Array>();try {// v0.36 (D9): hydrate from the active column so rescore happens in// the same embedding space the HNSW just ranked in. Without this,// a Voyage HNSW retrieval would HNSW-rank against Voyage vectors but// rescore against OpenAI vectors → NaN or wrong rankings.- embeddingMap = await engine.getEmbeddingsByChunkIds(chunkIds, column);+ embeddingMap = chunkIds.length > 0 ? await engine.getEmbeddingsByChunkIds(chunkIds, column) : new Map();+ if (imageSpace && imageChunkIds.length > 0) {+ imageEmbeddingMap = await engine.getEmbeddingsByChunkIds(imageChunkIds, imageSpace.column);+ }} catch {// DB error is non-fatal, return results without re-scoringreturn results;}- if (embeddingMap.size === 0) return results;+ if (embeddingMap.size === 0 && imageEmbeddingMap.size === 0) return results;// Normalize RRF scores to 0-1 for blendingconst maxRrf = Math.max(...results.map(r => r.score));@@ -3183,8 +3094,9 @@ export async function cosineReScore(// results). Route it through the SAME blend with cosine=0 instead of// excluding it — excluding would make embed_skip pages unsearchable,// a different (undesired) behavior change.- const chunkEmb = r.chunk_id != null ? embeddingMap.get(r.chunk_id) : undefined;- const cosine = chunkEmb ? cosineSimilarity(queryEmbedding, chunkEmb) : 0;+ const image = inImageSpace(r);+ const chunkEmb = r.chunk_id != null ? (image ? imageEmbeddingMap : embeddingMap).get(r.chunk_id) : undefined;+ const cosine = chunkEmb ? cosineSimilarity(image ? imageSpace!.queryEmbedding : queryEmbedding, chunkEmb) : 0;const normRrf = maxRrf > 0 ? r.score / maxRrf : 0;const blended = 0.7 * normRrf + 0.3 * cosine;diff --git a/src/core/search/intent-weights.ts b/src/core/search/intent-weights.tsindex 2da11aba54..7db6327616 100644--- a/src/core/search/intent-weights.ts+++ b/src/core/search/intent-weights.ts@@ -32,7 +32,7 @@import type { QueryIntent } from './query-intent.ts';import type { SearchResult } from '../types.ts';-import { isTitleMentionedInQuery, tokenizeTitle } from './title-match.ts';+import { containsTokenRun, isTitleMentionedInQuery, titleAsQuerySubject, tokenizeTitle } from './title-match.ts';/*** Weight adjustments to apply for a classified intent. All factors are@@ -161,6 +161,37 @@ export function applyExactMatchBoost(}}+/**+ * #4694 — score multiplier under general and temporal intent (no+ * exact-match boost; concept intent is excluded, see hybrid.ts) for a result whose multi-token title or slug+ * tail is the query's subject (`titleAsQuerySubject`: "Which document is+ * <title>?" classifies as general, so the entity-intent boost never reached+ * it).+ */+export const TITLE_MENTION_BOOST = 1.18;++/**+ * Apply TITLE_MENTION_BOOST in place. When several qualifying titles are+ * mentioned and one is a sub-run of another ("Budget Review" inside+ * "Offsite Budget Review"), only the longest is boosted. Stamps+ * `exact_match_boost` for --explain. Caller re-sorts.+ */+export function applyTitleMentionBoost(results: SearchResult[], query: string): void {+ const subjects = new Map<SearchResult, string[]>();+ for (const r of results) {+ const slug = r.slug ?? '';+ const tokens = titleAsQuerySubject(query, r.title ?? '')+ ?? titleAsQuerySubject(query, slug.slice(slug.lastIndexOf('/') + 1));+ if (tokens) subjects.set(r, tokens);+ }+ const all = [...subjects.values()];+ for (const [r, tokens] of subjects) {+ if (all.some((other) => other.length > tokens.length && containsTokenRun(other, tokens))) continue;+ r.score *= TITLE_MENTION_BOOST;+ r.exact_match_boost = TITLE_MENTION_BOOST;+ }+}+/** Longest alias n-gram looked up for a query mention (tokens). */const MAX_ALIAS_MENTION_TOKENS = 5;diff --git a/src/core/search/mode.ts b/src/core/search/mode.tsindex 2204548d60..f370016284 100644--- a/src/core/search/mode.ts+++ b/src/core/search/mode.ts@@ -734,6 +734,10 @@ export interface ResolveSearchModeInput {overrides?: SearchKeyOverrides;/** Per-call opts (SearchOpts / HybridSearchOpts). */perCall?: SearchPerCallOpts;+ /** Raw `search.source_boosts` (read in the same snapshot; see source-boost.ts). */+ sourceBoosts?: string;+ /** Raw `search.alias_token_hop` (read in the same snapshot; #5428, opt-in). */+ aliasTokenHop?: string;}export interface ResolvedSearchKnobs extends ModeBundle {@@ -1441,6 +1445,10 @@ export const SEARCH_MODE_CONFIG_KEYS: ReadonlyArray<string> = Object.freeze(Obje* the operator's mode choice.*/export const SEARCH_MODE_KEY = 'search.mode';+/** Per-brain source-boost map, read alongside the mode keys (not a bundle knob). */+export const SOURCE_BOOSTS_KEY = 'search.source_boosts';+/** Opt-in single-token alias hop (#5428), read alongside the mode keys. */+export const ALIAS_TOKEN_HOP_KEY = 'search.alias_token_hop';/*** Load the live mode config (mode + per-key overrides) from the brain engine.@@ -1478,8 +1486,10 @@ export async function loadSearchModeConfig(}};- const [mode, ...overrideValues] = await Promise.all([+ const [mode, sourceBoosts, aliasTokenHop, ...overrideValues] = await Promise.all([safeGet(SEARCH_MODE_KEY),+ safeGet(SOURCE_BOOSTS_KEY),+ safeGet(ALIAS_TOKEN_HOP_KEY),...SEARCH_MODE_CONFIG_KEYS.map(safeGet),]);@@ -1491,5 +1501,7 @@ export async function loadSearchModeConfig(return {mode,overrides: loadOverridesFromConfig(configMap),+ ...(sourceBoosts !== undefined ? { sourceBoosts } : {}),+ ...(aliasTokenHop !== undefined ? { aliasTokenHop } : {}),};}diff --git a/src/core/search/relational-intent.ts b/src/core/search/relational-intent.tsindex 35d9e2bc2a..f6944e78c1 100644--- a/src/core/search/relational-intent.ts+++ b/src/core/search/relational-intent.ts@@ -109,16 +109,76 @@ export interface CompiledPattern {// boundary without catastrophic backtracking.const SEED = '(.{1,80}?)';-// ── who_rel verb bank: "who <verb> <seed>" → traverse INTO the seed ──-// Each entry is explicit (linkTypes inline) so there is no second lookup.-const WHO_REL_VERBS: Array<{ verb: string; linkTypes: string[]; direction: RelationDirection }> = [- { verb: 'invested in|invests in|funded|backed|backs|led the round in|led the seed in|led the series [a-z] in', linkTypes: ['invested_in', 'led_round'], direction: 'in' },- { verb: 'founded|co-?founded|started', linkTypes: ['founded'], direction: 'in' },- { verb: 'advises|advised', linkTypes: ['advises'], direction: 'in' },- { verb: 'works at|worked at|works for', linkTypes: ['works_at'], direction: 'in' },- { verb: 'attended', linkTypes: ['attended'], direction: 'in' },+// ── Relation lexicon ──+// One row per edge family. The query frames below combine each row's+// phrasings, so a new synonym lands in every frame at once:+// inVerbs "who <verb> X", "which funds <verb> X", "people who <verb> X"+// agentNouns "X's <noun>", "<noun> of|in|at... X" (incoming: X is the target)+// outVerbs "what (companies) did X <verb>" (outgoing: X is the source)+// outWho "who does X <verb>" (outgoing)+// outNouns "X's <noun>" (outgoing)+interface RelationLexicon {+ linkTypes: string[];+ inVerbs: string;+ agentNouns: string;+ nounPreps: string;+ outVerbs?: string;+ outWho?: string;+ outNouns?: string;+}++const ROUND = '(?:the\\s+)?(?:[a-z0-9-]+\\s+)?(?:round|seed|series\\s+[a-z])';++const RELATIONS: RelationLexicon[] = [+ {+ linkTypes: ['invested_in', 'led_round'],+ inVerbs: `invested in|invests in|invest in|investing in|funded|funds|fund|funding|backed|backs|back|backing|financed|finances|finance|put money (?:into|in)|led ${ROUND} (?:in|for|of|at)|participated in ${ROUND} (?:of|for|in|at)`,+ agentNouns: 'investors?|backers?|funders?|financiers?|shareholders?',+ nounPreps: 'in|of|behind|for|into|at',+ outVerbs: 'invest(?:ed)? in|backed|back|funded|fund|financed|finance',+ outWho: 'invest in|back|fund|finance',+ outNouns: 'portfolio(?:\\s+companies)?|investments',+ },+ {+ linkTypes: ['founded'],+ inVerbs: 'founded|co-?founded|started|founds',+ agentNouns: 'founders?|co-?founders?|founding team',+ nounPreps: 'of|at|behind',+ outVerbs: 'found|co-?found|start|founded|co-?founded|started',+ },+ {+ linkTypes: ['works_at'],+ inVerbs: 'works at|worked at|works for|worked for|work at|work for|working at|working for|employed (?:at|by)|on the team at',+ agentNouns: 'employees?|staff(?:ers)?|team members?',+ nounPreps: 'at|of|in',+ outWho: 'work for|work at|worked for|worked at',+ outNouns: 'employer',+ },+ {+ linkTypes: ['advises'],+ inVerbs: 'advises|advised|advise|advising|(?:sits|sat|serves|served|is) on the advisory board (?:of|at|for)|on the advisory board (?:of|at|for)',+ agentNouns: 'advis[eo]rs?|advisory board(?:\\s+members)?',+ nounPreps: 'to|of|for|at',+ outVerbs: 'advise',+ outWho: 'advise',+ },+ {+ linkTypes: ['attended'],+ inVerbs: 'attended',+ agentNouns: 'attendees',+ nounPreps: 'of|at',+ },];+// Leading request words a noun-phrase query may carry ("who are X's investors",+// "list the founders of X"). Anchored at the start so the noun phrase has to BE+// the query, not a fragment of a longer content question.+const ASK = "(?:(?:who|what)(?:'s|’s|\\s+(?:are|is|were|was))\\s+|(?:list|show|name|find|give)(?:\\s+me)?\\s+(?:all\\s+)?|tell me\\s+)?(?:the\\s+|all\\s+)?";+const POSS = "(?:'s|’s|')";+const AUX = "(?:'s|’s|\\s+has|\\s+have|\\s+had|\\s+did|\\s+is|\\s+are|\\s+was|\\s+were)?";+const HEADS = 'people|persons|individuals|folks|investors|firms|funds|vcs|angels|companies|founders|employees|advis[eo]rs|partners|entities';+const END = '\\s*[?.!]?$';+function buildPatterns(vocab?: RelationVocab): CompiledPattern[] {const patterns: CompiledPattern[] = [];@@ -137,6 +197,14 @@ function buildPatterns(vocab?: RelationVocab): CompiledPattern[] {),kind: 'connects', linkTypes: null, direction: 'both', seedGroups: 2,});+ for (const re of [+ `^(?:what(?:'s|’s|\\s+is|\\s+was)\\s+)?(?:the\\s+)?(?:relationship|connection|link|relation|tie)\\s+between\\s+${SEED}\\s+(?:and|&)\\s+${SEED}${END}`,+ `\\bhow\\s+(?:is|was|are|were)\\s+${SEED}\\s+(?:connected|related|linked|tied)\\s+(?:to|with)\\s+${SEED}${END}`,+ `^what\\s+do(?:es)?\\s+${SEED}\\s+(?:and|&)\\s+${SEED}\\s+have in common${END}`,+ `\\bhow\\s+do(?:es)?\\s+${SEED}\\s+(?:and|&)\\s+${SEED}\\s+know each other${END}`,+ ]) {+ patterns.push({ re: new RegExp(re, 'i'), kind: 'connects', linkTypes: null, direction: 'both', seedGroups: 2 });+ }// intro — type-agnostic walk around the named person (no `introduced` edge).patterns.push({@@ -146,6 +214,12 @@ function buildPatterns(vocab?: RelationVocab): CompiledPattern[] {),kind: 'intro', linkTypes: null, direction: 'both', seedGroups: 1,});+ for (const re of [+ `\\bwho\\s+(?:can|could|would|might)\\s+(?:introduce|intro|connect|refer)\\s+(?:me|us)\\s+(?:to|with)\\s+${SEED}${END}`,+ `^who\\s+knows\\s+${SEED}${END}`,+ ]) {+ patterns.push({ re: new RegExp(re, 'i'), kind: 'intro', linkTypes: null, direction: 'both', seedGroups: 1 });+ }// who_at — entity in the middle: "who at acme works on payments".patterns.push({@@ -156,12 +230,21 @@ function buildPatterns(vocab?: RelationVocab): CompiledPattern[] {kind: 'who_at', linkTypes: ['works_at'], direction: 'in', seedGroups: 1,});- // who_rel — "who <verb> <seed>".- for (const v of WHO_REL_VERBS) {- patterns.push({- re: new RegExp(`\\bwho\\s+(?:${v.verb})\\s+${SEED}\\s*\\??$`, 'i'),- kind: 'who_rel', linkTypes: v.linkTypes, direction: v.direction, seedGroups: 1,- });+ for (const r of RELATIONS) {+ // nosemgrep: javascript.lang.security.audit.detect-non-literal-regexp.detect-non-literal-regexp -- sources are this module's constant RELATIONS lexicon (default patterns are memoized); query text is only matched against them, never compiled+ const out = (re: string) => patterns.push({ re: new RegExp(re, 'i'), kind: 'who_rel', linkTypes: r.linkTypes, direction: 'out', seedGroups: 1 });+ // nosemgrep: javascript.lang.security.audit.detect-non-literal-regexp.detect-non-literal-regexp -- same constant vocabulary as `out` above+ const inc = (re: string) => patterns.push({ re: new RegExp(re, 'i'), kind: 'who_rel', linkTypes: r.linkTypes, direction: 'in', seedGroups: 1 });+ // Outgoing first: "which companies has X backed" must not read as incoming.+ if (r.outVerbs) out(`^(?:what|which)\\s+(?:companies|startups|deals|businesses|firms|organizations)?\\s*(?:has|have|did|does|do)\\s+${SEED}\\s+(?:${r.outVerbs})${END}`);+ if (r.outWho) out(`^who\\s+(?:does|did|has)\\s+${SEED}\\s+(?:${r.outWho})${END}`);+ if (r.outNouns) out(`^${ASK}${SEED}${POSS}\\s+(?:${r.outNouns})${END}`);+ // Incoming.+ inc(`\\bwho${AUX}\\s+(?:${r.inVerbs})\\s+${SEED}${END}`);+ inc(`^(?:which|what)\\s+(?:${HEADS})\\s+(?:(?:have|has|had|did|are|were|is)\\s+)?(?:${r.inVerbs})\\s+${SEED}${END}`);+ inc(`^(?:the\\s+)?(?:${HEADS}|those|everyone|anyone)\\s+(?:who|that)\\s+(?:(?:have|has|had|are)\\s+)?(?:${r.inVerbs})\\s+${SEED}${END}`);+ inc(`^${ASK}(?:${r.agentNouns})\\s+(?:${r.nounPreps})\\s+${SEED}${END}`);+ inc(`^${ASK}${SEED}${POSS}\\s+(?:${r.agentNouns})${END}`);}// outgoing variants — "what did <seed> invest in", "where does <seed> work".@@ -173,7 +256,7 @@ function buildPatterns(vocab?: RelationVocab): CompiledPattern[] {kind: 'who_rel', linkTypes: ['invested_in', 'led_round'], direction: 'out', seedGroups: 1,});patterns.push({- re: new RegExp(`\\bwhere\\s+(?:does|did|has)\\s+${SEED}\\s+work\\b`, 'i'),+ re: new RegExp(`\\bwhere\\s+(?:does|did|has|is)\\s+${SEED}\\s+(?:work|employed)\\b`, 'i'),kind: 'who_rel', linkTypes: ['works_at'], direction: 'out', seedGroups: 1,});@@ -192,15 +275,23 @@ function buildPatterns(vocab?: RelationVocab): CompiledPattern[] {function cleanSeed(raw: string): string {return raw.trim()- .replace(/\?+$/, '')+ .replace(/[?.!]+$/, '').replace(/^["'`]|["'`]$/g, '').replace(/^(?:the|a|an)\s+/i, '').trim();}+// A seed is an entity name, never a clause: "who knows how to deploy X",+// "who at the company wants to ...".+const CLAUSE_START = /^(?:how|what|why|when|where|whether|if|to|which|who)\b/i;+// ... and a name does not end in a dangling preposition ("the founders of+// stoicism known for").+const DANGLING_END = /\b(?:for|to|of|in|on|with|about|by|from|at|as|like)$/i;+function validSeed(s: string): boolean {if (s.length === 0 || s.length > 80) return false;if (STOPWORD_SEEDS.has(s.toLowerCase())) return false;+ if (CLAUSE_START.test(s) || DANGLING_END.test(s)) return false;return true;}diff --git a/src/core/search/rerank.ts b/src/core/search/rerank.tsindex f53a1e7959..90ad4d3120 100644--- a/src/core/search/rerank.ts+++ b/src/core/search/rerank.ts@@ -206,9 +206,26 @@ export async function applyReranker(// (so a top_n response with fewer items than head.length naturally// drops the missing ones — but since we don't pass top_n by default,// every input gets a score).+ // #5428: exact score ties carry no cross-encoder preference, and providers+ // emit tied rows in arbitrary (call-to-call unstable) order. Within each run+ // of adjacent, exactly equal finite scores, keep the fused (input) order.+ // Rows never cross a different score.+ const ordered = [...reranked];+ for (let start = 0; start < ordered.length; ) {+ let end = start + 1;+ const score = ordered[start].relevanceScore;+ if (Number.isFinite(score)) {+ while (end < ordered.length && ordered[end].relevanceScore === score) end++;+ if (end - start > 1) {+ const run = ordered.slice(start, end).sort((a, b) => a.index - b.index);+ ordered.splice(start, run.length, ...run);+ }+ }+ start = end;+ }const seen = new Set<number>();const reorderedHead: SearchResult[] = [];- for (const r of reranked) {+ for (const r of ordered) {if (r.index >= 0 && r.index < head.length && !seen.has(r.index)) {seen.add(r.index);const item = head[r.index]!;diff --git a/src/core/search/source-boost.ts b/src/core/search/source-boost.tsindex d58cd88e33..fb1dc67a7a 100644--- a/src/core/search/source-boost.ts+++ b/src/core/search/source-boost.ts@@ -9,7 +9,9 @@* inside sql-ranking.ts). Defaults grounded in the composition of the* canonical brain at ~/git/brain/.*- * Override via env: GBRAIN_SOURCE_BOOST="originals/:1.8,openclaw/chat/:0.3"+ * Per brain: `gbrain config set search.source_boosts "wiki/:1.3,daily/:1.0"`+ * (`none` drops the defaults). Per process (wins over the brain):+ * GBRAIN_SOURCE_BOOST="originals/:1.8,openclaw/chat/:0.3"* Hard-exclude via env: GBRAIN_SEARCH_EXCLUDE="test/,scratch/"*/@@ -103,14 +105,22 @@ export function parseHardExcludesEnv(env: string | undefined): string[] {}/**- * Resolve the effective boost map by merging defaults with env override.- * Env entries override defaults (shallow merge); env-only entries are added.+ * Resolve the effective boost map: defaults, then the brain's+ * `search.source_boosts` config (same `prefix:factor` format; a bare `none`+ * entry drops the defaults so a brain with a different layout starts from a+ * neutral map), then the GBRAIN_SOURCE_BOOST env override. Shallow merges;+ * later layers win per prefix.*/export function resolveBoostMap(envValue: string | undefined = process.env.GBRAIN_SOURCE_BOOST,+ configValue?: string | null,): Record<string, number> {- const override = parseSourceBoostEnv(envValue);- return { ...DEFAULT_SOURCE_BOOSTS, ...override };+ const dropDefaults = (configValue ?? '').split(',').some((entry) => entry.trim() === 'none');+ return {+ ...(dropDefaults ? {} : DEFAULT_SOURCE_BOOSTS),+ ...parseSourceBoostEnv(configValue ?? undefined),+ ...parseSourceBoostEnv(envValue),+ };}/**diff --git a/src/core/search/title-match.ts b/src/core/search/title-match.tsindex f1a75fe44d..7aee241399 100644--- a/src/core/search/title-match.ts+++ b/src/core/search/title-match.ts@@ -109,3 +109,26 @@ export function isTitleMentionedInQuery(query: string, title: string): boolean {if (tContent.length < MIN_CONTENT_TOKENS && tContent[0].length < MIN_SINGLE_TOKEN_TITLE_CHARS) return false;return containsTokenRun(qTokens, tTokens);}++/** Share of the query's distinct content tokens a title must supply to count as the query's subject. */+const TITLE_SUBJECT_MIN_COVERAGE = 0.5;++/**+ * The strict form used under intents without an exact-match boost (#4694):+ * returns the title's tokens when `title` (>= MIN_CONTENT_TOKENS content+ * tokens) is mentioned in `query` AND supplies at least half of the query's+ * distinct content tokens — the query asks for this document by name ("Which+ * document is <title>?"). A title mentioned inside a longer question about+ * something else ("Which amendment superseded the <title>?") does not+ * qualify: on the #4694 benchmark boosting those sent the mentioned page+ * above the right answer. Returns null otherwise.+ */+export function titleAsQuerySubject(query: string, title: string): string[] | null {+ const tTokens = tokenizeTitle(title);+ const tContent = contentTokens(tTokens);+ if (tContent.length < MIN_CONTENT_TOKENS || !isTitleMentionedInQuery(query, title)) return null;+ const qContent = new Set(contentTokens(tokenizeTitle(query)));+ return tContent.length / qContent.size >= TITLE_SUBJECT_MIN_COVERAGE ? tTokens : null;+}++export { containsTokenRun };diff --git a/src/core/search/token-budget.ts b/src/core/search/token-budget.tsindex 430582aa68..2e771222ab 100644--- a/src/core/search/token-budget.ts+++ b/src/core/search/token-budget.ts@@ -5,11 +5,12 @@* (agents, MCP, the query op) can guarantee their search payload fits a* downstream context window. The enforcer is the LAST stage of the search* pipeline — all scoring, ranking, dedup, boosts, two-pass walk are done- * before this fires. It does NOT re-rank; it greedily walks top-down and- * stops when the next result would push the running total past the- * budget.+ * before this fires. It does NOT re-rank; it walks top-down and skips any+ * result that would push the running total past the budget (the frozen+ * `packToBudget` used by the memory verbs stops at the first one instead).*- * Token counting uses a deliberately cheap char/4 heuristic instead of+ * Token counting uses a deliberately cheap script-aware heuristic+ * (char/4, CJK 1/char) instead of* dropping in a real tokenizer (js-tiktoken is 1.5MB+ and would balloon* the bun build --compile bundle). The heuristic is accurate within* ~10-15% for English text and ~5-25% for mixed code/Unicode — over-@@ -26,19 +27,43 @@*/import type { SearchResult } from '../types.ts';+import { CJK_SLUG_CHARS } from '../cjk.ts';++const CJK_CHAR = new RegExp(`[${CJK_SLUG_CHARS}]`);+const CJK_CHARS_G = new RegExp(`[${CJK_SLUG_CHARS}]`, 'g');/**- * Cheap char/4 token estimate. Returns 0 for empty strings.+ * Cheap script-aware token estimate. Returns 0 for empty strings.*- * Why char/4: OpenAI's tokenization averages ~4 chars/token for English- * prose; closer to 3 for code with lots of punctuation; up to 8 for- * CJK. Overshoot is fine for a safety budget. Undershoot would let us- * blow past the cap, so we round UP when in doubt.+ * OpenAI-style tokenizers average ~4 chars/token for English prose (closer+ * to 3 for punctuation-heavy code) but ~1 token per CJK character, so CJK+ * characters cost 1 each and everything else char/4. Overshoot is fine for+ * a safety budget; undershoot would let a payload blow past the cap, so+ * the total rounds UP.*/export function estimateTokens(text: string | null | undefined): number {if (!text) return 0;- // Math.ceil so a 1-char string still costs at least 1 token.- return Math.ceil(text.length / 4);+ const cjk = text.match(CJK_CHARS_G)?.length ?? 0;+ return Math.ceil((text.length - cjk) / 4) + cjk;+}++/**+ * Longest prefix of `text` whose `estimateTokens` cost is <= `maxTokens`,+ * cut on a code-point boundary (never a lone surrogate).+ */+function sliceToTokens(text: string, maxTokens: number): string {+ let cjk = 0;+ let other = 0;+ let end = 0;+ for (const ch of text) {+ const nextCjk = CJK_CHAR.test(ch) ? cjk + 1 : cjk;+ const nextOther = nextCjk === cjk ? other + ch.length : other;+ if (Math.ceil(nextOther / 4) + nextCjk > maxTokens) break;+ cjk = nextCjk;+ other = nextOther;+ end += ch.length;+ }+ return text.slice(0, end);}/**@@ -155,16 +180,34 @@ export function enforceTokenBudget(results: SearchResult[],budget: number | undefined,): { results: SearchResult[]; meta: TokenBudgetMeta } {- const { items, meta } = packToBudget(results, resultTokens, budget);- if (items.length === 0 && results.length > 0 && meta.budget > 0 && searchSalvageEnabled()) {+ const safeBudget = typeof budget === 'number' && budget > 0 ? budget : 0;+ if (safeBudget === 0 || results.length === 0) {+ const passthrough = packToBudget(results, resultTokens, budget);+ return { results: passthrough.items, meta: passthrough.meta };+ }+ // Once the head fits, a result that does not fit is skipped and packing+ // continues: one oversized chunk must not drop every lower-ranked result+ // after it. An oversized HEAD still takes the minKeep path below.+ const items: SearchResult[] = [];+ let used = 0;+ for (const r of results) {+ const c = resultTokens(r);+ if (used + c <= safeBudget) {+ items.push(r);+ used += c;+ } else if (items.length === 0) {+ break;+ }+ }+ const meta: TokenBudgetMeta = { budget: safeBudget, used, dropped: results.length - items.length, kept: items.length };+ if (items.length === 0 && searchSalvageEnabled()) {const first = results[0];- // Chars that keep resultTokens(copy) <= budget under the char/4 model:- // ceil(4*(budget - titleCost)/4) = budget - titleCost. A sub-title-cost- // budget slices the title itself (budget*4 chars costs exactly budget- // tokens under ceil(len/4)), so used <= budget holds unconditionally.- const title = (first.title ?? '').slice(0, meta.budget * 4);- const chunkChars = Math.max(0, (meta.budget - estimateTokens(title)) * 4);- const copy: SearchResult = { ...first, title, chunk_text: first.chunk_text.slice(0, chunkChars) };+ // Title first (a sub-title-cost budget slices the title itself), then+ // the chunk gets what is left, both cut by estimated cost on code-point+ // boundaries, so used <= budget holds unconditionally.+ const title = sliceToTokens(first.title ?? '', meta.budget);+ const chunk = sliceToTokens(first.chunk_text, meta.budget - estimateTokens(title));+ const copy: SearchResult = { ...first, title, chunk_text: chunk };return {results: [copy],meta: {diff --git a/src/core/think/index.ts b/src/core/think/index.tsindex 9273093221..a3be2dc62c 100644--- a/src/core/think/index.ts+++ b/src/core/think/index.ts@@ -18,6 +18,7 @@*/import type Anthropic from '@anthropic-ai/sdk';+import { OperationTimeoutError, withTimeout } from '../timeout.ts';import type { BrainEngine, SynthesisEvidenceInput } from '../engine.ts';import type { SearchResult } from '../types.ts';import { runGather, renderPagesBlock, pagesBlockExcerptLen, takesHitToTakeForPrompt, selectRelevantExcerpt } from './gather.ts';@@ -624,9 +625,9 @@ export async function runThink(if (resolved.source === 'fallback_slugify') return null;if (seenSlugs.has(resolved.slug)) return null;seenSlugs.add(resolved.slug);- // 5s per-candidate timeout. Promise.race resolves with the- // first to land; the timeout returns [] (empty trajectory).- const points = await Promise.race([+ // 5s per-candidate timeout (cleared on settle); a timeout+ // is an empty trajectory, any other error rejects as before.+ const points = await withTimeout(engine.findTrajectory({entitySlug: resolved.slug,...(opts.sourceId !== undefined ? { sourceId: opts.sourceId } : {}),@@ -635,10 +636,12 @@ export async function runThink(kind: 'all',limit: 100,}),- new Promise<import('../engine.ts').TrajectoryPoint[]>(resolve => {- setTimeout(() => resolve([]), 5000);- }),- ]);+ 5000,+ 'findTrajectory',+ ).catch((err: unknown) => {+ if (err instanceof OperationTimeoutError) return [];+ throw err;+ });const boundedPoints = window ? points.filter(point => {const ms = point.valid_from.getTime();const outside = (window.startMs !== null && ms < window.startMs)diff --git a/src/core/timeline-extract.ts b/src/core/timeline-extract.tsindex cfe81f1dc9..d4c359c8f5 100644--- a/src/core/timeline-extract.ts+++ b/src/core/timeline-extract.ts@@ -11,7 +11,7 @@* names, so its existing importers are unaffected.*/-import { parseInlineCitationTimelineEntries, findTimelineSourceDelimiter } from './link-extraction.ts';+import { parseInlineCitationTimelineEntries, findTimelineSourceDelimiter, parseTimelineEntries } from './link-extraction.ts';import type { BrainEngine } from './engine.ts';import { firstMaterializedMarkerIndex } from './timeline-marker.ts';@@ -97,35 +97,115 @@ export function extractTimelineFromContent(content: string, slug: string): Extrareturn entries;}+type TimelineTuple = Pick<ExtractedTimelineEntry, 'date' | 'source' | 'summary'>;+const tupleKey = (e: TimelineTuple) => JSON.stringify([e.date, e.source, e.summary]);++/**+ * Every (date, source, summary) tuple a page text yields under either timeline+ * parser: the file-walk parser above and the DB-side parseTimelineEntries.+ * Reconciliation keeps and retracts against this union, so the file and DB+ * extraction paths never undo each other's rows.+ */+function markdownTimelineKeys(text: string, slug: string): Set<string> {+ const keys = new Set(extractTimelineFromContent(text, slug).map(tupleKey));+ for (const entry of parseTimelineEntries(text)) keys.add(tupleKey({ ...entry, source: entry.source ?? '' }));+ return keys;+}+/**- * Retract the timeline rows a page's previous text produced that its current- * text no longer does (a corrected or deleted dated bullet). The previous text- * is the page's latest version snapshot, taken before the import that changed- * it. Only exact (date, source, summary) tuples that text produced are- * removed, so rows from other producers (enrichment, meeting fan-out, event- * projections) are never touched. Returns the number of rows removed.+ * Reconcile a page's timeline rows with its current text: retract every row+ * an earlier version of the page produced that the current text no longer+ * does (a corrected or deleted dated bullet, however many edits ago). Rows no+ * version of the page ever produced (enrichment, meeting fan-out, inferred+ * anchors) and event-page projections are never touched. The page_versions+ * scan only runs when the page holds a row the current text does not produce.+ * Returns the orphaned rows; they are deleted unless `dryRun`.*/export async function retractRemovedTimelineEntries(engine: Pick<BrainEngine, 'executeRaw'>,slug: string,sourceId: string,- current: ReadonlyArray<ExtractedTimelineEntry>,-): Promise<number> {- const [previous] = await engine.executeRaw<{ compiled_truth: string; timeline: string | null }>(- `SELECT v.compiled_truth, v.timeline FROM page_versions v JOIN pages p ON p.id = v.page_id- WHERE p.source_id = $1 AND p.slug = $2 ORDER BY v.id DESC LIMIT 1`, [sourceId, slug]);- if (!previous) return 0;- const key = (e: Pick<ExtractedTimelineEntry, 'date' | 'source' | 'summary'>) => JSON.stringify([e.date, e.source, e.summary]);- const kept = new Set(current.map(key));- const removed = extractTimelineFromContent(`${previous.compiled_truth}\n${previous.timeline ?? ''}`, slug)- .filter(entry => !kept.has(key(entry)))- .map(({ date, source, summary }) => ({ date, source, summary }));- if (!removed.length) return 0;- const rows = await engine.executeRaw(- `DELETE FROM timeline_entries t USING pages p- WHERE p.id = t.page_id AND p.source_id = $1 AND p.slug = $2 AND t.event_page_id IS NULL- AND EXISTS (SELECT 1 FROM jsonb_to_recordset($3::text::jsonb) AS r(date date, source text, summary text)- WHERE r.date = t.date AND r.source = t.source AND r.summary = t.summary)- RETURNING t.id`, [sourceId, slug, JSON.stringify(removed)]);- return rows.length;+ currentText: string,+ opts: { dryRun?: boolean } = {},+): Promise<Array<TimelineTuple & { id: number }>> {+ const kept = markdownTimelineKeys(currentText, slug);+ const rows = await engine.executeRaw<TimelineTuple & { id: number }>(+ `SELECT t.id, to_char(t.date, 'YYYY-MM-DD') AS date, t.source, t.summary FROM timeline_entries t+ JOIN pages p ON p.id = t.page_id+ WHERE p.source_id = $1 AND p.slug = $2 AND t.event_page_id IS NULL`, [sourceId, slug]);+ const extra = rows.filter(row => !kept.has(tupleKey(row)));+ if (!extra.length) return [];+ const versions = await engine.executeRaw<{ compiled_truth: string; timeline: string | null }>(+ `SELECT DISTINCT v.compiled_truth, v.timeline FROM page_versions v JOIN pages p ON p.id = v.page_id+ WHERE p.source_id = $1 AND p.slug = $2`, [sourceId, slug]);+ const produced = new Set<string>();+ for (const version of versions) {+ for (const key of markdownTimelineKeys(`${version.compiled_truth}\n${version.timeline ?? ''}`, slug)) produced.add(key);+ }+ const orphans = extra.filter(row => produced.has(tupleKey(row)));+ if (!orphans.length || opts.dryRun) return orphans;+ await engine.executeRaw(+ `DELETE FROM timeline_entries WHERE id IN (SELECT jsonb_array_elements_text($1::text::jsonb)::int)`,+ [JSON.stringify(orphans.map(row => row.id))]);+ return orphans;+}++export interface TimelineOrphanPruneResult {+ pagesScanned: number;+ orphans: number;+ removed: number;+ examples: Array<{ source_id: string; slug: string; date: string; summary: string }>;+}++/**+ * Managed brains guard `timeline_entries`: the retraction runs as a coordinated+ * write under the page lock, against the text read inside that transaction.+ */+async function retractCoordinated(engine: BrainEngine, pageId: number, slug: string, sourceId: string) {+ const { withCoordinatedWrite } = await import('./persistence/context.ts');+ return engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], async () => {+ await tx.lockPageKeys([{ sourceId, slug }]);+ const [page] = await tx.executeRaw<{ compiled_truth: string; timeline: string | null }>(+ 'SELECT compiled_truth, timeline FROM pages WHERE id = $1 AND deleted_at IS NULL', [pageId]);+ return page ? retractRemovedTimelineEntries(tx, slug, sourceId, `${page.compiled_truth}\n${page.timeline ?? ''}`) : [];+ }));+}++/**+ * One-time prune of timeline rows orphaned before extraction reconciled them+ * (#4649): runs the reconciliation above against each page's stored text for+ * every live page that holds timeline rows, optionally scoped to one source+ * and capped at `limit` pages (the doctor check samples; the CLI prunes all).+ */+export async function pruneTimelineOrphans(+ engine: BrainEngine,+ opts: { sourceId?: string; dryRun: boolean; limit?: number; coordinated?: boolean },+): Promise<TimelineOrphanPruneResult> {+ const result: TimelineOrphanPruneResult = { pagesScanned: 0, orphans: 0, removed: 0, examples: [] };+ let afterId = 0;+ for (;;) {+ const pageSize = Math.min(200, (opts.limit ?? Infinity) - result.pagesScanned);+ if (pageSize <= 0) break;+ const params: unknown[] = [afterId, pageSize];+ if (opts.sourceId) params.push(opts.sourceId);+ const pages = await engine.executeRaw<{ id: number; slug: string; source_id: string; compiled_truth: string; timeline: string | null }>(+ `SELECT p.id, p.slug, p.source_id, p.compiled_truth, p.timeline FROM pages p+ WHERE p.id > $1 AND p.deleted_at IS NULL${opts.sourceId ? ' AND p.source_id = $3' : ''}+ AND EXISTS (SELECT 1 FROM timeline_entries t WHERE t.page_id = p.id AND t.event_page_id IS NULL)+ ORDER BY p.id LIMIT $2`, params);+ if (!pages.length) break;+ for (const page of pages) {+ const orphans = opts.coordinated && !opts.dryRun+ ? await retractCoordinated(engine, page.id, page.slug, page.source_id)+ : await retractRemovedTimelineEntries(engine, page.slug, page.source_id, `${page.compiled_truth}\n${page.timeline ?? ''}`, { dryRun: opts.dryRun });+ result.orphans += orphans.length;+ if (!opts.dryRun) result.removed += orphans.length;+ for (const row of orphans.slice(0, Math.max(0, 5 - result.examples.length))) {+ result.examples.push({ source_id: page.source_id, slug: page.slug, date: row.date, summary: row.summary });+ }+ }+ result.pagesScanned += pages.length;+ afterId = pages[pages.length - 1]!.id;+ }+ return result;}diff --git a/src/core/transcripts/ingest.ts b/src/core/transcripts/ingest.tsindex 7ff4945e94..efda0d6f9c 100644--- a/src/core/transcripts/ingest.ts+++ b/src/core/transcripts/ingest.ts@@ -35,9 +35,13 @@ import { detectAdapter } from './detect.ts';import {loadImportRedactionPatterns,redactSession,+ renderPartContent,renderSessionParts,+ type RenderedPart,type RenderSessionResult,} from './render.ts';+import { RECONCILE_SAFETY_KEYS } from '../persistence/reconcile-safety.ts';+import { ATOMS_SCAN_HASH_KEY } from '../utils.ts';export interface IngestActivePack {page_types: ReadonlyArray<{ name: string; path_prefixes: ReadonlyArray<string> }>;@@ -89,6 +93,8 @@ export interface IngestSessionOutcome {redactions: number;imperatives: number;error?: string;+ /** C-19: a session with no timestamps is skipped (never fabricated), not errored. */+ skipped?: 'no_timestamp';}export interface IngestFileOutcome {@@ -109,6 +115,8 @@ export interface TranscriptsIngestResult {sessionsImported: number;sessionsFiltered: number;sessionsErrored: number;+ /** Sessions with no timestamps at all: reported, not imported, not an error (C-19). */+ sessionsSkippedNoTimestamp: number;redactions: number;imperatives: number;partsDeleted: number;@@ -163,6 +171,7 @@ export async function runTranscriptsIngest(sessionsImported: 0,sessionsFiltered: 0,sessionsErrored: 0,+ sessionsSkippedNoTimestamp: 0,redactions: 0,imperatives: 0,partsDeleted: 0,@@ -258,6 +267,16 @@ export async function runTranscriptsIngest(};fileOutcome.sessions.push(outcome);+ // C-19: a session with no timestamps can never render (provenance is+ // never fabricated), so retrying it is pointless; report the skip and+ // keep the scan clean instead of freezing the --since checkpoint.+ if (!session.meta.startedAt && !session.messages.some(m => m.timestamp)) {+ outcome.skipped = 'no_timestamp';+ result.sessionsSkippedNoTimestamp++;+ step = await gen.next();+ continue;+ }+try {const redacted = redactSession(session, {userPatternsPath: opts.userPatternsPath,@@ -289,6 +308,7 @@ export async function runTranscriptsIngest(let resolvedBaseSlug = rendered.baseSlug;for (const part of rendered.parts) {try {+ await preserveForeignFrontmatter(engine, opts.sourceId ?? 'default', part);const r = await importFromContent(engine, part.slug, part.content, {noEmbed: !opts.embed,sourceId: opts.sourceId,@@ -465,6 +485,22 @@ export async function runTranscriptsIngest(* slug, the importer's cross-slug identity dedup skipped it as a duplicate* and every message added since the last import was silently dropped.*/+/**+ * Re-ingest replaces only what the collector renders (#5431): keys another+ * tool or the operator added to an imported conversation page (a review flag,+ * say) are carried onto the re-rendered part. Gate- and phase-owned markers+ * are re-derived from the new content, so they are never carried.+ */+async function preserveForeignFrontmatter(engine: BrainEngine, sourceId: string, part: RenderedPart): Promise<void> {+ const existing = await engine.getPage(part.slug, { sourceId });+ const foreign = Object.entries(existing?.frontmatter ?? {})+ .filter(([key]) => !Object.hasOwn(part.frontmatter, key) && !RE_DERIVED_KEYS.has(key));+ if (foreign.length === 0) return;+ part.content = renderPartContent({ ...part.frontmatter, ...Object.fromEntries(foreign) }, part.body);+}++const RE_DERIVED_KEYS = new Set([...RECONCILE_SAFETY_KEYS, ATOMS_SCAN_HASH_KEY]);+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`,diff --git a/src/core/transcripts/render.ts b/src/core/transcripts/render.tsindex 7f8483e4d1..63fd2f2285 100644--- a/src/core/transcripts/render.ts+++ b/src/core/transcripts/render.ts@@ -262,6 +262,13 @@ export interface RenderedPart {frontmatterId: string;part: number;of: number;+ /** The keys this collector renders (and so owns on re-ingest), and the body. */+ frontmatter: Record<string, unknown>;+ body: string;+}++export function renderPartContent(frontmatter: Record<string, unknown>, body: string): string {+ return `---\n${safeDump(frontmatter, { lineWidth: 1000 })}---\n\n${body}\n`;}export interface RenderSessionResult {@@ -366,8 +373,7 @@ export function renderSessionParts(},};const body = group.join('\n\n');- const content = `---\n${safeDump(fm, { lineWidth: 1000 })}---\n\n${body}\n`;- return { slug, content, frontmatterId, part, of };+ return { slug, content: renderPartContent(fm, body), frontmatterId, part, of, frontmatter: fm, body };});return { parts, baseSlug, dateIso };diff --git a/src/core/types.ts b/src/core/types.tsindex 7a8bb3f4d0..9444ee6aa7 100644--- a/src/core/types.ts+++ b/src/core/types.ts@@ -1160,6 +1160,12 @@ export interface SearchOpts extends PageReadPolicy {* via DEFAULT_SOURCE_BOOSTS so archived content stays findable by default.*/exclude_slug_prefixes?: string[];+ /**+ * Resolved source-boost map (prefix → factor) for the ranking arms. Set by+ * hybridSearch from the brain's `search.source_boosts` config; engines+ * fall back to `resolveBoostMap()` (defaults + env) when absent.+ */+ source_boosts?: Record<string, number>;/*** Opt-back-in list — subtracts entries from the resolved hard-exclude set.* E.g. `include_slug_prefixes: ['test/']` lets a query see test/ pages even@@ -1839,6 +1845,8 @@ export const DEGRADED_STAGES = ['expansion_partial','rescore_skipped','vector_arm_failed',+ 'keyword_arm_failed',+ 'title_arm_failed','budget_dropped_all','budget_truncated','keyword_zero',diff --git a/src/eval/longmemeval/harness.ts b/src/eval/longmemeval/harness.tsindex 07045df763..fe27c02036 100644--- a/src/eval/longmemeval/harness.ts+++ b/src/eval/longmemeval/harness.ts@@ -62,3 +62,39 @@ export async function withBenchmarkBrain<T>(await engine.disconnect();}}++/** #5092: questions per harness-owned benchmark brain before it is replaced. */+export const LME_BRAIN_RECYCLE_EVERY = 40;++/**+ * #5092 — TRUNCATE between questions never returns PGLite's WASM memory,+ * which grows with every question's vectors (~30 MB per 500-chunk question)+ * until a long single-process run stalls at 100% CPU around question 90-120.+ * `next()` hands out the brain for the next question, replacing it with a+ * fresh, re-configured one every `every` questions (0 = never). `close()`+ * disconnects a replacement; the first brain stays its owner's to close.+ */+export function brainRecycler(+ first: PGLiteEngine,+ every: number,+ create: () => Promise<PGLiteEngine>,+ configure: (engine: PGLiteEngine) => Promise<void>,+): { next(): Promise<PGLiteEngine>; close(): Promise<void> } {+ let brain = first;+ let served = 0;+ return {+ async next() {+ if (every > 0 && served === every) {+ await brain.disconnect();+ brain = await create();+ await configure(brain);+ served = 0;+ }+ served++;+ return brain;+ },+ async close() {+ if (brain !== first) await brain.disconnect();+ },+ };+}diff --git a/src/eval/longmemeval/trajectory-route.ts b/src/eval/longmemeval/trajectory-route.tsindex 5f06df0bb8..95abacb1f9 100644--- a/src/eval/longmemeval/trajectory-route.ts+++ b/src/eval/longmemeval/trajectory-route.ts@@ -14,6 +14,7 @@ import type { TrajectoryPoint } from '../../core/engine.ts';import { extractCandidateEntities } from '../../core/think/entity-extract.ts';import { resolveEntitySlugWithSource, type ResolutionSource } from '../../core/entities/resolve.ts';import { formatTrajectoryBlock } from '../../core/trajectory-format.ts';+import { OperationTimeoutError, withTimeout } from '../../core/timeout.ts';import type { Intent } from './intent.ts';export interface TrajectoryRoute {@@ -41,10 +42,14 @@ export async function routeTrajectory(// fallback_slugify results: the extractor and the lookup both slugify// free-form entity names, so they cohere on the same fallback slug// and there are no canonical pages in the benchmark to protect.- const points = await Promise.race([+ const points: TrajectoryPoint[] = await withTimeout(engine.findTrajectory({ entitySlug: resolved.slug, sourceId: 'default', remote: false, kind: 'all', limit: 100 }),- new Promise<TrajectoryPoint[]>(resolve => { setTimeout(() => resolve([]), 5000); }),- ]);+ 5000,+ 'findTrajectory',+ ).catch((err: unknown) => {+ if (err instanceof OperationTimeoutError) return [];+ throw err;+ });if (points.length === 0) continue;const fmt = formatTrajectoryBlock(points, resolved.slug, { intent });if (fmt.rendered.length === 0) continue;diff --git a/src/eval/shared/embed-cache.ts b/src/eval/shared/embed-cache.tsindex a0c6a5d7d6..17fa281729 100644--- a/src/eval/shared/embed-cache.ts+++ b/src/eval/shared/embed-cache.ts@@ -84,7 +84,8 @@ function fromBlob(blob: Uint8Array, dims: number): number[] {export class EmbeddingCache {readonly path: string;private db: Database | null = null;- private txDepth = 0;+ /** Buffered writes, one frame per open transaction (innermost last). */+ private frames: Array<Map<string, { model: string; dims: number; blob: Uint8Array }>> = [];private hits = 0;private misses = 0;private bypassed = 0;@@ -129,6 +130,13 @@ export class EmbeddingCache {get(model: string, dims: number, text: string, side: EmbedSide = 'document'): number[] | null {const db = this.requireDb();const key = this.key(model, dims, text, side);+ for (let i = this.frames.length - 1; i >= 0; i--) {+ const pending = this.frames[i].get(key);+ if (pending) {+ this.hits++;+ return fromBlob(pending.blob, dims);+ }+ }const row = withBusyRetry(() =>db.query<{ dims: number; byte_len: number; vector: Uint8Array }, [string]>(@@ -161,6 +169,11 @@ export class EmbeddingCache {throw new EmbedCacheIntegrityError(this.path, key, `vector has ${vector.length} dims, expected ${dims}`);}const blob = toBlob(vector);+ const frame = this.frames[this.frames.length - 1];+ if (frame) {+ frame.set(key, { model, dims, blob });+ return;+ }withBusyRetry(() =>db.query('INSERT OR REPLACE INTO embed_cache (key, model, dims, byte_len, vector) VALUES (?, ?, ?, ?, ?)')@@ -168,66 +181,90 @@ export class EmbeddingCache {);}- private txBegin(db: Database, depth: number): void {- withBusyRetry(() => db.exec(depth === 0 ? 'BEGIN' : `SAVEPOINT embed_cache_sp_${depth}`));- this.txDepth++;+ /**+ * Write one frame's rows in a single short `BEGIN IMMEDIATE` transaction.+ * IMMEDIATE takes the write lock up front, so a concurrent run sharing the+ * file waits on `busy_timeout` instead of failing with SQLITE_BUSY_SNAPSHOT+ * (a deferred transaction whose read snapshot went stale can never upgrade).+ */+ private flush(frame: Map<string, { model: string; dims: number; blob: Uint8Array }>): void {+ if (frame.size === 0) return;+ const db = this.requireDb();+ withBusyRetry(() => {+ db.exec('BEGIN IMMEDIATE');+ try {+ const stmt = db.query('INSERT OR REPLACE INTO embed_cache (key, model, dims, byte_len, vector) VALUES (?, ?, ?, ?, ?)');+ for (const [key, r] of frame) stmt.run(key, r.model, r.dims, r.blob.byteLength, r.blob);+ db.exec('COMMIT');+ } catch (err) {+ try { db.exec('ROLLBACK'); } catch { /* the original error is the one worth surfacing */ }+ throw err;+ }+ });}- private txEnd(db: Database, depth: number, ok: boolean): void {- try {- if (ok) db.exec(depth === 0 ? 'COMMIT' : `RELEASE embed_cache_sp_${depth}`);- else db.exec(depth === 0 ? 'ROLLBACK' : `ROLLBACK TO embed_cache_sp_${depth}; RELEASE embed_cache_sp_${depth}`);- } catch (err) {- if (ok) throw err;- /* rolling back: the original error is the one worth surfacing */- } finally {- this.txDepth--;+ /** Close the innermost frame: merge into its parent, or flush when outermost. */+ private closeFrame(): void {+ const frame = this.frames.pop()!;+ const parent = this.frames[this.frames.length - 1];+ if (parent) {+ for (const [key, r] of frame) parent.set(key, r);+ return;}+ this.flush(frame);}/**- * Run `fn` inside one transaction (BEGIN/COMMIT at depth 0, SAVEPOINT when- * nested). Accepts sync or async `fn`; rolls back on throw. Per-question- * batching: wrap one question's embeds so its writes hit the WAL once.+ * Run `fn` as one unit of writes: puts inside it are buffered in memory and+ * written in one short transaction when the outermost unit completes;+ * nested units merge into their parent; a throwing body discards its own+ * writes. Reads see buffered writes. No SQLite transaction or lock is held+ * across the async body, so concurrent runs sharing one cache file never+ * block each other on a question's network round-trips. A failed flush of+ * the outermost unit is a cache infrastructure fault (counted, warned),+ * never a failure of `fn`.*- * NOT safe for CONCURRENT async callers: SQLite savepoints are a stack, so- * two interleaved async bodies release each other's savepoints (`no such- * savepoint`). The harness calls this once per question, sequentially; the- * caching transport's write-back (which IS concurrent under expansion's- * parallel query/variant embeds) uses `transactionSync` instead.+ * NOT safe for CONCURRENT async callers (frames are a stack). The harness+ * calls this once per question, sequentially; the caching transport's+ * write-back (concurrent under expansion's parallel embeds) uses+ * `transactionSync`, which never yields.*/async withTransaction<T>(fn: () => T | Promise<T>): Promise<T> {- const db = this.requireDb();- const depth = this.txDepth;- this.txBegin(db, depth);+ this.requireDb();+ this.frames.push(new Map());let out: T;try {out = await fn();} catch (err) {- this.txEnd(db, depth, false);+ this.frames.pop();throw err;}- this.txEnd(db, depth, true);+ try {+ this.closeFrame();+ } catch (err) {+ this.infraFaults++;+ process.stderr.write(`[embed-cache] write-back failed, continuing uncached (infra_faults > 0): ${(err as Error).message}\n`);+ }return out;}/*** Synchronous sibling of `withTransaction`: `fn` runs to completion without- * yielding, so the savepoint it opens is always the innermost one when it is- * released — safe when many async callers write back concurrently inside- * one outer `withTransaction` (or with none).+ * yielding, so its frame is always the innermost one when it closes — safe+ * when many async callers write back concurrently inside one outer+ * `withTransaction` (or with none, when it flushes immediately). Throws on a+ * failed flush so the caller can account the fault.*/transactionSync(fn: () => void): void {- const db = this.requireDb();- const depth = this.txDepth;- this.txBegin(db, depth);+ this.requireDb();+ this.frames.push(new Map());try {fn();} catch (err) {- this.txEnd(db, depth, false);+ this.frames.pop();throw err;}- this.txEnd(db, depth, true);+ this.closeFrame();}/** Bypass accounting for the caching transport (see installEmbedCache). */@@ -272,7 +309,7 @@ export class EmbeddingCache {*/canonicalSha256(): string {const db = this.requireDb();- if (this.txDepth === 0) {+ if (this.frames.length === 0) {try {db.exec('PRAGMA wal_checkpoint(TRUNCATE)');} catch {@@ -296,7 +333,7 @@ export class EmbeddingCache {* `canonicalSha256` for `run_config.cache`. */fileSha256(): string {const db = this.requireDb();- if (this.txDepth === 0) {+ if (this.frames.length === 0) {try {db.exec('PRAGMA wal_checkpoint(TRUNCATE)');} catch {diff --git a/src/schema.sql b/src/schema.sqlindex 3f38bdebe9..b7bb6fe31a 100644--- a/src/schema.sql+++ b/src/schema.sql@@ -513,6 +513,8 @@ CREATE TABLE IF NOT EXISTS tags (id SERIAL PRIMARY KEY,page_id INTEGER NOT NULL REFERENCES pages(id) ON DELETE CASCADE,tag TEXT NOT NULL,+ -- 'frontmatter' (import-owned, deleted when it leaves the frontmatter), 'added', or NULL (legacy).+ tag_source TEXT,UNIQUE(page_id, tag));diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.mdindex 2db7729509..1c7ac74e4d 100644--- a/templates/bootstrap/template-repo/README.md+++ b/templates/bootstrap/template-repo/README.md@@ -1,6 +1,6 @@# gbrain agent workspace — template-<!-- gbrain-template-stamp: 0.60.5.0 -->+<!-- gbrain-template-stamp: 0.60.6.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/attendance-retrieval.test.ts b/test/attendance-retrieval.test.tsindex 2f8fc65707..c8d07f095d 100644--- a/test/attendance-retrieval.test.ts+++ b/test/attendance-retrieval.test.ts@@ -96,16 +96,15 @@ for (const kind of testBackends()) {capabilities: { embeddings: { available: false }, extraction: { available: false }, search: 'keyword-only', mode: 'keyless' } });}for (const lane of ['fs-sync', 'fs-incremental', 'fs-batch']) {- // The per-slug sync lanes replace a page's own markdown-derived links- // (the put_page contract); the full-walk batch lane stays additive.- const replaces = lane !== 'fs-batch';- test(`${lane}: ordinary meeting links ${replaces ? 'are replaced like put_page' : 'keep additive filesystem handling'}`, async () => {+ // Every filesystem lane, the full walk included, replaces a page's own+ // markdown-derived links (the put_page contract).+ test(`${lane}: ordinary meeting links are replaced like put_page`, async () => {await seed(meeting, 'meeting', '[Alice](../people/alice-example.md)');await extract(lane);expect((await engine.getLinks(meeting, { sourceId })).map(row => row.to_slug)).toEqual([person]);await seed(meeting, 'meeting', 'An ordinary reference was removed, with no attendance claim.');await extract(lane);- expect((await engine.getLinks(meeting, { sourceId })).map(row => row.to_slug)).toEqual(replaces ? [] : [person]);+ expect((await engine.getLinks(meeting, { sourceId })).map(row => row.to_slug)).toEqual([]);});test(`${lane}: unchanged DB-only attendance survives and real evidence removal retracts it`, async () => {await seed(meeting, 'meeting', positive);diff --git a/test/attribution-rules-opt-in.test.ts b/test/attribution-rules-opt-in.test.tsnew file mode 100644index 0000000000..bedcdbb7d5--- /dev/null+++ b/test/attribution-rules-opt-in.test.ts@@ -0,0 +1,40 @@+/**+ * #5425: the speaker/withdrawal prompt rules proposed by @clatyceo are+ * opt-in (a matched run measured no benefit and a small cat15 recall drop).+ * Default prompts are unchanged; the config keys add the rules, and+ * propose-takes caches opt-in extractions under their own prompt version.+ */+import { describe, expect, test } from 'bun:test';+import { __testing } from '../src/core/cycle/synthesize.ts';+import { defaultExtractor, EXTRACT_TAKES_ATTRIBUTION_RULES } from '../src/core/cycle/propose-takes.ts';+import { __setChatTransportForTests, configureGateway, resetGateway, type ChatOpts } from '../src/core/ai/gateway.ts';++const transcript = { filePath: '/t/x.txt', basename: 'x', content: 'User: hi', contentHash: 'a'.repeat(64) };++describe('attribution rules are opt-in (#5425)', () => {+ test('the synthesis prompt carries rule 8 only when enabled', () => {+ const build = (on: boolean) => __testing.buildSynthesisPrompt(transcript as never, 'User: hi', 0, 1, '', 'wiki', '', '', [], undefined, undefined, 'oneshot', '2026-09-29', on);+ expect(build(false)).not.toContain('Keep the speaker and source timing explicit');+ expect(build(true)).toContain('8. Keep the speaker and source timing explicit');+ });++ test('the propose-takes extractor adds the rules only when enabled', async () => {+ configureGateway({ chat_model: 'anthropic:claude-sonnet-4-6', env: { ANTHROPIC_API_KEY: 'sk-test' } } as never);+ const prompts: string[] = [];+ __setChatTransportForTests(async (o: ChatOpts) => {+ prompts.push(String(o.messages?.[0]?.content ?? ''));+ return { text: '[]', blocks: [{ type: 'text', text: '[]' }], stopReason: 'end',+ usage: { input_tokens: 1, output_tokens: 1, cache_read_tokens: 0, cache_creation_tokens: 0 }, model: o.model ?? 'x', providerId: 'anthropic' };+ });+ try {+ const input = { pagePath: 'wiki/x', pageBody: 'Some prose.', existingTakes: [] };+ await defaultExtractor(input);+ await defaultExtractor({ ...input, attributionRules: true });+ } finally {+ __setChatTransportForTests(null);+ resetGateway();+ }+ expect(prompts[0]).not.toContain(EXTRACT_TAKES_ATTRIBUTION_RULES.trim());+ expect(prompts[1]).toContain(EXTRACT_TAKES_ATTRIBUTION_RULES.trim());+ });+});diff --git a/test/budget-meter-fail-closed.test.ts b/test/budget-meter-fail-closed.test.tsnew file mode 100644index 0000000000..13281c729e--- /dev/null+++ b/test/budget-meter-fail-closed.test.ts@@ -0,0 +1,121 @@+// Write-path audit C-16: dream budget meter gaps.+// - A model missing from the pricing table is metered at a conservative+// fallback rate instead of bypassing the gate; `dream.budget.allow_unpriced`+// restores the bypass.+// - A budget of 0 spends nothing everywhere; `unlimited` is the explicit+// no-cap value.+// - Drift estimates its input tokens from the actual prompt.++import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { BudgetMeter, parseBudgetUsd, loadAllowUnpriced, _resetBudgetMeterWarningsForTest } from '../src/core/cycle/budget-meter.ts';+import { runPhaseDrift } from '../src/core/cycle/drift.ts';++let tmpDir: string;++beforeEach(() => {+ tmpDir = mkdtempSync(join(tmpdir(), 'budget-fail-closed-'));+ _resetBudgetMeterWarningsForTest();+});++describe('BudgetMeter fails closed', () => {+ test('an unpriced model is metered at the fallback rate and denied past the cap', () => {+ const meter = new BudgetMeter({ budgetUsd: 0.001, phase: 'drift', auditPath: join(tmpDir, 'a.jsonl') });+ const r = meter.check({ modelId: 'proxy:unknown-alias', estimatedInputTokens: 100_000, maxOutputTokens: 10_000, label: 'x' });+ expect(r.unpriced).toBe(true);+ expect(r.allowed).toBe(false);+ expect(r.estimatedCostUsd).toBeGreaterThan(0);+ });++ test('local model servers cost nothing and are never capped by the fallback rate', () => {+ const meter = new BudgetMeter({ budgetUsd: 0.001, phase: 'drift', auditPath: join(tmpDir, 'l.jsonl') });+ for (const modelId of ['ollama:llama3.3', 'lmstudio:qwen3-8b', 'llama-server:local']) {+ const r = meter.check({ modelId, estimatedInputTokens: 1e6, maxOutputTokens: 1e5, label: modelId });+ expect(r.allowed).toBe(true);+ expect(r.estimatedCostUsd).toBe(0);+ expect(r.unpriced).toBeFalsy();+ }+ });++ test('allowUnpriced restores the documented bypass', () => {+ const meter = new BudgetMeter({ budgetUsd: 0.001, phase: 'drift', auditPath: join(tmpDir, 'b.jsonl'), allowUnpriced: true });+ const r = meter.check({ modelId: 'proxy:unknown-alias', estimatedInputTokens: 100_000, maxOutputTokens: 10_000, label: 'x' });+ expect(r.unpriced).toBe(true);+ expect(r.allowed).toBe(true);+ });++ test('a budget of 0 spends nothing; Infinity is the explicit no-cap value', () => {+ const zero = new BudgetMeter({ budgetUsd: 0, phase: 'drift', auditPath: join(tmpDir, 'c.jsonl') });+ expect(zero.check({ modelId: 'claude-opus-4-7', estimatedInputTokens: 100, maxOutputTokens: 100, label: 'z' }).allowed).toBe(false);+ const open = new BudgetMeter({ budgetUsd: Infinity, phase: 'drift', auditPath: join(tmpDir, 'd.jsonl') });+ expect(open.check({ modelId: 'claude-opus-4-7', estimatedInputTokens: 1e7, maxOutputTokens: 1e6, label: 'u' }).allowed).toBe(true);+ expect(open.check({ modelId: 'proxy:unknown-alias', estimatedInputTokens: 1e7, maxOutputTokens: 1e6, label: 'u2' }).allowed).toBe(true);+ });++ test('parseBudgetUsd: 0 is honored, negatives clamp to 0, unlimited is Infinity, garbage falls back', () => {+ expect(parseBudgetUsd('0', 1)).toBe(0);+ expect(parseBudgetUsd('2.5', 1)).toBe(2.5);+ expect(parseBudgetUsd(3, 1)).toBe(3);+ expect(parseBudgetUsd('unlimited', 1)).toBe(Infinity);+ expect(parseBudgetUsd(' Unlimited ', 1)).toBe(Infinity);+ expect(parseBudgetUsd('-1', 1)).toBe(0);+ expect(parseBudgetUsd('abc', 1)).toBe(1);+ expect(parseBudgetUsd('', 1)).toBe(1);+ expect(parseBudgetUsd(null, 1)).toBe(1);+ expect(parseBudgetUsd(undefined, 1)).toBe(1);+ });+});++describe('drift budget', () => {+ let engine: PGLiteEngine;+ beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ const page = await engine.putPage('people/dana-example', { title: 'Dana', type: 'person', compiled_truth: 'Dana content' });+ await engine.addTakesBatch([{ page_id: page.id, row_num: 1, claim: 'Strong operator', kind: 'take', holder: 'brain', weight: 0.6 }]);+ const today = new Date().toISOString().slice(0, 10);+ await engine.addTimelineEntriesBatch(Array.from({ length: 12 }, (_, i) => ({+ slug: 'people/dana-example', date: today, source: `meeting-${i}`, summary: `Long notes ${i}: ${'word '.repeat(800)}`,+ })));+ await engine.setConfig('dream.drift.enabled', 'true');+ await engine.setConfig('models.drift', 'anthropic:claude-sonnet-4-6');+ }, 60_000);+ afterAll(async () => {+ await engine.disconnect();+ rmSync(tmpDir, { recursive: true, force: true });+ });++ async function judgeCalls(budget: string): Promise<{ calls: number; status: string }> {+ await engine.setConfig('dream.drift.budget', budget);+ let calls = 0;+ const r = await runPhaseDrift(engine, {+ dryRun: false,+ auditPath: join(tmpDir, `drift-${budget}.jsonl`),+ judge: async () => { calls++; return { drifted: false, confidence: 0.5, reasoning: '' }; },+ });+ return { calls, status: r.status };+ }++ test('the input estimate follows the real evidence size', async () => {+ // ~12k tokens of evidence cannot fit $0.02 at Sonnet rates; the old fixed+ // 1,500-token estimate said it could.+ expect(await judgeCalls('0.02')).toEqual({ calls: 0, status: 'partial' });+ expect((await judgeCalls('1.0')).calls).toBe(1);+ });++ test('"0" spends nothing and "unlimited" has no cap', async () => {+ expect((await judgeCalls('0')).calls).toBe(0);+ expect((await judgeCalls('unlimited')).calls).toBe(1);+ });++ test('loadAllowUnpriced reads dream.budget.allow_unpriced', async () => {+ expect(await loadAllowUnpriced(engine)).toBe(false);+ await engine.setConfig('dream.budget.allow_unpriced', 'true');+ expect(await loadAllowUnpriced(engine)).toBe(true);+ await engine.setConfig('dream.budget.allow_unpriced', 'false');+ });+});diff --git a/test/budget-meter.test.ts b/test/budget-meter.test.tsindex cf520d882c..67995b0810 100644--- a/test/budget-meter.test.ts+++ b/test/budget-meter.test.ts@@ -45,20 +45,24 @@ describe('BudgetMeter', () => {expect(r2.reason).toContain('BUDGET_EXHAUSTED');});- test('budget=0 disables the gate (cycle runs unbounded)', () => {- const meter = new BudgetMeter({ budgetUsd: 0, phase: 'drift', auditPath });+ test('budget=0 spends nothing; Infinity is the explicit no-cap value (C-16)', () => {+ const zero = new BudgetMeter({ budgetUsd: 0, phase: 'drift', auditPath });+ expect(zero.check({ modelId: 'claude-opus-4-7', estimatedInputTokens: 100_000, maxOutputTokens: 100_000, label: 'huge' }).allowed).toBe(false);+ const meter = new BudgetMeter({ budgetUsd: Infinity, phase: 'drift', auditPath });const r = meter.check({ modelId: 'claude-opus-4-7', estimatedInputTokens: 100_000, maxOutputTokens: 100_000, label: 'huge' });expect(r.allowed).toBe(true);});- test('non-Anthropic model bypasses gate with warn-once + ledger entry', () => {+ test('an unpriced model is metered at the fallback rate with warn-once + ledger entry (C-16)', () => {const meter = new BudgetMeter({ budgetUsd: 0.001, phase: 'auto_think', auditPath });const r1 = meter.check({ modelId: 'gemini-3-pro', estimatedInputTokens: 1000, maxOutputTokens: 1000, label: 'gem1' });const r2 = meter.check({ modelId: 'gemini-3-pro', estimatedInputTokens: 1000, maxOutputTokens: 1000, label: 'gem2' });- expect(r1.allowed).toBe(true);+ expect(r1.allowed).toBe(false);expect(r1.unpriced).toBe(true);- expect(r2.allowed).toBe(true);+ expect(r2.allowed).toBe(false);expect(meter.unpricedSubmits).toBe(2);+ const bypass = new BudgetMeter({ budgetUsd: 0.001, phase: 'auto_think', auditPath, allowUnpriced: true });+ expect(bypass.check({ modelId: 'gemini-3-pro', estimatedInputTokens: 1000, maxOutputTokens: 1000, label: 'gem3' }).allowed).toBe(true);});test('a canonical-priced non-Anthropic model is gated, not waved through', () => {@@ -79,16 +83,16 @@ describe('BudgetMeter', () => {expect(readLedger().at(-1)!.event).toBe('submit_denied');});- test('a model absent from the canonical table keeps the documented bypass', () => {- // Unchanged behaviour: gemini-3-pro is in neither table. Whether these- // should also be gated (via a conservative fallback rate, as- // synthesize-concepts and skillopt/preflight do) is a policy call and is- // deliberately not decided here.+ test('a model absent from the canonical table is gated at a conservative fallback rate (C-16)', () => {+ // gemini-3-pro is in neither table. Like synthesize-concepts and+ // skillopt/preflight, it is metered at Sonnet-tier rates;+ // dream.budget.allow_unpriced=true is the explicit bypass.const meter = new BudgetMeter({ budgetUsd: 0.001, phase: 'auto_think', auditPath });const r = meter.check({ modelId: 'gemini-3-pro', estimatedInputTokens: 1000, maxOutputTokens: 1000, label: 'absent' });expect(r.unpriced).toBe(true);- expect(r.allowed).toBe(true);+ expect(r.allowed).toBe(false);expect(readLedger().at(-1)!.event).toBe('submit_unpriced');+ expect(readLedger().at(-1)!.allowed).toBe(false);});test('Anthropic ids price identically through canonical and the derived view', () => {diff --git a/test/config-search-registry.test.ts b/test/config-search-registry.test.tsindex 7cb3d6f1bd..f65998538a 100644--- a/test/config-search-registry.test.ts+++ b/test/config-search-registry.test.ts@@ -26,6 +26,8 @@ const DIRECTLY_READ_SINGLETONS = [REMOTE_PRIVATE_PAGES_KEY, // search/private-visibility.ts'search.track_retrieval', // last-retrieved.ts'search.intent_patterns', // search/query-intent.ts+ 'search.source_boosts', // search/mode.ts snapshot + ops/search.ts+ 'search.alias_token_hop', // search/mode.ts snapshot'search.adaptive_return', // return-policy.ts via loadConfigWithEngine'search.adaptive_return_entity_max','search.adaptive_return_other_max',diff --git a/test/connectors-provider-pagination.test.ts b/test/connectors-provider-pagination.test.tsnew file mode 100644index 0000000000..ffa7ecac63--- /dev/null+++ b/test/connectors-provider-pagination.test.ts@@ -0,0 +1,138 @@+/**+ * Write-path audit C-17 / C-18: connector list passes never silently drop+ * conversations.+ * - Claude: chat_conversations is paged with limit/offset (the endpoint+ * caps an unpaged list), every chat-capable org is listed, and timestamps+ * are normalized to Z-form ISO like ChatGPT's.+ * - ChatGPT: a conversation removed from the list mid-walk (archived or+ * deleted) shifts later items to lower offsets; the walk re-covers the+ * shifted boundary instead of skipping it, and yields each id once.+ */+import { describe, expect, test } from 'bun:test';+import { ConnectorClient } from '../src/core/connectors/client.ts';+import { claudeProvider } from '../src/core/connectors/providers/claude.ts';+import { chatgptProvider } from '../src/core/connectors/providers/chatgpt.ts';+import type { ConversationStub } from '../src/core/connectors/types.ts';++function json(body: unknown, status = 200): Response {+ return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });+}++function clientFor(baseUrl: string, handler: (url: URL) => Response, seen: string[] = []): ConnectorClient {+ return new ConnectorClient({+ baseUrl,+ headers: async () => ({}),+ sleep: () => Promise.resolve(),+ fetchImpl: async (input: string) => {+ const url = new URL(input);+ seen.push(url.pathname + url.search);+ return handler(url);+ },+ });+}++async function collect(gen: AsyncGenerator<ConversationStub>): Promise<ConversationStub[]> {+ const out: ConversationStub[] = [];+ for await (const s of gen) out.push(s);+ return out;+}++describe('claude connector listing (C-17)', () => {+ const iso = (i: number) => new Date(Date.UTC(2026, 7, 1) + i * 60_000).toISOString();+ function claudeServer(orgs: Array<{ uuid: string; capabilities?: string[]; convs: number }>) {+ return (url: URL): Response => {+ if (url.pathname === '/api/organizations') return json(orgs.map(o => ({ uuid: o.uuid, capabilities: o.capabilities })));+ const list = url.pathname.match(/^\/api\/organizations\/([^/]+)\/chat_conversations$/);+ if (list) {+ const org = orgs.find(o => o.uuid === list[1]);+ if (!org || (org.capabilities && !org.capabilities.includes('chat'))) return json({ error: 'forbidden' }, 403);+ // Newest-first; an unpaged request is capped like the live endpoint.+ const rows = Array.from({ length: org.convs }, (_, i) => ({+ uuid: `${org.uuid}-c${i}`, name: `c${i}`,+ created_at: iso(org.convs - i),+ updated_at: iso(org.convs - i).replace('Z', '123+00:00').replace('.000', '.000'),+ }));+ const limit = Math.min(Number(url.searchParams.get('limit') ?? '50'), 100);+ const offset = Number(url.searchParams.get('offset') ?? '0');+ return json(rows.slice(offset, offset + limit));+ }+ const detail = url.pathname.match(/^\/api\/organizations\/([^/]+)\/chat_conversations\/([^/]+)$/);+ if (detail) {+ if (!detail[2].startsWith(`${detail[1]}-`)) return json({ error: 'not found' }, 404);+ return json({ uuid: detail[2], name: 'x', chat_messages: [{ uuid: 'm', sender: 'human', created_at: iso(0), text: 'hi' }] });+ }+ return json({ error: 'unhandled' }, 404);+ };+ }++ test('pages past the endpoint cap and lists every conversation once', async () => {+ const client = clientFor('https://claude.ai', claudeServer([{ uuid: 'org-a', capabilities: ['chat'], convs: 230 }]));+ const stubs = await collect(claudeProvider.listConversations(client, {}));+ expect(stubs).toHaveLength(230);+ expect(new Set(stubs.map(s => s.id)).size).toBe(230);+ });++ test('lists every chat-capable org and fetches each conversation from its own org', async () => {+ const seen: string[] = [];+ const client = clientFor('https://claude.ai', claudeServer([+ { uuid: 'org-a', capabilities: ['chat', 'claude_max'], convs: 3 },+ { uuid: 'org-api', capabilities: ['api'], convs: 5 },+ { uuid: 'org-b', capabilities: ['chat'], convs: 2 },+ ]), seen);+ const stubs = await collect(claudeProvider.listConversations(client, {}));+ expect(stubs.map(s => s.id).sort()).toEqual(['org-a-c0', 'org-a-c1', 'org-a-c2', 'org-b-c0', 'org-b-c1']);+ const conv = await claudeProvider.fetchConversation(client, 'org-b-c1', {});+ expect(conv.uuid).toBe('org-b-c1');+ expect(seen.some(p => p.startsWith('/api/organizations/org-api/chat_conversations'))).toBe(false);+ });++ test('timestamps are normalized to Z-form ISO', async () => {+ const client = clientFor('https://claude.ai', claudeServer([{ uuid: 'org-a', capabilities: ['chat'], convs: 1 }]));+ const [stub] = await collect(claudeProvider.listConversations(client, {}));+ expect(stub.updatedAt).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/);+ expect(stub.createdAt).toMatch(/Z$/);+ });+});++describe('chatgpt connector listing (C-18)', () => {+ test('a conversation archived mid-walk does not make the walk skip its neighbour', async () => {+ const active = Array.from({ length: 60 }, (_, i) => ({ id: `c${i}`, title: `c${i}`, create_time: 1_786_000_000 - i * 60, update_time: 1_786_000_000 - i * 60 }));+ const archived: typeof active = [];+ let listCalls = 0;+ const client = clientFor('https://chatgpt.com', (url) => {+ if (url.pathname !== '/backend-api/conversations') return json({ error: 'unhandled' }, 404);+ const isArchived = url.searchParams.get('is_archived') === 'true';+ const pool = isArchived ? archived : active;+ const offset = Number(url.searchParams.get('offset'));+ const limit = Number(url.searchParams.get('limit'));+ const body = { items: pool.slice(offset, offset + limit), total: pool.length, offset, limit };+ // The user archives c3 right after the first page was served.+ if (!isArchived && ++listCalls === 1) archived.push(...active.splice(3, 1));+ return json(body);+ });+ const stubs = await collect(chatgptProvider.listConversations(client, {}));+ const ids = stubs.map(s => s.id);+ expect(new Set(ids).size).toBe(ids.length);+ expect(ids.sort()).toEqual(Array.from({ length: 60 }, (_, i) => `c${i}`).sort());+ });++ test('a conversation updated mid-walk is yielded once', async () => {+ const active = Array.from({ length: 40 }, (_, i) => ({ id: `c${i}`, title: `c${i}`, create_time: 1_786_000_000 - i * 60, update_time: 1_786_000_000 - i * 60 }));+ let listCalls = 0;+ const client = clientFor('https://chatgpt.com', (url) => {+ const isArchived = url.searchParams.get('is_archived') === 'true';+ const pool = isArchived ? [] : active;+ const offset = Number(url.searchParams.get('offset'));+ const limit = Number(url.searchParams.get('limit'));+ const body = { items: pool.slice(offset, offset + limit), total: pool.length, offset, limit };+ // c35 gets a new message and moves to the top after the first page.+ if (!isArchived && ++listCalls === 1) {+ const [moved] = active.splice(35, 1);+ active.unshift({ ...moved, update_time: 1_786_000_500 });+ }+ return json(body);+ });+ const ids = (await collect(chatgptProvider.listConversations(client, {}))).map(s => s.id);+ expect(new Set(ids).size).toBe(ids.length);+ });+});diff --git a/test/cycle-date-consistency.test.ts b/test/cycle-date-consistency.test.tsnew file mode 100644index 0000000000..2b3f7d6fe5--- /dev/null+++ b/test/cycle-date-consistency.test.ts@@ -0,0 +1,71 @@+// Write-path audit C-15: every dream phase uses one calendar date per cycle,+// resolved by `resolveCycleDate` (cycle.timezone > host timezone > UTC),+// never the UTC day from `toISOString().slice(0, 10)`.++import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { readdirSync, readFileSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { runPhaseDrift } from '../src/core/cycle/drift.ts';+import { shiftCalendarDate } from '../src/core/cycle/cycle-date.ts';+import { __testing } from '../src/core/cycle/synthesize.ts';++const ROOT = join(import.meta.dir, '..');++describe('cycle date lint', () => {+ test('no phase under src/core/cycle derives "today" from the UTC day', () => {+ const files = [+ join(ROOT, 'src/core/cycle.ts'),+ ...readdirSync(join(ROOT, 'src/core/cycle'), { recursive: true })+ .map(String).filter(f => f.endsWith('.ts')).map(f => join(ROOT, 'src/core/cycle', f)),+ ].filter(f => !f.endsWith('cycle-date.ts'));+ const offenders = files.flatMap(file => readFileSync(file, 'utf8').split('\n')+ .map((line, i) => ({ line, at: `${file.slice(ROOT.length + 1)}:${i + 1}` }))+ .filter(({ line }) => /toISOString\(\)\.slice\(0,\s*10\)/.test(line) && !line.trim().startsWith('//') && !line.trim().startsWith('*'))+ .map(({ at }) => at));+ expect(offenders).toEqual([]);+ });++ test('shiftCalendarDate does calendar arithmetic on the date string', () => {+ expect(shiftCalendarDate('2026-03-01', -1)).toBe('2026-02-28');+ expect(shiftCalendarDate('2026-12-31', 1)).toBe('2027-01-01');+ expect(shiftCalendarDate('2026-09-29', -30)).toBe('2026-08-30');+ });+});++describe('phases take the cycle date', () => {+ let engine: PGLiteEngine;+ beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ }, 60_000);+ afterAll(async () => {+ await engine.disconnect();+ });++ test('drift dates its report and lookback window by the cycle date', async () => {+ const page = await engine.putPage('people/erin-example', { title: 'Erin', type: 'person', compiled_truth: 'Erin' });+ await engine.addTakesBatch([{ page_id: page.id, row_num: 1, claim: 'Careful operator', kind: 'take', holder: 'brain', weight: 0.6 }]);+ await engine.addTimelineEntriesBatch([{ slug: 'people/erin-example', date: '2030-01-15', source: 'meeting', summary: 'Changed roles' }]);+ await engine.setConfig('dream.drift.enabled', 'true');+ await engine.setConfig('models.drift', 'anthropic:claude-sonnet-4-6');+ const r = await runPhaseDrift(engine, {+ dryRun: false,+ cycleDate: '2030-01-20',+ auditPath: join(tmpdir(), `drift-cycle-date-${process.pid}.jsonl`),+ judge: async () => ({ drifted: true, confidence: 0.9, reasoning: 'moved' }),+ });+ expect(r.status).toBe('complete');+ expect(await engine.getPage('reports/drift-2030-01-20')).not.toBeNull();+ }, 30_000);++ test('the synthesis prompt dates undated sources by the cycle date', () => {+ const prompt = __testing.buildSynthesisPrompt(+ { filePath: '/c/undated.txt', basename: 'undated', content: 'x', contentHash: 'a'.repeat(64) } as never,+ 'chunk', 0, 1, '', 'wiki', '', '', [], undefined, undefined, 'oneshot', '2030-01-20',+ );+ expect(prompt).toContain('2030-01-20');+ });+});diff --git a/test/cycle-repeated-consolidation.test.ts b/test/cycle-repeated-consolidation.test.tsindex d04b4e2e91..606cc2ce18 100644--- a/test/cycle-repeated-consolidation.test.ts+++ b/test/cycle-repeated-consolidation.test.ts@@ -2,7 +2,8 @@* Repeated-consolidation regression pin (gbrain 10x plan, amendment 7).** Three real dream cycles on a fixed brain with a scripted model that- * invents quotes, swaps speakers and invents numbers, including edits into+ * invents quotes, swaps speakers, invents numbers and states one speaker's+ * proposal as another speaker's decision (#5425), including edits into* existing pages. See test/helpers/repeated-consolidation.ts for the design* and scripts/repeated-consolidation-experiment.ts for the printable run.*@@ -20,8 +21,8 @@ describe('repeated consolidation: three dream cycles with invented claims', () =const m = await runRepeatedConsolidation();for (const c of m.per_cycle) expect(c.statuses).toEqual({ synthesize: 'ok', extract: 'ok', extract_facts: 'ok' });- expect(m.claims_by_kind).toEqual({ valid: 13, fabricated_quote: 6, speaker_swap: 3, invented_number: 6, unquoted_invention: 2 });- expect(m.invented_active_by_kind).toEqual({ fabricated_quote: 0, speaker_swap: 0, invented_number: 0, unquoted_invention: 2 });+ expect(m.claims_by_kind).toEqual({ valid: 14, fabricated_quote: 6, speaker_swap: 3, invented_number: 6, misattributed_decision: 1, unquoted_invention: 2 });+ expect(m.invented_active_by_kind).toEqual({ fabricated_quote: 0, speaker_swap: 0, invented_number: 0, misattributed_decision: 0, unquoted_invention: 2 });expect(m.invented_active_ids.sort()).toEqual(['c1-unq', 'c3-unq']);expect(m.wrong_attribution_active).toBe(0);diff --git a/test/cycle-synthesize-daily-cap.test.ts b/test/cycle-synthesize-daily-cap.test.tsindex d033bacf03..bd346179b4 100644--- a/test/cycle-synthesize-daily-cap.test.ts+++ b/test/cycle-synthesize-daily-cap.test.ts@@ -380,7 +380,7 @@ describe('daily cap — engaged', () => {}}, 60_000);- test('fail-open: a throwing count query warns to stderr and skips the cap for the run', async () => {+ test('fail-closed (C-13): a throwing count query warns to stderr and submits nothing this run', async () => {const rig = await setupRig();try {await rig.engine.setConfig('dream.synthesize.max_submissions_per_source_per_day', '1');@@ -409,14 +409,59 @@ describe('daily cap — engaged', () => {};try {const details = await runPhase(rig);- expect(details.children_submitted).toBe(1); // cap skipped, phase proceeded+ expect(details.children_submitted).toBe(0);+ expect(details.skips.map(s => s.reason)).toEqual(['daily_cap_unavailable: count query failed']);} finally {(process.stderr as unknown as { write: typeof origWrite }).write = origWrite;// Remove the own-property patch so the SHARED engine's prototype// method is restored for subsequent tests in this file.delete (rig.engine as unknown as { executeRaw?: unknown }).executeRaw;}- expect(stderrChunks.join('')).toMatch(/daily-cap count query failed.*skipping the cap/s);+ expect(stderrChunks.join('')).toMatch(/daily-cap count query failed.*submitting nothing/s);+ } finally {+ await rig.cleanup();+ }+ }, 60_000);+});++describe('USD budget gate (C-13)', () => {+ test('the default budget admits a normal run', async () => {+ const rig = await setupRig();+ try {+ await seedPassingFile(rig, '2026-08-10-a.txt');+ const details = await runPhase(rig) as CapDetails & { budget_usd: number; estimated_spend_usd: number };+ expect(details.children_submitted).toBe(1);+ expect(details.budget_usd).toBe(5);+ expect(details.estimated_spend_usd).toBeGreaterThan(0);+ } finally {+ await rig.cleanup();+ }+ }, 60_000);++ test('a submission whose estimate crosses dream.synthesize.budget_usd is deferred before any spend', async () => {+ const rig = await setupRig();+ try {+ await rig.engine.setConfig('models.dream.synthesize', 'anthropic:claude-sonnet-4-6');+ await rig.engine.setConfig('dream.synthesize.budget_usd', '0.0001');+ await seedPassingFile(rig, '2026-08-11-a.txt');+ await seedPassingFile(rig, '2026-08-12-b.txt');+ const details = await runPhase(rig) as CapDetails & { budget_deferred_transcripts: string[] };+ expect(details.children_submitted).toBe(0);+ expect(details.budget_deferred_transcripts.sort()).toEqual(['2026-08-11-a.txt', '2026-08-12-b.txt']);+ expect(await rig.engine.getConfig('dream.synthesize.last_completion_ts')).toBeNull();+ } finally {+ await rig.cleanup();+ }+ }, 60_000);++ test('"0" spends nothing; "unlimited" removes the cap', async () => {+ const rig = await setupRig();+ try {+ await rig.engine.setConfig('dream.synthesize.budget_usd', '0');+ await seedPassingFile(rig, '2026-08-13-a.txt');+ expect((await runPhase(rig)).children_submitted).toBe(0);+ await rig.engine.setConfig('dream.synthesize.budget_usd', 'unlimited');+ expect((await runPhase(rig)).children_submitted).toBe(1);} finally {await rig.cleanup();}diff --git a/test/cycle-synthesize-dream-ownership.test.ts b/test/cycle-synthesize-dream-ownership.test.tsnew file mode 100644index 0000000000..bb5aeb5dbd--- /dev/null+++ b/test/cycle-synthesize-dream-ownership.test.ts@@ -0,0 +1,110 @@+/**+ * Dream output ownership (write-path audit C-8, #5685 follow-up).+ *+ * A page is the run's own only when a child created it. The provenance stamp+ * (`dream_generated`) and whole-page grounding apply to the run's own pages;+ * a human page a child edited, or a page another writer created while the+ * child ran, keeps its identity and is verified only on the child's new units.+ */++import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { mkdtempSync, readFileSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { __testing } from '../src/core/cycle/synthesize.ts';+import { readVerifyEpoch, verifyAndRepairDreamPages } from '../src/core/cycle/synthesize-verify.ts';+import { importFromContent } from '../src/core/import-file.ts';++const { collectChildPutPageSlugs, stampDreamProvenance, reverseWriteRefs } = __testing;++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ await engine.executeRaw(`INSERT INTO minion_jobs (submission_authority, id, queue, name, data, status)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 4001, 'default', 'subagent', '{}'::jsonb, 'completed')`);+}, 60_000);++afterAll(async () => {+ await engine.disconnect();+});++const tick = () => new Promise(resolve => setTimeout(resolve, 10));++async function recordChildPut(slug: string, ordinal: number): Promise<void> {+ await engine.executeRaw(+ `INSERT INTO subagent_tool_executions (job_id, message_idx, tool_use_id, tool_name, status, input, ordinal)+ VALUES (4001, $1, $2, 'brain_put_page', 'complete', $3::jsonb, $1)`,+ [ordinal, `tool_${ordinal}`, JSON.stringify({ slug })],+ );+}++describe('dream output ownership', () => {+ test('refs carry the time of the child\'s first write to each slug', async () => {+ await recordChildPut('wiki/people/first-write-example', 0);+ await tick();+ await recordChildPut('wiki/people/first-write-example', 1);+ const refs = await collectChildPutPageSlugs(engine as never, [4001], new Map());+ const ref = refs.find((r: { slug: string }) => r.slug === 'wiki/people/first-write-example') as { first_write_at?: Date };+ const [row] = await engine.executeRaw<{ at: string }>(+ `SELECT MIN(started_at) AS at FROM subagent_tool_executions WHERE job_id = 4001`);+ expect(ref.first_write_at?.getTime()).toBe(new Date(row.at).getTime());+ });++ test('the provenance stamp skips a human page a child edited and stamps pages the child created', async () => {+ const human = 'wiki/people/alice-example';+ await importFromContent(engine, human, '---\ntype: person\ntitle: Alice\n---\nHand-written notes about Alice.', { noEmbed: true, remote: false, sourceId: 'default' });+ await tick();+ const firstWriteAt = await readVerifyEpoch(engine);+ await importFromContent(engine, human, '---\ntype: person\ntitle: Alice\n---\nHand-written notes about Alice.\n\nA dream edit.', { noEmbed: true, remote: false, sourceId: 'default' });+ const created = 'wiki/personal/reflections/2026-09-20-created-abc123';+ await importFromContent(engine, created, '---\ntype: note\n---\nA reflection.', { noEmbed: true, remote: false, sourceId: 'default' });++ const refs = [+ { slug: human, source_id: 'default', raw_source: '/t/a.txt', first_write_at: firstWriteAt },+ { slug: created, source_id: 'default', raw_source: '/t/a.txt', first_write_at: firstWriteAt },+ ];+ await stampDreamProvenance(engine as never, refs, '2026-09-20');++ const humanPage = await engine.getPage(human, { sourceId: 'default' });+ expect(humanPage!.frontmatter.dream_generated).toBeUndefined();+ expect(humanPage!.frontmatter.raw_source).toBeUndefined();+ expect((await engine.getPage(created, { sourceId: 'default' }))!.frontmatter.dream_generated).toBe(true);++ // The reverse-written file of the human page carries no dream marker either,+ // so the next sync cannot import one.+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-dream-ownership-'));+ try {+ await reverseWriteRefs(engine as never, dir, refs, 'default');+ expect(readFileSync(join(dir, `${human}.md`), 'utf8')).not.toContain('dream_generated');+ expect(readFileSync(join(dir, `${created}.md`), 'utf8')).toContain('dream_generated: true');+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ }, 30_000);++ test('a page another writer created while the child ran is verified on the child\'s new units only', async () => {+ const transcript = 'user: The verdict was "ship the repair pass now, measure later." That is the plan.';+ const since = await readVerifyEpoch(engine);+ await tick();+ const slug = 'wiki/people/carol-example';+ const human = 'Carol said "a quote from an entirely different conversation last spring".';+ await importFromContent(engine, slug, `---\ntype: person\n---\n${human}`, { noEmbed: true, remote: false, sourceId: 'default' });+ await tick();+ const firstWriteAt = await readVerifyEpoch(engine);+ await importFromContent(engine, slug, `---\ntype: person\n---\n${human}\n\nThe user said "ship the repair pass now, measure later."\n\nThe user said "we are shutting down the company next quarter".`,+ { noEmbed: true, remote: false, sourceId: 'default' });++ const stats = await verifyAndRepairDreamPages(engine, [+ { slug, source_id: 'default', raw_source: '/t/session.md', first_write_at: firstWriteAt },+ ], new Map([['/t/session.md', { content: transcript }]]), { since, checkedAt: '2026-09-20' });++ expect(stats.preexisting_diffed).toBe(1);+ const page = await engine.getPage(slug, { sourceId: 'default' });+ expect(page!.compiled_truth).toBe(`${human}\n\nThe user said "ship the repair pass now, measure later."`);+ expect((page!.frontmatter.unverified_claims as unknown[])).toHaveLength(1);+ }, 30_000);+});diff --git a/test/cycle-synthesize-verify-decisions.test.ts b/test/cycle-synthesize-verify-decisions.test.tsnew file mode 100644index 0000000000..4dbdc07482--- /dev/null+++ b/test/cycle-synthesize-verify-decisions.test.ts@@ -0,0 +1,63 @@+/**+ * #5425: an assistant's proposal must not become the user's decision.+ *+ * The grounding gate checks, mechanically, the one part of a decision or+ * commitment it can: when a claim says a speaker decided, agreed, committed+ * or will do something, the numbers and dates it carries must come from that+ * speaker's own turns, or from the turn they explicitly accepted. A decision+ * whose specifics only another speaker stated is quarantined as+ * `decision_misattributed`. Claims without numbers or dates are left to the+ * synthesis prompt.+ */+import { describe, expect, test } from 'bun:test';+import { groundSource, verifyBody } from '../src/core/cycle/synthesize-verify.ts';++const transcript = [+ 'User: Let us look into moving the launch.',+ 'Assistant: I recommend moving the launch to 2026-10-15 and adding a pricing page first.',+ 'User: No, keep the date as is. Only the pricing page.',+ 'Assistant: Should we cap the beta at $30K of credits?',+ 'User: Sounds good, do that.',+ 'User: I will send the investor update by March 3.',+].join('\n');+const src = [groundSource('/t/launch.txt', transcript)];++describe('decision attribution (#5425)', () => {+ test('a user decision whose date only the assistant proposed is quarantined', () => {+ const r = verifyBody('The user decided to move the launch to 2026-10-15.', src);+ expect(r.quarantined.map(q => q.reason)).toEqual(['decision_misattributed']);+ expect(r.body).toBe('');+ });++ test('crediting the proposal to the assistant is kept', () => {+ const body = 'The assistant proposed moving the launch to 2026-10-15; the user declined.';+ expect(verifyBody(body, src).quarantined).toEqual([]);+ });++ test('a proposal the user explicitly accepted may be stated as the user\'s decision', () => {+ expect(verifyBody('The user agreed to cap the beta at $30K of credits.', src).quarantined).toEqual([]);+ });++ test('a commitment whose date the user stated is kept', () => {+ expect(verifyBody('The user will send the investor update by March 3rd.', src).quarantined).toEqual([]);+ });++ test('a decision recorded with its refusal, or a proposal, is kept', () => {+ expect(verifyBody('The user decided not to move the launch to 2026-10-15.', src).quarantined).toEqual([]);+ expect(verifyBody('When a launch on 2026-10-15 was suggested, the user said they will keep the date.', src).quarantined).toEqual([]);+ });++ test('a number no speaker stated (a file-name date) is not attributed to anyone', () => {+ const dated = [groundSource('/t/2026-09-20-session.txt', transcript)];+ expect(verifyBody('In a 2026 session the user committed to weekly customer calls.', dated).quarantined).toEqual([]);+ });++ test('a plain statement without a decision verb is not a decision claim', () => {+ expect(verifyBody('A launch date of 2026-10-15 was discussed.', src).quarantined).toEqual([]);+ });++ test('a transcript without speaker turns is not checked for attribution', () => {+ const flat = [groundSource('/t/notes.txt', 'Notes: move the launch to 2026-10-15 maybe.')];+ expect(verifyBody('The user decided to move the launch to 2026-10-15.', flat).quarantined).toEqual([]);+ });+});diff --git a/test/cycle/extract-atoms-reconcile.test.ts b/test/cycle/extract-atoms-reconcile.test.tsnew file mode 100644index 0000000000..597eec1bdf--- /dev/null+++ b/test/cycle/extract-atoms-reconcile.test.ts@@ -0,0 +1,92 @@+// Write-path audit C-14: atoms follow their source.+// - An undated source page dates its atoms by the page's creation date, not+// the run date, so re-extraction on a later day upserts the same slugs.+// - Re-extracting an edited source retires the atoms the previous+// extraction produced and the new one did not (LLM-chosen titles drift),+// so live atoms per source stay flat instead of piling up.++import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { runPhaseExtractAtoms } from '../../src/core/cycle/extract-atoms.ts';+import { resetPgliteState } from '../helpers/reset-pglite.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import type { ChatResult, ChatOpts } from '../../src/core/ai/gateway.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 60_000);++afterAll(async () => {+ await engine.disconnect();+});++beforeEach(async () => {+ await resetPgliteState(engine);+}, 60_000);++function chatWithTitles(titles: string[]): (o: ChatOpts) => Promise<ChatResult> {+ const text = JSON.stringify(titles.map(title => ({ title, atom_type: 'insight', body: `Body for ${title}.` })));+ return async (o: ChatOpts) => ({+ text, blocks: [{ type: 'text', text }], stopReason: 'end',+ usage: { input_tokens: 10, output_tokens: 10, cache_read_tokens: 0, cache_creation_tokens: 0 },+ model: o.model ?? 'anthropic:claude-haiku-4-5', providerId: 'anthropic',+ });+}++async function liveAtoms(where: string, param: string): Promise<string[]> {+ const rows = await engine.executeRaw<{ slug: string }>(+ `SELECT slug FROM pages WHERE type = 'atom' AND deleted_at IS NULL AND ${where} ORDER BY slug`, [param]);+ return rows.map(r => r.slug);+}++const body = (n: number) => `Detailed notes about a careful operator and the lessons drawn, revision ${n}. `.repeat(20);++describe('extract_atoms reconciles atoms with their source (C-14)', () => {+ test('an undated page dates its atoms by creation date and an edit retires stale atoms', async () => {+ const slug = 'meetings/frank-example';+ const write = (n: number) => importFromContent(engine, slug, `---\ntype: meeting\ntitle: Frank sync\n---\n${body(n)}`, { noEmbed: true, sourceId: 'default' });+ await write(1);+ await engine.executeRaw(`UPDATE pages SET created_at = '2025-01-02T12:00:00Z' WHERE slug = $1`, [slug]);++ await runPhaseExtractAtoms(engine, { _transcripts: [], _chat: chatWithTitles(['Patience compounds', 'Hire slowly']) });+ const first = await liveAtoms(`frontmatter->>'source_slug' = $1`, slug);+ expect(first).toHaveLength(2);+ for (const atom of first) expect(atom.startsWith('atoms/2025-01-02/')).toBe(true);++ await write(2);+ await runPhaseExtractAtoms(engine, { _transcripts: [], _chat: chatWithTitles(['Patience compounds over years', 'Hire slowly']) });+ const second = await liveAtoms(`frontmatter->>'source_slug' = $1`, slug);+ expect(second).toHaveLength(2);+ expect(second.some(s => s.includes('/patience-compounds-over-years-'))).toBe(true);+ expect(second.some(s => /\/patience-compounds-[0-9a-f]+$/.test(s))).toBe(false);+ }, 60_000);++ test('a re-extracted transcript retires atoms its new extraction dropped', async () => {+ const filePath = '/corpus/2026-05-01-standup.txt';+ await runPhaseExtractAtoms(engine, {+ _transcripts: [{ filePath, content: 'v1', contentHash: 'a'.repeat(64) }], _pages: [],+ _chat: chatWithTitles(['Ship smaller', 'Measure first']),+ });+ expect(await liveAtoms(`frontmatter->>'source_path' = $1`, filePath)).toHaveLength(2);+ await runPhaseExtractAtoms(engine, {+ _transcripts: [{ filePath, content: 'v2', contentHash: 'b'.repeat(64) }], _pages: [],+ _chat: chatWithTitles(['Ship smaller']),+ });+ const live = await liveAtoms(`frontmatter->>'source_path' = $1`, filePath);+ expect(live).toHaveLength(1);+ expect(live[0]).toContain('/ship-smaller-');+ }, 60_000);++ test('an undated transcript gets a stable date segment instead of the run date', async () => {+ const filePath = '/corpus/standup-notes.txt';+ await runPhaseExtractAtoms(engine, {+ _transcripts: [{ filePath, content: 'v1', contentHash: 'c'.repeat(64) }], _pages: [],+ _chat: chatWithTitles(['Keep a changelog']),+ });+ expect(await liveAtoms(`frontmatter->>'source_path' = $1`, filePath)).toEqual([expect.stringMatching(/^atoms\/undated\/keep-a-changelog-/)]);+ }, 60_000);+});diff --git a/test/cycle/synthesize-concepts-human-owned.test.ts b/test/cycle/synthesize-concepts-human-owned.test.tsindex cfc12cce8d..0aab3e78b7 100644--- a/test/cycle/synthesize-concepts-human-owned.test.ts+++ b/test/cycle/synthesize-concepts-human-owned.test.ts@@ -52,10 +52,15 @@ describe('synthesize_concepts human-owned pages', () => {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' });+ // The phase's own page is still eligible for a refresh on the next run+ // (a changed member set; an unchanged one is skipped as unchanged).+ const grown = [...atoms, { slug: 'atoms/a3', title: 'A3', body: 'b3', concept_refs: ['flywheel', 'theme'] }];+ await engine.putPage('atoms/a3', { type: 'atom', title: 'A3', compiled_truth: 'b3', timeline: '' });+ const second = await runPhaseSynthesizeConcepts(engine, { _atoms: grown, 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);+ const third = await runPhaseSynthesizeConcepts(engine, { _atoms: grown, sourceId: 'default' });+ expect((third.details as Record<string, unknown>).skipped_unchanged).toEqual(['concepts/theme']);}, 120000);test('the ownership check runs before any LLM spend', async () => {diff --git a/test/cycle/synthesize-concepts-identity.test.ts b/test/cycle/synthesize-concepts-identity.test.tsnew file mode 100644index 0000000000..236df0ec94--- /dev/null+++ b/test/cycle/synthesize-concepts-identity.test.ts@@ -0,0 +1,132 @@+// synthesize_concepts concept identity and narrative stability.+//+// C-4: spelling variants of one concept ("Network Effects", "network-effects",+// "concepts/network-effects") are one concept page with a valid slug.+// C-5: an unchanged member set costs nothing on the next cycle, and a page that+// already has an LLM narrative is never replaced by a template stub when the+// budget runs out or the model errors.++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 { validatePageSlug } from '../../src/core/ops/context.ts';+import { resetPgliteState } from '../helpers/reset-pglite.ts';+import type { ChatResult, ChatOpts } from '../../src/core/ai/gateway.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);+ await engine.setConfig('models.dream.synthesize', 'anthropic:claude-sonnet-4-6');+}, 120000);++function chatReturning(text: string, calls: { n: number }): (o: ChatOpts) => Promise<ChatResult> {+ return async (o: ChatOpts) => {+ calls.n++;+ return {+ text,+ blocks: [{ type: 'text', text }],+ stopReason: 'end',+ usage: { input_tokens: 100, output_tokens: 50, cache_read_tokens: 0, cache_creation_tokens: 0 },+ model: o.model ?? 'unset',+ providerId: 'test',+ };+ };+}++async function conceptPages(): Promise<string[]> {+ const rows = await engine.executeRaw<{ slug: string }>(+ `SELECT slug FROM pages WHERE type = 'concept' AND deleted_at IS NULL ORDER BY slug`,+ );+ return rows.map(r => r.slug);+}++const t2Atoms = (n = 5) => Array.from({ length: n }, (_, i) => ({+ slug: `atoms/a${i}`, title: `A${i}`, body: `body ${i}`, concept_refs: ['flywheel'],+}));++describe('synthesize_concepts concept identity (C-4)', () => {+ test('spelling variants merge into one concept page with a valid slug', async () => {+ const atoms = [+ { slug: 'atoms/v1', title: 'V1', body: 'b1', concept_refs: ['Network Effects'] },+ { slug: 'atoms/v2', title: 'V2', body: 'b2', concept_refs: ['network-effects'] },+ { slug: 'atoms/v3', title: 'V3', body: 'b3', concept_refs: ['concepts/network-effects'] },+ { slug: 'atoms/v4', title: 'V4', body: 'b4', concept_refs: ['Network effects ', 'network effects'] },+ ];+ const result = await runPhaseSynthesizeConcepts(engine, { _atoms: atoms, sourceId: 'default' });+ const slugs = await conceptPages();+ expect(slugs).toEqual(['concepts/network-effects']);+ for (const slug of slugs) expect(() => validatePageSlug(slug)).not.toThrow();+ const page = await engine.getPage('concepts/network-effects', { sourceId: 'default' });+ // One atom naming the concept twice still counts once.+ expect(page?.frontmatter.mention_count).toBe(4);+ expect((result.details as Record<string, unknown>).groups_found).toBe(1);+ }, 120000);++ test('a concept ref that normalizes to nothing is dropped instead of written', async () => {+ const atoms = [+ { slug: 'atoms/x1', title: 'X1', body: 'b1', concept_refs: ['!!!', 'theme'] },+ { slug: 'atoms/x2', title: 'X2', body: 'b2', concept_refs: ['!!!', 'theme'] },+ ];+ await runPhaseSynthesizeConcepts(engine, { _atoms: atoms, sourceId: 'default' });+ expect(await conceptPages()).toEqual(['concepts/theme']);+ }, 120000);+});++describe('synthesize_concepts narrative stability (C-5)', () => {+ test('an unchanged member set is not re-synthesized or rewritten', async () => {+ const calls = { n: 0 };+ await runPhaseSynthesizeConcepts(engine, { _atoms: t2Atoms(), sourceId: 'default', _chat: chatReturning('Good narrative.', calls) });+ expect(calls.n).toBe(1);+ const before = await engine.getPage('concepts/flywheel', { sourceId: 'default' });++ const second = await runPhaseSynthesizeConcepts(engine, { _atoms: t2Atoms(), sourceId: 'default', _chat: chatReturning('Other.', calls) });+ expect(calls.n).toBe(1);+ const after = await engine.getPage('concepts/flywheel', { sourceId: 'default' });+ expect(after?.compiled_truth.trim()).toBe('Good narrative.');+ expect(after?.frontmatter.synthesized_at).toBe(before?.frontmatter.synthesized_at);+ expect((second.details as Record<string, unknown>).skipped_unchanged).toEqual(['concepts/flywheel']);+ }, 120000);++ test('a model error never downgrades an LLM narrative to a template stub', async () => {+ const calls = { n: 0 };+ await runPhaseSynthesizeConcepts(engine, { _atoms: t2Atoms(5), sourceId: 'default', _chat: chatReturning('Good narrative.', calls) });+ const failing = (async () => { throw new Error('boom: unexpected provider fault'); }) as unknown as (o: ChatOpts) => Promise<ChatResult>;+ const result = await runPhaseSynthesizeConcepts(engine, { _atoms: t2Atoms(6), sourceId: 'default', _chat: failing });+ const page = await engine.getPage('concepts/flywheel', { sourceId: 'default' });+ expect(page?.compiled_truth.trim()).toBe('Good narrative.');+ expect(page?.frontmatter.synthesis_mode).toBe('llm');+ expect((result.details as Record<string, unknown>).kept_existing_narrative).toEqual(['concepts/flywheel']);+ }, 120000);++ test('an empty model answer keeps the existing LLM narrative too', async () => {+ const calls = { n: 0 };+ await runPhaseSynthesizeConcepts(engine, { _atoms: t2Atoms(5), sourceId: 'default', _chat: chatReturning('Good narrative.', calls) });+ await runPhaseSynthesizeConcepts(engine, { _atoms: t2Atoms(7), sourceId: 'default', _chat: chatReturning(' ', calls) });+ const page = await engine.getPage('concepts/flywheel', { sourceId: 'default' });+ expect(page?.compiled_truth.trim()).toBe('Good narrative.');+ expect(page?.frontmatter.synthesis_mode).toBe('llm');+ }, 120000);++ test('a fallback page is retried with the LLM on the next cycle', async () => {+ const failing = (async () => { throw new Error('boom: unexpected provider fault'); }) as unknown as (o: ChatOpts) => Promise<ChatResult>;+ await runPhaseSynthesizeConcepts(engine, { _atoms: t2Atoms(), sourceId: 'default', _chat: failing });+ expect((await engine.getPage('concepts/flywheel', { sourceId: 'default' }))?.frontmatter.synthesis_mode).toBe('error_fallback');+ const calls = { n: 0 };+ await runPhaseSynthesizeConcepts(engine, { _atoms: t2Atoms(), sourceId: 'default', _chat: chatReturning('Recovered.', calls) });+ expect(calls.n).toBe(1);+ const page = await engine.getPage('concepts/flywheel', { sourceId: 'default' });+ expect(page?.compiled_truth.trim()).toBe('Recovered.');+ expect(page?.frontmatter.synthesis_mode).toBe('llm');+ }, 120000);+});diff --git a/test/doctor-slug-collisions.test.ts b/test/doctor-slug-collisions.test.tsnew file mode 100644index 0000000000..037c2de402--- /dev/null+++ b/test/doctor-slug-collisions.test.ts@@ -0,0 +1,60 @@+/**+ * slug_collisions doctor check (A3): files in a source checkout that map to+ * one page slug are reported with their paths and which one is indexed.+ *+ * PGLite in-memory ($0).+ */++import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { mkdtempSync, writeFileSync, mkdirSync } from 'fs';+import { execSync } from 'child_process';+import { tmpdir } from 'os';+import { join } from 'path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { runSources } from '../src/commands/sources.ts';+import { performSync } from '../src/commands/sync.ts';+import { slugCollisionsCheck } from '../src/commands/doctor/checks/slug-collisions.ts';+import { categorizeCheck } from '../src/core/doctor-categories.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 60_000);++afterAll(async () => { if (engine) await engine.disconnect(); }, 60_000);++function repo(files: Record<string, string>): string {+ const dir = mkdtempSync(join(tmpdir(), 'slug-collide-'));+ execSync('git init -q && git config user.email t@t && git config user.name t', { cwd: dir });+ for (const [rel, body] of Object.entries(files)) {+ mkdirSync(join(dir, rel, '..'), { recursive: true });+ writeFileSync(join(dir, rel), body);+ }+ execSync('git add -A && git commit -qm seed', { cwd: dir });+ return dir;+}++describe('slug_collisions doctor check', () => {+ test('a clean checkout is ok', async () => {+ const dir = repo({ 'notes/one.md': '---\ntitle: One\n---\nOne.\n' });+ await runSources(engine, ['add', 'clean', '--path', dir, '--no-federated']);+ const check = await slugCollisionsCheck(engine);+ expect(check.status).toBe('ok');+ expect(categorizeCheck('slug_collisions')).toBe('brain');+ }, 60_000);++ test('two files mapping to one slug are reported with the indexed path', async () => {+ const dir = repo({ 'notes/Foo Bar.md': '---\ntitle: One\n---\napples\n', 'notes/foo-bar.md': '---\ntitle: Two\n---\noranges\n' });+ await runSources(engine, ['add', 'collide', '--path', dir, '--no-federated']);+ await performSync(engine, { repoPath: dir, sourceId: 'collide', noPull: true, noEmbed: true });+ const check = await slugCollisionsCheck(engine);+ expect(check.status).toBe('warn');+ expect(check.message).toContain('collide:notes/foo-bar');+ expect(check.message).toContain('notes/Foo Bar.md');+ expect(check.message).toContain('notes/foo-bar.md');+ expect(check.message).toMatch(/indexed: notes\/(Foo Bar|foo-bar)\.md/);+ }, 60_000);+});diff --git a/test/e2e/connectors-ingest-failure-pglite.test.ts b/test/e2e/connectors-ingest-failure-pglite.test.tsnew file mode 100644index 0000000000..977080f327--- /dev/null+++ b/test/e2e/connectors-ingest-failure-pglite.test.ts@@ -0,0 +1,108 @@+/**+ * #5666 follow-up: a conversation that downloads but fails to ingest is+ * attributed per conversation. Its batch siblings are recorded as synced,+ * and after QUARANTINE_ATTEMPTS failures at the same version it is+ * quarantined and stops holding the watermark back, exactly like a+ * conversation whose fetch keeps failing.+ *+ * Real ConnectorClient against the fixture backend, real ingest for every+ * conversation; the ingest seam only reports one conversation's session as+ * failed. 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 { CHATGPT_BASE_URL } from '../../src/core/connectors/providers/chatgpt.ts';+import { runTranscriptsIngest } from '../../src/core/transcripts/ingest.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-ingest-fail-'));+ 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): FixtureConversation {+ return { id, title: `Title ${id}`, createTime: updateTime - 100, updateTime,+ turns: [{ role: 'user', text: `question ${id}` }, { role: 'assistant', text: `answer ${id}` }] };+}++/** Real ingest; the session for `failingId` is reported as a failed import. */+function ingestFailing(failingId: string): typeof runTranscriptsIngest {+ return async (eng, opts) => {+ const r = await runTranscriptsIngest(eng, opts);+ for (const file of r.files) {+ for (const s of file.sessions) {+ if (s.sessionId !== failingId) continue;+ s.error = 'page import returned error status';+ r.sessionsErrored++;+ r.cleanScan = false;+ }+ }+ return r;+ };+}++async function run(state: FixtureState, runIngest: typeof runTranscriptsIngest) {+ 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(),+ runIngest,+ },+ });+ } finally {+ srv.stop();+ }+}++describe('connector ingest failures', () => {+ test('a conversation that fails to ingest is quarantined and stops holding the watermark', async () => {+ const state = newFixtureState([conv('c-1', T0 + 10), conv('c-2', T0 + 20), conv('c-3', T0 + 30)]);+ const runIngest = ingestFailing('c-1');+ const results = [];+ for (let k = 0; k < 4; k++) results.push(await run(state, runIngest));++ // Siblings in the failing batch are synced on the first run, not re-fetched.+ expect(state.hits['detail:c-2']).toBe(1);+ expect(state.hits['detail:c-3']).toBe(1);+ expect(state.hits['detail:c-1']).toBe(3);+ expect(results.slice(0, 2).map(r => r.watermarkAdvancedTo)).toEqual([undefined, undefined]);+ expect(results[2].quarantined).toEqual(['c-1']);+ expect(results[2].watermarkAdvancedTo).toBe(new Date((T0 + 30) * 1000).toISOString());+ expect(results[3].fetched).toBe(0);+ expect(results[3].status).toBe('nothing_new');+ });+});diff --git a/test/e2e/fact-vector-repair-parity.test.ts b/test/e2e/fact-vector-repair-parity.test.tsindex b608417f28..dbcee6eb03 100644--- a/test/e2e/fact-vector-repair-parity.test.ts+++ b/test/e2e/fact-vector-repair-parity.test.ts@@ -125,8 +125,11 @@ for (const kind of ['pglite', 'postgres'] as const) {const result = await runExtractFacts(engine, { slugs: [slug] });const rows = await snapshot();expect(result.factsInserted).toBe(1);- expect(rows[0].fact).toBe('Changed claim');- expect(JSON.parse(rows[0].embedding!)[0]).toBe(0.5);+ // B-5: the replaced row is expired and detached (row_num NULL), not deleted.+ const current = rows.filter(row => row.row_num != null);+ expect(current.map(row => row.fact)).toEqual(['Changed claim']);+ expect(JSON.parse(current[0].embedding!)[0]).toBe(0.5);+ expect(rows.find(row => row.fact === 'Original claim')).toMatchObject({ row_num: null });});test('failed embedding cannot retain a removed claim as active or reuse its vector for changed text', async () => {diff --git a/test/e2e/fact-withdrawal-scope-postgres.test.ts b/test/e2e/fact-withdrawal-scope-postgres.test.tsnew file mode 100644index 0000000000..922a02c64d--- /dev/null+++ b/test/e2e/fact-withdrawal-scope-postgres.test.ts@@ -0,0 +1,94 @@+/**+ * Postgres scale gate for claim-keyed withdrawal discovery. Ported from+ * garrytan/gbrain#5469 by @tarush1989: rare, stopword and common-anchor claims+ * each withdraw exactly one page of a 2,500-page source inside a 5-second+ * statement budget, leaving unrelated pages untouched.+ */+import { describe, expect, test } from 'bun:test';+import { renderFactsTable } from '../../src/core/facts-fence.ts';+import { recordFactWithdrawal } from '../../src/core/facts/withdrawal.ts';+import { hasDatabase } from './helpers.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';++const describePg = hasDatabase() ? describe : describe.skip;++describePg('Postgres fact-withdrawal scope', () => {+ test('stays inside admission with source-scoped evidence while preserving unrelated pages', async () => {+ const fixture = await isolatedPersistencePostgres(process.env.DATABASE_URL!);+ const { engine } = fixture;+ const sourceId = 'withdrawal-postgres-scale';+ const claim = 'indexed withdrawal needle sentinel';+ try {+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [sourceId]);+ await engine.executeRaw(`ALTER TABLE pages DISABLE TRIGGER USER`);+ await engine.executeRaw(`INSERT INTO pages(source_id,slug,type,title,compiled_truth,timeline,frontmatter,search_vector)+ SELECT $1,'notes/scale-'||n,'note','Scale '||n,+ replace($2,'__N__',n::text)||chr(10)||repeat('realistic page padding ',200),'','{}'::jsonb,+ to_tsvector('english','Scale '||n) FROM generate_series(1,2500) n`,+ [sourceId, renderFactsTable([{ rowNum: 1, claim: 'unrelated fence __N__', kind: 'fact', confidence: 1,+ visibility: 'world', notability: 'medium', active: true }])]);+ await engine.executeRaw(`ALTER TABLE pages ENABLE TRIGGER USER`);+ await engine.executeRaw(`ALTER TABLE content_chunks DISABLE TRIGGER USER`);+ await engine.executeRaw(`INSERT INTO content_chunks(page_id,chunk_index,chunk_text,chunk_source,search_vector)+ SELECT p.id,n,CASE WHEN p.slug='notes/scale-2499' AND n=0 THEN $2 ELSE 'unrelated filler '||p.slug||' '||n END,+ 'compiled_truth',to_tsvector('english',CASE WHEN p.slug='notes/scale-2499' AND n=0 THEN $2 ELSE 'unrelated filler '||p.slug||' '||n END)+ FROM pages p CROSS JOIN generate_series(0,2) n WHERE p.source_id=$1`, [sourceId, claim]);+ await engine.executeRaw(`ALTER TABLE content_chunks ENABLE TRIGGER USER`);+ const [unrelatedBefore] = await engine.executeRaw<{ knowledge_revision: string }>(+ `SELECT knowledge_revision FROM pages WHERE source_id=$1 AND slug='notes/scale-1'`, [sourceId]);+ const stored = await engine.insertFact({ fact: claim, source: 'test', visibility: 'world' }, { source_id: sourceId });++ const started = performance.now();+ const result = await engine.transaction(async tx => {+ await tx.executeRaw(`SELECT set_config('statement_timeout','5000ms',true)`);+ return recordFactWithdrawal(tx, stored.id, sourceId, true);+ });++ expect(performance.now() - started).toBeLessThan(5000);+ expect(result.pages.map(page => page.slug)).toEqual(['notes/scale-2499']);+ const [unrelatedAfter] = await engine.executeRaw<{ knowledge_revision: string }>(+ `SELECT knowledge_revision FROM pages WHERE source_id=$1 AND slug='notes/scale-1'`, [sourceId]);+ expect(unrelatedAfter.knowledge_revision).toBe(unrelatedBefore.knowledge_revision);+ expect(await engine.executeRaw(`SELECT c.id FROM content_chunks c JOIN pages p ON p.id=c.page_id+ WHERE p.source_id=$1 AND p.slug='notes/scale-2499'`, [sourceId])).toEqual([]);++ const stopwordClaim = 'not now';+ const privateFence = renderFactsTable([{ rowNum: 1, claim: stopwordClaim, kind: 'fact', confidence: 1,+ visibility: 'private', notability: 'medium', active: true }]);+ await engine.executeRaw(`UPDATE pages SET compiled_truth=$3 WHERE source_id=$1 AND slug=$2`,+ [sourceId, 'notes/scale-2498', privateFence]);+ const privateFact = await engine.insertFact({ fact: stopwordClaim, source: 'test', visibility: 'private' },+ { source_id: sourceId });+ const stopwordStarted = performance.now();+ const stopwordResult = await engine.transaction(async tx => {+ await tx.executeRaw(`SELECT set_config('statement_timeout','5000ms',true)`);+ return recordFactWithdrawal(tx, privateFact.id, sourceId, false);+ });+ expect(performance.now() - stopwordStarted).toBeLessThan(5000);+ expect(stopwordResult.pages.map(page => page.slug)).toEqual(['notes/scale-2498']);++ // Common anchor: the claim's longest token ("realistic") is on every+ // page, so a single-token prefilter would keep all of them; the+ // all-token prefilter must still narrow discovery to the one page.+ const commonAnchorClaim = 'realistic page claim zz';+ await engine.executeRaw(`UPDATE pages SET compiled_truth=$3||chr(10)||repeat('realistic page padding ',200)+ WHERE source_id=$1 AND slug=$2`, [sourceId, 'notes/scale-2497', renderFactsTable([{ rowNum: 1,+ claim: commonAnchorClaim, kind: 'fact', confidence: 1, visibility: 'world', notability: 'medium', active: true }])]);+ const [anchored] = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM pages+ WHERE source_id=$1 AND position('realistic' in lower(compiled_truth))>0+ AND position('gbrain:facts:begin' in compiled_truth)>0`, [sourceId]);+ expect(anchored.n).toBeGreaterThanOrEqual(2499);+ const commonFact = await engine.insertFact({ fact: commonAnchorClaim, source: 'test', visibility: 'world' },+ { source_id: sourceId });+ const commonStarted = performance.now();+ const commonResult = await engine.transaction(async tx => {+ await tx.executeRaw(`SELECT set_config('statement_timeout','5000ms',true)`);+ return recordFactWithdrawal(tx, commonFact.id, sourceId, true);+ });+ expect(performance.now() - commonStarted).toBeLessThan(5000);+ expect(commonResult.pages.map(page => page.slug)).toEqual(['notes/scale-2497']);+ } finally {+ await fixture.close();+ }+ }, 60_000);+});diff --git a/test/e2e/synthesize-bigint-job-id-postgres.test.ts b/test/e2e/synthesize-bigint-job-id-postgres.test.tsindex b7584c134c..dafcc99fc6 100644--- a/test/e2e/synthesize-bigint-job-id-postgres.test.ts+++ b/test/e2e/synthesize-bigint-job-id-postgres.test.ts@@ -72,6 +72,7 @@ describeE2E('synthesis receipt job-id correlation on Postgres', () => {slug: 'wiki/agents/test/postgres-bigint-abc123-c2',source_id: 'default',raw_source: '/transcripts/postgres-bigint.md',+ first_write_at: expect.any(Date),}]);} finally {await conn`DELETE FROM minion_jobs WHERE id = ${jobId}`;diff --git a/test/e2e/transcripts-no-timestamp-pglite.test.ts b/test/e2e/transcripts-no-timestamp-pglite.test.tsnew file mode 100644index 0000000000..686bee56c4--- /dev/null+++ b/test/e2e/transcripts-no-timestamp-pglite.test.ts@@ -0,0 +1,60 @@+/**+ * Write-path audit C-19: a session with no timestamps at all cannot be+ * rendered (provenance is never fabricated). It is a reported skip, not a+ * session error, so it no longer freezes the `--since last` checkpoint and+ * forces a full rescan on every later run.+ */+import { afterAll, afterEach, 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 tmp: string;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+});+afterAll(async () => {+ await engine.disconnect();+});+beforeEach(async () => {+ await resetPgliteState(engine);+ tmp = mkdtempSync(join(tmpdir(), 'gb-transcripts-no-ts-'));+});+afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++describe('transcripts ingest: sessions without timestamps (C-19)', () => {+ test('are reported as skipped and keep the scan clean', async () => {+ const path = join(tmp, 'conversations.json');+ writeFileSync(path, JSON.stringify([+ { uuid: 'dated-1', name: 'Dated', created_at: '2026-08-01T10:00:00Z',+ chat_messages: [+ { uuid: 'm1', sender: 'human', created_at: '2026-08-01T10:00:00Z', text: 'hello there' },+ { uuid: 'm2', sender: 'assistant', created_at: '2026-08-01T10:00:30Z', text: 'hi back' },+ ] },+ { uuid: 'undated-1', name: 'Undated',+ chat_messages: [+ { uuid: 'm3', sender: 'human', text: 'no clock here' },+ { uuid: 'm4', sender: 'assistant', text: 'none here either' },+ ] },+ ]));++ const r = await runTranscriptsIngest(engine, { paths: [path], sourceId: 'default', format: 'claude-export' });++ expect(r.sessionsImported).toBe(1);+ expect(r.sessionsErrored).toBe(0);+ expect(r.sessionsSkippedNoTimestamp).toBe(1);+ expect(r.cleanScan).toBe(true);+ const undated = r.files[0].sessions.find(s => s.sessionId === 'undated-1');+ expect(undated?.skipped).toBe('no_timestamp');+ expect(undated?.error).toBeUndefined();+ });+});diff --git a/test/effective-date-brain-timezone.test.ts b/test/effective-date-brain-timezone.test.tsnew file mode 100644index 0000000000..31ee6e4c04--- /dev/null+++ b/test/effective-date-brain-timezone.test.ts@@ -0,0 +1,61 @@+/**+ * A11: `brain.timezone` sets the IANA zone offset-less frontmatter datetimes+ * are read in. Unset keeps UTC; date-only values stay UTC calendar dates; the+ * syncing host's TZ never matters.+ *+ * PGLite in-memory ($0).+ */++import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { spawnSync } from 'child_process';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { computeEffectiveDate } from '../src/core/effective-date.ts';++const at = new Date('2026-01-01T00:00:00Z');+const effective = (frontmatter: Record<string, unknown>, timeZone?: string) =>+ computeEffectiveDate({ slug: 'notes/x', frontmatter, updatedAt: at, createdAt: at, timeZone }).date?.toISOString();++describe('computeEffectiveDate with a brain timezone', () => {+ test('naive datetimes follow the zone, DST included; UTC stays the default', () => {+ expect(effective({ date: '2024-01-15 10:00' })).toBe('2024-01-15T10:00:00.000Z');+ expect(effective({ date: '2024-01-15 10:00' }, 'America/New_York')).toBe('2024-01-15T15:00:00.000Z');+ expect(effective({ date: '2024-07-15 10:00' }, 'America/New_York')).toBe('2024-07-15T14:00:00.000Z');+ expect(effective({ date: '2024-07-15T10:00:00+02:00' }, 'America/New_York')).toBe('2024-07-15T08:00:00.000Z');+ expect(effective({ date: '2024-07-15' }, 'Asia/Tokyo')).toBe('2024-07-15T00:00:00.000Z');+ expect(effective({ date: '2024-07-15 10:00' }, 'Not/AZone')).toBe('2024-07-15T10:00:00.000Z');+ });++ test('the host TZ does not change the result', () => {+ const script = `import { computeEffectiveDate } from '${process.cwd()}/src/core/effective-date.ts';+ const at = new Date('2026-01-01T00:00:00Z');+ console.log(['2024-03-05 23:30', 'March 5, 2024', '2024/03/15'].map(date =>+ computeEffectiveDate({ slug: 'notes/x', frontmatter: { date }, updatedAt: at, createdAt: at, timeZone: 'Europe/Berlin' }).date?.toISOString()).join(','));`;+ const run = (TZ: string) => spawnSync(process.execPath, ['-e', script], { env: { ...process.env, TZ }, encoding: 'utf8' }).stdout.trim();+ const tokyo = run('Asia/Tokyo');+ expect(tokyo).toBe('2024-03-05T22:30:00.000Z,2024-03-05T00:00:00.000Z,2024-03-15T00:00:00.000Z');+ expect(run('America/Los_Angeles')).toBe(tokyo);+ });+});++describe('import reads brain.timezone', () => {+ let engine: PGLiteEngine;+ beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ }, 60_000);+ afterAll(async () => { await engine.disconnect(); }, 30_000);++ const stored = async (slug: string) => (await engine.executeRaw<{ d: string }>(+ `SELECT to_char(effective_date AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI') d FROM pages WHERE slug = $1`, [slug]))[0].d;++ test('a YAML datetime without an offset is read in the brain zone', async () => {+ const page = (n: number) => `---\ntype: note\ntitle: Meeting ${n}\ndate: 2024-01-15T10:00:00\n---\nNotes ${n}.\n`;+ await importFromContent(engine, 'notes/utc', page(1), { noEmbed: true });+ expect(await stored('notes/utc')).toBe('2024-01-15T10:00');+ await engine.setConfig('brain.timezone', 'America/New_York');+ await importFromContent(engine, 'notes/zoned', page(2), { noEmbed: true });+ expect(await stored('notes/zoned')).toBe('2024-01-15T15:00');+ });+});diff --git a/test/effective-date-git-first-commit.test.ts b/test/effective-date-git-first-commit.test.tsnew file mode 100644index 0000000000..0aa88853e5--- /dev/null+++ b/test/effective-date-git-first-commit.test.ts@@ -0,0 +1,67 @@+/**+ * A12: with `sync.git_first_commit_dates` on, an undated page imported from a+ * git checkout takes the file's first-commit date as its effective-date+ * fallback instead of the clone's file timestamps. Off by default; shallow+ * clones fall back to the file timestamps.+ *+ * PGLite in-memory ($0).+ */++import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { mkdtempSync, writeFileSync, mkdirSync } from 'fs';+import { execSync } from 'child_process';+import { tmpdir } from 'os';+import { join } from 'path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { runSources } from '../src/commands/sources.ts';+import { performSync } from '../src/commands/sync.ts';++let engine: PGLiteEngine;+let origin: string;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ origin = mkdtempSync(join(tmpdir(), 'first-commit-origin-'));+ execSync('git init -q && git config user.email t@t && git config user.name t', { cwd: origin });+ mkdirSync(join(origin, 'notes'));+ writeFileSync(join(origin, 'notes/undated.md'), '---\ntitle: Undated\n---\nAn old undated note.\n');+ writeFileSync(join(origin, 'notes/dated.md'), '---\ntitle: Dated\ndate: 2019-06-01\n---\nA dated note.\n');+ execSync('git add -A && git commit -qm old', { cwd: origin, env: { ...process.env, GIT_AUTHOR_DATE: '2015-04-02T12:00:00Z', GIT_COMMITTER_DATE: '2015-04-02T12:00:00Z' } });+ writeFileSync(join(origin, 'notes/undated.md'), '---\ntitle: Undated\n---\nAn old undated note, edited.\n');+ execSync('git commit -qam edit', { cwd: origin, env: { ...process.env, GIT_AUTHOR_DATE: '2020-01-01T00:00:00Z', GIT_COMMITTER_DATE: '2020-01-01T00:00:00Z' } });+}, 60_000);++afterAll(async () => { if (engine) await engine.disconnect(); }, 60_000);++async function cloneAndSync(sourceId: string, shallow = false) {+ const clone = mkdtempSync(join(tmpdir(), 'first-commit-clone-'));+ execSync(`git clone -q ${shallow ? '--depth 1 ' : ''}file://${origin} ${clone}`);+ await runSources(engine, ['add', sourceId, '--path', clone, '--no-federated']);+ await performSync(engine, { repoPath: clone, sourceId, noPull: true, noEmbed: true });+ return Object.fromEntries((await engine.executeRaw<{ slug: string; d: string; s: string }>(+ `SELECT slug, to_char(effective_date AT TIME ZONE 'UTC', 'YYYY-MM-DD') d, effective_date_source s FROM pages WHERE source_id = $1`,+ [sourceId])).map(r => [r.slug, `${r.d} ${r.s}`]));+}++describe('git first-commit effective-date fallback', () => {+ test('off by default: an undated clone takes the file timestamp', async () => {+ const pages = await cloneAndSync('fc-off');+ expect(pages['notes/undated']).not.toBe('2015-04-02 fallback');+ expect(pages['notes/undated']).toEndWith(' fallback');+ }, 60_000);++ test('opted in: an undated page takes its first-commit date; dated pages keep theirs', async () => {+ await engine.setConfig('sync.git_first_commit_dates', 'true');+ const pages = await cloneAndSync('fc-on');+ expect(pages['notes/undated']).toBe('2015-04-02 fallback');+ expect(pages['notes/dated']).toBe('2019-06-01 date');+ }, 60_000);++ test('a shallow clone keeps the file timestamp', async () => {+ await engine.setConfig('sync.git_first_commit_dates', 'true');+ const pages = await cloneAndSync('fc-shallow', true);+ expect(pages['notes/undated']).not.toBe('2015-04-02 fallback');+ }, 60_000);+});diff --git a/test/embed-stale-images.test.ts b/test/embed-stale-images.test.tsnew file mode 100644index 0000000000..36c90afdc7--- /dev/null+++ b/test/embed-stale-images.test.ts@@ -0,0 +1,116 @@+/**+ * `gbrain embed --stale --images` rebuilds image pages whose index is+ * incomplete (no visual vector, or no OCR text while OCR is enabled) from+ * their source files, without `sync --full`. Complete images are not+ * candidates and cost no provider call; a vanished source file is reported.+ *+ * PGLite in-memory; the Voyage provider is a fetch stub ($0).+ */++import { describe, test, expect, beforeAll, afterAll, beforeEach, afterEach } from 'bun:test';+import { mkdtempSync, writeFileSync, mkdirSync, rmSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { importImageFile } from '../src/core/import-file.ts';+import { embedStaleImages } from '../src/core/embed-stale-images.ts';+import { runSources } from '../src/commands/sources.ts';+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';+import { withEnv } from './helpers/with-env.ts';+import { runEmbed } from '../src/commands/embed.ts';++const PNG = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==', 'base64');++let engine: PGLiteEngine;+let embedCalls = 0;+let dir: string;+const origFetch = globalThis.fetch;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ dir = mkdtempSync(join(tmpdir(), 'img-sweep-'));+ mkdirSync(join(dir, 'photos'));+ await runSources(engine, ['add', 'img', '--path', dir, '--no-federated', '--force']);+}, 60_000);++beforeEach(() => {+ embedCalls = 0;+ globalThis.fetch = (async () => {+ embedCalls++;+ return new Response(JSON.stringify({+ data: [{ embedding: Array.from({ length: 1024 }, () => 0.1), index: 0 }], model: 'voyage-multimodal-3',+ }), { status: 200, headers: { 'Content-Type': 'application/json' } });+ }) as unknown as typeof fetch;+ configureGateway({+ embedding_model: 'voyage:voyage-multimodal-3',+ embedding_multimodal_model: 'voyage:voyage-multimodal-3',+ embedding_dimensions: 1024,+ env: { VOYAGE_API_KEY: 'test-key' },+ });+});++afterEach(() => {+ globalThis.fetch = origFetch;+ resetGateway();+});++afterAll(async () => {+ if (engine) await engine.disconnect();+}, 60_000);++const hasVector = async (slug: string) => (await engine.executeRaw<{ has_vec: boolean }>(+ `SELECT c.embedding_image IS NOT NULL AS has_vec FROM pages p JOIN content_chunks c ON c.page_id = p.id+ WHERE p.source_id = 'img' AND p.slug = $1`, [slug]))[0]?.has_vec;++describe('embed --stale --images', () => {+ test('rebuilds a vectorless image from its file, then finds nothing to do', async () => {+ writeFileSync(join(dir, 'photos/whiteboard.png'), PNG);+ await importImageFile(engine, join(dir, 'photos/whiteboard.png'), 'photos/whiteboard.png', { noEmbed: true, sourceId: 'img' });+ expect(await hasVector('photos/whiteboard.png')).toBe(false);++ const preview = await embedStaleImages(engine, { sourceId: 'img', dryRun: true });+ expect(preview.candidates).toBe(1);+ expect(embedCalls).toBe(0);++ const swept = await embedStaleImages(engine, { sourceId: 'img', dryRun: false });+ expect(swept).toMatchObject({ candidates: 1, rebuilt: 1, missingFile: 0, failures: 0 });+ expect(embedCalls).toBe(1);+ expect(await hasVector('photos/whiteboard.png')).toBe(true);++ embedCalls = 0;+ expect((await embedStaleImages(engine, { sourceId: 'img', dryRun: false })).candidates).toBe(0);+ expect(embedCalls).toBe(0);+ }, 60_000);++ test('an image missing OCR text is a candidate only while OCR is enabled', async () => {+ writeFileSync(join(dir, 'photos/receipt.png'), PNG);+ await importImageFile(engine, join(dir, 'photos/receipt.png'), 'photos/receipt.png', { sourceId: 'img' });+ expect(await hasVector('photos/receipt.png')).toBe(true);+ expect((await embedStaleImages(engine, { sourceId: 'img', dryRun: true })).candidates).toBe(0);+ await withEnv({ GBRAIN_EMBEDDING_IMAGE_OCR: 'true' }, async () => {+ expect((await embedStaleImages(engine, { sourceId: 'img', dryRun: true })).candidates).toBe(2);+ });+ }, 60_000);++ test('a vanished source file is reported, not silently skipped', async () => {+ writeFileSync(join(dir, 'photos/gone.png'), PNG);+ await importImageFile(engine, join(dir, 'photos/gone.png'), 'photos/gone.png', { noEmbed: true, sourceId: 'img' });+ rmSync(join(dir, 'photos/gone.png'));+ const swept = await embedStaleImages(engine, { sourceId: 'img', dryRun: false });+ expect(swept).toMatchObject({ candidates: 1, rebuilt: 0, missingFile: 1 });+ }, 60_000);++ test('the CLI runs the sweep scoped to --source', async () => {+ const lines: string[] = [];+ const origLog = console.log;+ console.log = (...args: unknown[]) => { lines.push(args.map(String).join(' ')); };+ try {+ await withEnv({ GBRAIN_EMBEDDING_MULTIMODAL: 'true' }, async () => {+ await runEmbed(engine, ['--stale', '--images', '--source', 'img', '--dry-run', '--json']);+ });+ } finally { console.log = origLog; }+ expect(JSON.parse(lines.at(-1)!)).toMatchObject({ candidates: 1, rebuilt: 0 });+ }, 60_000);+});diff --git a/test/entity-identity.test.ts b/test/entity-identity.test.tsindex 3664a654c7..e809666e85 100644--- a/test/entity-identity.test.ts+++ b/test/entity-identity.test.ts@@ -109,6 +109,34 @@ describe('identity helpers — (source_id, slug) is the key', () => {expect(moved[0]!.slug).toBe('people/alice');});+ test('B-19: re-linking the canonical member without `canonical` keeps it canonical', async () => {+ await seedTwoSourceAlice();+ await linkEntityIdentity(engine, { entityId: 'alice-chen', slug: 'people/alice', sourceId: 'default', canonical: true });+ await linkEntityIdentity(engine, { entityId: 'alice-chen', slug: 'people/alice', sourceId: 'default', confidence: 0.6 });+ const [me] = (await listEntityIdentities(engine, { entityId: 'alice-chen' })).filter(m => m.slug === 'people/alice');+ expect(me).toMatchObject({ canonical: true, confidence: 0.6 });+ // An explicit canonical:false still demotes.+ await linkEntityIdentity(engine, { entityId: 'alice-chen', slug: 'people/alice', sourceId: 'default', canonical: false });+ expect((await listEntityIdentities(engine, { entityId: 'alice-chen' })).some(m => m.canonical)).toBe(false);+ });++ test('B-19: a failed canonical link leaves the previous canonical in place', async () => {+ await seedTwoSourceAlice();+ await linkEntityIdentity(engine, { entityId: 'alice-chen', slug: 'people/alice', sourceId: 'default', canonical: true });+ await engine.executeRaw(`CREATE OR REPLACE FUNCTION test_reject_identity() RETURNS trigger LANGUAGE plpgsql AS $fn$+ BEGIN RAISE EXCEPTION 'identity insert rejected'; END $fn$`);+ await engine.executeRaw('CREATE TRIGGER test_reject_identity BEFORE INSERT ON entity_identities FOR EACH ROW EXECUTE FUNCTION test_reject_identity()');+ try {+ await expect(linkEntityIdentity(engine, {+ entityId: 'alice-chen', slug: 'people/alice-chen', sourceId: 'team-brain', canonical: true,+ })).rejects.toThrow('identity insert rejected');+ } finally {+ await engine.executeRaw('DROP TRIGGER IF EXISTS test_reject_identity ON entity_identities');+ }+ const members = await listEntityIdentities(engine, { entityId: 'alice-chen' });+ expect(members.filter(m => m.canonical).map(m => m.slug)).toEqual(['people/alice']);+ });+test('a new canonical demotes the previous one (at most one per group)', async () => {await linkEntityIdentity(engine, { entityId: 'alice-chen', slug: 'people/alice', sourceId: 'default', canonical: true });await linkEntityIdentity(engine, { entityId: 'alice-chen', slug: 'people/alice-chen', sourceId: 'team-brain', canonical: true });diff --git a/test/entity-resolution-near-names.test.ts b/test/entity-resolution-near-names.test.tsindex 6a2d2cc579..63c173c0f8 100644--- a/test/entity-resolution-near-names.test.ts+++ b/test/entity-resolution-near-names.test.ts@@ -32,6 +32,9 @@ beforeAll(async () => {['companies/widgetco-robotics', 'company', 'Widgetco Robotics'],['meetings/2026-03-01-bob-jones-example-sync', 'meeting', 'Bob Jones Example sync'],['concepts/retrieval-augmented-generation', 'concept', 'Retrieval Augmented Generation'],+ ['meetings/2026-03-02-dana-jones-example', 'meeting', 'Dana Jones Example'],+ ['people/erin-lee-example', 'person', 'Erin Lee Example'],+ ['projects/erin-lee-example-launch', 'project', 'Erin Lee Example'],];for (const [slug, type, title] of pages) {await importFromContent(engine, slug, `---\ntype: ${type}\ntitle: ${title}\n---\n\n${title} notes.\n`, { noEmbed: true });@@ -78,6 +81,16 @@ describe('fact entity resolver', () => {.toEqual({ slug: 'bob-jones-example', source: 'fallback_slugify' });});+ test('a meeting page titled with a person name is not an entity (B-8)', async () => {+ expect(await resolveEntitySlugWithSource(engine, 'default', 'Dana Jones Example'))+ .toEqual({ slug: 'dana-jones-example', source: 'fallback_slugify' });+ });++ test('two entity pages carrying the same name are ambiguous, never the first by score (B-8)', async () => {+ expect(await resolveEntitySlugWithSource(engine, 'default', 'Lee, Erin Example'))+ .toEqual({ slug: 'lee-erin-example', source: 'fallback_slugify' });+ });+test('the same person in another spelling still resolves', async () => {expect(await resolveEntitySlugWithSource(engine, 'default', 'Example, Alice Smith')).toEqual({ slug: 'people/alice-smith-example', source: 'fuzzy_match' });diff --git a/test/entity-resolve.test.ts b/test/entity-resolve.test.tsindex f89dbacea3..1b61971d22 100644--- a/test/entity-resolve.test.ts+++ b/test/entity-resolve.test.ts@@ -314,19 +314,22 @@ describe('resolveEntitySlugWithSource — fuzzy_match branch', () => {expect(result!.source).toBe<ResolutionSource>('fuzzy_match');});- it('returns fuzzy_match for prefix-expansion (bare first name "Alice")', async () => {+});++describe('resolveEntitySlugWithSource — prefix_expansion branch', () => {+ it('returns prefix_expansion for a bare first name ("Alice")', async () => {// Bare name "Alice" doesn't exact-match any slug, fuzzy fails the// 0.4 threshold on short trigrams, so prefix expansion fires and- // resolves to people/alice-example. We tag this branch as- // fuzzy_match (not fallback_slugify) so trajectory routing knows- // it's a real-page resolution.+ // resolves to people/alice-example. Tagged prefix_expansion: a+ // real-page resolution, but chosen only because it is the sole+ // people/alice-* page, so fact writes flag it as unverified.const result = await resolveEntitySlugWithSource(engine as unknown as BrainEngine,'default','Alice',);expect(result!.slug).toBe('people/alice-example');- expect(result!.source).toBe<ResolutionSource>('fuzzy_match');+ expect(result!.source).toBe<ResolutionSource>('prefix_expansion');});});diff --git a/test/eval-contradictions-auto-supersession.test.ts b/test/eval-contradictions-auto-supersession.test.tsindex 946442cf50..80d8b3553c 100644--- a/test/eval-contradictions-auto-supersession.test.ts+++ b/test/eval-contradictions-auto-supersession.test.ts@@ -125,6 +125,41 @@ describe('renderResolutionCommand', () => {expect(cmd).not.toContain('arbitrary chunk prose');});+ test('B-17 — temporal_supersede with same-day dates never picks a side', () => {+ const pair: ContradictionPair = {+ kind: 'intra_page_chunk_take',+ a: { slug: 'people/alice', chunk_id: null, take_id: 40, take_row_num: 12, source_tier: 'curated', holder: 'garry', text: 't', effective_date: '2026-03-01', effective_date_source: 'frontmatter' },+ b: { slug: 'people/alice', chunk_id: null, take_id: 41, take_row_num: 13, source_tier: 'curated', holder: 'garry', text: 'u', effective_date: '2026-03-01', effective_date_source: 'frontmatter' },+ combined_score: 1,+ };+ const cmd = renderResolutionCommand(pair, 'temporal_supersede');+ expect(cmd).not.toContain('gbrain takes supersede');+ expect(cmd).toContain('date order unclear');+ });++ test('B-17 — temporal_supersede orders timezone-bearing dates by instant, not by string', () => {+ // 2026-03-01T23:00-08:00 is 2026-03-02T07:00Z: newer than 2026-03-02 (UTC midnight).+ const pair: ContradictionPair = {+ kind: 'intra_page_chunk_take',+ a: { slug: 'people/alice', chunk_id: null, take_id: 40, take_row_num: 1, source_tier: 'curated', holder: 'garry', text: 'late take', effective_date: '2026-03-01T23:00-08:00', effective_date_source: 'frontmatter' },+ b: { slug: 'people/alice', chunk_id: null, take_id: 41, take_row_num: 2, source_tier: 'curated', holder: 'garry', text: 'early take', effective_date: '2026-03-02', effective_date_source: 'frontmatter' },+ combined_score: 1,+ };+ const cmd = renderResolutionCommand(pair, 'temporal_supersede');+ expect(cmd).toContain('--row 2');+ expect(cmd).toContain(`--claim 'late take'`);+ });++ test('B-17 — an unparseable date never picks a side', () => {+ const pair: ContradictionPair = {+ kind: 'intra_page_chunk_take',+ a: { slug: 'people/alice', chunk_id: null, take_id: 40, take_row_num: 1, source_tier: 'curated', holder: 'garry', text: 't', effective_date: 'sometime in spring', effective_date_source: 'frontmatter' },+ b: { slug: 'people/alice', chunk_id: null, take_id: 41, take_row_num: 2, source_tier: 'curated', holder: 'garry', text: 'u', effective_date: '2026-03-02', effective_date_source: 'frontmatter' },+ combined_score: 1,+ };+ expect(renderResolutionCommand(pair, 'temporal_supersede')).toContain('date order unclear');+ });+test('manual_review emits a no-op comment naming both slugs', () => {const pair = mkCrossSlugPair('daily/x', 'openclaw/chat/y');const cmd = renderResolutionCommand(pair, 'manual_review');diff --git a/test/eval-contradictions/no-valid-until-write.test.ts b/test/eval-contradictions/no-valid-until-write.test.tsindex 8b448ff2f5..971436a3ca 100644--- a/test/eval-contradictions/no-valid-until-write.test.ts+++ b/test/eval-contradictions/no-valid-until-write.test.ts@@ -42,6 +42,10 @@ import { join } from 'node:path';// from the accepted canonical Markdown fence, including version reverts,// in the guarded page publication transaction. This copies user-authored// state; it never applies contradiction-probe inference.+// - cycle/extract-facts.ts — the unmanaged fence reconcile updates a+// matched row in place with the fence's explicit valid_until cell (the+// same user-authored copy canonical-projections.ts makes); it never+// applies contradiction-probe inference.// - postgres-engine.ts + pglite-engine.ts (v0.42.56.0, #2390 — Life// Chronicle ontology: `mergeOntologyFact` forward-supersession closes// the prior OPEN row's valid_until when a NEW value arrives for the@@ -51,6 +55,7 @@ import { join } from 'node:path';// auto-supersession.ts:4 invariant is preserved. Deliberate design// change per the #2390 eng review (G1: ontology extends facts).const VALID_UNTIL_WRITE_ALLOWLIST: ReadonlySet<string> = new Set([+ 'src/core/cycle/extract-facts.ts','src/core/cycle/phases/consolidate.ts','src/core/facts/forget.ts','src/core/facts/withdrawal.ts',diff --git a/test/eval-longmemeval-brain-recycle.test.ts b/test/eval-longmemeval-brain-recycle.test.tsnew file mode 100644index 0000000000..6561f36d26--- /dev/null+++ b/test/eval-longmemeval-brain-recycle.test.ts@@ -0,0 +1,58 @@+/**+ * #5092: a long single-process LongMemEval run stalled at 100% CPU after+ * ~90-120 questions. TRUNCATE between questions never returns PGLite's WASM+ * memory, which grows with each question's vectors (≈30 MB per 500-chunk+ * question). A harness-owned brain is now replaced on a fixed cadence, with+ * the run's config pins re-applied to each fresh brain.+ */+import { describe, test, expect } from 'bun:test';+import { mkdtempSync, rmSync, readFileSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';+import { runEvalLongMemEval, LME_BRAIN_RECYCLE_EVERY } from '../src/commands/eval-longmemeval.ts';+import { createBenchmarkBrain } from '../src/eval/longmemeval/harness.ts';+import type { PGLiteEngine } from '../src/core/pglite-engine.ts';++const FIXTURE_PATH = join(import.meta.dir, 'fixtures', 'longmemeval-mini.jsonl');+const ARGS = (out: string) => [FIXTURE_PATH, '--keyword-only', '--retrieval-only', '--no-trajectory', '--output', out, '--mode', 'tokenmax'];++function rows(path: string) {+ return readFileSync(path, 'utf8').trim().split('\n').map((l) => JSON.parse(l)).filter((r) => typeof r.question_id === 'string');+}++describe('LongMemEval benchmark brain recycling (#5092)', () => {+ test('a harness-owned brain is replaced every N questions, config re-applied, results unchanged', async () => {+ expect(LME_BRAIN_RECYCLE_EVERY).toBeGreaterThan(0);+ const tmp = mkdtempSync(join(tmpdir(), 'lme-recycle-'));+ const brains: PGLiteEngine[] = [];+ const modes: Array<string | null> = [];+ try {+ await runEvalLongMemEval(ARGS(join(tmp, 'recycled.jsonl')), {+ exitOnError: false,+ brainRecycleEvery: 2,+ createBrain: async () => {+ const b = await createBenchmarkBrain();+ const setConfig = b.setConfig.bind(b);+ b.setConfig = async (k: string, v: string) => { if (k === 'search.mode') modes.push(v); return setConfig(k, v); };+ brains.push(b);+ return b;+ },+ });+ const shared = await createBenchmarkBrain();+ try {+ await runEvalLongMemEval(ARGS(join(tmp, 'single.jsonl')), { exitOnError: false, engine: shared });+ } finally {+ await shared.disconnect();+ }+ const recycled = rows(join(tmp, 'recycled.jsonl'));+ const single = rows(join(tmp, 'single.jsonl'));+ expect(recycled.length).toBe(single.length);+ expect(brains.length).toBe(Math.ceil(recycled.length / 2));+ expect(modes).toEqual(brains.map(() => 'tokenmax'));+ expect(recycled.map((r) => [r.question_id, r.recall_all_hit, r.error ?? null]))+ .toEqual(single.map((r) => [r.question_id, r.recall_all_hit, r.error ?? null]));+ } finally {+ rmSync(tmp, { recursive: true, force: true });+ }+ }, 120_000);+});diff --git a/test/extract-facts-phase.test.ts b/test/extract-facts-phase.test.tsindex c8326fdabd..0e56524c78 100644--- a/test/extract-facts-phase.test.ts+++ b/test/extract-facts-phase.test.ts@@ -396,9 +396,15 @@ describe('runExtractFacts — happy path', () => {expect(r.factsInserted).toBe(1);// eslint-disable-next-line @typescript-eslint/no-explicit-anyconst rows = await (engine as any).db.query(- `SELECT fact FROM facts WHERE source_markdown_slug = 'people/alice-fresh' ORDER BY row_num`,+ `SELECT fact FROM facts WHERE source_markdown_slug = 'people/alice-fresh' AND expired_at IS NULL ORDER BY row_num`,);expect(rows.rows.map((row: { fact: string }) => row.fact)).toEqual(['Existing']);+ // B-5: the stale row is expired and detached from the fence, never deleted.+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ const stale = await (engine as any).db.query(+ `SELECT row_num, expired_at IS NOT NULL AS expired FROM facts WHERE source_markdown_slug = 'people/alice-fresh' AND fact = 'Stale indexed row'`,+ );+ expect(stale.rows).toEqual([{ row_num: null, expired: true }]);} finally {rmSync(root, { recursive: true, force: true });}@@ -432,9 +438,15 @@ describe('runExtractFacts — happy path', () => {expect(r.factsDeleted).toBeGreaterThan(0);// eslint-disable-next-line @typescript-eslint/no-explicit-anyconst rows = await (engine as any).db.query(- `SELECT fact FROM facts WHERE source_markdown_slug = 'people/alice-wt-off' ORDER BY row_num`,+ `SELECT fact FROM facts WHERE source_markdown_slug = 'people/alice-wt-off' AND expired_at IS NULL ORDER BY row_num`,);expect(rows.rows.map((row: { fact: string }) => row.fact)).toEqual(['Existing']);+ // B-5: the stale row is expired and detached from the fence, never deleted.+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ const stale = await (engine as any).db.query(+ `SELECT row_num, expired_at IS NOT NULL AS expired FROM facts WHERE source_markdown_slug = 'people/alice-wt-off' AND fact = 'Stale indexed row'`,+ );+ expect(stale.rows).toEqual([{ row_num: null, expired: true }]);} finally {await engine.unsetConfig('sync.write_through');_resetWriteThroughCacheForTest();@@ -510,27 +522,38 @@ describe('runExtractFacts — happy path', () => {.toEqual(['Fence fact', 'conversation fact']);});- test('removed-from-fence row is deleted from DB (wipe-and-reinsert pattern)', async () => {+ test('removed-from-fence row is expired and detached, the kept row keeps its id (B-5)', async () => {// Seed: 2 facts.await putPage('people/alice', FACT_FENCE(`| 1 | A | fact | 1.0 | world | medium | 2026-01-01 | | s | || 2 | B | fact | 1.0 | world | medium | 2026-01-01 | | s | |`,));await runExtractFacts(engine, { slugs: ['people/alice'] });+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ const before = await (engine as any).db.query(+ `SELECT id, fact FROM facts WHERE source_markdown_slug = 'people/alice' ORDER BY row_num`,+ );// Edit the page to remove row 2.await putPage('people/alice', FACT_FENCE(`| 1 | A | fact | 1.0 | world | medium | 2026-01-01 | | s | |`,));- await runExtractFacts(engine, { slugs: ['people/alice'] });+ const r = await runExtractFacts(engine, { slugs: ['people/alice'] });+ expect(r.factsDeleted).toBe(1);+ expect(r.factsInserted).toBe(0);// eslint-disable-next-line @typescript-eslint/no-explicit-anyconst rows = await (engine as any).db.query(- `SELECT fact FROM facts WHERE source_markdown_slug = 'people/alice'`,+ `SELECT id, fact, row_num, expired_at IS NOT NULL AS expired FROM facts+ WHERE source_markdown_slug = 'people/alice' ORDER BY id`,);- expect(rows.rows).toHaveLength(1);- expect(rows.rows[0].fact).toBe('A');+ expect(rows.rows).toEqual([+ { id: before.rows[0].id, fact: 'A', row_num: 1, expired: false },+ { id: before.rows[1].id, fact: 'B', row_num: null, expired: true },+ ]);+ const active = await engine.listFactsByEntity('default', 'people/alice', { activeOnly: true });+ expect(active.map(f => f.fact)).toEqual(['A']);});// #4870 — visibility / notability are fence cells (parsed + validated as@@ -550,19 +573,24 @@ describe('runExtractFacts — happy path', () => {);expect(rows.rows).toEqual([{ visibility: 'world', notability: 'medium' }]);+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ const [{ id }] = (await (engine as any).db.query(`SELECT id FROM facts WHERE source_markdown_slug = 'people/alice'`)).rows;await putPage('people/alice', FACT_FENCE(`| 1 | Alice likes tea | preference | 0.9 | private | medium | | | fence | |`,));const second = await runExtractFacts(engine, { slugs: ['people/alice'] });- expect(second.factsInserted).toBe(1);+ // B-5: updated in place, the fact id survives.+ expect(second.factsUpdated).toBe(1);+ expect(second.factsInserted).toBe(0);// eslint-disable-next-line @typescript-eslint/no-explicit-anyrows = await (engine as any).db.query(- `SELECT visibility, notability FROM facts WHERE source_markdown_slug = 'people/alice'`,+ `SELECT id, visibility, notability FROM facts WHERE source_markdown_slug = 'people/alice'`,);- expect(rows.rows).toEqual([{ visibility: 'private', notability: 'medium' }]);+ expect(rows.rows).toEqual([{ id, visibility: 'private', notability: 'medium' }]);const third = await runExtractFacts(engine, { slugs: ['people/alice'] });expect(third.factsInserted).toBe(0);+ expect(third.factsUpdated).toBe(0);expect(third.factsDeleted).toBe(0);});@@ -572,16 +600,20 @@ describe('runExtractFacts — happy path', () => {));await runExtractFacts(engine, { slugs: ['people/alice'] });+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ const [{ id }] = (await (engine as any).db.query(`SELECT id FROM facts WHERE source_markdown_slug = 'people/alice'`)).rows;await putPage('people/alice', FACT_FENCE(`| 1 | Alice likes tea | preference | 0.9 | world | high | | | fence | |`,));const second = await runExtractFacts(engine, { slugs: ['people/alice'] });- expect(second.factsInserted).toBe(1);+ // B-5: updated in place, the fact id survives.+ expect(second.factsUpdated).toBe(1);+ expect(second.factsInserted).toBe(0);// eslint-disable-next-line @typescript-eslint/no-explicit-anyconst rows = await (engine as any).db.query(- `SELECT visibility, notability FROM facts WHERE source_markdown_slug = 'people/alice'`,+ `SELECT id, visibility, notability FROM facts WHERE source_markdown_slug = 'people/alice'`,);- expect(rows.rows).toEqual([{ visibility: 'world', notability: 'high' }]);+ expect(rows.rows).toEqual([{ id, visibility: 'world', notability: 'high' }]);const third = await runExtractFacts(engine, { slugs: ['people/alice'] });expect(third.factsInserted).toBe(0);@@ -659,7 +691,7 @@ describe('runExtractFacts — happy path', () => {expect(rows.rows.map((row: { fact: string }) => row.fact)).toEqual(['Seeded']);});- test('page with no facts fence → DB facts for that page wiped (empty fence reconciles to empty index)', async () => {+ test('page with no facts fence → its fence rows are expired and detached (empty fence reconciles to an empty active index)', async () => {await putPage('people/alice', FACT_FENCE(`| 1 | seeded | fact | 1.0 | world | medium | 2026-01-01 | | s | |`,));@@ -675,7 +707,8 @@ describe('runExtractFacts — happy path', () => {// eslint-disable-next-line @typescript-eslint/no-explicit-anyconst rows = await (engine as any).db.query(- `SELECT COUNT(*) AS n FROM facts WHERE source_markdown_slug = 'people/alice'`,+ `SELECT COUNT(*) AS n FROM facts WHERE source_markdown_slug = 'people/alice'+ AND (expired_at IS NULL OR row_num IS NOT NULL)`,);expect(Number(rows.rows[0].n)).toBe(0);});@@ -740,7 +773,8 @@ describe('runExtractFacts — happy path', () => {// eslint-disable-next-line @typescript-eslint/no-explicit-anyconst rows = await (engine as any).db.query(- `SELECT COUNT(*) AS n FROM facts WHERE source_markdown_slug = 'people/alice'`,+ `SELECT COUNT(*) AS n FROM facts WHERE source_markdown_slug = 'people/alice'+ AND (expired_at IS NULL OR row_num IS NOT NULL)`,);expect(Number(rows.rows[0].n)).toBe(0);});@@ -1118,12 +1152,16 @@ describe('runExtractFacts — empty-fence guard (Codex R2-#7)', () => {expect(r.factsDeleted).toBe(1); // only the stale fence-owned rowexpect(r.factsInserted).toBe(1);+ // B-5: the stale fence row is expired and detached; the hybrid row is untouched.// eslint-disable-next-line @typescript-eslint/no-explicit-anyconst rows = await (engine as any).db.query(- `SELECT fact FROM facts WHERE source_markdown_slug = 'people/alice' ORDER BY id`,+ `SELECT fact, row_num, expired_at IS NOT NULL AS expired FROM facts WHERE source_markdown_slug = 'people/alice' ORDER BY id`,);- expect(rows.rows.map((row: { fact: string }) => row.fact))- .toEqual(['forgotten hybrid claim', 'replacement fact']);+ expect(rows.rows).toEqual([+ { fact: 'forgotten hybrid claim', row_num: null, expired: true },+ { fact: 'old fact', row_num: null, expired: true },+ { fact: 'replacement fact', row_num: 1, expired: false },+ ]);});test('fence claim matching an expired legacy row is inserted active — fence is canonical (#2646)', async () => {@@ -1550,9 +1588,11 @@ describe('runExtractFacts — v0.46 (#3014) supersession transport + heal', () =expect(drifted.superseded_by).toBeNull();expect(drifted.expired_at).toBeNull();+ const idsBefore = await readIds();const healRun = await runExtractFacts(engine, { slugs: ['people/deal'] });- // Drift detected → wipe+reinsert re-transports the columns.- expect(healRun.factsInserted).toBeGreaterThan(0);+ // Drift detected → the row is healed in place (B-5: ids kept).+ expect(healRun.factsUpdated).toBeGreaterThan(0);+ expect(await readIds()).toEqual(idsBefore);const healed = (await readSupersessionCols()).find(x => x.row_num === 1)!;expect(healed.superseded_by).not.toBeNull();@@ -1606,15 +1646,17 @@ describe('runExtractFacts — v0.46 (#3014) supersession transport + heal', () =expect(await readIds()).toEqual(idsAfterFirst);});- test('idempotent: a chain (struck → struck) does not churn — second reconcile is a no-op', async () => {+ test('a chain (struck → struck) links every hop and does not churn — second reconcile is a no-op (B-13)', async () => {await putPage('people/deal', FACT_FENCE(`| 1 | ~~Link a~~ | commitment | 0.6 | world | medium | 2026-01-01 | | call | superseded by #2 || 2 | ~~Link b~~ | commitment | 0.6 | world | medium | 2026-02-01 | | call | superseded by #3 || 3 | Live tail | fact | 1.0 | world | high | 2026-03-01 | | call | |`,));const first = await runExtractFacts(engine, { slugs: ['people/deal'] });- expect(first.warnings.some(w => w.includes('struck'))).toBe(true);+ expect(first.warnings.filter(w => w.includes('superseded'))).toEqual([]);const idsAfterFirst = await readIds();+ const links = (await readSupersessionCols()).map(x => (x.superseded_by == null ? null : Number(x.superseded_by)));+ expect(links).toEqual([idsAfterFirst[1], idsAfterFirst[2], null]);const second = await runExtractFacts(engine, { slugs: ['people/deal'] });expect(second.factsInserted).toBe(0);@@ -1641,7 +1683,7 @@ describe('runExtractFacts — v0.46 (#3014) supersession transport + heal', () =| 2 | New claim | fact | 1.0 | world | high | 2026-07-01 | | call | |`,));const r = await runExtractFacts(engine, { slugs: ['people/deal'] });- expect(r.factsInserted).toBeGreaterThan(0);+ expect(r.factsUpdated).toBeGreaterThan(0);// eslint-disable-next-line @typescript-eslint/no-explicit-anyconst ids = await (engine as any).db.query(@@ -1661,7 +1703,7 @@ describe('runExtractFacts — v0.46 (#3014) supersession transport + heal', () =// BEFORE the separate insertFacts transaction; an insert throw left the// page permanently emptied. The caller now defers the wipe into// insertFacts' own transaction, so a failing insert can never empty it.- test('a failing insert during the wipe+reinsert path leaves the page intact', async () => {+ test('a failing write during reconcile rolls back and leaves the page intact', async () => {await putPage('people/deal', SUPERSEDE_FENCE);await runExtractFacts(engine, { slugs: ['people/deal'] });const before = await readIds();@@ -1673,25 +1715,28 @@ describe('runExtractFacts — v0.46 (#3014) supersession transport + heal', () =`UPDATE facts SET superseded_by = NULL, expired_at = NULL WHERE source_markdown_slug = 'people/deal' AND row_num = 1`,);- // Make the insert throw. Pre-fix, the separate-commit delete had already- // emptied the page by the time this threw; now no delete runs outside- // insertFacts, so the rows survive.- const original = engine.insertFacts;+ // Make the reconcile's final write throw. Every write of one page's+ // reconcile runs in a single transaction, so the heal above it rolls back.+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ await (engine as any).db.query(`CREATE OR REPLACE FUNCTION test_reject_link() RETURNS trigger LANGUAGE plpgsql AS $fn$+ BEGIN RAISE EXCEPTION 'simulated write failure'; END $fn$`);// eslint-disable-next-line @typescript-eslint/no-explicit-any- (engine as any).insertFacts = async () => { throw new Error('simulated insert failure'); };+ await (engine as any).db.query('CREATE TRIGGER test_reject_link BEFORE UPDATE OF superseded_by ON facts FOR EACH ROW EXECUTE FUNCTION test_reject_link()');try {// 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');+ expect(result.warnings.some(w => w.startsWith('people/deal: FACTS_RECONCILE_FAILED') && w.includes('simulated write failure'))).toBe(true);} finally {// eslint-disable-next-line @typescript-eslint/no-explicit-any- (engine as any).insertFacts = original;+ await (engine as any).db.query('DROP TRIGGER IF EXISTS test_reject_link ON facts');}- // The page keeps its rows — not silently emptied.+ // The page keeps its rows, and the in-place heal rolled back with the failure.expect(await readIds()).toEqual(before);+ const row1 = (await readSupersessionCols()).find(x => x.row_num === 1)!;+ expect(row1.expired_at).toBeNull();});// An int4-overflowing #N in the fence must be treated as a danglingdiff --git a/test/extract-facts-stable-identity.test.ts b/test/extract-facts-stable-identity.test.tsnew file mode 100644index 0000000000..4ee63c4a6b--- /dev/null+++ b/test/extract-facts-stable-identity.test.ts@@ -0,0 +1,174 @@+/**+ * The legacy extract_facts reconcile keys fence rows by row number, the+ * fence's own unique identity, and keeps fact ids stable across edits.+ *+ * - A claim that reverts to an earlier value (NYC -> SF -> NYC) keeps the+ * current row active instead of collapsing onto the struck history row.+ * - An attribute-only edit (notability, visibility, context) updates the row+ * in place: its id, created_at, source_session and consolidation state+ * survive, so an id handed out by recall still works for forget.+ * - A supersession chain (A -> B -> C) links every hop, not only the last.+ * - Facts of a soft-deleted page leave active recall.+ *+ * 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';++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: '' });+}++interface Row { id: number; row_num: number | null; fact: string; expired: boolean; superseded_by: number | null; notability: string; visibility: string }++async function rows(slug: string): Promise<Row[]> {+ return engine.executeRaw<Row>(+ `SELECT id, row_num, fact, expired_at IS NOT NULL AS expired, superseded_by, notability, visibility+ FROM facts WHERE source_id='default' AND source_markdown_slug=$1 ORDER BY id`, [slug]);+}++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 stable identity', () => {+ test('a claim that reverts to an earlier value stays active', async () => {+ const slug = 'people/carol-example';+ await putPage(slug, fence([+ '| 1 | ~~Lives in NYC~~ | fact | 1.0 | world | medium | 2020-01-01 | | chat | superseded by #2 |',+ '| 2 | ~~Lives in SF~~ | fact | 1.0 | world | medium | 2022-01-01 | | chat | superseded by #3 |',+ '| 3 | Lives in NYC | fact | 1.0 | world | medium | 2024-01-01 | | chat | |',+ ].join('\n')));+ await runExtractFacts(engine, { slugs: [slug] });+ const active = (await rows(slug)).filter(r => !r.expired);+ expect(active.map(r => [Number(r.row_num), r.fact])).toEqual([[3, 'Lives in NYC']]);+ });++ test('every hop of a supersession chain keeps its link', async () => {+ const slug = 'people/dana-example';+ await putPage(slug, fence([+ '| 1 | ~~Works at Acme~~ | fact | 1.0 | world | medium | 2020-01-01 | | chat | superseded by #2 |',+ '| 2 | ~~Works at Beta~~ | fact | 1.0 | world | medium | 2022-01-01 | | chat | superseded by #3 |',+ '| 3 | Works at Gamma | fact | 1.0 | world | medium | 2024-01-01 | | chat | |',+ ].join('\n')));+ const result = await runExtractFacts(engine, { slugs: [slug] });+ const byRow = new Map((await rows(slug)).map(r => [Number(r.row_num), r]));+ expect(Number(byRow.get(1)!.superseded_by)).toBe(Number(byRow.get(2)!.id));+ expect(Number(byRow.get(2)!.superseded_by)).toBe(Number(byRow.get(3)!.id));+ expect(result.warnings.filter(w => w.includes('itself struck'))).toEqual([]);+ // A second run over the unchanged fence is a no-op.+ const again = await runExtractFacts(engine, { slugs: [slug] });+ expect(again.factsInserted + again.factsDeleted).toBe(0);+ });++ test('a supersession cycle is still rejected', async () => {+ const slug = 'people/erin-example';+ await putPage(slug, fence([+ '| 1 | ~~Likes tea~~ | fact | 1.0 | world | medium | 2020-01-01 | | chat | superseded by #2 |',+ '| 2 | ~~Likes coffee~~ | fact | 1.0 | world | medium | 2022-01-01 | | chat | superseded by #1 |',+ ].join('\n')));+ await runExtractFacts(engine, { slugs: [slug] });+ expect((await rows(slug)).map(r => r.superseded_by)).toEqual([null, null]);+ });++ test('an attribute-only edit keeps fact ids and derived state', async () => {+ const slug = 'people/frank-example';+ const v1 = [+ '| 1 | Founded Acme | fact | 1.0 | world | medium | 2020-01-01 | | chat | |',+ '| 2 | Prefers email | preference | 0.9 | world | medium | 2021-01-01 | | chat | |',+ ];+ await putPage(slug, fence(v1.join('\n')));+ await runExtractFacts(engine, { slugs: [slug] });+ const before = await rows(slug);+ await engine.executeRaw(+ `UPDATE facts SET source_session='sess-1', consolidated_at=now() WHERE source_markdown_slug=$1`, [slug]);++ await putPage(slug, fence([+ v1[0],+ '| 2 | Prefers email | preference | 0.9 | private | high | 2021-01-01 | | chat | said twice |',+ ].join('\n')));+ const result = await runExtractFacts(engine, { slugs: [slug] });+ const after = await rows(slug);+ expect(after.map(r => r.id)).toEqual(before.map(r => r.id));+ expect(after.map(r => [r.notability, r.visibility])).toEqual([['medium', 'world'], ['high', 'private']]);+ expect(result.factsDeleted).toBe(0);+ const derived = await engine.executeRaw<{ source_session: string | null; consolidated: boolean; context: string | null }>(+ `SELECT source_session, consolidated_at IS NOT NULL AS consolidated, context FROM facts+ WHERE source_markdown_slug=$1 ORDER BY id`, [slug]);+ expect(derived.map(d => [d.source_session, d.consolidated])).toEqual([['sess-1', true], ['sess-1', true]]);+ expect(derived[1].context).toBe('said twice');+ });++ test('a removed or rewritten row is expired and detached, never deleted', async () => {+ const slug = 'people/gina-example';+ await putPage(slug, fence([+ '| 1 | Founded Acme | fact | 1.0 | world | medium | 2020-01-01 | | chat | |',+ '| 2 | Prefers email | preference | 1.0 | world | medium | 2021-01-01 | | chat | |',+ '| 3 | Lives in Paris | fact | 1.0 | world | medium | 2021-01-01 | | chat | |',+ ].join('\n')));+ await runExtractFacts(engine, { slugs: [slug] });+ const before = await rows(slug);++ await putPage(slug, fence([+ '| 1 | Founded Acme | fact | 1.0 | world | medium | 2020-01-01 | | chat | |',+ '| 3 | Lives in Lyon | fact | 1.0 | world | medium | 2021-01-01 | | chat | |',+ ].join('\n')));+ await runExtractFacts(engine, { slugs: [slug] });+ const after = await rows(slug);+ expect(after.find(r => r.id === before[0].id)).toMatchObject({ row_num: 1, expired: false });+ expect(after.find(r => r.id === before[1].id)).toMatchObject({ row_num: null, expired: true });+ expect(after.find(r => r.id === before[2].id)).toMatchObject({ row_num: null, expired: true, fact: 'Lives in Paris' });+ const lyon = after.find(r => r.fact === 'Lives in Lyon')!;+ expect(lyon).toMatchObject({ expired: false });+ expect(Number(lyon.row_num)).toBe(3);+ const again = await runExtractFacts(engine, { slugs: [slug] });+ expect(again.factsInserted + again.factsDeleted).toBe(0);+ });++ test('facts of a soft-deleted page leave active recall', async () => {+ const slug = 'people/hank-example';+ await putPage(slug, fence('| 1 | CTO at acme-example | fact | 1.0 | world | medium | 2020-01-01 | | chat | |'));+ await runExtractFacts(engine, { slugs: [slug] });+ await engine.softDeletePage(slug, { sourceId: 'default' });+ await runExtractFacts(engine, {});+ const active = await engine.listFactsByEntity('default', slug, { activeOnly: true });+ expect(active).toEqual([]);+ expect((await rows(slug)).map(r => r.expired)).toEqual([true]);++ // Restoring the page brings its fence back; the next reconcile+ // re-activates the same row, id kept.+ const [before] = await rows(slug);+ await engine.restorePage(slug, { sourceId: 'default' });+ await runExtractFacts(engine, { slugs: [slug] });+ expect((await rows(slug)).map(r => [r.id, r.expired])).toEqual([[before.id, false]]);+ });+});diff --git a/test/extract-from-fence.test.ts b/test/extract-from-fence.test.tsindex 5ae759fa23..bdf06386ed 100644--- a/test/extract-from-fence.test.ts+++ b/test/extract-from-fence.test.ts@@ -284,6 +284,19 @@ describe('resolveSupersededByRow — reference resolution (#3014)', () => {});});+describe('resolveSupersededByRow — supersession chains (B-13)', () => {+ test('a struck target that is itself superseded resolves', () => {+ const r = resolveSupersededByRow(1, 2, { id: 7, struck: true }, 'deals/acme', new Map([[2, 3]]));+ expect(r).toEqual({ superseded_by: 7, warning: null });+ });++ test('a chain that cycles back to the row is rejected', () => {+ const r = resolveSupersededByRow(1, 2, { id: 7, struck: true }, 'deals/acme', new Map([[1, 2], [2, 1]]));+ expect(r.superseded_by).toBeNull();+ expect(r.warning).toContain('cycle');+ });+});+describe('isInt4RowRef — supersession-target overflow guard (#3014)', () => {test('accepts a normal positive row reference', () => {expect(isInt4RowRef(1)).toBe(true);diff --git a/test/extract-takes-bootstrap-safety.test.ts b/test/extract-takes-bootstrap-safety.test.tsnew file mode 100644index 0000000000..c7cedcfc23--- /dev/null+++ b/test/extract-takes-bootstrap-safety.test.ts@@ -0,0 +1,123 @@+/**+ * B-14: the takes bootstrap from pages+ * - never appends a claim the page's takes fence already holds (a rerun with+ * includeCovered, or a page with a hand-added take, used to duplicate+ * gradeable takes and skew calibration),+ * - stops at a USD budget (`takes.bootstrap_budget_usd`, or the budgetUsd+ * option), and+ * - reports a failed chat call as a skipped page with its reason instead of+ * looking like "nothing to extract".+ *+ * Hermetic PGLite + tempdir repo + gateway chat seam.+ */+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';+import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { configureGateway, resetGateway, __setChatTransportForTests } from '../src/core/ai/gateway.ts';+import { extractTakesFromPages } from '../src/core/extract-takes-from-pages.ts';+import { parseTakesFence } from '../src/core/takes-fence.ts';++let engine: PGLiteEngine;+let repo: string;+let chatCalls = 0;+let reply: () => string = () => '[]';++const body = 'An opinion-bearing body long enough to clear the 200-char eligibility floor. '.repeat(5);++async function seed(slug: string): Promise<void> {+ await engine.putPage(slug, { type: 'concept', title: slug, compiled_truth: body, frontmatter: {} });+ writeFileSync(join(repo, `${slug}.md`), `# ${slug}\n\n${body}\n`, 'utf-8');+}++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ repo = mkdtempSync(join(tmpdir(), 'gb-takes-bootstrap-safety-'));+ mkdirSync(join(repo, 'concepts'), { recursive: true });+ await engine.setConfig('sync.repo_path', repo);+ configureGateway({ chat_model: 'anthropic:claude-haiku-4-5-20251001', env: { ANTHROPIC_API_KEY: 'sk-ant-test' } });+ __setChatTransportForTests(async () => {+ chatCalls++;+ const text = reply();+ return {+ text, blocks: [{ type: 'text' as const, text }], stopReason: 'end' as const,+ usage: { input_tokens: 1, output_tokens: 1, cache_read_tokens: 0, cache_creation_tokens: 0 },+ model: 'anthropic:claude-haiku-4-5-20251001', providerId: 'anthropic',+ };+ });+});++afterAll(async () => {+ __setChatTransportForTests(null);+ resetGateway();+ await engine.disconnect();+ rmSync(repo, { recursive: true, force: true });+});++beforeEach(async () => {+ chatCalls = 0;+ await engine.executeRaw('DELETE FROM takes');+ await engine.executeRaw('DELETE FROM pages');+});++describe('takes bootstrap safety (B-14)', () => {+ test('a rerun never appends a claim the fence already holds', async () => {+ await seed('concepts/dedupe-example');+ reply = () => '[{"claim":"Remote work beats offices","kind":"take","weight":0.7}]';+ const first = await extractTakesFromPages(engine, { bootstrapEnabled: true });+ expect(first.claims_extracted).toBe(1);++ reply = () => '[{"claim":"remote work beats offices.","kind":"take","weight":0.6},{"claim":"Offices will empty by 2030","kind":"bet","weight":0.4}]';+ const second = await extractTakesFromPages(engine, { bootstrapEnabled: true, includeCovered: true });+ expect(second.claims_extracted).toBe(1);+ const fence = parseTakesFence(readFileSync(join(repo, 'concepts/dedupe-example.md'), 'utf-8')).takes;+ expect(fence.map(t => t.claim)).toEqual(['Remote work beats offices', 'Offices will empty by 2030']);+ });++ test('a failed chat call is a skipped page with its reason', async () => {+ await seed('concepts/outage-example');+ __setChatTransportForTests(async () => { throw Object.assign(new Error('invalid x-api-key'), { status: 401 }); });+ try {+ const result = await extractTakesFromPages(engine, { bootstrapEnabled: true });+ expect(result.claims_extracted).toBe(0);+ expect(result.pages_skipped).toBe(1);+ expect(result.skipped[0].slug).toBe('concepts/outage-example');+ expect(result.skipped[0].reason).toStartWith('llm_error:');+ } finally {+ __setChatTransportForTests(async () => {+ chatCalls++;+ const text = reply();+ return {+ text, blocks: [{ type: 'text' as const, text }], stopReason: 'end' as const,+ usage: { input_tokens: 1, output_tokens: 1, cache_read_tokens: 0, cache_creation_tokens: 0 },+ model: 'anthropic:claude-haiku-4-5-20251001', providerId: 'anthropic',+ };+ });+ }+ });++ test('a run stops at its USD budget before calling the model', async () => {+ await seed('concepts/budget-a');+ await seed('concepts/budget-b');+ reply = () => '[{"claim":"A claim","kind":"take","weight":0.5}]';+ const result = await extractTakesFromPages(engine, { bootstrapEnabled: true, budgetUsd: 0.0000001 });+ expect(chatCalls).toBe(0);+ expect(result.budget_exhausted).toBe(true);+ expect(result.claims_extracted).toBe(0);+ });++ test('the budget reads takes.bootstrap_budget_usd', async () => {+ await seed('concepts/budget-config');+ await engine.setConfig('takes.bootstrap_budget_usd', '0.0000001');+ try {+ const result = await extractTakesFromPages(engine, { bootstrapEnabled: true });+ expect(chatCalls).toBe(0);+ expect(result.budget_exhausted).toBe(true);+ } finally {+ await engine.unsetConfig('takes.bootstrap_budget_usd');+ }+ });+});diff --git a/test/extract-takes-scoping.test.ts b/test/extract-takes-scoping.test.tsnew file mode 100644index 0000000000..2db3d7e91d--- /dev/null+++ b/test/extract-takes-scoping.test.ts@@ -0,0 +1,96 @@+/**+ * B-18: the fence -> takes extractor (v0_28_0 migration + fs/db entry points)+ * - resolves a page within its source and never onto a soft-deleted page,+ * - re-extracts a slug in every source that holds it (no hard-coded+ * 'default'), and+ * - removes takes whose rows left a cleanly parsed fence.+ *+ * Hermetic PGLite + tempdir repo.+ */+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';+import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { extractTakesFromDb, extractTakesFromFs } from '../src/core/cycle/extract-takes.ts';+import { TAKES_FENCE_BEGIN, TAKES_FENCE_END } from '../src/core/takes-fence.ts';++let engine: PGLiteEngine;++const fence = (rows: string[]) => `# Page++## Takes++${TAKES_FENCE_BEGIN}+| # | claim | kind | who | weight | since | source |+|---|-------|------|-----|--------|-------|--------|+${rows.join('\n')}+${TAKES_FENCE_END}+`;+const row = (n: number, claim: string) => `| ${n} | ${claim} | take | people/alice-example | 0.5 | 2026-01 | manual |`;++async function put(slug: string, body: string, sourceId = 'default'): Promise<number> {+ await engine.putPage(slug, { type: 'concept', title: slug, compiled_truth: body, frontmatter: {} }, { sourceId });+ const [page] = await engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE slug=$1 AND source_id=$2', [slug, sourceId]);+ return page.id;+}++async function claims(pageId: number): Promise<string[]> {+ return (await engine.executeRaw<{ claim: string }>('SELECT claim FROM takes WHERE page_id=$1 ORDER BY row_num', [pageId])).map(r => r.claim);+}++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ await engine.executeRaw(`INSERT INTO sources (id, name) VALUES ('other', 'other') ON CONFLICT DO NOTHING`);+});++afterAll(async () => {+ await engine.disconnect();+});++beforeEach(async () => {+ await engine.executeRaw('DELETE FROM takes');+ await engine.executeRaw('DELETE FROM pages');+});++describe('extract takes scoping (B-18)', () => {+ test('a row removed from the fence is removed from the takes index', async () => {+ const id = await put('concepts/stale-take', fence([row(1, 'Keep me'), row(2, 'Drop me')]));+ await extractTakesFromDb(engine, { slugs: ['concepts/stale-take'] });+ expect(await claims(id)).toEqual(['Keep me', 'Drop me']);+ await put('concepts/stale-take', fence([row(1, 'Keep me')]));+ await extractTakesFromDb(engine, { slugs: ['concepts/stale-take'] });+ expect(await claims(id)).toEqual(['Keep me']);+ });++ test('a slug is re-extracted in every source that holds it', async () => {+ const other = await put('concepts/shared-take', fence([row(1, 'Other source take')]), 'other');+ const mine = await put('concepts/shared-take', fence([row(1, 'Default source take')]));+ await extractTakesFromDb(engine, { slugs: ['concepts/shared-take'] });+ expect(await claims(other)).toEqual(['Other source take']);+ expect(await claims(mine)).toEqual(['Default source take']);+ });++ test('the fs path attaches takes to the page in its own source, never a deleted page', async () => {+ const repo = mkdtempSync(join(tmpdir(), 'extract-takes-scoping-'));+ try {+ mkdirSync(join(repo, 'concepts'), { recursive: true });+ writeFileSync(join(repo, 'concepts/fs-take.md'), fence([row(1, 'From disk')]), 'utf-8');+ const other = await put('concepts/fs-take', 'Other source page.', 'other');+ const mine = await put('concepts/fs-take', 'Default page.');+ await extractTakesFromFs(engine, { repoPath: repo });+ expect(await claims(other)).toEqual([]);+ expect(await claims(mine)).toEqual(['From disk']);++ await engine.executeRaw('DELETE FROM takes');+ await engine.softDeletePage('concepts/fs-take', { sourceId: 'default' });+ const result = await extractTakesFromFs(engine, { repoPath: repo });+ expect(await claims(mine)).toEqual([]);+ expect(result.warnings.some(w => w.startsWith('TAKES_PAGE_NOT_IN_DB'))).toBe(true);+ } finally {+ rmSync(repo, { recursive: true, force: true });+ }+ });+});diff --git a/test/fact-withdrawal-normalized.test.ts b/test/fact-withdrawal-normalized.test.tsnew file mode 100644index 0000000000..49f36f41c0--- /dev/null+++ b/test/fact-withdrawal-normalized.test.ts@@ -0,0 +1,97 @@+/**+ * Write-path audit B-9: a forgotten claim must stay forgotten when extraction+ * re-emits it from unchanged prose with different punctuation, casing or+ * spacing. Fingerprints fold those differences (migration v174); ledger rows+ * recorded with the older exact fingerprint keep matching. Real PGLite.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { recordFactWithdrawal, isFactWithdrawn } from '../src/core/facts/withdrawal.ts';+import { FACT_WITHDRAWAL_NORMALIZED_SQL, normalizeLoweredClaim } from '../src/core/facts/withdrawal-schema.ts';+import { renderFactsTable, parseFactsFence } from '../src/core/facts-fence.ts';++let engine: PGLiteEngine;+const fence = (...claims: string[]) => renderFactsTable(claims.map((claim, i) => ({+ rowNum: i + 1, claim, visibility: 'world' as const, kind: 'fact' as const, confidence: 1, notability: 'medium' as const, active: true,+})));+const expired = async (id: number) => (await engine.executeRaw<{ expired: boolean }>('SELECT expired_at IS NOT NULL AS expired FROM facts WHERE id=$1', [id]))[0].expired;+const source = async (id: string) => { await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [id]); return id; };++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+});+afterAll(async () => { await engine.disconnect(); });++test('punctuation, casing and spacing variants re-extracted after forget stay withdrawn; other claims do not', async () => {+ const sourceId = await source('normalized-reextract');+ const original = await engine.insertFact({ fact: 'Used to live in Tokyo', visibility: 'world', source: 'synthetic' }, { source_id: sourceId });+ expect((await recordFactWithdrawal(engine, original.id, sourceId)).withdrawn).toBe(true);+ for (const variant of ['used to live in Tokyo.', ' USED to live — in "Tokyo"!! ', 'Used to live in Tokyo…']) {+ const reextracted = await engine.insertFact({ fact: variant, visibility: 'world', source: 'synthetic' }, { source_id: sourceId });+ expect(await expired(reextracted.id)).toBe(true);+ expect(await isFactWithdrawn(engine, sourceId, 'world', variant, null)).toBe(true);+ }+ const other = await engine.insertFact({ fact: 'Used to live in Kyoto', visibility: 'world', source: 'synthetic' }, { source_id: sourceId });+ expect(await expired(other.id)).toBe(false);+});++test('symbols that carry meaning in names keep their claims distinct; sentence punctuation still folds', async () => {+ const sourceId = await source('normalized-symbols');+ const insert = (fact: string) => engine.insertFact({ fact, visibility: 'world', source: 'synthetic' }, { source_id: sourceId });+ const knowsC = await insert('Knows C');+ const kept = await Promise.all(['Knows C++', 'Knows C#', 'Knows F#', 'Uses .NET', 'Uses Node.js', 'Rated 3.5 stars'].map(insert));+ for (const fact of ['Knows F', 'Uses NET', 'Uses Nodejs', 'Rated 35 stars']) expect((await recordFactWithdrawal(engine, (await insert(fact)).id, sourceId)).withdrawn).toBe(true);+ expect((await recordFactWithdrawal(engine, knowsC.id, sourceId)).withdrawn).toBe(true);+ for (const fact of kept) expect(await expired(fact.id)).toBe(false);+ for (const claim of ['Knows C++', 'Knows C#', 'Uses .NET', 'Uses Node.js']) expect(await isFactWithdrawn(engine, sourceId, 'world', claim, null)).toBe(false);+ expect(await isFactWithdrawn(engine, sourceId, 'world', 'knows c.', null)).toBe(true);++ const email = await insert('Prefers email.');+ expect((await recordFactWithdrawal(engine, email.id, sourceId)).withdrawn).toBe(true);+ expect(await expired((await insert('prefers email')).id)).toBe(true);+ expect(await isFactWithdrawn(engine, sourceId, 'world', 'Prefers Email...', null)).toBe(true);+});++test('the JS overlay normalization matches the database for every folding rule', async () => {+ const claims = ['knows c++.', 'knows c#!', 'uses .net.', 'uses node.js, daily', 'prefers email...', 'e.g. this', 'a . b', '"quoted" — dash…', 'rated 3.5 stars.', 'tokyo 東京。'];+ const rows = await engine.executeRaw<{ claim: string; norm: string }>(`SELECT c AS claim,gbrain_fact_normalize(c) AS norm+ FROM unnest($1::text[]) c`, [claims]);+ expect(rows.map(row => normalizeLoweredClaim(row.claim))).toEqual(rows.map(row => row.norm));+});++test('discovery and the snapshot overlay strike a punctuation variant fence row', async () => {+ const sourceId = await source('normalized-overlay');+ await engine.putPage('people/alice-example', { type: 'person', title: 'Alice', compiled_truth: fence('Used to live in Tokyo.', 'Prefers email') }, { sourceId });+ const fact = await engine.insertFact({ fact: 'used to live in tokyo', visibility: 'world', source: 'synthetic' }, { source_id: sourceId });+ expect((await recordFactWithdrawal(engine, fact.id, sourceId)).pages.map(page => page.slug)).toEqual(['people/alice-example']);+ const snapshot = (await engine.readPageSnapshot('people/alice-example', { sourceId }))!;+ expect(parseFactsFence(snapshot.page.compiled_truth).facts.map(f => [f.claim, f.forgotten ?? false]))+ .toEqual([['Used to live in Tokyo.', true], ['Prefers email', false]]);+});++test('exact legacy ledger rows keep matching and v174 adds folded rows wherever the claim text survives', async () => {+ const sourceId = await source('normalized-legacy');+ const kept = await engine.insertFact({ fact: 'Legacy claim, here.', visibility: 'world', source: 'synthetic' }, { source_id: sourceId });+ await engine.executeRaw('UPDATE facts SET expired_at=now() WHERE id=$1', [kept.id]);+ await engine.executeRaw(`INSERT INTO fact_withdrawals(source_id,visibility,fact_hash)+ VALUES ($1,'world',gbrain_fact_fingerprint_v1('Legacy claim, here.')),($1,'world',gbrain_fact_fingerprint_v1('Orphan legacy claim.'))`, [sourceId]);+ expect(await isFactWithdrawn(engine, sourceId, 'world', 'legacy claim, HERE.', null)).toBe(true);+ expect(await isFactWithdrawn(engine, sourceId, 'world', 'Orphan legacy claim.', null)).toBe(true);+ const variant = await engine.insertFact({ fact: 'Legacy claim here', visibility: 'world', source: 'synthetic' }, { source_id: sourceId });+ expect(await expired(variant.id)).toBe(false);++ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ await (engine as any).db.exec(FACT_WITHDRAWAL_NORMALIZED_SQL);+ expect(await expired(variant.id)).toBe(true);+ expect(await isFactWithdrawn(engine, sourceId, 'world', 'legacy claim here!', null)).toBe(true);+ expect(await isFactWithdrawn(engine, sourceId, 'world', 'Orphan legacy claim.', null)).toBe(true);+ expect(await isFactWithdrawn(engine, sourceId, 'world', 'orphan legacy claim', null)).toBe(false);+ expect((await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM fact_withdrawals WHERE source_id=$1', [sourceId]))[0].n).toBe(3);+});++test('the claim fingerprint lookup is indexed', async () => {+ expect(await engine.executeRaw(`SELECT indexname FROM pg_indexes WHERE indexname='idx_facts_withdrawal_fingerprint'`))+ .toEqual([{ indexname: 'idx_facts_withdrawal_fingerprint' }]);+});diff --git a/test/fact-withdrawal-prepare-wiring.test.ts b/test/fact-withdrawal-prepare-wiring.test.tsnew file mode 100644index 0000000000..ab8586c2ad--- /dev/null+++ b/test/fact-withdrawal-prepare-wiring.test.ts@@ -0,0 +1,43 @@+/**+ * Ported from garrytan/gbrain#5469 by @tarush1989.+ * Structural pin: every coordinated prepare path that applies a prepared content+ * import must also run that import's pre-publication `validate` (the fact-withdrawal+ * race check), and the coordinator must run `validate` before any file publication.+ * The managed-import and put_page paths are proven behaviorally in+ * persistence-file-import.test.ts and withdrawal-publication-file.test.ts; sync,+ * connector and reconcile fixtures are heavy, so their wiring is pinned here.+ */+import { expect, test } from 'bun:test';+import { readFileSync } from 'fs';+import { join } from 'path';++// test-reads-source-ok[structural]: pin on coordinated prepare wiring; sync, connector and reconcile fixtures are too heavy to drive each path behaviorally.+const source = (path: string) => readFileSync(join(import.meta.dir, '../src/core/persistence', path), 'utf8').replace(/\s+/g, ' ');+const count = (text: string, needle: string) => text.split(needle).length - 1;++test.each([+ ['import-prepare.ts', 1],+ ['connector-sync.ts', 1],+ ['sync-prepare.ts', 2],+ ['reconcile-prepare.ts', 1],+ ['page-prepare.ts', 1],+] as const)('%s validates every prepared content import it applies', (file, applied) => {+ const text = source(file);+ expect(count(text, 'await ready.apply(tx)') + count(text, 'await applied.apply(tx)')).toBe(applied);+ expect(count(text, 'await ready.validate(tx)') + count(text, 'validate: ready.validate')).toBe(applied);+});++test('a managed rename validates the import it re-prepares at the new slug before applying it', () => {+ const text = source('sync-prepare.ts');+ const validated = text.indexOf('await movedImport.validate(tx); applied = movedImport;');+ expect(validated).toBeGreaterThan(0);+ expect(validated).toBeLessThan(text.indexOf('await applied.apply(tx)'));+});++test('the coordinator validates prepared mutations before publication boundaries and file writes', () => {+ const text = source('coordinator.ts');+ const validate = text.indexOf('await prepared.validate?.(tx)');+ expect(validate).toBeGreaterThan(0);+ expect(validate).toBeLessThan(text.indexOf("hooks.boundary?.('before_publication', row)"));+ expect(validate).toBeLessThan(text.indexOf("hooks.fileBoundary?.('before_file', row, index)"));+});diff --git a/test/facts-backstop-unverified-resolution.test.ts b/test/facts-backstop-unverified-resolution.test.tsnew file mode 100644index 0000000000..01b4510f63--- /dev/null+++ b/test/facts-backstop-unverified-resolution.test.ts@@ -0,0 +1,159 @@+/**+ * facts/backstop.ts — unverified-resolution context annotation.+ *+ * `resolveEntitySlugWithSource`'s `prefix_expansion` branch resolves a bare+ * single-token name ("Victor") to the ONLY existing `<dir>/<token>-*` page+ * purely because it's the sole candidate sharing that token — not because+ * anything confirms the mention refers to that same person or company.+ * Unlike `fallback_slugify` (an invented slug, blocked from spawning a+ * canonical stub page by the #4108 stub guard), prefix_expansion always+ * targets an already-existing, already-curated page, so a false match here+ * silently corrupts real content instead of an obviously-empty stub.+ *+ * Observed in the wild 2026-09-03: a Back-to-School-Night meeting+ * transcript's bare "Victor" (a classmate mentioned by first name only)+ * resolved onto an unrelated pre-existing `people/victor-*` page and wrote+ * a fact about him that wasn't his, with no signal anything was off.+ *+ * These tests pin that `runFactsBackstop` stamps the fact's context cell+ * with a visible caution note when (and only when) the entity resolved via+ * prefix_expansion — the fact is still written (dropping it would re-lose+ * real facts the way the daily-enrich.ts died-job bug did), but the+ * uncertainty is no longer indistinguishable from a confirmed fact.+ *+ * Real PGLite engine (in-memory, no DATABASE_URL). LLM is stubbed via+ * __setChatTransportForTests. No sources.local_path configured, so writes+ * take the legacy DB-only bucket — sufficient to exercise the annotation,+ * which is applied identically on both the legacy and fence-write paths.+ */++import { describe, test, expect, beforeAll, afterAll, afterEach } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { runFactsBackstop } from '../src/core/facts/backstop.ts';+import type { FactsBackstopCtx } from '../src/core/facts/backstop.ts';+import {+ __setChatTransportForTests,+ resetGateway,+ type ChatResult,+} from '../src/core/ai/gateway.ts';+import { __resetFactsQueueForTests } from '../src/core/facts/queue.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();++ // Sole `people/victor-*` page — the only candidate prefix_expansion has+ // to pick from for a bare "Victor" mention, whether or not it's the+ // right one.+ await engine.putPage('people/victor-example', {+ type: 'person',+ title: 'Victor Example',+ compiled_truth: '# Victor Example',+ frontmatter: {},+ }, { sourceId: 'default' });+});++afterAll(async () => {+ await engine.disconnect();+});++afterEach(() => {+ __setChatTransportForTests(null);+ resetGateway();+ __resetFactsQueueForTests();+});++const LONG_BODY = 'this is a real meeting note longer than 80 chars '.repeat(3);++function chatStub(facts: Array<{ fact: string; kind: string; notability?: string; entity?: string | null }>) {+ __setChatTransportForTests(async (): Promise<ChatResult> => ({+ text: JSON.stringify({+ facts: facts.map(f => ({+ fact: f.fact,+ kind: f.kind,+ entity: f.entity ?? null,+ confidence: 1.0,+ notability: f.notability,+ })),+ }),+ blocks: [],+ stopReason: 'end',+ usage: { input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_creation_tokens: 0 },+ model: 'test:stub',+ providerId: 'test',+ }));+}++function makeCtx(overrides: Partial<FactsBackstopCtx> = {}): FactsBackstopCtx {+ return {+ engine,+ sourceId: 'default',+ sessionId: null,+ source: 'mcp:put_page',+ ...overrides,+ };+}++const meetingPage = (slug = 'meetings/test-' + Math.random().toString(36).slice(2, 9)) => ({+ slug,+ type: 'meeting' as const,+ compiled_truth: LONG_BODY,+ frontmatter: {} as Record<string, unknown>,+});++async function contextFor(id: number): Promise<string | null> {+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ const rows = await (engine as any).db.query('SELECT context FROM facts WHERE id = $1', [id]);+ return rows.rows[0]?.context ?? null;+}++describe('runFactsBackstop — unverified prefix_expansion resolution', () => {+ test('bare-name entity resolved via prefix_expansion gets a caution note in context', async () => {+ chatStub([+ { fact: 'Victor prefers design and tech over performing', kind: 'preference', notability: 'medium', entity: 'Victor' },+ ]);+ const r = await runFactsBackstop(meetingPage(), makeCtx({ mode: 'inline' }));+ expect(r.mode).toBe('inline');+ if (r.mode !== 'inline') return;+ expect(r.inserted).toBe(1);++ const context = await contextFor(r.fact_ids[0]);+ expect(context).toContain('unverified');+ expect(context).toContain('prefix expansion');+ });++ test('exact-slug entity is NOT annotated', async () => {+ chatStub([+ { fact: 'Victor Example hosted an event', kind: 'event', notability: 'medium', entity: 'people/victor-example' },+ ]);+ const r = await runFactsBackstop(meetingPage(), makeCtx({ mode: 'inline' }));+ expect(r.mode).toBe('inline');+ if (r.mode !== 'inline') return;+ expect(r.inserted).toBe(1);++ const context = await contextFor(r.fact_ids[0]);+ // No sourceSlug is set on this ctx, so an unflagged resolution's+ // context is null (unchanged pre-existing behavior) — assert against+ // '' rather than null so `.not.toContain` doesn't choke on null.+ expect(context ?? '').not.toContain('unverified');+ });++ test('multi-word fuzzy title match is NOT annotated (only bare-name prefix_expansion is)', async () => {+ chatStub([+ { fact: 'Victor Example spoke at the spring meetup', kind: 'event', notability: 'medium', entity: 'Victor Example' },+ ]);+ const r = await runFactsBackstop(meetingPage(), makeCtx({ mode: 'inline' }));+ expect(r.mode).toBe('inline');+ if (r.mode !== 'inline') return;+ expect(r.inserted).toBe(1);++ const context = await contextFor(r.fact_ids[0]);+ // No sourceSlug is set on this ctx, so an unflagged resolution's+ // context is null (unchanged pre-existing behavior) — assert against+ // '' rather than null so `.not.toContain` doesn't choke on null.+ expect(context ?? '').not.toContain('unverified');+ });+});diff --git a/test/facts-extract-confidence.test.ts b/test/facts-extract-confidence.test.tsnew file mode 100644index 0000000000..43e7849f21--- /dev/null+++ b/test/facts-extract-confidence.test.ts@@ -0,0 +1,64 @@+/**+ * B-16: the LLM extractor reads the confidence the model stated. A numeric+ * string ("0.3") used to become 1.0, maximum certainty. A missing or null+ * confidence keeps the legacy 1.0 unless `facts.extraction_missing_confidence`+ * opts into a lower value. Unknown kinds are counted in a warning instead of+ * being folded into 'fact' silently.+ *+ * Gateway chat-transport test seam — no API key, no network.+ */+import { afterAll, beforeEach, describe, expect, test } from 'bun:test';+import { configureGateway, resetGateway, __setChatTransportForTests } from '../src/core/ai/gateway.ts';+import type { ChatResult } from '../src/core/ai/gateway.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import { extractFactsFromTurn } from '../src/core/facts/extract.ts';++beforeEach(() => {+ resetGateway();+ __setChatTransportForTests(null);+ configureGateway({ chat_model: 'anthropic:claude-sonnet-4-6', env: { ANTHROPIC_API_KEY: 'sk-ant-test' } });+});++afterAll(() => {+ __setChatTransportForTests(null);+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: { ...process.env } });+});++function reply(facts: unknown[]): void {+ const text = JSON.stringify({ facts });+ __setChatTransportForTests(async () => ({+ text, blocks: [{ type: 'text', text }], stopReason: 'end',+ usage: { input_tokens: 1, output_tokens: 1, cache_read_tokens: 0, cache_creation_tokens: 0 },+ model: 'anthropic:claude-sonnet-4-6', providerId: 'anthropic',+ }) as ChatResult);+}++const configEngine = (config: Record<string, string>) =>+ ({ getConfig: async (key: string) => config[key] ?? null }) as unknown as BrainEngine;++describe('extractor confidence', () => {+ test('a numeric-string confidence is the stated value, not maximum certainty', async () => {+ reply([{ fact: 'might move to Berlin', kind: 'belief', confidence: '0.3', notability: 'medium' }]);+ const facts = await extractFactsFromTurn({ turnText: 'a hedged turn', source: 'test:confidence' });+ expect(facts.map(f => f.confidence)).toEqual([0.3]);+ });++ test('a missing confidence uses the opt-in configured value', async () => {+ reply([+ { fact: 'might move to Berlin', kind: 'belief', confidence: null, notability: 'medium' },+ { fact: 'likes tea', kind: 'preference', notability: 'medium' },+ { fact: 'works at Acme', kind: 'fact', confidence: 'very', notability: 'medium' },+ ]);+ const facts = await extractFactsFromTurn({+ turnText: 'a turn', source: 'test:confidence', embedding: null,+ engine: configEngine({ 'facts.extraction_missing_confidence': '0.5' }),+ });+ expect(facts.map(f => f.confidence)).toEqual([0.5, 0.5, 0.5]);+ });++ test('without the opt-in, a missing confidence keeps the legacy 1.0', async () => {+ reply([{ fact: 'likes tea', kind: 'preference', notability: 'medium' }]);+ const facts = await extractFactsFromTurn({ turnText: 'a turn', source: 'test:confidence', embedding: null, engine: configEngine({}) });+ expect(facts.map(f => f.confidence)).toEqual([1]);+ });+});diff --git a/test/facts-fence-dates.test.ts b/test/facts-fence-dates.test.tsnew file mode 100644index 0000000000..69a3bf4838--- /dev/null+++ b/test/facts-fence-dates.test.ts@@ -0,0 +1,103 @@+/**+ * Fence date cells are lossless: a TTL or a default "now" valid_from is+ * written as a UTC timestamp, while a date-only (UTC midnight) value keeps its+ * `YYYY-MM-DD` cell. Before, both were truncated to the UTC date, so a+ * `remember(ttl: '1h')` fact was already expired once the fence was re-read,+ * and a fact written in the evening west of UTC was stamped with tomorrow.+ *+ * Real PGLite + a real filesystem under a per-test tempdir.+ */++import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';+import { mkdtempSync, readFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';++import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { writeFactsToFence, type FenceInputFact } from '../src/core/facts/fence-write.ts';+import { formatFenceDate, parseFactsFence } from '../src/core/facts-fence.ts';+import { parseMarkdown } from '../src/core/markdown.ts';+import { runExtractFacts } from '../src/core/cycle/extract-facts.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { _resetWriteThroughCacheForTest } from '../src/core/write-through.ts';++let engine: PGLiteEngine;+let brainDir: string;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+});++afterAll(async () => {+ await engine.disconnect();+});++beforeEach(async () => {+ brainDir = mkdtempSync(join(tmpdir(), 'fence-dates-test-'));+ _resetWriteThroughCacheForTest();+ await engine.executeRaw('DELETE FROM facts');+ await engine.executeRaw('DELETE FROM pages');+ await engine.executeRaw(`UPDATE sources SET local_path = $1 WHERE id = 'default'`, [brainDir]);+});++const input = (overrides: Partial<FenceInputFact> = {}): FenceInputFact => ({+ fact: 'Is traveling this week',+ kind: 'fact',+ notability: 'medium',+ source: 'mcp:remember',+ visibility: 'world',+ confidence: 1.0,+ embedding: null,+ sessionId: null,+ ...overrides,+});++const target = { sourceId: 'default', localPath: '', slug: 'people/ttl-example', resolutionSource: 'exact_page' as const };++describe('formatFenceDate', () => {+ test('UTC midnight renders as a date, anything else as a UTC timestamp', () => {+ expect(formatFenceDate(new Date('2026-03-01T00:00:00.000Z'))).toBe('2026-03-01');+ expect(formatFenceDate(new Date('2026-03-01T22:02:52.123Z'))).toBe('2026-03-01T22:02:52Z');+ });+});++describe('fence date round trip', () => {+ test('a short TTL survives the fence and a rebuild still active', async () => {+ const until = new Date(Date.now() + 60_000);+ const result = await writeFactsToFence(engine, { ...target, localPath: brainDir }, [input({ validUntil: until })]);+ expect(result.inserted).toBe(1);++ const file = readFileSync(join(brainDir, 'people/ttl-example.md'), 'utf-8');+ const [row] = parseFactsFence(parseMarkdown(file, 'people/ttl-example.md').compiled_truth).facts;+ expect(new Date(row.validUntil!).getTime()).toBe(Math.floor(until.getTime() / 1000) * 1000);++ const active = await engine.listFactsByEntity('default', 'people/ttl-example', { activeOnly: true });+ expect(active.map(f => f.fact)).toEqual(['Is traveling this week']);++ // Rebuild from the fence: import the file, drop the index, reconcile.+ await importFromContent(engine, 'people/ttl-example', file, { noEmbed: true });+ await engine.executeRaw('DELETE FROM facts');+ await runExtractFacts(engine, { slugs: ['people/ttl-example'] });+ const rebuilt = await engine.listFactsByEntity('default', 'people/ttl-example', { activeOnly: true });+ expect(rebuilt.map(f => new Date(f.valid_until!).getTime())).toEqual([Math.floor(until.getTime() / 1000) * 1000]);+ });++ test('a default valid_from is the write instant, not the UTC date', async () => {+ const before = Date.now();+ await writeFactsToFence(engine, { ...target, localPath: brainDir }, [input()]);+ const file = readFileSync(join(brainDir, 'people/ttl-example.md'), 'utf-8');+ const [row] = parseFactsFence(parseMarkdown(file, 'people/ttl-example.md').compiled_truth).facts;+ const stamped = new Date(row.validFrom!).getTime();+ expect(stamped).toBeGreaterThanOrEqual(Math.floor(before / 1000) * 1000);+ expect(stamped).toBeLessThanOrEqual(Date.now());+ });++ test('a date-only valid_from keeps its date cell', async () => {+ await writeFactsToFence(engine, { ...target, localPath: brainDir }, [input({ validFrom: new Date(Date.UTC(2017, 0, 1)) })]);+ const file = readFileSync(join(brainDir, 'people/ttl-example.md'), 'utf-8');+ const [row] = parseFactsFence(parseMarkdown(file, 'people/ttl-example.md').compiled_truth).facts;+ expect(row.validFrom).toBe('2017-01-01');+ });+});diff --git a/test/facts-fence-strict-numbers.test.ts b/test/facts-fence-strict-numbers.test.tsnew file mode 100644index 0000000000..80b9da6e19--- /dev/null+++ b/test/facts-fence-strict-numbers.test.ts@@ -0,0 +1,46 @@+/**+ * Fence numeric cells parse strictly (B-15). parseFloat accepted a numeric+ * prefix of anything: `2.5M` stored 2.5 (so an ARR of 2.5M then 900k read as+ * growth), the European decimal `1,5` stored 15, and `0.9abc` confidence+ * passed. Magnitude suffixes (k/M/B) and a leading currency symbol now scale+ * explicitly; any other shape is a FACTS_TABLE_MALFORMED warning, which keeps+ * the page's existing index instead of storing a silently wrong value.+ */++import { describe, test, expect } from 'bun:test';+import { parseFactsFence } from '../src/core/facts-fence.ts';++const fence = (confidence: string, value: string) => `<!--- gbrain:facts:begin -->+| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context | claim_metric | claim_value | claim_unit | claim_period |+|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|--------------|-------------|------------|--------------|+| 1 | ARR | fact | ${confidence} | private | high | 2026-04-12 | | call | | arr | ${value} | USD | annual |+<!--- gbrain:facts:end -->`;++describe('fence numeric cells', () => {+ for (const [cell, expected] of [+ ['2500000', 2500000], ['2,500,000', 2500000], ['2.5M', 2500000], ['900k', 900000],+ ['1.2B', 1200000000], ['$10M', 10000000], ['-3.5', -3.5], ['1e3', 1000], ['0.25', 0.25],+ ] as const) {+ test(`claim_value "${cell}" parses to ${expected}`, () => {+ const parsed = parseFactsFence(fence('0.9', cell));+ expect(parsed.warnings).toEqual([]);+ expect(parsed.facts[0].claimValue).toBe(expected);+ });+ }++ for (const cell of ['1,5', '0.9abc', '12,34,567', '10 million', 'n/a', '1.2.3']) {+ test(`claim_value "${cell}" is a malformed-row warning`, () => {+ const parsed = parseFactsFence(fence('0.9', cell));+ expect(parsed.facts).toEqual([]);+ expect(parsed.warnings.some(w => w.startsWith('FACTS_TABLE_MALFORMED') && w.includes(cell))).toBe(true);+ });+ }++ for (const cell of ['0.9abc', '1.0.0', '90%']) {+ test(`confidence "${cell}" is a malformed-row warning`, () => {+ const parsed = parseFactsFence(fence(cell, '5'));+ expect(parsed.facts).toEqual([]);+ expect(parsed.warnings.some(w => w.startsWith('FACTS_TABLE_MALFORMED') && w.includes(cell))).toBe(true);+ });+ }+});diff --git a/test/facts-write-path-failures.test.ts b/test/facts-write-path-failures.test.tsnew file mode 100644index 0000000000..b599e41eb1--- /dev/null+++ b/test/facts-write-path-failures.test.ts@@ -0,0 +1,111 @@+/**+ * B-21: failures on the facts write path are not swallowed.+ *+ * - The entity resolver no longer turns a database error on the exact-slug+ * or fuzzy lookup into a fallback slug (a silent misattribution); only a+ * brain without pg_trgm degrades the fuzzy arm.+ * - The fence writer's fallback to file-only row numbering when the DB+ * MAX(row_num) lookup fails (the duplicate-key class it guards) is+ * reported instead of silent.+ * - A failed page-cache mirror after a fence write is reported.+ *+ * Real PGLite; failures injected by wrapping executeRaw / refreshPageBody.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, spyOn, test } from 'bun:test';+import { mkdtempSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import { resolveEntitySlugWithSource } from '../src/core/entities/resolve.ts';+import { writeFactsToFence } from '../src/core/facts/fence-write.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { _resetWriteThroughCacheForTest } from '../src/core/write-through.ts';++let engine: PGLiteEngine;+let brainDir: string;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+});++afterAll(async () => {+ await engine.disconnect();+});++beforeEach(async () => {+ brainDir = mkdtempSync(join(tmpdir(), 'facts-failures-'));+ _resetWriteThroughCacheForTest();+ await engine.executeRaw('DELETE FROM facts');+ await engine.executeRaw('DELETE FROM pages');+ await engine.executeRaw(`UPDATE sources SET local_path = $1 WHERE id = 'default'`, [brainDir]);+});++/** An engine whose executeRaw throws for SQL matching `pattern`. */+function failing(pattern: RegExp, error: Error): BrainEngine {+ return new Proxy(engine, {+ get(target, prop, receiver) {+ if (prop === 'executeRaw') {+ return async (sql: string, params?: unknown[]) => {+ if (pattern.test(sql)) throw error;+ return target.executeRaw(sql, params as never);+ };+ }+ const value = Reflect.get(target, prop, receiver);+ return typeof value === 'function' ? value.bind(target) : value;+ },+ }) as unknown as BrainEngine;+}++const input = {+ fact: 'Founded Acme in 2017', kind: 'fact' as const, notability: 'high' as const, source: 'test',+ visibility: 'world' as const, confidence: 1.0, validFrom: new Date(Date.UTC(2017, 0, 1)), embedding: null, sessionId: null,+};++describe('facts write-path failures (B-21)', () => {+ test('an exact-slug lookup error is not a fallback slug', async () => {+ const broken = failing(/SELECT slug FROM pages WHERE source_id = \$1 AND slug = \$2/, new Error('connection reset'));+ await expect(resolveEntitySlugWithSource(broken, 'default', 'people/alice-example')).rejects.toThrow('connection reset');+ });++ test('a fuzzy lookup error is not a fallback slug, but a missing pg_trgm still degrades', async () => {+ const broken = failing(/similarity\(/, new Error('connection reset'));+ await expect(resolveEntitySlugWithSource(broken, 'default', 'Alice Example')).rejects.toThrow('connection reset');+ const noTrgm = failing(/similarity\(/, Object.assign(new Error('function similarity(text, unknown) does not exist'), { code: '42883' }));+ expect(await resolveEntitySlugWithSource(noTrgm, 'default', 'Alice Example'))+ .toEqual({ slug: 'alice-example', source: 'fallback_slugify' });+ });++ test('a failed DB row-number lookup is reported, not silent', async () => {+ const broken = failing(/MAX\(row_num\)/, new Error('connection reset'));+ const warn = spyOn(console, 'warn').mockImplementation(() => {});+ try {+ const result = await writeFactsToFence(broken, { sourceId: 'default', localPath: brainDir, slug: 'people/alice-example', resolutionSource: 'exact_page' }, [input]);+ expect(result.inserted).toBe(1);+ expect(warn.mock.calls.some(c => String(c[0]).includes('FACTS_ROW_NUM_HINT_UNAVAILABLE') && String(c[0]).includes('connection reset'))).toBe(true);+ } finally {+ warn.mockRestore();+ }+ });++ test('a failed page-cache mirror after a fence write is reported', async () => {+ await importFromContent(engine, 'people/alice-example', '---\ntitle: Alice Example\ntype: person\n---\n# Alice Example\n', { noEmbed: true });+ const broken = new Proxy(engine, {+ get(target, prop, receiver) {+ if (prop === 'refreshPageBody') return async () => { throw new Error('mirror write failed'); };+ const value = Reflect.get(target, prop, receiver);+ return typeof value === 'function' ? value.bind(target) : value;+ },+ }) as unknown as BrainEngine;+ const warn = spyOn(console, 'warn').mockImplementation(() => {});+ try {+ const result = await writeFactsToFence(broken, { sourceId: 'default', localPath: brainDir, slug: 'people/alice-example', resolutionSource: 'exact_page' }, [input]);+ expect(result.inserted).toBe(1);+ expect(warn.mock.calls.some(c => String(c[0]).includes('FACTS_PAGE_MIRROR_FAILED') && String(c[0]).includes('mirror write failed'))).toBe(true);+ } finally {+ warn.mockRestore();+ }+ });+});diff --git a/test/fence-write.test.ts b/test/fence-write.test.tsindex 3a4f7f65b7..24d46a2f82 100644--- a/test/fence-write.test.ts+++ b/test/fence-write.test.ts@@ -288,6 +288,49 @@ describe('writeFactsToFence — happy path', () => {}, 60_000);});+describe('writeFactsToFence — withdrawn claims (write-path audit B-10)', () => {+ test('never appends a withdrawn claim, or a punctuation variant of it, as an active Markdown row', async () => {+ await engine.executeRaw(`INSERT INTO fact_withdrawals(source_id,visibility,subject,fact_hash)+ VALUES ('default','world','people/alice',gbrain_fact_fingerprint('Founded Acme in 2017'))`);+ const result = await writeFactsToFence(+ engine,+ { sourceId: 'default', localPath: brainDir, slug: 'people/alice', resolutionSource: 'exact_page' },+ [baseInput(), baseInput({ fact: 'founded Acme, in 2017.' }), baseInput({ fact: 'Moved to Lisbon in 2020' })],+ );+ expect(result.withdrawnSkipped).toBe(2);+ expect(result.inserted).toBe(1);+ const body = readFileSync(join(brainDir, 'people/alice.md'), 'utf-8');+ expect(body).not.toContain('Acme');+ expect(body).toContain('Moved to Lisbon in 2020');+ expect(await engine.executeRaw(`SELECT fact FROM facts WHERE entity_slug='people/alice' ORDER BY id`))+ .toEqual([{ fact: 'Moved to Lisbon in 2020' }]);+ });++ test('a claim withdrawn for another entity is still written for this one', async () => {+ await engine.executeRaw(`INSERT INTO fact_withdrawals(source_id,visibility,subject,fact_hash)+ VALUES ('default','world','people/bob',gbrain_fact_fingerprint('Founded Acme in 2017'))`);+ const result = await writeFactsToFence(+ engine,+ { sourceId: 'default', localPath: brainDir, slug: 'people/alice', resolutionSource: 'exact_page' },+ [baseInput()],+ );+ expect(result).toMatchObject({ inserted: 1 });+ expect(result.withdrawnSkipped).toBeUndefined();+ });++ test('an entirely withdrawn batch leaves the filesystem untouched', async () => {+ await engine.executeRaw(`INSERT INTO fact_withdrawals(source_id,visibility,subject,fact_hash)+ VALUES ('default','world','*',gbrain_fact_fingerprint('Founded Acme in 2017'))`);+ const result = await writeFactsToFence(+ engine,+ { sourceId: 'default', localPath: brainDir, slug: 'people/carol', resolutionSource: 'exact_page' },+ [baseInput()],+ );+ expect(result).toEqual({ inserted: 0, ids: [], withdrawnSkipped: 1 });+ expect(existsSync(join(brainDir, 'people/carol.md'))).toBe(false);+ });+});+describe('writeFactsToFence — legacy fallback', () => {test('null localPath returns legacyFallback:true with no inserts', async () => {const result = await writeFactsToFence(diff --git a/test/helpers/managed-facts-contract.ts b/test/helpers/managed-facts-contract.tsindex 7e637ce7b5..287ec17050 100644--- a/test/helpers/managed-facts-contract.ts+++ b/test/helpers/managed-facts-contract.ts@@ -14,7 +14,7 @@ import { localHostId, registerLocalWriter } from '../../src/core/persistence/ideimport { claimPersistenceEffect } from '../../src/core/persistence/effect-journal.ts';import { dispatchFactsBackstopEffect } from '../../src/core/persistence/effect-facts.ts';import { serializePageToMarkdown } from '../../src/core/markdown.ts';-import { upsertFactRow } from '../../src/core/facts-fence.ts';+import { parseFactsFence, upsertFactRow } from '../../src/core/facts-fence.ts';import { MinionWorker } from '../../src/core/minions/worker.ts';import { registerBuiltinHandlers } from '../../src/commands/jobs.ts';import type { MinionJobContext } from '../../src/core/minions/types.ts';@@ -169,8 +169,15 @@ export async function exerciseManagedFacts(engine: BrainEngine, scenario: Case):const rows = await engine.executeRaw<{ id: number; visibility: string; source_session: string }>('SELECT id,visibility,source_session FROM facts WHERE source_id=$1 AND id=ANY($2::integer[])', [sourceId, first.fact_ids]);expect(rows).toHaveLength(2);for (const row of rows) expect(row).toMatchObject({ visibility: 'private', source_session: 'fixture-session' });- const dates = await engine.executeRaw<{ time: string }>("SELECT to_char(valid_from AT TIME ZONE 'UTC','HH24:MI:SS') AS time FROM facts WHERE source_id=$1 AND id=ANY($2::integer[]) AND source_markdown_slug IS NOT NULL", [sourceId, first.fact_ids]);- for (const date of dates) expect(date.time).toBe('00:00:00');+ // B-20: a fenced fact's indexed valid_from is exactly its fence cell (a+ // lossless write instant, never truncated to the UTC date).+ const dates = await engine.executeRaw<{ fact: string; valid_from: Date; slug: string }>("SELECT fact, valid_from, source_markdown_slug AS slug FROM facts WHERE source_id=$1 AND id=ANY($2::integer[]) AND source_markdown_slug IS NOT NULL", [sourceId, first.fact_ids]);+ expect(dates.length).toBeGreaterThan(0);+ for (const date of dates) {+ const cell = parseFactsFence(readFileSync(join(root, `${date.slug}.md`), 'utf8')).facts.find(f => f.claim === date.fact)!.validFrom!;+ expect(cell).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/);+ expect(new Date(date.valid_from).getTime()).toBe(new Date(cell).getTime());+ }expect(readFileSync(join(root, `${secondSlug}.md`), 'utf8')).toContain('Acme-example measures monthly growth.');expect(JSON.stringify(await operationsByName.get_page.handler(ctx, { slug: secondSlug }))).not.toContain('Acme-example measures monthly growth.');const [afterVector] = await engine.executeRaw<{ vector: string }>('SELECT embedding::text AS vector FROM facts WHERE id=$1', [old.ids[0]]);diff --git a/test/helpers/repeated-consolidation.ts b/test/helpers/repeated-consolidation.tsindex c9147bd9fd..1d71746d2b 100644--- a/test/helpers/repeated-consolidation.ts+++ b/test/helpers/repeated-consolidation.ts@@ -12,6 +12,8 @@* - fabricated quote a quotation nobody said* - speaker swap a real quotation attributed to the other speaker* - invented number a figure the transcript never states+ * - misattributed decision one speaker's proposal stated as another+ * speaker's decision (#5425)* - unquoted invention a plain-prose claim with no quote or number* (not mechanically checkable; measured to show* the limit honestly)@@ -38,7 +40,7 @@ import { normForGrounding } from '../../src/core/cycle/synthesize-verify.ts';import { __setChatTransportForTests, resetGateway, type ChatOpts, type ChatResult } from '../../src/core/ai/gateway.ts';import { withEnv } from './with-env.ts';-export type ClaimKind = 'valid' | 'fabricated_quote' | 'speaker_swap' | 'invented_number' | 'unquoted_invention';+export type ClaimKind = 'valid' | 'fabricated_quote' | 'speaker_swap' | 'invented_number' | 'misattributed_decision' | 'unquoted_invention';export interface ScriptedClaim {id: string;@@ -75,6 +77,10 @@ export const CYCLES: CycleFixture[] = [pad(12),'Alice-example: Our churn is 4% this quarter, down from last quarter.','Bob-example: I will hire two engineers before the launch.',+ 'Bob-example: I suggest we move the offsite to November 12.',+ 'Alice-example: No, keep the offsite where it is.',+ 'Bob-example: Should we cap the pilot budget at $30K?',+ 'Alice-example: Sounds good, do that.',pad(12),].join('\n'),newPage: [@@ -82,6 +88,8 @@ export const CYCLES: CycleFixture[] = [{ id: 'c1-pilot', kind: 'valid', text: 'The acme-example pilot costs $40,000 and starts on September 15th.' },{ id: 'c1-churn', kind: 'valid', text: 'Churn is 4% this quarter.' },{ id: 'c1-hire', kind: 'valid', text: 'Bob-example plans to hire two engineers before the launch.' },+ { id: 'c1-accept', kind: 'valid', text: 'Alice-example agreed to cap the pilot budget at $30K.' },+ { id: 'c1-misattr', kind: 'misattributed_decision', text: 'Alice-example decided to move the offsite to November 12.' },{ id: 'c1-fab', kind: 'fabricated_quote', text: 'Alice-example said "we will shut down the hardware line by December."' },{ id: 'c1-swap', kind: 'speaker_swap', text: 'Bob-example said "We will price the product per seat, not per usage."' },{ id: 'c1-num', kind: 'invented_number', text: 'The pilot budget was raised to $95K.' },@@ -325,9 +333,9 @@ export async function runRepeatedConsolidation(opts: { onCycle?: (cycle: number,const final = perCycle[perCycle.length - 1].active;const invented = claims.filter(c => c.kind !== 'valid');const valid = claims.filter(c => c.kind === 'valid');- const byKind = { fabricated_quote: 0, speaker_swap: 0, invented_number: 0, unquoted_invention: 0 };+ const byKind = { fabricated_quote: 0, speaker_swap: 0, invented_number: 0, misattributed_decision: 0, unquoted_invention: 0 };for (const c of invented) if (final[c.id]) byKind[c.kind as keyof typeof byKind]++;- const claimsByKind = { valid: 0, fabricated_quote: 0, speaker_swap: 0, invented_number: 0, unquoted_invention: 0 };+ const claimsByKind = { valid: 0, fabricated_quote: 0, speaker_swap: 0, invented_number: 0, misattributed_decision: 0, unquoted_invention: 0 };for (const c of claims) claimsByKind[c.kind]++;const person = await engine.getPage(PERSON_SLUG, { sourceId: 'default' });const validLost = valid.filter(c => !final[c.id]).map(c => c.id);diff --git a/test/helpers/with-env.test.ts b/test/helpers/with-env.test.tsindex bfe16064be..56626e99f0 100644--- a/test/helpers/with-env.test.ts+++ b/test/helpers/with-env.test.ts@@ -85,4 +85,11 @@ describe('withEnv', () => {expect(process.env[KEY2]).toBeUndefined();delete process.env[KEY];});++ test('TZ overrides restore the zone in effect before them, not a stale earlier override', async () => {+ const zone = () => Intl.DateTimeFormat().resolvedOptions().timeZone;+ const before = zone();+ for (const tz of ['Asia/Tokyo', 'America/Los_Angeles', 'UTC']) await withEnv({ TZ: tz }, () => expect(zone()).toBe(tz));+ expect(zone()).toBe(before);+ });});diff --git a/test/hybrid-arm-rethrow.test.ts b/test/hybrid-arm-rethrow.test.tsindex f68c22297e..72707b1703 100644--- a/test/hybrid-arm-rethrow.test.ts+++ b/test/hybrid-arm-rethrow.test.ts@@ -100,3 +100,27 @@ describe('hybridSearch both-lexical-arms-FAILED rethrow', () => {expect(results).toEqual([]);});});++describe('a failed lexical arm is stamped in meta.degraded (#5324)', () => {+ test('keyword arm failure → keyword_arm_failed; title arm failure → title_arm_failed', async () => {+ const run = async (arms: Parameters<typeof fakeEngine>[0]) => {+ let degraded: Array<{ stage: string; reason?: string }> = [];+ await hybridSearch(fakeEngine(arms), QUERY, { limit: 5, onMeta: (m) => { degraded = (m.degraded ?? []) as typeof degraded; } });+ return degraded;+ };+ expect(await run({ searchKeyword: () => Promise.reject(new Error('boom')), searchTitles: async () => [] }))+ .toContainEqual({ stage: 'keyword_arm_failed', reason: 'provider_error' });+ const titles = await run({ searchKeyword: async () => [], searchTitles: () => Promise.reject(new Error('boom')) });+ expect(titles).toContainEqual({ stage: 'title_arm_failed', reason: 'provider_error' });+ expect(titles.map(d => d.stage)).not.toContain('keyword_arm_failed');+ });++ test('healthy arms stamp neither stage', async () => {+ let degraded: Array<{ stage: string }> = [];+ await hybridSearch(fakeEngine({ searchKeyword: async () => [], searchTitles: async () => [] }), QUERY, {+ limit: 5, onMeta: (m) => { degraded = (m.degraded ?? []) as typeof degraded; },+ });+ expect(degraded.map(d => d.stage)).not.toContain('keyword_arm_failed');+ expect(degraded.map(d => d.stage)).not.toContain('title_arm_failed');+ });+});diff --git a/test/import-frontmatter-tag-removal.test.ts b/test/import-frontmatter-tag-removal.test.tsnew file mode 100644index 0000000000..0092f31254--- /dev/null+++ b/test/import-frontmatter-tag-removal.test.ts@@ -0,0 +1,55 @@+/**+ * A14: removing a tag from a page's frontmatter removes it from the DB on the+ * next import. Tags carry provenance (`tags.tag_source`): the importer stamps+ * frontmatter tags 'frontmatter' and deletes only those rows once the tag+ * leaves the frontmatter. Tags other producers add (add_tag, enrichment, the+ * code importer) and legacy rows no import has claimed are never deleted.+ *+ * PGLite in-memory, no embeddings ($0).+ */++import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { importFromContent } from '../src/core/import-file.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 60_000);++afterAll(async () => { await engine.disconnect(); }, 30_000);++beforeEach(async () => { await resetPgliteState(engine); });++const page = (tags: string[], body = 'Body text for the page.') =>+ `---\ntype: concept\ntitle: Example\ntags: [${tags.join(', ')}]\n---\n${body}\n`;+const tags = async () => (await engine.getTags('concepts/example')).sort();++describe('frontmatter tag removal (A14)', () => {+ test('a tag removed from frontmatter leaves the DB; other producers keep theirs', async () => {+ await importFromContent(engine, 'concepts/example', page(['alpha', 'beta']), { noEmbed: true });+ await engine.addTag('concepts/example', 'enrichment-tag');+ await importFromContent(engine, 'concepts/example', page(['alpha'], 'Edited body.'), { noEmbed: true });+ expect(await tags()).toEqual(['alpha', 'enrichment-tag']);+ });++ test('an explicit add_tag of a frontmatter tag keeps it after the frontmatter drops it', async () => {+ await importFromContent(engine, 'concepts/example', page(['alpha', 'beta']), { noEmbed: true });+ await engine.addTag('concepts/example', 'beta');+ await importFromContent(engine, 'concepts/example', page(['alpha'], 'Edited body.'), { noEmbed: true });+ expect(await tags()).toEqual(['alpha', 'beta']);+ });++ test('legacy rows are adopted only while they appear in the frontmatter', async () => {+ await importFromContent(engine, 'concepts/example', page(['alpha', 'beta']), { noEmbed: true });+ await engine.addTag('concepts/example', 'legacy-unclaimed');+ await engine.executeRaw('UPDATE tags SET tag_source = NULL');+ await importFromContent(engine, 'concepts/example', page(['alpha', 'beta'], 'Touch.'), { noEmbed: true });+ await importFromContent(engine, 'concepts/example', page(['alpha'], 'Touch again.'), { noEmbed: true });+ expect(await tags()).toEqual(['alpha', 'legacy-unclaimed']);+ });+});diff --git a/test/import-identity-move.test.ts b/test/import-identity-move.test.tsindex 982994e04f..e661902f7b 100644--- a/test/import-identity-move.test.ts+++ b/test/import-identity-move.test.ts@@ -14,7 +14,7 @@*/import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';-import { mkdtempSync, writeFileSync, mkdirSync, renameSync } from 'fs';+import { mkdtempSync, writeFileSync, mkdirSync, renameSync, rmSync } from 'fs';import { execSync } from 'child_process';import { tmpdir } from 'os';import { join } from 'path';@@ -150,3 +150,109 @@ describe('a moved file carries its page', () => {expect(row.compiled_truth).toContain('approved');});});++describe('move inference is bound to the root the page was imported from (#5675)', () => {+ const note = (title: string, body: string) => `---\ntype: note\ntitle: ${title}\nid: reused-template-id\n---\n\n${body}\n`;++ test('importing another root with a reused id never renames the live page', async () => {+ const rootA = mkdtempSync(join(tmpdir(), 'idroot-a-'));+ const rootB = mkdtempSync(join(tmpdir(), 'idroot-b-'));+ mkdirSync(join(rootA, 'notes'), { recursive: true });+ mkdirSync(join(rootB, 'notes'), { recursive: true });+ writeFileSync(join(rootA, 'notes/original.md'), note('Original', 'The original note.'));+ writeFileSync(join(rootB, 'notes/unrelated.md'), note('Unrelated', 'Completely different content.'));+ await importFromFile(engine, join(rootA, 'notes/original.md'), 'notes/original.md', { noEmbed: true });+ const [before] = await engine.executeRaw<{ id: number }>(`SELECT id FROM pages WHERE slug = 'notes/original'`);++ const second = await importFromFile(engine, join(rootB, 'notes/unrelated.md'), 'notes/unrelated.md', { noEmbed: true });+ expect(second.status).toBe('imported');+ expect(second.slug).toBe('notes/unrelated');+ expect(await liveSlugs()).toEqual(['notes/original', 'notes/unrelated']);+ const [original] = await engine.executeRaw<{ id: number; compiled_truth: string }>(+ `SELECT id, compiled_truth FROM pages WHERE slug = 'notes/original'`);+ expect(Number(original.id)).toBe(Number(before.id));+ expect(original.compiled_truth).toContain('The original note.');+ });++ test('an identical copy under another root is a duplicate, not a move', async () => {+ const rootA = mkdtempSync(join(tmpdir(), 'idroot-a-'));+ const rootB = mkdtempSync(join(tmpdir(), 'idroot-b-'));+ mkdirSync(join(rootA, 'notes'), { recursive: true });+ mkdirSync(join(rootB, 'notes'), { recursive: true });+ writeFileSync(join(rootA, 'notes/original.md'), note('Original', 'Same text.'));+ writeFileSync(join(rootB, 'notes/copy.md'), note('Original', 'Same text.'));+ await importFromFile(engine, join(rootA, 'notes/original.md'), 'notes/original.md', { noEmbed: true });+ const copy = await importFromFile(engine, join(rootB, 'notes/copy.md'), 'notes/copy.md', { noEmbed: true });+ expect(copy.status).toBe('skipped');+ expect(copy.slug).toBe('notes/original');+ expect(await liveSlugs()).toEqual(['notes/original']);+ });++ test('a missing file under another root is no move evidence even when the old file is gone', async () => {+ const rootA = mkdtempSync(join(tmpdir(), 'idroot-a-'));+ const rootB = mkdtempSync(join(tmpdir(), 'idroot-b-'));+ mkdirSync(join(rootA, 'inbox'), { recursive: true });+ mkdirSync(join(rootB, 'archive'), { recursive: true });+ writeFileSync(join(rootA, 'inbox/plan.md'), note('Plan', 'Draft plan.'));+ await importFromFile(engine, join(rootA, 'inbox/plan.md'), 'inbox/plan.md', { noEmbed: true });+ rmSync(join(rootA, 'inbox/plan.md'));+ writeFileSync(join(rootB, 'archive/plan.md'), note('Plan', 'Final plan, approved.'));+ const other = await importFromFile(engine, join(rootB, 'archive/plan.md'), 'archive/plan.md', { noEmbed: true });+ expect(other.slug).toBe('archive/plan');+ expect(await liveSlugs()).toEqual(['archive/plan', 'inbox/plan']);+ });++ test('full sync: a new file reusing a deleted file\'s id indexes as its own page', async () => {+ await runSources(engine, ['add', 'reuse-src', '--no-federated']);+ const repo = gitRepo('idroot-sync-');+ mkdirSync(join(repo, 'notes'), { recursive: true });+ writeFileSync(join(repo, 'notes/original.md'), note('Original', 'The original note.'));+ execSync('git add -A && git commit -qm init', { cwd: repo });+ await performSync(engine, { repoPath: repo, full: true, sourceId: 'reuse-src', noPull: true, noEmbed: true });+ const [before] = await engine.executeRaw<{ id: number }>(`SELECT id FROM pages WHERE source_id = 'reuse-src' AND slug = 'notes/original'`);++ rmSync(join(repo, 'notes/original.md'));+ writeFileSync(join(repo, 'notes/unrelated.md'), note('Unrelated', 'Completely different content.'));+ execSync('git add -A && git commit -qm reuse', { cwd: repo });+ await performSync(engine, { repoPath: repo, full: true, sourceId: 'reuse-src', noPull: true, noEmbed: true });++ expect(await liveSlugs('reuse-src')).toEqual(['notes/unrelated']);+ const [after] = await engine.executeRaw<{ id: number; compiled_truth: string }>(+ `SELECT id, compiled_truth FROM pages WHERE source_id = 'reuse-src' AND slug = 'notes/unrelated'`);+ expect(Number(after.id)).not.toBe(Number(before.id));+ expect(after.compiled_truth).toContain('Completely different content.');+ }, 60_000);+});++describe('move evidence origin', () => {+ test('a page recorded before origins existed falls back to the source\'s configured root', async () => {+ const root = mkdtempSync(join(tmpdir(), 'idroot-cfg-'));+ mkdirSync(join(root, 'inbox'), { recursive: true });+ mkdirSync(join(root, 'archive'), { recursive: true });+ writeFileSync(join(root, 'inbox/plan.md'), page('uuid-legacy', 'Draft plan.'));+ await importFromFile(engine, join(root, 'inbox/plan.md'), 'inbox/plan.md', { noEmbed: true });+ const [recorded] = await engine.executeRaw<{ source_uri: string | null }>(`SELECT source_uri FROM pages WHERE slug = 'inbox/plan'`);+ expect(recorded.source_uri).toBe(`file://${join(root, 'inbox/plan.md')}`);+ await engine.executeRaw(`UPDATE pages SET source_uri = NULL WHERE slug = 'inbox/plan'`);+ renameSync(join(root, 'inbox/plan.md'), join(root, 'archive/plan.md'));++ const unbound = await importFromFile(engine, join(root, 'archive/plan.md'), 'archive/plan.md', { noEmbed: true });+ expect(unbound.status).toBe('skipped');+ expect(await liveSlugs()).toEqual(['inbox/plan']);++ await engine.executeRaw(`UPDATE sources SET local_path = $1 WHERE id = 'default'`, [root]);+ const moved = await importFromFile(engine, join(root, 'archive/plan.md'), 'archive/plan.md', { noEmbed: true });+ expect(moved.slug).toBe('archive/plan');+ expect(await liveSlugs()).toEqual(['archive/plan']);+ });++ test('a file import never replaces non-file provenance', async () => {+ const root = mkdtempSync(join(tmpdir(), 'idroot-prov-'));+ mkdirSync(join(root, 'notes'), { recursive: true });+ await importFromContent(engine, 'notes/captured', page('uuid-cap', 'Captured.'), { noEmbed: true, source_uri: 'https://example.com/msg/1' });+ writeFileSync(join(root, 'notes/captured.md'), page('uuid-cap', 'Captured, then edited on disk.'));+ await importFromFile(engine, join(root, 'notes/captured.md'), 'notes/captured.md', { noEmbed: true });+ const [row] = await engine.executeRaw<{ source_uri: string | null }>(`SELECT source_uri FROM pages WHERE slug = 'notes/captured'`);+ expect(row.source_uri).toBe('https://example.com/msg/1');+ });+});diff --git a/test/import-markdown-embedding-reuse.test.ts b/test/import-markdown-embedding-reuse.test.tsnew file mode 100644index 0000000000..ecf8637c88--- /dev/null+++ b/test/import-markdown-embedding-reuse.test.ts@@ -0,0 +1,115 @@+/**+ * A13: a markdown edit re-embeds only the chunks whose embedding input+ * changed. Unchanged chunks keep their stored vectors when the chunk text,+ * chunk source, contextual wrapper and embedding signature all match and+ * neither the old nor the new body holds protected (facts/takes) fences.+ *+ * PGLite in-memory; the embedding transport is stubbed ($0).+ */++import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';+import { importFromContent } from '../src/core/import-file.ts';++const DIMS = 1536;+let engine: PGLiteEngine;+let embedded: string[] = [];+let counter = 0;++function gateway(model = 'openai:text-embedding-3-large') {+ configureGateway({ embedding_model: model, embedding_dimensions: DIMS, env: { OPENAI_API_KEY: 'sk-test' } });+ __setEmbedTransportForTests((async ({ values }: { values: string[] }) => {+ embedded.push(...values);+ return {+ embeddings: values.map(() => { const v = new Array(DIMS).fill(0); v[counter++ % DIMS] = 1; return v; }),+ usage: { tokens: values.length },+ };+ }) as never);+}++beforeAll(async () => {+ resetGateway();+ gateway();+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 60_000);++afterAll(async () => {+ __setEmbedTransportForTests(null);+ resetGateway();+ await engine.disconnect();+}, 30_000);++beforeEach(() => { embedded = []; gateway(); });++const paragraph = (word: string) => Array.from({ length: 400 }, (_, i) => `${word}${i}`).join(' ') + '.';+const page = (title: string, words: string[], extra = '') =>+ `---\ntype: note\ntitle: ${title}\n---\n\n${words.map(w => `## Section ${w}\n\n${paragraph(w)}`).join('\n\n')}\n${extra}`;++async function vectors(slug: string) {+ const chunks = await engine.getChunks(slug, { includeEmbedding: true, includeUnsealed: true });+ return new Map(chunks.map(c => [c.chunk_text, Array.from(c.embedding as Float32Array).indexOf(1)]));+}++describe('markdown import reuses unchanged chunk vectors (A13)', () => {+ test('a one-section edit embeds only the changed chunk and keeps the others byte-identical', async () => {+ const slug = 'notes/reuse-edit';+ await importFromContent(engine, slug, page('Reuse', ['alpha', 'bravo', 'charlie', 'delta']));+ const before = await vectors(slug);+ expect(before.size).toBeGreaterThanOrEqual(3);+ embedded = [];+ await importFromContent(engine, slug, page('Reuse', ['alpha', 'bravo', 'charlie', 'echo']));+ const after = await vectors(slug);+ expect(embedded.length).toBeLessThan(before.size);+ expect(embedded.length).toBeGreaterThan(0);+ for (const text of embedded) expect(text).toContain('echo');+ for (const [text, idx] of after) {+ if (before.has(text)) expect(idx).toBe(before.get(text)!);+ expect(idx).toBeGreaterThanOrEqual(0);+ }+ });++ test('a title change under the title wrapper re-embeds every chunk', async () => {+ await engine.setConfig('search.contextual_retrieval', 'title');+ try {+ const slug = 'notes/reuse-title';+ await importFromContent(engine, slug, page('First title', ['alpha', 'bravo', 'charlie']));+ const count = (await vectors(slug)).size;+ embedded = [];+ await importFromContent(engine, slug, page('Second title', ['alpha', 'bravo', 'charlie']));+ expect(embedded.length).toBe(count);+ } finally {+ await engine.unsetConfig?.('search.contextual_retrieval');+ await engine.executeRaw(`DELETE FROM config WHERE key = 'search.contextual_retrieval'`);+ }+ });++ test('an embedding model change re-embeds every chunk', async () => {+ const slug = 'notes/reuse-model';+ await importFromContent(engine, slug, page('Model', ['alpha', 'bravo', 'charlie']));+ embedded = [];+ gateway('openai:text-embedding-3-small');+ await importFromContent(engine, slug, page('Model', ['alpha', 'bravo', 'charlie', 'delta']));+ expect(embedded.length).toBe((await vectors(slug)).size);+ });++ test('a page with protected fences never reuses vectors', async () => {+ const slug = 'notes/reuse-protected';+ const fence = '\n<!--- gbrain:takes:begin -->\nPRIVATE_CANARY\n<!--- gbrain:takes:end -->\n';+ await importFromContent(engine, slug, page('Protected', ['alpha', 'bravo', 'charlie'], fence));+ embedded = [];+ await importFromContent(engine, slug, page('Protected', ['alpha', 'bravo', 'delta'], fence));+ const count = (await vectors(slug)).size;+ expect(embedded.length).toBe(count);+ });++ test('--force-rechunk re-embeds every chunk', async () => {+ const slug = 'notes/reuse-force';+ await importFromContent(engine, slug, page('Force', ['alpha', 'bravo', 'charlie']));+ embedded = [];+ await importFromContent(engine, slug, page('Force', ['alpha', 'bravo', 'delta']), { forceRechunk: true });+ expect(embedded.length).toBe((await vectors(slug)).size);+ });+});diff --git a/test/ingestion/put-page-write-through.test.ts b/test/ingestion/put-page-write-through.test.tsindex 70c7a9bacb..297e5acf88 100644--- a/test/ingestion/put-page-write-through.test.ts+++ b/test/ingestion/put-page-write-through.test.ts@@ -16,7 +16,7 @@ import { PGLiteEngine } from '../../src/core/pglite-engine.ts';import { resetPgliteState } from '../helpers/reset-pglite.ts';import { operations, OperationError } from '../../src/core/operations.ts';import type { OperationContext } from '../../src/core/operations.ts';-import { resetGateway } from '../../src/core/ai/gateway.ts';+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../../src/core/ai/gateway.ts';import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';import { withEnv } from '../helpers/with-env.ts';import { parseMarkdown, serializePageToMarkdown } from '../../src/core/markdown.ts';@@ -97,6 +97,31 @@ const putPage = { ...putPageOperation,};describe('put_page write-through — happy path', () => {+ test('MCP writes commit before any embedding and queue it durably (#5100)', async () => {+ let embedCalls = 0;+ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: 1536, env: { OPENAI_API_KEY: 'sk-test' } });+ __setEmbedTransportForTests(async ({ values }: { values: string[] }) => {+ embedCalls++;+ return { embeddings: values.map(() => new Array(1536).fill(0)), usage: { tokens: 1 } } as any;+ });+ try {+ const ctx = makeCtx({ remote: true });+ const result = (await putPage.handler(ctx, {+ slug: 'inbox/mcp-deferred-embed',+ content: '---\ntitle: Deferred\n---\n\nThis page must be durable before its embedding runs.',+ })) as { embedding_state?: string; persistence?: { embedding_state?: string } };+ expect(embedCalls).toBe(0);+ expect(result.embedding_state ?? result.persistence?.embedding_state).toBe('queued');+ expect(await engine.getPage('inbox/mcp-deferred-embed', { sourceId: 'default' })).not.toBeNull();+ const [chunks] = await engine.executeRaw<{ n: number }>(+ `SELECT COUNT(*)::int AS n FROM content_chunks c JOIN pages p ON p.id = c.page_id WHERE p.slug = 'inbox/mcp-deferred-embed' AND c.embedding IS NULL`);+ expect(Number(chunks.n)).toBeGreaterThan(0);+ } finally {+ __setEmbedTransportForTests(null);+ resetGateway();+ }+ });+test('writes the markdown file to disk at brainDir/<slug>.md', async () => {const ctx = makeCtx();const content = '---\ntitle: Test\n---\n\n# WT body';diff --git a/test/insert-facts-batch.test.ts b/test/insert-facts-batch.test.tsindex 6f669ad54b..57e5fd5090 100644--- a/test/insert-facts-batch.test.ts+++ b/test/insert-facts-batch.test.ts@@ -380,23 +380,33 @@ describe('engine.insertFacts — v0.46 (#3014) supersession transport', () => {expect(persisted.rows[0].superseded_by).toBeNull();});- test('chain (#N names another struck row) → superseded_by NULL + warning', async () => {+ test('chain (#N names another superseded row) → every hop links, no warning', async () => {// Row 1 superseded by #2; row 2 is itself struck (superseded by #3).+ // B-13: an A -> B -> C history keeps both links.const r = await engine.insertFacts([struck(1, 2, { fact: 'link a' }), struck(2, 3, { fact: 'link b' }), fixtureFact(3, { fact: 'live tail' })],{ source_id: 'default' },);- // Row 1 → row 2 is a chain (row 2 struck) → NULL + warning.- // Row 2 → row 3 (live) resolves cleanly.- expect(r.warnings.some(w => w.includes('struck'))).toBe(true);+ expect(r.warnings).toEqual([]);// eslint-disable-next-line @typescript-eslint/no-explicit-anyconst persisted = await (engine as any).db.query(`SELECT row_num, superseded_by FROM facts WHERE source_markdown_slug = 'people/alice' ORDER BY row_num`,);- expect(persisted.rows[0].superseded_by).toBeNull(); // row 1: chain rejected+ expect(Number(persisted.rows[0].superseded_by)).toBe(Number(r.ids[1])); // row 1 → row 2expect(Number(persisted.rows[1].superseded_by)).toBe(Number(r.ids[2])); // row 2 → row 3});+ test('forgotten target (struck, not superseded) → superseded_by NULL + warning', async () => {+ const forgotten = { ...fixtureFact(2, { fact: 'withdrawn' }), expired_at: new Date('2026-01-01T00:00:00Z') };+ const r = await engine.insertFacts([struck(1, 2, { fact: 'link a' }), forgotten], { source_id: 'default' });+ expect(r.warnings.some(w => w.includes('struck'))).toBe(true);+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ const persisted = await (engine as any).db.query(+ `SELECT superseded_by FROM facts WHERE row_num = 1 AND source_markdown_slug = 'people/alice'`,+ );+ expect(persisted.rows[0].superseded_by).toBeNull();+ });+test('int4-overflow reference (11-digit #N) resolves as dangling — never throws', async () => {// The fence parser accepts any finite #N; an 11-digit value would// overflow the int4 row_num comparison in the resolution SELECT anddiff --git a/test/longmemeval-embed-cache.test.ts b/test/longmemeval-embed-cache.test.tsindex 5f14e5e086..b8eba70a9a 100644--- a/test/longmemeval-embed-cache.test.ts+++ b/test/longmemeval-embed-cache.test.ts@@ -470,3 +470,66 @@ describe('installEmbedCache — gateway seam', () => {cache.close();});});++describe('EmbeddingCache — concurrent runs sharing one cache file', () => {+ test('withTransaction does not hold the SQLite write lock across its async body', async () => {+ const path = join(dir, 'shared.sqlite');+ const a = new EmbeddingCache(path);+ a.open();+ let lockedDuringBody: string | null = 'not-probed';+ await a.withTransaction(async () => {+ a.put(MODEL, DIMS, 'a-1', vec(1));+ await Promise.resolve();+ const other = new Database(path);+ try {+ other.exec('PRAGMA busy_timeout = 0');+ other.exec('BEGIN IMMEDIATE');+ other.exec('ROLLBACK');+ lockedDuringBody = null;+ } catch (err) {+ lockedDuringBody = (err as Error).message;+ } finally {+ other.close();+ }+ });+ expect(lockedDuringBody).toBeNull();+ expect(a.get(MODEL, DIMS, 'a-1')).toEqual(vec(1));+ a.close();+ });++ test('a run whose read snapshot predates another run\'s commit still lands its writes', async () => {+ const path = join(dir, 'shared.sqlite');+ const a = new EmbeddingCache(path);+ const b = new EmbeddingCache(path);+ a.open();+ b.open();+ let releaseA!: () => void;+ const gateA = new Promise<void>((r) => { releaseA = r; });+ const runA = a.withTransaction(async () => {+ a.put(MODEL, DIMS, 'a-1', vec(1));+ await gateA;+ });+ await b.withTransaction(async () => {+ expect(b.get(MODEL, DIMS, 'b-1')).toBeNull();+ releaseA();+ await runA;+ b.put(MODEL, DIMS, 'b-1', vec(2));+ });+ expect(b.get(MODEL, DIMS, 'a-1')).toEqual(vec(1));+ expect(a.get(MODEL, DIMS, 'b-1')).toEqual(vec(2));+ expect(a.stats().infra_faults + b.stats().infra_faults).toBe(0);+ a.close();+ b.close();+ });++ test('reads inside a transaction see that transaction\'s own buffered writes', async () => {+ const c = new EmbeddingCache(join(dir, 'own.sqlite'));+ c.open();+ await c.withTransaction(async () => {+ c.put(MODEL, DIMS, 'x', vec(3));+ expect(c.get(MODEL, DIMS, 'x')).toEqual(vec(3));+ });+ expect(c.size()).toBe(1);+ c.close();+ });+});diff --git a/test/managed-maintenance-links.test.ts b/test/managed-maintenance-links.test.tsnew file mode 100644index 0000000000..bf03cb8f6e--- /dev/null+++ b/test/managed-maintenance-links.test.ts@@ -0,0 +1,85 @@+// #5685 follow-up: a managed maintenance page write (the dream synthesis+// write-back after grounding quarantine) reconciles the page's automatic+// links from the published body, the same way an ordinary put_page does. A+// link that only a quarantined sentence carried must not outlive it.++import { afterAll, beforeAll, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { maintenancePreflight, publishMaintenancePage } from '../src/core/persistence/prepared-maintenance.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { withEnv } from './helpers/with-env.ts';+import { testBackends } from './helpers/test-backends.ts';++const backends = testBackends();+const engines: BrainEngine[] = [];+const dataDir = mkdtempSync(join(tmpdir(), 'gbrain-maintenance-links-db-'));+let closePostgres: (() => Promise<void>) | undefined;+beforeAll(async () => {+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} });+ if (backends.includes('pglite')) {+ const engine = new PGLiteEngine();+ await engine.connect({ database_path: dataDir }); await engine.initSchema(); engines.push(engine);+ }+ if (backends.includes('postgres')) {+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);+ engines.push(pg.engine); closePostgres = pg.close;+ }+}, 120_000);+afterAll(async () => {+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }+ await closePostgres?.(); resetGateway(); rmSync(dataDir, { recursive: true, force: true });+});++async function linkTargets(engine: BrainEngine, sourceId: string, slug: string): Promise<string[]> {+ const rows = await engine.executeRaw<{ slug: string }>(+ `SELECT t.slug FROM links l JOIN pages f ON f.id = l.from_page_id JOIN pages t ON t.id = l.to_page_id+ WHERE f.source_id = $1 AND f.slug = $2 ORDER BY t.slug`, [sourceId, slug]);+ return rows.map(r => r.slug);+}++test('a managed maintenance page write reconciles automatic links from the published body', async () => {+ for (const engine of engines) {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-maintenance-links-'));+ const root = join(dir, 'brain'); mkdirSync(root);+ const sourceId = `links-${randomUUID().slice(0, 8)}`;+ try {+ await withEnv({ GBRAIN_HOME: join(dir, 'home') }, async () => {+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);+ await engine.setConfig('sync.write_through', 'true');+ await claimWorktree(engine, sourceId, root);+ const ctx = { engine, sourceId, remote: false as const, config: { engine: engine.kind, embedding_disabled: true },+ dryRun: false, logger: { info() {}, warn() {}, error() {} } };+ for (const slug of ['people/alice-example', 'people/bob-example', 'people/carol-example']) {+ await submitPageMutation(ctx, { operation: 'put_page', params: {+ slug, content: `---\ntitle: ${slug}\ntype: person\n---\nA person.`, request_id: randomUUID() } });+ }+ const slug = 'wiki/personal/reflections/session-abc123';+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug, request_id: randomUUID(),+ content: '---\ntitle: Session\ntype: note\n---\nMet [[people/alice-example]]. Invented: [[people/bob-example]] said "a fabricated quote".' } });+ expect(await linkTargets(engine, sourceId, slug)).toEqual(['people/alice-example', 'people/bob-example']);++ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const authority = (await maintenancePreflight(engine, sourceId))!;+ const before = (await engine.readPageSnapshot(slug, { sourceId }))!;+ await publishMaintenancePage(engine, authority, slug,+ '---\ntitle: Session\ntype: note\n---\nMet [[people/alice-example]] and [[people/carol-example]].', { expectedRevision: before.revision });++ expect(await linkTargets(engine, sourceId, slug)).toEqual(['people/alice-example', 'people/carol-example']);+ });+ } finally {+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ rmSync(dir, { recursive: true, force: true });+ }+ }+}, 60_000);diff --git a/test/mcp-client-hardening.test.ts b/test/mcp-client-hardening.test.tsindex 3334c64fd6..b4f4c14580 100644--- a/test/mcp-client-hardening.test.ts+++ b/test/mcp-client-hardening.test.ts@@ -19,9 +19,11 @@ import {extractToolErrorCode,extractToolErrorDetail,buildAbortController,+ buildMcpRequestOptions,RemoteMcpError,type CallRemoteToolOptions,} from '../src/core/mcp-client.ts';+import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';const MCP_URL = 'https://brain-host.example/mcp';const PENDING_WRITE = { request_id: 'd7599b95-65c2-4d54-aa4e-cb5745af90cf', state: 'queued' as const, retry_after_ms: 1000 };@@ -80,6 +82,14 @@ describe('toRemoteMcpError', () => {expect(out.detail?.kind).toBe('timeout');});+ test('SDK RequestTimeout becomes network/timeout while the caller signal is still live', () => {+ const controller = new AbortController();+ const out = toRemoteMcpError(new McpError(ErrorCode.RequestTimeout, 'Request timed out', { timeout: 60_000 }), MCP_URL, controller.signal);+ expect(controller.signal.aborted).toBe(false);+ expect(out.reason).toBe('network');+ expect(out.detail?.kind).toBe('timeout');+ });+test('non-Error throwable (string) becomes network/unreachable', () => {const out = toRemoteMcpError('something blew up', MCP_URL);expect(out).toBeInstanceOf(RemoteMcpError);@@ -284,6 +294,18 @@ describe('buildAbortController', () => {});});+describe('buildMcpRequestOptions', () => {+ test('forwards the caller timeout into the MCP SDK request deadline', () => {+ const controller = new AbortController();+ expect(buildMcpRequestOptions({ timeoutMs: 200_000 }, controller.signal)).toEqual({ signal: controller.signal, timeout: 200_000 });+ });++ test('leaves the SDK default untouched when no timeout was requested', () => {+ const controller = new AbortController();+ expect(buildMcpRequestOptions({}, controller.signal)).toEqual({ signal: controller.signal });+ });+});+describe('RemoteMcpError class shape', () => {test('is an instance of Error', () => {const e = new RemoteMcpError('network', 'msg');diff --git a/test/persistence-diagnostics.test.ts b/test/persistence-diagnostics.test.tsindex 1d6bbb19f8..3d1c5dc7b1 100644--- a/test/persistence-diagnostics.test.ts+++ b/test/persistence-diagnostics.test.ts@@ -97,14 +97,14 @@ test('fresh and upgraded engines agree on the database-only pending index', asyn} finally { abort.abort(); release.resolve(); await holding; await interrupted; }}await engine.setConfig('version', '164');- expect(LATEST_VERSION).toBe(173);- expect(await runMigrations(engine)).toEqual({ applied: 9, current: 173 });+ expect(LATEST_VERSION).toBe(175);+ expect(await runMigrations(engine)).toEqual({ applied: 11, current: 175 });const [upgraded] = await engine.executeRaw<{ indexdef: string }>("SELECT indexdef FROM pg_indexes WHERE indexname='persistence_requests_database_pending'");expect(upgraded.indexdef).toBe(fresh.indexdef);const [parked] = await engine.executeRaw<{ indexdef: string }>("SELECT indexdef FROM pg_indexes WHERE indexname='persistence_effects_parked'");expect(parked.indexdef).toContain('parked');- expect(await engine.getConfig('version')).toBe('173');+ expect(await engine.getConfig('version')).toBe('175');}}, 15000);diff --git a/test/persistence-managed-lifecycle.test.ts b/test/persistence-managed-lifecycle.test.tsnew file mode 100644index 0000000000..086295d4d2--- /dev/null+++ b/test/persistence-managed-lifecycle.test.ts@@ -0,0 +1,317 @@+/**+ * Managed-path lifecycle regressions found by the gbrain-evals lifecycle+ * experiment: slug collisions, renames (identity, inbound links, old-slug+ * aliases), link extraction on the managed write path, and `extract --stale`+ * on a managed brain. Runs on PGLite, and on Postgres when DATABASE_URL is set.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { execFileSync } from 'node:child_process';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { runManagedStaleExtraction } from '../src/core/persistence/links-maintenance.ts';+import { runExtract } from '../src/commands/extract.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { LINK_EXTRACTOR_VERSION_TS } from '../src/core/link-extraction.ts';+import { withEnv } from './helpers/with-env.ts';++const home = mkdtempSync(join(tmpdir(), 'gbrain-managed-lifecycle-'));+const engines: BrainEngine[] = [];+const sources: string[] = [];+let closePostgres: (() => Promise<void>) | undefined;+function git(root: string, ...args: string[]): string { return execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim(); }+function commit(root: string, message = 'test content'): string {+ git(root, 'add', '-A'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message);+ return git(root, 'rev-parse', 'HEAD');+}+function write(root: string, path: string, body: string) { const full = join(root, path); mkdirSync(join(full, '..'), { recursive: true }); writeFileSync(full, body); }+async function fixture(engine: BrainEngine, files: Record<string, string>) {+ const id = `life-${randomUUID().replace(/-/g, '').slice(0, 20)}`; sources.push(id);+ const root = join(home, id); mkdirSync(root); git(root, 'init', '-q');+ for (const [path, body] of Object.entries(files)) write(root, path, body);+ const head = commit(root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,\'{}\')', [id, root]);+ await claimWorktree(engine, id, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ return { id, root, head };+}+const person = (title: string) => `---\ntitle: ${title}\ntype: person\n---\n${title} is a fictional person.\n`;+const note = (title: string, body: string, extra = '') => `---\ntitle: ${title}\n${extra}---\n${body}\n`;+async function backlinkSources(engine: BrainEngine, slug: string, sourceId: string) {+ return (await engine.getBacklinks(slug, { sourceId })).map(link => link.from_slug).sort();+}+async function pageId(engine: BrainEngine, slug: string, sourceId: string) {+ const [row] = await engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL', [sourceId, slug]);+ return row?.id ?? null;+}++beforeAll(async () => {+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);+ if (process.env.DATABASE_URL) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL); engines.push(pg.engine); closePostgres = pg.close; }+}, 120_000);+afterAll(async () => {+ await withEnv({ GBRAIN_HOME: home }, async () => {+ for (const engine of engines) {+ await disposePersistenceConsumer(engine); await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ for (const id of sources) { await engine.executeRaw('DELETE FROM oauth_clients WHERE source_id=$1', [id]); await engine.executeRaw('DELETE FROM sources WHERE id=$1', [id]); }+ await engine.disconnect();+ }+ });+ await closePostgres?.();+ rmSync(home, { recursive: true, force: true });+});++test('two files mapping to one slug skip the loser instead of blocking the whole sync', async () => withEnv({ GBRAIN_HOME: home }, async () => {+ for (const engine of engines) {+ const f = await fixture(engine, {+ 'notes/Foo Bar.md': note('Foo Bar spaced', 'Apples and orchards.'),+ 'notes/foo-bar.md': note('foo-bar dashed', 'Oranges and groves.'),+ 'notes/zz-bystander.md': note('Bystander', 'An ordinary note that sorts after the pair.'),+ });+ const first = await performManagedSync(engine, { sourceId: f.id, noPull: true });+ expect(first).toMatchObject({ status: 'first_sync', added: 2 });+ expect(first.slugCollisions).toEqual([{ slug: 'notes/foo-bar', kept: 'notes/foo-bar.md', skipped: ['notes/Foo Bar.md'] }]);+ const kept = await engine.getPage('notes/foo-bar', { sourceId: f.id });+ expect(kept?.source_path).toBe('notes/foo-bar.md');+ expect(kept?.compiled_truth).toContain('Oranges');+ expect(await engine.getPage('notes/zz-bystander', { sourceId: f.id })).not.toBeNull();+ const [source] = await engine.executeRaw<{ last_commit: string }>('SELECT last_commit FROM sources WHERE id=$1', [f.id]);+ expect(source.last_commit).toBe(f.head);+ // A full re-import reports the same collision and still succeeds.+ const full = await performManagedSync(engine, { sourceId: f.id, noPull: true, full: true });+ expect(['synced', 'up_to_date']).toContain(full.status);+ expect(full.slugCollisions).toEqual([{ slug: 'notes/foo-bar', kept: 'notes/foo-bar.md', skipped: ['notes/Foo Bar.md'] }]);+ expect(await engine.executeRaw("SELECT id FROM persistence_requests WHERE source_id=$1 AND state<>'committed'", [f.id])).toEqual([]);+ }+}), 180_000);++test('a live page keeps its slug when a later file maps onto it', async () => withEnv({ GBRAIN_HOME: home }, async () => {+ for (const engine of engines) {+ const f = await fixture(engine, { 'notes/Foo Bar.md': note('Foo Bar spaced', 'Apples and orchards.') });+ await performManagedSync(engine, { sourceId: f.id, noPull: true });+ const owner = await pageId(engine, 'notes/foo-bar', f.id);+ write(f.root, 'notes/foo-bar.md', note('foo-bar dashed', 'Oranges and groves.'));+ write(f.root, 'notes/other.md', note('Other', 'Unrelated content.'));+ commit(f.root, 'colliding file');+ const next = await performManagedSync(engine, { sourceId: f.id, noPull: true });+ expect(next).toMatchObject({ status: 'synced', added: 1 });+ expect(next.slugCollisions).toEqual([{ slug: 'notes/foo-bar', kept: 'notes/Foo Bar.md', skipped: ['notes/foo-bar.md'] }]);+ expect(await pageId(engine, 'notes/foo-bar', f.id)).toBe(owner);+ expect((await engine.getPage('notes/foo-bar', { sourceId: f.id }))?.compiled_truth).toContain('Apples');+ expect(await engine.getPage('notes/other', { sourceId: f.id })).not.toBeNull();+ }+}), 180_000);++test('a file that replaces its vanished origin at the same slug takes over the page', async () => withEnv({ GBRAIN_HOME: home }, async () => {+ for (const engine of engines) {+ const f = await fixture(engine, { 'notes/Foo Bar.md': note('Foo Bar', 'Apples and orchards.') });+ await performManagedSync(engine, { sourceId: f.id, noPull: true });+ const id = await pageId(engine, 'notes/foo-bar', f.id);+ git(f.root, 'mv', 'notes/Foo Bar.md', 'notes/foo-bar.md');+ commit(f.root, 'respell');+ const next = await performManagedSync(engine, { sourceId: f.id, noPull: true });+ expect(next).toMatchObject({ status: 'synced', renamed: 1, deleted: 0 });+ expect(await pageId(engine, 'notes/foo-bar', f.id)).toBe(id);+ expect((await engine.getPage('notes/foo-bar', { sourceId: f.id }))?.source_path).toBe('notes/foo-bar.md');+ expect((await performManagedSync(engine, { sourceId: f.id, noPull: true, full: true })).slugCollisions).toBeUndefined();+ // A case-only respelling whose old file this sync removes is the same page, not an ambiguous alias.+ git(f.root, 'mv', 'notes/foo-bar.md', 'notes/Foo-Bar.md');+ commit(f.root, 'case-only respelling');+ expect(await performManagedSync(engine, { sourceId: f.id, noPull: true })).toMatchObject({ status: 'synced', renamed: 1, deleted: 0 });+ expect(await pageId(engine, 'notes/foo-bar', f.id)).toBe(id);+ expect((await engine.getPage('notes/foo-bar', { sourceId: f.id }))?.source_path).toBe('notes/Foo-Bar.md');+ }+}), 180_000);++test('two new files whose paths differ only by case are refused rather than guessed', async () => withEnv({ GBRAIN_HOME: home }, async () => {+ for (const engine of engines) {+ const f = await fixture(engine, { 'notes/Case.md': note('Upper', 'Upper case spelling.'), 'notes/case.md': note('Lower', 'Lower case spelling.') });+ await expect(performManagedSync(engine, { sourceId: f.id, noPull: true })).rejects.toMatchObject({ code: 'page_identity_changed' });+ expect(await engine.getPage('notes/case', { sourceId: f.id })).toBeNull();+ }+}), 180_000);++test('a renamed page keeps its id, inbound links and old slug; a moved file keeps its old slug', async () => withEnv({ GBRAIN_HOME: home }, async () => {+ for (const engine of engines) {+ const f = await fixture(engine, {+ 'people/erin-example.md': person('Erin Example'),+ 'people/carol-example.md': person('Carol Example'),+ 'notes/b.md': note('Note B', 'Saw [[people/erin-example]] today.'),+ 'inbox/standup.md': note('Weekly standup', 'Standup notes. [[people/carol-example]] presented.', 'id: lc-standup-0001\n'),+ });+ await performManagedSync(engine, { sourceId: f.id, noPull: true });+ const erin = await pageId(engine, 'people/erin-example', f.id);+ const standup = await pageId(engine, 'inbox/standup', f.id);+ expect(await backlinkSources(engine, 'people/erin-example', f.id)).toEqual(['notes/b']);+ mkdirSync(join(f.root, 'meetings'));+ git(f.root, 'mv', 'people/erin-example.md', 'people/erin-example-2.md');+ git(f.root, 'mv', 'inbox/standup.md', 'meetings/standup.md');+ commit(f.root, 'move and rename');+ const moved = await performManagedSync(engine, { sourceId: f.id, noPull: true });+ expect(moved).toMatchObject({ status: 'synced', renamed: 2, added: 0, deleted: 0 });+ expect(await pageId(engine, 'people/erin-example-2', f.id)).toBe(erin);+ expect(await pageId(engine, 'meetings/standup', f.id)).toBe(standup);+ expect(await engine.getPage('people/erin-example', { sourceId: f.id })).toBeNull();+ expect(await engine.resolveSlugWithAlias('people/erin-example', f.id)).toBe('people/erin-example-2');+ expect(await engine.resolveSlugWithAlias('inbox/standup', f.id)).toBe('meetings/standup');+ expect(await backlinkSources(engine, 'people/erin-example-2', f.id)).toEqual(['notes/b']);+ expect((await engine.getLinks('meetings/standup', { sourceId: f.id })).map(link => link.to_slug)).toEqual(['people/carol-example']);+ // The move never rewrites the user's files.+ expect(git(f.root, 'status', '--porcelain', '--', 'people', 'meetings', 'notes')).toBe('');+ // Re-extracting the unchanged link text still reaches the renamed page through its alias.+ write(f.root, 'notes/b.md', note('Note B', 'Saw [[people/erin-example]] again.'));+ commit(f.root, 'edit linking note');+ await performManagedSync(engine, { sourceId: f.id, noPull: true });+ expect(await backlinkSources(engine, 'people/erin-example-2', f.id)).toEqual(['notes/b']);+ expect((await performManagedSync(engine, { sourceId: f.id, noPull: true, full: true })).status).toMatch(/synced|up_to_date/);+ expect(await pageId(engine, 'people/erin-example-2', f.id)).toBe(erin);+ }+}), 180_000);++test('a rename that also edits the file moves the page and applies the new text', async () => withEnv({ GBRAIN_HOME: home }, async () => {+ for (const engine of engines) {+ const f = await fixture(engine, { 'people/dana-example.md': person('Dana Example') + 'First version with plenty of stable text for rename detection.\n' });+ await performManagedSync(engine, { sourceId: f.id, noPull: true });+ const id = await pageId(engine, 'people/dana-example', f.id);+ git(f.root, 'mv', 'people/dana-example.md', 'people/dana-example-2.md');+ write(f.root, 'people/dana-example-2.md', person('Dana Example') + 'First version with plenty of stable text for rename detection. Plus an edit.\n');+ commit(f.root, 'rename with edit');+ expect(await performManagedSync(engine, { sourceId: f.id, noPull: true })).toMatchObject({ status: 'synced', renamed: 1 });+ const page = await engine.getPage('people/dana-example-2', { sourceId: f.id });+ expect(page?.id).toBe(id);+ expect(page?.compiled_truth).toContain('Plus an edit');+ expect(readFileSync(join(f.root, 'people/dana-example-2.md'), 'utf8')).toContain('Plus an edit');+ }+}), 180_000);++test('managed sync derives links for its pages, including forward references, and stamps them fresh', async () => withEnv({ GBRAIN_HOME: home }, async () => {+ for (const engine of engines) {+ const f = await fixture(engine, {+ 'notes/a.md': note('Note A', 'Planning with [[people/zed-example]] and [[people/alice-example]].'),+ 'people/alice-example.md': person('Alice Example'),+ 'people/zed-example.md': person('Zed Example'),+ });+ const first = await performManagedSync(engine, { sourceId: f.id, noPull: true });+ expect(first.links).toMatchObject({ created: 2, remaining: 0 });+ expect((await engine.getLinks('notes/a', { sourceId: f.id })).map(link => link.to_slug).sort()).toEqual(['people/alice-example', 'people/zed-example']);+ expect(await engine.countStalePagesForExtraction({ sourceId: f.id, versionTs: LINK_EXTRACTOR_VERSION_TS })).toBe(0);+ // A removed link disappears on the next sync (replace semantics).+ write(f.root, 'notes/a.md', note('Note A', 'Planning with [[people/alice-example]].'));+ commit(f.root, 'remove link');+ expect((await performManagedSync(engine, { sourceId: f.id, noPull: true })).links).toMatchObject({ removed: 1 });+ expect((await engine.getLinks('notes/a', { sourceId: f.id })).map(link => link.to_slug)).toEqual(['people/alice-example']);+ }+}), 180_000);++test('a sweep that stamps pages mid-sync cannot strand the links of pages this sync imported', async () => withEnv({ GBRAIN_HOME: home }, async () => {+ for (const engine of engines) {+ const f = await fixture(engine, {+ 'notes/a.md': note('Note A', 'Met [[people/zed-example]].'),+ 'people/zed-example.md': person('Zed Example'),+ });+ // Like a serve's idle sweep: stamp whatever exists after the first page lands, before its link target is imported.+ const stampEarly = async () => {+ const pages = await engine.executeRaw<{ slug: string }>('SELECT slug FROM pages WHERE source_id=$1', [f.id]);+ await engine.markPagesExtractedBatch(pages.map(page => ({ slug: page.slug, source_id: f.id })), new Date(Date.now() + 60_000).toISOString());+ };+ let stamped: Promise<void> | undefined;+ const result = await performManagedSync(engine, { sourceId: f.id, noPull: true,+ onProgress: progress => { if (progress.bankedFiles === 1) stamped = stampEarly(); } });+ await stamped;+ expect(result.status).toBe('first_sync');+ expect((await engine.getLinks('notes/a', { sourceId: f.id })).map(link => link.to_slug)).toEqual(['people/zed-example']);+ }+}), 180_000);++test('extract --stale on a managed brain derives links after a --no-extract sync without touching guarded rows', async () => withEnv({ GBRAIN_HOME: home }, async () => {+ for (const engine of engines) {+ const f = await fixture(engine, {+ 'notes/a.md': note('Note A', 'Met [[people/alice-example]].'),+ 'people/alice-example.md': person('Alice Example') + '\n## Timeline\n- **2024-03-01** | Joined Acme Example\n',+ });+ const synced = await performManagedSync(engine, { sourceId: f.id, noPull: true, noExtract: true });+ expect(synced.links).toBeUndefined();+ expect(await engine.getLinks('notes/a', { sourceId: f.id })).toEqual([]);+ expect(await runManagedStaleExtraction(engine, { sourceId: f.id, dryRun: true })).toMatchObject({ pages: 0, remaining: 2 });+ const printed: string[] = [];+ const stdoutWrite = process.stdout.write;+ process.stdout.write = ((chunk: string | Uint8Array) => { printed.push(String(chunk)); return true; }) as typeof process.stdout.write;+ try { await runExtract(engine, ['--stale', '--source-id', f.id, '--json']); } finally { process.stdout.write = stdoutWrite; }+ const report = JSON.parse(printed.at(-1)!);+ expect(report).toMatchObject({ action: 'extract_stale_done', pages_processed: 2, links_created: 1, stale_remaining: 0 });+ expect(report.skipped_changed).toBeUndefined();+ expect((await engine.getLinks('notes/a', { sourceId: f.id })).map(link => link.to_slug)).toEqual(['people/alice-example']);+ expect((await engine.getTimeline('people/alice-example', { sourceId: f.id })).map(entry => entry.summary)).toEqual(['Joined Acme Example']);+ }+}), 180_000);++test('a managed brain prunes timeline rows an earlier page version left behind, and timeline_history does not resurrect them', async () => withEnv({ GBRAIN_HOME: home }, async () => {+ const { withCoordinatedWrite } = await import('../src/core/persistence/context.ts');+ const { timelineHistoryCheck } = await import('../src/commands/doctor/checks/timeline-history.ts');+ for (const engine of engines) {+ const f = await fixture(engine, {+ 'people/bea-example.md': person('Bea Example') + '\n## Timeline\n- **2024-03-01** | Joined Acme Example\n- **2024-05-01** | Left Acme Example\n',+ });+ await performManagedSync(engine, { sourceId: f.id, noPull: true });+ const [left] = await engine.executeRaw<{ date: string; source: string; summary: string }>(`SELECT to_char(t.date,'YYYY-MM-DD') AS date,t.source,t.summary+ FROM timeline_entries t JOIN pages p ON p.id=t.page_id WHERE p.source_id=$1 AND t.summary='Left Acme Example'`, [f.id]);+ expect(left).toBeDefined();+ write(f.root, 'people/bea-example.md', person('Bea Example') + '\n## Timeline\n- **2024-03-01** | Joined Acme Example\n');+ commit(f.root, 'drop a dated bullet');+ await performManagedSync(engine, { sourceId: f.id, noPull: true });+ const summaries = async () => (await engine.getTimeline('people/bea-example', { sourceId: f.id })).map(entry => entry.summary).sort();+ expect(await summaries()).toEqual(['Joined Acme Example']);+ // A row left over from before timeline reconciliation: an earlier version produced it, the current text does not.+ await engine.transaction(tx => withCoordinatedWrite(tx, [f.id], () => tx.addTimelineEntry('people/bea-example',+ { ...left, detail: '' }, { sourceId: f.id })));+ expect(await summaries()).toEqual(['Joined Acme Example', 'Left Acme Example']);+ expect((await timelineHistoryCheck(engine, f.id)).details).toMatchObject({ materializable_rows: 0 });+ const printed: string[] = [];+ const stdoutWrite = process.stdout.write;+ process.stdout.write = ((chunk: string | Uint8Array) => { printed.push(String(chunk)); return true; }) as typeof process.stdout.write;+ try {+ await runExtract(engine, ['timeline', '--prune-orphans', '--dry-run', '--source-id', f.id, '--json']);+ await runExtract(engine, ['timeline', '--prune-orphans', '--source-id', f.id, '--json']);+ } finally { process.stdout.write = stdoutWrite; }+ expect(JSON.parse(printed.at(-2)!)).toMatchObject({ action: 'timeline_prune_orphans', dry_run: true, orphans: 1 });+ expect(JSON.parse(printed.at(-1)!)).toMatchObject({ action: 'timeline_prune_orphans', dry_run: false, removed: 1 });+ expect(await summaries()).toEqual(['Joined Acme Example']);+ }+}), 180_000);++test('a managed rename carries fence facts to the new slug once, keeping their ids', async () => withEnv({ GBRAIN_HOME: home }, async () => {+ const fenced = (extra = '') => person('Gia Example') + 'Plenty of stable text so Git sees the move as a rename of this person page.\n' + extra + `+## Facts++<!--- gbrain:facts:begin -->+| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |+|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|+| 1 | Lives in Lisbon | fact | 1.0 | world | medium | 2024-01-01 | | note | |+| 2 | Prefers tea | preference | 0.9 | world | low | 2024-02-01 | | note | |+<!--- gbrain:facts:end -->+`;+ const facts = (engine: BrainEngine, sourceId: string, slug: string) => engine.executeRaw<{ id: number; row_num: number | null; fact: string; expired: boolean }>(+ `SELECT id, row_num, fact, expired_at IS NOT NULL AS expired FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 ORDER BY row_num`, [sourceId, slug]);+ for (const engine of engines) {+ const f = await fixture(engine, { 'people/gia-example.md': fenced() });+ await performManagedSync(engine, { sourceId: f.id, noPull: true });+ const before = await facts(engine, f.id, 'people/gia-example');+ expect(before.map(r => [r.row_num, r.fact, r.expired])).toEqual([[1, 'Lives in Lisbon', false], [2, 'Prefers tea', false]]);+ git(f.root, 'mv', 'people/gia-example.md', 'people/gia-example-2.md');+ write(f.root, 'people/gia-example-2.md', fenced('An edit that rides along with the rename.\n'));+ commit(f.root, 'rename with facts');+ expect(await performManagedSync(engine, { sourceId: f.id, noPull: true })).toMatchObject({ status: 'synced', renamed: 1 });+ expect(await facts(engine, f.id, 'people/gia-example')).toEqual([]);+ const after = await facts(engine, f.id, 'people/gia-example-2');+ expect(after.map(r => [r.id, r.row_num, r.fact, r.expired])).toEqual(before.map(r => [r.id, r.row_num, r.fact, false]));+ const [alias] = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM slug_aliases WHERE source_id=$1 AND alias_slug='people/gia-example'`, [f.id]);+ expect(alias.n).toBe(1);+ }+}), 180_000);diff --git a/test/persistence-sync-stdio-owner.serial.test.ts b/test/persistence-sync-stdio-owner.serial.test.tsindex 47fc826310..af8a804e8b 100644--- a/test/persistence-sync-stdio-owner.serial.test.ts+++ b/test/persistence-sync-stdio-owner.serial.test.ts@@ -82,6 +82,28 @@ test('actual CLI sync and page reads delegate to a real non-serve stdio owner beexpect(inspectLockHolder(databasePath).pid).toBe(owner!.pid);},90000);+test('extract --stale delegates to the resident owner, and the delegated sync already stamped its pages',async()=>{+ const preview=await cli(['extract','--stale','--source-id','workspace','--dry-run','--json']);+ expect({code:preview.code,err:preview.err}).toMatchObject({code:0});+ expect(JSON.parse(preview.out)).toMatchObject({action:'extract_stale_dry_run',stale_pages:0});+ const extracted=await cli(['extract','--stale','--json']);+ expect({code:extracted.code,err:extracted.err}).toMatchObject({code:0});+ const report=JSON.parse(extracted.out);+ expect(report).toMatchObject({action:'extract_stale_done',stale_remaining:0});+ expect(report.skipped_changed).toBeUndefined();+ expect(extracted.err).not.toContain('writer_coordinator_required');+ expect(inspectLockHolder(databasePath).pid).toBe(owner!.pid);+},90000);++test('remote stdio credentials cannot request trusted stale extraction',async()=>{+ const socket=persistenceSocketPathForConfig(config)!,cap=await requestPersistenceCapabilities(socket);+ expect(cap.administration).toContain('writer_extract_stale');+ const registration=JSON.parse(readFileSync(join(home,'.gbrain','persistence',`${cap.brain_id}.stdio.json`),'utf8'));+ await expect(requestPersistenceAdministration(socket,{version:1,kind:'administration',brain_id:cap.brain_id,+ operation:'writer_extract_stale',params:{source_id:'workspace'},registration:{...registration,lane:'cli'}}))+ .rejects.toMatchObject({code:'permission_denied'});+});+test('resident-owner failure JSON retains safe scoped diagnostics and the frozen receipt without a local ledger',async()=>{const path=join(root,'a.md');const pinned=execFileSync('git',['-C',root,'show','HEAD:a.md'],{encoding:'utf8'});diff --git a/test/phantom-redirect-merge.test.ts b/test/phantom-redirect-merge.test.tsnew file mode 100644index 0000000000..2f1ce88aaf--- /dev/null+++ b/test/phantom-redirect-merge.test.ts@@ -0,0 +1,162 @@+/**+ * B-12: a phantom-redirect merge is lossless.+ *+ * - Backlinks to the phantom move to the canonical page, and the phantom+ * slug is recorded as an alias of the canonical.+ * - The canonical fence lands in the page's recorded file (the shared+ * write-target resolver), not a slug-named twin.+ * - Expired and superseded history moves with the active rows instead of+ * being hard-deleted, `superseded by #N` references follow the renumber,+ * and the moved rows keep their ids through the canonical's next+ * reconcile (DB row numbers equal the numbers written to disk).+ * - A canonical chosen by fuzzy match must agree with the prefix+ * candidates.+ *+ * Hermetic PGLite + tempdir brain.+ */++import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';+import * as fs from 'node:fs';+import * as path from 'node:path';+import * as os from 'node:os';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { withEnv } from './helpers/with-env.ts';+import { runExtractFacts } from '../src/core/cycle/extract-facts.ts';+import { tryRedirectPhantom } from '../src/core/cycle/phantom-redirect.ts';+import { parseFactsFence } from '../src/core/facts-fence.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+});++afterAll(async () => {+ await engine.disconnect();+});++beforeEach(async () => {+ await resetPgliteState(engine);+});++const FENCE = (rows: string): string => `# alice++## 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, type = 'person', title = slug): Promise<void> {+ await engine.putPage(slug, { title, type: type as never, compiled_truth: body, frontmatter: {}, timeline: '' });+}++function withBrain<T>(fn: (brainDir: string) => Promise<T>): Promise<T> {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'phantom-merge-'));+ const brainDir = path.join(root, 'brain');+ fs.mkdirSync(brainDir, { recursive: true });+ fs.mkdirSync(path.join(root, 'audit'), { recursive: true });+ return withEnv({ GBRAIN_AUDIT_DIR: path.join(root, 'audit') }, async () => {+ try {+ return await fn(brainDir);+ } finally {+ fs.rmSync(root, { recursive: true, force: true });+ }+ });+}++function writeMd(brainDir: string, rel: string, body: string): void {+ fs.mkdirSync(path.dirname(path.join(brainDir, rel)), { recursive: true });+ fs.writeFileSync(path.join(brainDir, rel), body, 'utf-8');+}++async function redirect(brainDir: string) {+ const phantom = await engine.getPage('alice', { sourceId: 'default' });+ return tryRedirectPhantom(engine, phantom!, 'default', brainDir, false);+}++describe('phantom-redirect merge (B-12)', () => {+ test('backlinks move to the canonical and the phantom slug becomes an alias', async () => {+ await withBrain(async brainDir => {+ await putPage('people/alice-example', '# alice-example\n');+ writeMd(brainDir, 'people/alice-example.md', '# alice-example\n');+ await putPage('alice', FENCE('| 1 | Founded Acme | fact | 1.0 | world | high | 2017-01-01 | | chat | |'));+ writeMd(brainDir, 'alice.md', FENCE('| 1 | Founded Acme | fact | 1.0 | world | high | 2017-01-01 | | chat | |'));+ await putPage('meetings/2026-01-01-sync', 'Met alice.', 'meeting');+ await engine.addLink('meetings/2026-01-01-sync', 'alice', 'met', 'mentions');++ expect((await redirect(brainDir)).outcome).toBe('redirected');+ const backlinks = await engine.getBacklinks('people/alice-example');+ expect(backlinks.map(l => l.from_slug)).toEqual(['meetings/2026-01-01-sync']);+ expect(await engine.resolveSlugWithAlias('alice', 'default')).toBe('people/alice-example');+ });+ });++ test('the fence lands in the canonical page\'s recorded file', async () => {+ await withBrain(async brainDir => {+ await engine.executeRaw(`UPDATE sources SET local_path = $1 WHERE id = 'default'`, [brainDir]);+ await putPage('people/alice-example', '# Alice Example\n');+ await engine.executeRaw(`UPDATE pages SET source_path = 'People/Alice Example.md' WHERE slug = 'people/alice-example'`);+ writeMd(brainDir, 'People/Alice Example.md', '# Alice Example\n');+ await putPage('alice', FENCE('| 1 | Founded Acme | fact | 1.0 | world | high | 2017-01-01 | | chat | |'));+ writeMd(brainDir, 'alice.md', FENCE('| 1 | Founded Acme | fact | 1.0 | world | high | 2017-01-01 | | chat | |'));++ expect((await redirect(brainDir)).outcome).toBe('redirected');+ expect(fs.readFileSync(path.join(brainDir, 'People/Alice Example.md'), 'utf-8')).toContain('Founded Acme');+ expect(fs.existsSync(path.join(brainDir, 'people/alice-example.md'))).toBe(false);+ });+ });++ test('history moves with renumbered supersession links and ids survive the canonical reconcile', async () => {+ await withBrain(async brainDir => {+ const canonicalBody = FENCE('| 1 | Lives in Paris | fact | 1.0 | world | medium | 2015-01-01 | | chat | |');+ await putPage('people/alice-example', canonicalBody);+ writeMd(brainDir, 'people/alice-example.md', canonicalBody);+ const phantomBody = FENCE([+ '| 1 | ~~Works at Acme~~ | fact | 1.0 | world | medium | 2017-01-01 | | chat | superseded by #2 |',+ '| 2 | Works at Beta | fact | 1.0 | world | medium | 2020-01-01 | | chat | |',+ ].join('\n'));+ await putPage('alice', phantomBody);+ writeMd(brainDir, 'alice.md', phantomBody);+ await runExtractFacts(engine, { slugs: ['alice', 'people/alice-example'] });+ const phantomIds = (await engine.executeRaw<{ id: number }>(+ `SELECT id FROM facts WHERE source_markdown_slug = 'alice' ORDER BY row_num`)).map(r => r.id);+ expect(phantomIds).toHaveLength(2);++ expect((await redirect(brainDir)).outcome).toBe('redirected');+ const fence = parseFactsFence(fs.readFileSync(path.join(brainDir, 'people/alice-example.md'), 'utf-8')).facts;+ expect(fence.map(f => [f.rowNum, f.claim, f.supersededBy ?? null])).toEqual([+ [1, 'Lives in Paris', null], [2, 'Works at Acme', 3], [3, 'Works at Beta', null],+ ]);++ // The canonical's body is refreshed from disk; its reconcile must keep the moved rows.+ await runExtractFacts(engine, { slugs: ['people/alice-example'] });+ const rows = await engine.executeRaw<{ id: number; row_num: number; expired: boolean; superseded_by: number | null }>(+ `SELECT id, row_num, expired_at IS NOT NULL AS expired, superseded_by FROM facts+ WHERE source_markdown_slug = 'people/alice-example' AND row_num IS NOT NULL ORDER BY row_num`);+ expect(rows.slice(1).map(r => r.id)).toEqual(phantomIds);+ expect(rows[1]).toMatchObject({ expired: true, superseded_by: phantomIds[1] });+ expect(await engine.executeRaw(`SELECT id FROM facts WHERE source_markdown_slug = 'alice'`)).toEqual([]);+ });+ });++ test('a fuzzy hit tied with the phantom itself never becomes the canonical', async () => {+ await withBrain(async brainDir => {+ await putPage('people/alice-example', '# alice-example\n');+ writeMd(brainDir, 'people/alice-example.md', '# alice-example\n');+ // Title "alice" scores 1.0, tied with the phantom slug, and sorts first.+ await putPage('agents/alice', '# alice\n', 'concept', 'alice');+ await putPage('alice', FENCE('| 1 | Founded Acme | fact | 1.0 | world | high | 2017-01-01 | | chat | |'));+ writeMd(brainDir, 'alice.md', FENCE('| 1 | Founded Acme | fact | 1.0 | world | high | 2017-01-01 | | chat | |'));+ const result = await redirect(brainDir);+ expect(result).toEqual({ outcome: 'redirected', canonical: 'people/alice-example' });+ expect(fs.existsSync(path.join(brainDir, 'agents/alice.md'))).toBe(false);+ });+ });+});diff --git a/test/propose-takes.test.ts b/test/propose-takes.test.tsindex d83573c22f..5ddcdef8ff 100644--- a/test/propose-takes.test.ts+++ b/test/propose-takes.test.ts@@ -626,7 +626,9 @@ New prose appended here.`;const result = await runPhaseProposeTakes(buildCtx(engine), {extractor,- meter: new BudgetMeter({ budgetUsd: 0.000001, phase: 'propose_takes' }),+ // The OpenRouter alias is not in the canonical pricing table; the+ // opt-in bypass keeps this test about model-id preservation (C-16).+ meter: new BudgetMeter({ budgetUsd: 0.000001, phase: 'propose_takes', allowUnpriced: true }),});expect(result.status).toBe('ok');diff --git a/test/reindex-preserve-tags.test.ts b/test/reindex-preserve-tags.test.tsindex 7621958596..596721f773 100644--- a/test/reindex-preserve-tags.test.ts+++ b/test/reindex-preserve-tags.test.ts@@ -6,9 +6,9 @@// re-import (notably `gbrain reindex --markdown`, which re-imports with// forceRechunk) deleted all enrichment / dream / signal-detector tags.//-// Fix: ADD-ONLY reconciliation. Re-import adds current frontmatter tags and-// never deletes. Accepted trade-off: removing a frontmatter tag no longer-// removes it from the DB (additive metadata; far better than wiping enrichment).+// Fix: re-import never deletes enrichment tags. Since A14 tags carry+// provenance (tags.tag_source), so removing a frontmatter tag removes only+// that frontmatter-owned row (test/import-frontmatter-tag-removal.test.ts).import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { resetPgliteState } from './helpers/reset-pglite.ts';@@ -52,7 +52,7 @@ describe('#1621 add-only tag reconciliation', () => {expect(tags.sort()).toEqual(['founder', 'yc']);});- test('add-only: removing a frontmatter tag does NOT remove it (accepted trade-off)', async () => {+ test('removing a frontmatter tag removes it; enrichment tags survive', async () => {await importFromContent(engine, 'people/xavi', page(['founder', 'yc']), { forceRechunk: true, noEmbed: true });await engine.addTag('people/xavi', 'enrichment-tag');@@ -60,8 +60,8 @@ describe('#1621 add-only tag reconciliation', () => {await importFromContent(engine, 'people/xavi', page(['founder']), { forceRechunk: true, noEmbed: true });const tags = await engine.getTags('people/xavi');- // "yc" lingers (add-only); enrichment-tag preserved; founder present.- expect(tags.sort()).toEqual(['enrichment-tag', 'founder', 'yc']);+ // "yc" left the frontmatter; enrichment-tag preserved; founder present.+ expect(tags.sort()).toEqual(['enrichment-tag', 'founder']);});test('adding a new frontmatter tag on re-import works (idempotent add)', async () => {diff --git a/test/relational-intent-paraphrase.test.ts b/test/relational-intent-paraphrase.test.tsnew file mode 100644index 0000000000..904ef42187--- /dev/null+++ b/test/relational-intent-paraphrase.test.ts@@ -0,0 +1,100 @@+/**+ * Relational intent recognition beyond the parser's own verbs. The template+ * phrasings ("who invested in X") fired the relational arm, but ordinary+ * rewordings ("X's investors", "people who funded X", "who backs X", "who is+ * the founder of X") parsed as non-relational, so the arm never ran.+ *+ * These are DEVELOPMENT paraphrases written for this test. The frozen+ * held-out paraphrase split in gbrain-evals is deliberately not mirrored.+ */+import { describe, test, expect } from 'bun:test';+import { parseRelationalQuery, KNOWN_LINK_TYPES, type RelationalKind, type RelationDirection } from '../src/core/search/relational-intent.ts';++type Expect = { kind: RelationalKind; seeds: string[]; linkTypes: string[] | null; direction: RelationDirection };+const INVEST = ['invested_in', 'led_round'];++const POSITIVES: Array<[string, Expect]> = [+ // investors of a company (incoming)+ ["widget-co's investors", { kind: 'who_rel', seeds: ['widget-co'], linkTypes: INVEST, direction: 'in' }],+ ['Who are Widget Co’s backers?', { kind: 'who_rel', seeds: ['Widget Co'], linkTypes: INVEST, direction: 'in' }],+ ['investors in acme-co', { kind: 'who_rel', seeds: ['acme-co'], linkTypes: INVEST, direction: 'in' }],+ ['list the funders of novapay', { kind: 'who_rel', seeds: ['novapay'], linkTypes: INVEST, direction: 'in' }],+ ['people who funded helio', { kind: 'who_rel', seeds: ['helio'], linkTypes: INVEST, direction: 'in' }],+ ['who backs quanta?', { kind: 'who_rel', seeds: ['quanta'], linkTypes: INVEST, direction: 'in' }],+ ['who has invested in mindbridge', { kind: 'who_rel', seeds: ['mindbridge'], linkTypes: INVEST, direction: 'in' }],+ ['which funds put money into widget-co', { kind: 'who_rel', seeds: ['widget-co'], linkTypes: INVEST, direction: 'in' }],+ ['who led the seed round for acme-co', { kind: 'who_rel', seeds: ['acme-co'], linkTypes: INVEST, direction: 'in' }],+ ['what firms have financed novapay?', { kind: 'who_rel', seeds: ['novapay'], linkTypes: INVEST, direction: 'in' }],+ // founders (incoming)+ ['who is the founder of mindbridge', { kind: 'who_rel', seeds: ['mindbridge'], linkTypes: ['founded'], direction: 'in' }],+ ["helio's co-founders", { kind: 'who_rel', seeds: ['helio'], linkTypes: ['founded'], direction: 'in' }],+ ['founders of quanta', { kind: 'who_rel', seeds: ['quanta'], linkTypes: ['founded'], direction: 'in' }],+ ['who started acme-co?', { kind: 'who_rel', seeds: ['acme-co'], linkTypes: ['founded'], direction: 'in' }],+ ['which people co-founded widget-co', { kind: 'who_rel', seeds: ['widget-co'], linkTypes: ['founded'], direction: 'in' }],+ // employees (incoming)+ ["novapay's employees", { kind: 'who_rel', seeds: ['novapay'], linkTypes: ['works_at'], direction: 'in' }],+ ['who is employed by helio', { kind: 'who_rel', seeds: ['helio'], linkTypes: ['works_at'], direction: 'in' }],+ ['staff at quanta', { kind: 'who_rel', seeds: ['quanta'], linkTypes: ['works_at'], direction: 'in' }],+ ['people who work for acme-co', { kind: 'who_rel', seeds: ['acme-co'], linkTypes: ['works_at'], direction: 'in' }],+ ["who's on the team at widget-co", { kind: 'who_rel', seeds: ['widget-co'], linkTypes: ['works_at'], direction: 'in' }],+ // advisors (incoming)+ ["mindbridge's advisors", { kind: 'who_rel', seeds: ['mindbridge'], linkTypes: ['advises'], direction: 'in' }],+ ['who are the advisers to novapay?', { kind: 'who_rel', seeds: ['novapay'], linkTypes: ['advises'], direction: 'in' }],+ ['people who advise helio', { kind: 'who_rel', seeds: ['helio'], linkTypes: ['advises'], direction: 'in' }],+ ['who sits on the advisory board of quanta', { kind: 'who_rel', seeds: ['quanta'], linkTypes: ['advises'], direction: 'in' }],+ // outgoing+ ['which companies has alice-example backed?', { kind: 'who_rel', seeds: ['alice-example'], linkTypes: INVEST, direction: 'out' }],+ ["fund-a's portfolio companies", { kind: 'who_rel', seeds: ['fund-a'], linkTypes: INVEST, direction: 'out' }],+ ['who does bob-example work for', { kind: 'who_rel', seeds: ['bob-example'], linkTypes: ['works_at'], direction: 'out' }],+ ["carol-example's employer", { kind: 'who_rel', seeds: ['carol-example'], linkTypes: ['works_at'], direction: 'out' }],+ ['what companies did dave-example found?', { kind: 'who_rel', seeds: ['dave-example'], linkTypes: ['founded'], direction: 'out' }],+ ['which startups does erin-example advise', { kind: 'who_rel', seeds: ['erin-example'], linkTypes: ['advises'], direction: 'out' }],+ // connects+ ['relationship between fund-a and fund-b', { kind: 'connects', seeds: ['fund-a', 'fund-b'], linkTypes: null, direction: 'both' }],+ ['what is the connection between alice-example and widget-co?', { kind: 'connects', seeds: ['alice-example', 'widget-co'], linkTypes: null, direction: 'both' }],+ ['how is novapay connected to helio', { kind: 'connects', seeds: ['novapay', 'helio'], linkTypes: null, direction: 'both' }],+ ['what do acme-co and quanta have in common?', { kind: 'connects', seeds: ['acme-co', 'quanta'], linkTypes: null, direction: 'both' }],+ ['how do bob-example and carol-example know each other', { kind: 'connects', seeds: ['bob-example', 'carol-example'], linkTypes: null, direction: 'both' }],+ // intro+ ['who can introduce me to alice-example?', { kind: 'intro', seeds: ['alice-example'], linkTypes: null, direction: 'both' }],+ ['who could connect us with bob-example', { kind: 'intro', seeds: ['bob-example'], linkTypes: null, direction: 'both' }],+ ['who knows carol-example?', { kind: 'intro', seeds: ['carol-example'], linkTypes: null, direction: 'both' }],+];++const NEGATIVES = [+ 'what did I eat for dinner last tuesday',+ 'who did I go to the concert with?',+ 'how do I invest in index funds',+ 'who knows how to deploy the staging cluster',+ 'people who work remotely are more productive',+ 'what are the founders of stoicism known for',+ 'employees should submit expenses by friday',+ 'what is the idea of debating in public forums',+ 'how are embeddings and keywords combined in hybrid search',+ 'staff meeting notes from monday',+ 'advisors often underestimate the time commitment',+ 'what should I name my new puppy',+ 'who is the best person to ask about taxes',+ 'my portfolio allocation for next year',+];++describe('relational intent — development paraphrases', () => {+ for (const [query, want] of POSITIVES) {+ test(query, () => {+ const got = parseRelationalQuery(query);+ expect(got).not.toBeNull();+ expect({ kind: got!.kind, seeds: got!.seeds, linkTypes: got!.linkTypes, direction: got!.direction }).toEqual(want);+ for (const lt of got!.linkTypes ?? []) expect(KNOWN_LINK_TYPES.has(lt)).toBe(true);+ });+ }+});++// Syntactically relational phrasings with a non-entity seed ("who started the+// fire", "the relationship between sleep and memory") still parse; the arm+// only fires when relational-recall resolves the seed to a page.+describe('relational intent — precision on non-relational queries', () => {+ test('generic seeds and non-relational phrasing stay null', () => {+ const fired = NEGATIVES.filter(q => parseRelationalQuery(q) !== null);+ expect(fired).toEqual([]);+ });+});diff --git a/test/rename-slug-alias.test.ts b/test/rename-slug-alias.test.tsindex fe73a1441e..d829d8de4c 100644--- a/test/rename-slug-alias.test.ts+++ b/test/rename-slug-alias.test.ts@@ -63,6 +63,32 @@ describe('updateSlug records an alias', () => {});});+describe('updateSlug carries slug-keyed bindings (#5431)', () => {+ test('facts and search aliases follow the renamed page; a purged page\'s leftovers yield', async () => {+ await importFromContent(engine, 'people/dana-example', `---\ntype: person\ntitle: Dana Example\naliases: [Dana E]\n---\n\nDana.\n`, { noEmbed: true });+ await engine.executeRaw(`INSERT INTO facts (source_id, entity_slug, fact, source, row_num, source_markdown_slug) VALUES+ ('default', 'people/dana-example', 'Dana founded a company.', 'test', 1, 'people/dana-example'),+ ('default', 'people/dana-example', 'Dana mentioned elsewhere.', 'test', NULL, 'notes/other-example'),+ ('default', 'people/erin-example', 'Stale fence row of a purged page.', 'test', 1, 'people/dana-example-2')`);+ await engine.executeRaw(`INSERT INTO page_aliases (source_id, alias_norm, slug) VALUES ('default', 'dana e', 'people/dana-example-2')+ ON CONFLICT DO NOTHING`);+ const before = await engine.executeRaw<{ alias_norm: string }>(`SELECT alias_norm FROM page_aliases WHERE source_id = 'default' AND slug = 'people/dana-example'`);+ expect(before.map(r => r.alias_norm)).toContain('dana e');++ expect(await engine.updateSlug('people/dana-example', 'people/dana-example-2')).toBe(1);++ const facts = await engine.executeRaw<{ entity_slug: string; source_markdown_slug: string; fact: string }>(+ `SELECT entity_slug, source_markdown_slug, fact FROM facts WHERE source_id = 'default' ORDER BY fact`);+ expect(facts).toEqual([+ { entity_slug: 'people/dana-example-2', source_markdown_slug: 'people/dana-example-2', fact: 'Dana founded a company.' },+ { entity_slug: 'people/dana-example-2', source_markdown_slug: 'notes/other-example', fact: 'Dana mentioned elsewhere.' },+ ]);+ const pageAliases = await engine.executeRaw<{ slug: string }>(+ `SELECT DISTINCT slug FROM page_aliases WHERE source_id = 'default' AND slug LIKE 'people/dana-example%'`);+ expect(pageAliases).toEqual([{ slug: 'people/dana-example-2' }]);+ });+});+describe('sync keeps inbound edges across a rename', () => {test('editing the referrer after a rename keeps its edge to the renamed page', async () => {const repo = mkdtempSync(join(tmpdir(), 'rename-alias-'));diff --git a/test/schema-bootstrap-coverage.test.ts b/test/schema-bootstrap-coverage.test.tsindex 667463456e..5fb021882d 100644--- a/test/schema-bootstrap-coverage.test.ts+++ b/test/schema-bootstrap-coverage.test.ts@@ -985,6 +985,11 @@ const COLUMN_EXEMPTIONS = new Set<string>([// Postgres-blob gate test below and the e2e pre-v143 convergence case.// This exemption only silences the PGLite column-only check.'dream_verdicts.expires_at',+ // A14 (migration v175) — tag provenance. Column-only and nullable; no index+ // in either schema blob references it, so the blob replay has no forward+ // reference to trip on, and every reader treats NULL as an unclaimed legacy+ // row (never import-deleted).+ 'tags.tag_source',]);test('every ALTER TABLE ADD COLUMN in MIGRATIONS is covered by applyForwardReferenceBootstrap (column-only class)', async () => {diff --git a/test/search-mode-config-snapshot.test.ts b/test/search-mode-config-snapshot.test.tsindex fd505c8bf5..4972aaa579 100644--- a/test/search-mode-config-snapshot.test.ts+++ b/test/search-mode-config-snapshot.test.ts@@ -48,7 +48,7 @@ describe('loadSearchModeConfig config reads', () => {const engine = perKeyOnlyEngine({ 'search.mode': 'balanced' });const out = await loadSearchModeConfig(engine);expect(out.mode).toBe('balanced');- expect(engine.calls.getConfig).toBe(SEARCH_MODE_CONFIG_KEYS.length + 1);+ expect(engine.calls.getConfig).toBe(SEARCH_MODE_CONFIG_KEYS.length + 3) // search.mode + search.source_boosts + search.alias_token_hop + one per knob key;});test('the snapshot path returns the same values as per-key reads', async () => {@@ -73,6 +73,6 @@ describe('loadSearchModeConfig config reads', () => {const out = await loadSearchModeConfig(engine);expect(out.mode).toBe('conservative');expect(engine.calls.getAllConfig).toBe(1);- expect(engine.calls.getConfig).toBe(SEARCH_MODE_CONFIG_KEYS.length + 1);+ expect(engine.calls.getConfig).toBe(SEARCH_MODE_CONFIG_KEYS.length + 3) // search.mode + search.source_boosts + search.alias_token_hop + one per knob key;});});diff --git a/test/search/alias-token-hop.test.ts b/test/search/alias-token-hop.test.tsnew file mode 100644index 0000000000..e1159f1b42--- /dev/null+++ b/test/search/alias-token-hop.test.ts@@ -0,0 +1,95 @@+/**+ * #5428 remainder: the alias hop only fired when the WHOLE query was an+ * alias, so "<alias> summary" never surfaced the entity page. With+ * `tokenHop` on (opt-in: per-call `aliasTokenHop` or brain config+ * `search.alias_token_hop=true`), a query token that is the alias of exactly+ * one person/company page moves that page to the front, or injects it when+ * absent (at most two pages). Off by default.+ */+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { resetPgliteState } from '../helpers/reset-pglite.ts';+import { applyAliasHop, hybridSearch } from '../../src/core/search/hybrid.ts';+import type { SearchResult } from '../../src/core/types.ts';++let engine: PGLiteEngine;+beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 120_000);+afterAll(async () => { await engine.disconnect(); });+beforeEach(async () => { await resetPgliteState(engine); });++function res(slug: string, score: number, type = 'note'): SearchResult {+ return { slug, title: slug, score, chunk_text: '', type, source_id: 'default', chunk_index: 0, chunk_id: 1 } as unknown as SearchResult;+}++describe('applyAliasHop — single-token alias hop', () => {+ test('off by default: "<alias> summary" changes nothing', async () => {+ await engine.putPage('people/alice-example', { type: 'person', title: 'Alice Example', compiled_truth: 'Alice runs the lab.' });+ await engine.setPageAliases('people/alice-example', 'default', ['ali']);+ const organic = [res('chats/log', 0.9), res('people/alice-example', 0.5, 'person')];+ const out = await applyAliasHop(engine, organic, 'ali summary', { sourceId: 'default' });+ expect(out.map(r => r.slug)).toEqual(['chats/log', 'people/alice-example']);+ });++ test('on: a present entity page moves to the front; the rest keep their order', async () => {+ await engine.putPage('people/alice-example', { type: 'person', title: 'Alice Example', compiled_truth: 'Alice runs the lab.' });+ await engine.setPageAliases('people/alice-example', 'default', ['ali']);+ const organic = [res('chats/log', 0.9), res('notes/x', 0.7), res('people/alice-example', 0.5, 'person')];+ const out = await applyAliasHop(engine, organic, 'ali summary', { sourceId: 'default', tokenHop: true });+ expect(out.map(r => r.slug)).toEqual(['people/alice-example', 'chats/log', 'notes/x']);+ expect(out[0].alias_hit).toBe(true);+ });++ test('on: an absent entity page is injected', async () => {+ await engine.putPage('companies/acme-example', { type: 'company', title: 'Acme Example', compiled_truth: 'Acme builds widgets.' });+ await engine.setPageAliases('companies/acme-example', 'default', ['acme']);+ const out = await applyAliasHop(engine, [res('chats/log', 0.9)], 'acme notes', { sourceId: 'default', tokenHop: true });+ expect(out.map(r => r.slug)).toEqual(['companies/acme-example', 'chats/log']);+ });++ test('on: an ambiguous token, a non-entity page, and an excluded page are ignored', async () => {+ await engine.putPage('people/alice-example', { type: 'person', title: 'Alice Example', compiled_truth: 'a' });+ await engine.putPage('people/alice-other', { type: 'person', title: 'Alice Other', compiled_truth: 'b' });+ await engine.setPageAliases('people/alice-example', 'default', ['alice']);+ await engine.setPageAliases('people/alice-other', 'default', ['alice']);+ await engine.putPage('projects/widget', { type: 'note', title: 'Widget', compiled_truth: 'c' });+ await engine.setPageAliases('projects/widget', 'default', ['widget']);+ await engine.putPage('people/bob-example', { type: 'person', title: 'Bob Example', compiled_truth: 'd' });+ await engine.setPageAliases('people/bob-example', 'default', ['bob']);+ const organic = [res('chats/log', 0.9)];+ expect((await applyAliasHop(engine, organic, 'alice widget summary', { sourceId: 'default', tokenHop: true })).map(r => r.slug))+ .toEqual(['chats/log']);+ expect((await applyAliasHop(engine, organic, 'bob summary', { sourceId: 'default', tokenHop: true, excludeSlugs: ['people/bob-example'] })).map(r => r.slug))+ .toEqual(['chats/log']);+ });++ test('on: at most two token pages', async () => {+ for (const [slug, alias] of [['people/a-example', 'aa'], ['people/b-example', 'bb'], ['people/c-example', 'cc']]) {+ await engine.putPage(slug, { type: 'person', title: slug, compiled_truth: slug });+ await engine.setPageAliases(slug, 'default', [alias]);+ }+ const out = await applyAliasHop(engine, [], 'aa bb cc', { sourceId: 'default', tokenHop: true });+ expect(out.length).toBe(2);+ });++ test('a full-query alias match takes precedence over token hops', async () => {+ await engine.putPage('projects/mingtang', { type: 'note', title: 'The Mingtang', compiled_truth: 'x' });+ await engine.setPageAliases('projects/mingtang', 'default', ['hall of light']);+ await engine.putPage('people/light-example', { type: 'person', title: 'Light Example', compiled_truth: 'y' });+ await engine.setPageAliases('people/light-example', 'default', ['light']);+ const out = await applyAliasHop(engine, [], 'hall of light', { sourceId: 'default', tokenHop: true });+ expect(out.map(r => r.slug)).toEqual(['projects/mingtang']);+ });+});++describe('hybridSearch wiring', () => {+ test('per-call aliasTokenHop and brain config search.alias_token_hop both enable it', async () => {+ await engine.putPage('people/alice-example', { type: 'person', title: 'Alice Example', compiled_truth: 'Alice runs the lab.' });+ await engine.setPageAliases('people/alice-example', 'default', ['ali']);+ await engine.putPage('chats/log', { type: 'note', title: 'Chat log', compiled_truth: 'ali summary of the week' });+ const rr = { reranker: { enabled: false, topNIn: 0, topNOut: null } as any };+ expect((await hybridSearch(engine, 'ali summary', rr)).map(r => r.slug)).not.toContain('people/alice-example');+ expect((await hybridSearch(engine, 'ali summary', { ...rr, aliasTokenHop: true }))[0].slug).toBe('people/alice-example');+ await engine.setConfig('search.alias_token_hop', 'true');+ expect((await hybridSearch(engine, 'ali summary', rr))[0].slug).toBe('people/alice-example');+ }, 60_000);+});diff --git a/test/search/cached-wrapper-roundtrips.test.ts b/test/search/cached-wrapper-roundtrips.test.tsnew file mode 100644index 0000000000..dddb626092--- /dev/null+++ b/test/search/cached-wrapper-roundtrips.test.ts@@ -0,0 +1,55 @@+/**+ * Read-path audit #20: semantic result caching is disabled+ * (semanticResultCacheAvailable() === false), but hybridSearchCached still+ * loaded the merged config, the cache config and the intent-pattern state to+ * build a cache key nothing reads. With the cache unavailable the wrapper+ * must cost no engine round-trips beyond the bare search it runs.+ */+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { installPageProjection, readProjectionSnapshot } from '../../src/core/page-state/projections.ts';+import { hybridSearch, hybridSearchCached } from '../../src/core/search/hybrid.ts';+import { semanticResultCacheAvailable } from '../../src/core/search/query-cache.ts';+import { basisEmbedding } from '../../src/eval/deterministic-embed.ts';+import type { BrainEngine } from '../../src/core/engine.ts';++let engine: PGLiteEngine;+beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ await engine.putPage('notes/a', { type: 'note', title: 'Note A', compiled_truth: 'widget alpha' } as any);+ const snap = (await readProjectionSnapshot(engine, 'notes/a', 'default', { allowUnsealed: true }))!;+ await installPageProjection(engine, snap, [{+ chunk_index: 0, chunk_text: 'widget alpha', chunk_source: 'compiled_truth', embedding: basisEmbedding(3, 1536), token_count: 5,+ }] as any, { seal: true });+}, 120_000);+afterAll(async () => { await engine.disconnect(); });++function counting(e: BrainEngine): { proxy: BrainEngine; calls: Record<string, number> } {+ const calls: Record<string, number> = {};+ const proxy = new Proxy(e, {+ get(target, prop, receiver) {+ const v = Reflect.get(target, prop, receiver);+ if (typeof v !== 'function') return v;+ return (...args: unknown[]) => {+ calls[String(prop)] = (calls[String(prop)] ?? 0) + 1;+ return (v as (...a: unknown[]) => unknown).apply(target, args);+ };+ },+ });+ return { proxy, calls };+}++describe('hybridSearchCached with the semantic cache unavailable', () => {+ test('costs no engine calls beyond the bare search', async () => {+ expect(semanticResultCacheAvailable()).toBe(false);+ const opts = { reranker: { enabled: false, topNIn: 0, topNOut: null } as any, queryEmbedFn: () => basisEmbedding(3, 1536) };+ const bare = counting(engine as unknown as BrainEngine);+ const wrapped = counting(engine as unknown as BrainEngine);+ const a = await hybridSearch(bare.proxy, 'widget', opts);+ const b = await hybridSearchCached(wrapped.proxy, 'widget', opts);+ expect(b.map(r => r.slug)).toEqual(a.map(r => r.slug));+ expect(wrapped.calls).toEqual(bare.calls);+ }, 60_000);+});diff --git a/test/search/cosine-rescore-image-space.test.ts b/test/search/cosine-rescore-image-space.test.tsnew file mode 100644index 0000000000..c46f8b878f--- /dev/null+++ b/test/search/cosine-rescore-image-space.test.ts@@ -0,0 +1,51 @@+/**+ * Read-path audit #7 remainder: in 'both' mode the image arm's rows were+ * rescored against the TEXT column with the TEXT query vector. An image+ * chunk has no text-space vector, so it took cosine 0 and a 30% blend+ * penalty regardless of how well it matched. Image rows now rescore in the+ * image space: the image column, the multimodal query vector.+ */+import { describe, test, expect } from 'bun:test';+import { cosineReScore } from '../../src/core/search/hybrid.ts';+import type { BrainEngine } from '../../src/core/engine.ts';+import type { SearchResult } from '../../src/core/types.ts';++function engineWithColumns(byColumn: Record<string, Map<number, Float32Array>>): BrainEngine {+ return {+ getEmbeddingsByChunkIds: async (ids: number[], column: string) => {+ const src = byColumn[column] ?? new Map();+ return new Map(ids.filter(id => src.has(id)).map(id => [id, src.get(id)!]));+ },+ } as unknown as BrainEngine;+}++const row = (slug: string, chunk_id: number, score: number, modality?: 'text' | 'image'): SearchResult => ({+ slug, page_id: chunk_id, title: slug, type: 'note', chunk_text: slug, chunk_source: 'compiled_truth',+ chunk_id, chunk_index: 0, score, stale: false, ...(modality ? { modality } : {}),+} as SearchResult);++describe('cosineReScore — image rows in both mode', () => {+ test('an image row takes its cosine from the image column and the multimodal query vector', async () => {+ const textQuery = new Float32Array([1, 0, 0]);+ const imageQuery = new Float32Array([0, 1]);+ const engine = engineWithColumns({+ embedding: new Map([[1, new Float32Array([0.6, 0.8, 0])]]),+ embedding_image: new Map([[2, new Float32Array([0, 1])]]),+ });+ const out = await cosineReScore(engine, [row('notes/text', 1, 1, 'text'), row('images/photo', 2, 1, 'image')], textQuery, 'embedding', {+ queryEmbedding: imageQuery,+ column: 'embedding_image',+ });+ const image = out.find(r => r.slug === 'images/photo')!;+ const text = out.find(r => r.slug === 'notes/text')!;+ expect(image.cosine).toBeCloseTo(1, 6);+ expect(text.cosine).toBeCloseTo(0.6, 6);+ expect(out[0].slug).toBe('images/photo');+ });++ test('without an image space, behavior is unchanged', async () => {+ const engine = engineWithColumns({ embedding: new Map([[1, new Float32Array([1, 0, 0])]]) });+ const out = await cosineReScore(engine, [row('notes/text', 1, 1, 'text'), row('images/photo', 2, 1, 'image')], new Float32Array([1, 0, 0]), 'embedding');+ expect(out.find(r => r.slug === 'images/photo')!.cosine).toBe(0);+ });+});diff --git a/test/search/general-title-mention-boost.test.ts b/test/search/general-title-mention-boost.test.tsnew file mode 100644index 0000000000..2ae5c00f28--- /dev/null+++ b/test/search/general-title-mention-boost.test.ts@@ -0,0 +1,106 @@+/**+ * #4694: the title/slug-mentioned-in-query boost (#5676) only fired for+ * entity/event intent, and both of the reporter's shapes ("Which board+ * document is the <title> that we signed last spring?", "Which document is+ * <title>?") classify as general. Under intents without an exact-match+ * boost, a MULTI-token title or slug tail that is the query's subject+ * (supplies at least half its content tokens) now gets a bounded boost; a+ * title merely mentioned inside a longer question does not (measured: that+ * variant sent the mentioned page above the right answer).+ */+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import {+ applyTitleMentionBoost,+ TITLE_MENTION_BOOST,+ weightsForIntent,+} from '../../src/core/search/intent-weights.ts';+import { classifyQuery } from '../../src/core/search/query-intent.ts';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { basisEmbedding } from '../../src/eval/deterministic-embed.ts';+import { installPageProjection, readProjectionSnapshot } from '../../src/core/page-state/projections.ts';+import { hybridSearch } from '../../src/core/search/hybrid.ts';+import type { SearchResult } from '../../src/core/types.ts';++const row = (slug: string, title: string, score = 1): SearchResult => ({+ slug, title, page_id: 1, type: 'note', chunk_text: title, chunk_source: 'compiled_truth',+ chunk_id: 1, chunk_index: 0, score, stale: false, source_id: 'default',+} as SearchResult);++describe('applyTitleMentionBoost', () => {+ test("the reporter's query shapes classify as general", () => {+ expect(classifyQuery('Which board document is the Harbor Street Lease Amendment that we signed last spring?').intent).toBe('general');+ expect(classifyQuery('Which document is Harbor Street Lease Amendment?').intent).toBe('general');+ expect(weightsForIntent('general').exactMatchBoost).toBe(1.0);+ });++ test('a multi-token title that is the subject of a general question is boosted', () => {+ const results = [row('notes/harbor-lease', 'Harbor Street Lease Amendment'), row('notes/other', 'Parking Permit Renewal')];+ applyTitleMentionBoost(results, 'Which document is Harbor Street Lease Amendment?');+ expect(results[0].score).toBe(TITLE_MENTION_BOOST);+ expect(results[0].exact_match_boost).toBe(TITLE_MENTION_BOOST);+ expect(results[1].score).toBe(1);+ });++ test('a title mentioned inside a longer question about something else is not boosted', () => {+ const results = [row('notes/harbor-lease', 'Harbor Street Lease Agreement'), row('notes/harbor-amendment', 'Harbor Street Lease Amendment')];+ applyTitleMentionBoost(results, 'Which amendment changed the rent and term originally set in the Harbor Street Lease Agreement?');+ applyTitleMentionBoost(results, 'Which board document is the Harbor Street Lease Agreement that we signed last spring?');+ expect(results.map(r => r.score)).toEqual([1, 1]);+ });++ test('when one mentioned title contains another, only the longer one is boosted', () => {+ const results = [row('finance/budget-review', 'Budget Review'), row('events/offsite-budget-review', 'Offsite Budget Review')];+ applyTitleMentionBoost(results, 'Which document is the Offsite Budget Review?');+ expect(results.map(r => r.score)).toEqual([1, TITLE_MENTION_BOOST]);+ });++ test('the slug tail counts when the title does not', () => {+ const results = [row('notes/harbor-street-lease', 'HSL-2')];+ applyTitleMentionBoost(results, 'harbor street lease draft');+ expect(results[0].score).toBe(TITLE_MENTION_BOOST);+ });++ test('one-token titles and partial mentions are not boosted', () => {+ const results = [row('notes/mingtang', 'Mingtang'), row('notes/harbor-lease', 'Harbor Street Lease Amendment')];+ applyTitleMentionBoost(results, 'what happened at mingtang about the harbor street lease');+ expect(results.map(r => r.score)).toEqual([1, 1]);+ });+});++describe('general-intent question ranks the mentioned title first (PGLite)', () => {+ let engine: PGLiteEngine;+ beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 120_000);+ afterAll(async () => { await engine.disconnect(); });++ async function seed(slug: string, title: string, text: string, dim: number) {+ await engine.putPage(slug, { type: 'note', title, compiled_truth: text } as any);+ const snap = (await readProjectionSnapshot(engine, slug, 'default', { allowUnsealed: true }))!;+ await installPageProjection(engine, snap, [{+ chunk_index: 0, chunk_text: text, chunk_source: 'compiled_truth', embedding: basisEmbedding(dim, 1536), token_count: 10,+ }] as any, { seal: true });+ }++ test('a relational question ("who invested in Pulse Labs") is not title-boosted', async () => {+ await seed('companies/pulse-labs', 'Pulse Labs', 'Pulse Labs builds sensors.', 3);+ await seed('notes/pulse-labs-update', 'Pulse Labs', 'Pulse Labs raised a seed round.', 3);+ const q = 'Who invested in Pulse Labs?';+ expect(classifyQuery(q).intent).not.toBe('entity');+ const out = await hybridSearch(engine, q, {+ reranker: { enabled: false, topNIn: 0, topNOut: null } as any, relationalRetrieval: false, queryEmbedFn: () => basisEmbedding(3, 1536),+ });+ expect(out.length).toBeGreaterThan(0);+ expect(out.some(r => r.exact_match_boost === TITLE_MENTION_BOOST)).toBe(false);+ }, 60_000);++ test('"Which document is Harbor Street Lease Amendment?"', async () => {+ await seed('notes/harbor-lease', 'Harbor Street Lease Amendment', 'Signed amendment extending the term and adjusting rent.', 5);+ await seed('notes/lease-summary', 'Lease Summary', 'Summary of every lease the board signed, including the harbor street site.', 6);+ const out = await hybridSearch(engine, 'Which document is Harbor Street Lease Amendment?', {+ // Closer to the summary page (cosine 0.8 vs 0.6): unboosted, the summary wins.+ queryEmbedFn: () => { const v = new Float32Array(1536); v[5] = 0.6; v[6] = 0.8; return v; },+ reranker: { enabled: false, topNIn: 0, topNOut: null } as any,+ });+ expect(out[0].slug).toBe('notes/harbor-lease');+ expect(out[0].exact_match_boost).toBe(TITLE_MENTION_BOOST);+ }, 60_000);+});diff --git a/test/search/injection-excludes-keyword-boost.test.ts b/test/search/injection-excludes-keyword-boost.test.tsnew file mode 100644index 0000000000..a6c9815ea3--- /dev/null+++ b/test/search/injection-excludes-keyword-boost.test.ts@@ -0,0 +1,79 @@+/**+ * Read-path audit leftovers:+ * - the alias hop and the exact-lookup tier inject pages AFTER the engine+ * arms, so they must honor the same prefix excludes the arms apply in SQL+ * (caller exclude_slug_prefixes plus the default/env hard excludes), on+ * every return path;+ * - the keyword-only (no embedding provider) path never applied the intent+ * exact-match boost.+ */+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { resetPgliteState } from '../helpers/reset-pglite.ts';+import { installPageProjection, readProjectionSnapshot } from '../../src/core/page-state/projections.ts';+import { hybridSearch } from '../../src/core/search/hybrid.ts';+import type { HybridSearchMeta } from '../../src/core/types.ts';+import { basisEmbedding } from '../../src/eval/deterministic-embed.ts';++let engine: PGLiteEngine;+beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 120_000);+afterAll(async () => { await engine.disconnect(); });+beforeEach(async () => { await resetPgliteState(engine); });++async function seed(slug: string, type: string, title: string, text: string, dim: number) {+ await engine.putPage(slug, { type, title, compiled_truth: text } as any);+ const snap = (await readProjectionSnapshot(engine, slug, 'default', { allowUnsealed: true }))!;+ await installPageProjection(engine, snap, [{+ chunk_index: 0, chunk_text: text, chunk_source: 'compiled_truth', embedding: basisEmbedding(dim, 1536), token_count: 5,+ }] as any, { seal: true });+}++const noRerank = { reranker: { enabled: false, topNIn: 0, topNOut: null } as any };+const vec = { ...noRerank, queryEmbedFn: () => basisEmbedding(3, 1536) };++describe('identity injections honor prefix excludes', () => {+ test('alias hop never injects a page under a caller exclude_slug_prefix', async () => {+ await seed('notes/a', 'note', 'Note A', 'widget alpha', 3);+ await seed('private-drafts/hall', 'note', 'Hall Draft', 'unrelated text entirely', 9);+ await engine.setPageAliases('private-drafts/hall', 'default', ['hall of light']);+ const out = await hybridSearch(engine, 'hall of light', { ...vec, exclude_slug_prefixes: ['private-drafts/'] });+ expect(out.map(r => r.slug)).not.toContain('private-drafts/hall');+ }, 60_000);++ test('exact-lookup slug probe never injects a hard-excluded or prefix-excluded page', async () => {+ await seed('notes/a', 'note', 'Note A', 'widget alpha', 3);+ await seed('test/fixture-page', 'note', 'Fixture', 'fixture body', 9);+ await seed('private-drafts/plan', 'note', 'Plan', 'plan body', 9);+ const hard = await hybridSearch(engine, 'test/fixture-page', vec);+ expect(hard.map(r => r.slug)).not.toContain('test/fixture-page');+ const admitted = await hybridSearch(engine, 'test/fixture-page', { ...vec, include_slug_prefixes: ['test/'] });+ expect(admitted.map(r => r.slug)).toContain('test/fixture-page');+ const prefixed = await hybridSearch(engine, 'private-drafts/plan', { ...vec, exclude_slug_prefixes: ['private-drafts/'] });+ expect(prefixed.map(r => r.slug)).not.toContain('private-drafts/plan');+ }, 60_000);++ test('keyword-only path: alias hop honors exclude_slugs and prefix excludes', async () => {+ await seed('notes/a', 'note', 'Note A', 'widget alpha', 3);+ await seed('projects/hall', 'note', 'Hall', 'unrelated text entirely', 9);+ await engine.setPageAliases('projects/hall', 'default', ['hall of light']);+ let meta: HybridSearchMeta | undefined;+ const bySlug = await hybridSearch(engine, 'hall of light', { ...noRerank, exclude_slugs: ['projects/hall'], onMeta: (m) => { meta = m; } });+ expect(meta?.vector_enabled).toBe(false);+ expect(bySlug.map(r => r.slug)).not.toContain('projects/hall');+ const byPrefix = await hybridSearch(engine, 'hall of light', { ...noRerank, exclude_slug_prefixes: ['projects/'] });+ expect(byPrefix.map(r => r.slug)).not.toContain('projects/hall');+ }, 60_000);+});++describe('keyword-only path applies the intent exact-match boost', () => {+ test('"who is Alice Example" boosts the Alice Example page without an embedding provider', async () => {+ await seed('people/alice-example', 'person', 'Alice Example', 'Alice Example runs the widget lab.', 5);+ await seed('people/charlie-example', 'person', 'Charlie Example', 'Charlie Example and Alice Example run the widget lab together.', 6);+ let meta: HybridSearchMeta | undefined;+ const out = await hybridSearch(engine, 'who is Alice Example', { ...noRerank, onMeta: (m) => { meta = m; } });+ expect(meta?.vector_enabled).toBe(false);+ const alice = out.find(r => r.slug === 'people/alice-example');+ expect(alice?.exact_match_boost).toBe(1.25);+ expect(out[0].slug).toBe('people/alice-example');+ }, 60_000);+});diff --git a/test/search/rerank.test.ts b/test/search/rerank.test.tsindex ab6c40dce6..0810e25947 100644--- a/test/search/rerank.test.ts+++ b/test/search/rerank.test.ts@@ -453,3 +453,41 @@ describe('applyReranker — pass-through cases', () => {expect(called).toBe(false);});});++describe('applyReranker — equal rerank scores (#5428)', () => {+ test('a run of exactly equal scores keeps the fused order, not the provider order', async () => {+ const results = [+ makeResult('people/alice-example', 1.0, 'canonical page'),+ makeResult('chats/log', 0.9, 'chat log'),+ makeResult('notes/other', 0.8, 'other'),+ makeResult('notes/tail', 0.7, 'tail'),+ ];+ const out = await applyReranker('q', results, {+ enabled: true,+ topNIn: 4,+ topNOut: null,+ rerankerFn: async () => [+ { index: 2, relevanceScore: 0.95 },+ { index: 1, relevanceScore: 0.90234375 },+ { index: 3, relevanceScore: 0.90234375 },+ { index: 0, relevanceScore: 0.90234375 },+ ],+ });+ expect(out.map(r => r.slug)).toEqual(['notes/other', 'people/alice-example', 'chats/log', 'notes/tail']);+ expect(out.map(r => r.reranker_delta)).toEqual([2, -1, -1, 0]);+ });++ test('rows never cross a different score, and unscored rows keep their place', async () => {+ const results = [makeResult('a', 1, 'a'), makeResult('b', 0.9, 'b'), makeResult('c', 0.8, 'c')];+ const out = await applyReranker('q', results, {+ enabled: true,+ topNIn: 3,+ topNOut: null,+ rerankerFn: async () => [+ { index: 2, relevanceScore: 0.9 },+ { index: 0, relevanceScore: 0.5 },+ ],+ });+ expect(out.map(r => r.slug)).toEqual(['c', 'a', 'b']);+ });+});diff --git a/test/search/source-boost-config.test.ts b/test/search/source-boost-config.test.tsnew file mode 100644index 0000000000..3b810e5afb--- /dev/null+++ b/test/search/source-boost-config.test.ts@@ -0,0 +1,60 @@+/**+ * Read-path audit #13: DEFAULT_SOURCE_BOOSTS fit one vault layout and were+ * only overridable per process (GBRAIN_SOURCE_BOOST). A brain can now carry+ * its own map in `search.source_boosts` (same `prefix:factor,...` format;+ * a `none` entry drops the defaults). Existing brains keep the defaults.+ */+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';+import { DEFAULT_SOURCE_BOOSTS, resolveBoostMap } from '../../src/core/search/source-boost.ts';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { resetPgliteState } from '../helpers/reset-pglite.ts';+import { installPageProjection, readProjectionSnapshot } from '../../src/core/page-state/projections.ts';+import { hybridSearch } from '../../src/core/search/hybrid.ts';+import { basisEmbedding } from '../../src/eval/deterministic-embed.ts';++describe('resolveBoostMap with a per-brain config value', () => {+ test('no config keeps the defaults', () => {+ expect(resolveBoostMap(undefined, undefined)).toEqual(DEFAULT_SOURCE_BOOSTS);+ });+ test('config entries override and extend the defaults', () => {+ const m = resolveBoostMap(undefined, 'people/:1.0,wiki/:1.3');+ expect(m['people/']).toBe(1.0);+ expect(m['wiki/']).toBe(1.3);+ expect(m['originals/']).toBe(DEFAULT_SOURCE_BOOSTS['originals/']);+ });+ test('a none entry drops the defaults', () => {+ expect(resolveBoostMap(undefined, 'none')).toEqual({});+ expect(resolveBoostMap(undefined, 'none,wiki/:1.3')).toEqual({ 'wiki/': 1.3 });+ });+ test('the env override still wins over the brain config', () => {+ expect(resolveBoostMap('wiki/:2', 'wiki/:1.3')['wiki/']).toBe(2);+ });+});++describe('search.source_boosts reaches the engine arms', () => {+ let engine: PGLiteEngine;+ beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 120_000);+ afterAll(async () => { await engine.disconnect(); });+ beforeEach(async () => { await resetPgliteState(engine); });++ async function seed(slug: string, text: string) {+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: text } as any);+ const snap = (await readProjectionSnapshot(engine, slug, 'default', { allowUnsealed: true }))!;+ await installPageProjection(engine, snap, [{+ chunk_index: 0, chunk_text: text, chunk_source: 'compiled_truth', embedding: basisEmbedding(3, 1536), token_count: 5,+ }] as any, { seal: true });+ }+ const opts = { reranker: { enabled: false, topNIn: 0, topNOut: null } as any, queryEmbedFn: () => basisEmbedding(3, 1536) };++ test('a brain-level map re-orders pages the default map would order the other way', async () => {+ await seed('daily/2026-01-01', 'widget pricing review notes');+ await seed('people/alice-example', 'widget pricing review notes');+ const before = await hybridSearch(engine, 'widget pricing review', opts);+ expect(before[0].slug).toBe('people/alice-example');+ await engine.setConfig('search.source_boosts', 'daily/:1.5');+ const after = await hybridSearch(engine, 'widget pricing review', opts);+ expect(after[0].slug).toBe('daily/2026-01-01');+ const kw = await engine.searchKeyword('widget pricing review', { source_boosts: resolveBoostMap(undefined, 'daily/:1.5') });+ expect(kw[0].slug).toBe('daily/2026-01-01');+ }, 60_000);+});diff --git a/test/sync-extract-scoped-metadata.test.ts b/test/sync-extract-scoped-metadata.test.tsnew file mode 100644index 0000000000..2f3ab61563--- /dev/null+++ b/test/sync-extract-scoped-metadata.test.ts@@ -0,0 +1,114 @@+/**+ * A16: the post-sync link hook reads page metadata for the changed pages and+ * their link endpoints, not the whole brain. It used to load every page of+ * every source (plus a DISTINCT join over links) on each incremental sync of+ * a single file. A15: post-sync extraction failures are reported, not+ * swallowed.+ *+ * PGLite in-memory, no embeddings ($0).+ */++import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { mkdtempSync, writeFileSync, mkdirSync } from 'fs';+import { execSync } from 'child_process';+import { tmpdir } from 'os';+import { join } from 'path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { runSources } from '../src/commands/sources.ts';+import { performSync } from '../src/commands/sync.ts';+import { extractLinksForSlugs } from '../src/commands/extract.ts';+import { importFromFile } from '../src/core/import-file.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ await runSources(engine, ['add', 'sm', '--no-federated']);+ await runSources(engine, ['add', 'other', '--no-federated']);+ await runSources(engine, ['add', 'ae', '--no-federated']);+}, 60_000);++afterAll(async () => {+ if (engine) await engine.disconnect();+}, 60_000);++const links = async (sourceId: string) => (await engine.executeRaw<{ f: string; t: string }>(+ `SELECT f.slug f, t.slug t FROM links l JOIN pages f ON f.id = l.from_page_id JOIN pages t ON t.id = l.to_page_id+ WHERE f.source_id = $1 ORDER BY 1, 2`, [sourceId])).map(r => `${r.f}->${r.t}`);++describe('post-sync link hook (A16)', () => {+ test('reads O(changed pages) page rows, and still replaces links', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'scoped-meta-'));+ mkdirSync(join(dir, 'notes'));+ mkdirSync(join(dir, 'people'));+ const put = async (sourceId: string, rel: string, body: string) => {+ writeFileSync(join(dir, rel), body);+ await importFromFile(engine, join(dir, rel), rel, { noEmbed: true, sourceId });+ };+ await put('sm', 'people/alice-example.md', `---\ntype: person\ntitle: Alice Example\n---\n\nAlice.\n`);+ await put('sm', 'people/bob-example.md', `---\ntype: person\ntitle: Bob Example\n---\n\nBob.\n`);+ for (let i = 0; i < 150; i++) {+ await engine.putPage(`notes/filler-${i}`, { type: 'note', title: `Filler ${i}`, compiled_truth: 'x', timeline: '', frontmatter: {} }, { sourceId: 'sm' });+ await engine.putPage(`notes/filler-${i}`, { type: 'note', title: `Filler ${i}`, compiled_truth: 'x', timeline: '', frontmatter: {} }, { sourceId: 'other' });+ }+ await put('sm', 'notes/a.md', `---\ntype: note\ntitle: A\n---\n\nMet [[people/alice-example]] and [[people/bob-example]].\n`);+ await extractLinksForSlugs(engine, dir, ['notes/a'], { sourceId: 'sm' });+ expect(await links('sm')).toEqual(['notes/a->people/alice-example', 'notes/a->people/bob-example']);++ writeFileSync(join(dir, 'notes/a.md'), `---\ntype: note\ntitle: A\n---\n\nMet [[people/alice-example]].\n`);+ await importFromFile(engine, join(dir, 'notes/a.md'), 'notes/a.md', { noEmbed: true, sourceId: 'sm' });+ const executeRaw = PGLiteEngine.prototype.executeRaw;+ let pageRows = 0;+ // A function (not an arrow) so transaction handles derived from the engine keep their own `this`.+ (engine as unknown as { executeRaw: unknown }).executeRaw = async function (this: PGLiteEngine, sql: string, params?: unknown[]) {+ const rows = await executeRaw.call(this, sql, params);+ if (/FROM pages\b/.test(sql)) pageRows += rows.length;+ return rows;+ };+ try {+ const r = await extractLinksForSlugs(engine, dir, ['notes/a'], { sourceId: 'sm' });+ expect(r.processed).toEqual(['notes/a']);+ } finally {+ delete (engine as unknown as { executeRaw?: unknown }).executeRaw;+ }+ expect(await links('sm')).toEqual(['notes/a->people/alice-example']);+ expect(pageRows).toBeLessThan(20);+ }, 60_000);+});++describe('post-sync extraction errors (A15)', () => {+ test('a failed extraction is logged and reported on the sync result', async () => {+ const repo = mkdtempSync(join(tmpdir(), 'extract-error-'));+ execSync('git init -q && git config user.email t@t && git config user.name t', { cwd: repo });+ mkdirSync(join(repo, 'notes'));+ writeFileSync(join(repo, 'notes/seed.md'), `---\ntype: note\ntitle: Seed\n---\n\nSeed.\n`);+ execSync('git add -A && git commit -qm seed', { cwd: repo });+ await performSync(engine, { repoPath: repo, sourceId: 'ae', noPull: true, noEmbed: true });+ writeFileSync(join(repo, 'notes/b.md'), `---\ntype: note\ntitle: B\n---\n\n- **2024-01-01** | something\n`);+ execSync('git add -A && git commit -qm b', { cwd: repo });++ const stderr: string[] = [];+ const origWrite = process.stderr.write.bind(process.stderr);+ (engine as unknown as { replaceDerivedLinks: unknown }).replaceDerivedLinks = async () => { throw new Error('graph store offline'); };+ const origError = console.error;+ process.stderr.write = ((chunk: unknown) => { stderr.push(String(chunk)); return true; }) as typeof process.stderr.write;+ console.error = (...args: unknown[]) => { stderr.push(args.map(String).join(' ')); };+ let result;+ try {+ result = await performSync(engine, { repoPath: repo, sourceId: 'ae', noPull: true, noEmbed: true });+ } finally {+ process.stderr.write = origWrite;+ console.error = origError;+ delete (engine as unknown as { replaceDerivedLinks?: unknown }).replaceDerivedLinks;+ }+ expect(result.status).toBe('synced');+ expect(result.extract_error).toContain('notes/b');+ expect(result.extract_error).toContain('graph store offline');+ expect(stderr.join('')).toContain('graph store offline');+ const [page] = await engine.executeRaw<{ links_extracted_at: string | null }>(+ `SELECT links_extracted_at FROM pages WHERE source_id = 'ae' AND slug = 'notes/b'`);+ expect(page.links_extracted_at).toBeNull();+ }, 60_000);+});diff --git a/test/sync-rename-reconcile.serial.test.ts b/test/sync-rename-reconcile.serial.test.tsindex 3d0375676b..d53f2e12df 100644--- a/test/sync-rename-reconcile.serial.test.ts+++ b/test/sync-rename-reconcile.serial.test.ts@@ -317,9 +317,12 @@ describe('#3056: rename fallback reconciles the stale old row', () => {// The stale old row reconciled away even though the skip wrote nothing...expect(await engine.getPage('people/carol')).toBeNull();- // ...and the destination row is genuinely untouched (the skip was real).- const after = await engine.readPageSnapshot('people/dana', { sourceId: 'default' });- expect(after).toEqual(before);+ // ...and the destination row is genuinely untouched (the skip was real):+ // the only change is the file origin every file import records (#5675),+ // bookkeeping that leaves the revision alone.+ const after = (await engine.readPageSnapshot('people/dana', { sourceId: 'default' }))!;+ expect(after.page.source_uri).toMatch(/^file:\/\/.*\/people\/dana\.md$/);+ expect(after).toEqual({ ...before, page: { ...before.page, source_uri: after.page.source_uri } });expect(await countPages()).toBe(1);});});diff --git a/test/takes-extract-json.test.ts b/test/takes-extract-json.test.tsindex f3f4d6a832..9a22bd9274 100644--- a/test/takes-extract-json.test.ts+++ b/test/takes-extract-json.test.ts@@ -55,6 +55,9 @@ describe('gbrain takes extract --from-pages --json (#3962)', () => {pages_skipped: 0,skipped: [],mirror_warnings: 0,+ // B-14: budget stop + fence dedupe accounting.+ budget_exhausted: false,+ duplicates_skipped: 0,});});});diff --git a/test/timeline-reconcile-all-paths.test.ts b/test/timeline-reconcile-all-paths.test.tsnew file mode 100644index 0000000000..e0f882a56b--- /dev/null+++ b/test/timeline-reconcile-all-paths.test.ts@@ -0,0 +1,193 @@+/**+ * Every extraction path reconciles a page's derived links and timeline rows+ * with its current markdown (#5170, #4649).+ *+ * Sync's inline hook and the cycle's incremental extract already replaced+ * links and retracted timeline rows the previous version produced. The+ * `extract --stale` sweep, the full-walk `gbrain extract` (file and DB+ * source) and pages edited several times between extractions still kept+ * removed rows. A timeline row is retracted when an earlier version of the+ * page produced it and the current text no longer does; rows no version ever+ * produced (enrichment, meeting fan-out) are never touched.+ *+ * PGLite in-memory, no embeddings ($0).+ */++import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { mkdtempSync, writeFileSync, mkdirSync } from 'fs';+import { execSync } from 'child_process';+import { tmpdir } from 'os';+import { join } from 'path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { runSources } from '../src/commands/sources.ts';+import { performSync } from '../src/commands/sync.ts';+import { runExtract, runExtractCore, extractStaleFromDB } from '../src/commands/extract.ts';+import { importFromFile } from '../src/core/import-file.ts';+import { pruneTimelineOrphans } from '../src/core/timeline-extract.ts';+import { timelineOrphansCheck } from '../src/commands/doctor/checks/timeline-orphans.ts';+import { categorizeCheck } from '../src/core/doctor-categories.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ for (const id of ['st', 'fw', 'db', 'gap', 'pr', 'pr2']) await runSources(engine, ['add', id, '--no-federated']);+}, 60_000);++afterAll(async () => {+ if (engine) await engine.disconnect();+}, 60_000);++const links = async (sourceId: string) => (await engine.executeRaw<{ f: string; t: string }>(+ `SELECT f.slug f, t.slug t FROM links l JOIN pages f ON f.id = l.from_page_id JOIN pages t ON t.id = l.to_page_id+ WHERE f.source_id = $1 ORDER BY 1, 2`, [sourceId])).map(r => `${r.f}->${r.t}`);++const timeline = async (sourceId: string, slug: string) => (await engine.executeRaw<{ d: string; summary: string }>(+ `SELECT t.date::text d, t.summary FROM timeline_entries t JOIN pages p ON p.id = t.page_id+ WHERE p.source_id = $1 AND p.slug = $2 ORDER BY 1, 2`, [sourceId, slug])).map(r => `${r.d} ${r.summary}`);++const note = (body: string) => `---\ntype: note\ntitle: A\n---\n\n${body}\n`;+const person = (bullet: string) =>+ `---\ntype: person\ntitle: Alice Example\n---\n\nAlice is an engineer.\n\n<!-- timeline -->\n\n## Timeline\n\n${bullet}\n`;++function gitRepo(): string {+ const repo = mkdtempSync(join(tmpdir(), 'timeline-reconcile-'));+ execSync('git init -q && git config user.email t@t && git config user.name t', { cwd: repo });+ mkdirSync(join(repo, 'notes'));+ mkdirSync(join(repo, 'people'));+ writeFileSync(join(repo, 'people/bob-example.md'), `---\ntype: person\ntitle: Bob Example\n---\n\nBob is a designer.\n`);+ return repo;+}++function brainDir() {+ const dir = mkdtempSync(join(tmpdir(), 'timeline-walk-'));+ mkdirSync(join(dir, 'notes'));+ mkdirSync(join(dir, 'people'));+ return dir;+}++async function writeAndImport(dir: string, sourceId: string, rel: string, body: string) {+ writeFileSync(join(dir, rel), body);+ await importFromFile(engine, join(dir, rel), rel, { noEmbed: true, sourceId });+}++describe('extract --stale (#5170)', () => {+ test('retracts a removed bullet even after several unextracted edits, keeps other producers', async () => {+ const repo = gitRepo();+ const sync = () => performSync(engine, { repoPath: repo, sourceId: 'st', noPull: true, noEmbed: true, noExtract: true });+ const stale = () => extractStaleFromDB(engine, { dryRun: false, jsonMode: false, quiet: true, sourceIdFilter: 'st', catchUp: true });+ writeFileSync(join(repo, 'notes/a.md'), note('Met with [[people/alice-example]] and [[people/bob-example]].'));+ writeFileSync(join(repo, 'people/alice-example.md'), person('- **2030-06-15** | synthetic event alpha'));+ execSync('git add -A && git commit -qm seed', { cwd: repo });+ await sync();+ await stale();+ expect(await links('st')).toEqual(['notes/a->people/alice-example', 'notes/a->people/bob-example']);+ expect(await timeline('st', 'people/alice-example')).toEqual(['2030-06-15 synthetic event alpha']);+ await engine.addTimelineEntry('people/alice-example', { date: '2023-01-01', source: 'enrichment', summary: 'Mentioned in a board memo' }, { sourceId: 'st' });++ writeFileSync(join(repo, 'people/alice-example.md'), person('- **2030-07-01** | synthetic event beta'));+ execSync('git commit -qam edit1', { cwd: repo });+ await sync();+ writeFileSync(join(repo, 'notes/a.md'), note('Met with [[people/alice-example]].'));+ writeFileSync(join(repo, 'people/alice-example.md'), person('- **2030-08-01** | synthetic event gamma'));+ execSync('git commit -qam edit2', { cwd: repo });+ await sync();+ await stale();++ expect(await links('st')).toEqual(['notes/a->people/alice-example']);+ expect(await timeline('st', 'people/alice-example')).toEqual([+ '2023-01-01 Mentioned in a board memo',+ '2030-08-01 synthetic event gamma',+ ]);+ }, 60_000);+});++describe('full-walk extract', () => {+ test('file walk replaces links and timeline rows like per-file sync', async () => {+ const dir = brainDir();+ const walk = () => runExtractCore(engine, { mode: 'all', dir, sourceId: 'fw', quiet: true });+ await writeAndImport(dir, 'fw', 'people/bob-example.md', `---\ntype: person\ntitle: Bob Example\n---\n\nBob.\n`);+ await writeAndImport(dir, 'fw', 'people/carol-example.md', person('- **2024-03-01** | Joined widget-co'));+ await writeAndImport(dir, 'fw', 'notes/b.md', note('Talked to [[people/bob-example]] and [[people/carol-example]].'));+ await walk();+ expect(await links('fw')).toEqual(['notes/b->people/bob-example', 'notes/b->people/carol-example']);+ await engine.addTimelineEntry('people/carol-example', { date: '2023-01-01', source: 'enrichment', summary: 'Mentioned in a memo' }, { sourceId: 'fw' });++ await writeAndImport(dir, 'fw', 'notes/b.md', note('Talked to [[people/carol-example]].'));+ await writeAndImport(dir, 'fw', 'people/carol-example.md', person('- **2024-05-01** | Joined widget-co'));+ await walk();+ expect(await links('fw')).toEqual(['notes/b->people/carol-example']);+ expect(await timeline('fw', 'people/carol-example')).toEqual(['2023-01-01 Mentioned in a memo', '2024-05-01 Joined widget-co']);+ }, 60_000);++ test('DB-source timeline walk retracts removed rows', async () => {+ const dir = brainDir();+ await writeAndImport(dir, 'db', 'people/dana-example.md', person('- **2024-03-01** | Joined widget-co'));+ await runExtract(engine, ['timeline', '--source', 'db', '--source-id', 'db', '--json']);+ expect(await timeline('db', 'people/dana-example')).toEqual(['2024-03-01 Joined widget-co']);+ await writeAndImport(dir, 'db', 'people/dana-example.md', person('- **2024-06-01** | Left widget-co'));+ await runExtract(engine, ['timeline', '--source', 'db', '--source-id', 'db', '--json']);+ expect(await timeline('db', 'people/dana-example')).toEqual(['2024-06-01 Left widget-co']);+ }, 60_000);+});++describe('sync inline extraction after unextracted edits', () => {+ test('rows from versions older than the previous one are retracted too', async () => {+ const repo = gitRepo();+ const sync = (noExtract: boolean) => performSync(engine, { repoPath: repo, sourceId: 'gap', noPull: true, noEmbed: true, noExtract });+ execSync('git add -A && git commit -qm seed', { cwd: repo });+ await sync(false);+ writeFileSync(join(repo, 'people/alice-example.md'), person('- **2024-01-01** | first'));+ execSync('git add -A && git commit -qm add', { cwd: repo });+ await sync(false);+ expect(await timeline('gap', 'people/alice-example')).toEqual(['2024-01-01 first']);+ writeFileSync(join(repo, 'people/alice-example.md'), person('- **2024-02-01** | second'));+ execSync('git commit -qam e1', { cwd: repo });+ await sync(true);+ writeFileSync(join(repo, 'people/alice-example.md'), person('- **2024-03-01** | third'));+ execSync('git commit -qam e2', { cwd: repo });+ await sync(false);+ expect(await timeline('gap', 'people/alice-example')).toEqual(['2024-03-01 third']);+ }, 60_000);+});++describe('one-time orphan prune (#4649)', () => {+ async function seedLegacyOrphans(sourceId: string) {+ const dir = brainDir();+ // Before v0.59.11 every extraction was insert-only: each edit left its old row behind.+ for (const [date, summary] of [['2024-01-01', 'first'], ['2024-02-01', 'second'], ['2024-03-01', 'third']]) {+ await writeAndImport(dir, sourceId, 'people/erin-example.md', person(`- **${date}** | ${summary}`));+ await engine.addTimelineEntry('people/erin-example', { date, source: 'markdown', summary }, { sourceId });+ }+ await engine.addTimelineEntry('people/erin-example', { date: '2023-01-01', source: 'enrichment', summary: 'Mentioned in a memo' }, { sourceId });+ }++ test('dry run reports orphans without deleting; apply removes only version-produced rows', async () => {+ await seedLegacyOrphans('pr');+ const check = await timelineOrphansCheck(engine);+ expect(check.status).toBe('warn');+ expect(check.message).toContain('gbrain extract timeline --prune-orphans');+ expect(check.message).toContain('pr:people/erin-example');+ expect(categorizeCheck('timeline_orphans')).toBe('brain');+ const preview = await pruneTimelineOrphans(engine, { sourceId: 'pr', dryRun: true });+ expect(preview.orphans).toBe(2);+ expect(preview.removed).toBe(0);+ expect((await timeline('pr', 'people/erin-example')).length).toBe(4);++ const applied = await pruneTimelineOrphans(engine, { sourceId: 'pr', dryRun: false });+ expect(applied.removed).toBe(2);+ expect(await timeline('pr', 'people/erin-example')).toEqual(['2023-01-01 Mentioned in a memo', '2024-03-01 third']);+ expect((await pruneTimelineOrphans(engine, { sourceId: 'pr', dryRun: true })).orphans).toBe(0);+ expect((await timelineOrphansCheck(engine)).status).toBe('ok');+ }, 60_000);++ test('the CLI prune is source-scoped', async () => {+ await seedLegacyOrphans('pr2');+ await runExtract(engine, ['timeline', '--prune-orphans', '--source-id', 'pr', '--json']);+ expect((await timeline('pr2', 'people/erin-example')).length).toBe(4);+ await runExtract(engine, ['timeline', '--prune-orphans', '--source-id', 'pr2', '--json']);+ expect(await timeline('pr2', 'people/erin-example')).toEqual(['2023-01-01 Mentioned in a memo', '2024-03-01 third']);+ }, 60_000);+});diff --git a/test/token-budget.test.ts b/test/token-budget.test.tsindex dc2b07ed9b..e378e7187e 100644--- a/test/token-budget.test.ts+++ b/test/token-budget.test.ts@@ -247,3 +247,49 @@ describe('packToBudget \u2014 frozen strict edge (memory-verb consumers)', () =>expect(tiny.meta.dropped).toBe(3);});});++describe('read-path audit #17 — packer and estimator', () => {+ test('one oversized result mid-list is skipped, not a cut of everything after it', () => {+ const results = [+ makeResult({ slug: 'a', title: 'a', chunk_text: 'xxxx' }),+ makeResult({ slug: 'huge', title: 'a', chunk_text: 'x'.repeat(4000) }),+ makeResult({ slug: 'c', title: 'a', chunk_text: 'xxxx' }),+ makeResult({ slug: 'd', title: 'a', chunk_text: 'xxxx' }),+ ];+ const { results: kept, meta } = enforceTokenBudget(results, 10);+ expect(kept.map(r => r.slug)).toEqual(['a', 'c', 'd']);+ expect(meta).toMatchObject({ used: 6, kept: 3, dropped: 1 });+ });++ test('CJK text costs about one token per character, not one per four', () => {+ expect(estimateTokens('知识管理系统')).toBe(6);+ expect(estimateTokens('こんにちは世界')).toBe(7);+ expect(estimateTokens('한국어 텍스트')).toBe(7);+ expect(estimateTokens('abcd知识')).toBe(3);+ });++ test('a CJK result is budgeted at its real cost', () => {+ const cjk = makeResult({ slug: 'cjk', title: '', chunk_text: '知'.repeat(40) });+ const tail = makeResult({ slug: 'tail', title: '', chunk_text: 'xxxx' });+ const { results: kept } = enforceTokenBudget([tail, cjk], 20);+ expect(kept.map(r => r.slug)).toEqual(['tail']);+ });++ test('the salvage truncation never splits a surrogate pair and stays within budget', () => {+ const emoji = makeResult({ slug: 'e', title: '', chunk_text: 'abc' + '😀'.repeat(50) });+ const { results: kept, meta } = enforceTokenBudget([emoji], 3);+ expect(meta.truncated).toBe(true);+ const text = kept[0].chunk_text;+ expect(text.isWellFormed()).toBe(true);+ expect(resultTokens(kept[0])).toBeLessThanOrEqual(3);+ expect(text.length).toBeGreaterThan(0);+ });++ test('the salvage truncation of CJK text stays within budget', () => {+ const cjk = makeResult({ slug: 'cjk', title: '知识', chunk_text: '知'.repeat(200) });+ const { results: kept, meta } = enforceTokenBudget([cjk], 10);+ expect(meta.truncated).toBe(true);+ expect(resultTokens(kept[0])).toBeLessThanOrEqual(10);+ expect(kept[0].chunk_text).toBe('知'.repeat(8));+ });+});diff --git a/test/trajectory-timeout-timers.test.ts b/test/trajectory-timeout-timers.test.tsnew file mode 100644index 0000000000..d6967811de--- /dev/null+++ b/test/trajectory-timeout-timers.test.ts@@ -0,0 +1,77 @@+/**+ * Read-path audit #20: the per-candidate 5 s findTrajectory deadline in+ * think and in the LongMemEval trajectory route was a bare setTimeout that+ * was never cleared, so every lookup left a live timer that could hold the+ * process open for up to 5 s after the answer was done.+ */+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { runThink, type ThinkLLMClient } from '../src/core/think/index.ts';+import { routeTrajectory } from '../src/eval/longmemeval/trajectory-route.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({ database_url: '' });+ await engine.initSchema();+ await engine.putPage('people/marco-example', { title: 'Marco Example', type: 'person', compiled_truth: 'Marco is a founder.' });+ await engine.executeRaw(`+ INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, valid_from, source, source_session, claim_metric, claim_value)+ VALUES ('default', 'people/marco-example', 'role: engineer', 'fact', 'private', '2026-01-01T00:00:00Z', 'test', 's1', 'role', 1),+ ('default', 'people/marco-example', 'role: VP eng', 'fact', 'private', '2026-04-01T00:00:00Z', 'test', 's2', 'role', 2)+ `);+}, 60_000);++afterAll(async () => { await engine.disconnect(); });++/** Run `fn` while tracking 5000 ms timers; returns how many were left uncleared. */+async function uncleared5sTimers(fn: () => Promise<unknown>): Promise<{ created: number; live: number }> {+ const realSet = globalThis.setTimeout;+ const realClear = globalThis.clearTimeout;+ const live = new Set<unknown>();+ let created = 0;+ globalThis.setTimeout = ((cb: (...a: unknown[]) => void, ms?: number, ...rest: unknown[]) => {+ const h = realSet(cb, ms, ...rest);+ if (ms === 5000) { created++; live.add(h); }+ return h;+ }) as typeof setTimeout;+ globalThis.clearTimeout = ((h: Parameters<typeof clearTimeout>[0]) => {+ live.delete(h);+ return realClear(h);+ }) as typeof clearTimeout;+ try {+ await fn();+ } finally {+ globalThis.setTimeout = realSet;+ globalThis.clearTimeout = realClear;+ }+ for (const h of live) realClear(h as Parameters<typeof clearTimeout>[0]);+ return { created, live: live.size };+}++const stubClient: ThinkLLMClient = {+ create: async () => ({+ id: 'stub', type: 'message', role: 'assistant', model: 'stub', stop_reason: 'end_turn', stop_sequence: null,+ usage: { input_tokens: 1, output_tokens: 1, cache_creation_input_tokens: 0, cache_read_input_tokens: 0, server_tool_use: null, service_tier: null },+ content: [{ type: 'text', text: JSON.stringify({ answer: 'ok', citations: [], gaps: [] }) }],+ } as never),+};++describe('trajectory lookup deadlines are cleared once the lookup settles', () => {+ test('think', async () => {+ const r = await uncleared5sTimers(() => runThink(engine, { remote: false, question: 'When did Marco last switch jobs?', client: stubClient }));+ expect(r.created).toBeGreaterThan(0);+ expect(r.live).toBe(0);+ });++ test('LongMemEval trajectory route', async () => {+ let block = '';+ const r = await uncleared5sTimers(async () => {+ block = (await routeTrajectory(engine, 'When did Marco Example change roles?', ['people/marco-example'], 'knowledge_update' as any)).block;+ });+ expect(block).toContain('people/marco-example');+ expect(r.created).toBeGreaterThan(0);+ expect(r.live).toBe(0);+ });+});diff --git a/test/transcripts-retitle.test.ts b/test/transcripts-retitle.test.tsindex 8d76030848..3aaf6d9e0e 100644--- a/test/transcripts-retitle.test.ts+++ b/test/transcripts-retitle.test.ts@@ -76,3 +76,23 @@ describe('retitled conversation', () => {expect(await livePages()).toHaveLength(1);});});++describe('re-ingest keeps frontmatter it does not render (#5431)', () => {+ test('a key another tool added survives a changed session; collector keys are replaced', async () => {+ await runTranscriptsIngest(engine, { paths: [exportFile('a.json', 'Original title', false)], sourceId: 'default', format: 'chatgpt' });+ const [first] = await livePages();+ await engine.executeRaw(`UPDATE pages SET frontmatter = frontmatter || '{"reviewed": true}'::jsonb WHERE slug = $1`, [first.slug]);++ const b = exportFile('b.json', 'Renamed by user', true);+ const second = await runTranscriptsIngest(engine, { paths: [b], sourceId: 'default', format: 'chatgpt' });+ expect(second.pages.imported).toBe(1);+ const [row] = await engine.executeRaw<{ frontmatter: Record<string, unknown>; title: string; has_new: boolean }>(+ `SELECT frontmatter, title, compiled_truth LIKE '%FOLLOWUP-MARKER%' AS has_new FROM pages WHERE slug = $1`, [first.slug]);+ expect(row.frontmatter.reviewed).toBe(true);+ expect(row.title).toBe('Renamed by user');+ expect(row.has_new).toBe(true);++ const again = await runTranscriptsIngest(engine, { paths: [b], sourceId: 'default', format: 'chatgpt' });+ expect(again.pages).toMatchObject({ imported: 0, skipped: 1 });+ });+});diff --git a/test/traverse-walk-cap.test.ts b/test/traverse-walk-cap.test.tsnew file mode 100644index 0000000000..0894da087e--- /dev/null+++ b/test/traverse-walk-cap.test.ts@@ -0,0 +1,50 @@+/**+ * Read-path audit #20: the graph walks enumerate every simple path with a+ * per-path visited array, so a dense hub is combinatorial (a 12-page clique+ * at depth 5 took ~22 s for traversePaths 'both' and ~3.5 s for+ * traverseGraph). The walk is now pulled through a row cap and deduped to+ * (page, depth) before the edge join, so it stays bounded and the shallow+ * neighbourhood stays complete.+ */+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';++const N = 12;+let engine: PGLiteEngine;+beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ for (let i = 0; i < N; i++) await engine.putPage(`clique/n${String(i).padStart(2, '0')}`, { type: 'note', title: `n${i}`, compiled_truth: `node ${i}` } as any);+ const links = [];+ for (let i = 0; i < N; i++) for (let j = 0; j < N; j++) if (i !== j) {+ links.push({ from_slug: `clique/n${String(i).padStart(2, '0')}`, to_slug: `clique/n${String(j).padStart(2, '0')}`, link_type: 'mentions' });+ }+ await engine.addLinksBatch(links);+}, 120_000);+afterAll(async () => { await engine.disconnect(); });++describe('graph walks on a dense clique stay bounded', () => {+ test('traversePathsDetailed both @ depth 5', async () => {+ const t = performance.now();+ const r = await engine.traversePathsDetailed('clique/n00', { depth: 5, direction: 'both' });+ expect(performance.now() - t).toBeLessThan(5000);+ // Every edge of the clique is reachable at depth 1 or 2; none may be lost.+ const shallow = new Set(r.paths.filter(p => p.depth <= 2).map(p => `${p.from_slug}>${p.to_slug}`));+ expect(shallow.size).toBe(N * (N - 1));+ }, 30_000);++ test('traverseGraph @ depth 5', async () => {+ const t = performance.now();+ const nodes = await engine.traverseGraph('clique/n00', 5);+ expect(performance.now() - t).toBeLessThan(1500);+ expect(new Set(nodes.filter(n => n.depth <= 1).map(n => n.slug)).size).toBe(N);+ }, 30_000);++ test('an uncapped walk keeps its exact shape (depth-2 out walk)', async () => {+ const r = await engine.traversePathsDetailed('clique/n00', { depth: 2, direction: 'out' });+ expect(r.truncated).toBe(false);+ expect(r.paths.filter(p => p.depth === 1).length).toBe(N - 1);+ expect(r.paths.filter(p => p.depth === 2).length).toBe((N - 1) * (N - 1));+ }, 30_000);+});diff --git a/test/withdrawal-bounded-safety.test.ts b/test/withdrawal-bounded-safety.test.tsindex 39f1528178..17114001df 100644--- a/test/withdrawal-bounded-safety.test.ts+++ b/test/withdrawal-bounded-safety.test.ts@@ -17,6 +17,8 @@ import { submissionAuthority } from '../src/core/persistence/authority.ts';import { admitWrite, completeWrite } from '../src/core/persistence/journal.ts';import { runPersistenceEffects } from '../src/core/persistence/effects.ts';import { retryEmbeddingEffect } from '../src/core/persistence/effect-retry.ts';+import { upgradeWithdrawalEffect } from '../src/core/persistence/effect-targets.ts';+import type { PersistenceEffect } from '../src/core/persistence/effect-model.ts';import { rebuildPendingPageProjections } from '../src/core/page-state/projections.ts';import { importFromContent } from '../src/core/import-file.ts';import type { PreparedContentImport } from '../src/core/persistence/prepared-import.ts';@@ -281,27 +283,48 @@ for (const backend of testBackends()) describe(`bounded withdrawal ${backend}`,await engine.transaction(tx => completeWrite(tx, f.request, 'cancelled', {}));});- test('a 12001-page source refuses atomically before withdrawal or durable effects', async () => {+ test('a source over the old 12,000-page inventory ceiling withdraws a claim with a small affected set (#5674)', async () => {const f = await fixture();try {await engine.executeRaw(`INSERT INTO pages(source_id,slug,type,title,compiled_truth,timeline,frontmatter)- SELECT $1,'capacity-page-'||n,'note','Capacity control','Unrelated control text','','{}'::jsonb FROM generate_series(1,11998) n`, [f.sourceId]);+ SELECT $1,'capacity-page-'||n,'note','Capacity control',$2||' capacity row '||n,'','{}'::jsonb FROM generate_series(1,11998) n`,+ [f.sourceId, fence('an unrelated capacity claim')]);const pages = () => engine.executeRaw(`SELECT count(*)::int AS count,md5(string_agg(row_to_json(p)::text,'' ORDER BY id)) AS fingerprint- FROM pages p WHERE source_id=$1`, [f.sourceId]);- const facts = () => engine.executeRaw('SELECT row_to_json(f) AS fact FROM facts f WHERE source_id=$1 ORDER BY id', [f.sourceId]);- const chunks = () => engine.executeRaw(`SELECT row_to_json(c) AS chunk FROM content_chunks c JOIN pages p ON p.id=c.page_id- WHERE p.source_id=$1 ORDER BY c.id`, [f.sourceId]);- const beforePages = await pages(), beforeFacts = await facts(), beforeChunks = await chunks();- expect(beforePages[0].count).toBe(12001);- const beforeRequest = await engine.executeRaw('SELECT row_to_json(r) AS request FROM persistence_requests r WHERE id=$1::uuid', [f.request.id]);- await expect(f.withdraw()).rejects.toMatchObject({ code: 'withdrawal_capacity' });- expect(await pages()).toEqual(beforePages); expect(await facts()).toEqual(beforeFacts); expect(await chunks()).toEqual(beforeChunks);- expect(await engine.executeRaw('SELECT row_to_json(r) AS request FROM persistence_requests r WHERE id=$1::uuid', [f.request.id])).toEqual(beforeRequest);- expect(await engine.executeRaw('SELECT 1 FROM fact_withdrawals WHERE source_id=$1', [f.sourceId])).toEqual([]);- expect(await engine.executeRaw('SELECT 1 FROM persistence_effects WHERE request_id=$1::uuid', [f.request.id])).toEqual([]);+ FROM pages p WHERE source_id=$1 AND slug<>'affected'`, [f.sourceId]);+ const before = await pages();+ expect((await engine.executeRaw<{ count: number }>('SELECT count(*)::int AS count FROM pages WHERE source_id=$1', [f.sourceId]))[0].count).toBe(12001);+ expect((await f.withdraw()).pages.map(page => page.slug)).toEqual(['affected']);+ expect(await pages()).toEqual(before);+ const effects = await engine.executeRaw<{ data: { targets: Array<{ slug: string }> } }>('SELECT data FROM persistence_effects WHERE request_id=$1::uuid', [f.request.id]);+ expect(effects.map(effect => effect.data.targets.map(t => t.slug))).toEqual([['affected'], ['affected'], ['affected']]);++ await engine.executeRaw(`INSERT INTO fact_withdrawals(source_id,visibility,fact_hash)+ SELECT $1,'world',md5('unrelated withdrawal '||n)||md5(n::text) FROM generate_series(1,300) n`, [f.sourceId]);+ await engine.executeRaw(`UPDATE persistence_effects SET data='{"source_scan":true}'::jsonb WHERE request_id=$1::uuid`, [f.request.id]);+ const [legacy] = await engine.executeRaw<PersistenceEffect>("SELECT * FROM persistence_effects WHERE request_id=$1::uuid AND kind='embedding'", [f.request.id]);+ const upgraded = await upgradeWithdrawalEffect(engine, legacy, hostId, false);+ expect(upgraded.data.version).toBe(2);+ expect((upgraded.data.targets as Array<{ slug: string }>).map(t => t.slug)).toEqual(['affected']);+ expect(await pages()).toEqual(before);} finally { await engine.executeRaw('DELETE FROM sources WHERE id=$1', [f.sourceId]); }}, 120_000);+ test('a claim whose affected set exceeds the bound refuses loudly with the matched count, even in a small source', async () => {+ const sourceId = `capacity-report-${randomUUID()}`;+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [sourceId]);+ try {+ await engine.executeRaw(`INSERT INTO pages(source_id,slug,type,title,compiled_truth,timeline,frontmatter)+ SELECT $1,'page-'||lpad(n::text,3,'0'),'note','Synthetic capacity',$2,'','{}'::jsonb FROM generate_series(1,300) n`, [sourceId, fence('widely repeated sentinel')]);+ const fact = await engine.insertFact({ fact: 'widely repeated sentinel', source: 'synthetic', visibility: 'world' }, { source_id: sourceId });+ const error = await recordFactWithdrawal(engine, fact.id, sourceId).catch(e => e);+ expect(error).toMatchObject({ code: 'withdrawal_capacity' });+ expect(String(error.message)).toContain('more than 256');+ expect(String(error.suggestion)).toContain('page-001');+ expect(await engine.executeRaw('SELECT 1 FROM fact_withdrawals WHERE source_id=$1', [sourceId])).toEqual([]);+ expect(await engine.executeRaw('SELECT 1 FROM facts WHERE id=$1 AND expired_at IS NULL', [fact.id])).toHaveLength(1);+ } finally { await engine.executeRaw('DELETE FROM sources WHERE id=$1', [sourceId]); }+ });+test('orphan closing fences block withdrawal and prepared publication of matching claims', async () => {const f = await fixture(), malformed = fence('uses A | B').replace(FACTS_FENCE_BEGIN, '');await engine.putPage('orphan', { type: 'note', title: 'Orphan', compiled_truth: malformed }, { sourceId: f.sourceId });@@ -321,7 +344,7 @@ for (const backend of testBackends()) describe(`bounded withdrawal ${backend}`,test('dense malformed markers refuse during parsing before ledger mutation', async () => {const f = await fixture();- await engine.putPage('dense', { type: 'note', title: 'Dense', compiled_truth: FACTS_FENCE_BEGIN.repeat(16_385) }, { sourceId: f.sourceId });+ await engine.putPage('dense', { type: 'note', title: 'Dense', compiled_truth: `${FACTS_FENCE_BEGIN.repeat(16_385)}\n${fence('uses A | B')}` }, { sourceId: f.sourceId });await expect(f.withdraw()).rejects.toMatchObject({ code: 'withdrawal_capacity' });expect(await engine.executeRaw('SELECT 1 FROM fact_withdrawals WHERE source_id=$1', [f.sourceId])).toEqual([]);expect(await engine.executeRaw('SELECT expired_at FROM facts WHERE id=$1', [f.fact.id])).toEqual([{ expired_at: null }]);