Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(embed): detect chunkless pages with non-empty content in embed --stale (#3993)
test8a626999f0b7
diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.mdindex 0646e86dbb..62c3fae050 100644--- a/docs/architecture/KEY_FILES.md+++ b/docs/architecture/KEY_FILES.md@@ -50,7 +50,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `src/core/sources-ops.ts` — Multi-source registration + clone-lifecycle ops (`addSource`, `recloneIfMissing`, `defaultCloneDir`, `isOwnedClone`, `unownedHint`). **Reclone-ownership invariant (must-never-violate): gbrain may only delete/re-clone a clone it created, NEVER a user working tree.** `recloneIfMissing` deletes `local_path`, so it gates on `isOwnedClone(src)` and throws a `SourceOpError('unmanaged_path', ...)` BEFORE any filesystem op when ownership is unprovable — fail-closed. Ownership is proven by `config.managed_clone === true` (written by `addSource`'s `--url` path, covering default-location and `--clone-dir` clones) OR `local_path === defaultCloneDir(id)` (back-compat for pre-marker clones, via exact normalized-path equality, symlink-free). A row with `remote_url` + an unowned `local_path` (a user-registered working tree, e.g. `sources add --path`) is refused untouched; re-add with `--url` to regain auto-reclone. The reclone is EXDEV-safe: clone into a SIBLING temp of `local_path` (not the shared `clones/.tmp`, which may sit on a different mount than a `--clone-dir` target), then swap (move old aside → move new in → drop old) so `local_path` is never left missing-and-unrecoverable; on swap failure the original is restored, and if restore fails the error names the `aside` path so it's never reflexively deleted. A TOCTOU re-check re-confirms ownership immediately before the destructive move and rejects a symlink leaf swapped in after the entry check (`symlink_escape`). `unownedHint(src, state)` is the shared recovery message used by both the core error and the `gbrain sync --source` CLI error; `gbrain sources restore` special-cases `unmanaged_path` to print "DB row restored; gbrain syncs this path read-only" instead of the misleading "try sync to recover" guidance. `SourceOpErrorCode` includes `unmanaged_path`. Pinned by `test/sources-ops.test.ts`, `test/sources-resync-recovery.test.ts`.- `src/core/utils.ts` — Shared SQL utilities extracted from postgres-engine.ts. Exports `parseEmbedding(value)` (throws on unknown input, used by migration + ingest paths where data integrity matters) and `tryParseEmbedding(value)` (returns `null` + warns once per process, used by search/rescore paths where availability matters more than strictness). `isUndefinedColumnError(err)` predicate — pattern-matches Postgres SQLSTATE 42703 / "column ... does not exist" with engine-driver shape variation tolerated; replaces bare `catch {}` blocks in `oauth-provider.ts` so genuine errors (lock timeout, network blip, permission denied) propagate while column-missing falls through to the legacy fallback. `validateSourceId(id)` throws on anything outside `^[a-z0-9_-]+$`, used by the per-source disk-layout fix in patterns.ts/synthesize.ts before any `join(brainDir, '.sources', source_id, slug+'.md')` so source_id can't traverse out of brainDir. `rowToSearchResult` projects email `message_id` / `thread_id` metadata and exposes `source_subject` only when a non-empty Message-ID proves the page is an email, so generated page titles never become authoritative email subjects. `rowToPage` populates the required `Page.source_id` from the SELECT projection (`scripts/check-source-id-projection.sh` enforces every projection feeding `rowToPage` includes the column).- `src/core/db.ts` — Connection management, schema initialization. `resolveSessionTimeouts()` returns `statement_timeout` + `idle_in_transaction_session_timeout` (defaults 5min each, env-overridable via `GBRAIN_STATEMENT_TIMEOUT`/`GBRAIN_IDLE_TX_TIMEOUT`/`GBRAIN_CLIENT_CHECK_INTERVAL`). Both `connect()` (module singleton) and `PostgresEngine.connect()` (worker pool) consume the result via postgres.js's `connection` option, sending GUCs as startup parameters that survive PgBouncer transaction mode (`setSessionDefaults` kept as a back-compat no-op shim). `connect()` returns `Promise<boolean>` — `true` iff THIS call created the module singleton, `false` if it joined an existing one; the decision is atomic (no `await` between the `if (sql)` null-check and the synchronous `sql = postgres(...)` assignment), so two concurrent module connects can't both claim creation. `PostgresEngine` stores the return as its `_ownsModuleSingleton` token and only the creating engine may `db.disconnect()` the singleton — a borrower probe engine (lint/doctor config-lift) no-ops its disconnect, so its teardown can't null the connection the long-lived cycle owner is still using (the dream-cycle "connect() has not been called" failure). The module `sql` is only ever nulled by `db.disconnect()` (postgres.js auto-reconnects its own internal pool and never touches our reference). `disconnect()` snapshots + nulls `sql` before awaiting the pool end so a concurrent connect can't join a pool that's already closing. The end routes through `endPoolBounded(pool)` (#1972) — a gbrain-owned `Promise.race` of `pool.end({ timeout: POOL_END_TIMEOUT_SECONDS })` against a hard timer — so a PgBouncer transaction-mode drain that never settles can't hang teardown — the #2084 contract (finishCliTeardown's computed-deadline backstop + flushThenExit's fence-and-grace exit in cli-force-exit.ts) bounds it and delivers pending stdout before exit. `connection-manager.ts` ends its direct + read pools concurrently through the same helper so the per-pool bounds don't stack.-- `src/commands/migrate-engine.ts` — Bidirectional engine migration (`gbrain migrate --to supabase/pglite`). Copies the complete source catalog FIRST (`copyMigrationSources` — every `sources` row incl. archived rows and sync/routing metadata, `ON CONFLICT (id) DO UPDATE`, `default` ordered first) so every page write has a valid `pages.source_id` FK parent and the target preserves per-source behavior; pages copy afterward, tracked in the resume manifest by composite `(source_id, slug)` key. The resume manifest is target-aware: `migrationTargetId(config)` hashes `(engine, locator)` (`database_url` for Postgres, resolved `database_path` for PGLite) and `manifestMatchesTarget` requires `schema_version === 2` plus a matching `target_id` — a legacy engine-only manifest, or one from a DIFFERENT target of the same engine kind, starts fresh instead of skipping "completed" pages the new target never received. Pinned by `test/migrate-engine-resume.test.ts` (manifest identity) + `test/e2e/migrate-engine-sources-postgres.test.ts` (source catalog lands before overlapping-slug pages, PGLite → real Postgres). Quiesces autopilot for the copy window via `quiesceAutopilot(engine?)`, claimed FIRST — before the target is connected or the manifest touched — so the pause marker doubles as the migrate mutex. Protocol: unconditional atomic claim (`wx` flag; the daemon lock vanishes routinely between supervisor respawns and cron runs, so lock-gating would leave recurring unguarded windows); a marker owned by a LIVE process (pid in the body, `markerHolderAlive`), any foreign hold, or an UNWRITABLE marker (EACCES/EROFS/ENOSPC — fail-closed) returns NULL and the migration ABORTS exit 1 (running unowned/unfenced would lose daemon writes at the flip); a dead migrate's orphan is adopted ATOMICALLY — `renameSync` is the compare-and-claim (exactly one racer wins; the loser aborts) and the fresh body with the adopter's pid goes through the same exclusive `wx` gate. After claiming, in-flight writers are DRAINED by polling `listLiveLocks` on the source engine (cycle/sync/embed all hold rows in `gbrain_cycle_locks` while writing; `gbrain-supervisor:*` PRESENCE locks are excluded — a healthy minion supervisor holds one continuously — and healthy `minion_jobs` rows with `status='active'` count as writers, fail-open if the table is absent) up to `GBRAIN_MIGRATE_QUIESCE_SECONDS` (default 300; `0` disables; empty = default; garbage warns + falls back), then proceeds with a loud residual warning naming the still-live locks. The worker side of the fence lives in `src/core/minions/worker.ts`: the poll loop checks the pause marker BEFORE `queue.claim`, so queued jobs stop being picked up for the copy window (in-flight jobs finish and are what the drain waits on). Cleanup registers IMMEDIATELY after the claim and the whole run sits in try/finally, so signals and handled errors both release the marker; a SIGKILL orphan is self-cleared by the daemon's next poll. On a clean flip, warns when an exported DATABASE_URL-style env var would override the new file config. Pinned by `test/autopilot-pause-marker.test.ts` (quiesce protocol, GBRAIN_HOME-isolated).+- `src/commands/migrate-engine.ts` — Bidirectional engine migration (`gbrain migrate --to supabase/pglite`). Copies the complete source catalog FIRST (`copyMigrationSources` — every `sources` row incl. archived rows and sync/routing metadata, `ON CONFLICT (id) DO UPDATE`, `default` ordered first) so every page write has a valid `pages.source_id` FK parent and the target preserves per-source behavior; pages copy afterward, tracked in the resume manifest by composite `(source_id, slug)` key. The resume manifest is target-aware: `migrationTargetId(config)` hashes `(engine, locator)` (`database_url` for Postgres, resolved `database_path` for PGLite) and `manifestMatchesTarget` requires `schema_version === 2` plus a matching `target_id` — a legacy engine-only manifest, or one from a DIFFERENT target of the same engine kind, starts fresh instead of skipping "completed" pages the new target never received. Pinned by `test/migrate-engine-resume.test.ts` (manifest identity) + `test/e2e/migrate-engine-sources-postgres.test.ts` (source catalog lands before overlapping-slug pages, PGLite → real Postgres).- `src/core/import-file.ts` — importFromFile + importFromContent (chunk + embed + tags). `importFromContent` and `importCodeFile` stamp `pages.embedding_signature` via `setPageEmbeddingSignature(slug, {sourceId, signature: currentEmbeddingSignature()})` when the import actually embedded (not `--no-embed`) so a model/dims swap is detectable as stale; `importCodeFile` only stamps when every chunk was freshly embedded this call (`needsEmbedIndexes.length === chunks.length`), mixed reuse-by-hash pages stay unstamped (`reindex --code --force` / `embed --stale` handle those). `importFromContent`'s tag reconciliation is ADD-ONLY: it only `addTag` (idempotent, ON CONFLICT DO NOTHING). The `tags` table has no provenance column and frontmatter tags are stripped from stored `pages.frontmatter` (markdown.ts:118), so a frontmatter-origin tag can't be distinguished from a DB-enrichment tag (auto-tag / dream synthesize / signal-detector) at re-import — deletion is unsafe (would wipe enrichment under `gbrain reindex --markdown`). Accepted trade-off: removing a tag from frontmatter no longer removes it from the DB on next sync (needs a `tag_source` provenance column). Pinned by `test/reindex-preserve-tags.test.ts` + `test/import-file.test.ts`. identity-based dedup pre-check at `:427-490`. Calls `engine.findDuplicatePage?.(sourceId, {hash, frontmatterId})` (optional `?` so test doubles compile). Posture: SKIP when `frontmatter.id` matches (true external duplicate from overlapping ingest roots), WARN-ALWAYS on content_hash collision with different/missing `frontmatter.id` (templates and daily logs may legitimately share text), FAIL CLOSED on lookup error, bypass via `--force-rechunk`. Soft-deleted pages excluded at the engine layer so tombstones don't block legitimate re-imports under new slugs. Pinned by `test/import-dedup-frontmatter-id.test.ts` (11 cases). `importFromContent` is the narrow waist every ingest path passes through (`gbrain import`, `gbrain sync`, `put_page` MCP, `/ingest` webhook). It runs a three-tier content-quality disposition via `assessContentSanity` from `src/core/content-sanity.ts` BEFORE chunking: (1) high-confidence junk (built-in Cloudflare/CAPTCHA interstitial patterns + operator literals) → QUARANTINE (stamps the `quarantine` frontmatter marker, writes ZERO chunks, hides the page from search) OR REJECT (throw → sync-failure) when `content_sanity.junk_disposition` is `reject`; (2) fuzzy markup-heavy (prose-vs-markup ratio above `content_sanity.max_markup_ratio`, warn-tier byte window, code pages exempt) → `content_flag:markup_heavy` marker (page stays fully searchable, marker rides search results + get_page to warn the agent); (3) oversize → `embed_skip` soft-block via `buildEmbedSkipMarker()` PLUS a `content_flag:oversized` marker, AND deletes any pre-existing chunks in the same transaction so search can't surface stale chunks. Gate-owned markers (`quarantine`, `content_flag`) are STRIPPED from untrusted (remote MCP, `ctx.remote !== false`) frontmatter so a write-scoped client can't hide pages or forge the warning channel; markers are excluded from `content_hash` so a flagged page doesn't re-embed every sync. `gbrain import` honors `errors > 0` for non-zero exit. `classifyErrorCode` in `src/core/sync.ts` recognizes the `PAGE_JUNK_PATTERN` code so sync-failures.jsonl grouping bins these. `extractEntityRefs` (canonical; matches both `[Name](people/slug)` markdown links and Obsidian `[[people/slug|Name]]` wikilinks), `extractPageLinks`, `inferLinkType` heuristics (attended/works_at/invested_in/founded/advises/source/mentions), `parseTimelineEntries`, `isAutoLinkEnabled` config helper. Link candidates match any dir-shaped path (#2576; existence-checked at persist). Used by extract.ts, operations.ts auto-link post-hook, and backlinks.ts. Pinned by `test/import-file-content-sanity.test.ts`.- `src/core/sync.ts` — Pure sync functions (manifest parsing, filtering, slug conversion). Exported `pruneDir(name: string): boolean` is the single source of truth for descent-time directory exclusion across walkers — blocks `node_modules` (no leading dot, so naive walkers slipped through and inflated MISSING_OPEN counts via vendor packages), `vendor`/`dist`/`build`/`venv`, dot-prefix dirs, and `*.raw` sidecars — NOT `ops/`, which is ordinary user content (#2404; the bundled daily-task-manager stores `ops/tasks` there); `isSyncable` applies it per path segment, and `walkMarkdownFiles` in `src/commands/extract.ts` + `listTextFiles` in `src/core/cycle/transcript-discovery.ts` consult it BEFORE recursing to save the IO of walking thousands of vendor files (closes #923 + #202). `manageGitignore` worktree discriminator matches the gitdir path segment (`/modules/<name>` = submodule, `/worktrees/<name>` = worktree, per Git's documented layout) so Conductor worktrees (first-class repos) get `.gitignore` management for storage-tiering (closes #889). The sync-failure ledger (failure store, error classifier, the shared bookmark gate, and the doctor severity rule) lives in `src/core/sync-failure-ledger.ts`; `sync.ts` re-exports `classifyErrorCode`, `summarizeFailuresByCode`, `loadSyncFailures`, `unacknowledgedSyncFailures`, `acknowledgeSyncFailures`, `recordSyncFailures`, `decideSyncFailureSeverity`, `applySyncFailureGate`, and the `SyncFailure` type for backward-compatible imports — see its entry below. `isSyncable` factored through private `classifySync(path, opts): SyncableReason | null`; exported companion `unsyncableReason(path, opts)` returns the same tagged reason or null when syncable. `SYNC_SKIP_FILES` is a named export (the four canonical metafile basenames `schema.md`, `index.md`, `log.md`, `README.md`). `SyncableReason` union: `'metafile' | 'strategy' | 'pruned-dir' | 'include-glob-miss' | 'exclude-glob-hit'`. The `commands/sync.ts` cleanup loop guards on `unsyncableReason(path)` being `'metafile'` OR `'pruned-dir'` (#2404) so previously-indexed metafile pages AND deliberately put-created pages under pruned dirs survive every re-sync. Does NOT cover `manifest.deleted` (the upstream filter already strips metafiles). Pinned by `test/sync-isSyncable-shape.test.ts` (15 cases, duality contract) + `test/sync-metafile-skip.serial.test.ts` (3 PGLite cases incl. the renamed `.md → .txt` negative). `pruneDir`: `pruneDir(name, parentDir?)` extended with optional `parentDir`. When provided, additionally rejects directories containing `.git` as a FILE — the git submodule gitfile pattern (regular repos have `.git` as a DIRECTORY; submodules as a file pointing into the parent's `.git/modules/`). Sync + extract walkers thread `parentDir` so the gitfile-as-FILE check fires per descend step. Best-effort: `statSync` failures fall through and treat as a normal dir. Closes the phantom-import bug class where syncing a worktree-with-submodules walked into submodule trees. Pinned by `test/sync-walker-submodule.test.ts`.- `src/core/sync-failure-ledger.ts` — the bounded auto-skip sync failure ledger (issue #1939; formerly inline "Bug 9" in `sync.ts`). A LEAF module (imports only fs/path/crypto/config) so `sync.ts` can re-export it without a circular dependency. State lives in `~/.gbrain/sync-failures.jsonl`, one JSON object per line, keyed by `(source_id, path)` with a per-key `attempts` count and a 3-state machine: `open` (fresh/blocking) → `acknowledged` (human resolved via `gbrain sync --skip-failed`) or `auto_skipped` (chronic). `classifyErrorCode(errorMsg)` regex classifier with 12 codes (`SLUG_MISMATCH`, `YAML_PARSE`, `YAML_DUPLICATE_KEY`, `MISSING_OPEN`, `MISSING_CLOSE`, `NESTED_QUOTES`, `EMPTY_FRONTMATTER`, `NULL_BYTES`, `INVALID_UTF8`, `STATEMENT_TIMEOUT`, `FILE_TOO_LARGE`, `SYMLINK_NOT_ALLOWED`) plus `UNKNOWN` (also recognizes `PAGE_JUNK_PATTERN` from the content-sanity gate); `summarizeFailuresByCode(failures)` returns sorted `[{code, count}]`; `MISSING_OPEN`/`MISSING_CLOSE`/`EMPTY_FRONTMATTER` regexes match the `markdown.ts` validator strings, `FILE_TOO_LARGE` covers `import-file.ts:199, 352, 401`, `SYMLINK_NOT_ALLOWED` covers `:347`. All mutations run under `withLedgerLock` (cross-process file lock) with an atomic rename write. The auto-skip threshold resolves via `resolveAutoSkipThreshold()` from `GBRAIN_SYNC_AUTOSKIP_AFTER` (default `DEFAULT_AUTOSKIP_AFTER = 3`; `0` disables the valve = pure fail-closed). Two pure decision functions are the unit-test surface: `decideGateAction({fileFailures, sentinels, attemptsByPath, threshold, skipFailed})` returns `hard_block | block | advance | advance_then_autoskip` (sentinels like `<head>` ALWAYS hard-block, even with `--skip-failed`, so a history rewrite can't auto-skip; any FRESH failure with `attempts < threshold` blocks fail-closed; only when ALL failures are chronic does it `advance_then_autoskip`), and `decideSyncFailureSeverity({entries, nowMs, failHours})` returns the `sync_failures` doctor status (`ok` when zero unresolved; `fail` when ≥10 OPEN-blocking or the oldest OPEN failure has blocked the bookmark past `failHours`; otherwise `warn` — `auto_skipped`-only rows stay WARN-visible regardless of count because the bookmark already advanced). `applySyncFailureGate(input)` is the one orchestrator BOTH sync paths (incremental + full/`runImport`) call: it records/clears ledger rows, runs `decideGateAction`, then executes effects in the crash-safe order (advance the bookmark FIRST via the injected `advance()` callback, THEN auto-skip the chronic set) so a crash can never mark a file skipped while leaving sync wedged. `isSkippablePath` rejects `<…>` sentinels. Pinned by `test/sync-failure-ledger.serial.test.ts` + `test/sync-failures.test.ts`.@@ -58,11 +58,10 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `src/core/storage-config.ts` — Storage tiering: `loadStorageConfig` reads `gbrain.yml`, normalizes deprecated keys (`git_tracked`/`supabase_only`) to canonical (`db_tracked`/`db_only`) with once-per-process deprecation warning, and runs `normalizeAndValidateStorageConfig` (auto-fixes missing trailing `/`, throws `StorageConfigError` on tier overlap). Path-segment matcher: `media/x/` does NOT match `media/xerox/foo`. Uses a dedicated parser for the `gbrain.yml` shape rather than gray-matter (broken on delimiter-less YAML). Also carries `DERIVE_PHASE_DB_ONLY_DEFAULTS` (`life/events/`, `atoms/`, `extracts/`, `dream-cycle-summaries/`) + `effectiveDbOnlyDirs` — the engine's derive-phase output prefixes treated as implicitly-declared db_only by the `undeclared_db_only_pages` doctor check but deliberately NOT merged into `loadStorageConfig` (a global merge would auto-gitignore those dirs and silently kill ingestion for brains that file-back them, the #2788 class) — and `findDbOnlyCollisions` (pure collector-output vs db_only overlap detector shared by the `db_only_collector_collision` doctor check and sync's `manageGitignore` warning). Pinned by `test/storage-config.test.ts` + `test/doctor-silent-death-checks.test.ts`.- `src/core/disk-walk.ts` — `walkBrainRepo(repoPath)` returns `Map<slug, {size, mtimeMs}>` from one recursive `readdirSync`. Skips dot-dirs, `node_modules`, non-`.md` files. Used by `gbrain storage status` to replace per-page `existsSync + statSync` (~400K syscalls on 200K-page brains → tens).- `src/core/git-head.ts` — local git HEAD freshness probe for `gbrain doctor`. `isSourceUnchangedSinceSync(localPath, lastCommit, opts?)` returns true iff `localPath` is a git repo whose current HEAD matches `lastCommit`; when `opts.requireCleanWorkingTree` is true also requires a clean working tree (mirrors `gbrain sync`'s force-walk gate at `sync.ts:1075` so doctor and sync agree on "is there work to do?"). `requireCleanWorkingTree` is `boolean | 'ignore-untracked'` — in `'ignore-untracked'` mode the clean probe runs `git status --porcelain --untracked-files=no` so a quiet repo with stray untracked dirs (`?? companies/`, `?? media/`) is still "unchanged" (sync's incremental path keys off the commit diff and never imports untracked files); `GitCleanProbe` gains an `ignoreUntracked?` second arg. Two probe seams (`_setGitHeadProbeForTests`, `_setGitCleanProbeForTests`) keep unit tests R2-compliant (no `mock.module`). Uses `execFileSync` with array args so shell metachars in `local_path` cannot escape to a shell (the regression test runs real `execFileSync` against `'/nonexistent/$(touch <sentinel>)/repo'` and asserts the sentinel is never created). Fail-open on every error (missing path, not a git repo, git not installed, timeout, NULL inputs, dirty-probe errored → false) preserving the caller's prior time-based behavior. The chunker-version-match check lives in the caller (doctor.ts) because it depends on engine state (`sources.chunker_version` vs `CHUNKER_VERSION` from `src/core/chunkers/code.ts`). Pinned by `test/core/git-head.test.ts` (incl. the shell-injection regression guard).-- `src/core/env-number.ts` — numeric env-var resolution with ONE shared warn-once memo. `resolveEnvNumber(varName, fallback, {unit?})` (positive numbers only; zero/negative/garbage → warn once + fallback), `resolveHoursEnv` (hours unit pre-applied), `warnOnceForEnv(varName, message)` for disabled-unless-set vars that need the same memo without the fallback shape (e.g. `GBRAIN_EXTRACTION_LAG_FAIL_PCT`). Lives in core because `source-health.ts` needs the hours resolver for the staleness ceiling while `doctor.ts` already imports FROM `source-health.ts` — reaching back would cycle, and duplicating would fork the memo so one bad var warns twice. `doctor.ts` re-exports it as `_resolveEnvNumber` for `sync.ts`'s dynamic import. `_resetEnvNumberWarnedForTests()` is a test seam.-- `src/core/source-health.ts` — per-source health metrics for `gbrain sources status` + doctor's `federation_health`. Commit-relative staleness: `newestCommitMs(localPath)` = HEAD committer time via `git log -1 --format=%ct` (fail-open null; NO working-tree mtime parsing — committed content only, robust against the porcelain-mtime bug farm); `lagFromContentMs(contentMs|null, lastSyncMs|null, nowMs, ceilingSeconds?)` = remote/column comparator (null lastSync → null; negative wall-clock → skew passthrough; `contentMs <= lastSync` → **`max(0, wallClock - ceiling)`**; else/null-content → wall-clock). Core logic is pure; only the DEFAULT `ceilingSeconds` reads env, via `resolveStalenessCeilingSeconds()` (`GBRAIN_STALENESS_CEILING_HOURS` overriding `GBRAIN_SYNC_FRESHNESS_FAIL_HOURS`, default 72) — pass the 4th arg for determinism. The caught-up branch RAMPS rather than returning a flat 0: a flat 0 meant a source whose clone vanished reported fresh forever (the dead-daemon class), while a hard step to the ceiling would trip `federation_health` (24h) and `sync_freshness` (24h/72h) in the same instant and skip the warn tier — the alert-storm shape the caught-up branch exists to prevent. Ramping keeps the escalation ordered. `computeAllSourceMetrics(engine, sources, {probeContent?})`: LOCAL (`probeContent:true`, `gbrain sources status`) → `isSourceUnchangedSinceSync(..., {requireCleanWorkingTree:'ignore-untracked'}) ? 0 : wall-clock` (live commit-hash catches HEAD moving to an old-dated commit a timestamp compare would miss); REMOTE (default, `federation_health` on the HTTP MCP path) → `lagFromContentMs(row.newest_content_at, ...)`, NO git subprocess (trust boundary). `commitTimeMs(localPath, sha)` is the `newestCommitMs` sibling pinned to an arbitrary commit (committer time via `git show -s --format=%ct <sha>`, fail-open null, execFileSync array args) — the resumable sync stamps `newest_content_at` against its pinned target commit, not whatever HEAD raced to. Pinned by `test/source-health.test.ts`.+- `src/core/source-health.ts` — per-source health metrics for `gbrain sources status` + doctor's `federation_health`. Commit-relative staleness: `newestCommitMs(localPath)` = HEAD committer time via `git log -1 --format=%ct` (fail-open null; NO working-tree mtime parsing — committed content only, robust against the porcelain-mtime bug farm); pure `lagFromContentMs(contentMs|null, lastSyncMs|null, nowMs)` = remote/column comparator (null lastSync → null; negative wall-clock → skew passthrough; `contentMs <= lastSync` → 0; else/null-content → wall-clock). `computeAllSourceMetrics(engine, sources, {probeContent?})`: LOCAL (`probeContent:true`, `gbrain sources status`) → `isSourceUnchangedSinceSync(..., {requireCleanWorkingTree:'ignore-untracked'}) ? 0 : wall-clock` (live commit-hash catches HEAD moving to an old-dated commit a timestamp compare would miss); REMOTE (default, `federation_health` on the HTTP MCP path) → `lagFromContentMs(row.newest_content_at, ...)`, NO git subprocess (trust boundary). `commitTimeMs(localPath, sha)` is the `newestCommitMs` sibling pinned to an arbitrary commit (committer time via `git show -s --format=%ct <sha>`, fail-open null, execFileSync array args) — the resumable sync stamps `newest_content_at` against its pinned target commit, not whatever HEAD raced to. Pinned by `test/source-health.test.ts`.- `src/core/npm-squat-check.ts` — classifies `gbrain` PATH entries as real, foreign npm package, broken, or unknown for doctor's `npm_squat` check. On Windows it normalizes Git Bash/MSYS drive paths (`/c/...` → `C:/...`) and tries the native `.exe` suffix before reporting a broken entry; non-Windows classification keeps the original single-candidate behavior. Pinned by `test/npm-squat-check.test.ts`.- `src/core/git-remote.ts` — SSRF-hardened git invocations for remote-source `cloneRepo`, `pullRepo`, and `fetchRemote(repoPath, branch)` (the last added for the sync cost-estimator's fetch-first path, #2139, so a cost preview / dry-run fetches through the same hardened flags + `GIT_TERMINAL_PROMPT=0` as real sync rather than a less-protected route). Exports two distinct flag constants because `git`'s argv grammar treats them differently: `GIT_SSRF_FLAGS` (3 `-c` config flags — `protocol.allow=user`, `protocol.file.allow=never`, `http.allowRedirects=false`) is global config, spread BEFORE the subcommand verb; `GIT_SSRF_SUBCOMMAND_FLAGS = ['--no-recurse-submodules']` is subcommand-scoped, spread AFTER the verb (a combined array would spread `--no-recurse-submodules` before the verb where real git rejects it exit 129). `cloneRepo` argv: `git <GIT_SSRF_FLAGS> clone <GIT_SSRF_SUBCOMMAND_FLAGS> --depth=1 [--branch X] -- <url> <dir>`. `pullRepo` argv: `git <GIT_SSRF_FLAGS> -C <dir> pull <GIT_SSRF_SUBCOMMAND_FLAGS> --ff-only`. Pinned by `test/git-remote.test.ts` position-anchored regression guard (`argv.indexOf('--no-recurse-submodules') > argv.indexOf(verb)`). Also exports the durability-side helpers that power `gbrain sources harden/pull`: `GIT_ENV_AUTH` (the no-prompt env minus the askpass `/bin/false` overrides, so an auth'd push/fetch can consult the repo's configured credential helper while `GIT_TERMINAL_PROMPT=0` still fails fast on a missing credential), `divergenceSafePull(repoPath, branch)` (fetch + `pull --rebase`; returns `skipped_dirty` on a dirty tree, `conflict_aborted` on a rebase conflict after `rebase --abort` so the tree is never left mid-rebase, else `up_to_date`/`advanced`), `detectDefaultBranch` (origin/HEAD → current branch → `main`), `pushProbe(repoPath, branch)` (authenticated `push --dry-run` that proves push access and classifies `auth`/`protected`/`unreachable`), and `isWorkingTreeDirty`. These auth'd paths route their `protocol.file.allow` through `GBRAIN_GIT_ALLOW_FILE_TRANSPORT` (default `never`; set `=1` for self-hosted filesystem remotes), unlike clone/pull which stay strict.-- `src/core/brain-repo-durability.ts` + `src/commands/sources-harden.ts` — brain-repo git durability. `hardenBrainRepo(opts)` makes a brain's working tree durable, idempotently: divergence-safe pull, a LOCAL untracked `.git/hooks/post-commit` auto-push safety net (never committed — a pulled commit can't rewrite executed code next to the token; installed into the active `core.hooksPath` dir and excluded via `.git/info/exclude` when that dir is tracked), a committed `scripts/brain-commit-push.sh` that refuses to exit 0 without a confirmed push and stages+commits BEFORE any pull so a dirty tree of modified pages (the write-through shape) can still be committed — the push-retry's rebase-on-reject handles a remote that advanced (#2426; hook + helper render from ONE bash push-retry template — DRY at the TS source, not by the hook sourcing a repo-controlled script), durability rules patched into the active resolver file (`findResolverFile` → RESOLVER.md > AGENTS.md; taxonomy rendered from the bundled `_brain-filing-rules.json`), a minimal DB-free 30-min pull cron (launchd/crontab running `gbrain sources pull --path <dir>` so it never opens the PGLite single-writer lock; on a non-darwin host `installDurabilityCron` probes `binaryOnPath('crontab')` first and returns `skipped` — not `needs_attention` — when absent, since containers/cloud sandboxes ship no scheduler and the event-driven pushes cover persistence; the wrapper self-disables via `git rev-parse --is-inside-work-tree`, worktree-safe both ways), and a push-probe verify (no heartbeat commit). `durabilityJobStatus(sourceId)` reports presence + LIVENESS (launchctl load-state on darwin, crontab line on linux, pull-log freshness) so the doctor `bootstrap_durability_job` check can't certify a dead job as healthy. Credential is REPO-scoped (`acceptPat` from `--pat-file`/`GBRAIN_GITHUB_PAT`, warns on loose perms; reuses an existing repo-local `credential.helper`, else a `0600` store wired via repo-local config); the token is redacted everywhere via `redactSecretsInText` and never enters the repo, remote URL, logs, or `DurabilityReport`. `unhardenBrainRepo` removes the cron/hook/credential wiring (ownership-fingerprinted) and runs before `sources remove`. CLI: `gbrain sources harden <id|--all>` / `pull <id>|--path <dir>` / `unharden <id>`; auto-harden fires on `sources add --url ... --pat-file` for managed clones (`--no-harden` opts out). `sources pull --path` is dispatched in `src/cli.ts` BEFORE `connectEngine` so the cron stays DB-free. CLI-only (writes executables + an OS cron + a credential helper on the host); never exposed over MCP. Tests: `test/brain-repo-durability.serial.test.ts`, `test/git-remote-durable.serial.test.ts`, `test/brain-durability-hook.serial.test.ts`, `test/durability-cron.test.ts`.+- `src/core/brain-repo-durability.ts` + `src/commands/sources-harden.ts` — brain-repo git durability. `hardenBrainRepo(opts)` makes a brain's working tree durable, idempotently: divergence-safe pull, a LOCAL untracked `.git/hooks/post-commit` auto-push safety net (never committed — a pulled commit can't rewrite executed code next to the token; installed into the active `core.hooksPath` dir and excluded via `.git/info/exclude` when that dir is tracked), a committed `scripts/brain-commit-push.sh` that refuses to exit 0 without a confirmed push and stages+commits BEFORE any pull so a dirty tree of modified pages (the write-through shape) can still be committed — the push-retry's rebase-on-reject handles a remote that advanced (#2426; hook + helper render from ONE bash push-retry template — DRY at the TS source, not by the hook sourcing a repo-controlled script), durability rules patched into the active resolver file (`findResolverFile` → RESOLVER.md > AGENTS.md; taxonomy rendered from the bundled `_brain-filing-rules.json`), a minimal DB-free pull cron (launchd/crontab running `gbrain sources pull --path <dir>` so it never opens the PGLite single-writer lock), and a push-probe verify (no heartbeat commit). Credential is REPO-scoped (`acceptPat` from `--pat-file`/`GBRAIN_GITHUB_PAT`, warns on loose perms; reuses an existing repo-local `credential.helper`, else a `0600` store wired via repo-local config); the token is redacted everywhere via `redactSecretsInText` and never enters the repo, remote URL, logs, or `DurabilityReport`. `unhardenBrainRepo` removes the cron/hook/credential wiring (ownership-fingerprinted) and runs before `sources remove`. CLI: `gbrain sources harden <id|--all>` / `pull <id>|--path <dir>` / `unharden <id>`; auto-harden fires on `sources add --url ... --pat-file` for managed clones (`--no-harden` opts out). `sources pull --path` is dispatched in `src/cli.ts` BEFORE `connectEngine` so the cron stays DB-free. CLI-only (writes executables + an OS cron + a credential helper on the host); never exposed over MCP. Tests: `test/brain-repo-durability.serial.test.ts`, `test/git-remote-durable.serial.test.ts`, `test/brain-durability-hook.serial.test.ts`, `test/durability-cron.test.ts`.- `src/commands/storage.ts` — `gbrain storage status [--repo P] [--json]`. Split into pure data (`getStorageStatus`) + JSON formatter + human formatter (ASCII-only) matching the `orphans.ts` pattern. `PageCountsByTier` and `DiskUsageByTier` are distinct nominal types so swaps fail at compile time.- `gbrain.yml` (brain repo root) — Optional storage tiering config. Top-level `storage:` section with `db_tracked:` and `db_only:` array-valued keys. `gbrain sync` auto-manages `.gitignore` for `db_only` paths on successful sync (skips on dry-run, blocked-by-failures, submodule context, or `GBRAIN_NO_GITIGNORE=1`). `gbrain export --restore-only [--repo P] [--type T] [--slug-prefix S]` repopulates missing `db_only` files from the database.- `src/core/supabase-admin.ts` — Supabase admin API (project discovery, pgvector check).@@ -197,11 +196,11 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `src/core/extraction-review.ts` — Extraction quarantine lane markers (issue #160), sibling of `src/core/quarantine.ts` / `embed-skip.ts` (frontmatter-key pattern, no schema migration). Auto-extracted stubs from untrusted input carry the PAIR `provenance: 'auto-extracted'` + `status: 'unverified'` (both required — user pages with their own `status`/`provenance` never match). Exports `quarantineMarkers()`, `isUnverifiedExtraction()` (JS predicate) and `unverifiedExtractionFragment(alias)` — the single SQL source of truth consumed by `buildSourceFactorCase` (namespace source-boost guard), both engines' `getUnverifiedExtractionPageIds`, the `extraction_pending` op, and the `unverified_extractions` doctor check, so filter and marker keys can never drift. Consequences: unverified stubs are excluded from the compiled-truth fusion boost + the `people/`/`companies/` source-boost (rank as ordinary content), stamped `unverified: true` in search results (`stampUnverifiedExtractions`, hybrid.ts), listed by `extraction_pending`, promoted (status → `verified`, provenance kept for audit) or rejected (soft-delete) by the owner-only `extraction_review` op. Pinned by `test/extraction-review.test.ts` (PGLite) + `test/e2e/extraction-review-postgres.test.ts` (live Postgres parity).- `src/commands/enrich.ts` + `src/core/enrich/thin.ts` + `src/core/cycle/enrich-thin.ts` — `gbrain enrich --thin`: batch-develops stub (thin) pages via **brain-internal grounded synthesis**. gbrain's model tooling sees only brain-internal context (search / get_page / facts / backlinks), not the web, so enrich consolidates what the brain ALREADY knows about an entity (scattered across meetings, other pages, deals, facts) into one cited page via ONE `gateway.chat` call per page; web research stays the agent-driven `enrich` SKILL's job. `runEnrichCore(engine, opts, signal)` (strict per-source; multi-source iteration is the caller's job) drives `enrichOne` per candidate: `withRefreshingLock('enrich:<src>:<slug>')` → `getPage` → deterministic retrieve (hybridSearch + getBacklinks + facts + raw_data, source-scoped, sanitized via `INJECTION_PATTERNS`) → `assessGrounding` gate (skip < `MIN_CONTEXT_CHARS`, no LLM) → `buildEnrichPrompt` (grounded dossier, `[Source: slug]` citations, SKIP sentinel) → synth → `put_page` handler (`remote:false`, auto-link + write-through) stamping `enriched_at` + `enriched_by:'cli:enrich'`. Candidate selection is the SQL-native `engine.listEnrichCandidates(opts)` (`src/core/engine.ts` interface + `EnrichCandidate`/`EnrichCandidatesOpts`/`ENRICH_ORDER_SQL` in `src/core/types.ts` + pg/pglite impls): thin-filter + per-page source-correct inbound count (`to_page_id = p.id`, `mentions` excluded) + `enriched_at` recency guard + whitelisted ORDER BY + LIMIT, lightweight projection (NO bodies). Resume via `src/core/op-checkpoint.ts` (local `enrichFingerprint`); budget via `BudgetTracker` + `withBudgetTracker` (best-effort under `--workers > 1` — `runSlidingPool` aborts new claims on `BUDGET_EXHAUSTED` but does NOT cancel in-flight `gateway.chat`; pin `--workers 1` for a hard ceiling). `sanitizeContext` (thin.ts) neutralizes the `<context>…</context>` data-envelope delimiters (injection escape, mirrors the `</trajectory>` convention); the `--background` multi-source fan-out idempotency key carries the run fingerprint via exported `backgroundIdempotencyKey(sid, args)` (a bare `enrich:${sid}` would return stale completed jobs); `runEnrichCore` flags `budget_exhausted` post-hoc when `tracker.totalSpent > tracker.cap` even when the gateway swallowed the final-call throw (via read-only `BudgetTracker.cap` getter); `body()` flushes the checkpoint on `BudgetExhausted` before it propagates so resume doesn't re-charge. The opt-in `enrich_thin` cycle phase (default OFF via `cycle.enrich_thin.enabled`) trickles `max_pages_per_tick` (default 3) per source with per-source cost cap enforced as `min(per_source_cap, brain_wide_remaining)` + brain-wide total + walltime caps. Wired into `cycle.ts` (`CyclePhase`/`ALL_PHASES` between `conversation_facts_backfill` and `skillopt`/`embed`; `PHASE_SCOPE='source'`; `NEEDS_LOCK`; dispatch), `cli.ts` (`CLI_ONLY` + `CLI_ONLY_SELF_HELP` + `THIN_CLIENT_REFUSED_COMMANDS` + dispatch), `jobs.ts` (Minion `enrich` handler, strict per-source, NOT in `PROTECTED_JOB_NAMES`). DI seam `opts.synthesizeFn` keeps tests hermetic (no API key, no mock.module). Pinned by `test/enrich/thin.test.ts`, `test/enrich/idempotency.test.ts`, `test/enrich-cycle-phase.test.ts`, `test/e2e/enrich-pglite.test.ts` (grew-cited, skip, ordering, multi-source, recency, resume, budget abort + checkpoint flush, final-call overage, lock-skip, provenance), `test/e2e/engine-parity.test.ts` (`listEnrichCandidates` pg↔pglite parity).- `src/core/data-research.ts` — Recipe validation, field extraction (MRR/ARR regex), dedup, tracker parsing, HTML stripping.-- `src/commands/embed.ts` — `gbrain embed [--stale|--all] [--slugs ...]`. `--stale` starts with `engine.countStaleChunks()` (single SELECT count(*) WHERE embedding IS NULL, ~50 bytes wire) so a fully-embedded brain short-circuits with no further reads. When stale chunks exist, `engine.listStaleChunks()` returns just the chunks needing embeddings (slug + chunk_index + chunk_text + metadata, no `vector(1536)` payload); caller groups by slug, embeds, re-upserts via `upsertChunks`. All `console.log`/`console.error` call sites use `slog`/`serr` from `src/core/console-prefix.ts` so when `runEmbedCore` runs inside a per-source `withSourcePrefix` scope (installed by the `gbrain sync --all` worker pool) every line carries the `[<source-id>] ` prefix; standalone callers see identical output because slog/serr fall through to bare console fns outside the wrap. Every embed-write path stamps `pages.embedding_signature` via `engine.setPageEmbeddingSignature(slug, {sourceId, signature: currentEmbeddingSignature()})` so a later model/dims swap is detectable as stale. The per-slug path (`embedPage`, used by `gbrain embed <slug>` AND sync's post-import embed step) and the full-re-embed path (`embedAll`) stamp per page when every chunk embedded cleanly. The stale path (`embedAllStale`) first calls `invalidateStaleSignatureEmbeddings` on a live run so signature-drifted pages flow through the NULL cursor, then stamps each page — but ONLY when EVERY chunk was stale this pass (a partially-stale page keeps preserved chunks of unknown provenance, so it stays unstamped rather than falsely marked current; `embed --all` fully re-embeds + stamps those). dry-run never mutates: it counts signature-drift via the widened `countStaleChunks({signature})` predicate without NULLing anything. `--include-null-signature` (#3391) lifts the NULL-signature grandfather clause: threads `includeNullSignature: true` into the invalidation + counts so pages that predate the v108 stamp re-embed too after a model swap (both engines' `countStaleChunks`/`sumStaleChunkChars`/`invalidateStaleSignatureEmbeddings` accept the flag; predicate becomes `sig IS NULL OR sig <> current`). Without the flag, a live stale run that just invalidated drifted rows probes for left-behind NULL-signature chunks and emits a loud stderr warning naming the count + the fix — mixed embedding spaces in one index are never silent. Pinned by `test/embedding-migration.test.ts` + `test/e2e/migrate-embeddings-postgres.test.ts`. Embed failures are never silent (#3037): all three page paths embed via `embedPageTexts`, which tries the page's chunks in one batch and, on a PERMANENT request-shaped failure (non-429, non-`AITransientError`, non-auth), retries once per chunk so one bad chunk costs one chunk instead of darkening the whole page (failed chunks stay `embedding IS NULL` for the next `--stale` pass; a partially-failed page is never signature-stamped). Rate-limit/outage/auth failures do NOT fan out (cost bounding — `embedBatchWithBackoff` already owns 429 backoff). Failed chunk counts land on `EmbedResult.failures` + capped `failure_samples`, and `src/cli.ts`'s embed case sets a non-zero exit verdict on `failures > 0` (mirror of the `import` errors>0 guard). Pinned by `test/embed-partial-failure-3037.serial.test.ts` + `test/embed-exit-code-3037.serial.test.ts` (real spawned CLI). applies the `embed-skip` filter at all 5 stale-chunk sites: `runEmbedCore --stale`, `runEmbedCore --all`, the `embed-stale` Minion helper, plus both engines' `listStaleChunks` + `countStaleChunks` via `EMBED_SKIP_SQL_FRAGMENT`. A soft-blocked page is queryable by title/slug but its chunks never enter the embed sweep. The shared helper from `src/core/embed-skip.ts` is the regression guard — no per-site ad-hoc filter allowed. Pinned by `test/embed-skip.test.ts`. both inline sliding-pool sites (`embedAll` simple at `:458-467` and `embedAllStale` paginated + AbortSignal at `:586-632`) call `runSlidingPool` from the shared worker-pool helper. Invariant-level contract preserved (counts + cost + AbortSignal propagation + per-batch rate-limit retry via `embedBatchWithBackoff`); byte-equality on progress-event ORDERING is NOT promised. The `GBRAIN_EMBED_CONCURRENCY || 20` default is preserved and embed bypasses `resolveWorkersWithClamp` because the 20-worker default would otherwise silently change every brain's embed hot path. Pinned by `test/embed-helper-migration.test.ts` (asserts the helper is wired in AND the pre-migration `let nextIdx = 0` + `Promise.all(Array.from({length: numWorkers}, ...))` shapes are gone). wires `--background` as the reference integration for the `maybeBackground()` helper. `gbrain embed --stale --background` submits as a Minion job, prints `job_id=N` to stdout, exits 0. Composable: `JOB=$(gbrain embed --stale --background | grep -oE 'job_id=[0-9]+' | cut -d= -f2); gbrain jobs follow $JOB`. The other six commands (`extract`, `lint`, `backlinks`, `reindex`, `integrity`, `pages`) adopt the same pattern in a follow-up wave. #1737: `runEmbedCore` accepts an optional `signal` threaded down both the `--stale` and `--all` paths (`embedAllStale`/`embedAll`/`embedPage`); each composes it with the internal wall-clock budget via `anySignal` and checks `isAborted`/`effectiveSignal.aborted` in every per-slug loop, page-claim pool, and `embedBatch` call, so a worker abort (wall-clock timeout / lock loss / SIGTERM) stops embedding within a batch. Pinned by `test/embed.serial.test.ts`. Keyless brains (`embedding_disabled: true`): the exported pure predicate `isKeylessStaleRefusal(args, embeddingDisabled)` gates a CLEAN refusal at the top of `runEmbed` — a bare stale run prints a stderr hint and returns a zero-failure result (exit 0), because the documented agent-scheduler chain `gbrain sync ... && gbrain embed --stale` must stay green on a keyless install; explicit asks (a slug, a slugs list, the all flag) and dry-run keep exiting 1 via `EmbeddingDisabledError`, mirroring the dispatch precedence where a slugs list wins over stale. Pinned by `test/embed-keyless-guard.test.ts` + `test/agent-scheduler-contract.serial.test.ts`.+- `src/commands/embed.ts` — `gbrain embed [--stale|--all] [--slugs ...]`. `--stale` first calls `engine.countChunklessPagesWithContent()` (chunkless-page safety net: a page written directly via `putPage` — e.g. an enrichment-generated stub — that never went through chunking has ZERO `content_chunks` rows, so it has no row to go stale and is otherwise invisible to this command forever; the predicate excludes quarantined/embed_skip pages, both intentionally chunkless). When found, `healChunklessPages` chunks them locally (mirrors `embedPage`'s chunkless branch: same `chunkText` calls over `compiled_truth`/`timeline`) with `embedding = NULL`, folding the new rows into the SAME pass; immediately before writing it re-fetches the LIVE page via `getPage` (chunks CURRENT content, not the batch-list snapshot) and re-checks `getChunks`, narrowing (NOT fully closing — accepted residual risk, see the function's docstring) the check-then-write window: a concurrent writer landing chunks in the gap between that re-check and the `upsertChunks` call can still have them overwritten with this sweep's stale-content chunks, the same unmitigated-until-now window `embedPage`'s single-page chunkless branch already ships with. Each page's work is try/caught (a bad chunkless page records a failure via the same `EmbedResult.failures`/`recordFailure` path as every other embed failure and the sweep moves on — it never aborts the whole `--stale` run before the normal stale-chunk pass even starts). `listChunklessPagesWithContent`'s default batch is 50 (not the 2000-row default elsewhere in this file) because each row carries a full page body. It honors the caller's pacer, mirrors `--catch-up` (removes its cap entirely, matching the main loop below), and otherwise shares ONE `GBRAIN_EMBED_TIME_BUDGET_MS` wall-clock budget with the main stale loop (both measure from the same `overallStartedAt`, not two independent 30-minute windows) so a large damaged brain can't run the combined `--stale` pass unbounded; an abort during healing stops the whole function before falling through to `invalidateStaleSignatureEmbeddings`. Pinned by `test/embed-stale-chunkless-pages.serial.test.ts` + `test/e2e/engine-parity.test.ts`. Then `--stale` calls `engine.countStaleChunks()` (single SELECT count(*) WHERE embedding IS NULL, ~50 bytes wire) so a fully-embedded brain short-circuits with no further reads beyond those two counts. When stale chunks exist, `engine.listStaleChunks()` returns just the chunks needing embeddings (slug + chunk_index + chunk_text + metadata, no `vector(1536)` payload); caller groups by slug, embeds, re-upserts via `upsertChunks`. All `console.log`/`console.error` call sites use `slog`/`serr` from `src/core/console-prefix.ts` so when `runEmbedCore` runs inside a per-source `withSourcePrefix` scope (installed by the `gbrain sync --all` worker pool) every line carries the `[<source-id>] ` prefix; standalone callers see identical output because slog/serr fall through to bare console fns outside the wrap. Every embed-write path stamps `pages.embedding_signature` via `engine.setPageEmbeddingSignature(slug, {sourceId, signature: currentEmbeddingSignature()})` so a later model/dims swap is detectable as stale. The per-slug path (`embedPage`, used by `gbrain embed <slug>` AND sync's post-import embed step) and the full-re-embed path (`embedAll`) stamp per page when every chunk embedded cleanly. The stale path (`embedAllStale`) first calls `invalidateStaleSignatureEmbeddings` on a live run so signature-drifted pages flow through the NULL cursor, then stamps each page — but ONLY when EVERY chunk was stale this pass (a partially-stale page keeps preserved chunks of unknown provenance, so it stays unstamped rather than falsely marked current; `embed --all` fully re-embeds + stamps those). dry-run never mutates: it counts signature-drift via the widened `countStaleChunks({signature})` predicate without NULLing anything. `--include-null-signature` (#3391) lifts the NULL-signature grandfather clause: threads `includeNullSignature: true` into the invalidation + counts so pages that predate the v108 stamp re-embed too after a model swap (both engines' `countStaleChunks`/`sumStaleChunkChars`/`invalidateStaleSignatureEmbeddings` accept the flag; predicate becomes `sig IS NULL OR sig <> current`). Without the flag, a live stale run that just invalidated drifted rows probes for left-behind NULL-signature chunks and emits a loud stderr warning naming the count + the fix — mixed embedding spaces in one index are never silent. Pinned by `test/embedding-migration.test.ts` + `test/e2e/migrate-embeddings-postgres.test.ts`. Embed failures are never silent (#3037): all three page paths embed via `embedPageTexts`, which tries the page's chunks in one batch and, on a PERMANENT request-shaped failure (non-429, non-`AITransientError`, non-auth), retries once per chunk so one bad chunk costs one chunk instead of darkening the whole page (failed chunks stay `embedding IS NULL` for the next `--stale` pass; a partially-failed page is never signature-stamped). Rate-limit/outage/auth failures do NOT fan out (cost bounding — `embedBatchWithBackoff` already owns 429 backoff). Failed chunk counts land on `EmbedResult.failures` + capped `failure_samples`, and `src/cli.ts`'s embed case sets a non-zero exit verdict on `failures > 0` (mirror of the `import` errors>0 guard). Pinned by `test/embed-partial-failure-3037.serial.test.ts` + `test/embed-exit-code-3037.serial.test.ts` (real spawned CLI). applies the `embed-skip` filter at all 5 stale-chunk sites: `runEmbedCore --stale`, `runEmbedCore --all`, the `embed-stale` Minion helper, plus both engines' `listStaleChunks` + `countStaleChunks` via `EMBED_SKIP_SQL_FRAGMENT`. A soft-blocked page is queryable by title/slug but its chunks never enter the embed sweep. The shared helper from `src/core/embed-skip.ts` is the regression guard — no per-site ad-hoc filter allowed. Pinned by `test/embed-skip.test.ts`. both inline sliding-pool sites (`embedAll` simple at `:458-467` and `embedAllStale` paginated + AbortSignal at `:586-632`) call `runSlidingPool` from the shared worker-pool helper. Invariant-level contract preserved (counts + cost + AbortSignal propagation + per-batch rate-limit retry via `embedBatchWithBackoff`); byte-equality on progress-event ORDERING is NOT promised. The `GBRAIN_EMBED_CONCURRENCY || 20` default is preserved and embed bypasses `resolveWorkersWithClamp` because the 20-worker default would otherwise silently change every brain's embed hot path. Pinned by `test/embed-helper-migration.test.ts` (asserts the helper is wired in AND the pre-migration `let nextIdx = 0` + `Promise.all(Array.from({length: numWorkers}, ...))` shapes are gone). wires `--background` as the reference integration for the `maybeBackground()` helper. `gbrain embed --stale --background` submits as a Minion job, prints `job_id=N` to stdout, exits 0. Composable: `JOB=$(gbrain embed --stale --background | grep -oE 'job_id=[0-9]+' | cut -d= -f2); gbrain jobs follow $JOB`. The other six commands (`extract`, `lint`, `backlinks`, `reindex`, `integrity`, `pages`) adopt the same pattern in a follow-up wave. #1737: `runEmbedCore` accepts an optional `signal` threaded down both the `--stale` and `--all` paths (`embedAllStale`/`embedAll`/`embedPage`); each composes it with the internal wall-clock budget via `anySignal` and checks `isAborted`/`effectiveSignal.aborted` in every per-slug loop, page-claim pool, and `embedBatch` call, so a worker abort (wall-clock timeout / lock loss / SIGTERM) stops embedding within a batch. Pinned by `test/embed.serial.test.ts`. Keyless brains (`embedding_disabled: true`): the exported pure predicate `isKeylessStaleRefusal(args, embeddingDisabled)` gates a CLEAN refusal at the top of `runEmbed` — a bare stale run prints a stderr hint and returns a zero-failure result (exit 0), because the documented agent-scheduler chain `gbrain sync ... && gbrain embed --stale` must stay green on a keyless install; explicit asks (a slug, a slugs list, the all flag) and dry-run keep exiting 1 via `EmbeddingDisabledError`, mirroring the dispatch precedence where a slugs list wins over stale. Pinned by `test/embed-keyless-guard.test.ts` + `test/agent-scheduler-contract.serial.test.ts`.- `src/core/retrieval-upgrade-planner.ts` — `runSchemaTransition(engine, targetDim)` (exported) is the ONE atomic dimension-transition path, shared by `ze-switch` and `gbrain migrate embeddings`. In a single transaction it rebuilds ALL THREE dim-pinned text-embedding-space columns at `targetDim` — `content_chunks.embedding`, `query_cache.embedding`, `facts.embedding` — preserving each column's declared type (`vector` vs `halfvec`, probed from `information_schema`) and recreating its HNSW index with the matching opclass, gated on `hnswIndexExpected` (above the per-type dim ceiling pgvector refuses the index and exact scans remain the path). query_cache + facts are created at brain-birth width by `migrate.ts` and NO migration ever ALTERs them, so omitting either leaves it silently broken: a narrow `query_cache.embedding` makes every `store()`/`lookup()` fail inside the cache's own error-swallowing (permanent 0% hit rate), and a narrow `facts.embedding` fails every per-fact embed write (the doctor check that would warn is skipped on PGLite, the default engine). `content_chunks.embedding_image` / `embedding_multimodal` are the deliberate exception — separate multimodal models, dimensions independent of the text model. Pinned by `test/embedding-migration.test.ts` (all three widths + a real INSERT at the new width into each) and `test/e2e/migrate-embeddings-postgres.test.ts`.- `src/core/embedding-migration.ts` — provider-agnostic embedding migration core (#3390): `planEmbeddingMigration` (workload counts via the widened stale predicates with the TARGET signature + `includeNullSignature`, so a mid-migration re-plan counts only what remains; cost via `embedding-pricing.ts`; `null_signature_chunks` split out for #3391 visibility; reranker-on-outgoing-provider warning), `applyEmbeddingMigration` (env-override gate BEFORE any mutation → in-flight state marker `embedding_migration.state` → `runSchemaTransition` when the ACTUAL column width differs from target → DB-plane `embedding_model`/`embedding_dimensions` → `persistConfig` callback for the file plane → `invalidateStaleSignatureEmbeddings({includeNullSignature: true})` → `SemanticQueryCache.clear()`), `completeEmbeddingMigration` (clears the marker + stamps `embedding_migration.completed`; call only at zero backlog), `resolveMigrationTarget` (validates `provider:model` via `resolveRecipe`, dims via `embeddingDimsForModel` or explicit `--dim`), `migrationSignature` (matches `currentEmbeddingSignature()` shape). Engine-pure; every step idempotent under crash + re-run — the NULL-embedding column is the checkpoint. Reuses `runSchemaTransition` (now exported from `retrieval-upgrade-planner.ts`) so ze-switch and the migration share ONE dimension-transition path. `reconcilePageSignatures(engine, plan)` runs after the re-embed drain and BEFORE the completion probe: it stamps the target signature on every page that has zero NULL-embedding chunks, covering pages whose chunks straddle a `listStaleChunks` batch boundary (the embed loop only stamps when `stale.length === existing.length`, so a split page is embedded correctly but never stamped — without the reconcile a >1-batch brain reports "incomplete" and the re-run re-invalidates and re-pays for those pages). Sound only because apply() invalidated everything not already in the target space; pages with a remaining NULL chunk stay unstamped so a real embed failure still surfaces. Invalidation is ordered BEFORE the config writes so a crash on a same-dim swap leaves rows merely stale (empty results) rather than new-space queries scored against old-space vectors (silently wrong). Pinned by `test/embedding-migration.test.ts` (PGLite) + `test/e2e/migrate-embeddings-postgres.test.ts` (real pgvector).- `src/commands/migrate-embeddings.ts` — `gbrain migrate embeddings --to <provider:model> [--dim N] [--dry-run] [--yes] [--json] [--no-embed] [--pace[=mode]] [--ignore-env-override]` (alias: `gbrain retrieval-upgrade`, the command README/doctor promised since v0.36). Flow: plan → render (stderr when `--json` so stdout stays JSON-clean) → consent gate (TTY y/N prompt or `--yes`; non-TTY without `--yes` refuses exit 2, mirroring the reindex-code cost gate) → live probe (one embed against the TARGET model/dims BEFORE any mutation — bad key/model/dim fails with nothing changed) → `applyEmbeddingMigration` with `persistEmbeddingFileConfig` (writes `~/.gbrain/config.json` + reconfigures the in-process gateway — the gateway reads file/env, NOT the DB plane) → `runEmbedCore({stale, catchUp, singleFlight, includeNullSignature, pace})` → drain check → `completeEmbeddingMigration` or exit 1 with the resume hint (re-run the same command). Also surfaced as the `migrate_embeddings` op (scope admin, localOnly, hidden cliHints; handler hard-refuses `ctx.remote !== false` and returns `needs_confirmation` + plan without `yes: true`). Pinned by `test/migrate-embeddings-flow.serial.test.ts` (full lifecycle incl. interrupted-run resume on PGLite).-- `src/core/conversation-parser/` — 18-pattern built-in chat-format registry + opt-in LLM polish/fallback. Modules: `types.ts` (PatternEntry + ParseResult + DateContext + CaptureMap + TimezonePolicy), `builtins.ts` (18 hand-vetted patterns sourced from public format docs — iMessage/Slack, Telegram bracket + text-export, bold-paren-time, bold-time-dash, bold-name-no-time, Discord classic + export, WhatsApp ISO + US, Signal, Matrix/Element, IRC classic + weechat, Teams export, markdown-heading-turn; module-load validation runs every `test_positive[]` + `test_negative[]` sample at startup so a typo in any built-in regex makes gbrain refuse to start; `DEFAULT_SPEAKER_CLEAN` exported as a module-level default), `parse.ts` (orchestrator with pattern-priority scoring across the first 10 lines + date derivation chain `explicit > frontmatter.date > effective_date > '1970-01-01'` + multi-line continuation + timezone warning), `llm-base.ts` (shared `runLlmCall<T>` with content-hash cache in-process + DB-persistent via migration v97 + 4-strategy JSON repair + Anthropic-key probe; polish and fallback are thin wrappers), `llm-polish.ts` (opt-IN; headroom guard skips when tracker within $0.10 of cap; pure `applyPolish` for merge/drop/edit ops), `llm-fallback.ts` (opt-IN; NO regex inference + NO persistence), `eval.ts` (`scoreFixture` + `aggregateScores` + `parseFixtureJsonl` for the fixture-corpus CI gate), `nightly-probe.ts` (DI-stubbed; mode-gated default tokenmax=ON, conservative/balanced opt-in; adversarial false-positive detection). Pattern `bold-name-no-time` (regex `/^\*\*(?!\[)(.+?):\*\*\s*(.*)$/`, ordered after the time-bearing bold patterns) parses `**Speaker:** text` with NO per-line timestamp (Circleback/Granola/Zoom), anchoring every message at `T00:00:00Z` of the frontmatter date (line order preserves sequence, same no-time convention as `irc-classic`); the `(?!\[)` lookahead rejects telegram-bracket `**[18:37] Name:**`; non-shadow is the colon-INSIDE-bold regex (NOT declaration order — `parse.ts` scores every candidate independently, order is only the tie-break). Because `**Label:** text` is a common prose idiom, the pattern sets optional `PatternEntry.score_full_body: true` so `parse.ts` recomputes the winner's acceptance score over the FULL body before the `SCORING_MIN_ACCEPTANCE` floor, keeping a bold-label notes page at `no_match`. Pattern `bold-paren-time` parses `**Speaker** (HH:MM): text` and `(HH:MM:SS)` (date_source: frontmatter). Fallback gates: `SCORING_HEAD_TRIGGER_THRESHOLD = 0.3` triggers a full-body re-score when the head pass scores below that; `SCORING_MIN_ACCEPTANCE = 0.05` blocks essay false-positives. Exported `scorePatternFull(body, entry)`; private `getNonBlankLines(body, headCap?)` + `scoreFromLines(lines, entry)` DRY the quick_reject+regex loop. CLI surfaces at `src/commands/eval-conversation-parser.ts` (`gbrain eval conversation-parser <fixture.jsonl>` exit 0/1/2, wired into `bun run verify` via `check:conversation-parser`) and `src/commands/conversation-parser.ts` (`scan <slug>` debug, `list-builtins`, `validate <file>`). Doctor checks: `conversation_format_coverage`, `progressive_batch_audit_health`, `conversation_parser_probe_health`. Pinned by `test/conversation-parser/{parse,llm-base,llm-fallback,llm-polish,nightly-probe}.test.ts` + the 27-case baseline at `test/extract-conversation-facts.test.ts` (back-compat invariant). Migration v97 (`conversation_parser_llm_cache_table`). Fixtures at `test/fixtures/conversation-formats/{imessage,imessage-time-only-12h,telegram-bracket,whatsapp-iso,whatsapp-us,signal-export,irc-classic,irc-weechat,matrix-element,teams-export,all,adversarial,bold-name-no-time,bold-time-dash}.jsonl` with `scripts/check-fixture-privacy.sh` banning real-name leaks. Maintainer guidance: [conversation parser patterns](conversation-parser-patterns.md).+- `src/core/conversation-parser/` — 17-pattern built-in chat-format registry + opt-in LLM polish/fallback. Modules: `types.ts` (PatternEntry + ParseResult + DateContext + CaptureMap + TimezonePolicy), `builtins.ts` (17 hand-vetted patterns sourced from public format docs — iMessage/Slack, Telegram bracket + text-export, bold-paren-time, bold-time-dash, bold-name-no-time, Discord classic + export, WhatsApp ISO + US, Signal, Matrix/Element, IRC classic + weechat, Teams export; module-load validation runs every `test_positive[]` + `test_negative[]` sample at startup so a typo in any built-in regex makes gbrain refuse to start; `DEFAULT_SPEAKER_CLEAN` exported as a module-level default), `parse.ts` (orchestrator with pattern-priority scoring across the first 10 lines + date derivation chain `explicit > frontmatter.date > effective_date > '1970-01-01'` + multi-line continuation + timezone warning), `llm-base.ts` (shared `runLlmCall<T>` with content-hash cache in-process + DB-persistent via migration v97 + 4-strategy JSON repair + Anthropic-key probe; polish and fallback are thin wrappers), `llm-polish.ts` (opt-IN; headroom guard skips when tracker within $0.10 of cap; pure `applyPolish` for merge/drop/edit ops), `llm-fallback.ts` (opt-IN; NO regex inference + NO persistence), `eval.ts` (`scoreFixture` + `aggregateScores` + `parseFixtureJsonl` for the fixture-corpus CI gate), `nightly-probe.ts` (DI-stubbed; mode-gated default tokenmax=ON, conservative/balanced opt-in; adversarial false-positive detection). Pattern `bold-name-no-time` (regex `/^\*\*(?!\[)(.+?):\*\*\s*(.*)$/`, ordered after the time-bearing bold patterns) parses `**Speaker:** text` with NO per-line timestamp (Circleback/Granola/Zoom), anchoring every message at `T00:00:00Z` of the frontmatter date (line order preserves sequence, same no-time convention as `irc-classic`); the `(?!\[)` lookahead rejects telegram-bracket `**[18:37] Name:**`; non-shadow is the colon-INSIDE-bold regex (NOT declaration order — `parse.ts` scores every candidate independently, order is only the tie-break). Because `**Label:** text` is a common prose idiom, the pattern sets optional `PatternEntry.score_full_body: true` so `parse.ts` recomputes the winner's acceptance score over the FULL body before the `SCORING_MIN_ACCEPTANCE` floor, keeping a bold-label notes page at `no_match`. Pattern `bold-paren-time` parses `**Speaker** (HH:MM): text` and `(HH:MM:SS)` (date_source: frontmatter). Fallback gates: `SCORING_HEAD_TRIGGER_THRESHOLD = 0.3` triggers a full-body re-score when the head pass scores below that; `SCORING_MIN_ACCEPTANCE = 0.05` blocks essay false-positives. Exported `scorePatternFull(body, entry)`; private `getNonBlankLines(body, headCap?)` + `scoreFromLines(lines, entry)` DRY the quick_reject+regex loop. CLI surfaces at `src/commands/eval-conversation-parser.ts` (`gbrain eval conversation-parser <fixture.jsonl>` exit 0/1/2, wired into `bun run verify` via `check:conversation-parser`) and `src/commands/conversation-parser.ts` (`scan <slug>` debug, `list-builtins`, `validate <file>`). Doctor checks: `conversation_format_coverage`, `progressive_batch_audit_health`, `conversation_parser_probe_health`. Pinned by `test/conversation-parser/{parse,llm-base,llm-fallback,llm-polish,nightly-probe}.test.ts` + the 27-case baseline at `test/extract-conversation-facts.test.ts` (back-compat invariant). Migration v97 (`conversation_parser_llm_cache_table`). Fixtures at `test/fixtures/conversation-formats/{imessage,imessage-time-only-12h,telegram-bracket,whatsapp-iso,whatsapp-us,signal-export,irc-classic,irc-weechat,matrix-element,teams-export,all,adversarial,bold-name-no-time,bold-time-dash}.jsonl` with `scripts/check-fixture-privacy.sh` banning real-name leaks. Maintainer guidance: [conversation parser patterns](conversation-parser-patterns.md).- `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).- `src/commands/extract-conversation-facts.ts` + `src/core/cycle/conversation-facts-backfill.ts` — bulk fact extraction for long-form conversation pages. Walks conversation/meeting/slack/email/imessage/imessage-daily pages, splits them into time-windowed segments (30-min gap or 30-msg cap), prepends a topical/temporal header, and uses the strict `extractFactsFromTurnWithOutcome()` path so provider and output failures remain retryable instead of becoming successful empty pages. Invariants: **strict per-source core** (`runExtractConversationFactsCore({sourceId, ...})` always takes one sourceId; CLI + cycle phase each do their own multi-source iteration because `PHASE_SCOPE='source'` is taxonomy-only); **bounded two-phase enumeration** (paginated `listPages({type, sourceId, limit:10})`; per-page body cap `MAX_PAGE_BODY_BYTES=25MB`); **page-global `row_num` accumulator** (the facts unique index is `(source_id, source_markdown_slug, row_num)`); **versioned snapshot-bound outcomes** (`cli:extract-conversation-facts:terminal:v2` for complete pages and a separate `non-extractable:v2` source for recognized pages with no eligible segment); **operation checkpoints are scheduling hints only** and never suppress a replay without a matching v2 outcome; **optional `opts.budgetTracker?`** is used as-is, while an absent tracker is created with `maxCostUsd`; **body reads cover compiled truth, timeline, and configured raw-transcript sidecars**; **`facts.extraction_enabled` kill-switch** with `--override-disabled`; **`--types LIST` allowlist** (`conversation,meeting,slack,email,imessage,imessage-daily`); and **`--background` via `maybeBackground`**. The companion `conversation_facts_backfill` cycle phase is default-off, iterates every source, and enforces per-source plus brain-wide cost and wall-time caps. Migration v94 provides the partial facts index used by outcome lookups. `computeConversationFactsBacklogCheck` reports fresh completed, scanned-not-extractable, and unfinished counts separately, warning when more than 10 eligible pages lack a fresh v2 outcome. `sources audit` exposes `facts_backfill_estimate: {pages, est_segments, est_cost_usd, types}`. Pinned by `test/extract-conversation-facts.test.ts` and `test/doctor-conversation-facts-backlog.test.ts`. `--workers N` for LLM-bound fact extraction over conversation pages, with a per-page advisory lock via `src/core/db-lock.ts:withRefreshingLock` (lock id `extract-conversation-facts:<source>:<slug>`, TTL `PER_PAGE_LOCK_TTL_MINUTES=2` with 20s refresh via `Math.max(15s, 120s/6)`; `LockUnavailableError` triggers skip-and-continue with rate-limited log per (source, minute) + `pages_lock_skipped` counter + CLI exits 3 when non-zero AND no hard failures). `deleteOrphanFactsForPage(engine, sourceId, slug)` provides delete-orphans-first replay safety — wipes facts from a prior crashed run for this (sourceId, slug) before re-extracting, closing the "terminal audit row written after partial insertFacts failure" class. `assertFactsEmbeddingDimMatchesConfig(engine)` is the startup preflight (throws `FactsEmbeddingDimMismatchError` with paste-ready ALTER hint BEFORE the first insert; cached per engine via WeakMap). Result type carries `pages_lock_skipped` + `orphan_facts_cleaned`. Checkpoint state is a shared `cpMap: Map<slug, endIso>` (NOT a per-page-mutated `cpEntries: string[]`) so atomic `Map.set` survives parallel workers. Minion handler `extract-conversation-facts` in `src/commands/jobs.ts` round-trips `workers` via `job.data.workers` for `--background --workers 20`. Cycle config key `cycle.conversation_facts_backfill.workers` (default 1; opt-in concurrency under brain-wide cost + walltime caps). Pinned by `test/extract-conversation-facts-workers.test.ts` + the existing extract-conversation-facts behavioral tests. with `src/commands/doctor.ts` durable outcome authority: page completion survives operation-checkpoint GC through versioned terminal audit rows (`cli:extract-conversation-facts:terminal:v2`), while recognized pages with no eligible segment use the separate `cli:extract-conversation-facts:non-extractable:v2` source. Each outcome is bound to the exact parsed snapshot: regular pages use `content_hash` plus the UTC effective date; raw-conversation sidecars and legacy null-hash pages use a canonical SHA-256 over every parser-relevant input. Selection checks the token before locking, refetches under the lock, and verifies it again before writing the outcome, so an edit cannot be certified by stale work. The strict extraction path treats provider, refusal, truncation, malformed/schema-invalid output, segment-write, cleanup, and terminal-write failures as unfinished work; bulk failures increment `pages_failed`, affect CLI/cycle receipts and exit status, and never advance the legacy checkpoint. Checkpoints are only a scheduling hint: a slug without a matching v2 outcome is replayed delete-first. `no_match`, errors, cancellation, and dry runs never become durable negatives. Result, CLI, cycle, and doctor surfaces keep completed, scanned-not-extractable, unfinished, failed, and lock-skipped counts separate. See [Conversation backfill durable outcomes](../operations/conversation-backfill-outcomes.md) for the operator and maintainer contract. Pinned by `test/extract-conversation-facts.test.ts` and `test/doctor-conversation-facts-backlog.test.ts`.- `src/core/link-extraction.ts` — shared library for the graph layer. `extractEntityRefs` (canonical) matches `[Name](people/slug)` markdown links and Obsidian `[[people/slug|Name]]` wikilinks; `extractPageLinks`, `inferLinkType` heuristics (attended/works_at/invested_in/founded/advises/source/mentions), `parseTimelineEntries`, `isAutoLinkEnabled`. #2576: markdown links, bare-slug prose refs, and slash-shaped wikilinks match ANY dir-shaped path (`ANY_DIR_SEGMENT`), not a directory whitelist — nonexistent targets are dropped by the persist paths' page-existence checks (`resolveCandidateSources`, put_page's allSlugs filter, `addLinksBatch` INNER JOINs) and counted as `skippedMissingTarget` in the extract summaries; the `DIR_PATTERN` whitelist survives only as the typed fast-path for pass-2b wikilinks (non-whitelisted `[[dir/...]]` get an equivalent direct typed candidate in pass 2c, plus the flag-gated suffix rescue for non-exact matches). Used by extract.ts, operations.ts auto-link post-hook, and backlinks.ts. **Opt-in global-basename wikilink resolution** (issue #972, default off): `WIKILINK_GENERIC_RE` catches bare `[[name]]` wikilinks outside `DIR_PATTERN` (third pass `2c` in `extractEntityRefs`); `EntityRef.needsResolution: true` tags refs from this pass (the ref's `slug` is the wikilink TARGET, `name` the optional display alias). `SlugResolver` gains optional `resolveBasenameMatches(name): Promise<string[]>` (multi-match by design — emits one edge per matching page). The single shared basename matcher is `buildBasenameIndex(slugs)` + `queryBasenameIndex(index, name)` + `normalizeBasename` (keys raw/lower/slugified tail, stable-sorted shorter-first then lexical), used by `makeResolver`, the FS `resolveBasenameMatchesFromSlugs`, AND the doctor check so they cannot drift. `makeResolver(engine, {mode, sourceId})` builds the index lazily via `engine.getAllSlugs({sourceId})` — source-scoped so a bare `[[name]]` never resolves to a same-tail page in a different source. `extractPageLinks` gains `opts.globalBasename` (routes `needsResolution` refs through `resolveBasenameMatches` keyed on `ref.slug`, emits candidates tagged `linkType: 'wikilink_basename'` + `linkSource: 'wikilink-resolved'`, skips self-loops) and `opts.skipFrontmatter` (replaces the old `nullResolver` ternary). All three surfaces (FS extract, DB extract, `put_page` auto-link) tag provenance with `link_source='wikilink-resolved'`; `put_page` includes it in its reconcilable-edge set so stale basename edges are removed when the wikilink or the flag goes away. Exports `WIKILINK_BASENAME_LINK_TYPE` + `isGlobalBasenameEnabled(engine)` (resolution order: env `GBRAIN_LINK_RESOLUTION_GLOBAL_BASENAME` → DB config `link_resolution.global_basename` → default false). `gbrain doctor`'s `link_resolution_opportunity` check surfaces a paste-ready enable hint when ≥5 bare wikilinks would resolve AND ≥20% match. Migration v113 widens `links_link_source_check` to admit `'wikilink-resolved'`; v114 (#1941) then opens it to any kebab-case provenance (`^[a-z][a-z0-9]*(-[a-z0-9]+)*$`, ≤64 chars) so external derivers register their own tag (e.g. `citation-graph`) without a migration. `LINK_EXTRACTOR_VERSION_TS` also lives here (bump like `CHUNKER_VERSION` to invalidate prior extract-stale stamps). Pinned by `test/link-extraction.test.ts`, `test/extract-fs.test.ts`, `test/doctor.test.ts`, `test/e2e/global-basename-pglite.test.ts`.@@ -267,8 +266,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `src/commands/agent-logs.ts` — `gbrain agent logs <job> [--follow] [--since]`. Merges JSONL heartbeat audit + `subagent_messages` into a chronological timeline. `parseSince` accepts ISO-8601 or relative (`5m`, `1h`, `2d`). Transcript tail renders only for terminal jobs.- `src/commands/jobs.ts` — `gbrain jobs` CLI subcommands + `gbrain jobs work` daemon. `case 'work'` wraps `worker.start()` in try/finally and owns engine lifecycle — calls `engine.disconnect()` on shutdown with loud error logging (the worker must not disconnect an engine it doesn't own; pool slots free immediately on shutdown rather than waiting for TCP keepalive). `jobs submit` surfaces the full `MinionJobInput` retry/backoff/timeout/idempotency surface as flags: `--max-stalled`, `--backoff-type fixed|exponential`, `--backoff-delay`, `--backoff-jitter`, `--timeout-ms`, `--idempotency-key`. `jobs smoke --sigkill-rescue` is the SIGKILL-rescue regression guard. `registerBuiltinHandlers` always registers `subagent` + `subagent_aggregator` (no env flag — `ANTHROPIC_API_KEY` is the cost gate, trust is via `PROTECTED_JOB_NAMES`) and loads `GBRAIN_PLUGIN_PATH` plugins at startup with a loud per-plugin line; `shell` handler still gated by `GBRAIN_ALLOW_SHELL_JOBS=1` (RCE surface). The `autopilot-cycle` handler forwards `job.data.phases` to `runCycle`, validated against `ALL_PHASES` from `src/core/cycle.ts` (invalid names filtered; empty/missing falls back to the default cycle); when `source_id` is set it binds `brainDir` to that source's `local_path` (null for a pure-DB source, never the global repo — the #2194/#2227 mixed-scope fix) and checks `isSourceInCooldown` before `runCycle`, returning a no-op `skipped` (not a failure) for a source still in its failure cooldown. The sibling `autopilot-global-maintenance` handler runs the brain-wide `GLOBAL_PHASES` once (no `sourceId`, `pull:false`) and stamps `autopilot.last_global_at` on success. `resolveJobPull` gives both cycle and standalone sync jobs one positive-polarity `pull` contract while preserving queued payloads that still carry the inverse legacy `noPull` key; explicit `pull` wins. The `sync` handler resolves `sourceId` at entry from `sources.local_path` (mirrors `cycle.ts:480`) so multi-source brains read the per-source `last_commit` anchor; concurrency routes through `autoConcurrency()` in `src/core/sync-concurrency.ts` (PGLite stays serial); `noEmbed` default is `true`. `gbrain jobs supervisor status` at `jobs.ts:803-826` consumes `summarizeCrashes()` from `src/core/minions/handlers/supervisor-audit.ts` for parity with `gbrain doctor`: JSON adds `crashes_by_cause: {runtime_error, oom_or_external_kill, unknown, legacy}` + `clean_exits_24h`; human output gains per-cause + clean-exits lines. Pinned by `test/job-pull-policy.test.ts` and 4 source-grep wiring assertions in `test/doctor.test.ts` requiring `crashes_by_cause` + `clean_exits_24h=` in both `doctor.ts` and `jobs.ts`. `gbrain jobs watch` decouples its two output axes: `--json` picks FORMAT (human default, never gated on isTTY), `--follow` picks LOOP (default `isTTY && !json`). Non-TTY with no flags prints ONE human snapshot then exits (clean for subagent/pipe/cron); `--follow` opts into a continuous stream (human plain per tick, or JSONL with `--json`); a TTY with no flags keeps the live ANSI dashboard. Resolution is the pure `resolveWatchMode(opts, isTTY): {json, follow, useAnsiDashboard}` in `src/commands/jobs-watch.ts`; the dispatch wires `--follow`. Pinned by `test/jobs-watch-mode.test.ts` (format×loop matrix incl. the TTY+`--json`-one-shot case) + `test/e2e/non-tty-output.serial.test.ts` (the `cmd </dev/null` non-empty-stdout contract). registers 11 Minion handlers: `reindex`, `repair-jsonb`, `orphans`, `integrity`, `purge`, `synthesize` (PROTECTED), `patterns` (PROTECTED), `consolidate` (PROTECTED), `extract_facts`, `resolve_symbol_edges`, `recompute_emotional_weight`. Phase wrappers delegate to `runCycle({phases:[name]})` so `src/core/cycle.ts` stays the single source of truth for phase semantics. The standalone `sync` handler passes `noExtract: true` to match `runPhaseSync`'s contract (doctor's remediation plan emitting `[sync, extract]` would otherwise double-extract).- `src/commands/features.ts` — `gbrain features --json --auto-fix`: usage scan + feature adoption salesman.-- `src/core/autopilot-paths.ts` — leaf module for the autopilot artifact paths + launchd label: `autopilotLockPath()`, `autopilotDisabledMarkerPath()`, `autopilotPausedMarkerPath()` (all via `gbrainHomePath()`, so `GBRAIN_HOME` installs converge), and `autopilotLaunchdLabel()` (`GBRAIN_AUTOPILOT_LABEL` test seam, grammar-validated because the label reaches a plist filename and a shell line — reject anything outside `[A-Za-z0-9._-]+` and dot-dot), plus the pause-ownership primitives shared by daemon and migrate: `autopilotDisableStrikesPath()`, `MIGRATE_PAUSE_MARKER_PREFIX`, and `markerHolderAlive(body)` (pid-liveness verdict: ESRCH=dead, EPERM=alive, unparseable=unknown). Deliberately a LEAF with no imports from the command plane: `migrate-engine.ts` needs the marker paths, and importing `commands/autopilot.ts` from there would fold autopilot's whole flag surface into migrate's generated-registry allowlist. Comments in this file must never contain bare dash-dash tokens (the flag-registry generator scans comments and strings).-- `src/commands/autopilot.ts` — `gbrain autopilot --install`: self-maintaining brain daemon (sync+extract+embed). Freshness sync jobs always send an explicit positive-polarity `pull` value derived from the source's parsed `remote_url`, so local-only sources skip pull and PGLite JSON-string configs behave like Postgres objects. Consumes `detectTini()` from `src/core/minions/spawn-helpers.ts`, resolved once at startup. Composes a `ChildWorkerSupervisor` instance for spawn-and-respawn (no inline `crashCount`/`startWorker`/`child.on('exit')`); `--max-rss 2048` and `maxCrashes: 5` preserved. `onMaxCrashesExceeded` routes through autopilot's own `shutdown('max_crashes')` so the autopilot lockfile gets cleaned up. `shutdown()` drains via `childSupervisor.killChild('SIGTERM')` + `awaitChildExit(35_000)`. Pinned by `test/autopilot-fanout-wiring.test.ts` and `test/autopilot-supervisor-wiring.test.ts` (6 static-shape guards: composes ChildWorkerSupervisor not legacy names, `--max-rss 2048` in argv, `maxCrashes: 5` literal, shutdown-via-callback, no workerProc reference). tick body invokes `runNightlyQualityProbe` when `cfg.autopilot.nightly_quality_probe.enabled === true` (default OFF — opt-in to protect API spend). NO scheduler-side rate-limit check — `runNightlyQualityProbe`'s internal `shouldRunNightly` (reading the audit JSONL) is the single source of truth. Probe call wrapped in try/catch that logs via `logError` and does NOT bump `consecutiveErrors` (probe failure is informational, never crashes the loop). Default `max_usd` cap = 5. Pinned by `test/autopilot-nightly-probe-wiring.test.ts`. per-source `extract_atoms` auto-drain. Postgres-only block after the freshness fan-out: gated on `autopilot.auto_drain.enabled` (default true) AND `!packDeclaresPhase(engine,'extract_atoms')` (the silent-backlog condition) AND per-source `countExtractAtomsBacklog > threshold` (default 25) AND a daily cap `floor(max_usd_per_day / ~$0.30)`. Enumerates `loadAllSources`. Submits the PROTECTED `extract-atoms-drain` job (`{allowProtectedSubmit:true}`) with a UTC-day time-sloted idempotency key `autopilot-extract-atoms-drain:<src.id>:<utcDay>` (a static key would block the source after the first job completed). `src/core/minions/protected-names.ts` adds `extract-atoms-drain`; `src/commands/jobs.ts` registers the handler (thin wrapper over `runExtractAtomsDrainForSource`, `LockUnavailableError` → `{deferred:true}`); `src/core/config.ts` adds the `autopilot.auto_drain.*` config keys + the `autopilot.` key prefix. Pinned by `test/extract-atoms-drain-handler.test.ts`, `test/autopilot-auto-drain-wiring.test.ts`. federated-brain co-existence + launchd hygiene. (1) `LOCK_PATH` resolves via `gbrainPath('autopilot.lock')` so it honors `GBRAIN_HOME` (two brains can run autopilot simultaneously without lock-stealing); lock file stores PID, startup checks `kill -0 <pid>` before refusing to start (stale lock from a crashed process no longer blocks). (2) exported `classifyReconnectError(err)` returns `'recoverable' | 'unrecoverable'`; unrecoverable causes `process.exit(0)` so launchd backs off instead of looping `config.database_url undefined`. (3) exported pure `generateLaunchdPlist(wrapperPath, home)` sets `ThrottleInterval=300` so launchd respects the exit-0 backoff. Pinned by `test/autopilot-lock-path.test.ts` + `test/autopilot-reconnect-classifier.test.ts`. Targeted-submit loop instead of blanket `autopilot-cycle` dispatch: `src/commands/autopilot-remediation-policy.ts` owns the routing policy and interval-scoped targeted-remediation keys. Each tick: cheap `engine.getHealth()` + `computeRecommendations()`, then route by shape — healthy/no-plan brains sleep until the 60-minute floor; an overdue full cycle runs regardless of score or a non-empty plan; fresh plans with `<=3` steps and `<5min` stay targeted; large/slow plans or score `<70` use the full cycle. Targeted jobs append `:autopilot:<dispatch-slot>` to the stable recommendation key, preserving doctor/remediate checkpoint semantics while reopening the slot after a completed interval (#4046). The `gbrain-cycle` lock prevents targeted submissions and the full cycle from running concurrently; `maxWaiting: 1` bounds the cross-window backlog when a handler runs longer than one interval. After restart, an all-fresh persisted fan-out advances the process-local full-cycle clock so a remaining targeted plan resumes on the next tick; failed or cooldown-gated stale sources do not. Pinned by `test/autopilot-fanout.test.ts` and `test/autopilot-fanout-wiring.test.ts`. `--status` is heartbeat-truth, not artifact-presence, and is dispatched ENGINE-FREE in cli.ts before connectEngine (`runAutopilotStatus`; a live PGLite daemon's exclusive DB lock or a DB outage must not take down the alarm — `--uninstall` rides the same pre-engine dispatch): pure `classifyAutopilotStatus` maps `{installed, disabledReason, pausedReason, heartbeatAgeSeconds, intervalSeconds}` → `not_installed`/`disabled`/`paused`/`never_run`/`stale`/`fresh` with exit codes 0/1/2 via `autopilotStatusExitCode` (disabled=2; paused/stale/never_run=1). Stale tolerance = 6×interval — the adaptive scheduler sleeps 2×interval on healthy brains, so 3× flapped false alarms; a non-finite or non-positive interval falls back to 1800s at BOTH the dispatch parse and the pure layer (NaN staleAfter would read a dead daemon as fresh), and the daemon's own interval parse carries the same guard (NaN reached setTimeout as 0 = busy-loop). `paused` outranks the heartbeat states because the tick loop refreshes its heartbeat BEFORE honoring the pause marker; the tick loop also SELF-CLEARS a migrate-signed marker whose recorded pid is dead (SIGKILL orphans heal within one poll) and exits-for-relaunch when the file-plane engine identity diverges from boot (`autopilotEngineIdentity`; null/torn reads are skipped, so a concurrent config write cannot restart it). `detectInstalledTarget()` probes plist/systemd-unit/start-script/crontab, where the crontab probe uses pure `crontabIndicatesAutopilotInstall` (a cron'd status-monitor line must not read as an install). The generated wrapper embeds `generateSelfDisableGuard(repo, target)`: repo-dir test (never `.git` — a file in worktrees), THREE consecutive misses required before disabling (strike counter file; one absent external/cloud volume at login must not permanently kill the install), marker write BEFORE the supervisor-specific stop (`launchctl bootout` / `systemctl disable --now`; cron/container just exit), all interpolations single-quoted shell literals. Wrapper + artifacts resolve through `gbrainHomePath()` and a GBRAIN_HOME install bakes the env var into the wrapper (supervisors don't pass the installer's env). `--install` and `--uninstall` clear both markers. launchd label + lock/marker/strike paths resolve through `src/core/autopilot-paths.ts`. Pinned by `test/autopilot-self-disable-and-status.test.ts` + `test/autopilot-launchd-lifecycle.serial.test.ts` (shimmed lifecycle on all platforms; REAL launchd on darwin).+- `src/commands/autopilot.ts` — `gbrain autopilot --install`: self-maintaining brain daemon (sync+extract+embed). Freshness sync jobs always send an explicit positive-polarity `pull` value derived from the source's parsed `remote_url`, so local-only sources skip pull and PGLite JSON-string configs behave like Postgres objects. Consumes `detectTini()` from `src/core/minions/spawn-helpers.ts`, resolved once at startup. Composes a `ChildWorkerSupervisor` instance for spawn-and-respawn (no inline `crashCount`/`startWorker`/`child.on('exit')`); `--max-rss 2048` and `maxCrashes: 5` preserved. `onMaxCrashesExceeded` routes through autopilot's own `shutdown('max_crashes')` so the autopilot lockfile gets cleaned up. `shutdown()` drains via `childSupervisor.killChild('SIGTERM')` + `awaitChildExit(35_000)`. Pinned by `test/autopilot-fanout-wiring.test.ts` and `test/autopilot-supervisor-wiring.test.ts` (6 static-shape guards: composes ChildWorkerSupervisor not legacy names, `--max-rss 2048` in argv, `maxCrashes: 5` literal, shutdown-via-callback, no workerProc reference). tick body invokes `runNightlyQualityProbe` when `cfg.autopilot.nightly_quality_probe.enabled === true` (default OFF — opt-in to protect API spend). NO scheduler-side rate-limit check — `runNightlyQualityProbe`'s internal `shouldRunNightly` (reading the audit JSONL) is the single source of truth. Probe call wrapped in try/catch that logs via `logError` and does NOT bump `consecutiveErrors` (probe failure is informational, never crashes the loop). Default `max_usd` cap = 5. Pinned by `test/autopilot-nightly-probe-wiring.test.ts`. per-source `extract_atoms` auto-drain. Postgres-only block after the freshness fan-out: gated on `autopilot.auto_drain.enabled` (default true) AND `!packDeclaresPhase(engine,'extract_atoms')` (the silent-backlog condition) AND per-source `countExtractAtomsBacklog > threshold` (default 25) AND a daily cap `floor(max_usd_per_day / ~$0.30)`. Enumerates `loadAllSources`. Submits the PROTECTED `extract-atoms-drain` job (`{allowProtectedSubmit:true}`) with a UTC-day time-sloted idempotency key `autopilot-extract-atoms-drain:<src.id>:<utcDay>` (a static key would block the source after the first job completed). `src/core/minions/protected-names.ts` adds `extract-atoms-drain`; `src/commands/jobs.ts` registers the handler (thin wrapper over `runExtractAtomsDrainForSource`, `LockUnavailableError` → `{deferred:true}`); `src/core/config.ts` adds the `autopilot.auto_drain.*` config keys + the `autopilot.` key prefix. Pinned by `test/extract-atoms-drain-handler.test.ts`, `test/autopilot-auto-drain-wiring.test.ts`. federated-brain co-existence + launchd hygiene. (1) `LOCK_PATH` resolves via `gbrainPath('autopilot.lock')` so it honors `GBRAIN_HOME` (two brains can run autopilot simultaneously without lock-stealing); lock file stores PID, startup checks `kill -0 <pid>` before refusing to start (stale lock from a crashed process no longer blocks). (2) exported `classifyReconnectError(err)` returns `'recoverable' | 'unrecoverable'`; unrecoverable causes `process.exit(0)` so launchd backs off instead of looping `config.database_url undefined`. (3) exported pure `generateLaunchdPlist(wrapperPath, home)` sets `ThrottleInterval=300` so launchd respects the exit-0 backoff. Pinned by `test/autopilot-lock-path.test.ts` + `test/autopilot-reconnect-classifier.test.ts`. targeted-submit loop instead of blanket `autopilot-cycle` dispatch. Each tick: cheap `engine.getHealth()` (single SQL count) + `computeRecommendations()`, then route by shape — `score >= 95 AND no plan AND <60min since last full` → sleep; `score >= 95 AND >=60min` → submit `autopilot-cycle` (60-min floor exercises phase-coupling invariants on healthy brains); `plan <= 3 steps AND est <5min` → submit individual handlers; `plan large OR score < 70` → submit full `autopilot-cycle`. The `gbrain-cycle` lock ensures targeted submissions and the full cycle can't run concurrently. `maxWaiting: 1` per submit closes the queue-fan-out vector.- `src/mcp/server.ts` — MCP stdio server (generated from operations). Tool-call handler delegates to `dispatchToolCall` from `src/mcp/dispatch.ts` so stdio + HTTP transports share one validation, context-build, and error-format path. Stdin `'end'` / `'close'` shutdown hooks are skipped when `process.env.MCP_STDIO === '1'` — gateway-piped stdio MCP wrappers (OpenClaw's `bundle-mcp`) pipe the handshake then close their stdin half, which would otherwise kill the server before the first tool call; signal handlers (SIGTERM/SIGINT/SIGHUP) + the parent-process watchdog still cover legitimate disconnects. `src/commands/serve.ts` exposes `ServeOptions.mcpStdio?: boolean` as a test seam so the guard is exercisable without process.env mutation. Pinned by `test/serve-stdio-lifecycle.test.ts`.- `src/mcp/dispatch.ts` — shared tool-call dispatch consumed by both stdio (`server.ts`) and HTTP transports. Exports `dispatchToolCall(engine, name, params, opts)`, `buildOperationContext(engine, params, opts)`, `validateParams(op, params)`. Single source of truth for `(ctx, params)` handler arg order and the 5-field `OperationContext` shape (engine + config + logger + dryRun + remote). Defaults `remote: true` (untrusted); local CLI callers pass `remote: false`. Also exports `summarizeMcpParams(opName, params)` — privacy-preserving redactor for `mcp_request_log` and the admin SSE feed, returns `{redacted, kind, declared_keys, unknown_key_count, approx_bytes}`. Intersects submitted top-level keys against the operation's declared `params` allow-list (declared keys preserved sorted; unknown keys counted but never named, closing the attacker-controlled-key-name leak). Byte counts bucketed up to nearest 1KB so an attacker can't binary-search secret-content sizes by probing. Raw payload visibility is opt-in via `gbrain serve --http --log-full-params` (loud stderr warning). New logging paths route through this helper, not `JSON.stringify(params)`.- `src/mcp/rate-limit.ts` — Bounded-LRU token-bucket limiter. `buildDefaultLimiters()` returns the two-bucket pipeline: pre-auth IP (30/60s, fires BEFORE the DB lookup so brute-force load against `access_tokens` is capped) + post-auth token-id (60/60s). Tracks `lastTouchedMs` separately from `lastRefillMs` so an exhausted key can't be reset by hammering past the TTL. LRU cap bounds memory under attacker-controlled key growth.@@ -495,16 +493,16 @@ Normative docs: `docs/designs/AGENT_BOOTSTRAP_DESIGN.md` (scope) +User-facing contract: `docs/guides/bootstrap.md`. Runbook the paste block fetches:`BOOTSTRAP_FOR_AGENTS.md` (root; carries a version stamp CI pins to VERSION).-- `src/commands/bootstrap.ts` — the `gbrain bootstrap {status,interview,render,repo,hooks,verify,uninstall,attach,cloud-setup-script}` dispatcher. Engine-free everywhere except `verify` (which opens/closes its own engine — safe because verify runs with no live serve, before host registration). `cloud-setup-script` is a pure printer (prints `templates/bootstrap/cloud-setup-script.sh` for the cloud environment's setup step). Mutating subcommands run under the workspace bootstrap lock; render is gated on interview `complete && confirmed` and hard-refuses when the workspace origin is a PUBLIC remote (identity files must never land in a public repo — the same template-door gate `status` enforces; unverifiable visibility warns and proceeds, treating the origin as public); the provider key routes to the 0600 config sink and never touches interview state; every MUTATING subcommand appends a line to `<home>/bootstrap/install.jsonl` (the read-only `status` and `cloud-setup-script` do not log). `hooks` on Claude Code writes the committed carrier in a cloud sandbox (`writeCommittedClaudeHooks`) and the gitignored local file otherwise; `uninstall` tears down the durability wiring and removes this workspace's per-root push/debounce state. Consent answers resolve FAIL-CLOSED: `consentAnswer` treats a hand-edited/unusable interview value (non-string, empty) as declined — loudly, with a re-record note — never falling through to a permissive bank default; `hooks` on Codex prints a corrective note when a persisted `project` MCP_SCOPE answer is found (raw state read, not the resolver — `codex mcp add` has no scope flag, registrations are always user-global) with safe clear instructions. `GBRAIN_BOOTSTRAP_ABORT_AFTER` is the deterministic kill-mid-phase test seam.+- `src/commands/bootstrap.ts` — the `gbrain bootstrap {status,interview,render,repo,hooks,verify,uninstall,attach}` dispatcher. Engine-free everywhere except `verify` (which opens/closes its own engine — safe because verify runs with no live serve, before host registration). Mutating subcommands run under the workspace bootstrap lock; render is gated on interview `complete && confirmed` and hard-refuses when the workspace origin is a PUBLIC remote (identity files must never land in a public repo — the same template-door gate `status` enforces; unverifiable visibility warns and proceeds, treating the origin as public); the provider key routes to the 0600 config sink and never touches interview state; every subcommand appends a line to `<home>/bootstrap/install.jsonl`. `GBRAIN_BOOTSTRAP_ABORT_AFTER` is the deterministic kill-mid-phase test seam.- `src/core/bootstrap/format.ts` — `agent.json` manifest (format_version 1, provisional; `initialized` sentinel distinguishes a template clone from a bootstrapped workspace) + the machine-local install receipt (`<home>/bootstrap/receipt.json`) that proves THIS machine ran bootstrap; uninstall is keyed to the receipt, never the repo manifest. Atomic writes; `readManifest` never throws (typed states incl. conflict markers).- `src/core/bootstrap/assets.ts` — every template + the question bank embedded via Bun `with { type: 'file' }` imports (the chunkers/code.ts pattern) so the compiled binary renders with no repo checkout; `DERIVED_TOKENS` (GITHUB_REPO_URL, CORPUS_RETENTION_DAYS) is the non-bank half of the template token set the CI bijection guard checks.- `templates/bootstrap/` — the ten `{{TOKEN}}` identity templates (AGENTS/CLAUDE/SOUL/USER/MEMORY/HEARTBEAT/ACCESS_POLICY/GITHUB/memory-README/gitignore), `questions.json` (12 asked / 6 required; consent keys; `persist:false` sink keys), and `template-repo/` — the VENDORED deterministic render the release job diffs against before publishing the public template repo. Generic placeholder content only (privacy iron rule; CI-asserted).- `src/core/bootstrap/interview.ts` — interview state at `<ws>/state/interview.json` (committed; multi-device re-render source). Read-back confirm hash: `--confirm` must present the hash of the exact answer set shown to the human, and ANY later answer change clears the confirmation — the single-batch self-confirm attack is structurally impossible. Set-time enforcement: length caps, reject-lists, allowed-lists, control-char strip, `{{` escaping. Conflict-markered files return agent-readable errors, not stack traces.- `src/core/bootstrap/render.ts` — token substitution with interview values treated as data (line-leading `#`/`<!--`/fence escaping), hard-fail on unresolved tokens, never-clobber + timestamped backups on `--force`, blank-line collapse, byte floors scaled to answered count. `--minimal` is the deterministic placeholder mode the template-repo generator uses (byte-identical across runs; leaves required tokens as literal fill-me markers; writes `initialized:false`). `--only` never writes agent.json.- `src/core/bootstrap/lock.ts` — the bootstrap-run mutex (atomic mkdir + pid liveness + age guard + ownership token; steal requires dead pid AND stale age) and the family's shared typed `BootstrapError` (GH_MISSING/GH_AUTH carry exit 2 = human action needed).-- `src/core/bootstrap/repo.ts` / `attach.ts` / `uninstall.ts` — private-repo lifecycle. `createPrivateRepo`: gh gates, slugified name probe, `gh repo create --private --source` (the push happens separately via `ensureRemoteHasWorkspace`), privacy verified via REST `gh api repos/{o}/{r} --jq .private` (rate-limit/5xx is VERIFY_UNAVAILABLE, distinct from not-private; a proxy-classed 403 → a cloud-specific message) before any push, idempotency keyed off the remote URL. It shares repo-visibility.ts's URL parser + `isProxyBlocked403` classifier but runs REST directly (not the full ladder — creation needs the authed-owner REST answer). A pre-existing origin is adopted (disposition 'adopted') when the authed gh user owns it, there's no recorded `repo_url`, and it is SAFE — empty or already carrying our history (`assertAdoptableOrigin`; a foreign-content repo is refused `ORIGIN_NOT_EMPTY`, never a silent no-op); this is the create-repo-first path. Org-owned origins and anything else are refused and pointed at attach. Inside a `cloud-sandbox` (execution-env), `createPrivateRepo` fails fast with `CLOUD_SANDBOX_REPO` before any `gh repo create` — a mid-session repo is never proxy-attached, so creation there is a dead end; the message routes to create-elsewhere + `bootstrap attach`. Repo-local git identity is set in both create and adopt paths before commit; `repo_url` is recorded only after a successful push. `attachWorkspace` (machine two, and the ONLY install path in a cloud sandbox since `repo` is refused there): requires an `initialized` manifest, writes this machine's receipt — recording `repo_url` from the adopted github origin so the no-daemon push gate (`repoPhaseComplete`) recognizes the repo phase as done and the per-turn/session-end pushes actually fire (privacy is still enforced at push time by the ladder) — and returns structured wiring steps. `uninstallWorkspace`: receipt-keyed, refuses under a live serve (read-only lock probe — never opens the engine), removes exactly receipt-recorded paths + marker-keyed host entries, keeps the brain unless `--delete-brain` AND bootstrap created it; never wholesale-deletes the gbrain home. All gh/git through an injectable ExecRunner seam.-- `src/core/bootstrap/hooks.ts` + `host-specs.ts` — host wiring. `host-specs.ts` is the ONE module owning host-format assumptions (dated spec targets with verifiedAt + doc references: claude-code hooks/settings shapes incl. the 10,000-char hook-output cap; codex mcp-add argv; no-TOML-writer-in-v1 decision recorded). `writeClaudeHooks` does a structural JSON merge into `.claude/settings.local.json` keyed by a `_gbrain` marker — foreign hooks and permissions survive, re-runs dedupe, broken JSON is backed up loudly. `writeCommittedClaudeHooks` [D12] is the CLOUD carrier: a fresh cloud clone never sees the gitignored local file and hook config snapshots at session start, so cloud installs write the repo-COMMITTED `.claude/settings.json` with a PATH-resolved fail-open command (`command -v gbrain … || exit 0`; no absolute paths — the file travels between machines). The writers enforce a dedupe invariant — an event carried by the committed file is skipped by the local writer and vice-versa, matched on the EXACT portable-command shape (a bare marker + `gbrain hook` substring is spoofable), so one event never fires from both; `removeClaudeHooks` cleans both carriers; GBRAIN_HOME is refused in the committed carrier (machine-specific). `registerClaudeMcp`/`registerCodexMcp` build argv only (Claude Code takes `--scope`, project default; Codex has no scope flag — `codex mcp add` is always user-global; `-e`/`--env GBRAIN_SOURCE` so MCP writes land in the workspace source, and `serve --surface full` pinned so a pre-existing `mcp_surface: verbs` config row can't silently narrow the bootstrap op surface).-- `src/commands/hook.ts` — engine-free `gbrain hook {session-start,user-prompt,stop,session-end,compact}` (zero engine modules in the import graph; a hook must NEVER contend for the PGLite writer lock). user-prompt: stdin hook JSON → transcript-path confinement → last-4-turns window + cross-turn dedupe (the transcript's `hook_additional_context` attachments — the blocks WE previously injected — ride `priorContextText`, deduplicated and capped at `PRIOR_CONTEXT_MAX_BYTES` (32KB, so the advisory payload can never blow the IPC message cap; one oversized block is skipped without evicting smaller ones), so a page is volunteered once per session, not once per mention; structured extraction only, never raw-turn substring matching) → IPC turn_context (with a feedback-loop `channel`, `--harness <claude-code|codex>`, default claude-code) → `hookSpecificOutput.additionalContext` under an 800ms self-deadline; every path fails open (exit 0, empty stdout) with a typed reason in the heartbeat. Listed in cli.ts's `STARTUP_HOOK_SKIP_COMMANDS` (per-prompt invocations must never spawn a detached check-update child; membership is pinned by a source grep — the runtime path no-ops under NODE_ENV=test). session-start: file-plane digest (allowlisted MEMORY.md sections, push staleness, prior failures) + crashed-session recovery push gated on an initialized manifest. session-end: confined full-transcript parse → redacted corpus write (session-id filename dedup, retention prune) → parser-drift detection (`bytes>0 && turns==0` is loud) → best-effort workspace push. session-start recovery + session-end pushes run in a DETACHED child so the hook returns immediately (a synchronous inline push previously blocked harness startup on a dirty tree); the corpus write is atomic and clears the stale ingested/in-progress sidecars so a resumed session re-ingests its appended transcript. stop: also runs a per-turn debounced detached push [D3] (`stopPushIfDue` — per-workspace-root debounce state, 5-min default local + ephemeral-container / every turn in a cloud-sandbox, a failing status bypasses to a 60s retry floor, same repo-phase security gate as session-end), closing the `/exit` gap (SessionEnd never fires on `/exit`) and the VM-reclaim gap; `GBRAIN_STOP_PUSH=0` disables it, `GBRAIN_STOP_PUSH_DEBOUNCE_MIN` / config `hooks.stop_push_debounce_min` tune it. user-prompt also surfaces a failing background push [D5/D19] as a ≤300-char banner on BOTH `additionalContext` (model) and `systemMessage` (human), announced once per failure and re-fired at most every 30 min, with the reason sanitized before it reaches any model-visible surface. Heartbeat JSONL is counters/reasons only by construction; `readHeartbeatTail` feeds doctor. `GBRAIN_HOOKS=0` kills all events.+- `src/core/bootstrap/repo.ts` / `attach.ts` / `uninstall.ts` — private-repo lifecycle. `createPrivateRepo`: gh gates, slugified name probe, `gh repo create --private --source --push`, privacy verified via `gh api .private` (rate-limit/5xx is VERIFY_UNAVAILABLE, distinct from not-private) before any push, idempotency keyed off the remote URL. A pre-existing origin is adopted (disposition 'adopted') when the authed gh user owns it, there's no recorded `repo_url`, and it is SAFE — empty or already carrying our history (`assertAdoptableOrigin`; a foreign-content repo is refused `ORIGIN_NOT_EMPTY`, never a silent no-op); this is the create-repo-first path. Org-owned origins and anything else are refused and pointed at attach. Repo-local git identity is set in both create and adopt paths before commit; `repo_url` is recorded only after a successful push. `attachWorkspace` (machine two): requires an `initialized` manifest, writes this machine's receipt, returns structured wiring steps. `uninstallWorkspace`: receipt-keyed, refuses under a live serve (read-only lock probe — never opens the engine), removes exactly receipt-recorded paths + marker-keyed host entries, keeps the brain unless `--delete-brain` AND bootstrap created it; never wholesale-deletes the gbrain home. All gh/git through an injectable ExecRunner seam.+- `src/core/bootstrap/hooks.ts` + `host-specs.ts` — host wiring. `host-specs.ts` is the ONE module owning host-format assumptions (dated spec targets with verifiedAt + doc references: claude-code hooks/settings shapes incl. the 10,000-char hook-output cap; codex mcp-add argv; no-TOML-writer-in-v1 decision recorded). `writeClaudeHooks` does a structural JSON merge into `.claude/settings.local.json` keyed by a `_gbrain` marker — foreign hooks and permissions survive, re-runs dedupe, broken JSON is backed up loudly; `registerClaudeMcp`/`registerCodexMcp` build argv only (project scope default, `-e GBRAIN_SOURCE` so MCP writes land in the workspace source, and `serve --surface full` pinned so a pre-existing `mcp_surface: verbs` config row can't silently narrow the bootstrap op surface).+- `src/commands/hook.ts` — engine-free `gbrain hook {session-start,user-prompt,stop,session-end}` (zero engine modules in the import graph; a hook must NEVER contend for the PGLite writer lock). user-prompt: stdin hook JSON → transcript-path confinement → last-4-turns window + cross-turn dedupe (the transcript's `hook_additional_context` attachments — the blocks WE previously injected — ride `priorContextText`, deduplicated and capped at `PRIOR_CONTEXT_MAX_BYTES` (32KB, so the advisory payload can never blow the IPC message cap; one oversized block is skipped without evicting smaller ones), so a page is volunteered once per session, not once per mention; structured extraction only, never raw-turn substring matching) → IPC turn_context (with a feedback-loop `channel`, `--harness <claude-code|codex>`, default claude-code) → `hookSpecificOutput.additionalContext` under an 800ms self-deadline; every path fails open (exit 0, empty stdout) with a typed reason in the heartbeat. Listed in cli.ts's `STARTUP_HOOK_SKIP_COMMANDS` (per-prompt invocations must never spawn a detached check-update child; membership is pinned by a source grep — the runtime path no-ops under NODE_ENV=test). session-start: file-plane digest (allowlisted MEMORY.md sections, push staleness, prior failures) + crashed-session recovery push gated on an initialized manifest. session-end: confined full-transcript parse → redacted corpus write (session-id filename dedup, retention prune) → parser-drift detection (`bytes>0 && turns==0` is loud) → best-effort workspace push. session-start recovery + session-end pushes run in a DETACHED child so the hook returns immediately (a synchronous inline push previously blocked harness startup on a dirty tree); the corpus write is atomic and clears the stale ingested/in-progress sidecars so a resumed session re-ingests its appended transcript. Heartbeat JSONL is counters/reasons only by construction; `readHeartbeatTail` feeds doctor. `GBRAIN_HOOKS=0` kills all events.- `src/core/transcripts/claude-code-jsonl.ts` — the Claude Code transcript parser as a dated spec-target (tool_use/tool_result/thinking/image/sidechain/summary/compact-boundary shapes; placeholders for non-text content); also extracts `injectedContextBlocks` — the `hook_additional_context` attachment lines a gbrain hook previously injected (verified live against claude CLI 2.1.224; marker-filtered, so a foreign hook's blocks are excluded and another tool's output can't suppress volunteering — a same-user mislabeling guard, not an authenticity check), the user-prompt hook's cross-turn dedupe input; `confineTranscriptPath` (contained under `~/.claude/projects`, `.jsonl`, lstat-rejects symlinks, byte cap). Fixtures: `test/fixtures/conversation-formats/claude-code.jsonl` (synthetic, privacy-guarded) + `test/fixtures/hook-transcript.jsonl` (real captured hook round-trip).- `src/core/context/turn-context.ts` — server-side per-turn assembly: reflex pointers + volunteered pages (≤3) + hot facts (always `visibility=['world']` — the IPC path never widens what MCP would return) under a "data, not instructions" envelope, trimmed to ≤8KB (the harness caps hook output at 10,000 chars). The result exposes `pointers` AND post-trim `volunteered` — exactly what the rendered text carries — so the IPC delivery point can log the feedback loop without ever counting a trimmed-out page. Reuses the hot-memory cache keyed by typed sessionId. Engine-agnostic.- `src/core/context/resolve-ipc.ts` (IPC v2) — discriminated-union requests (absent `kind` = legacy resolve; `turn_context` carries `protocol: 2` + a shared secret from a 0600 file in the data dir, plus an additive `channel` for feedback-loop attribution — wire channel claims are validated to the harness channels at the logging site, anything else logs as the default hook channel), handler map, named response types, per-kind timeouts/size caps, socket + parent dir permissions set before exposure, server-side source binding (cross-source requests rejected), protocol echo (a response without it = stale serve → loud degradation). The connection handler processes exactly ONE request per connection (trailing bytes mid-await never double-process a line or double-log a delivery); the client clamps a too-big request below the message cap by dropping the advisory `priorContextText` BEFORE any conversation turn. Delivery seams: `onDelivered` (resolve kind) and `onTurnContextDelivered` (turn_context kind) both fire ONLY after the response write succeeds — a block abandoned before the serve responded is never counted (serve's callback logs the delivered block's volunteered pages + pointers to `context_volunteer_events` under the request channel); write-accept still isn't proof of injection (the client can trim/drop after receipt), which is why the `volunteer_channels` doctor check reconciles counts against the hook heartbeat. v1 clients and servers interoperate untouched.@@ -512,10 +510,8 @@ User-facing contract: `docs/guides/bootstrap.md`. Runbook the paste block fetche- `src/core/sweep.ts` + `src/commands/sweep.ts` — the serve-resident maintenance sweep (the lock owner closes the persistence loop): facts-fence reconciliation (zero-LLM, reuses the cycle extractor with a slug subset), deterministic link/timeline extraction over recent workspace pages (the same cores as `gbrain extract` — remote put_page deliberately skips these, the sweep is where the graph compounds), and spend-gated corpus ingest (skipped keyless; sidecar-marked exactly-once). Bounded, fail-soft, never throws; armed at serve startup (3s, best-effort) and on 10-min idle ticks through the injectable timer seam, everything unref'd; `GBRAIN_SWEEP=0` kills it. `gbrain sweep --once` is the trusted CLI seam `bootstrap verify` uses (CLI-only, never over MCP).- `src/core/capability.ts` — config-plane keyless/keyed detection + the honest capability report (`keyless mode: keyword search, agent-authored memory; add ONE key to unlock…`) rendered by verify and the runbook.- `src/core/secret-scan.ts` — pattern scanner for USER workspaces (own minimal allowlist + `<ws>/.gbrain-scan-allow` per-finding overrides — deliberately NOT the repo's `.gitleaks.toml`, which is a public-repo CI fixture policy); redacted previews only; `redactFindings` is the corpus-write mode.-- `src/core/workspace-push.ts` — `gbrain sources push`: deny-glob backstop (tracked `*.pglite`/`.env*` refused regardless of .gitignore state) → stage FIRST → secret-scan the STAGED index blobs via `git cat-file` (closes the scan-then-stage TOCTOU — scanned bytes == committed bytes) → commit FIRST → divergence-safe pull → push, under one cross-platform lock (mkdir-atomic; flock is not a dependency — macOS). The pre-push secret gate FAILS CLOSED: an unreadable, oversized (> `PUSH_MAX_SCAN_BYTES`), or otherwise unscannable staged blob returns `blocked_unscannable` (nothing committed) instead of sailing through — only a confirmed staged deletion is skipped, and binary/NUL-sniffed blobs are scanned anyway. Statuses map to exit codes in `src/commands/sources.ts`: `pushed`/`skipped_in_flight` → 0; `blocked_secrets`/`blocked_tracked_deny`/`blocked_unscannable`/`refused_visibility` → 5; `pull_conflict`/`push_failed`/other → 1. The privacy gate runs the shared `repo-visibility.ts` ladder (REST → git protocol) and refuses proven-public AND unverifiable remotes (never fail-open). Three escape hatches for self-hosted git you trust, each warns and downgrades ONLY `unverifiable` (never a proven-public push): CLI `--allow-unverified-remote` > env `GBRAIN_ALLOW_UNVERIFIED_REMOTE=1` > file-plane config `push.allow_unverified_remote` (the only channel a detached hook child can read). Pushes even on clean trees; writes per-workspace status `<home>/bootstrap/push-status-<roothash>.json` (a shared `readPushStatuses`/`summarizePushStatuses` reader; one workspace's success can't mask another's failure, and records for a since-deleted root are filtered). Parent-repo-aware (a source may be a subdirectory of the workspace repo).+- `src/core/workspace-push.ts` — `gbrain sources push`: deny-glob backstop (tracked `*.pglite`/`.env*` refused regardless of .gitignore state) → stage FIRST → secret-scan the STAGED index blobs via `git cat-file` (closes the scan-then-stage TOCTOU — scanned bytes == committed bytes) → commit FIRST → divergence-safe pull → push, under one cross-platform lock (mkdir-atomic; flock is not a dependency — macOS). The pre-push secret gate FAILS CLOSED: an unreadable, oversized (> `PUSH_MAX_SCAN_BYTES`), or otherwise unscannable staged blob returns `blocked_unscannable` (nothing committed) instead of sailing through — only a confirmed staged deletion is skipped, and binary/NUL-sniffed blobs are scanned anyway. Statuses map to exit codes in `src/commands/sources.ts`: `pushed`/`skipped_in_flight` → 0; `blocked_secrets`/`blocked_tracked_deny`/`blocked_unscannable`/`refused_visibility` → 5; `pull_conflict`/`push_failed`/other → 1. Refuses public AND unverifiable remotes (never fail-open); pushes even on clean trees; writes `<home>/bootstrap/push-status.json`. Parent-repo-aware (a source may be a subdirectory of the workspace repo).- `src/core/gbrain-home.ts` — the single GBRAIN_HOME resolution choke point (delegates to config's parent-dir semantics; 0700 on create) — durability, push, hooks, and bootstrap all route through it so home semantics cannot drift.-- `src/core/execution-env.ts` — the third bootstrap axis (harness × engine × ENVIRONMENT). `detectExecutionEnvironment(signals?)` returns `local | cloud-sandbox | ephemeral-container` from injected signals: `CLAUDE_CODE_REMOTE=true` (official, never local) or a `cse_`-prefixed remote-session id or a credential-injecting proxy (`GH_TOKEN`/`GITHUB_TOKEN === 'proxy-injected'`, or an anthropic-egress `https_proxy`) → cloud-sandbox; RENDER/RAILWAY/FLY / `/.dockerenv` → ephemeral-container. `isCredentialInjectingProxy(env?)` is the exported proxy check (load-bearing for the repo-visibility ambiguity rule). `binaryOnPath(name)` moved here (live-PATH `Bun.which`) and is re-exported by `bootstrap/status.ts`; autopilot's `detectInstallTarget()` routes its ephemeral branch through the shared detector. Pure + signal-injected. Tests: `test/execution-env.test.ts`.-- `src/core/repo-visibility.ts` — ONE repo-privacy verdict shared by every consumer, replacing three drifted probes. The FULL ladder runs in `workspace-push.ts` (the push gate) and `bootstrap/verify.ts` (`checkRepoPrivacy`); `bootstrap/repo.ts` and `bootstrap/status.ts` reuse its URL parser + 403 classifier but call REST directly (both are sync-by-contract: repo creation needs the authed-owner answer, status runs inside the phase-detect chain). `verifyRepoVisibility({originUrl, repoDir, runner, fetchImpl, env})` runs a fail-closed ladder: REST (`gh api repos/{o}/{r} --jq .private` — NEVER `gh repo view`/GraphQL, which cloud proxies pin) → authed `git ls-remote` (SSRF flags via `durableSsrfFlags` + `--end-of-options`) → an anonymous smart-HTTP probe (`redirect:'manual'`, userinfo stripped). A 200 counts PUBLIC only with git-advertisement proof (content-type or pkt-line prefix); a 401/404 counts PRIVATE only with origin attribution (github.com needs `x-github-request-id` — a bare `WWW-Authenticate` is RFC-mandated on every 401 and a middlebox 401s identically, so it is NOT proof; non-github origins have no trustable signal → `unverifiable`). Everything else → `unverifiable`. `classifyGh403`/`isProxyBlocked403` distinguish a real GitHub 403 (JSON with `message`+`documentation_url`) from a sandbox-proxy 403. `parseGithubOwnerRepo` is the canonical URL parser (bootstrap/repo + hook re-adapt it). Private verdicts cache 1h (private-only, per-origin, userinfo-stripped key) at `<home>/bootstrap/visibility-cache.json`. Engine-free; every IO seam injected. Tests: `test/repo-visibility.test.ts`.- `src/core/bootstrap/verify.ts` + `status.ts` — verify is the definition of done: fail-soft check suite over the REAL write path (put_page op → write-through file under `brain/` → in-process sweep → graph floor via link tables → recall), the keyless magic-moment check (`## Facts` fence → zero-LLM reconciliation → world-visibility read-back), source_id collision resolution (as the one bootstrap subcommand holding an engine: a manifest `source_id` already registered to a DIFFERENT checkout → derives a stable `workspace-<8char-path-hash>`, persists it to agent.json, names the re-register steps — every consumer reads `manifest.source_id`), token sweep, byte floors, secret scan, deny globs, repo privacy, hooks smoke (in-process IPC), capability report, first-run tour; snapshots kept last-5 under `<home>/bootstrap/`. status owns the ordered PHASES list (the runbook defers to it), artifact-first detection, install.jsonl, the runbook version-stamp skew check, and the support blob doctor/agents relay verbatim.- `src/core/bootstrap/template-repo.ts` + `scripts/generate-template-repo.ts` — deterministic public-template generation (render `--minimal` + placeholder manifest + stamped README); published only by the release workflow after diffing against the vendored tree.-- `scripts/check-bootstrap-tag.sh` / `scripts/check-bootstrap-templates.sh` — CI guards: sanctioned distribution ref only (`latest-stable`; the release job advances it after assets publish) + runbook stamp == VERSION; template↔question-bank token bijection + placeholder-only assertion + offline generator↔vendored byte-diff + runbook-phase↔status.ts consistency + harness-scoping counter-signal pins (the MCP-scope consent is Claude Code only: the runbook must carry the Codex "Do NOT offer an MCP scope choice" bullet and the "Claude Code only" consent scoping, and the bank's MCP_SCOPE question must start with `(Claude Code only` with `phase: interview` — tripwires against deleting the load-bearing prose, not placement proofs). Both skip gracefully when their subjects are absent.+- `scripts/check-bootstrap-tag.sh` / `scripts/check-bootstrap-templates.sh` — CI guards: sanctioned distribution ref only (`latest-stable`; the release job advances it after assets publish) + runbook stamp == VERSION; template↔question-bank token bijection + placeholder-only assertion + offline generator↔vendored byte-diff + runbook-phase↔status.ts consistency. Both skip gracefully when their subjects are absent.diff --git a/src/commands/embed.ts b/src/commands/embed.tsindex d2de0235d5..2c80f63252 100644--- a/src/commands/embed.ts+++ b/src/commands/embed.ts@@ -198,6 +198,14 @@ export interface EmbedResult {failure_samples: string[];/** True if this run was a dry-run. */dryRun: boolean;+ /**+ * Chunkless-page safety net (`--stale` only): pages with non-empty+ * content but zero `content_chunks` rows that this run chunked (or, in+ * dryRun, would chunk) so their new NULL-embedding chunks fold into the+ * SAME pass. 0 on a healthy brain. Additive field — see+ * `ChunklessPageRow` for the detection rationale.+ */+ chunkless_pages_healed: number;/*** E1 (paced-backfill): end-of-run pacing telemetry. Present ONLY when pacing* was active (enabled bundle). The number the operator could not get from an@@ -317,6 +325,7 @@ export async function runEmbedCore(engine: BrainEngine, opts: EmbedOpts): Promisfailures: 0,failure_samples: [],dryRun: !!opts.dryRun,+ chunkless_pages_healed: 0,};if (opts.slugs && opts.slugs.length > 0) {@@ -529,6 +538,7 @@ export async function runEmbed(engine: BrainEngine, args: string[]): Promise<Embreturn {embedded: 0, skipped: 0, would_embed: 0, total_chunks: 0,pages_processed: 0, failures: 0, failure_samples: [], dryRun: false,+ chunkless_pages_healed: 0,};}@@ -988,6 +998,201 @@ async function embedAll(}}+/**+ * Chunkless-page safety net for `embed --stale`. `listStaleChunks` /+ * `countStaleChunks` only ever look at `content_chunks` rows where+ * `embedding IS NULL` — a page written directly via `putPage` that never+ * went through chunking (e.g. an enrichment-generated entity stub) has NO+ * chunk row at all, so it is invisible to that scan forever, even after+ * unlimited `embed --stale` runs.+ *+ * This sweep finds pages with non-empty content (`compiled_truth` and/or+ * `timeline` — both are chunked independently, mirroring `embedPage`'s+ * chunkless branch) and zero `content_chunks` rows+ * (`engine.listChunklessPagesWithContent`, which already excludes+ * quarantined + embed_skip pages — both intentionally chunkless). The new+ * chunk rows land with `embedding = NULL`, so they flow into the SAME+ * `embed --stale` pass via the existing cursor below — no separate embed+ * step needed here.+ *+ * dryRun chunks locally (a pure, in-memory operation) to report an+ * accurate count without writing anything, matching embedPage's dry-run+ * contract (including `pages_processed`, which embedPage's own dry-run+ * branch increments for exactly this "examined, didn't write" case).+ *+ * Race note (review catch, three rounds — ACCEPTED RESIDUAL RISK, not+ * fully closed): between listing a page and writing its chunks, a+ * concurrent writer (sync, another `put_page`) could change or chunk the+ * SAME page. Two mitigations, both bounded — full atomicity (a+ * transaction/version-guarded conditional write inside `upsertChunks`)+ * would need a new engine primitive shared by every `upsertChunks` caller,+ * which is out of scope for a chunkless-page safety net:+ * 1. Immediately before writing, re-fetch the LIVE page via `getPage`+ * and build `inputs` from ITS CURRENT content, not the batch-list+ * snapshot — closes the "content changed but still chunkless"+ * sub-case, not just the "chunks appeared" one.+ * 2. Re-check `getChunks` right after that same fetch — skip (don't+ * overwrite) if chunks now exist AT THE TIME OF THE CHECK.+ * What this does NOT close: a writer that inserts chunks in the gap+ * BETWEEN step 2's check and the `upsertChunks` call immediately below it+ * (no intervening `await` other than that one call, but `upsertChunks`+ * itself is not conditioned on the check — this is still check-then-write,+ * not compare-and-swap) can still have its chunks overwritten — HONESTLY:+ * `upsertChunks` treats its input as the full desired chunk set for that+ * page and deletes any existing chunk_index absent from it, so a+ * concurrent writer's chunks landing in that exact gap CAN be replaced+ * with this sweep's stale-content chunks (embedding NULL). This is the+ * SAME check-then-write window `embedPage`'s existing single-page+ * chunkless branch already ships with today (that branch doesn't even+ * have step 2's re-check) — no new race CLASS is introduced, and the+ * window here is a single sequential getPage+getChunks+upsertChunks+ * instead of spanning a whole batch. The blast radius is bounded: the+ * page is NOT deleted or corrupted, just re-chunked from a stale+ * snapshot, and the NEXT write to that page (sync, another edit) that+ * actually chunks it restores correct content — this sweep's own+ * predicate is idempotent and doesn't compound the drift. Closing this+ * fully (true atomicity) is tracked as a follow-up, not blocking this+ * safety net.+ *+ * Per-page failure isolation (review catch): one malformed/oversized+ * chunkless page must not abort the sweep and, with it, the entire+ * `--stale` run before the normal NULL-embedding pass even starts — that+ * would make the safety net WORSE than the bug it fixes. Each page's+ * work is try/caught; a failure is recorded (`EmbedResult.failures` ++ * `failure_samples`, same convention as every other embed failure path)+ * and the sweep moves on.+ *+ * Bounded, keyset-paginated (like listStalePagesForExtraction) — a safety+ * net for a rare drift case, not the primary bulk-chunking path. `BATCH_SIZE`+ * is deliberately small (unlike the 2000-chunk-row default elsewhere in+ * this file): each row here carries a FULL page body (`compiled_truth` ++ * `timeline`), so a large batch of large pages is a real memory/latency+ * concern the metadata-only `listStaleChunks` rows never had (review+ * catch). It still respects the caller's pacer (no-op when pacing is off)+ * and a soft wall-clock cap (`GBRAIN_EMBED_TIME_BUDGET_MS`) so a+ * pathologically large damaged brain can't run this sweep unbounded — it+ * heals what it can and reports the rest for the next `embed --stale` run+ * (the SQL predicate is idempotent; nothing here requires finishing in one+ * pass). `startedAt` is shared with the caller's overall run clock (review+ * catch) — healing and the main stale loop draw from ONE combined budget+ * window, not two independent 30-minute ones. `catchUp` mirrors the main+ * loop's own `--catch-up` handling: removes the cap entirely (the keyset+ * cursor still terminates on its own; `signal` remains the abort path).+ */+async function healChunklessPages(+ engine: BrainEngine,+ sourceId: string | undefined,+ dryRun: boolean,+ result: EmbedResult,+ quiet: boolean | undefined,+ signal: AbortSignal | undefined,+ pacer: DbPacer | undefined,+ startedAt: number,+ catchUp: boolean,+): Promise<void> {+ const BATCH_SIZE = 50;+ const BUDGET_MS: number | null = catchUp+ ? null+ : parseInt(process.env.GBRAIN_EMBED_TIME_BUDGET_MS || `${30 * 60 * 1000}`, 10);+ const activePacer = pacer ?? createNoopPacer();+ let afterPageId: number | undefined;+ let pagesHealed = 0;+ let budgetExceeded = false;++ const buildInputs = (compiledTruth: string, timeline: string): ChunkInput[] => {+ const inputs: ChunkInput[] = [];+ if (compiledTruth.trim()) {+ for (const c of chunkText(compiledTruth)) {+ inputs.push({ chunk_index: inputs.length, chunk_text: c.text, chunk_source: 'compiled_truth' });+ }+ }+ if (timeline.trim()) {+ for (const c of chunkText(timeline)) {+ inputs.push({ chunk_index: inputs.length, chunk_text: c.text, chunk_source: 'timeline' });+ }+ }+ return inputs;+ };+ // BUDGET_MS === null means catch-up: no wall-clock cap on this sweep,+ // mirroring the main stale loop's own --catch-up handling below.+ const overBudget = (): boolean => BUDGET_MS != null && Date.now() - startedAt > BUDGET_MS;++ // eslint-disable-next-line no-constant-condition+ while (true) {+ if (isAborted(signal)) break;+ if (overBudget()) { budgetExceeded = true; break; }+ const batch = await observed(activePacer, () => engine.listChunklessPagesWithContent({+ batchSize: BATCH_SIZE,+ ...(afterPageId != null && { afterPageId }),+ ...(sourceId && { sourceId }),+ }));+ if (batch.length === 0) break;+ afterPageId = batch[batch.length - 1].id;++ for (const page of batch) {+ if (isAborted(signal)) break;+ if (overBudget()) { budgetExceeded = true; break; }++ try {+ if (dryRun) {+ // dryRun never writes, so there's no live-refetch race to close —+ // chunk the listed snapshot directly (matches embedPage's own+ // dry-run, which chunks whatever getPage returned at call time).+ const inputs = buildInputs(page.compiled_truth, page.timeline);+ // Whitespace-only content (SQL prefilter is `<> ''`, not+ // trim-aware) chunks to nothing — matches embedPage's contract.+ if (inputs.length === 0) continue;+ result.total_chunks += inputs.length;+ result.would_embed += inputs.length;+ result.pages_processed++;+ pagesHealed++;+ continue;+ }++ // Re-fetch the LIVE page + re-check chunks immediately before+ // writing (see race note above): chunk CURRENT content, and skip+ // rather than clobber if a concurrent writer already chunked this+ // page since we listed it.+ const [livePage, stillChunkless] = await Promise.all([+ observed(activePacer, () => engine.getPage(page.slug, { sourceId: page.source_id })),+ observed(activePacer, () => engine.getChunks(page.slug, { sourceId: page.source_id })),+ ]);+ if (!livePage || stillChunkless.length > 0) continue;+ const inputs = buildInputs(livePage.compiled_truth, livePage.timeline);+ if (inputs.length === 0) continue;++ await observed(activePacer, () =>+ engine.upsertChunks(page.slug, inputs, { sourceId: page.source_id }),+ );+ pagesHealed++;+ try {+ await activePacer.pace(signal);+ } catch (e) {+ if (!(e instanceof AbortError)) throw e;+ }+ } catch (e) {+ if (isAborted(signal)) break;+ recordFailure(result, 1, page.slug, e);+ serr(`\n [embed] chunkless-page heal failed for ${page.slug}: ${e instanceof Error ? e.message : e}`);+ }+ }++ if (budgetExceeded || batch.length < BATCH_SIZE) break;+ }++ result.chunkless_pages_healed = pagesHealed;+ if (pagesHealed > 0 && !quiet) {+ if (dryRun) {+ serr(`[embed] [dry-run] would chunk ${pagesHealed} page(s) with non-empty content but zero content_chunks rows`);+ } else {+ serr(`[embed] chunked ${pagesHealed} page(s) that had non-empty content but zero content_chunks rows (embedding them in this pass)`);+ }+ }+ if (budgetExceeded && !quiet) {+ serr(`[embed] chunkless-page sweep hit its time budget (${BUDGET_MS}ms) with more pages left; re-run embed --stale to continue healing them`);+ }+}+/*** SQL-side stale path: replaces the listPages + per-page getChunks* walk with a count + slug-grouped SELECT. Preserves the existing@@ -1028,11 +1233,38 @@ async function embedAllStale(signature?: string,externalSignal?: AbortSignal,) {+ // Shared wall-clock anchor (review catch): the healing sweep below and the+ // main stale loop's own budget timer (further down) both measure against+ // this SAME start time, so a run's total wall-clock spend stays capped at+ // ONE `GBRAIN_EMBED_TIME_BUDGET_MS` window instead of summing two+ // independent 30-minute budgets.+ const overallStartedAt = Date.now();+// D7: thread sourceId so source-scoped runs only count + visit// that source's NULL embeddings.const sourceOpt = sourceId ? { sourceId } : undefined;const includeNullSig = !!staleOpts?.includeNullSignature;+ // Chunkless-page safety net: pre-flight count mirrors the countStaleChunks+ // short-circuit just below — a healthy brain pays one extra SELECT+ // count(*) and does no further work. Only when pages are actually found+ // do we pay for the keyset-paginated chunk sweep. Chunking here (before+ // countStaleChunks) means any newly-written NULL-embedding chunks flow+ // into the SAME pass via the existing cursor.+ const chunklessCount = await engine.countChunklessPagesWithContent(sourceOpt);+ if (chunklessCount > 0) {+ await healChunklessPages(+ engine, sourceId, dryRun, result, staleOpts?.quiet, externalSignal, staleOpts?.pacer,+ overallStartedAt, !!staleOpts?.catchUp,+ );+ }+ // Review catch: an abort during healing must stop the run HERE, before+ // falling through into invalidateStaleSignatureEmbeddings below (which —+ // pre-existing, unchanged by this PR — does not itself check+ // externalSignal). Without this, a caller-cancelled run could still NULL+ // out signature-drifted embeddings and exit, leaving retrieval degraded.+ if (isAborted(externalSignal)) return;+// v0.41.31: re-embed pages whose embedding_signature drifted (model/dims// swap). dry-run must NOT mutate, so it counts signature-stale via the// widened predicate; a live run NULLs them first so the existing@@ -1085,7 +1317,15 @@ async function embedAllStale(if (staleCount === 0) {if (!staleOpts?.quiet) {if (dryRun) {- slog('[dry-run] Would embed 0 chunks (0 stale found)');+ // dryRun never writes, so a healed-but-hypothetical chunkless page's+ // chunks never land in content_chunks and staleCount can't see them+ // — report result.would_embed (already includes them) instead of a+ // bare "0 chunks" that would contradict the returned EmbedResult.+ if (result.would_embed > 0) {+ slog(`[dry-run] Would embed ${result.would_embed} chunks (0 stale found; ${result.chunkless_pages_healed} chunkless page(s) would be chunked)`);+ } else {+ slog('[dry-run] Would embed 0 chunks (0 stale found)');+ }} else {slog('Embedded 0 chunks (0 stale found)');}@@ -1101,7 +1341,16 @@ async function embedAllStale(// made `embed.pages` claim total:1 next to a summary naming a much larger// stale count. docs/progress-events.md allows omitting `total` when it is// not known up front; it does not allow asserting a wrong one.- if (!staleOpts?.quiet) slog(`[dry-run] Would embed ${staleCount} stale chunks`);+ //+ // Log result.would_embed (staleCount + any chunkless-page-healing+ // contribution from above), not the bare staleCount — otherwise this+ // line understates the total whenever chunkless pages were also found.+ if (!staleOpts?.quiet) {+ const chunklessNote = result.chunkless_pages_healed > 0+ ? `, including ${result.chunkless_pages_healed} chunkless page(s)`+ : '';+ slog(`[dry-run] Would embed ${result.would_embed} stale chunks${chunklessNote}`);+ }return;}@@ -1132,9 +1381,12 @@ async function embedAllStale(? null: parseInt(process.env.GBRAIN_EMBED_TIME_BUDGET_MS || `${30 * 60 * 1000}`, 10);const budgetController = new AbortController();- const budgetStart = Date.now();+ // Shares overallStartedAt with the chunkless-page healing sweep above+ // (review catch) so the two phases draw from ONE combined budget window+ // instead of each getting a fresh 30 minutes.+ const budgetStart = overallStartedAt;let budgetTimer = BUDGET_MS != null- ? setTimeout(() => budgetController.abort(), BUDGET_MS)+ ? setTimeout(() => budgetController.abort(), Math.max(0, budgetStart + BUDGET_MS - Date.now())): undefined;// E-4 (paced-backfill): the budget measures WORK, not waiting. After each// batch, re-arm the timer to fire at start + BUDGET + total-paced-sleep, so adiff --git a/src/core/engine.ts b/src/core/engine.tsindex 37357e8853..64d2d310ae 100644--- a/src/core/engine.ts+++ b/src/core/engine.ts@@ -1,6 +1,6 @@import type {Page, PageInput, PageFilters, GetPageOpts,- Chunk, ChunkInput, StaleChunkRow, StalePageRow,+ Chunk, ChunkInput, StaleChunkRow, StalePageRow, ChunklessPageRow,SearchResult, SearchOpts,Link, GraphNode, GraphPath, RelationalFanoutRow, RelationalFanoutOpts,TimelineEntry, TimelineInput, TimelineOpts,@@ -1087,6 +1087,35 @@ export interface BrainEngine {// common denominator on the wire).afterUpdatedAt?: string | null;}): Promise<StaleChunkRow[]>;+ /**+ * Pre-flight count for the chunkless-page safety net: pages with+ * non-empty `compiled_truth` AND/OR non-empty `timeline` — both are+ * chunked independently by the healer — and ZERO `content_chunks` rows.+ * `embed --stale` only scans `content_chunks` (embedding IS NULL) — a+ * page written directly via `putPage` that never got chunked has no+ * chunk row to find, so it stays invisible to that scan forever.+ * `opts.sourceId` scopes the count to a single source, matching+ * `countStaleChunks`. Quarantined and `embed_skip` pages are excluded —+ * both are intentionally chunkless by design, not drift needing repair.+ * See `ChunklessPageRow` for the full rationale.+ */+ countChunklessPagesWithContent(opts?: { sourceId?: string }): Promise<number>;+ /**+ * List pages with non-empty `compiled_truth` and/or `timeline` and zero+ * `content_chunks` rows (sibling of `countChunklessPagesWithContent`;+ * same predicate). Keyset-paginated on `id` (mirrors+ * `listStalePagesForExtraction`) — pass the last row's `id` as+ * `afterPageId` for the next page. Default `batchSize` 50 — deliberately+ * small (unlike the 2000-row default on chunk-metadata-only cursors+ * elsewhere): each row here carries a FULL page body, so a large batch+ * of large pages is a real memory concern this is a safety-net sweep for+ * a rare drift case, not the primary bulk-import chunking path.+ */+ listChunklessPagesWithContent(opts?: {+ batchSize?: number;+ afterPageId?: number;+ sourceId?: string;+ }): Promise<ChunklessPageRow[]>;/*** Delete every chunk for a page. Internal page-id lookup is sourceId-scoped* when `opts.sourceId` is given; otherwise the bare-slug subquery returnsdiff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.tsindex 08460ee262..59b3079048 100644--- a/src/core/pglite-engine.ts+++ b/src/core/pglite-engine.ts@@ -55,7 +55,7 @@ import { attemptWalRepairAndRetry, closeRepairEpisodeIfOpen, type WalRepairReceiimport { getFtsLanguage } from './fts-language.ts';import type {Page, PageInput, PageFilters, PageType,- Chunk, ChunkInput, StaleChunkRow, StalePageRow,+ Chunk, ChunkInput, StaleChunkRow, StalePageRow, ChunklessPageRow,SearchResult, SearchOpts,Link, GraphNode, GraphPath,TimelineEntry, TimelineInput, TimelineOpts,@@ -87,6 +87,8 @@ import { buildSourceFactorCase, buildHardExcludeClause, buildVisibilityClause, bimport { unverifiedExtractionFragment } from './extraction-review.ts';import { shouldExcludeFromOrphanReporting, loadOrphanPolicyOverrides } from './orphan-policy.ts';import { LINK_EXTRACTOR_VERSION_TS } from './link-extraction.ts';+import { EMBED_SKIP_FILTER_FRAGMENT } from './embed-skip.ts';+import { QUARANTINE_FILTER_FRAGMENT } from './quarantine.ts';import {normalizeEngineColumn,buildVectorCastFragment,@@ -2945,6 +2947,73 @@ export class PGLiteEngine implements BrainEngine {return rows as unknown as StaleChunkRow[];}+ /**+ * Shared chunkless-page-with-content predicate (mirrors PostgresEngine).+ * Excludes quarantined + embed_skip pages — both are intentionally+ * chunkless by design, not drift the safety net should repair.+ */+ private buildChunklessPagesWhere(opts?: { sourceId?: string }): { where: string; params: unknown[] } {+ const conds: string[] = [+ 'p.deleted_at IS NULL',+ // healChunklessPages chunks BOTH compiled_truth and timeline (mirrors+ // embedPage) — a timeline-only page (rare but schema-legal) has+ // something to heal even with compiled_truth = ''.+ `(p.compiled_truth <> '' OR p.timeline <> '')`,+ EMBED_SKIP_FILTER_FRAGMENT,+ QUARANTINE_FILTER_FRAGMENT,+ 'NOT EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id)',+ ];+ const params: unknown[] = [];+ if (opts?.sourceId) {+ params.push(opts.sourceId);+ conds.push(`p.source_id = $${params.length}`);+ }+ return { where: conds.join(' AND '), params };+ }++ async countChunklessPagesWithContent(opts?: { sourceId?: string }): Promise<number> {+ const { where, params } = this.buildChunklessPagesWhere(opts);+ const { rows } = await this.db.query(+ `SELECT count(*)::int AS count FROM pages p WHERE ${where}`,+ params,+ );+ const count = (rows[0] as { count: number } | undefined)?.count ?? 0;+ return Number(count);+ }++ async listChunklessPagesWithContent(opts?: {+ batchSize?: number;+ afterPageId?: number;+ sourceId?: string;+ }): Promise<ChunklessPageRow[]> {+ const { where, params } = this.buildChunklessPagesWhere(opts);+ let afterClause = '';+ if (opts?.afterPageId != null) {+ params.push(opts.afterPageId);+ afterClause = ` AND p.id > $${params.length}`;+ }+ // Small default (unlike the 2000-row chunk-metadata cursors elsewhere):+ // each row here carries a FULL page body. See engine.ts docstring.+ const limit = opts?.batchSize ?? 50;+ params.push(limit);+ const limitIdx = params.length;+ const { rows } = await this.db.query(+ `SELECT p.id, p.slug, p.source_id, p.compiled_truth, p.timeline+ FROM pages p+ WHERE ${where}${afterClause}+ ORDER BY p.id+ LIMIT $${limitIdx}`,+ params,+ );+ return (rows as Record<string, unknown>[]).map(r => ({+ id: r.id as number,+ slug: r.slug as string,+ source_id: (r.source_id as string | undefined) ?? 'default',+ compiled_truth: (r.compiled_truth as string | null) ?? '',+ timeline: (r.timeline as string | null) ?? '',+ }));+ }+async deleteChunks(slug: string, opts?: { sourceId?: string }): Promise<void> {const sourceId = opts?.sourceId ?? 'default';// Source-qualify the page-id subquery; slugs are only unique per source.diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex 4ba0cf765c..8da46531af 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -60,7 +60,7 @@ import { getFtsLanguage, applyFtsLanguagePolicy } from './fts-language.ts';import { MARKDOWN_CHUNKER_VERSION } from './chunkers/recursive.ts';import type {Page, PageInput, PageFilters, PageType,- Chunk, ChunkInput, StaleChunkRow, StalePageRow,+ Chunk, ChunkInput, StaleChunkRow, StalePageRow, ChunklessPageRow,SearchResult, SearchOpts,Link, GraphNode, GraphPath,TimelineEntry, TimelineInput, TimelineOpts,@@ -93,6 +93,8 @@ import { DELETE_BATCH_SIZE } from './engine-constants.ts';import { SOURCE_CONFIG_OBJECT_SQL } from './source-config-sql.ts';import { shouldExcludeFromOrphanReporting, loadOrphanPolicyOverrides } from './orphan-policy.ts';import { LINK_EXTRACTOR_VERSION_TS } from './link-extraction.ts';+import { EMBED_SKIP_FILTER_FRAGMENT } from './embed-skip.ts';+import { QUARANTINE_FILTER_FRAGMENT } from './quarantine.ts';function escapeSqlStringLiteral(value: string): string {return value.replace(/'/g, "''");@@ -2878,6 +2880,78 @@ export class PostgresEngine implements BrainEngine {});}+ /**+ * Shared chunkless-page-with-content predicate (mirrors PGLiteEngine).+ * Excludes quarantined + embed_skip pages — both are intentionally+ * chunkless by design, not drift the safety net should repair.+ */+ private buildChunklessPagesWhere(opts?: { sourceId?: string }): { where: string; params: unknown[] } {+ const conds: string[] = [+ 'p.deleted_at IS NULL',+ // healChunklessPages chunks BOTH compiled_truth and timeline (mirrors+ // embedPage) — a timeline-only page (rare but schema-legal) has+ // something to heal even with compiled_truth = ''.+ `(p.compiled_truth <> '' OR p.timeline <> '')`,+ EMBED_SKIP_FILTER_FRAGMENT,+ QUARANTINE_FILTER_FRAGMENT,+ 'NOT EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id)',+ ];+ const params: unknown[] = [];+ if (opts?.sourceId) {+ params.push(opts.sourceId);+ conds.push(`p.source_id = $${params.length}`);+ }+ return { where: conds.join(' AND '), params };+ }++ async countChunklessPagesWithContent(opts?: { sourceId?: string }): Promise<number> {+ const { where, params } = this.buildChunklessPagesWhere(opts);+ // RLS scope binding (opt-in via GBRAIN_RLS_SCOPE_BINDING).+ return await this.withScopedReadTransaction(undefined, opts?.sourceId, async (tx) => {+ const rows = await tx.unsafe(+ `SELECT count(*)::int AS count FROM pages p WHERE ${where}`,+ params as Parameters<typeof tx.unsafe>[1],+ );+ return Number((rows[0] as { count?: number } | undefined)?.count ?? 0);+ });+ }++ async listChunklessPagesWithContent(opts?: {+ batchSize?: number;+ afterPageId?: number;+ sourceId?: string;+ }): Promise<ChunklessPageRow[]> {+ const { where, params } = this.buildChunklessPagesWhere(opts);+ let afterClause = '';+ if (opts?.afterPageId != null) {+ params.push(opts.afterPageId);+ afterClause = ` AND p.id > $${params.length}`;+ }+ // Small default (unlike the 2000-row chunk-metadata cursors elsewhere):+ // each row here carries a FULL page body. See engine.ts docstring.+ const limit = opts?.batchSize ?? 50;+ params.push(limit);+ const limitIdx = params.length;+ // RLS scope binding (opt-in via GBRAIN_RLS_SCOPE_BINDING).+ return await this.withScopedReadTransaction(undefined, opts?.sourceId, async (tx) => {+ const rows = await tx.unsafe(+ `SELECT p.id, p.slug, p.source_id, p.compiled_truth, p.timeline+ FROM pages p+ WHERE ${where}${afterClause}+ ORDER BY p.id+ LIMIT $${limitIdx}`,+ params as Parameters<typeof tx.unsafe>[1],+ );+ return (rows as Record<string, unknown>[]).map(r => ({+ id: r.id as number,+ slug: r.slug as string,+ source_id: (r.source_id as string | undefined) ?? 'default',+ compiled_truth: (r.compiled_truth as string | null) ?? '',+ timeline: (r.timeline as string | null) ?? '',+ }));+ });+ }+async deleteChunks(slug: string, opts?: { sourceId?: string }): Promise<void> {const sql = this.sql;const sourceId = opts?.sourceId ?? 'default';diff --git a/src/core/types.ts b/src/core/types.tsindex 8bfd38408c..646a2f404e 100644--- a/src/core/types.ts+++ b/src/core/types.ts@@ -623,6 +623,29 @@ export interface StaleChunkRow {page_id: number;}+/**+ * A page with non-empty `compiled_truth` and/or `timeline` (both are+ * chunked independently by the healer) but ZERO `content_chunks` rows,+ * returned by `listChunklessPagesWithContent`. `embed --stale` scans+ * `content_chunks` (embedding IS NULL) — a page written directly via+ * `putPage` that never went through the chunking step (e.g. an+ * enrichment-generated entity stub) has no chunk row to go stale, so it is+ * invisible to that scan forever. This is the safety-net detection: find+ * such pages so `embed --stale` can chunk them and fold the resulting+ * NULL-embedding chunks into the same run.+ *+ * Quarantined and `embed_skip` pages are excluded by the underlying query+ * (`src/core/quarantine.ts` / `src/core/embed-skip.ts`) — both are+ * INTENTIONALLY chunkless by design (content-quality gate), not drift.+ */+export interface ChunklessPageRow {+ id: number;+ slug: string;+ source_id: string;+ compiled_truth: string;+ timeline: string;+}+/*** v0.42.7 (#1696) — a page that needs link/timeline extraction, returned by* `listStalePagesForExtraction`. Carries the page CONTENT (compiled_truth +diff --git a/test/e2e/engine-parity.test.ts b/test/e2e/engine-parity.test.tsindex 6e8b925ec0..82b178ed66 100644--- a/test/e2e/engine-parity.test.ts+++ b/test/e2e/engine-parity.test.ts@@ -720,6 +720,56 @@ describeBoth('Engine parity — Postgres vs PGLite', () => {expect(await pgliteEngine.countStalePagesForExtraction({ sourceId: SRC })).toBe(2);});+ // Chunkless-page safety net (embed --stale detection gap): a page with+ // non-empty content but zero content_chunks rows (e.g. a putPage-only+ // write) must be found on BOTH engines identically, and quarantined /+ // embed_skip pages (intentionally chunkless by design) must be excluded+ // identically on both. Isolated under a dedicated source.+ test('chunkless-page-with-content detection: Postgres ↔ PGLite parity', async () => {+ const SRC = 'chunkless-parity';+ for (const eng of [pgEngine, pgliteEngine]) {+ await eng.executeRaw(`INSERT INTO sources (id, name, config) VALUES ($1, 'Chunkless Parity', '{}'::jsonb) ON CONFLICT DO NOTHING`, [SRC]);++ // cp/stub: non-empty content, never chunked — THE bug this fix targets.+ await eng.putPage('cp/stub', { type: 'person', title: 'Stub', compiled_truth: 'stub content, never chunked' }, { sourceId: SRC });+ // cp/chunked: same shape, but chunked — must be excluded.+ await eng.putPage('cp/chunked', { type: 'note', title: 'Chunked', compiled_truth: 'chunked content' }, { sourceId: SRC });+ await eng.upsertChunks('cp/chunked', [+ { chunk_index: 0, chunk_text: 'chunked content', chunk_source: 'compiled_truth' },+ ], { sourceId: SRC });+ // cp/empty: no content — must be excluded (the #2822 empty-put class, not this bug).+ await eng.putPage('cp/empty', { type: 'note', title: 'Empty', compiled_truth: '' }, { sourceId: SRC });+ // cp/quarantined: chunkless BY DESIGN — must be excluded.+ await eng.putPage('cp/quarantined', {+ type: 'note', title: 'Quarantined', compiled_truth: 'junk content',+ frontmatter: { quarantine: { reason: 'junk_pattern', detail: 'parity fixture', assessed_at: new Date().toISOString() } },+ }, { sourceId: SRC });+ // cp/skipped: chunkless BY DESIGN — must be excluded.+ await eng.putPage('cp/skipped', {+ type: 'note', title: 'Skipped', compiled_truth: 'x'.repeat(500),+ frontmatter: { embed_skip: { reason: 'oversized', bytes: 500, assessed_at: new Date().toISOString() } },+ }, { sourceId: SRC });+ }++ expect(await pgEngine.countChunklessPagesWithContent({ sourceId: SRC })).toBe(1);+ expect(await pgliteEngine.countChunklessPagesWithContent({ sourceId: SRC })).toBe(1);++ const pgRows = await pgEngine.listChunklessPagesWithContent({ sourceId: SRC });+ const pgliteRows = await pgliteEngine.listChunklessPagesWithContent({ sourceId: SRC });+ expect(pgRows.map(r => r.slug)).toEqual(['cp/stub']);+ expect(pgliteRows.map(r => r.slug)).toEqual(['cp/stub']);+ expect(pgRows[0].compiled_truth).toBe('stub content, never chunked');+ expect(pgliteRows[0].compiled_truth).toBe(pgRows[0].compiled_truth);++ // Unscoped count/list is >= the scoped count on both engines (other+ // tests' fixtures may also be chunkless — this only asserts the SRC+ // subset is reachable without scoping, not an exact global count).+ const pgAllSlugs = (await pgEngine.listChunklessPagesWithContent({ batchSize: 10000 })).map(r => r.slug);+ const pgliteAllSlugs = (await pgliteEngine.listChunklessPagesWithContent({ batchSize: 10000 })).map(r => r.slug);+ expect(pgAllSlugs).toContain('cp/stub');+ expect(pgliteAllSlugs).toContain('cp/stub');+ });+test('v0.41.39 listEnrichCandidates parity (thin filter + source-aware inbound + order)', async () => {const stub = 'Stub page.';const pageSql = `diff --git a/test/embed-stale-chunkless-pages.serial.test.ts b/test/embed-stale-chunkless-pages.serial.test.tsnew file mode 100644index 0000000000..10fcfd2433--- /dev/null+++ b/test/embed-stale-chunkless-pages.serial.test.ts@@ -0,0 +1,308 @@+/**+ * Chunkless-page safety net for `embed --stale`.+ *+ * `embedAllStale` (and the underlying `listStaleChunks`/`countStaleChunks`)+ * only ever scan `content_chunks` rows where `embedding IS NULL`. A page+ * written directly via `putPage` that never went through chunking (e.g. an+ * enrichment-generated entity stub — the dogfooding case this fix targets)+ * has NO `content_chunks` row at all, so it is invisible to that scan+ * forever: there is no row to go stale, no matter how many times+ * `embed --stale` runs.+ *+ * Two layers tested here:+ * 1. The detection primitive itself (`countChunklessPagesWithContent` /+ * `listChunklessPagesWithContent`) — including that quarantined and+ * `embed_skip` pages are excluded, since BOTH are intentionally+ * chunkless by design (content-quality gate), not drift to repair.+ * 2. The end-to-end `embed --stale` wiring — a chunkless page gets+ * chunked AND embedded in the SAME pass, while pre-existing stale+ * chunks and intentionally-chunkless pages are unaffected.+ *+ * Named `.serial.test.ts` (mirrors v0_37_gap_fill.serial.test.ts Lane D.2):+ * configures the AI gateway + a fake embed transport for its whole+ * lifecycle, which withEnv() can't wrap.+ */+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';+import { runEmbedCore } from '../src/commands/embed.ts';+import { EMBED_SKIP_KEY, buildEmbedSkipMarker } from '../src/core/embed-skip.ts';+import { QUARANTINE_KEY, buildQuarantineMarker } from '../src/core/quarantine.ts';+import type { BrainEngine } from '../src/core/engine.ts';++const DIMS = 1536;+let engine: PGLiteEngine;++beforeAll(async () => {+ configureGateway({+ embedding_model: 'openai:text-embedding-3-large',+ embedding_dimensions: DIMS,+ env: { ...process.env, OPENAI_API_KEY: 'sk-test-fake' },+ });+ __setEmbedTransportForTests(async ({ values }: { values: string[] }) => ({+ embeddings: values.map(() => new Array(DIMS).fill(0.001)),+ usage: { tokens: values.length * 4 },+ } as never));++ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 30000);++afterAll(async () => {+ __setEmbedTransportForTests(null);+ resetGateway();+ await engine.disconnect();+});++beforeEach(async () => {+ await resetPgliteState(engine);+});++describe('countChunklessPagesWithContent / listChunklessPagesWithContent', () => {+ test('detects a page written via putPage that was never chunked', async () => {+ await engine.putPage('stub/entity-a', {+ type: 'person',+ title: 'Entity A',+ compiled_truth: 'Entity A is a stub written directly via putPage.',+ });++ expect(await engine.countChunklessPagesWithContent()).toBe(1);+ const rows = await engine.listChunklessPagesWithContent();+ expect(rows).toHaveLength(1);+ expect(rows[0].slug).toBe('stub/entity-a');+ expect(rows[0].compiled_truth).toContain('stub written directly');+ });++ test('excludes pages that already have chunk rows', async () => {+ await engine.putPage('normal/page', { type: 'note', title: 'Normal', compiled_truth: 'hello world' });+ await engine.upsertChunks('normal/page', [+ { chunk_index: 0, chunk_text: 'hello world', chunk_source: 'compiled_truth' },+ ]);++ expect(await engine.countChunklessPagesWithContent()).toBe(0);+ expect(await engine.listChunklessPagesWithContent()).toEqual([]);+ });++ test('excludes pages with empty content', async () => {+ // Matches pages.compiled_truth's schema DEFAULT '' — the #2822 empty-put+ // case. Empty content has nothing to chunk; it is not this bug class.+ await engine.putPage('empty/page', { type: 'note', title: 'Empty', compiled_truth: '' });++ expect(await engine.countChunklessPagesWithContent()).toBe(0);+ });++ test('detects a timeline-only page (empty compiled_truth, non-empty timeline)', async () => {+ // healChunklessPages chunks compiled_truth AND timeline independently+ // (mirrors embedPage) — the SQL predicate must not require+ // compiled_truth alone or this class of page is never even detected.+ await engine.putPage('timeline-only/page', {+ type: 'note',+ title: 'Timeline Only',+ compiled_truth: '',+ timeline: '2026-01-01: something happened',+ });++ expect(await engine.countChunklessPagesWithContent()).toBe(1);+ const rows = await engine.listChunklessPagesWithContent();+ expect(rows.map(r => r.slug)).toEqual(['timeline-only/page']);+ });++ test('excludes quarantined pages (intentionally chunkless by design)', async () => {+ await engine.putPage('junk/page', {+ type: 'note',+ title: 'Junk',+ compiled_truth: 'Cloudflare interstitial junk content',+ frontmatter: { [QUARANTINE_KEY]: buildQuarantineMarker('junk_pattern', 'test fixture') },+ });++ expect(await engine.countChunklessPagesWithContent()).toBe(0);+ });++ test('excludes embed_skip pages (intentionally chunkless by design)', async () => {+ await engine.putPage('oversized/page', {+ type: 'note',+ title: 'Oversized',+ compiled_truth: 'x'.repeat(1000),+ frontmatter: { [EMBED_SKIP_KEY]: buildEmbedSkipMarker(1000) },+ });++ expect(await engine.countChunklessPagesWithContent()).toBe(0);+ });++});++describe('embed --stale chunkless-page safety net (end-to-end)', () => {+ test('a putPage-only page gets chunked AND embedded in the same --stale pass', async () => {+ await engine.putPage('stub/heal-me', {+ type: 'person',+ title: 'Heal Me',+ compiled_truth: 'This entity stub was written directly via putPage and never chunked.',+ });+ expect(await engine.getChunks('stub/heal-me')).toEqual([]);++ const result = await runEmbedCore(engine, { stale: true, quiet: true });++ expect(result.chunkless_pages_healed).toBe(1);+ const chunks = await engine.getChunks('stub/heal-me');+ expect(chunks.length).toBeGreaterThan(0);+ for (const c of chunks) {+ expect(c.embedded_at).not.toBeNull();+ }+ });++ test('pre-existing NULL-embedding chunks on other pages still get embedded (no regression)', async () => {+ await engine.putPage('normal/pre-chunked', { type: 'note', title: 'Pre-chunked', compiled_truth: 'hello world' });+ await engine.upsertChunks('normal/pre-chunked', [+ { chunk_index: 0, chunk_text: 'hello world', chunk_source: 'compiled_truth' },+ ]);+ await engine.putPage('stub/heal-me-2', {+ type: 'person',+ title: 'Heal Me Two',+ compiled_truth: 'Another chunkless stub.',+ });++ const result = await runEmbedCore(engine, { stale: true, quiet: true });++ expect(result.chunkless_pages_healed).toBe(1);+ expect(result.embedded).toBeGreaterThanOrEqual(2); // 1 pre-existing + >=1 healed+ const preChunked = await engine.getChunks('normal/pre-chunked');+ expect(preChunked[0]?.embedded_at).not.toBeNull();+ });++ test('quarantined and embed_skip pages stay chunkless — the safety net does not touch them', async () => {+ await engine.putPage('junk/quarantined', {+ type: 'note',+ title: 'Junk',+ compiled_truth: 'junk content',+ frontmatter: { [QUARANTINE_KEY]: buildQuarantineMarker('junk_pattern', 'test fixture') },+ });+ await engine.putPage('oversized/skipped', {+ type: 'note',+ title: 'Oversized',+ compiled_truth: 'x'.repeat(1000),+ frontmatter: { [EMBED_SKIP_KEY]: buildEmbedSkipMarker(1000) },+ });++ const result = await runEmbedCore(engine, { stale: true, quiet: true });++ expect(result.chunkless_pages_healed).toBe(0);+ expect(await engine.getChunks('junk/quarantined')).toEqual([]);+ expect(await engine.getChunks('oversized/skipped')).toEqual([]);+ });++ test('dry-run reports the would-be-healed count without writing any chunks', async () => {+ await engine.putPage('stub/dry-run-only', {+ type: 'person',+ title: 'Dry Run Only',+ compiled_truth: 'This stub must NOT be chunked by a dry run.',+ });++ const result = await runEmbedCore(engine, { stale: true, dryRun: true, quiet: true });++ expect(result.chunkless_pages_healed).toBe(1);+ expect(result.would_embed).toBeGreaterThan(0);+ expect(await engine.getChunks('stub/dry-run-only')).toEqual([]); // no mutation+ });++ test('healthy brain (no chunkless pages) pays no extra cost and behaves exactly as before', async () => {+ await engine.putPage('normal/only-page', { type: 'note', title: 'Only', compiled_truth: 'hello' });+ await engine.upsertChunks('normal/only-page', [+ { chunk_index: 0, chunk_text: 'hello', chunk_source: 'compiled_truth' },+ ]);++ const result = await runEmbedCore(engine, { stale: true, quiet: true });++ expect(result.chunkless_pages_healed).toBe(0);+ expect(result.embedded).toBe(1);+ });++ test('race mitigation: a page chunked by a concurrent writer between list and write is not clobbered', async () => {+ // Review catch: healChunklessPages lists chunkless pages, chunks them+ // in memory, then writes. If a concurrent writer (sync, another+ // put_page/embed) chunks the SAME page in between, a naive write would+ // overwrite the concurrent writer's (newer) chunks with this sweep's+ // stale-content snapshot. Simulate that race by injecting a write+ // immediately after listChunklessPagesWithContent returns — i.e. AFTER+ // the sweep has decided to heal this page but BEFORE its own write.+ await engine.putPage('stub/raced', {+ type: 'person',+ title: 'Raced',+ compiled_truth: 'Original content the sweep read.',+ });++ let injected = false;+ const realList = engine.listChunklessPagesWithContent.bind(engine);+ const raceEngine = new Proxy(engine, {+ get(target, prop, receiver) {+ if (prop === 'listChunklessPagesWithContent') {+ return async (opts?: Parameters<typeof realList>[0]) => {+ const rows = await realList(opts);+ if (!injected && rows.some(r => r.slug === 'stub/raced')) {+ injected = true;+ // Simulate the concurrent writer: chunks the page with DIFFERENT+ // content than what the sweep just read.+ await engine.upsertChunks('stub/raced', [+ { chunk_index: 0, chunk_text: 'concurrently-written chunk', chunk_source: 'compiled_truth' },+ ]);+ }+ return rows;+ };+ }+ const value = Reflect.get(target, prop, receiver);+ return typeof value === 'function' ? value.bind(target) : value;+ },+ }) as unknown as BrainEngine;++ const result = await runEmbedCore(raceEngine, { stale: true, quiet: true });++ // The race was detected and the page was skipped this pass (not+ // counted as healed by this sweep) rather than clobbered.+ expect(result.chunkless_pages_healed).toBe(0);+ const chunks = await engine.getChunks('stub/raced');+ expect(chunks).toHaveLength(1);+ expect(chunks[0].chunk_text).toBe('concurrently-written chunk');+ });++ test('one broken chunkless page does not abort the whole --stale run (per-page failure isolation)', async () => {+ // Review catch: healChunklessPages must try/catch per page. Before the+ // fix, an exception from getPage/getChunks/upsertChunks for ONE+ // chunkless page propagated out of healChunklessPages entirely,+ // aborting embedAllStale before it even reached the normal+ // NULL-embedding pass — making the safety net worse than the bug.+ await engine.putPage('stub/broken', {+ type: 'person',+ title: 'Broken',+ compiled_truth: 'This page will fail to heal.',+ });+ await engine.putPage('normal/unrelated', { type: 'note', title: 'Unrelated', compiled_truth: 'fine' });+ await engine.upsertChunks('normal/unrelated', [+ { chunk_index: 0, chunk_text: 'fine', chunk_source: 'compiled_truth' },+ ]);++ const brokenEngine = new Proxy(engine, {+ get(target, prop, receiver) {+ if (prop === 'getPage') {+ return async (slug: string, opts?: unknown) => {+ if (slug === 'stub/broken') throw new Error('simulated getPage failure');+ return (engine.getPage as (s: string, o?: unknown) => unknown)(slug, opts);+ };+ }+ const value = Reflect.get(target, prop, receiver);+ return typeof value === 'function' ? value.bind(target) : value;+ },+ }) as unknown as BrainEngine;++ const result = await runEmbedCore(brokenEngine, { stale: true, quiet: true });++ // The broken page's failure is recorded, not swallowed silently...+ expect(result.failures).toBeGreaterThanOrEqual(1);+ expect(result.failure_samples.some(s => s.includes('stub/broken'))).toBe(true);+ // ...but did NOT abort the run: the unrelated pre-existing stale chunk+ // still got embedded in the SAME pass.+ expect(result.embedded).toBeGreaterThanOrEqual(1);+ const unrelatedChunks = await engine.getChunks('normal/unrelated');+ expect(unrelatedChunks[0]?.embedded_at).not.toBeNull();+ });+});diff --git a/test/embed.serial.test.ts b/test/embed.serial.test.tsindex 9846c892f0..eea1b2eb74 100644--- a/test/embed.serial.test.ts+++ b/test/embed.serial.test.ts@@ -177,6 +177,31 @@ describe('runEmbed --all (parallel)', () => {expect(result.embedded).toBe(0);});+ test('#1737 review catch: signal aborted during chunkless-page healing stops before invalidateStaleSignatureEmbeddings', async () => {+ // Round-3 review finding: embedAllStale must check the abort signal+ // immediately after the chunkless-page healing sweep, before falling+ // through into invalidateStaleSignatureEmbeddings (a write path) —+ // otherwise a caller-cancelled run could still NULL out+ // signature-drifted embeddings and exit, leaving retrieval degraded.+ const ac = new AbortController();+ let invalidateCalled = false;+ const engine = mockEngine({+ countChunklessPagesWithContent: async () => 1,+ listChunklessPagesWithContent: async () => {+ // Simulate the caller's cancellation firing WHILE the healing sweep+ // is mid-flight (e.g. worker timeout / lock loss / SIGTERM).+ ac.abort(new Error('lock-lost'));+ return [];+ },+ invalidateStaleSignatureEmbeddings: async () => { invalidateCalled = true; return 0; },+ countStaleChunks: async () => 0,+ });++ await runEmbedCore(engine, { stale: true, signal: ac.signal });++ expect(invalidateCalled).toBe(false);+ });+test('respects GBRAIN_EMBED_CONCURRENCY=1 (serial)', async () => {const pages = Array.from({ length: 5 }, (_, i) => ({ slug: `page-${i}` }));const chunksBySlug = new Map(