Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

chore: delete dead scripts, orphan modules and zero-caller seams; document kept tools (W7 T7.1)

garrytan7b330faa57e3
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index f22459886f..ec7536542d 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -178,8 +178,8 @@ loop" below), silent fallback to recursive chunking in the compiled binary
manifest; coverage ratchets up from the `todo` rows) can actually fail by
running it against known-bad fixtures — a new `scripts/check-*` guard must be
registered in the manifest or the build fails. There is no `check:all` script; the
-trailing-newline, exports-count, and no-legacy-getconnection checks run in
-`verify` with everything else.
+trailing-newline and no-legacy-getconnection checks run in `verify` with
+everything else, and `test/public-exports.test.ts` owns the package export map.
### Writing tests that survive the parallel loop
diff --git a/docs/RELEASING.md b/docs/RELEASING.md
index 90c10ef28e..386708323b 100644
--- a/docs/RELEASING.md
+++ b/docs/RELEASING.md
@@ -534,6 +534,22 @@ flipping the repo-wide "send secrets to fork PRs" toggle, both broaden
secret distribution to every fork PR from that account or any fork. Moving
the branch keeps secret scope tight to just the one PR being shipped.
+## ClawHub bundle plugin publish (manual)
+
+`openclaw.plugin.json` makes this repository a ClawHub bundle plugin (see
+[docs/mcp/OPENCLAW.md](mcp/OPENCLAW.md)). Publishing a new version to ClawHub is
+a manual step outside `release.yml`, run from a clean checkout of the release
+tag by an owner with an authenticated `clawhub` CLI:
+
+```bash
+bun run prepublish:clawhub # bun run build:all: bin/gbrain-darwin-arm64 + bin/gbrain-linux-x64
+bun run publish:clawhub # clawhub package publish . --family bundle-plugin
+```
+
+`build:all` compiles only those two targets; the full binary matrix ships
+through the GitHub release job above. ClawHub users upgrade with
+`clawhub update gbrain`, which `gbrain upgrade` runs for ClawHub installs.
+
## Plugin dist tree (codex/claude lanes)
The committed `plugin/` and `plugin-variants/` trees embed the VERSION stamp
diff --git a/docs/TESTING.md b/docs/TESTING.md
index d7ade381df..690c69606a 100644
--- a/docs/TESTING.md
+++ b/docs/TESTING.md
@@ -400,6 +400,9 @@ Test command tiers, each with a clear scope:
| `bun run test:serial` | Just the `*.serial.test.ts` set (cross-file-contention quarantine; one bun process per file for true module-registry isolation), run through a POOL of concurrent per-file processes — the isolation is per-process, not per-machine. Dispatch is heaviest-first (LPT) from the advisory `scripts/serial-weights.json` (seconds; mined from the `.context/serial-durations.txt` table each run banks; absent/corrupt weights fall back to discovery order, absent keys to the corpus p75 — scheduling only, never correctness; LPT order + the corrupt-weights fail-soft are pinned by `test/scripts/run-serial-pool.test.ts`). Pool defaults to `min(detect_cpus, 4)` then memory-adapts (same doctrine as the parallel runner); a small growth-guarded set of files (machine-global state or contention-critical timing — see the justified `EXCLUSIVE_FILES` list in `scripts/run-serial-tests.sh`, capped at 3 by `test/scripts/serial-files.test.ts`) runs on a sequential EXCLUSIVE lane after the pool. Per-test timeout 120s (pooled contention headroom); each pooled file is wall-clock-killed at 300s (`timeout -k`, exit-hang containment). `SHARD=N/M` partitions pooled files by duration; the three exclusive files run only on shard 1. Unset runs the complete corpus. Routing variables are cleared before tests start, so nested runners remain independent. Externally-killed files (exit 143/137 or a missing exit sentinel — sibling-workspace cleanup, memory jetsam) get ONE sequential rescue re-run, mirroring the parallel runner's doctrine: phantoms stay green with a rescue note, real failures stay red. Prints per-file PASS lines plus a top-10 slowest-files list. Knobs: `GBRAIN_SERIAL_POOL=N` (explicit pool width — bypasses the memory clamp; `1` restores fully-sequential), `GBRAIN_SERIAL_FILE_TIMEOUT`. | a few minutes for all ~220 files at pool=4 | Debugging quarantined files; CI's serial-tests job. |
| `bun run test:e2e` | Real Postgres E2E. Requires Docker + `DATABASE_URL`. Sequential within a shard; `SHARD=N/M` fans out against separate databases (ci-local runs 4 containers). Activates the PGLite snapshot like every other runner (per-file cold-path opt-outs where the test asserts the path TO post-initSchema state), exporting it as an ABSOLUTE path so CLI children spawned with varying cwd still find it. | ~5-10min | Pre-ship; nightly. |
| `bun run test:compile-smoke` | Self-update integrity verify under a REAL `bun build --compile` binary, offline; also runs unconditionally in the serial lane. The unit suite mocks the network seams; this proves the dependency-free crypto/base64/JSON verify path survives compilation — the failure mode `sigstore-js` would have hit. | under 1s (one small compile) | When touching `src/core/binary-self-update.ts`; pre-ship on self-update changes. |
+| `bun run test:agent-voice` | The agent-voice recipe's vitest unit suite (`recipes/agent-voice/tests/unit`), via `scripts/test-agent-voice.sh`: installs pinned vitest + ws into a temporary prefix and links it as the recipe's `node_modules` for the run. Needs node + npm and registry access. CI runs it in test.yml's verify job. | ~10s | When touching `recipes/agent-voice/`. |
+| `scripts/ship-remote-tests.sh` | Pushes the branch, dispatches `test.yml` (or `--workflow`) on GitHub's runners for that branch or `--ref`, and waits with `gh run watch --exit-status`, so its exit code is the run's. Needs an authenticated `gh`; unlike `ci:ubicloud` it needs no Ubicloud credential and runs the workflow's own job inventory. | one CI run | Offloading the suite from a saturated local machine. |
+| `bun run test:profile` | Reads a captured `bun test` log on stdin and prints the N slowest tests (`-n N`, default 10): `bun test 2>&1 \| bun run test:profile`. | seconds | Finding slow tests to fix or demote to `*.slow.test.ts`. |
| `bun run test:admin` | Pinned Playwright Chromium tests for the production embedded admin UI, served with an isolated temporary home/cwd and in-memory PGLite. Exercises owner login, OAuth consent, registration, setup, and lifecycle actions. | seconds-to-minutes | When touching the admin browser flow; required `admin-browser` CI job. |
For the admin browser lane, install frozen dependencies in the repository and
@@ -412,7 +415,7 @@ activation inside a native vendor harness.
There is no `check:all` script: a second, hand-synced guard registry would
drift from `verify`, leaving checks that never run anywhere. The `CHECKS`
array in `scripts/run-verify-parallel.sh` is the single execution list
-(including `check:newlines`, `check:exports-count`,
+(including `check:newlines`,
`check:no-legacy-getconnection`). The guard REGISTRY is `scripts/guards-manifest.tsv` (see "Guard registry and
self-test" below).
diff --git a/docs/architecture/key-files/commands-3.md b/docs/architecture/key-files/commands-3.md
index a3c29f2dfb..9efcf4e757 100644
--- a/docs/architecture/key-files/commands-3.md
+++ b/docs/architecture/key-files/commands-3.md
@@ -19,7 +19,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/eval-replay.ts` — contributor-facing replay tool. Reads NDJSON from `gbrain eval export`, re-runs each captured `query` / `search` op against the current brain, computes set-Jaccard@k between captured + current `retrieved_slugs`, top-1 stability rate, and latency Δ. Stable JSON shape (`schema_version: 1`) for CI gating; human mode prints a regression table. Pure Bun, zero new deps. The dev-loop half of BrainBench-Real. See `docs/eval-bench.md`. `parseNdjson` skips lines where `_kind === 'baseline_metadata'` so `gbrain bench publish` baselines parse cleanly without the metadata header polluting row counts. Exports `replayCore(engine, opts): Promise<{summary, results}>` + `ReplaySummary` type so `gbrain eval gate` calls replay in-process (NOT subprocess — avoids gbrain-version-drift for source-tree CI). CLI `runEvalReplay` wraps `replayCore`. D2: under the `--json` guard the result is one compact NDJSON line (`writeJsonLine`; unguarded callers keep the pretty document) and failures end with a `{status:'error'}` envelope line (`invalid_params` exit 2, `not_found`, `parse_error`). `eval gate` follows the same contract; a breached gate is the result line then a `gate_failed` error line (exit 1).
-- `src/commands/eval-suspected-contradictions.ts` + `src/core/eval-contradictions/{judge,runner,types,date-filter,cost-tracker,cache,severity-classify,cross-source,trends,calibration,judge-errors,auto-supersession,fixture-redact}.ts` — `gbrain eval suspected-contradictions [run|trend|review]`. Probe samples top-K retrieval pairs per query (cross-slug + intra-page chunk-vs-take), date pre-filters (3-rule layered — same-paragraph-dual-date overrides separation rule), LLM judge (query-conditioned; UTF-8-safe truncation; confidence-floor double-enforcement; resolution_kind output drives paste-ready commands), persistent cache keyed on `(chunk_a_hash, chunk_b_hash, model_id, prompt_version, truncation_policy)` (prompt edits cleanly invalidate prior verdicts), Wilson 95% CI calibration on the headline percentage with `small_sample_note` when n<30, judge_errors as first-class typed counters (parse_fail/refusal/timeout/http_5xx/unknown — avoids bias from silent skip), trend writes to `eval_contradictions_runs`, source-tier breakdown reuses `DEFAULT_SOURCE_BOOSTS` prefix logic, deterministic sampling (combined_score DESC + lex tiebreaker for stable cache hit-rate). Hermetic via `judgeFn` + `searchFn` DI in the runner; never touches the real gateway in tests. Engine surface: `BrainEngine.listActiveTakesForPages` (batched), `writeContradictionsRun` + `loadContradictionsTrend`, `getContradictionCacheEntry` + `putContradictionCacheEntry` + `sweepContradictionCache`. Schema migrations v51 + v52. Pair members carry only content effective dates; a `fallback` date becomes null (`(date unknown)`). MCP op `find_contradictions` (read scope, NOT localOnly, NOT in subagent allowlist — user-initiated only; stored reports answer only trusted local callers without a user-selected source, keyed on `ctx.localSourceImplicit` from `makeContext`). Doctor check surfaces high-severity findings with paste-ready resolution commands; synthesize phase pre-fetches the latest probe's top-5-by-severity findings and threads them into `buildSynthesisPrompt` as an informational block. Architecture doc: `docs/contradictions.md`.
+- `src/commands/eval-suspected-contradictions.ts` + `src/core/eval-contradictions/{judge,runner,types,date-filter,cost-tracker,cache,severity-classify,cross-source,trends,calibration,judge-errors,auto-supersession}.ts` — `gbrain eval suspected-contradictions [run|trend|review]`. Probe samples top-K retrieval pairs per query (cross-slug + intra-page chunk-vs-take), date pre-filters (3-rule layered — same-paragraph-dual-date overrides separation rule), LLM judge (query-conditioned; UTF-8-safe truncation; confidence-floor double-enforcement; resolution_kind output drives paste-ready commands), persistent cache keyed on `(chunk_a_hash, chunk_b_hash, model_id, prompt_version, truncation_policy)` (prompt edits cleanly invalidate prior verdicts), Wilson 95% CI calibration on the headline percentage with `small_sample_note` when n<30, judge_errors as first-class typed counters (parse_fail/refusal/timeout/http_5xx/unknown — avoids bias from silent skip), trend writes to `eval_contradictions_runs`, source-tier breakdown reuses `DEFAULT_SOURCE_BOOSTS` prefix logic, deterministic sampling (combined_score DESC + lex tiebreaker for stable cache hit-rate). Hermetic via `judgeFn` + `searchFn` DI in the runner; never touches the real gateway in tests. Engine surface: `BrainEngine.listActiveTakesForPages` (batched), `writeContradictionsRun` + `loadContradictionsTrend`, `getContradictionCacheEntry` + `putContradictionCacheEntry` + `sweepContradictionCache`. Schema migrations v51 + v52. Pair members carry only content effective dates; a `fallback` date becomes null (`(date unknown)`). MCP op `find_contradictions` (read scope, NOT localOnly, NOT in subagent allowlist — user-initiated only; stored reports answer only trusted local callers without a user-selected source, keyed on `ctx.localSourceImplicit` from `makeContext`). Doctor check surfaces high-severity findings with paste-ready resolution commands; synthesize phase pre-fetches the latest probe's top-5-by-severity findings and threads them into `buildSynthesisPrompt` as an informational block. Architecture doc: `docs/contradictions.md`.
- `src/commands/eval-trajectory.ts` + `src/commands/founder-scorecard.ts` + `src/core/trajectory.ts` — temporal trajectory + founder scorecard. `gbrain eval trajectory <entity>` shows the chronological typed-claim history (mrr/arr/team_size/etc) with regressions auto-flagged inline; `gbrain founder scorecard <entity>` rolls up claim_accuracy / consistency / growth_trajectory / red_flags into one JSON. Pure-function math in `trajectory.ts`: `detectRegressions(points, threshold)` walks consecutive metric-value pairs per metric (10% drop default, env override `GBRAIN_TRAJECTORY_REGRESSION_THRESHOLD`); `computeDriftScore(points)` returns `1 - mean(cosine(emb[i], emb[i-1]))` over existing embeddings (null when <3 embedded points). Backed by `BrainEngine.findTrajectory(opts)` — both Postgres and PGLite, single SQL query that selects the NEWEST `limit` points (`ORDER BY valid_from DESC, id DESC`) and returns them chronologically, so a capped series keeps its latest value. Source-scoped via the `sourceId` scalar / `sourceIds` array dual pattern; visibility-filtered for remote callers. MCP op `find_trajectory` (read scope, NOT localOnly) registered after `find_experts`. Migration v67 adds optional typed-claim columns (`claim_metric`, `claim_value`, `claim_unit`, `claim_period`) + a partial index on `(entity_slug, claim_metric, valid_from) WHERE claim_metric IS NOT NULL`. Fence widens from 10 to 14 cells when any row has typed data; renderer stays at 10 cells when none do (no churn diff on existing fences). Metric labels normalize to lowercase snake_case via `normalizeMetricLabel` (15-entry seed map). The `consolidate` cycle phase does semantic upsert keyed on `(page_id, claim, since_date)` (so re-running the cycle after `extract_facts` clears `consolidated_at` cannot append duplicates via `MAX(row_num)+1`) and writes chronological `valid_until` on each cluster's older facts. The `extract_facts` cycle phase batch-embeds via `gateway.embed()` before insert AND threads `pages.effective_date` as the `pageEffectiveDate` fallback for `valid_from` (precedence: fence-row > pageEffectiveDate > now()). The contradiction probe MUST NOT write `valid_until` — grep guard at `test/eval-contradictions/no-valid-until-write.test.ts`. Haiku extraction lives in `src/core/facts/extract.ts` (not the `extract-facts.ts` cycle phase); its output cap is config `facts.extraction_max_tokens` (default 4000), a `stopReason: 'length'` response retries once at 2× the cap, and persistent truncation warns loudly on stderr instead of silently extracting zero facts. Mixed extractor arrays salvage valid candidates and warn with the dropped malformed count; all-malformed output still fails retryably, while an explicitly empty facts array remains a successful empty result. `pageEffectiveDate` is OPTIONAL because `fence-write.ts` callers have no Page object. Migration v89 adds a nullable `event_type TEXT` column on `facts` so the substrate carries event-shaped rows (`event_type='meeting'` / `'job_change'` / `'location_change'`) alongside metric rows. `TrajectoryPoint.event_type: string | null` projected by both engines. `TrajectoryOpts.kind?: 'metric' | 'event' | 'all'` filter (default `'all'`); `founder-scorecard` + `eval-trajectory` pass `kind: 'metric'` explicitly. Back-compat pinned by `test/regressions/v0_40_2_0-trajectory-backcompat.test.ts` (byte-identical `computeFounderScorecard` + `computeTrajectoryStats` with and without event rows); engine parity in `test/engine-parity-event-type.test.ts`.
diff --git a/docs/architecture/key-files/core-services-1.md b/docs/architecture/key-files/core-services-1.md
index e932344b60..b743ff3442 100644
--- a/docs/architecture/key-files/core-services-1.md
+++ b/docs/architecture/key-files/core-services-1.md
@@ -31,15 +31,13 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/chronicle/{contract,eligibility,config,reasons,ledger,ledger-stats,execute,publish,backfill,job,upgrade-notice,extract-events,ontology,narrative}.ts` + `src/core/cycle/chronicle.ts` + `src/eval/chronicle/harness.ts` + `src/commands/eval-chronicle.ts` — Life Chronicle: the temporal spine. `contract.ts` holds the ledger columns, the extractor version, the phase bounds and the phase result details. `reasons.ts` is the one reason table (`CHRONICLE_REASONS`: stage, meaning, stored fix Action with argv/preview_argv/consent/actor, never a stored `next`; `auto_chronicle_off` has no fix because it is off by choice) and builds the `chronicle_backstop` receipt field (`{pending:'next_cycle', daily_remaining}` or `{skipped, stage, why, fix}`, omitted for pages that are not chronicle-shaped); `docs/guides/life-chronicle.md` renders its table from it. `eligibility.isChronicleEligible` is the one eligibility function (meeting/conversation/calendar-event + directory rescue; diary and event pages NEVER eligible — privacy + anti-loop); with a time policy it also applies the invite end (`not_yet_happened`), the recency window on the page's own date (an authored `effective_date`, else frontmatter `date`/`start`; a `fallback` date counts as undated) and the settle window. `config.ts` owns the switch and knobs: `autoChronicleSetting` reads `auto_chronicle` as on when unset, on/off for true/false words, and `invalid` (off) for any other word; `chronicleSettings` reads `chronicle.job_budget_usd`/`auto_daily_limit`/`auto_recent_days`/`auto_settle_seconds`/`judge_max_tokens` with ranges (`CHRONICLE_NUMERIC_KEYS`, enforced by `config set`; a malformed stored row falls back and is listed in `invalid`) and `chronicle.activated_at` (stamped by the first write decision or phase run; earlier revisions are history); `autoChronicleNeedsAcknowledgement` is true while on and `chronicle.default_on_acknowledged` is unset (stamped by `config set auto_chronicle`). The opt-out is `gbrain config set auto_chronicle false` everywhere. `ledger.ts` owns `chronicle_page_state` (one row per source/page/content hash/extractor version: state, reason, trigger, deciding writer and request, `no_extract`, attempts, `next_attempt_at`, cost/unpriced, event slugs and hashes): `recordChronicleDecision` runs inside every coordinated publication that imports a page (from `queuePublicationEffects`), applies the shared writer-confinement predicate, `--no-extract`, the opt-out and eligibility, and puts `chronicle_backstop` on the outcome through `reasons.ts`; `reserveChronicleSlot` is the rolling 24 h reservation under a transaction advisory lock. `ledger-stats.ts` rolls up the ledger and reservations for doctor and the advisor. `upgrade-notice.ts` is the one-shot post-upgrade notice (`chronicle.default_on_notice_shown`). The global `chronicle` cycle phase (`cycle/chronicle.ts`) supersedes rows whose content is no longer live, discovers pages changed since activation with no row (unmanaged brains decide there; managed ones record `no_write_decision`), and executes settled rows round-robin across sources (≤50 judged items and a wall-time bound per run; automatic rows only while `auto_chronicle` is on, backfill rows always); no chat provider → no calls; the extract_atoms cost gate refuses an explicit cap on an unpriced model. `execute.ts` runs one row: live-content check, time rules, the reservation (automatic rows; attempts count), the judge in a `chronicle:<trigger>` BudgetTracker scope with the per-page cap and an explicit post-call cap check, failure classes (chat_error/budget → failed with backoff, no provider/no_pricing → failed until config changes, refused → skipped, only a parsed `[]` is `no_events`). `publish.ts` publishes one generation against the pinned depth snapshot: each event write re-validates the depth revision, content hash, source incarnation, privacy and the deciding writer's grant (events also read as private when their `event.depth` origin is private by field or declared lineage, or missing, `search/private-visibility.ts`) (`managed_maintenance_chronicle_event`/`_retire` intents on managed brains, one transaction per event otherwise), stamps the depth's visibility, never overwrites an operator-edited event (live hash not in the ledger) or resurrects an operator-deleted one, and after a complete generation retires the previous generation's owned events (`retired_by: life-chronicle`; restored when produced again). `extract-events.runChronicleExtract` is the direct-caller body over the same snapshot and publication path: deterministic when/who, injectable judge (default = chat gateway; output cap 4000 tokens by default, operator override `chronicle.judge_max_tokens`), an ALL-or-nothing parse barrier (`isValidProposal` requires a real parseable date), content-addressed `life/events/` pages + a `timeline_entries` projection. An unusable judge response is never recorded as `no_events`: truncation, unparseable output, a provider error and a refusal surface as `judge_truncated`/`judge_parse_failed`/`judge_chat_error`/`judge_refused`. `backfill.ts` (`chronicle_backfill`) queues `trigger='backfill'` ledger rows, exempt from the daily limit and recency (unless `--recent`), across types and rescue prefixes under one global `--limit`; `--since` is the update date, `--dated-since` the page date; a dry run reports `estimated_usd` and skip reasons; a live run needs `--yes`; content already extracted or queued is never re-queued, even after `gbrain jobs prune`. `job.ts` drains `chronicle_extract` jobs from older releases through the same executor. `ontology.ts` carries the deterministic pieces of the bi-temporal per-entity ontology that RIDES THE `facts` TABLE (migration v122 adds `dimension`/`value`/`value_hash`/`dim_status`): `valueHash` (normalized, timestamp-free; the v188 dedup index adds the stint's `valid_from`, so a crash-retry conflicts while a same-provenance return to an earlier value records a new interval), `normalizeDimension` (seed alias lexicon), `isNovelDimension` (novel → quarantined, excluded from resolution/context until confirmed). The engine methods (`mergeOntologyFact` — corroborate on same value (noop when the same provenance already observed it during the current stint), forward-supersede via `valid_until`+`superseded_by` on a new value, backdated conflicts kept + flagged; `getOntology` with `--asof` valid-time travel; `discoverOntologyDimensions`; `findOntologyConflicts` — currently-open rows only) live in BOTH engines; both engines are on the R8 `valid_until` write allow-list (engine-layer, `dimension IS NOT NULL` rows only). Chronicle reads (`getTimelineForDate`/`getSince`/`getLastSeen`/`getOnThisDay`) JOIN the depth page (`deleted_at IS NULL`), hide soft-deleted event projections at READ time, and order by event `effective_date` for intra-day sequence. Ops: `chronicle_day`/`chronicle_since`/`chronicle_last_seen`/`chronicle_on_this_day`/`ontology_*`/`volunteer_chronicle` (agent orientation via `src/core/context/chronicle-context.ts`)/`chronicle_backfill` (admin, localOnly). Diary privacy: fail-closed for `ctx.remote !== false` callers — diary-sourced ontology + conflict values are redacted, the four timeline read ops (`chronicle_day`/`chronicle_since`/`chronicle_on_this_day` + `volunteer_chronicle`'s `recent_timeline`) drop rows whose depth page, event page, or `source` provenance lives under `life/diary/`, and `chronicle_last_seen` answers the never-seen shape (`last_date`/`last_event_slug`/`days_ago` all null) when the latest sighting is diary-sourced or a diary page is queried as the entity. Remote callers read only `visibility = 'world'` observations, like recall: `getOntology`/`findOntologyConflicts` take a `visibility` filter applied before resolution and the conflict HAVING. `ontology_propose` commits through `coordinatedDatabaseWrite` on a managed brain. Page visibility rides the same policy: `ontology_get`/`ontology_conflicts`/`volunteer_chronicle`'s ontologies resolve through `readPolicyOpts`, and both engines' `getOntology`/`findOntologyConflicts` apply `privateProvenanceFilterFragment` (an observation whose provenance page, looked up in the fact's own source, is `visibility: private` is dropped BEFORE per-dimension resolution and before the conflict HAVING, so an untrusted caller resolves the newest value they may see rather than a private value or a hole). The chronicle reads' event-page LEFT JOIN carries the caller's source scope in BOTH engines, so a scoped read can't surface another source's event pages through the join. Search: `applyChronicleTypeBoost` in `search/hybrid.ts` (bounded [1.0,1.25], fires only inside the `recency !== 'off'` post-fusion branch → non-temporal search bit-for-bit unchanged). Advisor collector `collect-chronicle.ts` (conflicts; coverage gap with a scoped `chronicle-backfill --since <date> --limit 50 --dry-run`; `auto_chronicle_default_on` ask_user until acknowledged; `auto_chronicle_invalid`; `chronicle_chat_unavailable`; `chronicle_extraction_failing`; `chronicle_daily_limit`); doctor `chronicle_projection_health` and `auto_chronicle` (`checks/auto-chronicle.ts`; BRAIN category). Eval: `gbrain eval chronicle` — deterministic, own in-memory PGLite, 6 gold tasks (day order, last-seen, supersession, asof, conflict, isolation), exit 0 iff 6/6. Tests: `test/chronicle-*.test.ts` (automatic path: `chronicle-auto-{decision,phase,unmanaged}`, `chronicle-event-privacy`, `chronicle-backfill`, `chronicle-reasons-5876`; Postgres arms in `test/e2e/chronicle-*-postgres.test.ts`), `test/eval-chronicle.test.ts`, `test/auto-chronicle-surfaces-5876.test.ts`.
-- `src/core/chunkers/` — 3-tier chunking (recursive, semantic, LLM-guided). `code.ts` is a tree-sitter-based semantic chunker for 30 languages (plus SQL via DerekStride/tree-sitter-sql) with embedded-asset WASMs (`src/assets/wasm/`), `@dqbd/tiktoken` cl100k_base tokenizer, small-sibling merging. `CHUNKER_VERSION` is folded into `importCodeFile`'s `content_hash` so chunker shape changes force clean re-chunks across releases. `extractSymbolName` has an inline SQL branch (`extractSqlSymbolName`) diving through DerekStride's `statement` wrapper into the inner DDL child (`create_table`/`create_function`/`create_view`/`create_index`/`create_procedure`/`create_type`/`create_schema`/`create_database`/`create_trigger`/`alter_table`/`alter_view`) and extracting the target identifier via the `name` field with identifier-shaped fallback; DML kinds (`select`/`insert`/`update`/`delete`/`merge`/`with`) deliberately return null so chunks emit unnamed (code-def is a DDL signal). `normalizeSymbolType` has parallel SQL branches mapping `create_table → 'table'`, `create_view → 'view'`, etc. `DEF_TYPES` (owned by `src/core/chunkers/def-types.ts`, re-exported by `src/commands/code-def.ts` — see that entry) carries the SQL kinds (`'table' | 'view' | 'index' | 'procedure' | 'schema' | 'database' | 'trigger'`) so the new chunks surface in `gbrain code-def <name>` queries.
+- `src/core/chunkers/` — markdown chunking (`recursive.ts`) and code chunking. `code.ts` is a tree-sitter-based semantic chunker for 30 languages (plus SQL via DerekStride/tree-sitter-sql) with embedded-asset WASMs (`src/assets/wasm/`), `@dqbd/tiktoken` cl100k_base tokenizer, small-sibling merging. `CHUNKER_VERSION` is folded into `importCodeFile`'s `content_hash` so chunker shape changes force clean re-chunks across releases. `extractSymbolName` has an inline SQL branch (`extractSqlSymbolName`) diving through DerekStride's `statement` wrapper into the inner DDL child (`create_table`/`create_function`/`create_view`/`create_index`/`create_procedure`/`create_type`/`create_schema`/`create_database`/`create_trigger`/`alter_table`/`alter_view`) and extracting the target identifier via the `name` field with identifier-shaped fallback; DML kinds (`select`/`insert`/`update`/`delete`/`merge`/`with`) deliberately return null so chunks emit unnamed (code-def is a DDL signal). `normalizeSymbolType` has parallel SQL branches mapping `create_table → 'table'`, `create_view → 'view'`, etc. `DEF_TYPES` (owned by `src/core/chunkers/def-types.ts`, re-exported by `src/commands/code-def.ts` — see that entry) carries the SQL kinds (`'table' | 'view' | 'index' | 'procedure' | 'schema' | 'database' | 'trigger'`) so the new chunks surface in `gbrain code-def <name>` queries.
- `src/core/chunkers/def-types.ts` — `DEF_TYPES`: the ONE list of definition-shaped normalized (post-`normalizeSymbolType`) symbol types, shared by `gbrain code-def`'s lookup allowlist (`src/commands/code-def.ts` re-exports it) and the code chunker's small-sibling merge guard so the two can't drift — a symbol type code-def can resolve never has its `symbol_name` erased by merging a small definition into a neighbor. Includes the fallthrough forms `normalizeSymbolType` emits verbatim for tree-sitter node types it doesn't canonicalize (`'method declaration'`, `'struct specifier'`, `'record declaration'`, …) — most of an OO codebase's symbols arrive in those forms. Pinned by `test/chunkers/code-merge-defs.test.ts`.
-- `src/core/chunkers/llm.ts` — LLM-guided chunking: pre-splits into 128-word candidates via the recursive chunker, then asks a Haiku-class model "where does the FIRST topic shift occur?" per window.
- `src/core/chunkers/recursive.ts` — base chunker: 300-word chunks, 50-word sentence-aware overlap, 5-level delimiter hierarchy. Applies `sanitizeRemoteBody` and then `credentialSafeProjection` (`src/core/credential-projection.ts`) before splitting, so only world Facts and ordinary prose enter retrieval text and private keys enter only as `<REDACTED:private_key_pem>`; all Takes and malformed protected sections are omitted. Non-overlapping portions reassemble to that sanitized input. The overlap extractor counts chars (not whitespace tokens) for CJK-dominant chunks — same unit as `countWords` — and aligns to `。!?` or a whitespace-followed ASCII `.!?`; the L4 char-slice fallback advances through `safeSplitIndex` so astral pairs (emoji, non-BMP CJK) are never halved. Both are gated on `isCJKDominant`, so English output is byte-identical (pinned by `test/chunkers/recursive-cjk-overlap.test.ts`). The markdown chunker version records the current index format.
-- `src/core/chunkers/semantic.ts` — embedding-based topic-boundary detection: embeds sentences, computes cosine-similarity valleys, smooths with a Savitzky-Golay filter (5-window, 3rd-order polynomial) to find chunk boundaries. Sanitizes the full body before sentence embedding and boundary detection.
- `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. A `calls` edge the extractor flagged `memberCall` (an untyped receiver, `obj.m()` emitted as bare `m`; persisted as `edge_metadata.member_call`) is never resolved within the file, since a member call cannot invoke a same-file top-level function (gbrain-evals N13-8, `test/code-intel/n13-edge-resolution.test.ts`); existing code pages pick this up when they re-import (`gbrain reindex-code`).
diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.md
index bbfed08f5c..2fb46b5f19 100644
--- a/docs/architecture/key-files/core-services-2.md
+++ b/docs/architecture/key-files/core-services-2.md
@@ -56,8 +56,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/page-state/version-types.ts` — complete canonical version contract with nullable legacy fields, re-exported by `types.ts` for existing callers. `page-state/versions.ts` records deletion, timeline, tags and originating revision in the page publication transaction.
-- `src/core/postgres-engine/` + `src/core/pglite-engine/` — per-engine module directories for code that is genuinely dialect-specific. Migrated storage domains (the `migrated` rows of `scripts/engine-sql-baseline.tsv`) do not live here: their SQL exists once in `src/core/engine-sql/` (see that entry in engines-2.md). What remains: `pglite-engine/checkpoint-guard.ts`, `pglite-engine/code-edges.ts` (PGLite's `getEdgesByChunk`, whose master SQL behaves differently from Postgres's: one UNION ALL under a shared LIMIT; listed in `docs/designs/refactor-wave-1/w1-inventory.md`), `postgres-engine/cancellation.ts`, `postgres-engine/init-schema-lock.ts` and `postgres-engine/forward-reference-bootstrap.ts` (a façade over the shared `engine-sql/bootstrap.ts`). Façades import these modules statically (engine-live no-runtime-dynamic-import rule) and keep their full public surface.
+- `src/core/postgres-engine/` + `src/core/pglite-engine/` — per-engine module directories for code that is genuinely dialect-specific. Migrated storage domains (the `migrated` rows of `scripts/engine-sql-baseline.tsv`) do not live here: their SQL exists once in `src/core/engine-sql/` (see that entry in engines-2.md). What remains: `pglite-engine/checkpoint-guard.ts`, `pglite-engine/code-edges.ts` (PGLite's `getEdgesByChunk`, whose master SQL behaves differently from Postgres's: one UNION ALL under a shared LIMIT; listed in `docs/designs/refactor-wave-1/w1-inventory.md`), `postgres-engine/cancellation.ts` and `postgres-engine/init-schema-lock.ts`; the forward-reference bootstrap lives once in `engine-sql/bootstrap.ts` for both engines. Façades import these modules statically (engine-live no-runtime-dynamic-import rule) and keep their full public surface.
-- `src/core/postgres-engine/forward-reference-bootstrap.ts` — façade re-exporting `applyPostgresForwardReferenceBootstrap(conn)` from `src/core/engine-sql/bootstrap.ts` (refactor wave 1, E1); runtime callers import the engine-sql module, the façade keeps the old import path working.
- `src/core/progressive-batch/` — shared ramp-up + cost-cap + verification primitive (trial 10 → ramp 100 → ramp 500 → full, with verification at each stage), with verifier+policy injection (callers describe HOW TO MEASURE SUCCESS, not WHEN TO WAIT FOR CTRL-C). Modules: `types.ts` (Stage, StageVerdict, AbortReason, discriminated `Verifier` union `OutputCountVerifier | IdempotentMutationVerifier | NoopVerifier`, Policy, StageReport), `orchestrator.ts` (`runProgressiveBatch(items, verifier, policy, runner)` — reads `getCurrentBudgetTracker()` ahead of `Policy.maxCostUsd` fail-closed; null both ways triggers `abort_cost_cap reason='no_budget_safety_net'`), `audit.ts` (ISO-week JSONL at `~/.gbrain/audit/progressive-batch-YYYY-Www.jsonl` via the shared `audit-writer` primitive), `stage-report.ts` (ASCII formatter for the default `Policy.onStageReport`). Env knobs: `GBRAIN_PROGRESSIVE_BATCH_DISABLED=1`, `GBRAIN_PROGRESSIVE_BATCH_AUTO=1` (skip Ctrl-C grace), `GBRAIN_PROGRESSIVE_BATCH_STAGES=10,100,500`. Sites that "jump straight to full" stay that way by default; ramp is opt-in per-site via `Policy.interactiveAbortMs > 0`. Pinned by `test/progressive-batch/orchestrator.test.ts` (35 cases, every verdict path).
diff --git a/docs/architecture/key-files/engines-1.md b/docs/architecture/key-files/engines-1.md
index 450ccf0dee..d818f1e4b5 100644
--- a/docs/architecture/key-files/engines-1.md
+++ b/docs/architecture/key-files/engines-1.md
@@ -29,7 +29,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/engine.ts` — Pluggable engine interface (BrainEngine). `clampSearchLimit(limit, default, cap)` takes an explicit cap so per-operation caps can be tighter than `MAX_SEARCH_LIMIT`. Exports `LinkBatchInput`/`TimelineBatchInput` for the bulk-insert API (`addLinksBatch`/`addTimelineEntriesBatch`). `readonly kind: 'postgres' | 'pglite'` discriminator lets `src/core/migrate.ts` and others branch without `instanceof` + dynamic imports. Methods: `batchLoadEmotionalInputs(slugs?)` (CTE-shaped read with per-table aggregates so page × N tags × M takes never produces N×M rows), `setEmotionalWeightBatch(rows)` (`UPDATE FROM unnest($1::text[],$2::text[],$3::real[])` composite-keyed on `(slug, source_id)`), `getRecentSalience(opts)`, `findAnomalies(opts)`. `PageFilters` has `sort?: 'updated_desc'|'updated_asc'|'created_desc'|'slug'` + `PAGE_SORT_SQL` whitelist consumed by both engines. `listAllPageRefs(): Promise<Array<{slug, source_id}>>` ordered by `(source_id, slug)` — cheap cross-source enumeration instead of a `getAllSlugs()→getPage(slug)` N+1 (which would silently default to `source_id='default'`); parity across postgres-engine.ts + pglite-engine.ts; Pinned by `test/e2e/multi-source-bug-class.test.ts`. `SearchOpts`+`PageFilters` add `sourceIds?: string[]` (federated read axis; both engines apply `WHERE source_id = ANY($N::text[])` when set, preserve scalar `sourceId` fast path when unset); `traverseGraph(slug, depth, opts?)` and `traversePaths(slug, opts?)` accept `opts.sourceId`/`opts.sourceIds`. `traversePathsDetailed(slug, opts?)` returns `{ paths: GraphPath[], truncated }` — the final SELECT of the path-enumerating recursive CTE is bounded at `TRAVERSE_PATH_ROW_CAP + 1` rows on both engines (the probe row signals overflow; `ORDER BY depth` means the deepest edges are dropped, so a truncated result is still the complete shallow neighbourhood; the cap counts raw rows before the in-memory edge dedup, so `paths.length` alone cannot reveal truncation) and `traversePaths` is its `.paths` projection. Each `GraphPath` carries `from_source_id`/`to_source_id` and the edge dedup keys on page ids; each `traverseGraph` `GraphNode` carries `source_id` (DISTINCT per page), so the same slug in two sources stays two edges or nodes. `resolveSlugWithAliasDetailed(slug, sourceOrSources)` returns `{ canonical_slug, source_id } | null` — the winning alias row AND its owning source under the same scope/precedence rules (`ORDER BY array_position(scope, source_id), id`; null when nothing matches or the `slug_aliases` table does not exist yet); `resolveSlugWithAlias` is its canonical-slug projection (falls back to the input slug). A consumer that goes on to read the canonical page must scope that read to `source_id`. The by-slug read methods carry the same federated axis: `getTags`/`getLinks`/`getBacklinks`/`getChunks` opts and `TimelineOpts` (consumed by `getTimeline`) accept `sourceIds?: string[]` taking precedence over the scalar `sourceId` (`source_id = ANY($::text[])` scoping the slug→page-id lookup); `getChunks` falls back to the `'default'` source when neither is set (importCodeFile's incremental-embedding reuse relies on it) and SELECTs an explicit non-vector column list — embedding vectors never ride the payload since rowToChunk discards them (`getChunksWithEmbeddings` stays scalar-only by design: engine-internal, zero remote-reachable callers); the link reads (`getLinks`/`getBacklinks`) scope ALL THREE endpoints (from/to/origin) on the federated branch while the scalar branch scopes only the near endpoint for trusted internal cross-source callers. `traverseGraph` opts has `frontierCap?: number` (per-iteration recursive-CTE cap, approx per-BFS-layer); return type `Promise<GraphNode[]>` for MCP wire stability; export `TraverseGraphOpts`; Postgres uses parenthesized `LIMIT N ORDER BY (slug, id)` inside the recursive term, PGLite mirrors with positional params; Pinned by `test/regressions/v0_36_frontier_cap.test.ts`. Phantom-redirect methods: `refreshPageBody(slug, sourceId, compiled_truth, timeline, content_hash)` narrow-UPDATEs three columns + updated_at, skipping soft-deleted rows (content_hash refresh required so `gbrain sync` sees the canonical as unchanged after fence merge); `migrateFactsToCanonical(phantomSlug, canonicalSlug, sourceId)` UPDATEs `entity_slug`+`source_markdown_slug` on every active fact row keyed on the phantom, preserving embedding/validUntil/kind/status/source_session/confidence and offsetting `row_num` past the canonical page's current MAX(row_num) (all rows incl. expired — the partial `idx_facts_fence_key` only excludes NULL; NULL stays NULL) so overlapping fence rows never collide; parity at `test/phantom-redirect-engine-parity.test.ts`. `getAdjacencyBoosts(pageIds): Promise<Map<number, AdjacencyRow>>` powers the per-query graph-signals stage — one SQL query returning inbound-link counts among top-K plus a cross-source count (links from differing `source_id`); `COALESCE(p.source_id,'default')` null safety, `HAVING >= 1`, cross-source CASE-WHEN excludes the target's own source; parity SQL across both engines; `SearchResult` gains optional `base_score`, `backlink_boost`, `salience_boost`, `recency_boost`, `exact_match_boost`, `graph_adjacency_boost`, `graph_cross_source_boost`, `session_demote_factor`, `reranker_delta` + internal staging fields; Pinned by `test/e2e/graph-signals-engine.test.ts`. Two REQUIRED methods: `deletePages(slugs, {sourceId}): Promise<string[]>` (single-batch primitive returning slugs actually deleted) and `resolveSlugsByPaths(paths, {sourceId}): Promise<Map<path,slug>>` (batch path→slug lookup); `sourceId` REQUIRED on both at the type level (asymmetric with single-row `deletePage` which keeps optional/'default'); both short-circuit on empty input and throw when `> DELETE_BATCH_SIZE`. `softDeletePages(slugs, {sourceId}): Promise<string[]>` is the batch soft-delete twin, mirroring `deletePages`' contract exactly (required `sourceId`, `> DELETE_BATCH_SIZE` throws, empty input short-circuits, caller owns chunking + decompose-to-one-element-batches on failure): one `UPDATE … SET deleted_at = now() … AND deleted_at IS NULL … RETURNING slug` round-trip returning only the slugs that actually flipped active→soft-deleted — the `deleted_at IS NULL` predicate is load-bearing so a re-run never refreshes an already-soft-deleted row's 72h purge clock — and NOTHING cascades (chunks/links/timeline stay behind the read-side `deleted_at` filters; the autopilot purge phase hard-deletes after 72h; a re-import within the window revives via `putPage`'s upsert; `deletePage`/`deletePages` remain the purge/teardown primitives). `getStats(opts?)` / `getHealth(opts?)` take an optional `{sourceId?, sourceIds?}` scope (same shape as `sourceScopeOpts` output): omitted = brain-wide; scoped = EVERY counter/coverage/degree confines to the grant, including derived-table counts via their page joins, and link-derived numbers count only edges with BOTH endpoints in scope — so an excluded source's numbers can't be recovered by subtraction. Consumer is the remote-caller ladder in `src/core/ops/admin.ts`; `getHealth` is a one-line delegation to `src/core/engine-sql/health.ts`. Embedding-signature stale-detection quartet: `countStaleChunks(opts?)` gains optional `signature?: string` widening the stale predicate from `embedding IS NULL` to ALSO include chunks whose JOINed page `embedding_signature IS NOT NULL AND <> $signature` (NULL signature is GRANDFATHERED, never counted; omit `signature` for the legacy NULL-only count); `sumStaleChunkChars(opts?: {sourceId?, signature?}): Promise<number>` = `SUM(LENGTH(chunk_text))` over stale chunks (same predicate + embed_skip filter + optional sourceId scope), used by `gbrain sync --all` cost preview via `estimateCostFromChars`; `setPageEmbeddingSignature(slug, {sourceId?, signature})` stamps `pages.embedding_signature` after a page's chunks (re)embed, idempotent no-op when page absent; `invalidateStaleSignatureEmbeddings({signature, sourceId?}): Promise<number>` NULLs `embedding`+`embedded_at` on every chunk whose page signature is set AND differs, returning the count, called BEFORE `listStaleChunks` so signature-drift pages flow through the NULL-embedding keyset cursor unchanged (NULL never invalidated). Widens `findOrphanPages(opts?: {sourceId?, sourceIds?})` (candidate-side scoping only; inbound links counted from any source). Pinned by `test/sum-stale-chunk-chars.test.ts`, `test/embedding-signature-stale.test.ts`, `test/e2e/engine-parity.test.ts`. Free-text alias layer: `resolveAliases(aliasNorms, opts?): Promise<Map<string, Array<{slug, source_id}>>>` (READ; maps each normalized alias to declaring `(slug, source_id)` pairs, source-scoped) and `setPageAliases(slug, sourceId, aliasNorms)` (WRITE; replaces the full alias set, delete-then-insert, empty clears, idempotent on the unique triple), called by the `importFromContent` ingest projection and the `reindex --aliases` backfill; parity across both engines, Pinned by `test/search/page-aliases-engine.test.ts`. `searchVector` in both engines injects the shared `buildBestPerPagePoolCte` per-page max-pool so a page surfaces on its strongest chunk. `executeRawDirect(sql, params?, opts?)` is the lock-hot-path sibling of `executeRaw`: same single-statement contract, but routes to the direct session-mode pool when dual-pool is active (Postgres/Supabase port 5432) so a long-held lock heartbeat survives the transaction pooler's per-transaction connection recycling; PGLite delegates straight to `executeRaw` (no pooler). Both engines implement it; the Minion lock path (`claim`/`renewLock`) is the consumer. `reconnect(ctx?: {error?})` is a REQUIRED lifecycle method on BOTH engines: it recovers a dropped connection using the config captured at the last `connect()`, so callers (autopilot health probe, `batchRetry`) never `disconnect()` + bare `connect()` (which loses the config and throws `database_url undefined` forever, and opens a null-connection window). PostgresEngine rebuilds its pool with a `_reconnecting` reentrancy guard and emits pool-recovery audit; PGLite is single-writer in-process so it just restores the saved data dir for parity. Plus two interface members: (1) optional `findDuplicatePage?(sourceId, {hash, frontmatterId?}): Promise<{slug, id} | null>` (identity precedence is content_hash OR frontmatter->>'id', both with `deleted_at IS NULL`); (2) `resolveSlugs(partial, opts?)` extended with `{sourceId?, sourceIds?}` so the MCP fuzzy `get_page` path scopes by source (field names match `sourceScopeOpts(ctx)` output so handlers spread directly; no opts gives the unscoped behavior). Plus a stable tiebreaker `ORDER BY score DESC, page_id ASC, chunk_id ASC` in `searchVector` in both engines: on a score tie (basis-vector eval fixtures) older `page_id` wins, so a new index on `pages` cannot flip ranking on tied scores.
-- `src/core/migrate.ts` — schema-migration runner. Re-exports `MIGRATIONS` from the generated registry `src/core/schema-migrations/registry.generated.ts`; each migration is one file `src/core/schema-migrations/v<NNN>-<name>.ts` (the source of truth for schema DDL history), with the `Migration` type in `schema-migrations/types.ts` and shared handler helpers (`migrationNotice`, `dropInvalidConcurrentIndex`, the fresh-install quiet flag) in `schema-migrations/helpers.ts`, a leaf that never imports `migrate.ts`. `Migration` carries `sqlFor?: { postgres?, pglite? }` (engine-specific SQL overrides `sql`) and `transaction?: boolean` (false for `CREATE INDEX CONCURRENTLY`, which Postgres refuses in a transaction; ignored on PGLite). Key migrations: v14 (handler branches on `engine.kind` for CONCURRENTLY-on-Postgres with invalid-remnant pre-drop via `pg_index.indisvalid`, plain `CREATE INDEX` on PGLite); v15 (`minion_jobs.max_stalled` default 1→5 + backfill non-terminal rows); v24 `rls_backfill_missing_tables` (`sqlFor: { pglite: '' }` no-op — PGLite has no RLS engine, targets subagent tables absent from pglite-schema.ts); v30 `dream_verdicts (file_path TEXT, content_hash TEXT, worth_processing BOOL, reasons JSONB, judged_at TIMESTAMPTZ, PK(file_path, content_hash))` (RLS-enabled under BYPASSRLS; synthesize reads/writes to avoid re-judging); v35 auto-RLS event trigger `auto_rls_on_create_table` fires on `ddl_command_end` for `WHEN TAG IN ('CREATE TABLE','CREATE TABLE AS','SELECT INTO')` running `ALTER TABLE … ENABLE ROW LEVEL SECURITY` on new `public.*` tables (no FORCE) + one-time backfill on every existing `public.*` base table whose comment doesn't match `^GBRAIN:RLS_EXEMPT\s+reason=\S.{3,}` (per-table failure aborts the offending CREATE TABLE; no EXCEPTION wrap; PGLite no-op via `sqlFor.pglite: ''`; breaking change: intentionally-RLS-off public tables need the GBRAIN:RLS_EXEMPT comment before upgrade); v40 `pages_emotional_weight` (`pages.emotional_weight REAL NOT NULL DEFAULT 0.0`, column-only metadata-only); v46 `mcp_request_log_params_jsonb_normalize` (`UPDATE ... SET params = params::text::jsonb WHERE jsonb_typeof(params) = 'string'`, idempotent); v60-v65 six-migration chain wiring source-scoping into `oauth_clients` — v60 (`oauth_clients_source_id_fk`: `source_id TEXT` NULL→`'default'` backfill + FK to `sources(id) ON DELETE SET NULL`), v61 (`federated_read TEXT[] NOT NULL DEFAULT '{}'`), v62 (explicit-CASE backfill so `source_id IS NULL` → `'{}'`), v63 (fail-loud check every row's source_id is in its federated_read array), v64 (FK flipped to `ON DELETE RESTRICT`), v65 (GIN index for array-containment); v68 `eval_candidates_embedding_column` (`eval_candidates.embedding_column TEXT NULL` per-row provenance for `gbrain eval replay` to reproduce the same retrieval space; NULL-tolerant); v108 `pages_embedding_signature` (`pages.embedding_signature TEXT NULL` = `<provider:model>:<dims>` stamped via `setPageEmbeddingSignature`; GRANDFATHER — stale predicate is `embedding_signature IS NOT NULL AND embedding_signature <> $current` so NULL is NEVER stale and upgrade never re-embeds the whole corpus; no index; metadata-only); v109 `sources_newest_content_at` (`sources.newest_content_at TIMESTAMPTZ` durable newest-COMMIT HEAD committer time written by `writeSyncAnchor`, read by the REMOTE staleness path instead of shelling to git; fresh-install column in `src/schema.sql`, generated into both blobs, plus a bootstrap probe); v110 `page_aliases` (`(id, source_id, alias_norm, slug, ...)` with `UNIQUE (source_id, alias_norm, slug)` + lookup indexes on `(source_id, alias_norm)` and `(source_id, slug)`; `alias_norm` is `normalizeAlias()` output so WRITE/READ key on the same form; also in `src/core/pglite-schema.ts`); v111 `search_telemetry_rank1_columns` (`ADD COLUMN IF NOT EXISTS` on both engines: `sum_rank1_score`, `count_rank1`, three buckets `rank1_lt_solid`/`rank1_solid`/`rank1_high` on `search_telemetry` — aggregate not per-query rows so rank-1 median drift is bounded-growth; ALTERs right after v57 which created the table); v114 `links_link_source_check_kebab_regex` (opens `link_source` from the closed allowlist to a kebab-case format gate `^[a-z][a-z0-9]*(-[a-z0-9]+)*$` + `char_length<=64`; Postgres branch uses `NOT VALID` + `VALIDATE CONSTRAINT` with `transaction:false`, PGLite plain DROP+ADD; existing built-ins all satisfy the regex so VALIDATE never fails on existing data); v116 `code_edges_source_backfill_and_callee_index` (idempotent: backfills NULL `code_edges_symbol`/`code_edges_chunk` `source_id` from each edge's `from_chunk` page — a NULL never matches a scoped `AND source_id = …` filter, so scoped `code-callers`/`code-callees` would return 0 rows on multi-source brains — plus plain `CREATE INDEX` on `from_symbol_qualified` for both edge tables, which had no index and seq-scanned per BFS node); v129 `dream_verdicts_triage_v1_columns` (additive `ADD COLUMN IF NOT EXISTS` widening `dream_verdicts` into a scored triage record — `score`, `content_type`, `segments`, `entities`, `model`, `triage_version`; legacy rows keep `score` NULL and read as cache misses, re-judged once; no backfill, no index; same SQL on both engines since `dream_verdicts` is migration-created on PGLite too, so the columns take the COLUMN_EXEMPTIONS route in `test/schema-bootstrap-coverage.test.ts` rather than bootstrap probes); v143 `dream_verdicts_ttl` (30-day `expires_at` TTL: nullable `ADD COLUMN` + `SET DEFAULT` run BEFORE the `judged_at`-derived backfill — statement order is load-bearing so a legacy writer racing the upgrade window picks up the default instead of inserting a NULL that would fail `SET NOT NULL` on every retry; on Postgres the schema blob's `dream_verdicts_expires_idx` forward-references the column, so `forward-reference-bootstrap.ts` probes + ALTERs it before the blob replays, and both engines' `getDreamVerdict` read predicate is NULL-tolerant — `expires_at IS NULL OR expires_at > now()` — so a pre-backfill row reads as a hit instead of silently re-judging the corpus). Three shape-keyed self-heals run on EVERY `runMigrations` pass, including the no-pending early-return path, because a merge-renumbered migration or a drifted restore can leave the version counter past a schema change while the live shape stays old: `repairTimelineDedupIndex` (`timeline_dedup_index`, see `timeline-dedup-repair.ts`) and `repairPagesUpsertArbiter` (`pages_source_slug_key`, see `pages-upsert-arbiter.ts`) are not version-gated at all; `repairLinkSourceCheck` (`links_link_source_check`, see `link-source-check-repair.ts`) runs only when the ledger is already >= `LINK_SOURCE_GATE_MIGRATION_VERSION` (114), because below it the pending loop replays v114 itself (running the repair first would rewrite the constraint twice, and a pre-v11 brain has no `link_source` column). All three are best-effort + idempotent; `doctor` surfaces each drift independently. `retry-matcher.ts` and `timeline-dedup-repair.ts` are static dependencies because `runMigrations()` executes from live engine initialization; the engine dynamic-import guard scans this file with both engine implementations. v95: `pages_dedup_partial_index` adds `CREATE INDEX pages_dedup_idx ON pages (source_id, content_hash) WHERE deleted_at IS NULL`. Postgres uses `CREATE INDEX CONCURRENTLY` with `transaction: false` + pre-drops any invalid remnant; PGLite uses plain `CREATE INDEX`. Powers `findDuplicatePage` hot path (O(log n) instead of O(n)). v74 `mcp_spend_log` uses BTREE on `(client_id, created_at)` + `(token_name, created_at)` — `date_trunc('day', TIMESTAMPTZ)` is NOT IMMUTABLE so can't appear in index expressions; a `created_at` range scan covers the per-day rollup. v75 `embedding_multimodal_column` is column-only (no HNSW index — deferred to post-reindex per pgvector best practice). Every pass (including one with nothing pending) ends with `page-state/revision-backfill-schema.ts:resumePageRevisionBackfill` while `pages.knowledge_revision` is nullable (#5216): the page-state schema adds `sources.incarnation` and `pages.knowledge_revision` nullable with a separate default (no volatile-default table rewrite on replay; an empty `pages` is constrained at once), rows are backfilled in committed id batches with a config cursor (`page_state.revision_backfill`), a failing row is isolated and retried at most three passes, and the column becomes NOT NULL via CHECK NOT VALID → VALIDATE → SET NOT NULL. The revision trigger handles a NULL old revision without reading bodies; snapshots report such a row's revision as `backfill_pending` and `assertPageRevision` refuses revision-bound writes with `revision_backfill_pending` (`page-revision-backfill-5216.test.ts`).
+- `src/core/migrate.ts` — schema-migration runner. Re-exports `MIGRATIONS` from the generated registry `src/core/schema-migrations/registry.generated.ts`; each migration is one file `src/core/schema-migrations/v<NNN>-<name>.ts` (the source of truth for schema DDL history), with the `Migration` type in `schema-migrations/types.ts` and shared handler helpers (`migrationNotice`, `dropInvalidConcurrentIndex`, the fresh-install quiet flag) in `schema-migrations/helpers.ts`, a leaf that never imports `migrate.ts`. `Migration` carries `sqlFor?: { postgres?, pglite? }` (engine-specific SQL overrides `sql`) and `transaction?: boolean` (false for `CREATE INDEX CONCURRENTLY`, which Postgres refuses in a transaction; ignored on PGLite). Key migrations: v14 (handler branches on `engine.kind` for CONCURRENTLY-on-Postgres with invalid-remnant pre-drop via `pg_index.indisvalid`, plain `CREATE INDEX` on PGLite); v15 (`minion_jobs.max_stalled` default 1→5 + backfill non-terminal rows); v24 `rls_backfill_missing_tables` (`sqlFor: { pglite: '' }` no-op — PGLite has no RLS engine, targets subagent tables absent from pglite-schema.ts); v30 `dream_verdicts (file_path TEXT, content_hash TEXT, worth_processing BOOL, reasons JSONB, judged_at TIMESTAMPTZ, PK(file_path, content_hash))` (RLS-enabled under BYPASSRLS; synthesize reads/writes to avoid re-judging); v35 auto-RLS event trigger `auto_rls_on_create_table` fires on `ddl_command_end` for `WHEN TAG IN ('CREATE TABLE','CREATE TABLE AS','SELECT INTO')` running `ALTER TABLE … ENABLE ROW LEVEL SECURITY` on new `public.*` tables (no FORCE) + one-time backfill on every existing `public.*` base table whose comment doesn't match `^GBRAIN:RLS_EXEMPT\s+reason=\S.{3,}` (per-table failure aborts the offending CREATE TABLE; no EXCEPTION wrap; PGLite no-op via `sqlFor.pglite: ''`; breaking change: intentionally-RLS-off public tables need the GBRAIN:RLS_EXEMPT comment before upgrade); v40 `pages_emotional_weight` (`pages.emotional_weight REAL NOT NULL DEFAULT 0.0`, column-only metadata-only); v46 `mcp_request_log_params_jsonb_normalize` (`UPDATE ... SET params = params::text::jsonb WHERE jsonb_typeof(params) = 'string'`, idempotent); v60-v65 six-migration chain wiring source-scoping into `oauth_clients` — v60 (`oauth_clients_source_id_fk`: `source_id TEXT` NULL→`'default'` backfill + FK to `sources(id) ON DELETE SET NULL`), v61 (`federated_read TEXT[] NOT NULL DEFAULT '{}'`), v62 (explicit-CASE backfill so `source_id IS NULL` → `'{}'`), v63 (fail-loud check every row's source_id is in its federated_read array), v64 (FK flipped to `ON DELETE RESTRICT`), v65 (GIN index for array-containment); v68 `eval_candidates_embedding_column` (`eval_candidates.embedding_column TEXT NULL` per-row provenance for `gbrain eval replay` to reproduce the same retrieval space; NULL-tolerant); v108 `pages_embedding_signature` (`pages.embedding_signature TEXT NULL` = `<provider:model>:<dims>` stamped via `setPageEmbeddingSignature`; GRANDFATHER — stale predicate is `embedding_signature IS NOT NULL AND embedding_signature <> $current` so NULL is NEVER stale and upgrade never re-embeds the whole corpus; no index; metadata-only); v109 `sources_newest_content_at` (`sources.newest_content_at TIMESTAMPTZ` durable newest-COMMIT HEAD committer time written by `writeSyncAnchor`, read by the REMOTE staleness path instead of shelling to git; fresh-install column in `src/schema.sql`, generated into both blobs, plus a bootstrap probe); v110 `page_aliases` (`(id, source_id, alias_norm, slug, ...)` with `UNIQUE (source_id, alias_norm, slug)` + lookup indexes on `(source_id, alias_norm)` and `(source_id, slug)`; `alias_norm` is `normalizeAlias()` output so WRITE/READ key on the same form; also in `src/core/pglite-schema.ts`); v111 `search_telemetry_rank1_columns` (`ADD COLUMN IF NOT EXISTS` on both engines: `sum_rank1_score`, `count_rank1`, three buckets `rank1_lt_solid`/`rank1_solid`/`rank1_high` on `search_telemetry` — aggregate not per-query rows so rank-1 median drift is bounded-growth; ALTERs right after v57 which created the table); v114 `links_link_source_check_kebab_regex` (opens `link_source` from the closed allowlist to a kebab-case format gate `^[a-z][a-z0-9]*(-[a-z0-9]+)*$` + `char_length<=64`; Postgres branch uses `NOT VALID` + `VALIDATE CONSTRAINT` with `transaction:false`, PGLite plain DROP+ADD; existing built-ins all satisfy the regex so VALIDATE never fails on existing data); v116 `code_edges_source_backfill_and_callee_index` (idempotent: backfills NULL `code_edges_symbol`/`code_edges_chunk` `source_id` from each edge's `from_chunk` page — a NULL never matches a scoped `AND source_id = …` filter, so scoped `code-callers`/`code-callees` would return 0 rows on multi-source brains — plus plain `CREATE INDEX` on `from_symbol_qualified` for both edge tables, which had no index and seq-scanned per BFS node); v129 `dream_verdicts_triage_v1_columns` (additive `ADD COLUMN IF NOT EXISTS` widening `dream_verdicts` into a scored triage record — `score`, `content_type`, `segments`, `entities`, `model`, `triage_version`; legacy rows keep `score` NULL and read as cache misses, re-judged once; no backfill, no index; same SQL on both engines since `dream_verdicts` is migration-created on PGLite too, so the columns take the COLUMN_EXEMPTIONS route in `test/schema-bootstrap-coverage.test.ts` rather than bootstrap probes); v143 `dream_verdicts_ttl` (30-day `expires_at` TTL: nullable `ADD COLUMN` + `SET DEFAULT` run BEFORE the `judged_at`-derived backfill — statement order is load-bearing so a legacy writer racing the upgrade window picks up the default instead of inserting a NULL that would fail `SET NOT NULL` on every retry; on Postgres the schema blob's `dream_verdicts_expires_idx` forward-references the column, so `src/core/engine-sql/bootstrap.ts` probes + ALTERs it before the blob replays, and both engines' `getDreamVerdict` read predicate is NULL-tolerant — `expires_at IS NULL OR expires_at > now()` — so a pre-backfill row reads as a hit instead of silently re-judging the corpus). Three shape-keyed self-heals run on EVERY `runMigrations` pass, including the no-pending early-return path, because a merge-renumbered migration or a drifted restore can leave the version counter past a schema change while the live shape stays old: `repairTimelineDedupIndex` (`timeline_dedup_index`, see `timeline-dedup-repair.ts`) and `repairPagesUpsertArbiter` (`pages_source_slug_key`, see `pages-upsert-arbiter.ts`) are not version-gated at all; `repairLinkSourceCheck` (`links_link_source_check`, see `link-source-check-repair.ts`) runs only when the ledger is already >= `LINK_SOURCE_GATE_MIGRATION_VERSION` (114), because below it the pending loop replays v114 itself (running the repair first would rewrite the constraint twice, and a pre-v11 brain has no `link_source` column). All three are best-effort + idempotent; `doctor` surfaces each drift independently. `retry-matcher.ts` and `timeline-dedup-repair.ts` are static dependencies because `runMigrations()` executes from live engine initialization; the engine dynamic-import guard scans this file with both engine implementations. v95: `pages_dedup_partial_index` adds `CREATE INDEX pages_dedup_idx ON pages (source_id, content_hash) WHERE deleted_at IS NULL`. Postgres uses `CREATE INDEX CONCURRENTLY` with `transaction: false` + pre-drops any invalid remnant; PGLite uses plain `CREATE INDEX`. Powers `findDuplicatePage` hot path (O(log n) instead of O(n)). v74 `mcp_spend_log` uses BTREE on `(client_id, created_at)` + `(token_name, created_at)` — `date_trunc('day', TIMESTAMPTZ)` is NOT IMMUTABLE so can't appear in index expressions; a `created_at` range scan covers the per-day rollup. v75 `embedding_multimodal_column` is column-only (no HNSW index — deferred to post-reindex per pgvector best practice). Every pass (including one with nothing pending) ends with `page-state/revision-backfill-schema.ts:resumePageRevisionBackfill` while `pages.knowledge_revision` is nullable (#5216): the page-state schema adds `sources.incarnation` and `pages.knowledge_revision` nullable with a separate default (no volatile-default table rewrite on replay; an empty `pages` is constrained at once), rows are backfilled in committed id batches with a config cursor (`page_state.revision_backfill`), a failing row is isolated and retried at most three passes, and the column becomes NOT NULL via CHECK NOT VALID → VALIDATE → SET NOT NULL. The revision trigger handles a NULL old revision without reading bodies; snapshots report such a row's revision as `backfill_pending` and `assertPageRevision` refuses revision-bound writes with `revision_backfill_pending` (`page-revision-backfill-5216.test.ts`).
Size ceiling: `scripts/module-size-limits.tsv` (per-change raise history: `git log -p` on that file). The runner (ordering, retry, verify, repair-handler hooks and the static helper imports engine-live paths require) has a plain ratchet ceiling; migrations no longer live in this file.
- `src/core/pglite-embedded-assets.ts` + `src/core/pglite-embedded-asset-paths.ts` — PGLite runtime-asset supply for every run mode (compiled binary, source checkout, bun-global install). `pglite-embedded-asset-paths.ts` is the bundler ANCHOR: five literal `with { type: 'file' }` imports of the wasm/data/extension-tarball assets via repo-relative node_modules paths (the package's `exports` map hides `./dist/*`) — keep the specifiers literal and byte-stable, an expression or indirection silently stops the bytes embedding and the compiled binary falls into the Bun-vfs ENOENT failure. `resolvePgliteAssetPaths()` in `pglite-embedded-assets.ts` is the tiered resolver: tier 1 dynamically `import()`s the anchor (the rejection under a hoisted install — bun-global upgrades dedupe `@electric-sql/pglite` to the global root, making the anchor's specifiers unresolvable — is EXPECTED and routes to tier 2, which is why the anchor is not a static import); tier 2 derives the dist dir via module resolution of `@electric-sql/pglite` (`import.meta.resolve` then `createRequire` — the SAME specifier the engine imports, so assets can never come from a different pglite copy than the loaded JS); tier 3 throws one actionable error naming everything tried, with the canonical GitHub reinstall command (never the npm-registry name, which is squatted — see the README install warning). `getEmbeddedPgliteOptions()` memoizes one build per process and hands PGLite compiled `WebAssembly.Module`s + fs-bundle Blob + materialized extension tarballs via `PGliteOptions`. Pinned by `test/pglite-embedded-assets.test.ts` + `test/pglite-hoisted-install.serial.test.ts` (real `bun add -g`-shaped hoisted layout).
diff --git a/docs/architecture/key-files/tooling-and-tests.md b/docs/architecture/key-files/tooling-and-tests.md
index 16cc394203..49bac8197c 100644
--- a/docs/architecture/key-files/tooling-and-tests.md
+++ b/docs/architecture/key-files/tooling-and-tests.md
@@ -94,6 +94,6 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `test/operations-trust-boundary.test.ts` + `scripts/check-operations-filter-bypass.sh` — operations trust-boundary contract coverage. Pure assertions over all 74 ops (every op has a scope annotation; every mutating op has a non-read scope; `localOnly: true` ops are excluded from `operations.filter(op => !op.localOnly)`; the seven sensitive localOnly ops snapshot-pinned by name) plus targeted handler-invocation guards for the HTTP-callable classes: `submit_job` with `name='shell'` + `ctx.remote=true` MUST reject (shell-job RCE); `search_by_image` with `image_path` + `ctx.remote=true` MUST reject (image leak); and the list-op read-leak class — `find_orphans`/`get_recent_salience`/`find_anomalies`/`find_experts` invoked with `ctx.remote=true` over a seeded `visibility: private` page MUST NOT return its slug/title, with a local positive control proving the assertions non-vacuous, count self-consistency assertions pinning the no-count-oracle posture (both orphan denominators shrink with hidden rows; `excluded` untouched; anomaly `count` mirrors the visible slug list), and a soft-delete re-probe pinning the includeDeleted fail-closed path. `file_upload` and `sync_brain` omitted from handler-invocation tests because they're `localOnly: true` (that path would test an impossible production scenario). The shell guard greps `src/` for any module importing the `operations` value outside the canonical filter site at `src/commands/serve-http.ts` (three import shapes: destructured, aliased, namespace), with an explicit 10-entry allow-list + a literal-string check that `serve-http.ts` still contains `operations.filter(op => !op.localOnly)`. Wired into `bun run verify`. Dynamic sibling: `test/remote-privacy-sweep.test.ts` (next entry) — same doctrine, corpus-seeded, catches leaks in ops neither curated list has heard of yet.
-- `test/public-exports.test.ts` — runtime contract test (R2). Imports each of the 17 public subpaths via package name and pins a canary symbol per module. Paired with `scripts/check-exports-count.sh`.
+- `test/public-exports.test.ts` — runtime contract test (R2). Imports every public subpath in package.json `exports` via package name, pins a canary symbol per module, and fails when the exports map gains, loses or renames a subpath without a matching `EXPECTED_EXPORTS` edit.
- `test/remote-privacy-sweep.test.ts` — registry-driven, corpus-seeded leak detection across the ENTIRE dispatch surface (catches a new remote surface that forgets the world-only filter). Seeds a hermetic PGLite corpus carrying high-entropy PRIVATE sentinels (private page title/body, a private fact, a non-world take, fence-row content — never slugs, which are legitimately echoed in "Page not found" errors and would false-positive on correct behavior) plus WORLD markers as positive controls; enumerates every non-localOnly op from the registry; dispatches each one remote-shaped through `dispatchToolCall` (the exact layer both MCP transports share) in BOTH caller shapes — scalar source-scoped (like stdio) and federated with an auth-array read grant; and asserts no private sentinel appears anywhere in the serialized response envelope: structured fields, rendered text, error messages, and the `_meta.brain_hot_memory` channel alike. Fail-closed maintenance contract: `EXPECTED_OUTCOME`'s key set must be set-equal to the enumerated registry, so a NEW op FAILS the suite until classified (`data` = must prove corpus contact via a WORLD marker / `ok` / `error` — envelope still sentinel-checked / `denied` = publish-gated, must error naming its `mcp.*` gate; plus a `PARAM_FACTORY` entry if it can return corpus data — the failure message prints exactly what to add). A separate arm asserts every `localOnly` op is denied fail-closed over non-stdio transports; `KNOWN_EXPOSED` op-wide exemptions must stay empty absent written justification + review. Phase W covers mutating ops against fresh slugs (destructive ops last, corpus-intact re-checks between phases). Honest scope: covers the dispatch surface for transport-floor callers; does NOT cover the IPC context-pack handler (`src/mcp/context-pack-handler.ts` bypasses `dispatchToolCall`) or write-triggered restoration echoes — the write-side sweep is a filed TODO. Static siblings: `test/operations-trust-boundary.test.ts` (previous entry) + `scripts/check-operations-filter-bypass.sh`.
diff --git a/docs/architecture/wave-1-moves.json b/docs/architecture/wave-1-moves.json
index ff419f485b..8f9e99916f 100644
--- a/docs/architecture/wave-1-moves.json
+++ b/docs/architecture/wave-1-moves.json
@@ -3969,9 +3969,10 @@
{
"old": "src/core/postgres-engine/forward-reference-bootstrap.ts:applyPostgresForwardReferenceBootstrap",
"kind": "split",
- "facade": "src/core/postgres-engine/forward-reference-bootstrap.ts:applyPostgresForwardReferenceBootstrap",
+ "facade": null,
"wasExported": true,
"new": [
+ "src/core/engine-sql/bootstrap.ts:applyPostgresForwardReferenceBootstrap",
"src/core/engine-sql/bootstrap.ts:applyForwardReferenceBootstrap",
"src/core/engine-sql/bootstrap.ts:forwardReferenceGaps"
]
diff --git a/docs/architecture/wave-1-porting.md b/docs/architecture/wave-1-porting.md
index 2c34784d9f..eaab279c6d 100644
--- a/docs/architecture/wave-1-porting.md
+++ b/docs/architecture/wave-1-porting.md
@@ -614,7 +614,7 @@ module path when it keeps exporting the name; "module-private" means the old mod
| Old symbol | Kind | Still importable from | New location(s) |
|---|---|---|---|
-| `applyPostgresForwardReferenceBootstrap` | split | `src/core/postgres-engine/forward-reference-bootstrap.ts:applyPostgresForwardReferenceBootstrap` | `src/core/engine-sql/bootstrap.ts:applyForwardReferenceBootstrap`<br>`src/core/engine-sql/bootstrap.ts:forwardReferenceGaps` |
+| `applyPostgresForwardReferenceBootstrap` | split | **not re-exported** | `src/core/engine-sql/bootstrap.ts:applyPostgresForwardReferenceBootstrap`<br>`src/core/engine-sql/bootstrap.ts:applyForwardReferenceBootstrap`<br>`src/core/engine-sql/bootstrap.ts:forwardReferenceGaps` |
### `src/core/postgres-engine/salience.ts`
diff --git a/docs/guides/system-one.md b/docs/guides/system-one.md
index 5a822cf867..444d191af4 100644
--- a/docs/guides/system-one.md
+++ b/docs/guides/system-one.md
@@ -693,5 +693,12 @@ gbrain decide judge-agreement --suite <longmemeval|grounding> --input <file> [--
output, or grounding labels) and reports Cohen's kappa. It needs no brain,
and nothing is substituted at runtime.
+Know-to-ask (`recall_needed`) turn latency: `bun scripts/bench-s6-turn-context.ts
+[--rounds 3] [--delays-ms 120,160,300] [--json]` replays every BrainBench
+know-to-ask turn through the hook's turn-context path in an in-memory brain,
+with S6 off and then on against a fixture transport drawing delays from a
+measured latency sample, and reports p50/p95/p99, the added latency per turn,
+the outcome mix and the deadline miss rate. It calls no provider.
+
Row and summary fields: [`docs/eval-bench.md`](../eval-bench.md#system-one-arms---decide).
Protocols and verdicts: [`docs/eval/system-one/`](../eval/system-one/).
diff --git a/package.json b/package.json
index 096ab4464b..b19259c39c 100644
--- a/package.json
+++ b/package.json
@@ -113,7 +113,6 @@
"check:test-names": "bash scripts/check-test-real-names.sh",
"check:progress": "bash scripts/check-progress-to-stdout.sh",
"check:no-tracked-symlinks": "bash scripts/check-no-tracked-symlinks.sh",
- "check:exports-count": "bash scripts/check-exports-count.sh",
"check:admin-build": "bash scripts/check-admin-build.sh",
"check:admin-embedded": "bash scripts/check-admin-embedded.sh",
"check:test-isolation": "bash scripts/check-test-isolation.sh",
diff --git a/scripts/bench-grandfather-5530.ts b/scripts/bench-grandfather-5530.ts
deleted file mode 100644
index 073d074489..0000000000
--- a/scripts/bench-grandfather-5530.ts
+++ /dev/null
@@ -1,109 +0,0 @@
-#!/usr/bin/env bun
-/**
- * #5530 benchmark: wall time per page for the v0.13.1 managed grandfather
- * step on a durability-hardened canonical repository that tracks a local
- * bare remote. Every page is its own admitted put_page; the measurement
- * covers admission, publication and the page's Git commit and push.
- *
- * bun scripts/bench-grandfather-5530.ts [--pages 250] [--postgres <url>] [--no-harden] [--no-push] [--json]
- *
- * --no-harden skips the durability hook, so Git effects record without running
- * git: the difference between the two runs is the Git share of the step.
- * --no-push unsets the branch upstream, so effects commit but never push.
- *
- * Isolated: a temporary GBRAIN_HOME, an in-memory PGLite brain (or a fresh
- * database on the given test Postgres server) and a local bare remote. It
- * never opens an operator brain and never reaches the network.
- */
-import { chmodSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
-import { tmpdir } from 'node:os';
-import { join } from 'node:path';
-import { randomUUID } from 'node:crypto';
-
-function arg(name: string): string | undefined {
- const at = process.argv.indexOf(name);
- return at >= 0 ? process.argv[at + 1] : undefined;
-}
-const pages = Number(arg('--pages') ?? 250);
-const databaseUrl = arg('--postgres');
-const json = process.argv.includes('--json');
-const harden = !process.argv.includes('--no-harden');
-const push = !process.argv.includes('--no-push');
-
-function git(root: string, ...args: string[]): string {
- const result = Bun.spawnSync(['git', '-C', root, ...args]);
- if (result.exitCode) throw new Error(`git ${args.join(' ')}: ${result.stderr.toString()}`);
- return result.stdout.toString();
-}
-
-const home = realpathSync.native(mkdtempSync(join(tmpdir(), 'gbrain-bench-5530-')));
-process.env.GBRAIN_HOME = home;
-delete process.env.DATABASE_URL;
-delete process.env.GBRAIN_DATABASE_URL;
-
-const { phaseCGrandfather } = await import('../src/commands/migrations/v0_13_1.ts');
-const { claimWorktree } = await import('../src/core/persistence/ownership.ts');
-const { activateSharedSkillPersistence } = await import('../src/core/persistence/skill-activation.ts');
-const { submitPageMutation } = await import('../src/core/persistence/page-mutations.ts');
-const { disposePersistenceConsumer } = await import('../src/core/persistence/service.ts');
-const { PGLiteEngine } = await import('../src/core/pglite-engine.ts');
-const { runPersistenceEffects } = await import('../src/core/persistence/effects.ts');
-const { localHostId } = await import('../src/core/persistence/identity.ts');
-
-const root = join(home, 'content'), remote = join(home, 'remote.git');
-mkdirSync(root); mkdirSync(remote);
-git(root, 'init', '-q', '-b', 'main');
-git(root, 'config', 'user.name', 'Example Writer');
-git(root, 'config', 'user.email', '[email protected]');
-writeFileSync(join(root, 'README.md'), 'Benchmark\n');
-git(root, 'add', 'README.md'); git(root, 'commit', '-q', '-m', 'Initial');
-git(remote, 'init', '-q', '--bare');
-git(root, 'remote', 'add', 'origin', remote); git(root, 'push', '-q', '-u', 'origin', 'main');
-
-let engine: import('../src/core/engine.ts').BrainEngine, close: () => Promise<void>;
-if (databaseUrl) {
- const { isolatedPersistencePostgres } = await import('../test/helpers/persistence-postgres.ts');
- ({ engine, close } = await isolatedPersistencePostgres(databaseUrl));
-} else {
- const pglite = new PGLiteEngine(); await pglite.connect({}); await pglite.initSchema();
- engine = pglite; close = () => pglite.disconnect();
-}
-try {
- await engine.executeRaw("UPDATE sources SET local_path=$1 WHERE id='default'", [root]);
- await claimWorktree(engine, 'default', root);
- await activateSharedSkillPersistence(engine, { confirmQuiesced: true });
- const ctx = { engine, config: { engine: engine.kind, embedding_disabled: true }, sourceId: 'default',
- remote: false, dryRun: false, logger: { info() {}, warn() {}, error() {} } } as never;
- // Seed before hardening, so the seed writes skip Git and only the step under test commits and pushes.
- for (let i = 0; i < pages; i++) {
- await submitPageMutation(ctx, { operation: 'put_page', params: { slug: `notes/page-${String(i).padStart(4, '0')}`, request_id: randomUUID(),
- content: `---\ntype: note\ntitle: Page ${i}\n---\n\nBenchmark page ${i}.\n` } });
- }
- await disposePersistenceConsumer(engine);
- git(root, 'add', '-A'); git(root, 'commit', '-q', '-m', 'Seed'); git(root, 'push', '-q');
- if (harden) {
- const hook = join(root, '.git', 'hooks', 'post-commit');
- writeFileSync(hook, '#!/bin/sh\n# gbrain brain-durability post-commit hook (v0.42.44+)\n');
- chmodSync(hook, 0o755);
- }
- if (!push) git(root, 'branch', '--unset-upstream');
- const commitsBefore = Number(git(root, 'rev-list', '--count', 'HEAD').trim());
- const started = performance.now();
- const result = await phaseCGrandfather(engine, { yes: true, dryRun: false, noAutopilotInstall: true } as never);
- const stepSeconds = (performance.now() - started) / 1000;
- await disposePersistenceConsumer(engine);
- // Git work the step left queued still has to run before the pages are backed up.
- await engine.executeRaw("UPDATE persistence_effects SET next_attempt_at=now() WHERE state='queued'").catch(() => undefined);
- while (await runPersistenceEffects(engine, ctx.config as never, { hostId: localHostId(), limit: 20 }) > 0);
- const seconds = (performance.now() - started) / 1000;
- const commits = Number(git(root, 'rev-list', '--count', 'HEAD').trim()) - commitsBefore;
- const remoteHead = git(remote, 'rev-parse', 'main').trim() === git(root, 'rev-parse', 'HEAD').trim();
- const report = { engine: engine.kind, pages, hardened: harden, push, touched: result.detail.touched, failed: result.detail.failed, failures: result.detail.failures.slice(0, 3),
- step_seconds: Number(stepSeconds.toFixed(2)), seconds: Number(seconds.toFixed(2)), seconds_per_page: Number((seconds / pages).toFixed(3)), commits, remote_matches_head: push ? remoteHead : null,
- platform: `${process.platform}-${process.arch}`, bun: Bun.version };
- console.log(json ? JSON.stringify(report) : Object.entries(report).map(([k, v]) => `${k}: ${v}`).join('\n'));
-} finally {
- await disposePersistenceConsumer(engine);
- await close();
- rmSync(home, { recursive: true, force: true });
-}
diff --git a/scripts/build-contradictions-fixture.ts b/scripts/build-contradictions-fixture.ts
deleted file mode 100644
index be9b8c69d5..0000000000
--- a/scripts/build-contradictions-fixture.ts
+++ /dev/null
@@ -1,308 +0,0 @@
-#!/usr/bin/env bun
-/**
- * scripts/build-contradictions-fixture.ts (v0.32.6, T2)
- *
- * Build a privacy-redacted gold fixture for the contradiction probe judge
- * by running the probe against the user's REAL brain and hand-labeling
- * the candidate pairs. Output: test/fixtures/contradictions-eval-gold.jsonl.
- *
- * Privacy posture (CLAUDE.md rule): the operator MUST inspect the
- * generated file before commit. The redactor (fixture-redact.ts) is
- * best-effort; the pre-commit review is the safety net. Fail-closed if
- * any pair fails the isCleanForCommit check after redaction.
- *
- * Usage:
- * bun run scripts/build-contradictions-fixture.ts \
- * [--queries-file FILE.jsonl] \
- * [--top-k N=5] \
- * [--judge MODEL=claude-haiku-4-5] \
- * [--max-pairs N=50] \
- * [--output PATH=test/fixtures/contradictions-eval-gold.jsonl] \
- * [--non-interactive]
- *
- * Interactive flow:
- * - Probe runs with --no-cache (so candidate pairs aren't pre-judged).
- * - For each candidate pair, the script prints A + B and prompts:
- * y) contradiction, n) not contradiction, s) skip
- * If y: prompt for severity (low|medium|high) and one-line axis.
- * - After labeling, redact in-memory, write JSONL with audit comments.
- * - Pre-commit safety: isCleanForCommit per line. Failures abort with
- * a sentinel string the operator must resolve manually.
- *
- * Non-interactive flow (`--non-interactive`): captures candidates with
- * NO labels, redacts, writes JSONL. Operator labels manually later.
- */
-
-import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';
-import { dirname } from 'node:path';
-import { createInterface } from 'node:readline/promises';
-import { stdin as input, stdout as output } from 'node:process';
-import { loadConfig, toEngineConfig } from '../src/core/config.ts';
-import { createEngine } from '../src/core/engine-factory.ts';
-import { connectWithRetry } from '../src/core/db.ts';
-import type { BrainEngine } from '../src/core/engine.ts';
-import { runContradictionProbe } from '../src/core/eval-contradictions/runner.ts';
-
-async function connectLocalEngine(): Promise<BrainEngine> {
- const cfg = loadConfig();
- if (!cfg) throw new Error('No brain configured. Run `gbrain init` first.');
- const engineCfg = toEngineConfig(cfg);
- const engine = await createEngine(engineCfg);
- await connectWithRetry(engine, engineCfg, { noRetry: false });
- return engine;
-}
-import {
- createRedactionSession,
- isCleanForCommit,
- redactSlug,
- redactText,
-} from '../src/core/eval-contradictions/fixture-redact.ts';
-import type { ContradictionPair, Severity } from '../src/core/eval-contradictions/types.ts';
-
-interface ParsedFlags {
- queriesFile?: string;
- topK: number;
- judge: string;
- maxPairs: number;
- output: string;
- nonInteractive: boolean;
- help: boolean;
-}
-
-function parseFlags(argv: string[]): ParsedFlags {
- const f: ParsedFlags = {
- topK: 5,
- judge: 'anthropic:claude-haiku-4-5',
- maxPairs: 50,
- output: 'test/fixtures/contradictions-eval-gold.jsonl',
- nonInteractive: false,
- help: false,
- };
- for (let i = 0; i < argv.length; i++) {
- const a = argv[i];
- const next = (): string => {
- const v = argv[++i];
- if (v === undefined) throw new Error(`flag ${a} requires a value`);
- return v;
- };
- if (a === '--help' || a === '-h') f.help = true;
- else if (a === '--queries-file') f.queriesFile = next();
- else if (a === '--top-k') f.topK = Number.parseInt(next(), 10);
- else if (a === '--judge') f.judge = next();
- else if (a === '--max-pairs') f.maxPairs = Number.parseInt(next(), 10);
- else if (a === '--output') f.output = next();
- else if (a === '--non-interactive') f.nonInteractive = true;
- else throw new Error(`unknown flag: ${a}`);
- }
- return f;
-}
-
-function printHelp(): void {
- process.stderr.write(`Build a privacy-redacted gold fixture for the contradiction probe judge.
-
-Usage:
- bun run scripts/build-contradictions-fixture.ts \\
- --queries-file FILE.jsonl # one JSON object per line, {query: "..."}
- [--top-k N=5]
- [--judge MODEL=claude-haiku-4-5]
- [--max-pairs N=50]
- [--output PATH=test/fixtures/contradictions-eval-gold.jsonl]
- [--non-interactive]
-
-Output: JSONL with one labeled-and-redacted pair per line. Lines that
-fail isCleanForCommit are marked with a sentinel string the operator
-MUST resolve manually before commit. Audit log printed to stderr.
-`);
-}
-
-function readQueriesFile(path: string): string[] {
- const raw = readFileSync(path, 'utf8');
- const out: string[] = [];
- for (const line of raw.split(/\r?\n/)) {
- const trimmed = line.trim();
- if (!trimmed) continue;
- if (trimmed.startsWith('{')) {
- try {
- const parsed = JSON.parse(trimmed) as { query?: string };
- if (typeof parsed.query === 'string' && parsed.query.length > 0) {
- out.push(parsed.query);
- }
- } catch {
- // ignore
- }
- } else {
- out.push(trimmed);
- }
- }
- return out;
-}
-
-async function promptLabel(rl: ReturnType<typeof createInterface>, pair: ContradictionPair): Promise<{
- contradicts: boolean;
- severity: Severity;
- axis: string;
- skip: boolean;
-}> {
- process.stderr.write(`\n--- Pair ---\n`);
- process.stderr.write(`A (${pair.a.slug}): ${pair.a.text.slice(0, 240)}${pair.a.text.length > 240 ? '…' : ''}\n`);
- process.stderr.write(`B (${pair.b.slug}): ${pair.b.text.slice(0, 240)}${pair.b.text.length > 240 ? '…' : ''}\n`);
- const ans = (await rl.question('Contradiction? [y/n/s skip]: ')).trim().toLowerCase();
- if (ans === 's' || ans === 'skip') {
- return { contradicts: false, severity: 'low', axis: '', skip: true };
- }
- if (ans !== 'y' && ans !== 'yes') {
- return { contradicts: false, severity: 'low', axis: '', skip: false };
- }
- let sev = (await rl.question('Severity [low/medium/high, default low]: ')).trim().toLowerCase();
- if (sev !== 'low' && sev !== 'medium' && sev !== 'high') sev = 'low';
- const axis = (await rl.question('One-line axis: ')).trim();
- return { contradicts: true, severity: sev as Severity, axis, skip: false };
-}
-
-async function main(): Promise<void> {
- let flags: ParsedFlags;
- try {
- flags = parseFlags(process.argv.slice(2));
- } catch (err) {
- process.stderr.write(`Error: ${(err as Error).message}\n`);
- printHelp();
- process.exit(2);
- }
- if (flags.help) {
- printHelp();
- return;
- }
-
- if (!flags.queriesFile) {
- process.stderr.write(`--queries-file is required for the fixture build.\n`);
- printHelp();
- process.exit(2);
- }
-
- const queries = readQueriesFile(flags.queriesFile);
- if (queries.length === 0) {
- process.stderr.write(`No queries in ${flags.queriesFile}.\n`);
- process.exit(2);
- }
-
- process.stderr.write(`Building gold fixture against the local brain.\n`);
- process.stderr.write(`Queries: ${queries.length} Top-K: ${flags.topK} Max pairs: ${flags.maxPairs}\n`);
- process.stderr.write(`Output: ${flags.output}\n\n`);
-
- const engine = await connectLocalEngine();
- try {
- // Run the probe with --no-cache so we get candidate pairs without
- // pre-judged verdicts. We don't keep verdicts; we hand-label every pair.
- // We intercept pairs via judgeFn returning contradicts:false (so nothing
- // is filtered to findings) and accumulating them for labeling instead.
- const candidatePairs: ContradictionPair[] = [];
- await runContradictionProbe({
- engine,
- queries,
- judgeModel: flags.judge,
- topK: flags.topK,
- noCache: true,
- // Wide budget so we don't hit cap during candidate collection.
- budgetUsd: 100,
- yesOverride: true,
- // Hijack the judge to collect pairs without spending tokens.
- judgeFn: async (input) => {
- candidatePairs.push({
- kind: 'cross_slug_chunks', // best-effort label; runner emits both kinds
- a: { slug: input.a.slug, chunk_id: 0, take_id: null, source_tier: 'curated', holder: input.a.holder ?? null, text: input.a.text },
- b: { slug: input.b.slug, chunk_id: 0, take_id: null, source_tier: 'curated', holder: input.b.holder ?? null, text: input.b.text },
- combined_score: 0,
- });
- return {
- verdict: { contradicts: false, severity: 'low', axis: '', confidence: 0, resolution_kind: null },
- usage: { inputTokens: 0, outputTokens: 0 },
- };
- },
- });
-
- process.stderr.write(`\nCollected ${candidatePairs.length} candidate pairs.\n`);
- const capped = candidatePairs.slice(0, flags.maxPairs);
-
- // Label.
- const rl = createInterface({ input, output });
- const session = createRedactionSession();
- const labeled: Array<{
- contradicts: boolean;
- severity: Severity;
- axis: string;
- query_redacted: string;
- a: { slug: string; text: string };
- b: { slug: string; text: string };
- }> = [];
-
- for (let i = 0; i < capped.length; i++) {
- const pair = capped[i];
- process.stderr.write(`\n[${i + 1}/${capped.length}]`);
- let label: { contradicts: boolean; severity: Severity; axis: string; skip: boolean };
- if (flags.nonInteractive) {
- label = { contradicts: false, severity: 'low', axis: '', skip: false };
- } else {
- label = await promptLabel(rl, pair);
- if (label.skip) continue;
- }
- const redactedA = {
- slug: redactSlug(session, pair.a.slug),
- text: redactText(session, pair.a.text),
- };
- const redactedB = {
- slug: redactSlug(session, pair.b.slug),
- text: redactText(session, pair.b.text),
- };
- labeled.push({
- contradicts: label.contradicts,
- severity: label.severity,
- axis: redactText(session, label.axis),
- // Query gets redacted too, in case it referenced real names.
- query_redacted: '', // candidatePairs don't carry the query; populated by future iteration
- a: redactedA,
- b: redactedB,
- });
- }
- rl.close();
-
- // Pre-commit safety: every text field must pass isCleanForCommit.
- const out: string[] = [];
- let flagged = 0;
- out.push(`# Gold fixture for contradiction probe judge (v0.32.6)`);
- out.push(`# schema_version: 1`);
- out.push(`# Generated: ${new Date().toISOString()}`);
- out.push(`# Audit (in-memory redactions applied):`);
- for (const entry of session.audit.slice(0, 100)) {
- out.push(`# ${entry}`);
- }
- out.push(`# Total redactions: ${session.audit.length}`);
- out.push(`#`);
- for (const row of labeled) {
- const cleanA = isCleanForCommit(row.a.text) && isCleanForCommit(row.a.slug);
- const cleanB = isCleanForCommit(row.b.text) && isCleanForCommit(row.b.slug);
- const sentinel = !cleanA || !cleanB ? ' [REDACT?]' : '';
- if (sentinel) flagged++;
- out.push(JSON.stringify({ ...row, ...(sentinel ? { _operator_review: 'REDACTION INCOMPLETE — fix manually before commit' } : {}) }));
- }
-
- // Ensure output dir exists, then write.
- mkdirSync(dirname(flags.output), { recursive: true });
- if (existsSync(flags.output)) {
- process.stderr.write(`\nWARN: ${flags.output} already exists. Overwriting.\n`);
- }
- writeFileSync(flags.output, out.join('\n') + '\n');
- process.stderr.write(`\nWrote ${labeled.length} labeled pairs to ${flags.output}.\n`);
- if (flagged > 0) {
- process.stderr.write(`*** ${flagged} pair(s) flagged with [REDACT?] — review before commit ***\n`);
- process.exit(1);
- }
- process.stderr.write(`OK — pre-commit safety pass. Inspect the file once more before committing.\n`);
- } finally {
- await engine.disconnect();
- }
-}
-
-main().catch((err) => {
- process.stderr.write(`fatal: ${(err as Error).message}\n`);
- process.exit(1);
-});
diff --git a/scripts/check-exports-count.sh b/scripts/check-exports-count.sh
deleted file mode 100755
index 6021397e81..0000000000
--- a/scripts/check-exports-count.sh
+++ /dev/null
@@ -1,48 +0,0 @@
-#!/usr/bin/env bash
-# CI guard: the public exports surface never shrinks silently (v0.21.0).
-#
-# Precedent: scripts/check-jsonb-pattern.sh + check-progress-to-stdout.sh
-# are grep-based structural guards wired into `bun run test`. This one
-# counts the entries in package.json "exports" and fails when the count
-# drops below the v0.21.0 baseline (17 entries).
-#
-# Policy (from CLAUDE.md):
-# "Removing any of these is a breaking change going forward."
-#
-# If you're legitimately removing a public export: bump gbrain's minor
-# version, note the removal in CHANGELOG.md under a "Breaking changes"
-# bullet, then bump EXPECTED_COUNT below. Anything else is a regression.
-#
-# Adding a new export: update EXPECTED_COUNT to match AND extend the
-# EXPECTED_EXPORTS list in test/public-exports.test.ts so the runtime
-# contract test pins the canary symbol.
-
-set -euo pipefail
-
-EXPECTED_COUNT=28
-
-# Count top-level keys in the exports object. `node -e` parses JSON
-# reliably without needing jq (which isn't in every CI environment).
-ACTUAL=$(node -e "
- const pkg = require('./package.json');
- console.log(Object.keys(pkg.exports || {}).length);
-")
-
-if [ "$ACTUAL" -lt "$EXPECTED_COUNT" ]; then
- echo "❌ public-exports guard: package.json exports shrank from $EXPECTED_COUNT to $ACTUAL"
- echo " Removing a public export is a breaking change (see CLAUDE.md)."
- echo " If intentional: bump gbrain minor version + update EXPECTED_COUNT in"
- echo " scripts/check-exports-count.sh and EXPECTED_EXPORTS in"
- echo " test/public-exports.test.ts, AND add a CHANGELOG 'Breaking changes' bullet."
- exit 1
-fi
-
-if [ "$ACTUAL" -gt "$EXPECTED_COUNT" ]; then
- echo "⚠️ public-exports guard: package.json exports grew from $EXPECTED_COUNT to $ACTUAL"
- echo " Additive public API change. Update EXPECTED_COUNT in this script + the"
- echo " EXPECTED_EXPORTS list in test/public-exports.test.ts to lock the new"
- echo " canary symbols."
- exit 1
-fi
-
-echo "✓ public-exports guard: $ACTUAL entries (matches baseline $EXPECTED_COUNT)"
diff --git a/scripts/check-orphan-modules.mjs b/scripts/check-orphan-modules.mjs
index 30ee9b34e2..a9cdc8eb6c 100644
--- a/scripts/check-orphan-modules.mjs
+++ b/scripts/check-orphan-modules.mjs
@@ -42,14 +42,7 @@ const SELF = 'scripts/check-orphan-modules.mjs';
// even tests. SHRINK-ONLY: a stale entry (module became reachable or was
// deleted) fails the guard so the list can't rot.
const ALLOWLIST = new Map([
- // Alternate chunker strategies kept as documented options for the chunker
- // registry; selectable via config in a future wave, currently unreferenced.
- ['src/core/chunkers/semantic.ts', 'alternate chunker strategy, config-selectable follow-up'],
- ['src/core/chunkers/llm.ts', 'alternate chunker strategy, config-selectable follow-up'],
- // Standalone single-arm search entrypoints superseded by search/hybrid's
- // internal arms; retained for the eval harness comparison work.
- ['src/core/search/keyword.ts', 'single-arm search kept for eval comparisons'],
- ['src/core/search/vector.ts', 'single-arm search kept for eval comparisons'],
+ // Empty: every module is reachable from an entrypoint or a test.
]);
// Permitted test-only modules (repo mode): unreachable from every runtime
@@ -61,13 +54,11 @@ const ALLOWLIST = new Map([
// reason 'script-reachable', which the guard verifies.
const PERMITTED_TEST_ONLY = [
{ path: 'src/core/bootstrap/template-repo.ts', reason: 'script-reachable' },
- { path: 'src/core/eval-contradictions/fixture-redact.ts', reason: 'script-reachable' },
{ path: 'src/eval/longmemeval/diagnostics.ts', reason: 'script-reachable' },
{ path: 'src/eval/longmemeval/evidence-packet.ts', reason: 'script-reachable' },
{ path: 'src/eval/shared/autocut-replay.ts', reason: 'script-reachable' },
{ path: 'src/mcp/http-transport.ts', reason: 'script-reachable' },
{ path: 'src/mcp/tool-catalog.ts', reason: 'script-reachable' },
- { path: 'src/core/postgres-engine/forward-reference-bootstrap.ts', reason: 'held: refactor wave 1 E1 façade re-exporting engine-sql/bootstrap.ts (CLAUDE.md façade rule); every runtime caller imports engine-sql/bootstrap.ts' },
{ path: 'src/core/archive-crawler-config.ts', reason: "held: skills/archive-crawler/SKILL.md describes the scan_paths safety fence as code-enforced; wire-or-retract is a product decision" },
{ path: 'src/core/onboard/impact-capture.ts', reason: 'held: sole writer of migration_impact_log, which the shipped `gbrain onboard --history` reads; wire-or-retract is a product decision' },
{ path: 'src/core/progressive-batch/orchestrator.ts', reason: 'held: TODOS.md keeps an open item to re-compose progressive-batch with --workers on the 3 reindex sites (callers dropped in the v0.41.17.0 merge)' },
diff --git a/scripts/fix-v0.11.0.sh b/scripts/fix-v0.11.0.sh
deleted file mode 100755
index ad3a2edac9..0000000000
--- a/scripts/fix-v0.11.0.sh
+++ /dev/null
@@ -1,171 +0,0 @@
-#!/usr/bin/env bash
-# fix-v0.11.0.sh — stopgap for broken v0.11.0 installs where the Minions
-# migration never fired on upgrade.
-#
-# Usage:
-# curl -fsSL https://raw.githubusercontent.com/garrytan/gbrain/v0.11.1/scripts/fix-v0.11.0.sh | bash
-#
-# What it does:
-# 1. gbrain init --migrate-only — applies schema v7 without touching config.
-# 2. gbrain jobs smoke — fails loudly if Minions isn't healthy.
-# 3. Prompts for minion_mode (or defaults to pain_triggered on non-TTY).
-# 4. Atomically writes ~/.gbrain/preferences.json (0o600).
-# 5. Appends ~/.gbrain/migrations/completed.jsonl with status:"partial" and
-# apply_migrations_pending: true — the v0.11.1 `apply-migrations` runner
-# will pick up where we left off (host rewrites, autopilot install).
-# 6. Detects host AGENTS.md / cron/jobs.json and PRINTS the rewrite guidance
-# as text. Never auto-edits host files from a curl-piped script — too
-# high blast-radius (user trust model is "I pasted this").
-# 7. Final line: tells the user to run `gbrain autopilot --install` as the
-# one-stop finisher (autopilot forks the Minions worker as a child).
-#
-# Retires when v0.11.1 is out: the canonical fix becomes
-# gbrain upgrade && gbrain apply-migrations
-
-set -euo pipefail
-
-RED=$'\033[1;31m'
-GREEN=$'\033[1;32m'
-YELLOW=$'\033[1;33m'
-NC=$'\033[0m'
-
-say() { printf "%s%s%s\n" "$1" "$2" "$NC"; }
-info() { say "" "$1"; }
-ok() { say "$GREEN" "$1"; }
-warn() { say "$YELLOW" "$1"; }
-die() { say "$RED" "$1"; exit 1; }
-
-command -v gbrain >/dev/null 2>&1 || die "gbrain not found on \$PATH. Install it first (\`bun add -g gbrain\` or download a binary)."
-
-GBRAIN_DIR="${HOME}/.gbrain"
-PREFS_PATH="${GBRAIN_DIR}/preferences.json"
-COMPLETED_PATH="${GBRAIN_DIR}/migrations/completed.jsonl"
-
-mkdir -p "${GBRAIN_DIR}/migrations"
-
-# ------------------------------------------------------------
-# Step 1: schema
-# ------------------------------------------------------------
-info "[1/8] Applying schema (gbrain init --migrate-only)..."
-if ! gbrain init --migrate-only; then
- die "Schema migration failed. Check ~/.gbrain/config.json has a valid database_url (or database_path for PGLite), then re-run."
-fi
-ok " schema ok"
-
-# ------------------------------------------------------------
-# Step 2: smoke
-# ------------------------------------------------------------
-info "[2/8] Running Minions smoke test (gbrain jobs smoke)..."
-if ! gbrain jobs smoke; then
- die "Smoke test failed. See the error above. Fix before continuing."
-fi
-ok " smoke ok"
-
-# ------------------------------------------------------------
-# Step 3: mode prompt
-# ------------------------------------------------------------
-info "[3/8] Choose minion_mode..."
-MODE="pain_triggered"
-if [ -t 0 ] && [ -t 1 ]; then
- echo ""
- echo " [1] always — route every background task through Minions (most durable)"
- echo " [2] pain_triggered — default to native subagents, switch to Minions on pain signals (recommended)"
- echo " [3] off — disable Minions; keep native subagents"
- echo ""
- read -r -p " Choice [2]: " CHOICE
- case "${CHOICE:-2}" in
- 1) MODE="always" ;;
- 3) MODE="off" ;;
- *) MODE="pain_triggered" ;;
- esac
-else
- warn " non-interactive shell → defaulting to pain_triggered (change later: \`gbrain config set minion_mode <mode>\`)"
-fi
-ok " mode=${MODE}"
-
-# ------------------------------------------------------------
-# Step 4: atomic write preferences.json (0o600)
-# ------------------------------------------------------------
-info "[4/8] Writing ~/.gbrain/preferences.json..."
-NOW_ISO=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
-TMP_PREFS=$(mktemp)
-cat > "${TMP_PREFS}" <<EOF
-{
- "minion_mode": "${MODE}",
- "set_at": "${NOW_ISO}",
- "set_in_version": "0.11.0"
-}
-EOF
-chmod 600 "${TMP_PREFS}"
-mv "${TMP_PREFS}" "${PREFS_PATH}"
-chmod 600 "${PREFS_PATH}"
-ok " wrote ${PREFS_PATH}"
-
-# ------------------------------------------------------------
-# Step 5: append completed.jsonl as status:"partial"
-# ------------------------------------------------------------
-info "[5/8] Recording migration as partial..."
-# We write "partial" + apply_migrations_pending:true. v0.11.1 apply-migrations
-# detects this and resumes the remaining phases (host rewrites + autopilot
-# install). If we wrote "complete" here, apply-migrations would SKIP the
-# remaining phases and the broken install would stay broken (Codex H2).
-echo "{\"version\":\"0.11.0\",\"status\":\"partial\",\"apply_migrations_pending\":true,\"mode\":\"${MODE}\",\"ts\":\"${NOW_ISO}\",\"source\":\"fix-v0.11.0.sh\"}" >> "${COMPLETED_PATH}"
-ok " appended ${COMPLETED_PATH}"
-
-# ------------------------------------------------------------
-# Step 6: detect AGENTS.md — PRINT guidance, do not auto-edit
-# ------------------------------------------------------------
-info "[6/8] Scanning for AGENTS.md..."
-AGENTS_FOUND=()
-for CANDIDATE in "${HOME}/.claude/AGENTS.md" "${HOME}/.openclaw/AGENTS.md" "${PWD}/AGENTS.md"; do
- [ -f "${CANDIDATE}" ] && AGENTS_FOUND+=("${CANDIDATE}")
-done
-if [ ${#AGENTS_FOUND[@]} -eq 0 ]; then
- ok " no AGENTS.md found — nothing to suggest"
-else
- for F in "${AGENTS_FOUND[@]}"; do
- warn " AGENTS.md detected: ${F}"
- echo " - Next steps (this script does NOT auto-edit):"
- echo " 1. Add a pointer to skills/conventions/subagent-routing.md"
- echo " 2. The v0.11.1 binary's \`gbrain apply-migrations --yes\` will inject"
- echo " this automatically once v0.11.1 is installed."
- done
-fi
-
-# ------------------------------------------------------------
-# Step 7: detect cron/jobs.json and scan for agentTurn
-# ------------------------------------------------------------
-info "[7/8] Scanning for cron manifests..."
-CRON_FOUND=()
-for CANDIDATE in "${HOME}/.claude/cron/jobs.json" "${HOME}/.openclaw/cron/jobs.json" "${PWD}/cron/jobs.json"; do
- [ -f "${CANDIDATE}" ] && CRON_FOUND+=("${CANDIDATE}")
-done
-if [ ${#CRON_FOUND[@]} -eq 0 ]; then
- ok " no cron/jobs.json found — nothing to suggest"
-else
- for F in "${CRON_FOUND[@]}"; do
- warn " cron manifest detected: ${F}"
- COUNT=$(grep -c 'agentTurn' "${F}" 2>/dev/null || echo 0)
- echo " - ${COUNT} agentTurn entries"
- echo " - v0.11.1 apply-migrations will:"
- echo " * auto-rewrite builtin handlers (sync/embed/lint/import/"
- echo " extract/backlinks/autopilot-cycle) to gbrain jobs submit"
- echo " * emit a pending-host-work.jsonl TODO for every non-builtin"
- echo " handler; host agent walks those per skills/migrations/v0.11.0.md"
- done
-fi
-
-# ------------------------------------------------------------
-# Step 8: final line
-# ------------------------------------------------------------
-info "[8/8] Done. Next step:"
-echo ""
-echo " ${GREEN}gbrain autopilot --install${NC}"
-echo ""
-echo " That ONE command does the rest: supervises autopilot, forks the"
-echo " Minions worker, and installs the right entry for your host (launchd"
-echo " on macOS, systemd on Linux, bootstrap hook on ephemeral containers)."
-echo ""
-echo " Once v0.11.1 is out:"
-echo " ${GREEN}gbrain upgrade && gbrain apply-migrations${NC}"
-echo " becomes the canonical fix. This script retires then."
diff --git a/scripts/guards-manifest.tsv b/scripts/guards-manifest.tsv
index d47e8fbbb0..359e6bb4c8 100644
--- a/scripts/guards-manifest.tsv
+++ b/scripts/guards-manifest.tsv
@@ -42,7 +42,6 @@ check-worker-pool-atomicity.sh scanner todo
check-gateway-routed-no-direct-anthropic.sh scanner yes no runtime @anthropic-ai/sdk import or new Anthropic() in gateway-routed files; GBRAIN_GUARD_ROOT seam
check-engine-dynamic-import.sh scanner yes .ts companion is its implementation, not a separate guard; scans engine façades, their module dirs, engine-sql/ and schema-migrations/; GBRAIN_GUARD_ROOT seam
check-key-files-current-state.sh scanner todo
-check-exports-count.sh scanner todo was reachable from neither verify nor CI pre-W0 (check:all only)
check-trailing-newline.sh scanner yes tracked src/test/root text files end with a newline (guard fixtures excluded); GBRAIN_GUARD_ROOT seam scans with find
check-test-isolation.sh scanner todo allowlist data file: check-test-isolation.allowlist
check-compile-autoload.sh scanner yes every `bun build --compile` invocation (CLI one-liners + TS spawn arrays) in package.json/.github/scripts/docs/CLAUDE.md/CONTRIBUTING.md must carry --no-compile-autoload-bunfig (a cwd bunfig.toml preload runs before cli-preflight in a compiled binary); also every curated help record in src/cli/command-table.ts loads its src/cli/help/<name>.ts module through a literal () => import() (D3), and every spec module has a record
diff --git a/scripts/run-verify-parallel.sh b/scripts/run-verify-parallel.sh
index 0535700910..4b36358d91 100755
--- a/scripts/run-verify-parallel.sh
+++ b/scripts/run-verify-parallel.sh
@@ -130,7 +130,6 @@ CHECKS=(
"check:skill-refs"
# Previously reachable ONLY from the deleted check:all (i.e. never run):
"check:newlines"
- "check:exports-count"
"check:no-legacy-getconnection"
# Revived registered-but-never-executed guards (this pass):
"check:pg-url-redaction"
diff --git a/scripts/smoke-test-mcp.ts b/scripts/smoke-test-mcp.ts
deleted file mode 100644
index 3d873b5736..0000000000
--- a/scripts/smoke-test-mcp.ts
+++ /dev/null
@@ -1,96 +0,0 @@
-#!/usr/bin/env bun
-/**
- * Smoke test: verify MCP tool calls work against a real database.
- * Usage: DATABASE_URL=... bun run scripts/smoke-test-mcp.ts
- */
-import { PostgresEngine } from '../src/core/postgres-engine.ts';
-import { handleToolCall } from '../src/mcp/server.ts';
-
-const DB_URL = process.env.DATABASE_URL;
-if (!DB_URL) { console.error('Set DATABASE_URL'); process.exit(1); }
-
-const eng = new PostgresEngine();
-await eng.connect({ database_url: DB_URL });
-
-let passed = 0;
-let failed = 0;
-
-async function test(name: string, fn: () => Promise<void>) {
- try {
- await fn();
- console.log(` ✓ ${name}`);
- passed++;
- } catch (e: any) {
- console.log(` ✗ ${name}: ${e.message}`);
- failed++;
- }
-}
-
-console.log('MCP Smoke Test\n');
-
-await test('get_stats returns counts', async () => {
- const stats = await handleToolCall(eng, 'get_stats', {}) as any;
- if (typeof stats.page_count !== 'number') throw new Error('page_count missing');
-});
-
-await test('put_page creates a page', async () => {
- await handleToolCall(eng, 'put_page', {
- slug: 'smoke/test-page',
- content: '---\ntitle: Smoke Test Page\ntype: note\n---\n\nThis page was created by the MCP smoke test.',
- });
-});
-
-await test('get_page retrieves the page', async () => {
- const page = await handleToolCall(eng, 'get_page', { slug: 'smoke/test-page' }) as any;
- if (page.title !== 'Smoke Test Page') throw new Error(`Wrong title: ${page.title}`);
-});
-
-await test('dry_run prevents mutation', async () => {
- const result = await handleToolCall(eng, 'put_page', {
- slug: 'smoke/should-not-exist',
- content: '---\ntitle: Should Not Exist\ntype: note\n---\n\ndry run test',
- dry_run: true,
- }) as any;
- if (!result.dry_run) throw new Error('dry_run flag not returned');
- // Verify page was NOT created
- try {
- await handleToolCall(eng, 'get_page', { slug: 'smoke/should-not-exist' });
- throw new Error('Page was created despite dry_run');
- } catch (e: any) {
- if (!e.message.includes('not found') && !e.code) throw e;
- }
-});
-
-await test('search finds the page', async () => {
- const results = await handleToolCall(eng, 'search', { query: 'smoke test' }) as any[];
- if (!Array.isArray(results)) throw new Error('search should return array');
- // Keyword search may or may not find it depending on search_vector trigger
-});
-
-await test('list_pages includes our page', async () => {
- const pages = await handleToolCall(eng, 'list_pages', { limit: 100 }) as any[];
- const found = pages.find((p: any) => p.slug === 'smoke/test-page');
- if (!found) throw new Error('smoke/test-page not in list');
-});
-
-await test('add_tag and get_tags work', async () => {
- await handleToolCall(eng, 'add_tag', { slug: 'smoke/test-page', tag: 'smoke-test' });
- const tags = await handleToolCall(eng, 'get_tags', { slug: 'smoke/test-page' }) as string[];
- if (!tags.includes('smoke-test')) throw new Error('tag not found');
-});
-
-await test('delete_page cleans up', async () => {
- await handleToolCall(eng, 'delete_page', { slug: 'smoke/test-page' });
- try {
- await handleToolCall(eng, 'get_page', { slug: 'smoke/test-page' });
- throw new Error('Page still exists after delete');
- } catch (e: any) {
- if (!e.message.includes('not found') && !e.code) throw e;
- }
-});
-
-await eng.disconnect();
-
-console.log(`\n${passed} passed, ${failed} failed`);
-if (failed > 0) process.exit(1);
-console.log('\n🧠 MCP smoke test passed!');
diff --git a/scripts/spike-bun-vm-timeout.ts b/scripts/spike-bun-vm-timeout.ts
deleted file mode 100644
index 9772269973..0000000000
--- a/scripts/spike-bun-vm-timeout.ts
+++ /dev/null
@@ -1,86 +0,0 @@
-#!/usr/bin/env bun
-// v0.38 spike: does Bun's `vm.runInContext({timeout})` actually interrupt
-// a catastrophic-backtracking regex?
-//
-// E6 locked vm.runInContext as the ReDoS guard. E9 required this spike
-// to derisk before production: Node's vm.timeout is well-tested but
-// Bun's implementation is younger. If the spike PASSES, the redos-guard
-// path is trusted. If it FAILS, fall back to E6 option B (persistent
-// worker pool); the public API in src/core/schema-pack/redos-guard.ts
-// stays the same.
-//
-// Test case: classic catastrophic regex `^(a+)+$` against a 1MB string
-// of 'a' characters with a trailing 'b'. Without a timeout, this would
-// pin CPU for hours. With timeout=50ms, vm should throw within ~50ms.
-//
-// Run: bun scripts/spike-bun-vm-timeout.ts
-// Exit codes:
-// 0 = PASS (timeout fired within budget; production path is safe)
-// 1 = FAIL (timeout did NOT interrupt; fall back to worker pool)
-// 2 = INCONCLUSIVE (test couldn't run; treat as FAIL)
-
-import { runInContext, createContext } from 'node:vm';
-
-const PATTERN = '^(a+)+$';
-const TEXT = 'a'.repeat(1_000_000) + 'b';
-const TIMEOUT_MS = 50;
-const BUDGET_MS = 200; // generous — if it takes > 200ms, the timeout failed
-
-function timeMs(): number { return performance.now(); }
-
-console.log('[spike] testing vm.runInContext timeout against catastrophic regex');
-console.log(`[spike] pattern: ${PATTERN}`);
-console.log(`[spike] input: 'a' × ${TEXT.length} + 'b'`);
-console.log(`[spike] timeout: ${TIMEOUT_MS}ms`);
-console.log(`[spike] budget: ${BUDGET_MS}ms (must throw within this window)`);
-console.log('');
-
-const ctx = createContext({ pattern: PATTERN, text: TEXT });
-const code = `(new RegExp(pattern)).exec(text)`;
-
-const start = timeMs();
-let elapsed = 0;
-let outcome: 'timeout' | 'completed' | 'budget-exceeded' = 'completed';
-let errorMessage = '';
-
-try {
- const result = runInContext(code, ctx, { timeout: TIMEOUT_MS });
- elapsed = timeMs() - start;
- if (elapsed > BUDGET_MS) {
- outcome = 'budget-exceeded';
- console.log(`[spike] FAIL: regex completed in ${elapsed.toFixed(1)}ms (no timeout fired)`);
- console.log(`[spike] result: ${JSON.stringify(result)}`);
- } else {
- console.log(`[spike] regex completed in ${elapsed.toFixed(1)}ms — unexpected fast exec`);
- }
-} catch (e) {
- elapsed = timeMs() - start;
- outcome = 'timeout';
- errorMessage = (e as Error).message;
- console.log(`[spike] caught error after ${elapsed.toFixed(1)}ms: ${errorMessage}`);
-}
-
-console.log('');
-console.log('[spike] outcome:', outcome);
-console.log('[spike] elapsed:', `${elapsed.toFixed(1)}ms`);
-
-if (outcome === 'timeout') {
- console.log('');
- console.log('[spike] PASS: vm.runInContext timeout DID interrupt catastrophic regex.');
- console.log(`[spike] wall-clock latency: ~${elapsed.toFixed(0)}ms for a ${TIMEOUT_MS}ms configured timeout.`);
- console.log('[spike] interpretation: Bun checks timeout at instruction boundaries; for tight');
- console.log('[spike] backtracking loops, actual interrupt latency is ~10x the configured value.');
- console.log('[spike] this is fine — one catastrophic regex burns the per-page budget; the');
- console.log('[spike] remaining verbs degrade to mentions per design.');
- console.log('[spike] production path in src/core/schema-pack/redos-guard.ts is SAFE.');
- process.exit(0);
-} else if (outcome === 'budget-exceeded') {
- console.log('');
- console.log('[spike] FAIL: timeout did NOT fire and regex ran to completion.');
- console.log('[spike] action: swap redos-guard.runRegexBounded for E6 option B (persistent worker pool).');
- process.exit(1);
-} else {
- console.log('');
- console.log('[spike] INCONCLUSIVE: regex completed too fast — input may be too small.');
- process.exit(2);
-}
diff --git a/scripts/test-weights.json b/scripts/test-weights.json
index c372d0758f..ccac0f65e8 100644
--- a/scripts/test-weights.json
+++ b/scripts/test-weights.json
@@ -678,7 +678,6 @@
"test/eval-contradictions-cross-source.test.ts": 8,
"test/eval-contradictions-date-filter.test.ts": 3,
"test/eval-contradictions-engine.test.ts": 1779,
- "test/eval-contradictions-fixture-redact.test.ts": 18,
"test/eval-contradictions-integrations.test.ts": 774,
"test/eval-contradictions-judge-errors.test.ts": 10,
"test/eval-contradictions-judge.test.ts": 8,
diff --git a/scripts/ubicloud/weights.json b/scripts/ubicloud/weights.json
index e446287924..8aa530b152 100644
--- a/scripts/ubicloud/weights.json
+++ b/scripts/ubicloud/weights.json
@@ -1288,7 +1288,6 @@
"unit:test/eval-contradictions-cross-source.test.ts": 206,
"unit:test/eval-contradictions-date-filter.test.ts": 178,
"unit:test/eval-contradictions-engine.test.ts": 3253,
- "unit:test/eval-contradictions-fixture-redact.test.ts": 179,
"unit:test/eval-contradictions-integrations.test.ts": 2030,
"unit:test/eval-contradictions-judge-errors.test.ts": 162,
"unit:test/eval-contradictions-judge.test.ts": 189,
diff --git a/src/assets/wasm/README.md b/src/assets/wasm/README.md
index d4994bacf8..1e97e71c4b 100644
--- a/src/assets/wasm/README.md
+++ b/src/assets/wasm/README.md
@@ -37,3 +37,16 @@ advances to 7 to trigger the existing re-chunk gate when Git HEAD is unchanged.
That gate does not force a full walk when new commits are present; use
`gbrain sync --source <id> --full` to recover all previously affected files in
an active repository rather than relying on an incremental sync.
+
+## Dart (#3356)
+
+`grammars/tree-sitter-dart.wasm` is the one grammar not taken from the
+`tree-sitter-wasms` npm bundle: that package's Dart build is ABI 15, which the
+pinned `[email protected]` runtime rejects. `scripts/build-dart-wasm.sh`
+regenerates the same upstream grammar at ABI 14 (needs git, npm and podman or
+docker):
+
+```sh
+bash scripts/build-dart-wasm.sh
+bun run check:wasm
+```
diff --git a/src/commands/extract-conversation-facts.ts b/src/commands/extract-conversation-facts.ts
index 087d9f2bfc..727900d5bb 100644
--- a/src/commands/extract-conversation-facts.ts
+++ b/src/commands/extract-conversation-facts.ts
@@ -653,11 +653,6 @@ export const PER_PAGE_LOCK_TTL_MINUTES = 2;
*/
const _lockBusyLogCache = new Map<string, number>();
-/** Test seam: clear the rate-limit cache so re-runs emit again. */
-export function _resetLockBusyLogCacheForTest(): void {
- _lockBusyLogCache.clear();
-}
-
function logLockBusyRateLimited(sourceId: string, slug: string): void {
const minuteBucket = Math.floor(Date.now() / 60_000);
const key = `${sourceId}:${minuteBucket}`;
diff --git a/src/core/chunkers/llm.ts b/src/core/chunkers/llm.ts
deleted file mode 100644
index bb58ba4aa1..0000000000
--- a/src/core/chunkers/llm.ts
+++ /dev/null
@@ -1,163 +0,0 @@
-/**
- * LLM-Guided Text Chunker
- * Ported from production Ruby implementation (llm_text_chunker.rb, 167 LOC)
- *
- * Algorithm:
- * 1. Pre-split into 128-word candidates via recursive chunker
- * 2. Sliding window of 3+ candidates
- * 3. Ask Claude Haiku: "Where does the FIRST topic shift occur?"
- * 4. Max 3 retries per window on unparseable responses
- * 5. Merge candidates between split points
- */
-
-import { chunkText as recursiveChunk, type TextChunk } from './recursive.ts';
-
-const CANDIDATE_SIZE = 128; // words per pre-split candidate
-const MAX_RETRIES = 3;
-const WINDOW_SIZE = 5; // candidates per window
-
-export interface LlmChunkOptions {
- chunkSize?: number;
- chunkOverlap?: number;
- askLlm?: (prompt: string) => Promise<string>;
-}
-
-export async function chunkTextLlm(
- text: string,
- opts: LlmChunkOptions,
-): Promise<TextChunk[]> {
- const chunkSize = opts.chunkSize || 300;
- const chunkOverlap = opts.chunkOverlap || 50;
- const askLlm = opts.askLlm;
-
- if (!askLlm) {
- return recursiveChunk(text, { chunkSize, chunkOverlap });
- }
-
- try {
- // Step 1: Pre-split into small candidates
- const candidates = recursiveChunk(text, {
- chunkSize: CANDIDATE_SIZE,
- chunkOverlap: 0,
- });
-
- if (candidates.length <= 2) {
- return recursiveChunk(text, { chunkSize, chunkOverlap });
- }
-
- // Step 2: Find split points via LLM
- const splitPoints = await findSplitPoints(candidates, askLlm);
-
- // Step 3: Merge candidates between split points
- const merged = mergeAtSplits(candidates, splitPoints);
-
- return merged.map((t, i) => ({ text: t.trim(), index: i }));
- } catch {
- return recursiveChunk(text, { chunkSize, chunkOverlap });
- }
-}
-
-async function findSplitPoints(
- candidates: TextChunk[],
- askLlm: (prompt: string) => Promise<string>,
-): Promise<number[]> {
- const splitPoints: number[] = [];
- let pos = 0;
-
- while (pos < candidates.length - 1) {
- const windowEnd = Math.min(pos + WINDOW_SIZE, candidates.length);
- const window = candidates.slice(pos, windowEnd);
-
- if (window.length < 2) break;
-
- const splitAt = await askForSplit(window, pos, askLlm);
-
- if (splitAt !== null && splitAt > pos) {
- splitPoints.push(splitAt);
- pos = splitAt;
- } else {
- // No split found in this window, advance by 1
- pos++;
- }
- }
-
- return splitPoints;
-}
-
-async function askForSplit(
- window: TextChunk[],
- offset: number,
- askLlm: (prompt: string) => Promise<string>,
-): Promise<number | null> {
- // Format candidates as numbered items
- const numbered = window
- .map((c, i) => `[${offset + i}] ${c.text.slice(0, 200)}${c.text.length > 200 ? '...' : ''}`)
- .join('\n\n');
-
- const prompt = `You are analyzing a document that has been split into numbered segments. Your job is to find where the FIRST major topic shift occurs.
-
-Here are the segments:
-
-${numbered}
-
-If there is a clear topic shift between any two adjacent segments, respond with ONLY the number of the segment where the NEW topic begins. For example, if the topic shifts between [${offset + 1}] and [${offset + 2}], respond with: ${offset + 2}
-
-If there is no clear topic shift, respond with: NONE
-
-Respond with only a number or NONE. Nothing else.`;
-
- for (let retry = 0; retry < MAX_RETRIES; retry++) {
- try {
- const response = await askLlm(prompt);
- const parsed = parseSplitResponse(response, offset, offset + window.length - 1);
- return parsed;
- } catch {
- continue;
- }
- }
-
- return null;
-}
-
-function parseSplitResponse(
- response: string,
- minId: number,
- maxId: number,
-): number | null {
- const trimmed = response.trim().toUpperCase();
- if (trimmed === 'NONE') return null;
-
- const num = parseInt(trimmed, 10);
- if (isNaN(num)) return null;
-
- // Clamp to valid range, ensure forward progress
- const clamped = Math.max(num, minId + 1);
- if (clamped > maxId) return null;
-
- return clamped;
-}
-
-function mergeAtSplits(candidates: TextChunk[], splitPoints: number[]): string[] {
- if (splitPoints.length === 0) {
- return [candidates.map(c => c.text).join(' ')];
- }
-
- const result: string[] = [];
- let start = 0;
-
- for (const split of splitPoints) {
- const group = candidates.slice(start, split);
- if (group.length > 0) {
- result.push(group.map(c => c.text).join(' '));
- }
- start = split;
- }
-
- // Last group
- const remaining = candidates.slice(start);
- if (remaining.length > 0) {
- result.push(remaining.map(c => c.text).join(' '));
- }
-
- return result.filter(t => t.trim().length > 0);
-}
diff --git a/src/core/chunkers/semantic.ts b/src/core/chunkers/semantic.ts
deleted file mode 100644
index ec90ed4cb7..0000000000
--- a/src/core/chunkers/semantic.ts
+++ /dev/null
@@ -1,342 +0,0 @@
-/**
- * Semantic Text Chunker
- * Ported from production Ruby implementation (semantic_text_chunker.rb, 242 LOC)
- *
- * Algorithm:
- * 1. Split text into sentences
- * 2. Embed each sentence
- * 3. Compute adjacent cosine similarities
- * 4. Savitzky-Golay filter (5-window, 3rd-order polynomial)
- * 5. Find local minima (topic boundaries)
- * 6. Group sentences, recursively split oversized groups
- *
- * Falls back to recursive chunker on any failure.
- */
-
-import { chunkText as recursiveChunk, type TextChunk } from './recursive.ts';
-import { sanitizeRemoteBody } from '../remote-body.ts';
-
-export interface SemanticChunkOptions {
- chunkSize?: number;
- chunkOverlap?: number;
- embedFn?: (texts: string[]) => Promise<Float32Array[]>;
-}
-
-export async function chunkTextSemantic(
- text: string,
- opts: SemanticChunkOptions,
-): Promise<TextChunk[]> {
- text = sanitizeRemoteBody(text);
- const chunkSize = opts.chunkSize || 300;
- const chunkOverlap = opts.chunkOverlap || 50;
- const embedFn = opts.embedFn;
-
- if (!embedFn) {
- return recursiveChunk(text, { chunkSize, chunkOverlap });
- }
-
- try {
- const sentences = splitSentences(text);
- if (sentences.length <= 3) {
- return recursiveChunk(text, { chunkSize, chunkOverlap });
- }
-
- // Embed all sentences
- const embeddings = await embedFn(sentences);
- if (embeddings.length !== sentences.length) {
- return recursiveChunk(text, { chunkSize, chunkOverlap });
- }
-
- // Compute adjacent cosine similarities
- const similarities = computeAdjacentSimilarities(embeddings);
-
- // Find topic boundaries
- const boundaries = findBoundaries(similarities);
-
- // Group sentences at boundaries
- const groups = groupAtBoundaries(sentences, boundaries);
-
- // Recursively split oversized groups
- const chunks: TextChunk[] = [];
- let idx = 0;
- for (const group of groups) {
- const groupText = group.join(' ');
- const wordCount = (groupText.match(/\S+/g) || []).length;
-
- if (wordCount > chunkSize * 1.5) {
- const subChunks = recursiveChunk(groupText, { chunkSize, chunkOverlap });
- for (const sc of subChunks) {
- chunks.push({ text: sc.text, index: idx++ });
- }
- } else {
- chunks.push({ text: groupText.trim(), index: idx++ });
- }
- }
-
- return chunks;
- } catch {
- // Any failure falls back to recursive
- return recursiveChunk(text, { chunkSize, chunkOverlap });
- }
-}
-
-/**
- * Split text into sentences. Handles common abbreviations.
- */
-export function splitSentences(text: string): string[] {
- // Split on sentence-ending punctuation followed by whitespace or newline
- const raw = text.split(/(?<=[.!?])\s+/);
- return raw
- .map(s => s.trim())
- .filter(s => s.length > 0);
-}
-
-/**
- * Compute cosine similarity between each adjacent pair of embeddings.
- * Returns array of length (embeddings.length - 1).
- */
-function computeAdjacentSimilarities(embeddings: Float32Array[]): number[] {
- const sims: number[] = [];
- for (let i = 0; i < embeddings.length - 1; i++) {
- sims.push(cosineSimilarity(embeddings[i], embeddings[i + 1]));
- }
- return sims;
-}
-
-/**
- * Find topic boundaries using Savitzky-Golay smoothing.
- * Falls back to percentile-based detection if SG fails.
- */
-function findBoundaries(similarities: number[]): number[] {
- if (similarities.length < 5) {
- return findBoundariesPercentile(similarities);
- }
-
- try {
- return findBoundariesSavGol(similarities);
- } catch {
- return findBoundariesPercentile(similarities);
- }
-}
-
-/**
- * Savitzky-Golay boundary detection.
- * Apply SG filter to get 1st derivative, find local minima.
- */
-function findBoundariesSavGol(similarities: number[]): number[] {
- // Compute 1st derivative via Savitzky-Golay (window=5, poly=3, deriv=1)
- const derivative = savitzkyGolay(similarities, 5, 3, 1);
-
- // Find zero crossings of the derivative (local minima)
- // A minimum is where derivative goes from negative to positive
- const minima: number[] = [];
- for (let i = 1; i < derivative.length; i++) {
- if (derivative[i - 1] < 0 && derivative[i] >= 0) {
- minima.push(i);
- }
- }
-
- // Filter by percentile: only keep minima where similarity is below 80th percentile
- const threshold = percentile(similarities, 0.2); // low similarity = topic shift
- const filtered = minima.filter(i => {
- const simIdx = Math.min(i, similarities.length - 1);
- return similarities[simIdx] < threshold;
- });
-
- // Enforce minimum distance of 2 between boundaries
- return enforceMinDistance(filtered, 2);
-}
-
-/**
- * Simple percentile-based boundary detection.
- * Find positions where similarity drops below the 20th percentile.
- */
-function findBoundariesPercentile(similarities: number[]): number[] {
- if (similarities.length === 0) return [];
-
- const threshold = percentile(similarities, 0.2);
- const boundaries: number[] = [];
-
- for (let i = 0; i < similarities.length; i++) {
- if (similarities[i] < threshold) {
- boundaries.push(i + 1); // boundary is after position i
- }
- }
-
- return enforceMinDistance(boundaries, 2);
-}
-
-/**
- * Savitzky-Golay filter implementation.
- * Polynomial fitting over a sliding window.
- */
-function savitzkyGolay(
- data: number[],
- windowSize: number,
- polyOrder: number,
- derivOrder: number,
-): number[] {
- const half = Math.floor(windowSize / 2);
- const n = data.length;
-
- if (n < windowSize) return data.slice();
-
- // Build Vandermonde matrix for the window
- const J: number[][] = [];
- for (let i = -half; i <= half; i++) {
- const row: number[] = [];
- for (let j = 0; j <= polyOrder; j++) {
- row.push(Math.pow(i, j));
- }
- J.push(row);
- }
-
- // Compute (J^T J)^-1 J^T
- const JT = transpose(J);
- const JTJ = matMul(JT, J);
- const JTJinv = invertMatrix(JTJ);
- const coeffs = matMul(JTJinv, JT);
-
- // The row corresponding to derivOrder gives us the filter coefficients
- // For derivative of order d, multiply by d!
- const filterRow = coeffs[derivOrder];
- const factorial = factorialN(derivOrder);
-
- const result: number[] = new Array(n).fill(0);
-
- for (let i = 0; i < n; i++) {
- let val = 0;
- for (let j = -half; j <= half; j++) {
- const idx = Math.min(Math.max(i + j, 0), n - 1);
- val += filterRow[j + half] * data[idx];
- }
- result[i] = val * factorial;
- }
-
- return result;
-}
-
-/**
- * Group sentences into chunks at the given boundary positions.
- */
-function groupAtBoundaries(sentences: string[], boundaries: number[]): string[][] {
- const groups: string[][] = [];
- let start = 0;
-
- for (const b of boundaries) {
- if (b > start && b < sentences.length) {
- groups.push(sentences.slice(start, b));
- start = b;
- }
- }
-
- // Last group
- if (start < sentences.length) {
- groups.push(sentences.slice(start));
- }
-
- return groups.length > 0 ? groups : [sentences];
-}
-
-// Math helpers
-
-function cosineSimilarity(a: Float32Array, b: Float32Array): number {
- let dot = 0, normA = 0, normB = 0;
- for (let i = 0; i < a.length; i++) {
- dot += a[i] * b[i];
- normA += a[i] * a[i];
- normB += b[i] * b[i];
- }
- const denom = Math.sqrt(normA) * Math.sqrt(normB);
- return denom === 0 ? 0 : dot / denom;
-}
-
-function percentile(arr: number[], p: number): number {
- const sorted = [...arr].sort((a, b) => a - b);
- const idx = Math.floor(p * sorted.length);
- return sorted[Math.min(idx, sorted.length - 1)];
-}
-
-function enforceMinDistance(boundaries: number[], minDist: number): number[] {
- if (boundaries.length <= 1) return boundaries;
- const result = [boundaries[0]];
- for (let i = 1; i < boundaries.length; i++) {
- if (boundaries[i] - result[result.length - 1] >= minDist) {
- result.push(boundaries[i]);
- }
- }
- return result;
-}
-
-function transpose(m: number[][]): number[][] {
- const rows = m.length, cols = m[0].length;
- const result: number[][] = Array.from({ length: cols }, () => new Array(rows).fill(0));
- for (let i = 0; i < rows; i++) {
- for (let j = 0; j < cols; j++) {
- result[j][i] = m[i][j];
- }
- }
- return result;
-}
-
-function matMul(a: number[][], b: number[][]): number[][] {
- const rows = a.length, cols = b[0].length, inner = b.length;
- const result: number[][] = Array.from({ length: rows }, () => new Array(cols).fill(0));
- for (let i = 0; i < rows; i++) {
- for (let j = 0; j < cols; j++) {
- for (let k = 0; k < inner; k++) {
- result[i][j] += a[i][k] * b[k][j];
- }
- }
- }
- return result;
-}
-
-function invertMatrix(m: number[][]): number[][] {
- const n = m.length;
- // Augment with identity
- const aug: number[][] = m.map((row, i) => {
- const identity = new Array(n).fill(0);
- identity[i] = 1;
- return [...row, ...identity];
- });
-
- // Gauss-Jordan elimination
- for (let col = 0; col < n; col++) {
- // Find pivot
- let maxRow = col;
- for (let row = col + 1; row < n; row++) {
- if (Math.abs(aug[row][col]) > Math.abs(aug[maxRow][col])) {
- maxRow = row;
- }
- }
- [aug[col], aug[maxRow]] = [aug[maxRow], aug[col]];
-
- const pivot = aug[col][col];
- if (Math.abs(pivot) < 1e-12) {
- throw new Error('Matrix is singular');
- }
-
- // Scale pivot row
- for (let j = 0; j < 2 * n; j++) {
- aug[col][j] /= pivot;
- }
-
- // Eliminate column
- for (let row = 0; row < n; row++) {
- if (row === col) continue;
- const factor = aug[row][col];
- for (let j = 0; j < 2 * n; j++) {
- aug[row][j] -= factor * aug[col][j];
- }
- }
- }
-
- return aug.map(row => row.slice(n));
-}
-
-function factorialN(n: number): number {
- let result = 1;
- for (let i = 2; i <= n; i++) result *= i;
- return result;
-}
diff --git a/src/core/cli-force-exit.ts b/src/core/cli-force-exit.ts
index 61f36def72..35e82fee8c 100644
--- a/src/core/cli-force-exit.ts
+++ b/src/core/cli-force-exit.ts
@@ -755,13 +755,6 @@ export function noteRenderedErrorCode(code: string): void {
lastRenderedErrorCode = code;
}
-/** Test seam. */
-export function _resetJsonGuardForTests(): void {
- jsonGuardMode = null;
- jsonDocumentWritten = false;
- lastRenderedErrorCode = undefined;
-}
-
function writeJsonFallbackIfMissing(exitCode: number): void {
if (!jsonGuardMode || jsonDocumentWritten) return;
if (exitCode === 0) {
diff --git a/src/core/engine-sql/bootstrap.ts b/src/core/engine-sql/bootstrap.ts
index feddb1cdaa..5be754ec76 100644
--- a/src/core/engine-sql/bootstrap.ts
+++ b/src/core/engine-sql/bootstrap.ts
@@ -1,8 +1,6 @@
/**
* Forward-reference bootstrap: one implementation for both engines (refactor
- * wave 1, E1). Replaces `PGLiteEngine#applyForwardReferenceBootstrap` and
- * `src/core/postgres-engine/forward-reference-bootstrap.ts`, which carried
- * the same probes and DDL twice (per-probe inventory:
+ * wave 1, E1), so the probes and DDL exist once (per-probe inventory:
* docs/designs/refactor-wave-1/w1-inventory.md, "Forward-reference
* bootstrap (E1)").
*
@@ -103,8 +101,6 @@ export function postgresBootstrapTarget(conn: ReturnType<typeof postgres>): Forw
/**
* Probe + patch every forward-reference target SCHEMA_SQL needs, on the
* caller-provided connection (see the module header for the lock contract).
- * Kept under this name for `postgres-engine/forward-reference-bootstrap.ts`,
- * which re-exports it.
*/
export async function applyPostgresForwardReferenceBootstrap(conn: ReturnType<typeof postgres>): Promise<void> {
await applyForwardReferenceBootstrap(postgresBootstrapTarget(conn));
diff --git a/src/core/eval-contradictions/fixture-redact.ts b/src/core/eval-contradictions/fixture-redact.ts
deleted file mode 100644
index c963a6fbbe..0000000000
--- a/src/core/eval-contradictions/fixture-redact.ts
+++ /dev/null
@@ -1,169 +0,0 @@
-/**
- * eval-contradictions/fixture-redact — T2 privacy redaction for gold fixture build.
- *
- * The fixture build script runs against the user's real brain to label
- * candidate contradiction pairs. Before commit, names + identifiers MUST be
- * scrubbed per CLAUDE.md privacy rule: "Never reference real people, companies,
- * funds, or private agent names in any public-facing artifact."
- *
- * Pass model (deterministic per session via a salt):
- * 1. PII via the v0.25.0 scrubber (emails, phones, SSN, JWT, credit cards).
- * 2. Slug rewrites: people/<name> → people/alice-example, companies/<name>
- * → companies/acme-example, deals/<name> → deals/acme-seed-example, etc.
- * Stable mapping within a session so the same name maps consistently.
- * 3. Quoted-name detection: capitalized firstname-lastname patterns.
- * 4. Numeric obfuscation: revenue / funding figures multiplied by a salt
- * scalar (preserves order-of-magnitude shape).
- *
- * Fail-closed: if the redactor can't determine a clean rewrite for a token
- * it flagged as potentially private, it emits a sentinel string `[REDACT?]`
- * that the operator must resolve before commit. The build script's
- * pre-commit review surfaces every redaction made.
- */
-
-import { scrubPii } from '../eval-capture-scrub.ts';
-
-const SLUG_PREFIX_REWRITES: Record<string, string> = {
- 'people/': 'people/',
- 'companies/': 'companies/',
- 'deals/': 'deals/',
- 'projects/': 'projects/',
- 'meetings/': 'meetings/',
-};
-
-const PLACEHOLDER_POOL: Record<string, string[]> = {
- 'people/': ['alice', 'bob', 'charlie', 'diana', 'eve', 'frank', 'grace', 'hank'],
- 'companies/': ['acme', 'widget-co', 'globex', 'initech', 'piedpiper', 'hooli', 'pinnacle'],
- 'deals/': ['acme-seed', 'widget-series-a', 'globex-series-b', 'initech-seed'],
- 'projects/': ['project-alpha', 'project-beta', 'project-gamma'],
- 'meetings/': [], // dates are kept; meeting-id segment redacted to numeric.
-};
-
-/** First+last name detector. Two-word capitalized run, length 2..40. */
-const QUOTED_NAME_REGEX = /\b([A-Z][a-z]{1,19})\s+([A-Z][a-z]{1,19})\b/g;
-
-/** Revenue / funding numeric tokens (e.g., $50K, $2M MRR, $1.2B). */
-const MONETARY_REGEX = /\$\s*(\d+(?:\.\d+)?)\s*([KMB])\b/gi;
-
-export interface RedactionSession {
- /** Per-session deterministic mapping: raw slug-suffix → placeholder. */
- slugMap: Map<string, string>;
- /** Quoted-name mapping (lower-case full name → "Firstname Lastname-example"). */
- nameMap: Map<string, string>;
- /** Pool offset per prefix so we cycle through placeholders. */
- poolOffset: Record<string, number>;
- /** Salt for the numeric obfuscation; deterministic per session. */
- numericSalt: number;
- /** Audit trail of every redaction performed (for pre-commit review). */
- audit: string[];
-}
-
-export function createRedactionSession(): RedactionSession {
- return {
- slugMap: new Map(),
- nameMap: new Map(),
- poolOffset: {
- 'people/': 0,
- 'companies/': 0,
- 'deals/': 0,
- 'projects/': 0,
- 'meetings/': 0,
- },
- numericSalt: 1.7, // multiply revenues by 1.7 to obscure (deterministic).
- audit: [],
- };
-}
-
-/** Allocate a placeholder for an unmapped slug. */
-function allocatePlaceholder(session: RedactionSession, prefix: string, raw: string): string {
- if (session.slugMap.has(raw)) return session.slugMap.get(raw)!;
- const pool = PLACEHOLDER_POOL[prefix] ?? [];
- if (pool.length === 0) {
- const next = `${prefix}redacted-${session.slugMap.size + 1}`;
- session.slugMap.set(raw, next);
- return next;
- }
- const idx = session.poolOffset[prefix] % pool.length;
- session.poolOffset[prefix] = (session.poolOffset[prefix] ?? 0) + 1;
- const placeholder = `${prefix}${pool[idx]}-example`;
- session.slugMap.set(raw, placeholder);
- return placeholder;
-}
-
-/** Rewrite a single slug, mapping its tail to a placeholder. Idempotent per session. */
-export function redactSlug(session: RedactionSession, slug: string): string {
- for (const prefix of Object.keys(SLUG_PREFIX_REWRITES)) {
- if (slug.startsWith(prefix)) {
- const placeholder = allocatePlaceholder(session, prefix, slug);
- if (placeholder !== slug) {
- session.audit.push(`slug: ${slug} → ${placeholder}`);
- }
- return placeholder;
- }
- }
- return slug;
-}
-
-/** Allocate a quoted-name placeholder (per-session deterministic). */
-function allocateNamePlaceholder(session: RedactionSession, lowerName: string): string {
- if (session.nameMap.has(lowerName)) return session.nameMap.get(lowerName)!;
- const peopleCount = session.poolOffset['people/'] ?? 0;
- const pool = PLACEHOLDER_POOL['people/'];
- const first = pool[peopleCount % pool.length];
- // Bump the people offset so name + slug pools stay in sync visually.
- session.poolOffset['people/'] = peopleCount + 1;
- const placeholder = `${first.charAt(0).toUpperCase()}${first.slice(1)} Example`;
- session.nameMap.set(lowerName, placeholder);
- return placeholder;
-}
-
-/** Replace quoted Firstname Lastname runs in a string. */
-export function redactNames(session: RedactionSession, text: string): string {
- if (!text) return text;
- return text.replace(QUOTED_NAME_REGEX, (match, first: string, last: string) => {
- const key = `${first} ${last}`.toLowerCase();
- const placeholder = allocateNamePlaceholder(session, key);
- if (placeholder !== match) {
- session.audit.push(`name: "${match}" → "${placeholder}"`);
- }
- return placeholder;
- });
-}
-
-/** Replace $50K / $2M / $1.2B style tokens by multiplying by the session salt. */
-export function redactMonetary(session: RedactionSession, text: string): string {
- if (!text) return text;
- return text.replace(MONETARY_REGEX, (match, value: string, suffix: string) => {
- const v = parseFloat(value);
- if (!Number.isFinite(v)) return match;
- const obfuscated = (v * session.numericSalt).toFixed(1).replace(/\.0$/, '');
- const out = `$${obfuscated}${suffix.toUpperCase()}`;
- session.audit.push(`monetary: ${match} → ${out}`);
- return out;
- });
-}
-
-/** Full redaction pass for an arbitrary text payload. PII first, then names, then monetary. */
-export function redactText(session: RedactionSession, text: string): string {
- let out = scrubPii(text);
- out = redactNames(session, out);
- out = redactMonetary(session, out);
- return out;
-}
-
-/**
- * Pre-commit safety: returns true iff redacted text contains no obviously
- * sensitive tokens. Conservative — only flags shape-matches the session
- * itself didn't authorize. Returning false should block commit until the
- * operator resolves the flagged token.
- */
-export function isCleanForCommit(text: string): boolean {
- // Match: capitalized two-word names that haven't been rewritten (no
- // " Example" suffix), JWT-shaped tokens, raw email patterns. These should
- // all have been caught upstream.
- const looksLikeRawName = /\b[A-Z][a-z]{2,19}\s+[A-Z][a-z]{2,19}\b/.test(text);
- if (looksLikeRawName && !text.includes(' Example')) return false;
- const looksLikeEmail = /[\w.+-]+@[\w-]+\.[\w.-]+/.test(text);
- if (looksLikeEmail) return false;
- return true;
-}
diff --git a/src/core/postgres-engine/forward-reference-bootstrap.ts b/src/core/postgres-engine/forward-reference-bootstrap.ts
deleted file mode 100644
index caf0f36d20..0000000000
--- a/src/core/postgres-engine/forward-reference-bootstrap.ts
+++ /dev/null
@@ -1,4 +0,0 @@
-// Façade (CLAUDE.md "peeled façades keep their surface"): the forward-reference
-// bootstrap has one implementation for both engines in
-// src/core/engine-sql/bootstrap.ts (refactor wave 1, E1). Import from there.
-export { applyPostgresForwardReferenceBootstrap } from '../engine-sql/bootstrap.ts';
diff --git a/src/core/schema-pack/redos-guard.ts b/src/core/schema-pack/redos-guard.ts
index 60e1e4bd4c..fea2d91311 100644
--- a/src/core/schema-pack/redos-guard.ts
+++ b/src/core/schema-pack/redos-guard.ts
@@ -1,52 +1,21 @@
-// v0.38 ReDoS guard (E6 + E9 refinement).
+// ReDoS guard for schema-pack link inference.
//
// Community schema packs ship arbitrary regexes in
-// `link_types[].inference.regex`. A pack with catastrophic-backtracking
-// pattern (`^(a+)+$` and friends) + a moderately-long paragraph would
-// pin CPU on every link extraction.
+// `link_types[].inference.regex`. A pack with a catastrophic-backtracking
+// pattern (`^(a+)+$` and friends) plus a moderately long paragraph would pin
+// CPU on every link extraction. Bounding is: (1) the input-length cap below,
+// (2) a runtime hard gate refusing nested-quantifier (catastrophic-shape)
+// patterns — the star-height lint heuristic, enforced at execution time
+// (degrade-to-mentions, never executed), and (3) a per-page cumulative budget
+// (`LINK_EXTRACTION_TOTAL_BUDGET_MS`): once a page's regex time exceeds it,
+// all remaining verbs on that page degrade to `mentions`, sorted by verb name
+// so degraded-link sets reproduce.
//
-// E6 locked `vm.runInContext({timeout: 50})` as the primary defense.
-// E9 added two layers:
-// 1. A Bun-vm spike (scripts/spike-bun-vm-timeout.ts) MUST run before
-// this guard is trusted in production. If the spike shows Bun's
-// vm timeout doesn't actually interrupt under catastrophic regex,
-// fall back to a persistent worker pool (E6 option B).
-// 2. A per-PAGE total budget. `LINK_EXTRACTION_TOTAL_BUDGET_MS = 500`.
-// If cumulative regex time on a page exceeds 500ms, degrade ALL
-// remaining verbs on that page to `mentions`, deterministically
-// sorted by lex of verb name so degraded-link sets reproduce.
-//
-// This file ships the integration shape; the spike confirmation is
-// gated by T24. If the spike fails, swap `runRegexBounded` with a
-// worker-pool variant; the public surface stays the same.
-//
-// T24 spike result (2026-05-20): Bun's vm.runInContext({timeout: 50})
-// DOES interrupt catastrophic regex, but with ~10x wall-clock latency
-// versus the configured timeout. A configured 50ms timeout takes ~500ms
-// wall-clock to actually unwind for `^(a+)+$` against a 1MB input. This
-// is because Bun checks the timeout at instruction boundaries, and tight
-// backtracking loops yield infrequently. The per-page budget design
-// absorbs this: one catastrophic regex consumes the 500ms budget, all
-// remaining verbs degrade to mentions. Total CPU per page is bounded by
-// the budget regardless of pathological pattern count. SAFE for v0.38.
-//
-// v0.46 megawave FALSIFICATION (bootstrap-verify corpus hang): in a process
-// that ALSO hosts PGLite (WASM Postgres), repeated `vm.runInContext(...,
-// { timeout })` calls wedge Bun's event loop — after some dozens of watchdog
-// runs, ALL JS timers stop firing and the next in-flight PGLite query promise
-// never resolves (main thread parks in kevent64 at 0% CPU forever). Repro:
-// put_page x ~20 with pack regex inference (#3190) against an in-memory
-// PGLite brain; hang point drifts run-to-run. The vm timeout was therefore
-// REMOVED — it protected against a slow regex by freezing the entire brain,
-// strictly worse than the attack. This is likely the mechanism behind the
-// #1569-followup field report of syncs wedging deterministically mid-run.
-// Bounding is now: (1) the input-length cap below, (2) a runtime HARD gate
-// refusing nested-quantifier (catastrophic-shape) patterns — the same
-// heuristic the star-height lint flags, escalated from advisory to enforced
-// at execution time (degrade-to-mentions, never executed), and (3) the
-// per-page cumulative budget. If a true preemptive bound is ever needed
-// again, it must be the E6 option B worker pool — NOT node:vm — because the
-// watchdog is unsafe in PGLite-hosting processes.
+// There is no `node:vm` timeout: in a process that also hosts PGLite,
+// repeated `vm.runInContext(..., { timeout })` calls wedge Bun's event loop
+// (timers stop firing and the next PGLite query never resolves), which froze
+// the whole brain to protect against one slow regex. If a preemptive bound is
+// ever needed, it must be a worker pool, not node:vm.
export const LINK_EXTRACTION_TOTAL_BUDGET_MS = 500 as const;
export const PER_REGEX_TIMEOUT_MS = 50 as const;
diff --git a/src/core/search/keyword.ts b/src/core/search/keyword.ts
deleted file mode 100644
index 55df210e2a..0000000000
--- a/src/core/search/keyword.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-import type { BrainEngine } from '../engine.ts';
-import type { SearchResult, SearchOpts } from '../types.ts';
-
-export async function keywordSearch(
- engine: BrainEngine,
- query: string,
- opts?: SearchOpts,
-): Promise<SearchResult[]> {
- return engine.searchKeyword(query, opts);
-}
diff --git a/src/core/search/vector.ts b/src/core/search/vector.ts
deleted file mode 100644
index 8ccf8273e7..0000000000
--- a/src/core/search/vector.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-import type { BrainEngine } from '../engine.ts';
-import type { SearchResult, SearchOpts } from '../types.ts';
-
-export async function vectorSearch(
- engine: BrainEngine,
- embedding: Float32Array,
- opts?: SearchOpts,
-): Promise<SearchResult[]> {
- return engine.searchVector(embedding, opts);
-}
diff --git a/test/e2e/postgres-bootstrap.test.ts b/test/e2e/postgres-bootstrap.test.ts
index 54868ff601..1bd82b6039 100644
--- a/test/e2e/postgres-bootstrap.test.ts
+++ b/test/e2e/postgres-bootstrap.test.ts
@@ -27,7 +27,7 @@ import { PostgresEngine } from '../../src/core/postgres-engine.ts';
import { LATEST_VERSION } from '../../src/core/migrate.ts';
import { readFactsEmbeddingDim } from '../../src/core/embedding-dim-check.ts';
import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
-import { applyPostgresForwardReferenceBootstrap } from '../../src/core/postgres-engine/forward-reference-bootstrap.ts';
+import { applyPostgresForwardReferenceBootstrap } from '../../src/core/engine-sql/bootstrap.ts';
const DATABASE_URL = process.env.DATABASE_URL;
const skip = !DATABASE_URL;
diff --git a/test/eval-contradictions-fixture-redact.test.ts b/test/eval-contradictions-fixture-redact.test.ts
deleted file mode 100644
index c9fe057d3b..0000000000
--- a/test/eval-contradictions-fixture-redact.test.ts
+++ /dev/null
@@ -1,137 +0,0 @@
-/**
- * Fixture redactor tests — T2 privacy redaction passes.
- */
-
-import { describe, test, expect } from 'bun:test';
-import {
- createRedactionSession,
- isCleanForCommit,
- redactMonetary,
- redactNames,
- redactSlug,
- redactText,
-} from '../src/core/eval-contradictions/fixture-redact.ts';
-
-describe('redactSlug', () => {
- test('people/<name> → people/alice-example (deterministic per session)', () => {
- const s = createRedactionSession();
- const out = redactSlug(s, 'people/garry-tan');
- expect(out).toMatch(/^people\/.+-example$/);
- });
-
- test('same raw slug maps consistently within a session', () => {
- const s = createRedactionSession();
- const a = redactSlug(s, 'people/garry-tan');
- const b = redactSlug(s, 'people/garry-tan');
- expect(a).toBe(b);
- });
-
- test('different raw slugs map to different placeholders', () => {
- const s = createRedactionSession();
- const a = redactSlug(s, 'people/garry-tan');
- const b = redactSlug(s, 'people/paul-graham');
- expect(a).not.toBe(b);
- });
-
- test('companies/, deals/, projects/ all rewrite', () => {
- const s = createRedactionSession();
- expect(redactSlug(s, 'companies/y-combinator')).toMatch(/^companies\/.+-example$/);
- expect(redactSlug(s, 'deals/y-seed')).toMatch(/^deals\/.+-example$/);
- expect(redactSlug(s, 'projects/secret')).toMatch(/^projects\/.+-example$/);
- });
-
- test('unrecognized prefix passes through unchanged', () => {
- const s = createRedactionSession();
- expect(redactSlug(s, 'random/page')).toBe('random/page');
- expect(redactSlug(s, 'concepts/foo')).toBe('concepts/foo');
- });
-
- test('audit trail records every redaction', () => {
- const s = createRedactionSession();
- redactSlug(s, 'people/garry');
- redactSlug(s, 'companies/yc');
- expect(s.audit.length).toBe(2);
- expect(s.audit[0]).toContain('garry');
- expect(s.audit[1]).toContain('yc');
- });
-});
-
-describe('redactNames', () => {
- test('Firstname Lastname → Alice Example', () => {
- const s = createRedactionSession();
- const out = redactNames(s, 'I met Mackenzie Burnett yesterday');
- expect(out).toMatch(/I met .+ Example yesterday/);
- });
-
- test('same name maps consistently', () => {
- const s = createRedactionSession();
- const out1 = redactNames(s, 'Garry Tan');
- const out2 = redactNames(s, 'Garry Tan');
- expect(out1).toBe(out2);
- });
-
- test('different names map to different placeholders', () => {
- const s = createRedactionSession();
- const out1 = redactNames(s, 'Alice Smith');
- const out2 = redactNames(s, 'Bob Jones');
- expect(out1).not.toBe(out2);
- });
-
- test('does not match lowercase strings (not name-shaped)', () => {
- const s = createRedactionSession();
- expect(redactNames(s, 'hello world')).toBe('hello world');
- });
-
- test('does not match single names', () => {
- const s = createRedactionSession();
- expect(redactNames(s, 'Alice said hi')).toBe('Alice said hi');
- });
-});
-
-describe('redactMonetary', () => {
- test('$50K → multiplied by salt', () => {
- const s = createRedactionSession();
- const out = redactMonetary(s, 'MRR is $50K');
- expect(out).not.toBe('MRR is $50K');
- expect(out).toMatch(/\$\d+(\.\d+)?K/);
- });
-
- test('$2M, $1.5B all rewritten', () => {
- const s = createRedactionSession();
- expect(redactMonetary(s, 'raised $2M')).not.toBe('raised $2M');
- expect(redactMonetary(s, 'valued at $1.5B')).not.toBe('valued at $1.5B');
- });
-
- test('non-monetary numbers pass through', () => {
- const s = createRedactionSession();
- expect(redactMonetary(s, 'we have 50 customers')).toBe('we have 50 customers');
- });
-});
-
-describe('redactText (full pass)', () => {
- test('chains PII + name + monetary', () => {
- const s = createRedactionSession();
- const out = redactText(s, 'Met Mackenzie Burnett, MRR $50K, email me at [email protected]');
- expect(out).not.toContain('Mackenzie Burnett');
- expect(out).not.toContain('[email protected]');
- expect(out).not.toContain('$50K');
- });
-});
-
-describe('isCleanForCommit', () => {
- test('clean text passes', () => {
- expect(isCleanForCommit('Alice Example met Bob Example at companies/acme-example')).toBe(true);
- });
-
- test('raw name shape blocks commit', () => {
- expect(isCleanForCommit('Met Mackenzie Burnett')).toBe(false);
- });
-
- test('raw email blocks commit', () => {
- expect(isCleanForCommit('contact me at [email protected]')).toBe(false);
- });
-
- test('empty text is clean', () => {
- expect(isCleanForCommit('')).toBe(true);
- });
-});
diff --git a/test/fixtures/guards/check-gateway-routed-no-direct-anthropic.sh/bad/src/core/think/index.ts b/test/fixtures/guards/check-gateway-routed-no-direct-anthropic.sh/bad/src/core/think/index.ts
index 518ee00217..8340690c8d 100644
--- a/test/fixtures/guards/check-gateway-routed-no-direct-anthropic.sh/bad/src/core/think/index.ts
+++ b/test/fixtures/guards/check-gateway-routed-no-direct-anthropic.sh/bad/src/core/think/index.ts
@@ -1,2 +1,3 @@
-import type Anthropic from '@anthropic-ai/sdk';
+// Value-shaped construction the guard must flag (gateway-routed files never build an SDK client).
+declare const Anthropic: new () => object;
export const client = new Anthropic();