Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

v0.50.2.0 fix: harden persistence, maintenance, sync, and hosted access (#5122)

Garry Tan7fb6617dbf81
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 875a2a31df..a0cad69ffb 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain",
- "version": "0.50.1.0",
+ "version": "0.50.2.0",
"description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.",
"author": {
"name": "Garry Tan",
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index c0591f4703..0d13ba51b5 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain",
- "version": "0.50.1.0",
+ "version": "0.50.2.0",
"description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.",
"author": {
"name": "Garry Tan",
diff --git a/AGENTS.md b/AGENTS.md
index 6c1bca36f8..c38f3df616 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -99,9 +99,10 @@ writing or reviewing an operation, consult `src/core/operations.ts` for the cont
- **Drive the brain to a target health score:** the one-command
loop. `gbrain doctor --remediation-plan --json` previews what would be
fixed; `gbrain doctor --remediate --yes --target-score 90 --max-usd 5`
- walks a dependency-ordered plan (sync before extract, embed after
- consolidate), re-checking score between every step, refusing to spend
- past the cost cap. Empty brains (no entity pages) or unconfigured embedding
+ walks a dependency-ordered plan, re-checking score between every step and
+ refusing to spend past the cost cap. Stale extraction uses source-scoped
+ database pages, including DB-only pages; it does not require a repository
+ sync first. Empty brains (no entity pages) or unconfigured embedding
keys hit a `max_reachable_score` ceiling and bail with what's missing.
Three phase handlers (synthesize / patterns / consolidate) are
PROTECTED — only trusted local callers can submit them; MCP cannot.
diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.md
index 35ae6ce1f4..5b78b72e29 100644
--- a/BOOTSTRAP_FOR_AGENTS.md
+++ b/BOOTSTRAP_FOR_AGENTS.md
@@ -1,4 +1,4 @@
-<!-- gbrain-runbook-stamp: 0.50.1.0 -->
+<!-- gbrain-runbook-stamp: 0.50.2.0 -->
<!-- This stamp must equal the VERSION file at every release; CI enforces it
(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it to
the installed binary and warns on skew. -->
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b0701a625e..10e35c367c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,58 @@
All notable changes to GBrain will be documented in this file.
+## [0.50.2.0] - 2026-09-15
+
+**Saved pages stay saved, rejected writes stay rejected, and maintenance stops reporting unfinished work as complete.**
+
+Saving a page now checks that its working folder is available before changing the stored revision. If writing the file fails, the previous page, tags, chunks, and revision history survive. Search enrichment runs after the page is saved and its page-save locks are released; a caller that holds its own surrounding lock may still block other writes. A slow enrichment result cannot replace a newer revision.
+
+Background jobs that promise to write a page must actually save one. Finishing with prose, declining to write, or returning a rejected import no longer counts as success. Maintenance keeps unfinished or budget-deferred work due for another attempt, including when some children succeeded.
+
+Unresolved facts keep their content and provenance without inventing a page to attach them to. The old fence migration stops creating empty pages for those references. Interrupted embedding runs retain completed work instead of paying to replace the same vectors again.
+
+### What changes in practice
+
+| Situation | Result |
+|---|---|
+| The source worktree is busy | The write is rejected before publication and explicitly is not queued. |
+| A page saves but embedding fails | The saved content remains available; embedding reports a separate failure. |
+| A hosted client connects without requesting scopes | It bootstraps read-only; writing still needs an explicit authorized request. |
+| A thin client searches without a source filter | Reads follow the host grant instead of being pinned to the isolated write source. |
+| Bash parsing or Windows subdirectory sync previously skipped content | A source-scoped full sync revisits the affected files. |
+
+### Things to watch
+
+This is not a durable write queue or a crash-atomic transaction spanning files and the database. Historical unmatched facts and empty stubs are not deleted or reconstructed. Back up DB-only knowledge separately from Markdown. Restart old PGLite holders normally to record structured process identity; never delete a live lock to force access.
+
+## To take advantage of v0.50.2.0
+
+Run `gbrain upgrade`, then `gbrain doctor`. If upgrading from before v0.50.0.0, follow its [coordinated authorization cutover](skills/migrations/v0.50.0.0.md) first. This release adds no schema migration.
+
+For a Bash/code source affected by earlier parsing or Windows scoping failures, replace `code-example` with that source's ID and run:
+
+```bash
+gbrain sync --source code-example --full --no-embed
+gbrain doctor
+```
+
+An ordinary incremental sync does not prove historical recovery. Approve any paid embedding separately. Reinstall affected hosted launchers using the existing private handoff and original installation settings; do not widen grants. Agents should follow [the v0.50.2.0 upgrade steps](skills/migrations/v0.50.2.0.md).
+
+**Say to your agent:** "Upgrade GBrain to v0.50.2.0, follow its migration guide, and check my affected sources. Preserve my capture and access settings, and ask before any paid enrichment."
+
+### Itemized changes
+
+- `put_page` acquires the worktree lock before importing, verifies the indexed revision before canonical publication and after commit, and performs write-through inside the import transaction. Deferred page-scoped embedding checks page identity, revision, and chunk generation. Adapted the persistence-first principle from #5100. Contributed by @xaviroblessarries.
+- Required-write accounting rejects prose-only finishes and import-error envelopes, including historical completed ledger entries. Optional-write jobs, unchanged saves, and saved pages with failed enrichment retain their intended behavior. Global maintenance and synthesis cooldowns stay unstamped for incomplete or explicitly deferred work. The global-freshness guard adapts #5089. Contributed by @tarush1989.
+- Unresolved fact references remain unparented. Exact full-basename matches require a unique live page in the same source. The v0.32.2 fence migration requires an existing canonical page/file, checks only the source's Git subtree, and preserves occupied fence row numbers. Adapted #5096. Contributed by @anshmudgil.
+- Embedding invalidation preserves chunks only when their model, current text hash, and vector width match the target; fully current pages can be restamped without another embedding call. Adapted #5056. Contributed by @harjothkhara.
+- PGLite locks preserve structured argument boundaries and use the Windows-aware process probe. Unprovable live legacy identity fails closed; dead-holder recovery remains available. Adapted #5065 and #5073. Contributed by @Masashi-Ono0611.
+- Windows Git-relative scope checks normalize separators. Bash uses the checksum-verified official tree-sitter-bash v0.23.3 grammar with code chunker version 7 and source/compiled semantic checks. Adapted the grammar-refresh approach from #5109 without its unrelated provider changes. Contributed by @lqtdys.
+- Hosted launchers stop forcing `--brain host` and a write-source filter onto reads; `gbrain call` refuses locally on thin clients. Adapted #5107. Contributed by @javieraldape. The documented `schema_pack` config key is accepted, and signal-detection guidance now requires capture opt-in.
+- OAuth discovery omits the non-DCR `agent` scope and scope-less challenges hint `read`, without changing existing token authority or accepting explicit delegation requests. Adapted #5113 with a read-only rather than read-write bootstrap hint. Contributed by @Garabed96 via @zegerhoogeboom.
+- Embedded LongMemEval uses resolved providers and throws on failure instead of terminating its host process; standalone CLI exit behavior is unchanged.
+- Stale-extraction recommendations use source-scoped database extraction, including DB-only pages, instead of suggesting a repository sync and filesystem-wide extraction with an unrelated embedding dependency.
+
## [0.50.1.0] - 2026-09-14
**The community fix wave, rebased onto 0.50.0.0: 21 contributor pull requests adopted or reworked with credit, 35 verified open issues fixed directly.** `gbrain sync --json` prints one JSON document again, so piping it into `jq` works, and a sync that only swept dead pages tells you so instead of "Already up to date". Brains on Gemini embeddings get a real dollar estimate in the cost gate, facts extraction on a local Ollama model asks for schema-constrained JSON so small models stop returning malformed output, and `gbrain dream --dry-run` stops billing you for takes and calibration while the patterns phase skips outright when nothing new has been reflected on. A remote search on a brain that has not been reindexed says so instead of claiming a clean miss, each Codex rollout lands on its own conversation page, and `gbrain config set` accepts the `search.*` keys the search path actually reads. A source marked `syncEnabled: false` is left alone by the daemon, the phantom redirect no longer aborts on a canonical page that already holds facts, and emoji folder names carrying an invisible variation selector slugify cleanly. Every adopted code fix carries a regression test proven red before the fix.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 0c9696f7c4..7ae82f5a9a 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -9,7 +9,7 @@ bun install
bun test
```
-Requires Bun 1.0+.
+Requires Bun 1.3.11 or newer, matching `package.json`.
### Windows
diff --git a/README.md b/README.md
index 86c45ff618..cd52bf0262 100644
--- a/README.md
+++ b/README.md
@@ -264,7 +264,7 @@ echo "from a pipe" | gbrain capture --stdin
SLUG=$(gbrain capture "..." --quiet)
```
-The page lands in the database and on disk in one move. Default slug `inbox/YYYY-MM-DD-<hash8>` so captures cluster in a predictable triage location. On thin-client installs the verb routes through MCP to the server: same command, same UX.
+For a file-backed source, the page is saved to the database and canonical Markdown before optional embedding. Ordinary file-write failures roll back the database revision; this is not a crash-atomic transaction across files and the database. A source without a configured repository can hold DB-only pages, which need a database backup. See the [persistence boundary](docs/architecture/system-of-record.md#page-write-persistence-boundary). Default slug `inbox/YYYY-MM-DD-<hash8>` so captures cluster in a predictable triage location. On thin-client installs the verb routes through MCP to the server.
**Say to your agent:** *"Remember this: ..."* — *"Save this thought to my brain"* — *"Capture this."* And to fill an empty brain from your existing life: *"Fill my brain"* (the cold-start skill walks your email, calendar, contacts, and archives one consented step at a time).
@@ -394,7 +394,7 @@ Want to see a tutorial that isn't here yet? [Open an issue](https://github.com/g
- **Signal detector**, after you opt in, captures durable ideas and entity mentions from substantive messages. Explicit remembering works without automatic capture; paid enrichment is a separate choice.
- **Brain-first lookup** before any external API call. The cheapest, fastest, most personal information source you have.
-- **Auto-link** fires on every page write. No LLM calls; pure pattern matching on `[[wiki/people/bob]]` style references. New entity → new page stub → graph grows.
+- **Auto-link** extracts graph links for trusted local page writes. No LLM calls; pure pattern matching on page references such as `[[people/alice-example]]`. Unresolved extracted facts keep their provenance without inventing a backing page.
- **Cron-driven enrichment** runs while you sleep: dedup people pages, fix citations, score salience, find contradictions, prep tomorrow's tasks.
The whole loop is described in [`docs/architecture/topologies.md`](docs/architecture/topologies.md) with diagrams.
@@ -529,7 +529,7 @@ flowchart LR
**Two engines, one contract.** PGLite (Postgres 17 via WASM, zero-config, default) for personal brains up to ~50K pages. Postgres + pgvector (Supabase or self-hosted) for shared / large / multi-machine deployments. The contract-first `BrainEngine` interface in [`src/core/engine.ts`](src/core/engine.ts) defines the 140+ methods both engines implement; CLI and MCP server are generated from one source.
-**Brain repo is the system of record.** Your knowledge lives in a regular git repo (your "brain repo") as markdown files. GBrain syncs the repo into Postgres for retrieval; deletes in git become soft-deletes in DB. You can publish public subsets, share team mounts, run thin-client setups pointing at a colleague's brain server. Topologies in [`docs/architecture/topologies.md`](docs/architecture/topologies.md).
+**Canonical files preserve file-backed knowledge.** Your brain repo holds Markdown that GBrain indexes for retrieval; deletes in git become soft-deletes in the database. DB-only pages, unresolved facts, revision history, and operational state need a separate database backup. See the [system-of-record contract](docs/architecture/system-of-record.md). You can publish public subsets, share team mounts, and run thin-client setups pointing at a colleague's brain server. Topologies in [`docs/architecture/topologies.md`](docs/architecture/topologies.md).
**Two organizational axes (brain ⊥ source).** A *brain* is a database (your personal brain, a team mount you joined). A *source* is a repo inside that brain (wiki, gstack, an essay, a knowledge base). Routing lives in `.gbrain-source` dotfiles and resolves via a documented 6-tier precedence chain. Full diagrams in [`docs/architecture/brains-and-sources.md`](docs/architecture/brains-and-sources.md).
diff --git a/TODOS.md b/TODOS.md
index cf7070f65b..2242216c68 100644
--- a/TODOS.md
+++ b/TODOS.md
@@ -9272,3 +9272,38 @@ covers DEAD logs; go-forward capture beyond Claude Code is deliberately absent.
pin in `test/chronicle-ontology-private-visibility.test.ts` and the
e2e content-privacy suite). **Context:** filed from the #4881 adoption
(refuter amendment). **Effort:** S.
+
+## v0.50.2.0 persistence and verification follow-ups
+
+- [ ] **P3 — historical migration banner accuracy.** The source-owned v0.32.2
+ feature pitch still promises full database reconstruction from Markdown and
+ refers to an unsupported `--write` flag. Align it with the corrected
+ `skills/migrations/v0.32.2.md` guide, preserving preview/retry behavior and
+ separate backups for DB-only knowledge. The guide is current; the historical
+ banner remains documentation debt.
+
+- [ ] **P2 — durable contention queue and caller revision preconditions (#5105).**
+ The collector rejects a busy worktree before changing the page and reports
+ that the write was not queued. Add a separately reviewed acceptance/replay
+ contract and revision check before claiming queued or conflict-safe writes.
+ Preserve source authorization, cancellation, and idempotency across replay.
+
+- [ ] **P2 — file/database commit-failure recovery.** A crash or database commit
+ failure after atomic rename can leave canonical Markdown ahead of the index.
+ Add fault injection at that boundary and a reconciler with explicit recovery
+ semantics before claiming crash-atomic persistence. Do not treat a Markdown
+ rebuild as recovery of DB-only knowledge or operational state.
+
+- [ ] **P2 — reviewed historical fact and stub repair (#5110, #5111).** New
+ unresolved facts retain provenance without inventing an entity page, and the
+ fence migration skips references without a canonical page. Existing unmatched
+ facts, empty stubs, and fence drift still need a source-scoped preview and
+ backup-backed repair plan. Never erase facts or fabricate backing pages just
+ to improve a parity count.
+
+- [ ] **P3 — native host and client verification for v0.50.2.0.** Exercise the
+ Windows process probe and subdirectory sync on Windows, then verify the
+ installed hosted launcher and read-only OAuth bootstrap in the intended
+ ChatGPT/Claude harness. Injected platform tests and SDK/HTTP tests do not prove
+ those native integrations. Live provider checks require separate consent and
+ configured credentials.
diff --git a/VERSION b/VERSION
index 34f40a4243..7154c9f887 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.50.1.0
+0.50.2.0
diff --git a/docs/TESTING.md b/docs/TESTING.md
index cfcef0246e..d7cdd9a64c 100644
--- a/docs/TESTING.md
+++ b/docs/TESTING.md
@@ -3,7 +3,24 @@
On-demand reference (see CLAUDE.md Reference map). Current behavior + invariants
only.
-`test/e2e/serve-http-oauth.test.ts` additionally pins confidential POST/Basic revocation, public-client SDK fallthrough, malformed/mixed authentication rejection, cross-client isolation, unknown-token opacity, metadata auth methods, no-store responses, strict post-revoke `401`, and retryable backend `503` semantics.
+`test/e2e/serve-http-oauth.test.ts` additionally pins confidential POST/Basic revocation, public-client SDK fallthrough, malformed/mixed authentication rejection, cross-client isolation, unknown-token opacity, metadata auth methods, no-store responses, strict post-revoke `401`, and retryable backend `503` semantics. SDK-driven discovery and real owner-approved PKCE also pin read-only bootstrap, explicit writer requests, scope clamping, and DCR delegation refusal. `test/oauth-scope-hint.test.ts` exercises the actual SDK middleware over HTTP without requiring a database.
+
+`test/put-page-persistence.test.ts` and `test/e2e/put-page-persistence-postgres.test.ts`
+pin the ordinary-error persistence boundary: contention does not publish a
+revision, filesystem failure rolls back the database transaction, embedding
+failure preserves the saved page, and a slow embed releases the page-owned
+worktree lock. The PGLite suite also covers source-path bookkeeping failure,
+legacy hashes, deletion/recreation, and secret-safe embedding diagnostics.
+Neither suite proves crash-atomic filesystem/database commit or a durable queue.
+
+`test/subagent-required-writes.test.ts` and
+`test/subagent-put-page-rejection.serial.test.ts` distinguish a persisted write
+from prose-only completion, rejected imports, and historical rejected ledger
+envelopes across the Anthropic, gateway, and oneshot lanes. Unchanged saves,
+optional-write jobs, and saved pages with failed enrichment are positive controls.
+`test/cycle/global-freshness-postcondition.serial.test.ts` exercises the registered
+maintenance handler with failed phases, incomplete children, budget deferrals,
+abort/lock loss, and successful warning-only controls.
### Test command tiers
diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.md
index 534d9ef9a5..d2dcc0d967 100644
--- a/docs/architecture/KEY_FILES.md
+++ b/docs/architecture/KEY_FILES.md
@@ -10,14 +10,14 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/runtime-version.ts` — Bun 1.3.11 minimum enforced by the CLI entrypoint and guarded HTTP transport, with upgrade/restart guidance. Package engines and runtime checks share the same supported floor.
- `src/core/data-frontmatter.ts` — shared data-only YAML/JSON parsing and serialization. Rejects unsupported language selectors before parsing, uses js-yaml safe schema with existing scalar types, sanitizes parser errors, and keeps body text opaque. Used by markdown, capture, recipes, plugins, and greenfield ingestion. Independent fixtures: `test/data-frontmatter.test.ts`, `test/frontmatter-security.test.ts`.
-- `src/core/oauth-grants.ts` — client-row-locked grant transactions shared by OAuth issuance, code/refresh consumption, and revocation. Preserves scope/resource ceilings and rolls back consumption with replacement writes. Bounded pending consent requests snapshot current operation and delegation policies. `src/commands/serve-http-oauth.ts` authenticates request details and enforces session-bound CSRF decisions; `admin/src/pages/OAuthConsent.tsx` renders the existing admin login/approval flow without exposing protected details in the page shell.
+- `src/core/oauth-grants.ts` — client-row-locked grant transactions shared by OAuth issuance, code/refresh consumption, and revocation. Preserves scope/resource ceilings and rolls back consumption with replacement writes. Bounded pending consent requests snapshot current operation and delegation policies. `src/commands/serve-http-oauth.ts` authenticates request details, enforces session-bound CSRF decisions, and adds a read-only bootstrap scope hint to scope-less Bearer challenges without changing token authority; `admin/src/pages/OAuthConsent.tsx` renders the existing admin login/approval flow without exposing protected details in the page shell.
- `src/core/minions/submission-authority.ts` — versioned authority kept outside caller job data. Submission normalization and worker revalidation bind remote jobs to immutable principal/grant/source/payload ceilings; application authority preserves trusted internal work. `src/core/minions/authorize-legacy.ts` provides explicit local preview and transactional snapshot comparison for selected historical rows. `src/core/minions/source-filesystem.ts` provides reentrant canonical root/worktree locking and descriptor-based confined reads/writes. Both worker modes enforce the same authority gate. Upgrade protocol: `docs/guides/authorization-upgrade.md`.
- `src/core/guarded-http.ts` + `src/core/ssrf-validate.ts` — DNS answer classification, validated-address connections with original TLS/HTTP hostname and port, shared deadline/redirect policy, header-only probes, and bounded gzip/deflate/Brotli decoding. Ambient proxies fail closed with restart guidance. Consumers: URL reachability, remote images, and HTTP integration checks. Real TLS fixtures run on Bun 1.3.11 and 1.3.13.
- `docs/operations/conversation-parser-llm-fallback.md` — operator and maintainer contract for the default-off LLM parse fallback: exact config key, deterministic-first dispatch boundary, sampled data surface, untrusted-content prompt handling, page-date/cache-key coupling, timestamp validation, cache/checkpoint behavior, observability, limitations, and focused test commands.
-- `src/core/operations.ts` — Contract-first operation contract, served through a ~300-line assembly façade: the op definitions live in the domain modules under `src/core/ops/` (next entry) and are spread into the single exported `operations` array here; the shared contract types (`src/core/ops/contract.ts`) and the security/scope layer (`src/core/ops/context.ts`) are re-exported through this file, so every import path below resolves through the façade unchanged. The rest of this entry describes the surface as consumers see it. Same-source graph mutations (`add_link`, `add_timeline_entry`) preflight each endpoint against the scalar write source via `requireWritablePage` (`ops/context.ts`): a page readable only from another granted source returns endpoint-specific `permission_denied` naming the boundary, pages outside the caller's `get_page` visibility scope stay `page_not_found` (a soft-deleted foreign page is indistinguishable from absence), and a mutation-time engine miss — the typed `PageMissingError` from `src/core/engine-errors.ts`, thrown by both engines' single-statement endpoint resolution — is reclassified into the same envelope by `instanceof`, never message matching. Exports upload validators `validateUploadPath`, `validatePageSlug`, `validateFilename`, plus `matchesSlugAllowList(slug, prefixes)` (glob matcher: `<prefix>/*` matches recursive children; bare `<prefix>` matches exact only). `OperationContext.remote` is a REQUIRED field flagging untrusted callers; `OperationContext.allowedSlugPrefixes` is the trusted-workspace allow-list set by the dream cycle; `OperationContext.auth?: AuthInfo` is threaded through HTTP dispatch for scope enforcement in `serve-http.ts` before the op runs. OAuth `whoami` exposes the authenticated `AuthInfo.sourceId` and `AuthInfo.allowedSources` grants as `source_id` and `federated_read`; absent grants serialize fail-closed as `null` and `[]`, while local, legacy, and stdio response shapes stay unchanged. `enforceSubagentSlugFence(ctx, slug, opName)` is the shared fail-closed subagent write fence: when `viaSubagent` and `allowedSlugPrefixes` is set, the slug must match the allow-list; else the legacy `wiki/agents/<id>/...` namespace check applies. Both `put_page` and `add_timeline_entry` (subagent-allowlisted) route through it. Auto-link/timeline hooks are skipped for remote-owned subagents even with explicit prefixes; only local subagents qualify as trusted workspaces. `enforceClientSlugFence(ctx, slug, opName)` is the OAuth-client write fence: when `ctx.auth.boundSlugPrefixes` is present (threaded from `oauth_clients.bound_slug_prefixes` at token-verification time), every direct slug-mutating write op — `put_page`, `delete_page`, `restore_page`, `add_tag`, `remove_tag`, `add_link`/`remove_link` (`from` endpoint only; linking TO a readable page is a reference), `add_timeline_entry`, `revert_version`, `put_raw_data` — rejects out-of-prefix slugs with `permission_denied`, BEFORE each op's dry-run short-circuit. Direct writes use the shared boundary-aware prefix rules; empty-array binding is deny-all (fail-closed); no auth / no binding = no fence. The match rule itself lives in the exported `slugUnderBoundPrefixes(prefixes, slug)` so non-op write surfaces reuse it verbatim. It is BOUNDARY-AWARE (a prefix matches whole segments, so `emp-alice` does not admit `emp-alice-2/…`), lowercases both sides (stored slugs are lowercased by `validateSlug`, so comparing the caller's raw string would let a mixed-case slug commit and only then trip the resolved-slug re-check), accepts BOTH the trailing-slash and the `<prefix>/*` glob spelling via `normalizeSlugPrefix` (direct and delegated fences share normalization while storing independently reviewed spans), and ignores empty-string prefixes. `assertValidSlugPrefixes` (`oauth-provider.ts`) rejects empty, whitespace-bearing, non-lowercase, and boundary-less entries at registration and rescope. `submit_agent` validates tools and namespaces against the independently stored `bound_tools`, `delegated_slug_prefixes`, and `delegated_namespace` grants. It normalizes accepted prefixes for `matchesSlugAllowList` and rejects explicit empty remote tool or prefix overrides. Workers interpret explicit empty tool lists as no tools, with defaults reserved for absent trusted-local bindings. `put_page` additionally fences the RESOLVED slug when importFromContent's dedup pre-check redirects the write to a different page (same content_hash / `frontmatter.id`), since the disk write-through runs against that slug. That re-check applies whichever confinement the CALLER is under — OAuth binding and/or subagent allow-list/legacy namespace — via `slugOutsideCallerFence(ctx, slug)`, which composes `slugUnderBoundPrefixes` with the subagent fence's own match rule: the delegated `submit_agent` → subagent context carries `viaSubagent` + `allowedSlugPrefixes` while its `auth` carries current read scope without the parent's direct-write fence, so an auth-only check would let a slug-bound client holding `agent` scope reach an out-of-fence page simply by delegating the write. Denials never name the resolved slug (it would be a slug-enumeration oracle). Pinned by `test/put-page-dedup-fence.test.ts`. `CLIENT_FENCED_WRITE_OPS` + `enforceBoundClientOpAllowList(auth, op)` are the fail-closed companion, applied once in `src/mcp/dispatch.ts` (the choke point both MCP transports share): a slug-bound client calling ANY `write`/`admin` op not on the allow-list gets `permission_denied`. This covers the ops that write by a key other than a slug and therefore cannot be fenced — `extract_entities`/`extract_facts` (mutate `people/*`, `companies/*`), `forget_fact` (numeric fact id, crosses sources), `ontology_propose` — and makes a write op added later denied-by-default instead of silently unfenced. `think` is on the allow-list because remote callers cannot persist from it. Pinned by `test/client-slug-fence.test.ts` and over-the-wire by `test/e2e/qm-provisioning.test.ts`. Every `Operation` carries `scope?: 'read' | 'write' | 'admin'` + `localOnly?: boolean`; `think` is read-scoped for OAuth/MCP because remote callers have `save`/`take` forced off before persistence, while local CLI can still persist via `remote:false`; `sync_brain`, `file_upload`, `file_list`, `file_url` are `admin + localOnly` (rejected over HTTP). Four trust-boundary call sites (`put_page` allowlist, file_upload trust-narrowing, submit_job protected-name guard, auto-link skip) use FAIL-CLOSED semantics: `ctx.remote === false` for trusted-only sites, `ctx.remote !== false` for "untrust unless explicit-false" — anything not strictly `false` is treated as remote (so a read+write OAuth token over HTTP MCP cannot submit `shell` jobs). `sourceScopeOpts(ctx)` encodes the source-scoped read precedence ladder — federated array (`ctx.auth.allowedSources`) wins over scalar (`ctx.sourceId`/`ctx.auth.sourceId`) over nothing; every read-side op handler routes through it so a source-bound OAuth client can't see neighboring sources via `search`/`query`/`list_pages`/`get_page`/`find_experts`/query's image path, plus the by-slug reads `get_tags`/`get_links`/`get_backlinks`/`get_timeline`/`get_chunks` (chunks follow the same ladder as `get_page`, so a federated grant that can open a page can read its chunks — and the chunk payload never carries embedding vectors) (and `get_page`'s tag fetch, which resolves against the concrete page's own `source_id`). `assertExplicitSourceLive(ctx, sourceIdParam)` is the async companion for the ops that accept a per-call `source_id` (`get_page`, `list_pages`, `search`, `query`): called right after `federatedSearchScope` (so the grant check has already run and it can only name a granted source), an explicit id with no live unarchived `sources` row throws `unknown_source` instead of silently scoping the read to an empty source — the CLI's `--source` existence rule applied to the op path; `__all__` and an omitted param skip it. `linkReadScopeOpts(ctx)` is the link-read sibling for `get_links`/`get_backlinks`: a link row references three pages (from/to/origin), and the engine's federated (`sourceIds[]`) branch scopes ALL THREE while its scalar (`sourceId`) branch scopes only the near endpoint (by design — trusted internal callers like `reconcileLinks` and back-link validators call the engine with a scalar scope and need the cross-source view). For an UNTRUSTED remote caller (`ctx.remote !== false`) carrying only a scalar scope it promotes that scope to a single-element `sourceIds:[id]`, routing them through the all-endpoint branch so a far/origin slug from outside the grant isn't disclosed; a federated array passes through unchanged and trusted local CLI (`ctx.remote === false`) keeps the scalar cross-source view. `thinkSourceScopeOpts(ctx)` maps the same precedence ladder onto `runThink`'s public options (`allowedSources`/`sourceId`) so the `think` op's gather and trajectory stages inherit the caller's source grant. `put_page`'s inline disk write-through is the shared `writePageThrough` helper (`src/core/write-through.ts`), ATOMIC via temp-sibling + rename so a crash or concurrent `gbrain sync` can't read a half-written `.md`; same helper backs `gbrain brainstorm/lsd --save`. Link provenance surface: `add_link` (`gbrain link`/`link-add`) + `remove_link` (`gbrain unlink`/`link-rm`) expose `link_source`/`link_type`; `add_link` rejects the reconciliation-managed built-ins via `MANAGED_LINK_SOURCES` (`markdown`/`frontmatter`/`mentions`/`wikilink-resolved`) and defaults omitted provenance to `'manual'` (the engine's own default stays `'markdown'` for internal callers); `list_link_sources` (`gbrain link-sources`, read) lists provenances via `sourceScopeOpts`. CLI aliases register through `cliHints.aliases` (collision-guarded in `src/cli.ts`).
+- `src/core/operations.ts` — Contract-first operation contract, served through a ~300-line assembly façade: the op definitions live in the domain modules under `src/core/ops/` (next entry) and are spread into the single exported `operations` array here; the shared contract types (`src/core/ops/contract.ts`) and the security/scope layer (`src/core/ops/context.ts`) are re-exported through this file, so every import path below resolves through the façade unchanged. The rest of this entry describes the surface as consumers see it. Same-source graph mutations (`add_link`, `add_timeline_entry`) preflight each endpoint against the scalar write source via `requireWritablePage` (`ops/context.ts`): a page readable only from another granted source returns endpoint-specific `permission_denied` naming the boundary, pages outside the caller's `get_page` visibility scope stay `page_not_found` (a soft-deleted foreign page is indistinguishable from absence), and a mutation-time engine miss — the typed `PageMissingError` from `src/core/engine-errors.ts`, thrown by both engines' single-statement endpoint resolution — is reclassified into the same envelope by `instanceof`, never message matching. Exports upload validators `validateUploadPath`, `validatePageSlug`, `validateFilename`, plus `matchesSlugAllowList(slug, prefixes)` (glob matcher: `<prefix>/*` matches recursive children; bare `<prefix>` matches exact only). `OperationContext.remote` is a REQUIRED field flagging untrusted callers; `OperationContext.allowedSlugPrefixes` is the trusted-workspace allow-list set by the dream cycle; `OperationContext.auth?: AuthInfo` is threaded through HTTP dispatch for scope enforcement in `serve-http.ts` before the op runs. OAuth `whoami` exposes the authenticated `AuthInfo.sourceId` and `AuthInfo.allowedSources` grants as `source_id` and `federated_read`; absent grants serialize fail-closed as `null` and `[]`, while local, legacy, and stdio response shapes stay unchanged. `enforceSubagentSlugFence(ctx, slug, opName)` is the shared fail-closed subagent write fence: when `viaSubagent` and `allowedSlugPrefixes` is set, the slug must match the allow-list; else the legacy `wiki/agents/<id>/...` namespace check applies. Both `put_page` and `add_timeline_entry` (subagent-allowlisted) route through it. Auto-link/timeline hooks are skipped for remote-owned subagents even with explicit prefixes; only local subagents qualify as trusted workspaces. `enforceClientSlugFence(ctx, slug, opName)` is the OAuth-client write fence: when `ctx.auth.boundSlugPrefixes` is present (threaded from `oauth_clients.bound_slug_prefixes` at token-verification time), every direct slug-mutating write op — `put_page`, `delete_page`, `restore_page`, `add_tag`, `remove_tag`, `add_link`/`remove_link` (`from` endpoint only; linking TO a readable page is a reference), `add_timeline_entry`, `revert_version`, `put_raw_data` — rejects out-of-prefix slugs with `permission_denied`, BEFORE each op's dry-run short-circuit. Direct writes use the shared boundary-aware prefix rules; empty-array binding is deny-all (fail-closed); no auth / no binding = no fence. The match rule itself lives in the exported `slugUnderBoundPrefixes(prefixes, slug)` so non-op write surfaces reuse it verbatim. It is BOUNDARY-AWARE (a prefix matches whole segments, so `emp-alice` does not admit `emp-alice-2/…`), lowercases both sides (stored slugs are lowercased by `validateSlug`, so comparing the caller's raw string would let a mixed-case slug commit and only then trip the resolved-slug re-check), accepts BOTH the trailing-slash and the `<prefix>/*` glob spelling via `normalizeSlugPrefix` (direct and delegated fences share normalization while storing independently reviewed spans), and ignores empty-string prefixes. `assertValidSlugPrefixes` (`oauth-provider.ts`) rejects empty, whitespace-bearing, non-lowercase, and boundary-less entries at registration and rescope. `submit_agent` validates tools and namespaces against the independently stored `bound_tools`, `delegated_slug_prefixes`, and `delegated_namespace` grants. It normalizes accepted prefixes for `matchesSlugAllowList` and rejects explicit empty remote tool or prefix overrides. Workers interpret explicit empty tool lists as no tools, with defaults reserved for absent trusted-local bindings. `put_page` additionally fences the RESOLVED slug when importFromContent's dedup pre-check redirects the write to a different page (same content_hash / `frontmatter.id`), since the disk write-through runs against that slug. That re-check applies whichever confinement the CALLER is under — OAuth binding and/or subagent allow-list/legacy namespace — via `slugOutsideCallerFence(ctx, slug)`, which composes `slugUnderBoundPrefixes` with the subagent fence's own match rule: the delegated `submit_agent` → subagent context carries `viaSubagent` + `allowedSlugPrefixes` while its `auth` carries current read scope without the parent's direct-write fence, so an auth-only check would let a slug-bound client holding `agent` scope reach an out-of-fence page simply by delegating the write. Denials never name the resolved slug (it would be a slug-enumeration oracle). Pinned by `test/put-page-dedup-fence.test.ts`. `CLIENT_FENCED_WRITE_OPS` + `enforceBoundClientOpAllowList(auth, op)` are the fail-closed companion, applied once in `src/mcp/dispatch.ts` (the choke point both MCP transports share): a slug-bound client calling ANY `write`/`admin` op not on the allow-list gets `permission_denied`. This covers the ops that write by a key other than a slug and therefore cannot be fenced — `extract_entities`/`extract_facts` (mutate `people/*`, `companies/*`), `forget_fact` (numeric fact id, crosses sources), `ontology_propose` — and makes a write op added later denied-by-default instead of silently unfenced. `think` is on the allow-list because remote callers cannot persist from it. Pinned by `test/client-slug-fence.test.ts` and over-the-wire by `test/e2e/qm-provisioning.test.ts`. Every `Operation` carries `scope?: 'read' | 'write' | 'admin'` + `localOnly?: boolean`; `think` is read-scoped for OAuth/MCP because remote callers have `save`/`take` forced off before persistence, while local CLI can still persist via `remote:false`; `sync_brain`, `file_upload`, `file_list`, `file_url` are `admin + localOnly` (rejected over HTTP). Four trust-boundary call sites (`put_page` allowlist, file_upload trust-narrowing, submit_job protected-name guard, auto-link skip) use FAIL-CLOSED semantics: `ctx.remote === false` for trusted-only sites, `ctx.remote !== false` for "untrust unless explicit-false" — anything not strictly `false` is treated as remote (so a read+write OAuth token over HTTP MCP cannot submit `shell` jobs). `sourceScopeOpts(ctx)` encodes the source-scoped read precedence ladder — federated array (`ctx.auth.allowedSources`) wins over scalar (`ctx.sourceId`/`ctx.auth.sourceId`) over nothing; every read-side op handler routes through it so a source-bound OAuth client can't see neighboring sources via `search`/`query`/`list_pages`/`get_page`/`find_experts`/query's image path, plus the by-slug reads `get_tags`/`get_links`/`get_backlinks`/`get_timeline`/`get_chunks` (chunks follow the same ladder as `get_page`, so a federated grant that can open a page can read its chunks — and the chunk payload never carries embedding vectors) (and `get_page`'s tag fetch, which resolves against the concrete page's own `source_id`). `assertExplicitSourceLive(ctx, sourceIdParam)` is the async companion for the ops that accept a per-call `source_id` (`get_page`, `list_pages`, `search`, `query`): called right after `federatedSearchScope` (so the grant check has already run and it can only name a granted source), an explicit id with no live unarchived `sources` row throws `unknown_source` instead of silently scoping the read to an empty source — the CLI's `--source` existence rule applied to the op path; `__all__` and an omitted param skip it. `linkReadScopeOpts(ctx)` is the link-read sibling for `get_links`/`get_backlinks`: a link row references three pages (from/to/origin), and the engine's federated (`sourceIds[]`) branch scopes ALL THREE while its scalar (`sourceId`) branch scopes only the near endpoint (by design — trusted internal callers like `reconcileLinks` and back-link validators call the engine with a scalar scope and need the cross-source view). For an UNTRUSTED remote caller (`ctx.remote !== false`) carrying only a scalar scope it promotes that scope to a single-element `sourceIds:[id]`, routing them through the all-endpoint branch so a far/origin slug from outside the grant isn't disclosed; a federated array passes through unchanged and trusted local CLI (`ctx.remote === false`) keeps the scalar cross-source view. `thinkSourceScopeOpts(ctx)` maps the same precedence ladder onto `runThink`'s public options (`allowedSources`/`sourceId`) so the `think` op's gather and trajectory stages inherit the caller's source grant. `put_page`'s inline disk write-through is the shared `writePageThrough` helper (`src/core/write-through.ts`), ATOMIC via temp-sibling + rename so a crash or concurrent `gbrain sync` can't read a half-written `.md`; same helper backs `gbrain brainstorm/lsd --save`. `put_page` acquires the root lock before publishing a revision, returns `storage_busy` with an explicit not-applied/not-queued result on acquisition contention, and reports post-persistence embedding outcomes separately. No durable queue or caller revision precondition is implied. Link provenance surface: `add_link` (`gbrain link`/`link-add`) + `remove_link` (`gbrain unlink`/`link-rm`) expose `link_source`/`link_type`; `add_link` rejects the reconciliation-managed built-ins via `MANAGED_LINK_SOURCES` (`markdown`/`frontmatter`/`mentions`/`wikilink-resolved`) and defaults omitted provenance to `'manual'` (the engine's own default stays `'markdown'` for internal callers); `list_link_sources` (`gbrain link-sources`, read) lists provenances via `sourceScopeOpts`. CLI aliases register through `cliHints.aliases` (collision-guarded in `src/cli.ts`).
- `src/core/ops/` — the operations contract's module directory (the meat behind the `operations.ts` façade). `contract.ts` is the foundation contract: the error envelope (`ErrorCode`/`OperationError`/`verbError`), the shared param/logger/auth/context types, and the `Operation` interface — re-exported wholesale by the façade. `context.ts` carries the context validators + scope resolvers: the upload/slug/filename validators, the subagent and bound-client slug fences, and the source-scope resolution ladder (some internal helpers are exported only here and deliberately NOT re-exported from the façade — import those from `context.ts` directly). The remaining modules are one-per-op-domain (`pages.ts`, `search.ts`, `takes.ts`, `tags.ts`, `links.ts`, `timeline.ts`, `admin.ts`, `skills-catalog.ts`, `sync-status.ts`, `raw-data.ts`, `chunks.ts`, `ingest-log.ts`, `files.ts`, `jobs.ts`, `orphans.ts`, `calibration.ts`, `salience.ts`, `facts.ts`, `sources.ts`, `transcripts.ts`, `insights.ts`, `image.ts`, `extraction.ts`, `code-intel.ts`, `chronicle.ts`, `embedding-migration.ts`, `request-tools.ts`, `schema-packs.ts`, `skillopt.ts`), each exporting a `<domain>Operations` map that the façade spreads into the single `operations` export. Add a new op in the matching domain module — an existing domain needs no façade change; a brand-new domain module gets one spread line in `operations.ts`. `facadeExpansion` in `scripts/generate-flag-registry.ts` maps the façade to this whole directory so every module's `--flag` text stays on the command flag-scan surface.
- `src/core/ops/links.ts` — the link-domain op module (`add_link`, `remove_link`, `get_links`, `get_backlinks`, `list_link_sources`, `traverse_graph`). Two load-bearing behaviors. (1) Pack vocabulary at the write surface: an EXPLICIT `link_type` on `add_link` must be declared by the active schema pack when one resolves (`schema-pack/write-vocabulary.ts`; no resolvable pack = no enforcement; omitted/empty link_type is the untyped-edge default and stays unchecked; the check runs before the dry-run return so dry runs preview the rejection). (2) `traverse_graph` output shape: trusted local no-filter callers (`ctx.remote === false`, no `link_type`/`direction`) keep the legacy `GraphNode[]` shape that `gbrain graph` renders; remote callers default to `direction: 'both'` and always receive explicit `GraphPath[]` edges, so a page whose typed edges are all inbound does not read as edge absence. An explicit `direction` param wins for every caller. Depth: default 5 (`DEFAULT_TRAVERSE_DEPTH`), except a remote call that let direction default to `both` ALSO defaults depth to `REMOTE_BIDIRECTIONAL_DEFAULT_DEPTH` (2) — bidirectional path enumeration is combinatorial on entity hubs and this is the per-agent-turn path; a `link_type`-only remote call still takes both/2; an explicit depth is honored up to `TRAVERSE_DEPTH_CAP` (10, clamped with a warn). The edge walk runs through `engine.traversePathsDetailed`, and a hit on `TRAVERSE_PATH_ROW_CAP` (`engine-constants.ts`) surfaces as a stderr warn naming the cap (shallowest edges kept) — the `GraphPath[]` wire shape stays unchanged. Pinned by `test/traverse-graph-op-default.test.ts` + `test/traverse-paths-row-cap.test.ts`.
- `src/core/ops/pages.ts` — the page-domain op module (`get_page`, `put_page`, `delete_page`/`restore_page`, `capture`, …; the source-scoping contract of the delete/restore trio is described under `src/core/destructive-guard.ts`). `get_page` resolution ladder: exact read in the caller's scope → alias hop → fuzzy. The alias hop scopes its lookup to the federated grant (`sourceIds[]`) > the scalar `sourceId` > (trusted unscoped only) every LIVE source — archived sources' alias rows count only when `include_deleted` asks for archived material — through `engine.resolveSlugWithAliasDetailed`, then reads the canonical page IN THE SOURCE THAT OWNS THE ALIAS ROW (`getPage(canonical, { sourceId: hit.source_id })`): a federated `getPage` prefers the anchor source, so an unrelated live page at the canonical slug in another granted source would otherwise shadow the alias owner's page. The redirect target composes with the same private-page gate as the exact read and reports `resolved_slug`. `capture`: an EXPLICIT type (the `type` param, else a frontmatter `type:` in the content — `explicitCaptureType` in `src/core/capture-content.ts`, BOM/CRLF tolerant, malformed YAML → none) is validated against the active pack when one resolves (`schema-pack/write-vocabulary.ts`) and IS the effective type for both the default slug and the merged frontmatter — approved as X, stored as X; no explicit type stamps `note` (never checked). Sits at its module-size ratchet ceiling (`scripts/module-size-limits.tsv`); the next growth peels a submodule. Pinned by `test/get-page-federated-scope.test.ts`, `test/capture-explicit-type.test.ts`, and the engine-parity suite (both engines pick the same owning row). The alias hop has no catch of its own: both engines return `null` for the pre-v104 missing-table case, so any other rejection (connection reset, timeout) propagates instead of degrading to `page_not_found`.
@@ -47,7 +47,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/engine-factory.ts` — Engine factory with dynamic imports (`'pglite'` | `'postgres'`).
- `src/core/pglite-engine.ts` — PGLite (embedded Postgres 17.5 via WASM) implementation, all BrainEngine methods. The facts/takes/code-edges/salience method clusters are implemented in narrow-deps modules under `src/core/pglite-engine/` (see the engine-module-dirs entry below); the class methods delegate to them and the façade keeps its full public surface. `listLinkSources({sourceId?, sourceIds?})` returns distinct `link_source` provenances + counts (`ORDER BY count DESC, link_source ASC NULLS LAST`; scalar + federated scoped; parity with postgres-engine.ts) powering `gbrain link-sources`. `addLinksBatch`/`addTimelineEntriesBatch`/`addTakesBatch` pass the whole batch as one JSONB document via `jsonb_to_recordset(($1::jsonb)->'rows')` (bound through `executeRawJsonb` with a `{ rows }` wrapper; rows built by the shared `src/core/batch-rows.ts` helpers, NUL-stripped), and are `batchRetry`-wrapped. `connect()` wraps `PGlite.create()` in a try/catch that classifies the failure and, for the `wasm-abort` verdict on a persistent data dir (torn WAL/checkpoint state after an unclean shutdown; it presents like a macOS WASM bug but is not one), runs in-place auto-repair via `attemptWalRepairAndRetry` (static import from `pglite-repair.ts`, per the engine-live rule; the retry create is `preservingProcessExitCode`-wrapped; success sets the public `walRepairReceipt` field + prints `buildWalRepairNotice` to stderr and returns with the lock held). The seam never throws, so every non-repaired path funnels through the single lock-release-then-throw site; repair refuses when the lock was acquired by reaping (`LockHandle.reaped` → `'possibly-live-writer'`), when disabled (`GBRAIN_PGLITE_WAL_REPAIR=off`), on layout-validation failure, or inside the post-failure cooldown. `disconnect()` early-nulls the handle (so no NEW statement can reach it), then runs `drainBackgroundWorkBeforeDisconnect()` so statements ALREADY in flight settle against the still-open handle — PGLite's `close()` deadlocks permanently (close's promise AND the in-flight query's promise never settle) with a statement in flight; the ordering is load-bearing (drain above the null would let a new statement race the close). Teardown defense is layered and honestly scoped: the drain PREVENTS the known wedge; the in-loop close bound (`GBRAIN_PGLITE_CLOSE_TIMEOUT_MS`, default 5000ms, floor 1s, ceiling 2^31−1, read per call) covers ONLY a close that still yields to the event loop — armed BEFORE `close()` is called and deliberately ref'd, a timed-out close degrades to a once-per-process stderr warning naming both env knobs and teardown proceeds (an abandoned close's later rejection is swallowed; the WAL-repair path covers a zombie instance on next open); a close that WEDGES the loop (blocked or microtask-starved) can never be caught by any same-loop timer and is observable/killable only by the opt-in out-of-band watchdog — a diagnostic/incident instrument, not ambient production protection: `GBRAIN_PGLITE_CLOSE_WATCHDOG_MS` (unset/0 = off; a positive value clamps UP to `max(5000, registered-sink-count×2000 + close timeout + 2000)` with a warn so a units typo never SIGKILLs a healthy slow teardown) + `GBRAIN_PGLITE_CLOSE_WATCHDOG_GRACE_MS` (default 30000) arm the shared `process-watchdog.ts` worker around a PGLite disconnect with a live handle (armed after the early-return, before the drain; disposed in a nested finally so a `releaseLock` throw can't leak it; SIGTERM at deadline, SIGKILL at deadline+grace; lock-only teardown and postgres pool teardown are out of scope). Pinned by `test/pglite-engine-disconnect.serial.test.ts` + `test/search-telemetry-disconnect-hang.serial.test.ts` + `test/pglite-disconnect-watchdog.serial.test.ts` (spawned fixture that genuinely starves the loop) + the structural pins in `test/fix-wave-structural.test.ts`. `searchKeyword`/`searchKeywordChunks` multiply `ts_rank` by the source-factor CASE at chunk grain; `searchVector` is a two-stage CTE — inner CTE keeps `ORDER BY cc.embedding <=> vec` so HNSW stays usable, outer SELECT re-ranks by `raw_score * source_factor`, inner LIMIT scales with offset to preserve pagination. `searchTakes`/`searchTakesVector` take full `SearchOpts` and apply the standard source-scope predicates (federated `sourceIds[]` wins over scalar `sourceId`, via the joined page's `source_id`) alongside the holder allow-list — parity SQL in postgres-engine.ts; pinned by `test/e2e/think-source-isolation-pglite.test.ts`. `initSchema()` calls `applyForwardReferenceBootstrap()` BEFORE replaying SCHEMA_SQL — probes for forward-referenced state the embedded blob needs (`pages.source_id`, `links.link_source`, `links.origin_page_id`, `content_chunks.symbol_name`, `content_chunks.language`, `sources` FK target, plus `files.source_id`, `files.page_id`, `oauth_clients.source_id`, `oauth_clients.federated_read`, `sources.archived`, `sources.archived_at`, `sources.archive_expires_at`, `timeline_entries.event_page_id` — column-only, migration v121 stays the source of truth for its FK + indexes) and adds only what's missing; threads the DDL connection from `initSchema` so probes run inside the advisory-lock scope; no-op on fresh installs and current brains (this is what keeps an upgrade from wedging on a forward-referenced column). `getBrainScore` returns 100/100 with full breakdown (35/25/15/15/10) when `pageCount === 0` (vacuous truth — empty brain has no coverage problem); Pinned by `test/brain-score-breakdown.test.ts` empty-brain assertion + `test/doctor-report-remote.serial.test.ts`. `disconnect()` uses snapshot+early-null (snapshot `_db`/`_lock`, null instance fields BEFORE any `await` so a concurrent `connect()` can't see a partial mid-close state) wrapped in try/finally guaranteeing lock-release even if `db.close()` throws; KEEPS close-then-release order (release-then-close was rejected: it would widen the window where a sibling process connects to a still-closing brain); Pinned by `test/pglite-engine-disconnect.serial.test.ts`. `PGlite.create()` runs inside `preservingProcessExitCode`: PGLite's Emscripten runtime writes its own status into `process.exitCode` (99 at create; in-memory brains run initdb whose status lands on a later tick; the exit status at close — and assigning `undefined` cannot clear a prior value), which would otherwise silently clobber an errored op's exit 1 back to 0. The wrapper keeps the global tidy for external readers; `db.close()` stays unwrapped (its 0-write is baseline behavior test runners depend on). The CLI's exit verdict is immune either way — it lives in the gbrain-owned channel in `cli-force-exit.ts` and never reads `process.exitCode` back. Exports `classifyPgliteInitError(message): 'bunfs' | 'wasm-abort' | 'corrupt' | 'unknown'` + `buildPgliteInitErrorMessage(verdict, original, platform?, ctx?)` + `stringifyPgliteInitError(err)` + `buildWalRepairNotice(receipt)` + the `PgliteInitRepairContext` type, routing the catch-block hint by failure shape (`bunfs` matches literal `$$bunfs` OR `ENOENT[\s\S]*pglite\.data` co-occurrence, surfaces a paste-ready `bun upgrade` + Node fallback; `corrupt` — 58P01/`internal_load_library`/missing vector type, catalog corruption WAL repair can't fix — stays matched BEFORE the wasm arm and routes to `reinit-pglite`; `wasm-abort` matches the real production shapes `Aborted()`/`RuntimeError`/`unreachable` plus legacy signatures, names the corrupt-WAL root cause + the recovery ladder (`pglite-repair` → rebuild → engine switch) + what auto-repair did per `ctx` incl. the honesty-critical `failed-not-restored` arm, and links the upstream tracking issue; `unknown` is platform-gated). `stringifyPgliteInitError` also surfaces message-less Emscripten objects (`ErrnoError (errno N)`) instead of `[object Object]`. Pinned by `test/pglite-init-classifier.test.ts` + `test/pglite-wal-repair.serial.test.ts` + `test/fix-wave-structural.test.ts`. Implements `deletePages(slugs, {sourceId})` + `resolveSlugsByPaths(paths, {sourceId})` via `slug = ANY($1::text[])` array-param binding, caller-chunking primitive throwing when input exceeds `DELETE_BATCH_SIZE`, `deletePages` returns `RETURNING slug` rows so callers filter `pagesAffected` to confirmed deletes. Implements the embedding-signature stale-detection quartet — `sumStaleChunkChars({sourceId?, signature?})`, `setPageEmbeddingSignature(slug, {sourceId?, signature})`, `invalidateStaleSignatureEmbeddings({signature, sourceId?})`, widened `countStaleChunks({sourceId?, signature?})` (the `signature` opt widens via `JOIN pages p ... WHERE cc.embedding IS NULL OR (p.embedding_signature IS NOT NULL AND p.embedding_signature <> $signature)`, NULL grandfathered); parity SQL with postgres-engine.ts. PGLite-specific DDL (pgvector, pg_trgm, triggers). Engine-path helper dependencies (`retry`, ontology, recency decay) avoid dynamic `import()`; the only lazy dynamic imports are `ai/gateway.ts` in `initSchema` and `_upsertChunksOnce`, line-marked because their local catches preserve compiled-default and stored-config fallbacks that eager module evaluation would bypass.
- `src/core/pglite-embedded-assets.ts` + `src/core/pglite-embedded-asset-paths.ts` — PGLite runtime-asset supply for every run mode (compiled binary, source checkout, bun-global install). `pglite-embedded-asset-paths.ts` is the bundler ANCHOR: five literal `with { type: 'file' }` imports of the wasm/data/extension-tarball assets via repo-relative node_modules paths (the package's `exports` map hides `./dist/*`) — keep the specifiers literal and byte-stable, an expression or indirection silently stops the bytes embedding and the compiled binary falls into the Bun-vfs ENOENT failure. `resolvePgliteAssetPaths()` in `pglite-embedded-assets.ts` is the tiered resolver: tier 1 dynamically `import()`s the anchor (the rejection under a hoisted install — bun-global upgrades dedupe `@electric-sql/pglite` to the global root, making the anchor's specifiers unresolvable — is EXPECTED and routes to tier 2, which is why the anchor is not a static import); tier 2 derives the dist dir via module resolution of `@electric-sql/pglite` (`import.meta.resolve` then `createRequire` — the SAME specifier the engine imports, so assets can never come from a different pglite copy than the loaded JS); tier 3 throws one actionable error naming everything tried, with the canonical GitHub reinstall command (never the npm-registry name, which is squatted — see the README install warning). `getEmbeddedPgliteOptions()` memoizes one build per process and hands PGLite compiled `WebAssembly.Module`s + fs-bundle Blob + materialized extension tarballs via `PGliteOptions`. Pinned by `test/pglite-embedded-assets.test.ts` + `test/pglite-hoisted-install.serial.test.ts` (real `bun add -g`-shaped hoisted layout).
-- `src/core/pglite-lock.ts` — advisory data-dir lock so two processes never open the same embedded PGLite (single-connection WASM Postgres) at once. Atomic `mkdir` of `.gbrain-lock/` + a `lock` file carrying `{pid, acquired_at, refreshed_at, command, subcommand}`. A held lock HEARTBEATS its `refreshed_at` every 30s (`.unref()`ed timer; informational). A waiting acquirer reaps a holder ONLY on affirmative proof of death — ESRCH from kill-0, or a `ps`-/`proc`-read command line proving the PID was recycled by a non-gbrain program under AFFIRMATIVE same-namespace proof (on Linux the lock's recorded `pid_ns` must be readable and equal ours, `boot_id` too when recorded; legacy locks without markers are never cmdline-reaped; unreadable cmdline and same-process PID also read as alive) — a LIVE holder is NEVER stolen, regardless of how stale its heartbeat is. Every reap serializes on an atomic claim dir (`tryReapLockDir`) and re-validates the victim's ownership token while the lock is still in place, so concurrent reapers can't delete each other's freshly installed locks; a crashed claimant's dir is broken after a 30s TTL / dead PID. A live `gbrain serve` holder is identified from the parsed `subcommand` and reported immediately with separate CLI-retry and MCP-tool choices; other live holders keep the bounded wait. `gbrain sync` normally never reaches this error under a live serve — the cli.ts preflight (`src/commands/sync-delegate.ts`) probes the lock file read-only and delegates the sync through the serve's IPC socket instead. The heartbeat runs on the JS event loop, which is blocked during long synchronous WASM imports/CHECKPOINTs, so a working `dream`/`embed` holder can look stale while alive; a steal-on-stale-heartbeat grace would let a second OS process open the same data dir and corrupt the catalog + pgvector extension (58P01 / `internal_load_library` / `type "vector" does not exist`), recoverable only by wipe+restore. A wedged-but-alive holder is never stolen: serve-tagged holders report immediately, while other holders time out with a message naming the PID. Each holder carries an ownership token (`<pid>:<acquired_at>`); the heartbeat and `releaseLock` verify the on-disk lock is STILL theirs before touching it. In-memory engines take no lock. There is deliberately NO same-process reentrancy or same-PID special case: a second `acquireLock` from the process that already holds the lock waits out the timeout like any other live holder (the classic cause is a command double-connecting a second engine on the same data dir; the fix is to reuse the connected engine at the dispatch layer, never to soften the lock). `LockHandle.reaped` marks an acquisition that reaped a prior holder's lock (dead-PID reap, PID-recycling reap, or corrupt-lock-file removal — the only reaps that exist); the WAL auto-repair gate refuses to run surgery on a reaped acquisition since a corrupt lock file cannot prove its holder is dead. A corrupt-lock reap ALSO writes a persisted marker (`<dataDir>.lock-reap.json`, read via exported `msSinceLastReap`) so the NEXT process's clean acquisition is still repair-quarantined for 10 minutes — the in-process flag alone would let the reaper's successor run surgery under a possibly-live writer; dead-PID reaps (affirmative ESRCH verdict; EPERM reads as ALIVE) deliberately skip the marker so dead-holder recovery stays one-failed-command-plus-one-re-run. Heartbeat refreshes write via tmp+rename (a torn in-place write could be read mid-flight by a polling acquirer and misclassify a HEALTHY live holder as a corrupt lock). Pinned by `test/pglite-lock.test.ts`. A corrupted store surfaces a `reinit-pglite` recovery hint via `classifyPgliteInitError`'s `corrupt` verdict in `pglite-engine.ts`. Exported `inspectLockHolder(dataDir): LockHolderInfo` is the READ-ONLY inspection seam for status surfaces (`gbrain engine status`, smoke-test): never reaps, never mkdirs, never blocks; a dead-PID holder reads as not-held, a live serve holder reads as `serve: true` so a probe can report `locked_by_serve` instead of hanging on the single-writer lock. `peekLock(dataDir)` is the pure read of the same lock — no `mkdir`, no acquisition side effect, never throws `LiveServeLockError` — so a third-party caller can tell "held by a live serve" apart from "available" without taking the lock itself; it reports not-held for a missing lock dir, a dead-PID holder, or an unreadable lock file, and is deliberately outside gbrain's own acquisition path, which is unchanged. Exported as `gbrain/pglite-lock`.
+- `src/core/pglite-lock.ts` — advisory data-dir lock so two processes never open the same embedded PGLite (single-connection WASM Postgres) at once. Atomic `mkdir` of `.gbrain-lock/` + a `lock` file carrying `{pid, acquired_at, refreshed_at, command, argv, subcommand}`. A held lock HEARTBEATS its `refreshed_at` every 30s (`.unref()`ed timer; informational). A waiting acquirer reaps a holder ONLY on affirmative proof of death — ESRCH from kill-0, or a `ps`-/`proc`-read command line (Windows uses the shared CIM probe) proving a mismatch with structured recorded argv under AFFIRMATIVE same-namespace proof (on Linux the lock's recorded `pid_ns` must be readable and equal ours, a readable, matching `boot_id` is also required; legacy locks without structured argv or required namespace markers are never cmdline-reaped; unreadable cmdline and same-process PID also read as alive) — a LIVE holder is NEVER stolen, regardless of how stale its heartbeat is. Every reap serializes on an atomic claim dir (`tryReapLockDir`) and re-validates the victim's ownership token while the lock is still in place, so concurrent reapers can't delete each other's freshly installed locks; a crashed claimant's dir is broken after a 30s TTL / dead PID. A live `gbrain serve` holder is identified from the parsed `subcommand` and reported immediately with separate CLI-retry and MCP-tool choices; other live holders keep the bounded wait. `gbrain sync` normally never reaches this error under a live serve — the cli.ts preflight (`src/commands/sync-delegate.ts`) probes the lock file read-only and delegates the sync through the serve's IPC socket instead. The heartbeat runs on the JS event loop, which is blocked during long synchronous WASM imports/CHECKPOINTs, so a working `dream`/`embed` holder can look stale while alive; a steal-on-stale-heartbeat grace would let a second OS process open the same data dir and corrupt the catalog + pgvector extension (58P01 / `internal_load_library` / `type "vector" does not exist`), recoverable only by wipe+restore. A wedged-but-alive holder is never stolen: serve-tagged holders report immediately, while other holders time out with a message naming the PID. Each holder carries an ownership token (`<pid>:<acquired_at>`); the heartbeat and `releaseLock` verify the on-disk lock is STILL theirs before touching it. In-memory engines take no lock. There is deliberately NO same-process reentrancy or same-PID special case: a second `acquireLock` from the process that already holds the lock waits out the timeout like any other live holder (the classic cause is a command double-connecting a second engine on the same data dir; the fix is to reuse the connected engine at the dispatch layer, never to soften the lock). `LockHandle.reaped` marks an acquisition that reaped a prior holder's lock (dead-PID reap, PID-recycling reap, or corrupt-lock-file removal — the only reaps that exist); the WAL auto-repair gate refuses to run surgery on a reaped acquisition since a corrupt lock file cannot prove its holder is dead. A corrupt-lock reap ALSO writes a persisted marker (`<dataDir>.lock-reap.json`, read via exported `msSinceLastReap`) so the NEXT process's clean acquisition is still repair-quarantined for 10 minutes — the in-process flag alone would let the reaper's successor run surgery under a possibly-live writer; dead-PID reaps (affirmative ESRCH verdict; EPERM reads as ALIVE) deliberately skip the marker so dead-holder recovery stays one-failed-command-plus-one-re-run. Heartbeat refreshes write via tmp+rename (a torn in-place write could be read mid-flight by a polling acquirer and misclassify a HEALTHY live holder as a corrupt lock). Pinned by `test/pglite-lock.test.ts`. A corrupted store surfaces a `reinit-pglite` recovery hint via `classifyPgliteInitError`'s `corrupt` verdict in `pglite-engine.ts`. Exported `inspectLockHolder(dataDir): LockHolderInfo` is the READ-ONLY inspection seam for status surfaces (`gbrain engine status`, smoke-test): never reaps, never mkdirs, never blocks; a dead-PID holder reads as not-held, a live serve holder reads as `serve: true` so a probe can report `locked_by_serve` instead of hanging on the single-writer lock. `peekLock(dataDir)` is the pure read of the same lock — no `mkdir`, no acquisition side effect, never throws `LiveServeLockError` — so a third-party caller can tell "held by a live serve" apart from "available" without taking the lock itself; it reports not-held for a missing lock dir, a dead-PID holder, or an unreadable lock file, and is deliberately outside gbrain's own acquisition path, which is unchanged. Exported as `gbrain/pglite-lock`.
- `src/core/pglite-resetwal.ts` — pg_resetwal for PGLite NodeFS data dirs, in TypeScript (a port of the electric-sql/pglite pg_resetwal contribution, PR #994, Apache-2.0). Validates the PG17 pg_control layout fail-closed (`WalResetUnsupportedError` on any unsupported shape — PG_VERSION ≠ 17, control ≠ 8192 bytes, control version ≠ 1700, bad seg/block size), removes stale postmaster.pid + old WAL segments + archive_status/summaries entries, writes a replacement shutdown-checkpoint WAL segment + CRC32C'd pg_control. Both file writes are atomic + durable (tmp cleared then opened `'wx'` so a pre-planted symlink at the predictable tmp name can never redirect the write, + fsync(tmp) + rename + fsync(parent dir)); write order is segment-first/control-last so a mid-write kill leaves a state that still fails startup and the next attempt re-runs (idempotent — a torn pair can never claim success). WAL segment size is capped at 64MB (pglite ships 16MB; the Postgres-general 1GB bound would let a corrupt-but-plausible control field drive a 1GB allocation on the repair path). Exports the shared PG17 layout literals (`PG_CONTROL_FILE_SIZE`, `isWalSegmentName`) consumed by pglite-repair.ts. LAYOUT COUPLING: any pglite bump past PG17 must revisit this file together with the `./vector` export blocker (TODOS.md "pglite upgrade blocker" entry). Pinned by `test/pglite-resetwal.test.ts`.
- `src/core/pglite-repair.ts` — WAL-repair orchestrator wrapping the resetWal port with the safety layers that make it runnable automatically from `connect()`: `validateWalRepairTarget` (read-only, fail-closed; refuses symlinked dataDir/pg_wal/`global`/pg_control — lstat follows INTERMEDIATE symlinks, so `global/` itself must be checked or surgery would write pg_control through it into a foreign dir; tolerates the in-dir `.gbrain-lock`), rename-based backup (the ENTIRE `pg_wal/` dir + postmaster.pid renamed into a sibling `<dataDir>.wal-repair-backup-<ts>/`, only the 8KB pg_control copied — zero transient disk cost), `restoreWalBackup` (overwrite order: control first via atomic tmp+rename, then a pg_wal dir swap with the reset dir set ASIDE inside the backup — nothing is ever deleted during restore; mtime guard refuses when a foreign segment is newer than the backup; a missing/empty backup NEVER reports `restored:true`), `WalRepairError` (thrown when resetWal fails AFTER the backup — carries the receipt + the best-effort restore's REAL result so the seam's `restored` flag and the `failed-restored`/`failed-not-restored` message arms never lie), a cooldown sidecar `<dataDir>.wal-repair-attempt.json` (skip `'recently-failed'` inside `GBRAIN_PGLITE_WAL_REPAIR_COOLDOWN_SECONDS`, default 3600 — bounds the autopilot/supervisor reconnect loops) with episode-scoped backups (attempts within one corruption episode REUSE the episode's first backup — the pre-damage forensic state, honored only when the sidecar's path is a real non-symlink `<dataDir>.wal-repair-backup-*` sibling since the sidecar is user-writable JSON; retention keeps the newest 3 episodes, never pruning the open episode's), and `attemptWalRepairAndRetry` — the engine seam that NEVER throws (gates: kill-switch → reaped-lock `'possibly-live-writer'` → 10-minute reap-marker quarantine (`msSinceLastReap`, cross-process) → validation → cooldown; then repair → retry create once → restore-and-record on failure; prints a repair-start stderr line so a timeout-killed attempt is self-explaining). `inspectPgliteDataDir` is the read-only diagnosis for `gbrain doctor` + `pglite-repair --dry-run`. Imports runtime values only from `pglite-lock.ts`/`pglite-resetwal.ts`/node:fs — never from `pglite-engine.ts` (no cycle; the engine statically imports THIS file per the engine-live rule). Pinned by `test/pglite-repair.test.ts` + `test/pglite-wal-repair.serial.test.ts`.
- `src/commands/pglite-repair.ts` — `gbrain pglite-repair`: the manual surface for WAL repair (`--dry-run | --yes | --json | --path <dir>`; CLI_ONLY + SELF_HELP; returns an exit code via `setCliExitVerdict`, never `process.exit`). Never connects an engine — works when the DB won't open and when auto-repair is disabled. `--dry-run` is strictly read-only. Its confirmation prompt (and `src/commands/reinit-pglite.ts`'s) writes to stderr so `--json` stdout stays clean, refuses non-TTY stdin in-prompt (defense-in-depth behind the caller-side "Non-TTY environment requires --yes" guard), resolves `false` on EOF/close instead of parking forever on a closed or piped stdin, and cleans up its listeners; `--yes`/`-y` stays the non-interactive path. The real run validates BEFORE locking (`acquireLock` mkdirs the data dir — a typo'd `--path` must not create directories), refuses a live lock holder (pre-lock diagnosis names the PID; a live `gbrain serve` is called out), refuses a reaped acquisition (`refused_reaped_lock` — no `--force` by design: force-removing `.gbrain-lock` would reopen the concurrent-writer hole), re-validates under the lock, repairs with episode-backup reuse, and records the attempt in the sidecar. Pinned by `test/pglite-repair-command.serial.test.ts`.
@@ -90,10 +90,10 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `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)` — 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 CLI teardown 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. `resolveMaxLifetimeSeconds(env?)` — explicit client-pool `max_lifetime` for all four postgres() call sites (matches the postgres.js implicit 30-60min jittered default; `GBRAIN_POOL_MAX_LIFETIME_S` overrides, 0 disables; warn-once on invalid). Pinned by `test/db-pool-max-lifetime.test.ts`.
- `src/core/pool-gauge.ts` — `CheckoutGauge`: approximate in-flight counters at the engine's raw/direct/reserved/tx seams, surfaced via duck-typed `PostgresEngine.getPoolDiagnostics()` (no BrainEngine change, no PGLite stub). HONESTY CONTRACT in the module doc: tagged-template traffic is untracked; consumers must label counts as a subset and never derive waiter/available figures. Fail-open (clamped release, try/finally around sync-throwing runUnsafe). Consumed by db-probe.ts. Pinned by `test/pool-gauge.test.ts`.
- `src/commands/migrate-engine.ts` — Bidirectional engine migration (`gbrain migrate --to supabase/pglite`). Copies the complete source catalog FIRST (`copyMigrationSources` — every `sources` row incl. archived rows and sync/routing metadata, `ON CONFLICT (id) DO UPDATE`, `default` ordered first) so every page write has a valid `pages.source_id` FK parent and the target preserves per-source behavior; pages copy afterward, tracked in the resume manifest by composite `(source_id, slug)` key. Link copy preserves each row's `to_source_id` (falling back to the origin source only for legacy rows without it), and failed-target filtering uses that same target composite key, so cross-source links migrate without being rebound to the origin source. The resume manifest is target-aware: `migrationTargetId(config)` hashes `(engine, locator)` (`database_url` for Postgres, resolved `database_path` for PGLite) and `manifestMatchesTarget` requires `schema_version === 2` plus a matching `target_id` — a legacy engine-only manifest, or one from a DIFFERENT target of the same engine kind, starts fresh instead of skipping "completed" pages the new target never received. After links, `copyMigrationFacts` carries the facts table verbatim (conversation facts have no markdown fence to re-sync from): source∩target column intersection via information_schema (older source schemas still copy), delete-and-recopy so every re-run converges to source truth, two-pass `superseded_by` restore (the self-FK points old→newer id, so id-ordered single-pass inserts would violate it), embeddings round-tripped as text into whichever physical type (`vector`/`halfvec`) the target column has with a NULL-embedding retry on per-row cast failure, and a `setval` bump so post-migration inserts don't collide with copied ids; fact-row failures block the config flip and force a non-zero exit, same contract as page failures. Takes are deliberately NOT copied (fence-canonical, keyed on target-reassigned `page_id`; the next extract cycle rebuilds them). `copyMigrationConfig` then copies EVERY DB-plane config row except the explicit engine-local denylist `MIGRATE_CONFIG_ENGINE_LOCAL_KEYS` (`engine`, `version` = target-owned schema ledger, `embedding_columns` + `search_embedding_column` = physical-column registry the copy doesn't materialize); skipped keys print in the end-of-run per-table copied-count summary, so nothing is dropped silently. Pinned by `test/migrate-engine-resume.test.ts` (manifest identity) + `test/e2e/migrate-engine-sources-postgres.test.ts` (source catalog lands before overlapping-slug pages, PGLite → real Postgres) + `test/e2e/multi-source-bug-class.test.ts` (cross-source links) + `test/migrate-engine-completeness.serial.test.ts` (facts chains/embeddings/sequence, config copy-all + denylist, summary).
-- `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 does not remove it from the DB on next sync (needs a `tag_source` provenance column). Pinned by `test/reindex-preserve-tags.test.ts` + `test/import-file.test.ts`. identity-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 (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`. `importCodeFile` writes `source_path: relativePath` on every code page (the same repo-relative path markdown imports record) so the full-sync reconcile — which only considers `source_path IS NOT NULL` rows — can retire a deleted code file's page; `putPage` COALESCEs the column, so rows imported before this keep NULL until the file changes or `gbrain reindex-code --force`.
+- `src/core/import-file.ts` — importFromFile + importFromContent (chunk + embed + tags). `beforeCommit` lets the page operation include canonical write-through inside the import transaction, including unchanged/legacy-hash paths; the indexed revision is read back before publication as well as after commit. `onPostCommitEmbedding` hands the caller a page-scoped completion callback so it can release its own worktree lock before embedding; vectors apply only if page ID, generation, and chunk generation still match; it returns embedded/failed/superseded separately, with a fixed failure message rather than provider error text. Ordinary file imports retain their prior embedding order. `importFromContent` and `importCodeFile` stamp `pages.embedding_signature` via `setPageEmbeddingSignature(slug, {sourceId, signature: currentEmbeddingSignature()})` when the import actually embedded (not `--no-embed`) so a model/dims swap is detectable as stale; `importCodeFile` only stamps when every chunk was freshly embedded this call (`needsEmbedIndexes.length === chunks.length`), mixed reuse-by-hash pages stay unstamped (`reindex-code --force` / `embed --stale` handle those). `importFromContent`'s tag reconciliation is ADD-ONLY: it only `addTag` (idempotent, ON CONFLICT DO NOTHING). The `tags` table has no provenance column and frontmatter tags are stripped from stored `pages.frontmatter` (markdown.ts:118), so a frontmatter-origin tag can't be distinguished from a DB-enrichment tag (auto-tag / dream synthesize / signal-detector) at re-import — deletion is unsafe (would wipe enrichment under `gbrain reindex --markdown`). Accepted trade-off: removing a tag from frontmatter does not remove it from the DB on next sync (needs a `tag_source` provenance column). Pinned by `test/reindex-preserve-tags.test.ts` + `test/import-file.test.ts`. identity-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 (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`. `importCodeFile` writes `source_path: relativePath` on every code page (the same repo-relative path markdown imports record) so the full-sync reconcile — which only considers `source_path IS NOT NULL` rows — can retire a deleted code file's page; `putPage` COALESCEs the column, so rows imported before this keep NULL until the file changes or `gbrain reindex-code --force`.
- `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 a naive walker would descend into it and inflate MISSING_OPEN counts via vendor packages), `vendor`/`dist`/`build`/`venv`, dot-prefix dirs, and `*.raw` sidecars — NOT `ops/`, which is ordinary user content (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. `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. 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' | 'malformed-path'`. Malformed filenames are TWO-TIER: `hasMalformedPathSegment` (ADMISSION — control chars on any path; square brackets on `.md`/`.mdx` paths only, so code-strategy lanes keep indexing `app/[id]/page.tsx` framework layouts) vs `isPoisonedPath` (DESTRUCTION — only the injection signature `](` or control chars; sync's row-DELETING lanes gate on this so a bare-bracket markdown row already in the DB survives reconcile while its file exists). `sanitizePathForDisplay` scrubs control bytes + caps length before echoing such paths. The `commands/sync.ts` cleanup loop guards on `unsyncableReason(path)` being `'metafile'` OR `'pruned-dir'` 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. Prevents phantom imports from a worktree-with-submodules sync walking into submodule trees. Pinned by `test/sync-walker-submodule.test.ts`.
- `src/core/sync-failure-ledger.ts` — the bounded auto-skip sync failure ledger. 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) → `auto_skipped` (chronic, still doctor-visible) or `acknowledged` (human resolved via `gbrain sync --skip-failed` from either unresolved state). `classifyErrorCode(errorMsg)` regex classifier with 23 named codes (`RENAME_RECONCILE`, `SLUG_MISMATCH`, `DB_DUPLICATE_KEY`, `STATEMENT_TIMEOUT`, `YAML_PARSE`, `YAML_DUPLICATE_KEY`, `MISSING_OPEN`, `MISSING_CLOSE`, `EMPTY_FRONTMATTER`, `NULL_BYTES`, `NESTED_QUOTES`, `INVALID_UTF8`, `FILE_TOO_LARGE`, `SYMLINK_NOT_ALLOWED`, `TAKES_TABLE_MALFORMED`, `TAKES_HOLDER_INVALID`, `EMBEDDING_NO_CREDS`, `EMBEDDING_NO_TOUCHPOINT`, `EMBEDDING_TIMEOUT`, `EMBEDDING_RATE_LIMIT`, `EMBEDDING_QUOTA`, `EMBEDDING_OVERSIZE`, `PAGE_JUNK_PATTERN`) plus `UNKNOWN` (the default fallthrough); `summarizeFailuresByCode(failures)` returns sorted `[{code, count}]`; `MISSING_OPEN`/`EMPTY_FRONTMATTER` regexes match the `markdown.ts` validator strings; `MISSING_CLOSE`'s regex is stale against current `markdown.ts` output — it matches the no-heading-hint case (`No closing --- delimiter found`) but not the heading-hint case (`No closing --- before heading at line N`), which falls through to `UNKNOWN`. `FILE_TOO_LARGE` covers `import-file.ts:395, 1236, 1436` (markdown/text, plain-file, and code-file import paths), `SYMLINK_NOT_ALLOWED` covers `:1231, 2038` (file and image import paths). `EMBEDDING_INFRA_CODES` is the subset (`EMBEDDING_TIMEOUT`/`EMBEDDING_RATE_LIMIT`/`EMBEDDING_QUOTA`) that means the embedding PROVIDER is unhealthy rather than the file being poison — `isEmbeddingInfraCode(code)` is consulted inside `decideGateAction`'s chronic-eligibility loop so these three are never counted toward auto-skip (treated as fresh, forcing `block` instead of `advance_then_autoskip`); an explicit `--skip-failed` still advances past them like any other failure, since that check runs before the loop. 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's `ts` (last attempt, NOT `first_seen`) is older than `failHours` — a failure retried inside that window keeps refreshing `ts` and never trips this leg even if `first_seen` is much older; 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`.
-- `src/core/sync-cost-gate.ts` + `sync-git.ts` + `sync-anchor.ts` + `sync-lock.ts` + `sync-reconcile.ts` + `sync-status-report.ts` — six pure-function clusters behind the `src/commands/sync.ts` façade, which re-exports them; `facadeExpansion` in `scripts/generate-flag-registry.ts` keeps exactly these six (NOT the other `sync-*` siblings, which are ordinary deps) on the sync command's flag-scan surface. `sync-cost-gate.ts`: the inline-embed cost gate + token estimation for `gbrain sync`. `sync-git.ts`: git plumbing — invocation building, repo discovery, baseline-commit self-heal, path-containment guards, and the delete/rename slug resolvers (`resolveSlugByPathOrSourcePath` — see its dedicated entry above — plus the verified `resolveSlugsForRemovedPaths`/`resolveRemovedPathSlug`). `sync-anchor.ts`: sync anchor + chunker-version state helpers (source-scoped vs legacy global-config storage). `sync-lock.ts`: the lock layer — typed lock-busy error, the rich busy message, `--break-lock` handling, the partial-result envelope (`performSync` itself stays in the façade). `sync-reconcile.ts`: full-sync reconcile planning (the mass-delete valve and ever-committed gate) + sync deadline/stall resolution. `sync-status-report.ts`: the per-source sync status report backing `gbrain sources status` and the `get_status_snapshot` op. Its queue context is engine-aware: only an explicitly worker-backed surface may promise job deferral; otherwise non-interactive cost deferral returns `manual_drain_required` with exact per-source `gbrain embed --stale --source <id>` commands and never writes or claims an embed-backfill row.
+- `src/core/sync-cost-gate.ts` + `sync-git.ts` + `sync-anchor.ts` + `sync-lock.ts` + `sync-reconcile.ts` + `sync-status-report.ts` — six pure-function clusters behind the `src/commands/sync.ts` façade, which re-exports them; `facadeExpansion` in `scripts/generate-flag-registry.ts` keeps exactly these six (NOT the other `sync-*` siblings, which are ordinary deps) on the sync command's flag-scan surface. `sync-cost-gate.ts`: the inline-embed cost gate + token estimation for `gbrain sync`. `sync-git.ts`: git plumbing — invocation building, repo discovery, baseline-commit self-heal, path-containment guards, OS-relative paths normalized to Git slash form by `gitRelativePath`, and the delete/rename slug resolvers (`resolveSlugByPathOrSourcePath` — see its dedicated entry above — plus the verified `resolveSlugsForRemovedPaths`/`resolveRemovedPathSlug`). `sync-anchor.ts`: sync anchor + chunker-version state helpers (source-scoped vs legacy global-config storage). `sync-lock.ts`: the lock layer — typed lock-busy error, the rich busy message, `--break-lock` handling, the partial-result envelope (`performSync` itself stays in the façade). `sync-reconcile.ts`: full-sync reconcile planning (the mass-delete valve and ever-committed gate), with stored paths normalized before scope filtering, plus sync deadline/stall resolution. `sync-status-report.ts`: the per-source sync status report backing `gbrain sources status` and the `get_status_snapshot` op. Its queue context is engine-aware: only an explicitly worker-backed surface may promise job deferral; otherwise non-interactive cost deferral returns `manual_drain_required` with exact per-source `gbrain embed --stale --source <id>` commands and never writes or claims an embed-backfill row.
- `src/core/sync-policy.ts` — `isSyncDisabledConfig(config)`: the one predicate for `config.syncEnabled === false` ("excluded from AUTOMATIC/bulk sync"), unwrapping PGLite's JSON-string config scalar via `parseSourceConfig`. Read by the `sync --all` fan-out filter (`src/commands/sync.ts`), autopilot's per-source freshness dispatcher (`src/commands/autopilot.ts`, skip before `queue.add('sync')`) and the full-cycle fan-out (`src/commands/autopilot-fanout.ts`, which drops the `sync` phase + pull from a disabled source's `autopilot-cycle` payload but keeps lint/backlinks/extract and the freshness stamp) and the `sync_enabled` column of `buildSyncStatusReport` (`src/core/sync-status-report.ts`, whose callers pass RAW `SELECT config` rows — a JSON string on PGLite — so a raw cast there contradicted the fan-out filter). Deliberately does NOT gate `performSync()`: an explicit `gbrain sync --source <id>` still runs; `sync-cost-gate.ts` keeps its own inline check because it also feeds the explicit single-source cost preview. Pinned by `test/sync-policy.test.ts`, the `#4399` cases in `test/autopilot-fanout-wiring.test.ts` (source-text) and `test/autopilot-fanout.test.ts` (stubbed dispatch).
- `src/core/sync-embed-backfill.ts` — Sync command’s engine-aware embedding-delivery seam. It derives separate worker-backed deferral and multi-source fan-out eligibility, keeps automatic-submission policy distinct from capability, invokes the shared cost gate for `--all` and single-source runs, propagates intrinsic large-sync deferral into final delivery outcomes, resolves backfill results through the centralized submitter, formats one truthful human status, and builds the single-source JSON envelope. `syncProducedEmbeddableContent` is the one content gate every automatic submit site (`sync --all`, single-source autodefer, the jobs `sync` handler) applies on top of status: a sweep-only or delete-only run reports `synced` but wrote no chunks, and minting a backfill for it would only arm the per-source cooldown against the next real import (the handler reports `embed_skip_reason: 'no_new_content'`). Keeping these pieces together prevents cost-gate, queue, human, and machine surfaces from drifting while the size-ratcheted `src/commands/sync.ts` façade stays at its committed ceiling.
- `src/core/storage.ts` — Pluggable storage interface (S3, Supabase Storage, local).
@@ -112,7 +112,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/chunkers/` — 3-tier chunking (recursive, semantic, LLM-guided). `code.ts` is a tree-sitter-based semantic chunker for 30 languages (plus SQL via DerekStride/tree-sitter-sql) with embedded-asset WASMs (`src/assets/wasm/`), `@dqbd/tiktoken` cl100k_base tokenizer, small-sibling merging. `CHUNKER_VERSION` is folded into `importCodeFile`'s `content_hash` so chunker shape changes force clean re-chunks across releases. `extractSymbolName` has an inline SQL branch (`extractSqlSymbolName`) diving through DerekStride's `statement` wrapper into the inner DDL child (`create_table`/`create_function`/`create_view`/`create_index`/`create_procedure`/`create_type`/`create_schema`/`create_database`/`create_trigger`/`alter_table`/`alter_view`) and extracting the target identifier via the `name` field with identifier-shaped fallback; DML kinds (`select`/`insert`/`update`/`delete`/`merge`/`with`) deliberately return null so chunks emit unnamed (code-def is a DDL signal). `normalizeSymbolType` has parallel SQL branches mapping `create_table → 'table'`, `create_view → 'view'`, etc. `DEF_TYPES` (owned by `src/core/chunkers/def-types.ts`, re-exported by `src/commands/code-def.ts` — see that entry) carries the SQL kinds (`'table' | 'view' | 'index' | 'procedure' | 'schema' | 'database' | 'trigger'`) so the new chunks surface in `gbrain code-def <name>` queries.
- `src/core/chunkers/def-types.ts` — `DEF_TYPES`: the ONE list of definition-shaped normalized (post-`normalizeSymbolType`) symbol types, shared by `gbrain code-def`'s lookup allowlist (`src/commands/code-def.ts` re-exports it) and the code chunker's small-sibling merge guard so the two can't drift — a symbol type code-def can resolve never has its `symbol_name` erased by merging a small definition into a neighbor. Includes the fallthrough forms `normalizeSymbolType` emits verbatim for tree-sitter node types it doesn't canonicalize (`'method declaration'`, `'struct specifier'`, `'record declaration'`, …) — most of an OO codebase's symbols arrive in those forms. Pinned by `test/chunkers/code-merge-defs.test.ts`.
- `src/core/errors.ts` — `StructuredAgentError` + `buildError` + `serializeError`. Every agent-facing surface (code-def, code-refs, usage errors) uses this envelope; matches the `CycleReport.PhaseResult.error` shape.
-- `src/assets/wasm/` — 37 tree-sitter grammar WASMs + tree-sitter runtime. Committed to the repo so `bun --compile` embeds them deterministically via `import path from ... with { type: 'file' }`. The CI guard `scripts/check-wasm-embedded.sh` fails the build if the compiled binary ever silently falls through to recursive chunks. `tree-sitter-sql.wasm` (DerekStride/tree-sitter-sql @ c2e1e08db1ea20dc23bdb8d228a81a8756e9c450, built with [email protected] --abi 14) adds SQL coverage at 11 MB — larger than peers because the grammar covers PostgreSQL + MySQL + SQLite + T-SQL basics (40 MB generated parser.c); the compiled binary grows ~6%.
+- `src/assets/wasm/` — 37 tree-sitter grammar WASMs + tree-sitter runtime. Committed to the repo so `bun --compile` embeds them deterministically via `import path from ... with { type: 'file' }`. The CI guard `scripts/check-wasm-embedded.sh` requires semantic TypeScript and Bash case-statement symbols in the compiled binary. Bash uses the official tree-sitter-bash v0.23.3 ABI-14 release asset, pinned by checksum in `scripts/vendor-bash-wasm.sh`; `src/assets/wasm/README.md` records provenance. Code chunker version 7 invalidates old content hashes; `gbrain sync --source <id> --full` revisits affected history in active repositories. `tree-sitter-sql.wasm` (DerekStride/tree-sitter-sql @ c2e1e08db1ea20dc23bdb8d228a81a8756e9c450, built with [email protected] --abi 14) adds SQL coverage at 11 MB — larger than peers because the grammar covers PostgreSQL + MySQL + SQLite + T-SQL basics (40 MB generated parser.c); the compiled binary grows ~6%.
- `src/commands/code-def.ts` + `src/commands/code-refs.ts` — symbol definition + references lookup. Query `content_chunks.symbol_name` or chunk_text ILIKE with `page_kind='code'` filter. Auto-JSON when stdout is not a TTY (gh-CLI convention). Bypass the standard `searchKeyword` `DISTINCT ON (slug)` collapse so multiple call-sites from the same file surface. The JSON envelope (CLI + the `code_def`/`code_refs` MCP ops) carries `status` + `ready` from `src/core/code-graph-readiness.ts` so a `count:0` result is distinguishable as `not_built` (no code indexed) vs `ready` (genuinely no match); human output prints a one-line hint when not ready. Both commands resolve `--source <id>` (space or inline `=` spelling) and the ambient source scope through the shared `code-scope.ts` resolver, matching `code-callers`/`code-callees`; `--all-sources` restores the brain-wide read. The `AND p.source_id = $N` fragment comes from `code-scope.ts`'s `pushSourcePredicate(params, opts)` (numbered off `params.length` so it composes with `--lang` and any other optional predicate; `''` when spanning every source) — code-def's lookup, its filtered-types probe, and code-refs all use it.
- `src/commands/code-scope.ts` — shared `--source`/`--all-sources` resolution for the four code-* CLI commands (code-def, code-refs, code-callers, code-callees), extracted so the four can't drift. `positionalArgs` skips value-taking flags AND their values (`--source`, `--limit`, `--lang` — a naive scan looked up the flag's value as the symbol); inline `name=value` spellings are one token and consume nothing. A bad `.gbrain-source`/`GBRAIN_SOURCE` pin is recognized through the shared `isResolverUserError` predicate (exported by `src/core/source-resolver.ts`, next to the messages it matches) and exits 2 with a clean `invalid_source_pin` envelope instead of an uncaught stack. Also exports `pushSourcePredicate(params, opts)`, the source-scope SQL fragment builder code-def/code-refs share.
- `src/core/code-graph-readiness.ts` — typed readiness signal shared by the code-* surfaces (`code-def`/`code-refs`/`code-callers`/`code-callees`, plus the `code_blast`/`code_flow` walk ops). `resolveCodeReadiness(engine, {kind:'symbol'|'edge', count, sourceId?, allSources?, remote?})` returns `{status:'not_built'|'no_symbols'|'indexing'|'ready'|'out_of_scope'|'unknown', ready, has_code, pending_edges, scoped_source_id?}` (6-state `CodeGraphStatus`; `scoped_source_id` is set only for `out_of_scope`, naming the excluded scope). `count>0` short-circuits to `ready` with no query; on empty it runs `EXISTS` probes against `content_chunks` JOIN `pages` (`page_kind='code'`) — no `page_kind` index needed, and the pending probe rides the partial `idx_content_chunks_edges_backfill`. `kind:'symbol'` (code-def/refs) is 3-state + brain-wide, because symbol metadata is set at chunk time and edge resolution is irrelevant to it: no code chunks → `not_built`; code chunks but none carry `symbol_name` yet → `no_symbols` (chunks indexed before symbol extraction; hints at `reindex-code`); symbol-bearing chunks → `ready` (it never reports `indexing`). `kind:'edge'` (code-callers/callees) is 3-state + source-scoped (`not_built`/`indexing`/`ready`), with the pending predicate mirroring the resolver (`edges_backfilled_at IS NULL OR < EDGE_EXTRACTOR_VERSION_TS` from `src/core/chunkers/symbol-resolver.ts`) so a resolver-version bump never falsely reports `ready`. Both grains additionally share `out_of_scope`: when the scoped probe finds no code but an unscoped rerun finds code exists brain-wide (a chunk-existence check only — it doesn't verify symbol metadata or edge completeness), it's the caller's resolved scope that excludes it, not an unbuilt graph. That unscoped rerun runs ONLY for trusted local callers (`remote === false`); a scoped remote caller sees `not_built` instead, never a brain-wide code-existence disclosure. Probe scope matches each command's result-query `deleted_at` posture (def/refs don't filter `deleted_at`, so neither do the probes). Any DB error returns `status:'unknown'` (fail-open; never breaks the command). `readinessHint(r)` renders the human one-liner. Wired into `code-def.ts`/`code-refs.ts` (brain-wide), `code-callers.ts`/`code-callees.ts` (resolved `sourceId`/`allSources`), and all six `code_*` MCP op handlers in `src/core/ops/code-intel.ts` (`operations.ts` imports `codeIntelOperations` and spreads it into the canonical `operations` array, not a re-export). `code_blast`/`code_flow` stamp `status`/`ready` (+ `scoped_source_id`) onto the walk result through the module-private `attachWalkReadiness` helper: computed AFTER the traversal cache (readiness is never cached), `not_found` probes at symbol grain, `ok`/`ambiguous` at edge grain with count = nodes/candidates, and `unsupported_language` is passed through untouched. Pinned by `test/code-graph-readiness.test.ts` + readiness-envelope cases in `test/e2e/code-intel-mcp-ops-pglite.test.ts`.
@@ -153,7 +153,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/commands/eval-prune.ts` — explicit retention cleanup. Requires `--older-than DUR`. `--dry-run` reports would-delete count.
- `src/commands/eval-replay.ts` — contributor-facing replay tool. Reads NDJSON from `gbrain eval export`, re-runs each captured `query` / `search` op against the current brain, computes set-Jaccard@k between captured + current `retrieved_slugs`, top-1 stability rate, and latency Δ. Stable JSON shape (`schema_version: 1`) for CI gating; human mode prints a regression table. Pure Bun, zero new deps. The dev-loop half of BrainBench-Real. See `docs/eval-bench.md`. `parseNdjson` skips lines where `_kind === 'baseline_metadata'` so `gbrain bench publish` baselines parse cleanly without the metadata header polluting row counts. Exports `replayCore(engine, opts): Promise<{summary, results}>` + `ReplaySummary` type so `gbrain eval gate` calls replay in-process (NOT subprocess — avoids gbrain-version-drift for source-tree CI). CLI `runEvalReplay` wraps `replayCore`.
- `src/core/bench/baseline-file.ts` + `src/core/bench/qrels-file.ts` + `src/core/bench/correctness-gate.ts` + `src/commands/bench-publish.ts` + `src/commands/eval-gate.ts` — the eval loop. `gbrain bench publish --from <captured.ndjson> --to <X.baseline.ndjson>` writes a baseline (stamps stable `query_hash` per row; metadata header carries `_kind: 'baseline_metadata'` + thresholds + `source_hash` + `baseline_mean_latency_ms`; deterministic sort by `(tool_name, query_hash)`; strict: empty=fail, dupes=fail with paste-ready hint, `--to` exists=refuse without `--force`). `gbrain eval gate [--baseline X] [--qrels Y]` is the two-gate dispatcher (regression gate via in-process `replayCore`, correctness gate via bare `hybridSearch` for determinism, both must pass when both flags set, exit 0 PASS / 1 FAIL / 2 USAGE). Source-id-aware: `bench publish` dedup key is `(tool_name, source_ids, query_hash)`; qrels compare keys are `${source_id}::${slug}` everywhere (so multi-source brains are keyed correctly at the file-shape layer). Latency math: `(baseline + delta) / baseline <= multiplier`. Fail-closed: ANY in-process throw flips verdict to fail with named breach in `breaches[]` — never silently exit 0. `.qrels.json` preserves the 12-row `test/fixtures/eval-baselines/qrels-search.json` fixture (slug-only `relevant_slugs` + `first_relevant_slug` auto-promote to `source_id='default'`) AND supports the federated shape (explicit `relevant: [{source_id, slug}]` + `expected_top1`). `correctness-gate.ts` runs each qrels query via bare `hybridSearch`; per-query throw recorded as `errored: true` and flagged as gate failure. Audit JSONL at `~/.gbrain/audit/bench-publish-YYYY-Www.jsonl`. Hermetic mode: `--embedder deterministic` (correctness gate ONLY — rejected with `--baseline`, requires `--qrels`) embeds each query as the qrels fixture's basis vector via `src/eval/deterministic-embed.ts` (`basisEmbedding` unit vectors; FNV-1a-derived fallback dim for off-fixture query texts) and threads it into bare `hybridSearch` through the `queryEmbedFn` seam — no API keys, no network; bare `hybridSearch` neither reads nor writes the semantic query cache (both live in `hybridSearchCached`), so deterministic runs cannot poison cached production results. `scripts/run-eval-canary.ts` (`check:eval-canary` package script, on-demand; in CI the same runner executes via `test/eval-canary.test.ts` in the unit matrix, not in the verify battery) is the hermetic CLI retrieval canary built on it: boots a throwaway PGLite brain under a temp GBRAIN_HOME, seeds the qrels fixture corpus (the expected-top1 page carries its query text in `timeline` too — page-grain FTS indexes title(A) + timeline(C) only, `compiled_truth` is deliberately unindexed), spawns the REAL CLI with engine-reroute/provider env stripped, and asserts exit 0 + metric floors; `--record` additionally appends an EvalRunRecord-shaped line to `.gbrain-evals/eval-results.jsonl`. Honest scope: the canary gates the hybrid ranking pipeline (keyword/title/alias arms + RRF against gold qrels) with synthetic vectors — semantic-embedding regressions remain the keyed eval suites' job. Pinned by `test/bench/baseline-file.test.ts`, `test/bench/qrels-file.test.ts`, `test/bench/correctness-gate.test.ts`, `test/bench-publish.test.ts`, `test/eval-gate.test.ts`, `test/eval-canary.test.ts`, `test/eval-replay-metadata-skip.test.ts`, `test/cycle/nightly-probe-adapters.test.ts`, `test/autopilot-nightly-probe-wiring.test.ts`, `test/e2e/eval-loop.test.ts`.
-- `src/core/cycle/nightly-probe-adapters.ts` — bridges the autopilot's object-shape `NightlyProbeDeps` to the argv-shape `runEvalLongMemEval` + `runEvalCrossModal` CLI functions. Cross-modal adapter argv MUST include `--output summaryPath` (without it the summary lands at the default receipt path and the adapter reads nothing from `summaryPath`). In-process invocation (NOT subprocess) — avoids gbrain-version-drift for source-tree CI. Pinned by `test/cycle/nightly-probe-adapters.test.ts` (incl. the argv-shape guard for the `--output` requirement).
+- `src/core/cycle/nightly-probe-adapters.ts` — bridges the autopilot's object-shape `NightlyProbeDeps` to the argv-shape `runEvalLongMemEval` + `runEvalCrossModal` CLI functions. Cross-modal adapter argv MUST include `--output summaryPath` (without it the summary lands at the default receipt path and the adapter reads nothing from `summaryPath`). In-process invocation (NOT subprocess) avoids gbrain-version-drift for source-tree CI. The LongMemEval adapter passes `exitOnError: false`: failures throw into the nightly audit/rate-limit boundary instead of exiting the host process, with resolved chat providers checked before embedding work. Pinned by `test/cycle/nightly-probe-adapters.test.ts` (incl. the argv-shape guard for the `--output` requirement).
- `test/eval-replay-gate.test.ts` + `test/fixtures/eval-baselines/qrels-search.json` — hermetic retrieval qrels gate running in the standard PR unit-shard CI matrix (`.github/workflows/test.yml`, NOT the fixed-file E2E workflow). Uses the canonical PGLite block (test-isolation R3+R4) and the basis-vector embedding pattern from `test/e2e/search-quality.test.ts:23-28` for fully hermetic retrieval. The qrels fixture (12 queries) uses PLACEHOLDER names only (alice-example, widget-co-example, etc. — privacy rule) and embeds each query at a deterministic basis dimension so retrieval is reproducible. Each query lists `relevant_slugs[]` + `first_relevant_slug`; the test computes `top1_match_rate` (top-1 == first_relevant) and `recall@10` (fraction of relevant_slugs in top-10), asserting both meet floors (defaults `>= 0.80` and `>= 0.85`). Env-overridable floors `GBRAIN_REPLAY_GATE_TOP1_FLOOR` / `GBRAIN_REPLAY_GATE_RECALL_FLOOR` (via `withEnv()` per R1). Refresh discipline: when ranking changes intentionally move expected slugs, edit `qrels-search.json` directly with a `Why:` line in the commit body or the gate degrades to rubber-stamp. Pinned by `test/eval-replay-gate.test.ts` (incl. a privacy-grep guard against real names).
- `src/core/cycle/nightly-quality-probe.ts` + `src/core/audit-quality-probe.ts` + `test/fixtures/longmemeval-nightly.jsonl` + `test/nightly-quality-probe.test.ts` — opt-in nightly cross-modal quality probe. The phase runs `gbrain eval longmemeval --by-type` against the committed 10-question placeholder fixture, pipes output through `gbrain eval cross-modal --batch --max-usd 5 --yes`, and writes one event per run to `~/.gbrain/audit/quality-probe-YYYY-Www.jsonl` (ISO-week-rotated, mirrors `audit-slug-fallback.ts`; honors `GBRAIN_AUDIT_DIR`). Default DISABLED — opt-in via `gbrain config set autopilot.nightly_quality_probe.enabled true` (prevents surprise API spend). 24h rate limit (pure `shouldRunNightly(now, recentEvents, windowMs?)`) skips with audit row `outcome: rate_limited`. Embedding-key short-circuit: longmemeval needs `gateway.embedQuery()`, so the phase exits early with `outcome: no_embedding_key` + stderr warn when no provider configured. Full DI surface via `NightlyProbeDeps` (`isEnabled`, `hasEmbeddingProvider`, `resolveMaxUsd`, `resolveRepoRoot`, `runLongMemEval`, `runCrossModalBatch`, `now`) so the unit test stubs every external effect. Cost ceiling: $5/run × 30 nights ≈ $150/month worst-case; expected ~$10.50/month. The `nightly_quality_probe_health` doctor check (`src/commands/doctor.ts`, right after `slug_fallback_audit`) reads last 7 days: SKIPPED when flag off (with enable command); OK when enabled + all PASS; WARN on any FAIL / ERROR / BUDGET_EXCEEDED with per-outcome counts. Pinned by `test/nightly-quality-probe.test.ts`.
- `src/commands/eval-trajectory.ts` + `src/commands/founder-scorecard.ts` + `src/core/trajectory.ts` — temporal trajectory + founder scorecard. `gbrain eval trajectory <entity>` shows the chronological typed-claim history (mrr/arr/team_size/etc) with regressions auto-flagged inline; `gbrain founder scorecard <entity>` rolls up claim_accuracy / consistency / growth_trajectory / red_flags into one JSON. Pure-function math in `trajectory.ts`: `detectRegressions(points, threshold)` walks consecutive metric-value pairs per metric (10% drop default, env override `GBRAIN_TRAJECTORY_REGRESSION_THRESHOLD`); `computeDriftScore(points)` returns `1 - mean(cosine(emb[i], emb[i-1]))` over existing embeddings (null when <3 embedded points). Backed by `BrainEngine.findTrajectory(opts)` — both Postgres and PGLite, single SQL query, deterministic `ORDER BY valid_from ASC, id ASC`. Source-scoped via the `sourceId` scalar / `sourceIds` array dual pattern; visibility-filtered for remote callers. MCP op `find_trajectory` (read scope, NOT localOnly) registered after `find_experts`. Migration v67 adds optional typed-claim columns (`claim_metric`, `claim_value`, `claim_unit`, `claim_period`) + a partial index on `(entity_slug, claim_metric, valid_from) WHERE claim_metric IS NOT NULL`. Fence widens from 10 to 14 cells when any row has typed data; renderer stays at 10 cells when none do (no churn diff on existing fences). Metric labels normalize to lowercase snake_case via `normalizeMetricLabel` (15-entry seed map). The `consolidate` cycle phase does semantic upsert keyed on `(page_id, claim, since_date)` (so re-running the cycle after `extract_facts` clears `consolidated_at` cannot append duplicates via `MAX(row_num)+1`) and writes chronological `valid_until` on each cluster's older facts. The `extract_facts` cycle phase batch-embeds via `gateway.embed()` before insert AND threads `pages.effective_date` as the `pageEffectiveDate` fallback for `valid_from` (precedence: fence-row > pageEffectiveDate > now()). The contradiction probe MUST NOT write `valid_until` — grep guard at `test/eval-contradictions/no-valid-until-write.test.ts`. Haiku extraction lives in `src/core/facts/extract.ts` (not the `extract-facts.ts` cycle phase); its output cap is config `facts.extraction_max_tokens` (default 4000), a `stopReason: 'length'` response retries once at 2× the cap, and persistent truncation warns loudly on stderr instead of silently extracting zero facts. Mixed extractor arrays salvage valid candidates and warn with the dropped malformed count; all-malformed output still fails retryably, while an explicitly empty facts array remains a successful empty result. `pageEffectiveDate` is OPTIONAL because `fence-write.ts` callers have no Page object. Migration v89 adds a nullable `event_type TEXT` column on `facts` so the substrate carries event-shaped rows (`event_type='meeting'` / `'job_change'` / `'location_change'`) alongside metric rows. `TrajectoryPoint.event_type: string | null` projected by both engines. `TrajectoryOpts.kind?: 'metric' | 'event' | 'all'` filter (default `'all'`); `founder-scorecard` + `eval-trajectory` pass `kind: 'metric'` explicitly. Back-compat pinned by `test/regressions/v0_40_2_0-trajectory-backcompat.test.ts` (byte-identical `computeFounderScorecard` + `computeTrajectoryStats` with and without event rows); engine parity in `test/engine-parity-event-type.test.ts`.
@@ -161,7 +161,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/think/intent.ts` + `src/core/think/entity-extract.ts` — pure `classifyIntent(question)` returns `'temporal' | 'knowledge_update' | 'other'` (regex-first, no LLM, `'other'` fast path short-circuits with zero SQL). `extractCandidateEntities(question, retrievedSlugs)` pulls high-precision candidates from retrieved entity-prefix slugs (`people/`, `companies/`, `organizations/`) and medium-precision noun phrases. Stop-word boundaries + leading-verb stripper handle "When did I last meet Marco" → `marco`. Both consumed by `runThink` and the LongMemEval harness so the two paths cannot drift. Pinned by `test/think-intent.test.ts` and `test/think-entity-extract.test.ts`.
- `src/commands/eval-suspected-contradictions.ts` + `src/core/eval-contradictions/{judge,runner,types,date-filter,cost-tracker,cache,severity-classify,cross-source,trends,calibration,judge-errors,auto-supersession,fixture-redact}.ts` — `gbrain eval suspected-contradictions [run|trend|review]`. Probe samples top-K retrieval pairs per query (cross-slug + intra-page chunk-vs-take), date pre-filters (3-rule layered — same-paragraph-dual-date overrides separation rule), LLM judge (query-conditioned; UTF-8-safe truncation; confidence-floor double-enforcement; resolution_kind output drives paste-ready commands), persistent cache keyed on `(chunk_a_hash, chunk_b_hash, model_id, prompt_version, truncation_policy)` (prompt edits cleanly invalidate prior verdicts), Wilson 95% CI calibration on the headline percentage with `small_sample_note` when n<30, judge_errors as first-class typed counters (parse_fail/refusal/timeout/http_5xx/unknown — avoids bias from silent skip), trend writes to `eval_contradictions_runs`, source-tier breakdown reuses `DEFAULT_SOURCE_BOOSTS` prefix logic, deterministic sampling (combined_score DESC + lex tiebreaker for stable cache hit-rate). Hermetic via `judgeFn` + `searchFn` DI in the runner; never touches the real gateway in tests. Engine surface: `BrainEngine.listActiveTakesForPages` (batched), `writeContradictionsRun` + `loadContradictionsTrend`, `getContradictionCacheEntry` + `putContradictionCacheEntry` + `sweepContradictionCache`. Schema migrations v51 + v52. MCP op `find_contradictions` (read scope, NOT localOnly, NOT in subagent allowlist — user-initiated only). Doctor check surfaces high-severity findings with paste-ready resolution commands; synthesize phase pre-fetches the latest probe's top-5-by-severity findings and threads them into `buildSynthesisPrompt` as an informational block. Architecture doc: `docs/contradictions.md`.
- `src/core/think/index.ts` — `runThink` builds its internal `LLMClient` via a small adapter wrapping `gateway.chat()` from `src/core/ai/gateway.ts` (not `new Anthropic()` directly) so stdio MCP launches (Claude Desktop, Cursor) that don't inherit shell env still find a key set via `gbrain config set anthropic_api_key` (the gateway reads `~/.gbrain/config.json` AND env). Test seam: `opts.client?: ThinkLLMClient` injection works (`test/think-pipeline.serial.test.ts`, `test/think-gateway-adapter.test.ts`); `opts.stubResponse` short-circuits before any LLM call. When neither key nor client is available, the "no LLM available" stub fires with `NO_ANTHROPIC_API_KEY`. Trajectory injection (default ON): `runThink` orchestrates `classifyIntent(question)` → `extractCandidateEntities(question, retrievedSlugs)` → `findTrajectory` (5s `Promise.race` timeout per candidate, concurrency cap 3) → `formatTrajectoryBlock`. `buildThinkUserMessage` (in `src/core/think/prompt.ts`) has a `trajectory?: ThinkTrajectoryBlockOpts` slot honoring BOTH prompt orderings (calibration mode: retrieval → calibration → trajectory → question; default mode: question → retrieval → trajectory → instruction). The MCP `think` op handler maps `sourceScopeOpts(ctx)` onto `RunThinkOpts` via `thinkSourceScopeOpts(ctx)` (operations.ts), and `runThink` threads the scope into `runGather` (`src/core/think/gather.ts`) — so every gather stream (hybrid retrieval, takes keyword + vector via the engines' scoped `searchTakes`/`searchTakesVector`, graph walk via `traversePaths`) AND trajectory resolution stay within the caller's source grant (federated `sourceIds[]` wins over scalar `sourceId`); pinned by `test/e2e/think-source-isolation-pglite.test.ts`. Config key `think.trajectory_enabled` (default `true`). Any error in the trajectory path degrades to "no block injected" + `TRAJECTORY_INJECTION_FAILED` warning — the think call never crashes from trajectory. Production path skips `fallback_slugify` resolutions (avoid querying invented slugs); the LongMemEval harness accepts them. Pinned by `test/think-trajectory-injection.test.ts`. Debug: `GBRAIN_THINK_DEBUG=1 gbrain think "..."` prints the spliced prompt to stderr.
-- `src/commands/eval-longmemeval.ts` + `src/eval/longmemeval/{harness,adapter,sanitize,extract,intent,reader,emit,capture,gateway-client,trajectory-route}.ts` — `gbrain eval longmemeval <dataset.jsonl>` runs the public [LongMemEval](https://huggingface.co/datasets/xiaowu0162/longmemeval) benchmark against gbrain's hybrid retrieval and is the repo's receipt producer for the strict retrieval metric and, with `--judge`, for judged answer accuracy (both reproduction paths are in `docs/eval-bench.md`). One in-memory PGLite per run via `createBenchmarkBrain` + `withBenchmarkBrain`; between questions, `TRUNCATE` over runtime-enumerated `pg_tables` with the infrastructure tables (`sources`, `config`, `gbrain_cycle_locks`, `subagent_rate_leases`) preserved — which is why the run's pins, written once via `engine.setConfig`, hold for every question. `cli.ts` pre-dispatch bypass skips `connectEngine()`, so `~/.gbrain` is never opened. **Metric (metrics.ts):** recall joins on RAW dataset session ids through a per-question slug→raw map; `recall_all@k` (every gold session among the distinct sessions of the top-k CHUNK rows returned at `limit: k`) is the headline, `recall_any@k` the diagnostic, and the per-row `recall_hit` is a deprecated alias of `recall_any_hit`; `_abs` abstention questions are emitted with `abstention: true` but stay out of the recall denominators unless `--include-abstention`; a slug collision touching a gold id aborts that question with an error row. **Pins:** `--mode`, `--reranker on|off`, `--autocut on|off`, `--expansion` (OFF for every mode — the per-call setting wins over the bundle, so `--mode tokenmax` alone never expands), `--expansion-variant-budget legacy|(0,4]`, `--search-pin KEY=VALUE` (repeatable; any `search.*` key, written verbatim via `engine.setConfig`); precedence is explicit flag > `--search-pin` > injected `RunOpts.searchConfigSnapshot` > bundle, so a flag wins over a pin on the same key. The raw `--search-pin` map folds into `retrieval_config_hash` (only when non-empty, so pin-free runs keep their hash identity) while the knobs hash covers only the resolved mode knobs. The reranker gate keys on the RESOLVED pin (flag, `--search-pin`, snapshot or bundle), not only on an explicit `--reranker on`: a run that resolves to reranker on preflights `rerankerReadinessForEngine` and exits 2 with the fix when the reranker cannot run (a `balanced` run with no `VOYAGE_API_KEY` exits with the fix text — `--reranker off` or set the key — instead of quietly scoring un-reranked rows). **Gates (exit 1):** a run in which every question errored, a row that fell through un-reranked under a resolved reranker-on pin (`reranker_skipped_rows`), a row whose vector arm silently degraded to keyword-only on a non-`--keyword-only` run (`vector_degraded_rows`: `vector_enabled:false` / `embed_unavailable` / `embed_timeout`), an `--expansion` row that did not expand as configured (`expansion_failed_rows`), an `--expansion-replay` miss, and `--by-type-floor F` breaches — which gate on `recall_all` by default (`--by-type-floor-metric recall_any` selects the lenient rate). The run-end gates and `GBRAIN_LME_DEBUG=1` prints per-question wall time to stderr; `--record` run through ONE `finishRun` from both the main path and the no-op resume path. **Rows:** `retrieved[]` (every returned chunk row: `slug`, `chunk_id`, RAW `session_id`, `rank`, `score`, `rerank_score?`, `alias_hit?`), `retrieved_session_ids`, `distinct_sessions_in_top_k`, `gold_total`/`gold_found`, `search_meta` (`vector_enabled`, `expansion_applied`, `degraded`, derived `reranked` = some finite `rerank_score` and no skip stage, `autocut`), `retrieval_config_hash`, the reader pins on every answered row (`reader_model` = the requested id, `reader_model_snapshot` = the provider-reported id when it differs — a dated API snapshot — else null, `reader_prompt_sha`, `reader_max_tokens`; `--retrieval-only` rows carry `retrieval_only: true` instead so a judge backfill can refuse them), `expansion_variants` when expansion ran (`--expansion-replay FILE` serves them back and stamps `expansion_replayed`, so every cell differs only in its knobs), and with `--capture-pool` a `rerank_pool` — the exact pre-autocut `returnPool` `hybridSearch` hands to `applyAutocut` (via `HybridSearchOpts.onRerankPool`; unscored alias/exact-lookup injections included; `rrf_rank`, `pool_rank`, `est_tokens` per row; `autocut_kept_keys` when the returned rows are the kept set) for the offline autocut-floor replay. **Summary:** `--by-type` emits a `schema_version: 2` `by_type_summary` (per-type + aggregate `{total, all_hit, all_rate, any_hit, any_rate}`, `excluded_abstention`, `mean_distinct_sessions`, `legacy_rows`, `gold_missing_from_haystack`, `slug_collisions`, and `run_config`: every pin, embedder `model@dims`, dataset sha256 + question count, `knobs_hash` + `KNOBS_HASH_VERSION`, `retrieval_config_hash`, the embed-cache receipt, the degradation counters); resume-replace keeps exactly ONE summary at the tail (`emit.ts:emitByTypeSummary`: the summary is always the FINAL line — any prior `by_type_summary` is removed before the new one is appended, and the file rewrite is atomic, `<path>.summary.tmp` + rename, so a kill mid-write never truncates the paid rows — its `_meta.metric_glossary` is the ONE glossary block per response and names exactly the metrics carried, `recall_all@k`, `recall_any@k`, and `qa_accuracy` when the judge lane ran; a CR inside any emitted line throws rather than splitting a JSONL record). **Reader (reader.ts):** `READER_SYSTEM_TEXT` is a module constant — every per-question input (question, `Current Date: {question_date}` when the dataset row carries one, the trajectory block, the sanitized `<chat_session>` blocks) lives in the USER message — so `READER_PROMPT_SHA` (sha256 of the system text) is a run-level pin and two rows with equal shas saw the identical instruction; `READER_MAX_TOKENS` is 512 (official 500). Disclosed deviations from the official `run_generation.py` prompt: an abstention instruction (say the information is not available / "I don't know" when the retrieved sessions lack it — without it the 30 `_abs` questions are answered and judged wrong by construction), the #4338 data-boundary framing + pattern stripping, and the 512 cap. `generateAnswer` returns `{text, response_model}`, `response_model` being the provider-reported snapshot when it differs from the requested id (the harness's gateway client maps `ChatResult.responseModel ?? model` into the Anthropic-shaped `message.model`). **Judge lane (`--judge`):** implies `--by-type`; `--judge --retrieval-only` is a usage error. Preflight (`judge-lane.ts:judgePreflight`): no usable chat provider for the judge model → exit 1; `--max-usd` against an unpriced model → exit 2 (pass `--max-usd off`); estimate over the cap without `--yes` → exit 2. The estimate (`judge.ts:estimateJudgeRunUsd`) assumes `READER_MAX_TOKENS` per live hypothesis and the stored hypothesis for backfill rows; the `BudgetLedger` soft-stops at the cap and the remaining rows are stamped `judge_skipped: 'budget'`. Live rows are judged inline after each reader call. `--judge --resume-from FILE` is the judge-only backfill: `selectBackfillRows` picks every prior row with a hypothesis and no settled verdict (`judge_error` rows are re-judged, `--retrieval-only` rows are refused, rows absent from the dataset are left unjudged with a WARN); a same-file resume ALWAYS appends (`makeEmitter(outputPath, append)` has no atomic-rewrite mode — appending is the only write path) — judged backfill rows and retries land as newer duplicates the moment they finish, so a timeout or kill loses at most the in-flight question — and `compactJsonlByQuestionId` (emit.ts) rewrites the file atomically (`<path>.compact.tmp` + rename) to one row per question_id (last wins, first-seen order) before the summary is emitted; `readJsonlRows` / `loadResumeSet` read appended files last-wins and `--judge-concurrency N` parallelizes the backfill. Every judged row carries `judge_config_hash` — the judge pins (model, `JUDGE_PROMPT_VERSION`, max_tokens, temperature) plus the reader pins the row was produced under; a prior row hashes from its OWN recorded `reader_model` / `reader_prompt_sha` / `reader_max_tokens`, so a file answered by another reader is never relabelled as this run's, and rows already judged under a different hash are refused unless `--allow-mixed-run-config`. Run end: `qa_accuracy` (`qa-accuracy.ts`) is rebuilt from ALL rows (prior + new, last row per `question_id` wins) whenever the lane ran or any row carries a verdict; a run with `judge_errors > 0`, `skipped_budget > 0` or `unjudged > 0` (the `qa_accuracy.complete` predicate) prints a `FAIL … NOT publishable` line and exits 1 unless `--allow-incomplete-judgments` (WARN, exit 0) — the fix is `--judge --resume-from FILE` until all three are 0; a row whose judge call threw is stamped `judge_error: 'provider_error'` by the backfill, never silently left unjudged. Judge row fields: exactly one of `judge_correct` / `judge_error` (+ secret-redacted `judge_error_detail`) / `judge_skipped`, plus `judge_model`, `judge_model_snapshot`, `judge_raw` (first 200 chars), `judge_cost_usd`, `judge_attempts`, `judge_prompt_kind`, `judge_prompt_version`, `judge_config_hash`. `RunOpts.judgeClient` / `judgeBackoffMs` are the test seams. **Embed cache:** on by default at `~/.cache/gbrain-eval/longmemeval-embed.sqlite` (`--embed-cache FILE` / `--no-embed-cache`; never installed on `--keyword-only`), installed through the gateway embed-transport seam so every arm sees byte-identical vectors; the cache transaction wraps only the embed-producing section of a question (import + search), never a reader call. **Resume:** `--resume-from FILE` re-scores prior rows from `retrieved[]` + the dataset's gold (stored booleans are never trusted) and refuses a file whose rows carry a different `retrieval_config_hash` unless `--allow-mixed-run-config`; error rows without a hypothesis are retried. `--question-ids FILE` restricts the run to a listed slice (unknown ids or an empty file exit 1); `--record` appends a secret-redacted `EvalRunRecord` (schema 3, suite `longmemeval`, params = `run_config`) via `persistRunRecord`. Flags live in ONE table, `LME_FLAGS`, that drives both `parseArgs` and `printHelp`, so the flag-registry scan sees every literal and help cannot drift from the parser. Sanitization parity: `harness.ts` reuses `INJECTION_PATTERNS` from `src/core/think/sanitize.ts`; retrieved chat content is wrapped in `<chat_session id="..." date="...">` and the answer-gen system prompt declares it UNTRUSTED. `RunOpts` seams — `client`, `extractorClient`/`extractorModel`, `engine`, `searchConfigSnapshot`, `expandFn`, `embedTransport`, `rerankerReadiness`, `recordDir` — let the full pipeline run hermetically without an API key. Trajectory routing (default on; `--no-trajectory` bypasses BOTH the extractor and the intent routing, the like-for-like retrieval setting): `extract.ts` runs the Haiku claim extractor over each haystack session into the benchmark brain's `facts` table (content-hash cache, per-question alias map, fail-open on every error path), `intent.ts` prefers the dataset's `question_type` before the SHARED regex set from `src/core/think/intent.ts`, temporal/knowledge_update questions splice a `findTrajectory` block into the reader prompt, and rows carry `intent`, `trajectory_points`, `entity_resolved`, `resolution_source`, `methodology_note` (`extractor=haiku-preprocess-full-haystack-v1` — that number is "gbrain + Haiku-preprocess", not "gbrain alone"). Pinned by `test/longmemeval-metrics.test.ts`, `test/eval-longmemeval-mixedcase.slow.test.ts` (raw-id join, strict/any split, abstention, pins, gates over the placeholder fixture `test/fixtures/longmemeval-mixedcase.jsonl`), `test/eval-longmemeval-cli-smoke.test.ts`, `test/longmemeval-embed-cache.test.ts`, `test/longmemeval-judge.test.ts` + `test/eval-longmemeval-judge.slow.test.ts` (the judge lane, reader pins and `qa_accuracy` denominators), `test/eval-longmemeval.slow.test.ts`, `test/eval-longmemeval-e2e.slow.test.ts`, `test/eval-longmemeval-search-config.test.ts`, `test/longmemeval-extract.test.ts`, `test/longmemeval-intent.test.ts`, `test/longmemeval-trajectory-routing.test.ts`.
+- `src/commands/eval-longmemeval.ts` + `src/eval/longmemeval/{harness,adapter,sanitize,extract,intent,reader,emit,capture,gateway-client,trajectory-route}.ts` — `gbrain eval longmemeval <dataset.jsonl>` runs the public [LongMemEval](https://huggingface.co/datasets/xiaowu0162/longmemeval) benchmark against gbrain's hybrid retrieval and is the repo's receipt producer for the strict retrieval metric and, with `--judge`, for judged answer accuracy (both reproduction paths are in `docs/eval-bench.md`). One in-memory PGLite per run via `createBenchmarkBrain` + `withBenchmarkBrain`; between questions, `TRUNCATE` over runtime-enumerated `pg_tables` with the infrastructure tables (`sources`, `config`, `gbrain_cycle_locks`, `subagent_rate_leases`) preserved — which is why the run's pins, written once via `engine.setConfig`, hold for every question. `cli.ts` pre-dispatch bypass skips `connectEngine()`, so `~/.gbrain` is never opened. Embedded callers use `RunOpts.exitOnError: false` to throw rather than terminate the host and preflight resolved chat providers before embedding; standalone CLI exits remain unchanged. **Metric (metrics.ts):** recall joins on RAW dataset session ids through a per-question slug→raw map; `recall_all@k` (every gold session among the distinct sessions of the top-k CHUNK rows returned at `limit: k`) is the headline, `recall_any@k` the diagnostic, and the per-row `recall_hit` is a deprecated alias of `recall_any_hit`; `_abs` abstention questions are emitted with `abstention: true` but stay out of the recall denominators unless `--include-abstention`; a slug collision touching a gold id aborts that question with an error row. **Pins:** `--mode`, `--reranker on|off`, `--autocut on|off`, `--expansion` (OFF for every mode — the per-call setting wins over the bundle, so `--mode tokenmax` alone never expands), `--expansion-variant-budget legacy|(0,4]`, `--search-pin KEY=VALUE` (repeatable; any `search.*` key, written verbatim via `engine.setConfig`); precedence is explicit flag > `--search-pin` > injected `RunOpts.searchConfigSnapshot` > bundle, so a flag wins over a pin on the same key. The raw `--search-pin` map folds into `retrieval_config_hash` (only when non-empty, so pin-free runs keep their hash identity) while the knobs hash covers only the resolved mode knobs. The reranker gate keys on the RESOLVED pin (flag, `--search-pin`, snapshot or bundle), not only on an explicit `--reranker on`: a run that resolves to reranker on preflights `rerankerReadinessForEngine` and exits 2 with the fix when the reranker cannot run (a `balanced` run with no `VOYAGE_API_KEY` exits with the fix text — `--reranker off` or set the key — instead of quietly scoring un-reranked rows). **Gates (exit 1):** a run in which every question errored, a row that fell through un-reranked under a resolved reranker-on pin (`reranker_skipped_rows`), a row whose vector arm silently degraded to keyword-only on a non-`--keyword-only` run (`vector_degraded_rows`: `vector_enabled:false` / `embed_unavailable` / `embed_timeout`), an `--expansion` row that did not expand as configured (`expansion_failed_rows`), an `--expansion-replay` miss, and `--by-type-floor F` breaches — which gate on `recall_all` by default (`--by-type-floor-metric recall_any` selects the lenient rate). The run-end gates and `GBRAIN_LME_DEBUG=1` prints per-question wall time to stderr; `--record` run through ONE `finishRun` from both the main path and the no-op resume path. **Rows:** `retrieved[]` (every returned chunk row: `slug`, `chunk_id`, RAW `session_id`, `rank`, `score`, `rerank_score?`, `alias_hit?`), `retrieved_session_ids`, `distinct_sessions_in_top_k`, `gold_total`/`gold_found`, `search_meta` (`vector_enabled`, `expansion_applied`, `degraded`, derived `reranked` = some finite `rerank_score` and no skip stage, `autocut`), `retrieval_config_hash`, the reader pins on every answered row (`reader_model` = the requested id, `reader_model_snapshot` = the provider-reported id when it differs — a dated API snapshot — else null, `reader_prompt_sha`, `reader_max_tokens`; `--retrieval-only` rows carry `retrieval_only: true` instead so a judge backfill can refuse them), `expansion_variants` when expansion ran (`--expansion-replay FILE` serves them back and stamps `expansion_replayed`, so every cell differs only in its knobs), and with `--capture-pool` a `rerank_pool` — the exact pre-autocut `returnPool` `hybridSearch` hands to `applyAutocut` (via `HybridSearchOpts.onRerankPool`; unscored alias/exact-lookup injections included; `rrf_rank`, `pool_rank`, `est_tokens` per row; `autocut_kept_keys` when the returned rows are the kept set) for the offline autocut-floor replay. **Summary:** `--by-type` emits a `schema_version: 2` `by_type_summary` (per-type + aggregate `{total, all_hit, all_rate, any_hit, any_rate}`, `excluded_abstention`, `mean_distinct_sessions`, `legacy_rows`, `gold_missing_from_haystack`, `slug_collisions`, and `run_config`: every pin, embedder `model@dims`, dataset sha256 + question count, `knobs_hash` + `KNOBS_HASH_VERSION`, `retrieval_config_hash`, the embed-cache receipt, the degradation counters); resume-replace keeps exactly ONE summary at the tail (`emit.ts:emitByTypeSummary`: the summary is always the FINAL line — any prior `by_type_summary` is removed before the new one is appended, and the file rewrite is atomic, `<path>.summary.tmp` + rename, so a kill mid-write never truncates the paid rows — its `_meta.metric_glossary` is the ONE glossary block per response and names exactly the metrics carried, `recall_all@k`, `recall_any@k`, and `qa_accuracy` when the judge lane ran; a CR inside any emitted line throws rather than splitting a JSONL record). **Reader (reader.ts):** `READER_SYSTEM_TEXT` is a module constant — every per-question input (question, `Current Date: {question_date}` when the dataset row carries one, the trajectory block, the sanitized `<chat_session>` blocks) lives in the USER message — so `READER_PROMPT_SHA` (sha256 of the system text) is a run-level pin and two rows with equal shas saw the identical instruction; `READER_MAX_TOKENS` is 512 (official 500). Disclosed deviations from the official `run_generation.py` prompt: an abstention instruction (say the information is not available / "I don't know" when the retrieved sessions lack it — without it the 30 `_abs` questions are answered and judged wrong by construction), the #4338 data-boundary framing + pattern stripping, and the 512 cap. `generateAnswer` returns `{text, response_model}`, `response_model` being the provider-reported snapshot when it differs from the requested id (the harness's gateway client maps `ChatResult.responseModel ?? model` into the Anthropic-shaped `message.model`). **Judge lane (`--judge`):** implies `--by-type`; `--judge --retrieval-only` is a usage error. Preflight (`judge-lane.ts:judgePreflight`): no usable chat provider for the judge model → exit 1; `--max-usd` against an unpriced model → exit 2 (pass `--max-usd off`); estimate over the cap without `--yes` → exit 2. The estimate (`judge.ts:estimateJudgeRunUsd`) assumes `READER_MAX_TOKENS` per live hypothesis and the stored hypothesis for backfill rows; the `BudgetLedger` soft-stops at the cap and the remaining rows are stamped `judge_skipped: 'budget'`. Live rows are judged inline after each reader call. `--judge --resume-from FILE` is the judge-only backfill: `selectBackfillRows` picks every prior row with a hypothesis and no settled verdict (`judge_error` rows are re-judged, `--retrieval-only` rows are refused, rows absent from the dataset are left unjudged with a WARN); a same-file resume ALWAYS appends (`makeEmitter(outputPath, append)` has no atomic-rewrite mode — appending is the only write path) — judged backfill rows and retries land as newer duplicates the moment they finish, so a timeout or kill loses at most the in-flight question — and `compactJsonlByQuestionId` (emit.ts) rewrites the file atomically (`<path>.compact.tmp` + rename) to one row per question_id (last wins, first-seen order) before the summary is emitted; `readJsonlRows` / `loadResumeSet` read appended files last-wins and `--judge-concurrency N` parallelizes the backfill. Every judged row carries `judge_config_hash` — the judge pins (model, `JUDGE_PROMPT_VERSION`, max_tokens, temperature) plus the reader pins the row was produced under; a prior row hashes from its OWN recorded `reader_model` / `reader_prompt_sha` / `reader_max_tokens`, so a file answered by another reader is never relabelled as this run's, and rows already judged under a different hash are refused unless `--allow-mixed-run-config`. Run end: `qa_accuracy` (`qa-accuracy.ts`) is rebuilt from ALL rows (prior + new, last row per `question_id` wins) whenever the lane ran or any row carries a verdict; a run with `judge_errors > 0`, `skipped_budget > 0` or `unjudged > 0` (the `qa_accuracy.complete` predicate) prints a `FAIL … NOT publishable` line and exits 1 unless `--allow-incomplete-judgments` (WARN, exit 0) — the fix is `--judge --resume-from FILE` until all three are 0; a row whose judge call threw is stamped `judge_error: 'provider_error'` by the backfill, never silently left unjudged. Judge row fields: exactly one of `judge_correct` / `judge_error` (+ secret-redacted `judge_error_detail`) / `judge_skipped`, plus `judge_model`, `judge_model_snapshot`, `judge_raw` (first 200 chars), `judge_cost_usd`, `judge_attempts`, `judge_prompt_kind`, `judge_prompt_version`, `judge_config_hash`. `RunOpts.judgeClient` / `judgeBackoffMs` are the test seams. **Embed cache:** on by default at `~/.cache/gbrain-eval/longmemeval-embed.sqlite` (`--embed-cache FILE` / `--no-embed-cache`; never installed on `--keyword-only`), installed through the gateway embed-transport seam so every arm sees byte-identical vectors; the cache transaction wraps only the embed-producing section of a question (import + search), never a reader call. **Resume:** `--resume-from FILE` re-scores prior rows from `retrieved[]` + the dataset's gold (stored booleans are never trusted) and refuses a file whose rows carry a different `retrieval_config_hash` unless `--allow-mixed-run-config`; error rows without a hypothesis are retried. `--question-ids FILE` restricts the run to a listed slice (unknown ids or an empty file exit 1); `--record` appends a secret-redacted `EvalRunRecord` (schema 3, suite `longmemeval`, params = `run_config`) via `persistRunRecord`. Flags live in ONE table, `LME_FLAGS`, that drives both `parseArgs` and `printHelp`, so the flag-registry scan sees every literal and help cannot drift from the parser. Sanitization parity: `harness.ts` reuses `INJECTION_PATTERNS` from `src/core/think/sanitize.ts`; retrieved chat content is wrapped in `<chat_session id="..." date="...">` and the answer-gen system prompt declares it UNTRUSTED. `RunOpts` seams — `client`, `extractorClient`/`extractorModel`, `engine`, `searchConfigSnapshot`, `expandFn`, `embedTransport`, `rerankerReadiness`, `recordDir` — let the full pipeline run hermetically without an API key. Trajectory routing (default on; `--no-trajectory` bypasses BOTH the extractor and the intent routing, the like-for-like retrieval setting): `extract.ts` runs the Haiku claim extractor over each haystack session into the benchmark brain's `facts` table (content-hash cache, per-question alias map, fail-open on every error path), `intent.ts` prefers the dataset's `question_type` before the SHARED regex set from `src/core/think/intent.ts`, temporal/knowledge_update questions splice a `findTrajectory` block into the reader prompt, and rows carry `intent`, `trajectory_points`, `entity_resolved`, `resolution_source`, `methodology_note` (`extractor=haiku-preprocess-full-haystack-v1` — that number is "gbrain + Haiku-preprocess", not "gbrain alone"). Pinned by `test/longmemeval-metrics.test.ts`, `test/eval-longmemeval-mixedcase.slow.test.ts` (raw-id join, strict/any split, abstention, pins, gates over the placeholder fixture `test/fixtures/longmemeval-mixedcase.jsonl`), `test/eval-longmemeval-cli-smoke.test.ts`, `test/longmemeval-embed-cache.test.ts`, `test/longmemeval-judge.test.ts` + `test/eval-longmemeval-judge.slow.test.ts` (the judge lane, reader pins and `qa_accuracy` denominators), `test/eval-longmemeval.slow.test.ts`, `test/eval-longmemeval-e2e.slow.test.ts`, `test/eval-longmemeval-search-config.test.ts`, `test/longmemeval-extract.test.ts`, `test/longmemeval-intent.test.ts`, `test/longmemeval-trajectory-routing.test.ts`.
- `src/eval/longmemeval/metrics.ts` — LongMemEval strict-recall metrics: the raw-id join, `recall_all@k` / `recall_any@k`, per-type buckets, the schema-v2 `by_type_summary`, and the per-question row assembler. PURE: no engine, no I/O, no LLM, so the harness and the tests score the same bytes. The join is on RAW session ids: `haystackToPages` lowercases and hyphenates ids to build slugs, so a slug tail compared against `answer_session_ids` never matches on the public `_s` split; `buildSlugToRawMap` inverts the slug construction per question, `distinctRetrievedSessions` joins through it, `detectSlugCollisions` / `collisionsTouchingGold` name the ambiguous slugs (a gold-touching collision makes the harness emit an error row), `goldMissingFromHaystack` counts dataset defects, and `normalizeSessionId` exists only for slug construction — never for the gold compare. k semantics: `recall_*@k` is scored over the DISTINCT sessions among the top-k CHUNK rows returned at `limit: k` (the caller slices first; `scoreRecall` treats k as a guard); empty gold scores both hits false, not vacuously true, and such rows stay out of the denominator. `addRowToBucket` folds a v2 row into `total`/`all_hit`/`any_hit`; a row carrying only the deprecated any-only `recall_hit` counts toward `total` + `any_hit` and bumps `legacy_rows` (its `all_rate` is therefore a lower bound); `buildByTypeSummaryV2` emits sorted type keys, `null` rates on empty buckets, `mean_distinct_sessions`, and the caller's `run_config`. `buildRow` assembles the JSONL row — scored fields over `results.slice(0, k)`, `retrieved[]` + `retrieved_session_ids` over EVERY returned row so replay can re-score at any smaller k — and harness passthrough `extra` keys never override the scored fields. Pinned by `test/longmemeval-metrics.test.ts`.
- `src/eval/longmemeval/run-config.ts` — the resolved retrieval pins, `retrieval_config_hash`, the `run_config` receipt block, secret redaction, and the `--question-ids` loader. Pure given its inputs (the harness resolves the mode bundle and the embedder string and passes them in). `RetrievalPins` = `{mode, keyword_only, reranker: {enabled, model}, autocut, expansion, expansion_variant_budget, embedder (model@dims or 'unconfigured'), top_k, trajectory}`; `retrievalConfigHash(pins, {knobs_hash, knobs_hash_version})` is sha256 over `stableStringify` (sorted keys at every level) of the pins PLUS the resolved `knobsHash`, so two runs hash equal regardless of flag order, dataset, output path or clock, and a resume file written under a config snapshot that differs in ANY result-shaping knob — not just a pin — is a different run. `redactSecrets` (URL userinfo, bearer tokens, secret-looking `key=value` pairs, provider key prefixes, `?password=`) is applied to every error string BEFORE it lands in a receipt row or the eval ledger. `loadQuestionIds` reads one id per line with `#` comments, dedupes, and throws on a missing or empty file. `buildRunConfig` stamps the summary's `run_config` (pins, `expansion_replay`, dataset sha256 + count, `question_ids_file`, both hashes, the `CacheReceipt` `{path, hits, misses, bypassed, infra_faults, canonical_sha256, sha256}` or `cache: null` + `cache_skipped` reason, and the counters `reranker_skipped_rows`, `vector_degraded_rows`, `expansion_failed_rows`, `expansion_replay_miss`, `gold_missing_from_haystack`, `slug_collisions`, `excluded_abstention`, `errors`).
- `src/eval/longmemeval/resume.ts` — reading a prior run's JSONL back: row scanning, the mixed-run check, expansion-variant replay maps, and per-type bucket re-seeding. INVARIANT: recall is RECOMPUTED, never trusted — `seedBucketsFromRows` re-derives both metrics for every prior row from `retrievedIdsAtK` (prefers `retrieved[]` sliced to k; falls back to the older `retrieved_session_ids` shape) joined against the dataset's gold, so a file written before the raw-id join simply scores false instead of poisoning the summary, and there is no legacy any-only counter. `readJsonlRows` skips corrupt lines (a SIGKILL tail); `isScoredQuestionRow` excludes summaries and hypothesis-less error rows (those are retried); `checkResumeConfigHash` reports rows stamped with a foreign `retrieval_config_hash` (refused by the harness unless `--allow-mixed-run-config`) and tolerates unstamped rows; `loadExpansionReplay` maps `question_id` → recorded `expansion_variants`. Pure given its inputs (file reads are the only I/O).
@@ -279,10 +279,10 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/extraction-review.ts` — Extraction quarantine lane markers, sibling of `src/core/quarantine.ts` / `embed-skip.ts` (frontmatter-key pattern, no schema migration). Auto-extracted stubs from untrusted input carry the PAIR `provenance: 'auto-extracted'` + `status: 'unverified'` (both required — user pages with their own `status`/`provenance` never match). Exports `quarantineMarkers()`, `isUnverifiedExtraction()` (JS predicate) and `unverifiedExtractionFragment(alias)` — the single SQL source of truth consumed by `buildSourceFactorCase` (namespace source-boost guard), both engines' `getUnverifiedExtractionPageIds`, the `extraction_pending` op, and the `unverified_extractions` doctor check, so filter and marker keys can never drift. Consequences: unverified stubs are excluded from the compiled-truth fusion boost + the `people/`/`companies/` source-boost (rank as ordinary content), stamped `unverified: true` in search results (`stampUnverifiedExtractions`, hybrid.ts), listed by `extraction_pending`, promoted (status → `verified`, provenance kept for audit) or rejected (soft-delete) by the owner-only `extraction_review` op. Pinned by `test/extraction-review.test.ts` (PGLite) + `test/e2e/extraction-review-postgres.test.ts` (live Postgres parity).
- `src/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` 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 window `embedPage`'s single-page chunkless branch has. 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`. Every re-embed merge carries per-chunk metadata through the ONE shared `carryChunkMetadata(chunk, loaded)` field list in `src/core/embed-stale.ts` — `modality` plus the code fields (`language`, `symbol_name`, `symbol_type`, `start_line`). This list is load-bearing: `upsertChunks` overwrites from EXCLUDED (not COALESCE), so any re-embed path that omits a field resets it — omitting `modality` flips every image chunk to `modality='text'` and silently zeroes the image search arm (its filter is `cc.modality = 'image'`). Never hand-roll a per-path field list. Pinned by `test/embed-modality-preserved.test.ts`. 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 through `stampIfPageProvenanceComplete` in `src/core/embed-stale.ts` (shared with the minion `embed-backfill` drain, `embedStaleForSource`): the stamp is judged from DB state — every chunk carries an active-column vector whose `model` matches the signature and whose `embedded_text_hash` matches `md5(chunk_text)` — never from the batch subset, because `listStaleChunks` pages by row with no page alignment, so a page straddling a batch boundary is stamped by whichever batch lands its last chunk (a partially-stale page keeping preserved chunks of another model, or a NULL model/hash, 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` 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: 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 single implementation — 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 no inline `let nextIdx = 0` + `Promise.all(Array.from({length: numWorkers}, ...))` pool shape remains). 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`. `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`. The stale path's signature invalidation is PROBE-GATED — a drift pre-count (two `countStaleChunks` calls) followed by one live `probeEmbedder` embed call (from `src/core/embed-stale.ts`; validates a real vector whose dims match the signature's trailing `:<dims>`) must succeed before anything is NULLed, so a misresolved config (temp `GBRAIN_HOME` → default model, no key) can never strip vectors it cannot replace; a failed probe warns loudly on stderr and degrades to NULL-only staleness. Every live stale run also calls `engine.invalidateContentDriftEmbeddings` (not probe-gated — blast radius is bounded by real content edits) so chunks whose `embedded_text_hash` no longer matches `md5(chunk_text)` re-embed from their CURRENT text; NULL hash (pre-v133 rows) is grandfathered. Pinned by `test/embed-stale.serial.test.ts` (probe-gate + content-drift blocks). The `--stale` single-flight lock HEARTBEAT (interval `GBRAIN_EMBED_LOCK_HEARTBEAT_MS`, default 5 min — test seam) is refresh-bounded per tick: each `refresh()` races a per-tick timeout (`GBRAIN_EMBED_LOCK_HEARTBEAT_TIMEOUT_MS`, default 30s via `DEFAULT_EMBED_LOCK_HEARTBEAT_TIMEOUT_MS`) with its own AbortController, so ONE never-settling refresh call can't silence the heartbeat forever; a slow tick never stacks on the next (`beating` guard), a refresh returning false (stolen/released lock) aborts the drain immediately as `lock_lost`, and 3 CONSECUTIVE tick failures (timeouts or throws) also abort as `lock_lost` rather than running without mutual exclusion. The interval is deliberately NOT unref'd (a lost drain promise stays a LOUD hang instead of a silent exit-0 that leaks the locks) while the per-tick timeout timer IS unref'd. `runEmbedCore --stale` also arms the progress-keyed stall watchdog from `src/core/embed-stall.ts` (`GBRAIN_EMBED_STALL_ABORT_SECONDS`, default 900 — see that entry): on stall it aborts the drain, releases the run's self-acquired locks, flushes the summary, and returns `reason: 'stall_timeout'`. Pinned by `test/embed.serial.test.ts` (heartbeat + stall blocks) + `test/jobs-embed-stall-wiring.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 window `embedPage`'s single-page chunkless branch has. 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`. Every re-embed merge carries per-chunk metadata through the ONE shared `carryChunkMetadata(chunk, loaded)` field list in `src/core/embed-stale.ts` — `modality` plus the code fields (`language`, `symbol_name`, `symbol_type`, `start_line`). This list is load-bearing: `upsertChunks` overwrites from EXCLUDED (not COALESCE), so any re-embed path that omits a field resets it — omitting `modality` flips every image chunk to `modality='text'` and silently zeroes the image search arm (its filter is `cc.modality = 'image'`). Never hand-roll a per-path field list. Pinned by `test/embed-modality-preserved.test.ts`. 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 through `stampIfPageProvenanceComplete` in `src/core/embed-stale.ts` (shared with the minion `embed-backfill` drain, `embedStaleForSource`): the stamp is judged from DB state — every chunk carries an active-column vector whose `model` and vector width match the signature and whose `embedded_text_hash` matches `md5(chunk_text)` — never from the batch subset, because `listStaleChunks` pages by row with no page alignment, so a page straddling a batch boundary is stamped by whichever batch lands its last chunk (a partially-stale page keeping preserved chunks of another model, or a NULL model/hash, 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` 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: 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 single implementation — 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 no inline `let nextIdx = 0` + `Promise.all(Array.from({length: numWorkers}, ...))` pool shape remains). 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`. `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`. The stale path's signature invalidation is PROBE-GATED — a drift pre-count (two `countStaleChunks` calls) followed by one live `probeEmbedder` embed call (from `src/core/embed-stale.ts`; validates a real vector whose dims match the signature's trailing `:<dims>`) must succeed before anything is NULLed, so a misresolved config (temp `GBRAIN_HOME` → default model, no key) can never strip vectors it cannot replace; a failed probe warns loudly on stderr and degrades to NULL-only staleness. Every live stale run also calls `engine.invalidateContentDriftEmbeddings` (not probe-gated — blast radius is bounded by real content edits) so chunks whose `embedded_text_hash` no longer matches `md5(chunk_text)` re-embed from their CURRENT text; NULL hash (pre-v133 rows) is grandfathered. Pinned by `test/embed-stale.serial.test.ts` (probe-gate + content-drift blocks). The `--stale` single-flight lock HEARTBEAT (interval `GBRAIN_EMBED_LOCK_HEARTBEAT_MS`, default 5 min — test seam) is refresh-bounded per tick: each `refresh()` races a per-tick timeout (`GBRAIN_EMBED_LOCK_HEARTBEAT_TIMEOUT_MS`, default 30s via `DEFAULT_EMBED_LOCK_HEARTBEAT_TIMEOUT_MS`) with its own AbortController, so ONE never-settling refresh call can't silence the heartbeat forever; a slow tick never stacks on the next (`beating` guard), a refresh returning false (stolen/released lock) aborts the drain immediately as `lock_lost`, and 3 CONSECUTIVE tick failures (timeouts or throws) also abort as `lock_lost` rather than running without mutual exclusion. The interval is deliberately NOT unref'd (a lost drain promise stays a LOUD hang instead of a silent exit-0 that leaks the locks) while the per-tick timeout timer IS unref'd. `runEmbedCore --stale` also arms the progress-keyed stall watchdog from `src/core/embed-stall.ts` (`GBRAIN_EMBED_STALL_ABORT_SECONDS`, default 900 — see that entry): on stall it aborts the drain, releases the run's self-acquired locks, flushes the summary, and returns `reason: 'stall_timeout'`. Pinned by `test/embed.serial.test.ts` (heartbeat + stall blocks) + `test/jobs-embed-stall-wiring.serial.test.ts`.
- `src/core/retrieval-upgrade-planner.ts` — legacy ze-switch planner, slated for deletion with the ZeroEntropy removal; CLI-unreachable (the ze-switch shim refuses every operation) and kept ONLY as a test vehicle: `applyRetrievalUpgrade`/`resumeRetrievalUpgrade` carry the multimodal-column preservation pins and env-override gate cases in `test/retrieval-upgrade-planner.test.ts` + `test/ze-switch-env-override.test.ts`. The shared primitives (`runSchemaTransition`, `transitionDimPinnedColumn`, `TEXT_EMBEDDING_DIM_PINNED_TABLES`, `detectEnvOverride`, `EnvOverrideWarning`, `formatEnvOverrideWarning`) LIVE in `embedding-migration.ts`; this file re-exports them until the deletion. Its resume/undo paths probe `readContentChunksEmbeddingDim` first and skip the schema transition when the column is already at the target width — a same-width DROP+ADD still deletes every stored vector. Note the plane caveat: apply/undo write DB-plane config (`engine.setConfig`) that the file-plane-canonical embed pipeline does not read.
- `src/core/embedding-migration.ts` — provider-agnostic embedding migration core; owns the schema-transition + env-gate primitives. `runSchemaTransition(engine, targetDim)`: ONE transaction rebuilds all three dim-pinned text-embedding-space columns (`content_chunks.embedding`, `query_cache.embedding`, `facts.embedding`) preserving each column's `vector`/`halfvec` type, HNSW gated on `hnswIndexExpected` (dims > 2000 skip the index; exact scans stay correct — 2048d targets work); image/multimodal columns deliberately untouched; AFTER commit it clears `embedded_at` in yielding 50k batches (belt-and-braces hygiene — read surfaces key on the vector itself). `planEmbeddingMigration`: workload via widened stale predicates (absent-column fallback counts every chunk), cost, `signature_census` (top-5 page signatures — DB-reality corroboration of From), `synopsis_tier_pages` (context-tier downgrade consent), bundle-aware `reranker_warning`, `dim_change` via the shared `schemaRebuildNeeded` (null ⇒ rebuild, same computation apply uses). `applyEmbeddingMigration`: env≠target refusal (`detectEnvOverride`; `detectEnvPresence` drives the ==target notice) → marker v2 write (same-target re-apply preserves `started_at`; retarget records `superseded` history + `force_sunset_target`) → full rebuild when the chunks column is off-width, else INDEPENDENT repair of stale dim-pinned columns (`readDimPinnedWidths`) → false-target-stamp clearing (chunk-model truth) + guarded NULL-signature-inclusive invalidation (embed_skip pages' retained vectors preserved; both via `embedding-invalidation.ts`) BEFORE config writes (same-dim-swap crash safety) → DB plane → file-plane callback → cache purge. `verifyMigrationComplete`: the ONLY basis for "nothing to migrate" — column + pinned widths, wide stale census, false-stamp census blocker (embedded chunks whose `model` contradicts a page already stamped with the target signature), `missing_embeddings` residue, chunkless-pages census, embed_skip-NULL visibility (report-only detail, never a blocker), marker state, un-merged file plane (or env-canonical), env-contradiction blocker; never trusts `from_model`. `completeEmbeddingMigration`: marker delete + completion stamp in ONE transaction (no lost-receipt crash window); accepts content-free `extra` (smoke-check outcome). `readMigrationState` (corrupt-safe), `readMigrationStatus` (read-only, spend-free, everything-degrades-to-null), `verifySearchRoundTrip` (completion smoke check: query-side `embedQuery` + `searchVector`, hit identity by page_id, NEVER throws, warn-don't-block, content-free samples), `resolveRerankerExposure`/`resolveRerankerPlan`/`applyRerankerAction` (D8 companion switch: bundle-resolved exposure; auto→target-provider default reranker, never a silent third provider; config write + cache purge in one tx), `reconcilePageSignatures` (batch-boundary stamp repair). Engine-pure; every step idempotent under crash + re-run — the NULL-embedding column is the checkpoint. Pinned by `test/embedding-migration.test.ts`, `test/migrate-embeddings-hardening.serial.test.ts`, `test/e2e/migrate-embeddings-postgres.test.ts`.
-- `src/core/embedding-invalidation.ts` — signature-truth guards shared by the migration + embed paths, engine-pure via `executeRaw` (identical SQL on both engines). `invalidateStaleSignatureEmbeddingsGuarded(engine, {signature, sourceId?, includeNullSignature?})`: same semantics as the engines' `invalidateStaleSignatureEmbeddings` PLUS the `NOT (frontmatter ? 'embed_skip')` predicate every stale selector applies — never NULL what nothing will re-embed (without it a migration would destroy vectors retained on embed_skip pages permanently and silently). ALL invalidation call sites (`applyEmbeddingMigration`, `runEmbedCore`, `embedStaleChunks`) route through it. `countFalseStampedChunks` / `clearFalseStampedSignatures`: the chunk-model truth cross-check — pages stamped WITH the target signature whose embedded chunks' `model` names another provider (bare provider-less model tails exempt, no surprise paid re-embed); count feeds plan/verify/`--status` honesty, clear runs in apply so the NULL-signature-inclusive invalidation re-embeds them. Pinned by `test/embedding-migration.test.ts` (`#4305 false target stamps + #4306 embed_skip-safe invalidation`).
+- `src/core/embedding-invalidation.ts` — signature-truth guards shared by the migration + embed paths, engine-pure via `executeRaw` (identical SQL on both engines). `invalidateStaleSignatureEmbeddingsGuarded(engine, {signature, sourceId?, includeNullSignature?})`: same semantics as the engines' `invalidateStaleSignatureEmbeddings` PLUS the `NOT (frontmatter ? 'embed_skip')` predicate every stale selector applies — never NULL what nothing will re-embed (without it a migration would destroy vectors retained on embed_skip pages permanently and silently). Chunks whose model, current text hash, and vector width already match the target are preserved across interrupted batches, and fully current pages are restamped without another embedding call. Both engines use the shared current-space predicate. ALL invalidation call sites (`applyEmbeddingMigration`, `runEmbedCore`, `embedStaleChunks`) route through it. `countFalseStampedChunks` / `clearFalseStampedSignatures`: the chunk-model truth cross-check — pages stamped WITH the target signature whose embedded chunks' `model` names another provider (bare provider-less model tails exempt, no surprise paid re-embed); count feeds plan/verify/`--status` honesty, clear runs in apply so the NULL-signature-inclusive invalidation re-embeds them. Pinned by `test/embedding-migration.test.ts` (`#4305 false target stamps + #4306 embed_skip-safe invalidation`).
- `src/core/ze-exposure.ts` — ZeroEntropy sunset exposure detection: the one shared answer to "is this brain still depending on ZeroEntropy?", consumed by the `v0_46_3` version migration (`src/commands/migrations/v0_46_3.ts`) and the stage-2 upgrade banner. Standalone module by design — it must outlive the ze-switch/retrieval-upgrade subsystem. `detectZeExposure(engine, fileCfg?, env?)` resolves exposure from the EFFECTIVE embedding model (env `GBRAIN_EMBEDDING_MODEL` → file `embedding_model` → the legacy configless runtime fallback — resolution-based, NOT vector evidence, so a configless brain is exposed even with zero vectors), the resolved reranker (through `resolveSearchMode`, the same plane search actually reranks with — the bundle default is Voyage, so only an explicit `zeroentropyai:*` `search.reranker.model` row exposes), and ZE-backed custom `embedding_columns` (file + DB planes). Tri-state `status`: a failed DB probe downgrades to `'unknown'`, never to `'clear'` — callers nag on `'unknown'` (fail-safe). Blast-radius counts (ZE-stamped pages, embedded chunks, est. re-embed cost at the recommended target) are LIMIT-capped at `BLAST_RADIUS_CAP` (100K) so a million-chunk brain can't stall apply-migrations on a full-table COUNT; blast-radius probe failures are informational and never flip status. `renderZeActionRequired(exposure)` renders the shared ACTION REQUIRED body both consumers wrap (migrate command with `--dim 1024` + the 1280-not-a-valid-Voyage-width note, the `voyage:rerank-2.5` reranker fix, the no-automated-custom-column-off-ramp honesty, and the env-override callout when `GBRAIN_EMBEDDING_MODEL` itself forces ZE).
- `src/commands/migrate-embeddings.ts` — `gbrain migrate embeddings --to <provider:model> [--dim N] [--dry-run] [--yes] [--json] [--no-embed] [--status] [--reranker auto|off|keep|<model>] [--retarget] [--batch-size N] [--pace[=mode]] [--ignore-env-override] [--force-sunset-target]` (alias: `gbrain retrieval-upgrade`, slated for removal). ONE shared orchestrator for CLI and the `migrate_embeddings` op: `planMigrationFlow` (plan + `verifyMigrationComplete` + env presence + un-merged file plane + brain/DB identity via `redactPgUrl` + concurrent-writer census + reranker plan + in-flight-other marker) and `executeMigrationFlow` (global `gbrain-embedding-migration` DbLock → retarget gate under it → all-source embed locks sorted with `includeArchived` → live embed probe → apply → reranker probe + switch → drain via `runEmbedCore({heldLocks, …})` so the migration never lock_skips itself, with a 5-min heartbeat whose refresh-false/3-errors ABORTS as `lock_lost` → reconcile → completion smoke check stamped into the marker → transactional complete; locks released in finally). The skip path exits 0 ONLY on `verify.complete` with no pending retarget decision and no pending reranker action (a resolved switch/disable runs as a config-only completion). `--status` is read-only/spend-free and never refuses on env (it REPORTS planes, key PRESENCE booleans only, censuses, markers verbatim incl. corrupt, the exact resume command, and the last completion + smoke-check outcome). `persistEmbeddingFileConfig` writes through `loadConfigFileOnly` (never persists env-sourced keys) and supports env-canonical no-file deployments (env pins target ⇒ proceed with notice). Exit codes: 0 completed/verified-no-work, 1 locked/refused/failed/incomplete (message names which; lock_skipped and lock_lost get their own copy), 2 non-TTY without `--yes`. Pinned by `test/migrate-embeddings-flow.serial.test.ts`, `test/migrate-embeddings-boundary.serial.test.ts`, `test/migrate-embeddings-hardening.serial.test.ts`. Discovery surfaces all render the canonical command from `renderCanonicalMigrationCommands` (`src/core/ai/defaults.ts`): gateway deprecation line, init warnings, upgrade ACTION REQUIRED banner, doctor `provider_sunset`, ze-switch refusal, advisor — drift-guarded by `test/canonical-migration-command.test.ts`; the shutdown date lives once as `ZEROENTROPY_SUNSET_DATE` in `defaults.ts`.
- `src/commands/ze-switch.ts` — pure refusal/redirect shim for the sunset ZeroEntropy switch. Every invocation refuses or redirects with exit 1 and `reason: 'provider_sunset'`, printing the off-ramp (`gbrain migrate embeddings --to voyage:voyage-4 --dim 1024 --dry-run`); the `--json` refusal envelope is `{status:'refused', reason:'provider_sunset', migrate, migrate_preview, message}` (live command + cost preview, each carrying an explicit `--brain` suffix); `--undo` REDIRECTS (reads the `ze_switch_previous_snapshot` config row and prints the exact migrate command that returns the brain to its pre-switch provider — `{status:'redirected', reason:'provider_sunset', undo_command, undo_preview, message}` in `--json`; missing/corrupt snapshot degrades to the refusal); `--help` answers engine-free via `CLI_ONLY_SELF_HELP` + the `SELF_HELP_WITHOUT_ENGINE` wrapper in cli.ts (exit 0, truthful sunset copy). Its flags stay REGISTERED (quoted literals feed the generated registry row) so existing scripts reach the refusal instead of a pre-dispatch unknown-flag error — the shim never consults them. Nothing here mutates the brain. The whole command is slated for removal after the sunset. Pinned by `test/ze-switch-cli.test.ts` + `test/cli-help-without-brain.serial.test.ts`.
@@ -336,7 +336,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/minions/supervisor-pid.ts` — `readSupervisorPid(pidFile) → {pid, running}`: the shared `existsSync → readFileSync → parseInt → process.kill(pid,0)` PID-file + liveness reader shared by `jobs.ts` (supervisor status), `jobs.ts` (stats), and `doctor.ts`. EPERM from the liveness probe counts as running. Pinned by `test/supervisor-pid.test.ts`.
- `src/core/minions/handler-timeouts.ts` — per-handler-type defaults for BOTH per-job time knobs, co-located so they can't drift apart unseen (they are different quantities: the budget bounds total runtime, the lease bounds dead-worker reclaim — never derive one from the other). `HANDLER_DEFAULT_TIMEOUT_MS`: 30 min for `subagent`, `subagent_aggregator`, `embed-backfill`, `autopilot-cycle`, `autopilot-global-maintenance`; 10 min for `chronicle_extract` + `facts-absorb`; 60 min for `contextual_reindex_per_chunk`. `HANDLER_DEFAULT_LOCK_DURATION_MS`: 300 s for the long LLM/loop handlers, 120 s for the single-LLM-call handlers, `shell` deliberately absent (fast dead-worker reclaim; verify-before-evict protects it anyway). `defaultTimeoutMsFor` / `defaultLockDurationMsFor` return the mapped default or `null` (short handlers keep the tight null-default wall-clock / the 30 s worker lease). `clampLockDurationMs` + `LOCK_DURATION_MS_MIN/MAX` ([5s, 1h]) is the ONE clamp shared by `queue.add`, the CLI `--lock-duration-ms` flag (`--dry-run` echoes the clamped value), and the MCP `submit_job` param; the same bound is mirrored in SQL at claim time and by the `minion_jobs.lock_duration_ms` range CHECK, so every layer agrees. Layers (explicit value always wins): `MinionQueue.add()` stamps at submit; `MinionQueue.claim()` COALESCEs NULL columns from the maps (durable invariant); migration v128 one-shot backfilled `timeout_ms` with authoring-time snapshot values — do NOT sync v128 when editing the maps (`lock_duration_ms` has no backfill: NULL = worker default). Pinned by `test/minions.test.ts` + `test/migrations-v128.test.ts` + `test/migrations-v130.test.ts`.
- `src/core/minions/admission.ts` — submit-side queue admission control (the drain-side pool-starvation half is the job-isolation work; claim fairness is a filed TODO, deliberately out of scope). Three primitives resolved per name via `resolveAdmissionPolicy` (config `minions.*` > per-name defaults tables, 60s in-process cache, fail-open with a once-per-process stderr warn; env kill-switch `GBRAIN_MINIONS_ADMISSION=0` disables all three): PARAM-COALESCING (`PARAM_COALESCE_DEFAULT` — on for `subagent`; `computeParamHash` = sha256 of stable-stringified payload excluding only `__param_hash` itself — `__owner_client_id` is deliberately INCLUDED so owner lanes never cross; parentless + waiting-only + age-bounded to ttl/2), WAITING-TTL (`WAITING_TTL_DEFAULT_HOURS` — 48h for `subagent`; swept by `MinionQueue.handleWaitingTTL` through `cancelJobs(ids, {reason, rootStatuses:['waiting']})` so descendants cancel, child_done lands, aggregator parents resolve, and the reason stamps ROOT ids only; ≤500/tick oldest-first; warn-before-act is `runWaitingTtlTick` — first tick counts affected + stamps `TTL_NOTICE_SHOWN_KEY` with an ISO timestamp, sweeping starts only after `ttlNoticeGraceMs()` (1h default, env `GBRAIN_MINIONS_TTL_NOTICE_GRACE_MS`) elapses; `gbrain upgrade` prints the same one-shot notice and starts the same clock; legacy `'true'` flag values sweep immediately), and NAME-GLOBAL QUOTA (`QUOTA_MAX_WAITING_DEFAULT` EMPTY by operator decision — activates only via `minions.quota_max_waiting.<name>`; counts the name across ALL queues so per-run `dream-inline-*` fanout queues can't dodge it, EXACT under concurrency via a `minion_quota:<name>` advisory xact lock taken only when a quota is configured; throws typed `QueueQuotaExceededError`, checked everywhere via `isQueueQuotaExceededError` — dream submitters record a phase skip, synthesize rolls back the current transcript's fresh chunks, agent fanout cancels the whole tree, `submit_agent` maps to a structured `rate_limited` OperationError). `TTL_REASON_PREFIX` is the single source for the sweep's error_text prefix and the stats/doctor LIKE patterns; `safeConfigSegment` gates untrusted job names out of copy-pasteable config hints. Alerting rides `getStats` (`drained_completed/failed/dead/cancelled` keyed on finished_at + `waiting_now` + `oldest_waiting_minutes`), the `jobs stats` DIVERGENT-QUEUE / waiting-TTL screams (`GBRAIN_QUEUE_DIVERGENCE_RATIO`=2, `GBRAIN_QUEUE_DIVERGENCE_MIN_WAITING`=50; divergence compares intake vs COMPLETED so TTL-cancel storms can't masquerade as throughput) + `--json`, and doctor `checkQueueHealth`. Pinned by `test/minions-admission.test.ts` + `test/jobs-stats-divergence.serial.test.ts`.
-- `src/core/minions/types.ts` — `MinionJobInput` + `MinionJobStatus` + handler context types. `MinionJobInput.max_stalled` is optional; omitted values let the schema DEFAULT (5) kick in, provided values are clamped to `[1, 100]`.
+- `src/core/minions/types.ts` — `MinionJobInput` + `MinionJobStatus` + handler context types. `MinionJobInput.max_stalled` is optional; omitted values let the schema DEFAULT (5) kick in, provided values are clamped to `[1, 100]`. `SubagentHandlerData.require_writes` requires at least one settled successful page write, not merely a clean model finish.
- `src/core/minions/errors.ts` — dependency-free `UnrecoverableError`, re-exported through `types.ts` for compatibility. Delegated policy imports this leaf directly, avoiding initialization cycles through durable authority. Fresh-process import tests preserve the shared error identity and isolated-worker reconstruction.
- `src/core/minions/protected-names.ts` — side-effect-free constant module exporting `PROTECTED_JOB_NAMES` + `isProtectedJobName()`. Kept pure so queue core can import without loading handler modules. `PROTECTED_JOB_NAMES` includes `synthesize`, `patterns`, `consolidate`. These phases internally submit `subagent` children with `allowProtectedSubmit=true` and can spend Anthropic credits. Only trusted local callers (CLI, autopilot, `doctor --remediate`) can submit them; MCP requests are rejected by `submit_job`'s protected-name guard.
- `src/core/minions/handlers/shell.ts` — `shell` job handler. Spawns `/bin/sh -c cmd` (absolute path, PATH-override-safe) or `argv[0] argv[1..]` (no shell). Env allowlist `PATH, HOME, USER, LANG, TZ, NODE_ENV` + caller `env:` overrides + `inherit:`-resolved keys. UTF-8-safe stdout/stderr tail via `string_decoder.StringDecoder`. Abort (either `ctx.signal` or `ctx.shutdownSignal`) fires SIGTERM → 5s grace → SIGKILL on child. Requires `GBRAIN_ALLOW_SHELL_JOBS=1` on worker (gated by `registerBuiltinHandlers`). `ShellJobParams.inherit?: string[]` is a free-form list of snake_case config-key names; the worker resolves each via `loadConfig()` and injects the value under the derived env key (`database_url` → `GBRAIN_DATABASE_URL`; else uppercased). Names persist in `minion_jobs.data` (and the shell-audit JSONL); values never do. The canonical validator `validateShellJobParams` (sibling `shell-validate.ts`) runs PRE-ENQUEUE in both submit surfaces — `gbrain jobs submit shell` (jobs.ts:271) AND the `submit_job` op for `name='shell'` (operations.ts:2085); the handler-entry re-validation here is defense-in-depth (so validation can never run only AFTER `queue.add()` has persisted the row). The validator does NOT police which config keys the agent inherits — same-uid trust model treats the agent as a peer of the worker.
@@ -347,9 +347,9 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/minions/handlers/shell-audit.ts` — per-submission JSONL audit trail at `~/.gbrain/audit/shell-jobs-YYYY-Www.jsonl` (ISO-week rotation; override via `GBRAIN_AUDIT_DIR`). Best-effort: `mkdirSync(recursive)` + `appendFileSync`; failures logged to stderr, submission not blocked. Logs cmd (first 80 chars) or argv (JSON array). Never logs env values.
- `src/core/minions/handlers/supervisor-audit.ts` — supervisor lifecycle JSONL audit at `~/.gbrain/audit/supervisor-YYYY-Www.jsonl` (ISO-week rotation; shares `computeIsoWeekName()` with `shell-audit.ts`). `writeSupervisorEvent(emission, supervisorPid)` appends one line per event (`started`, `worker_spawned`, `worker_exited`, `backoff`, `health_warn`, `health_error`, `max_crashes_exceeded`, `shutting_down`, `stopped`, `worker_spawn_failed`). `readSupervisorEvents({sinceMs})` is the readback for `gbrain doctor`. Exports `isCrashExit(event)`, `summarizeCrashes(events)`, `CrashSummary` type, and `CLEAN_EXIT_CAUSES` denylist (`'clean_exit' | 'graceful_shutdown'`). Single shared point — both `gbrain doctor` (supervisor check) and `gbrain jobs supervisor status` import from here so the two surfaces can't drift. `isCrashExit` classifies a single `worker_exited` against the denylist: clean/graceful are NON-crashes; everything else (incl. any future `likely_cause` from `child-worker-supervisor.ts`) is a crash; audit lines lacking `likely_cause` fall back to `code !== 0`. `summarizeCrashes` returns `{total, by_cause: {runtime_error, oom_or_external_kill, unknown, legacy}, clean_exits}` — the `legacy` bucket catches both old fallback entries AND unrecognized future causes (fail-loud, not silent underreport); denylist-over-allowlist is deliberate. Pinned by `test/supervisor-audit.test.ts` (14 cases) and 4 source-grep wiring assertions in `test/doctor.test.ts`.
- `src/core/minions/backpressure-audit.ts` — sibling of shell-audit.ts for `maxWaiting` AND `maxPending` coalesce events. JSONL at `~/.gbrain/audit/backpressure-YYYY-Www.jsonl`. One line per coalesce with `(queue, name, waiting_count/max_waiting OR pending_count/max_pending, returned_job_id, ts)`. `readRecentCoalesceCounts` feeds the `jobs stats` Backpressure line (reads current + previous ISO-week files so a 24h window survives week boundaries, filtered per queue). Makes the backpressure guards' coalesces visible instead of silent drops. Pinned by `test/backpressure-audit-read.test.ts`.
-- `src/core/minions/handlers/subagent.ts` — LLM-loop handler. Two-phase tool persistence (pending → complete/failed), replay reconciliation for mid-dispatch crashes, dual-signal abort (`ctx.signal` + `ctx.shutdownSignal`), Anthropic prompt caching on system + tool defs. `makeSubagentHandler({engine, client?, ...})` factory; `MessagesClient` is an injectable interface the real SDK implements structurally. Per-turn output cap resolves via `resolveMaxOutputTokens` (`data.max_tokens` → `agent.max_output_tokens` config → 8192 default); a `stop_reason: 'max_tokens'` final turn surfaces as `SubagentStopReason 'max_tokens'` (not a silent `end_turn`), and a max_tokens stop mid-tool-round injects a truncation note into the tool-result turn so the model re-issues the dropped call. Throws `RateLeaseUnavailableError` (renewable) when rate-lease capacity is full. Both loop paths (the direct Anthropic SDK turn loop and the gateway toolLoop's `acquireTurnPermit`) heartbeat the held lease at ttl/3 for the duration of each provider call — single-flight renewals so a stalled renewal never stacks behind a starved pool; a FALSE renewal means the lease row was pruned/stolen (the slot is already re-admitted), so the in-flight call aborts and converts to a lease-full requeue instead of running above `maxConcurrent`. Anthropic 400 `prompt is too long` responses (status 400 + body matches `/prompt is too long|prompt_too_long|context.*length/i`) classify as `UnrecoverableError` so the job goes straight to `dead` on first attempt instead of stalling three times. Catches both initial-prompt overflow and turn-N tool-loop accumulation that `synthesize.ts`'s chunker can't bound ahead of time. terminal-state short-circuit on resume. When a stored message thread already ends in `stop_reason: 'end_turn'`, the handler returns `{ ok: true }` immediately instead of issuing another `messages.create` call (re-prompting past `end_turn` would get a 400 and dead-letter an already-successful job). Pinned by `test/subagent-handler.test.ts`. Oneshot dispatch: `data.mode === 'oneshot'` on a FRESH job (zero persisted messages) routes to `runSubagentOneshot` (subagent-oneshot.ts) before either loop; a validation fallback re-enters the loops in the SAME job, stamped `synth_mode_used: 'agentic_fallback'` + `fallback_reason`. Write accounting (`finalizeWriteAccounting` in subagent-persistence.ts): every job's result carries pages_attempted/written/failed derived from the tool-execution ledger (settled rows only); `data.require_writes` jobs (dream synthesize + patterns fan-outs) throw UnrecoverableError → dead when attempted>0 with zero successes. `resolveMaxOutputTokens` takes the model: thinking-by-default models (Claude 5 by name or recipe-declared `thinking_by_default` such as DeepSeek v4, via the gateway's shared `isThinkingModel`) default to 32000 when neither per-job nor config caps are set. Gateway-path `onToolCallStart` has a uniq_subagent_tools_use_id backstop: a provider repeating a tool id across turns persists under a `#m<idx>o<ordinal>`-suffixed debug id (second violation reconciles to the existing row's gbrain_tool_use_id) instead of dead-lettering the job. Persistence helpers live in subagent-persistence.ts (pure peel; `__testing` unchanged). Tool-execution rows carry NO job-wide unique on the raw provider `tool_use_id` (migration v131 drops `uniq_subagent_tools_use_id`: providers like claude-cli legitimately re-mint the same short id every turn, and a collision would dead-letter the job); row identity is the stable `(job_id, message_idx, ordinal)` unique, and readers/settlement resolve an execution by `(message_idx, tool_use_id)`. Settle writes (complete/failed) target exactly ONE row — the call's own ordinal first, then a legacy ordinal=NULL row, never a row that already settled complete (a broader status disjunct could only capture a same-id sibling's row); pending inserts guard legacy NULL-ordinal rows via NOT EXISTS and use the stable-id `ON CONFLICT` as the zombie-worker backstop. Replay/reconcile resolve an execution by persisted ordinal first (validated against the raw id), then by `(message_idx, tool_use_id)` only when the id is unique within the turn, then the same-tool legacy positional fallback. Mixed-version window: a still-running pre-v131 `gbrain jobs work` daemon errors on tool persistence after the migration until it restarts (its two-phase writes targeted the dropped constraint)
+- `src/core/minions/handlers/subagent.ts` — LLM-loop handler. Two-phase tool persistence (pending → complete/failed), replay reconciliation for mid-dispatch crashes, dual-signal abort (`ctx.signal` + `ctx.shutdownSignal`), Anthropic prompt caching on system + tool defs. `makeSubagentHandler({engine, client?, ...})` factory; `MessagesClient` is an injectable interface the real SDK implements structurally. Per-turn output cap resolves via `resolveMaxOutputTokens` (`data.max_tokens` → `agent.max_output_tokens` config → 8192 default); a `stop_reason: 'max_tokens'` final turn surfaces as `SubagentStopReason 'max_tokens'` (not a silent `end_turn`), and a max_tokens stop mid-tool-round injects a truncation note into the tool-result turn so the model re-issues the dropped call. Throws `RateLeaseUnavailableError` (renewable) when rate-lease capacity is full. Both loop paths (the direct Anthropic SDK turn loop and the gateway toolLoop's `acquireTurnPermit`) heartbeat the held lease at ttl/3 for the duration of each provider call — single-flight renewals so a stalled renewal never stacks behind a starved pool; a FALSE renewal means the lease row was pruned/stolen (the slot is already re-admitted), so the in-flight call aborts and converts to a lease-full requeue instead of running above `maxConcurrent`. Anthropic 400 `prompt is too long` responses (status 400 + body matches `/prompt is too long|prompt_too_long|context.*length/i`) classify as `UnrecoverableError` so the job goes straight to `dead` on first attempt instead of stalling three times. Catches both initial-prompt overflow and turn-N tool-loop accumulation that `synthesize.ts`'s chunker can't bound ahead of time. terminal-state short-circuit on resume. When a stored message thread already ends in `stop_reason: 'end_turn'`, the handler returns `{ ok: true }` immediately instead of issuing another `messages.create` call (re-prompting past `end_turn` would get a 400 and dead-letter an already-successful job). Pinned by `test/subagent-handler.test.ts`. Oneshot dispatch: `data.mode === 'oneshot'` on a FRESH job (zero persisted messages) routes to `runSubagentOneshot` (subagent-oneshot.ts) before either loop; a validation fallback re-enters the loops in the SAME job, stamped `synth_mode_used: 'agentic_fallback'` + `fallback_reason`. Write accounting (`finalizeWriteAccounting` in subagent-persistence.ts): every job's result carries pages_attempted/written/failed derived from the tool-execution ledger (settled rows only); `data.require_writes` jobs (dream synthesize + patterns fan-outs) require at least one settled successful page write; zero successes, including a clean prose-only finish or pending-only ledger, throw UnrecoverableError. Optional-write jobs can still complete without writing. `resolveMaxOutputTokens` takes the model: thinking-by-default models (Claude 5 by name or recipe-declared `thinking_by_default` such as DeepSeek v4, via the gateway's shared `isThinkingModel`) default to 32000 when neither per-job nor config caps are set. Gateway-path `onToolCallStart` has a uniq_subagent_tools_use_id backstop: a provider repeating a tool id across turns persists under a `#m<idx>o<ordinal>`-suffixed debug id (second violation reconciles to the existing row's gbrain_tool_use_id) instead of dead-lettering the job. Persistence helpers live in subagent-persistence.ts (pure peel; `__testing` unchanged). Tool-execution rows carry NO job-wide unique on the raw provider `tool_use_id` (migration v131 drops `uniq_subagent_tools_use_id`: providers like claude-cli legitimately re-mint the same short id every turn, and a collision would dead-letter the job); row identity is the stable `(job_id, message_idx, ordinal)` unique, and readers/settlement resolve an execution by `(message_idx, tool_use_id)`. Settle writes (complete/failed) target exactly ONE row — the call's own ordinal first, then a legacy ordinal=NULL row, never a row that already settled complete (a broader status disjunct could only capture a same-id sibling's row); pending inserts guard legacy NULL-ordinal rows via NOT EXISTS and use the stable-id `ON CONFLICT` as the zombie-worker backstop. Replay/reconcile resolve an execution by persisted ordinal first (validated against the raw id), then by `(message_idx, tool_use_id)` only when the id is unique within the turn, then the same-tool legacy positional fallback. Mixed-version window: a still-running pre-v131 `gbrain jobs work` daemon errors on tool persistence after the migration until it restarts (its two-phase writes targeted the dropped constraint)
- `src/core/minions/handlers/subagent-oneshot.ts` — oneshot synthesis runner. ONE rate-leased tool-less `gateway.chat` call (static `ONESHOT_SYSTEM` JSON contract rides the prompt-cache prefix; sub-budget min(5 min, timeout/4) → `fallback_reason: 'oneshot_timeout'`), then all-or-nothing validation BEFORE any write: JSON contract (`parseOneshotResponse`, ≤12 pages), slug grammar + `allowed_slug_prefixes` + reflections/originals task shape + the exact `oneshot_slug_suffix` (the idempotency boundary, enforced structurally), exact-match wikilink rule against existing ∪ in-batch slugs (`extractWikilinkTargets`; cold-brain relaxation: <5 pages AND no manifest accepts syntactic presence). Writes go through the SAME `brain_put_page` ToolDef the loop uses (fences/side-effects/provenance identical) with `deferEmbeds`, bracketed by standard ledger rows under invocation-scoped ids `oneshot-<inv8>-p<i>`; a post-batch `autoLinkWrittenPage` pass materializes in-batch forward wikilink edges. Ledger-first crash recovery: any prior oneshot rows → finalize from the ledger, never re-call the nondeterministic model. Transcript rows persist ONLY after success (a failed attempt is never replayable as a completed result). Every failure shape returns `{kind:'fallback', reason}` and the same job falls through to the agentic loop. Pinned by `test/minions/subagent-oneshot.test.ts` + the oneshot describes in `test/subagent-handler.test.ts` and `test/e2e/dream-synthesize-pglite.test.ts`. `ONESHOT_SYSTEM` spells out JSON string escaping (quotes, backslashes, line breaks). A parse failure whose reported output usage reaches the requested cap falls back as `length` even when the provider normalized the stop to `end`/`other`; below-cap malformed output stays `unparseable`, and valid JSON at the cap proceeds normally.
-- `src/core/minions/handlers/subagent-persistence.ts` — subagent transcript + tool-execution persistence (pure peel from subagent.ts): loadPriorMessages/Tools/ToolsV2, persistMessage, persistToolExecPending/Complete/Failed (all `$N::text::jsonb` discipline), plus `finalizeWriteAccounting`: derives pages_attempted/written/failed from the job's put_page ledger rows (settled only — pending counts toward neither), merges them into every SubagentResult, and throws UnrecoverableError on require_writes jobs whose every attempted write failed; `scopeToolUseIdPrefix` narrows the scan to the oneshot invocation family.
+- `src/core/minions/handlers/subagent-persistence.ts` — subagent transcript + tool-execution persistence (pure peel from subagent.ts): loadPriorMessages/Tools/ToolsV2, persistMessage, persistToolExecPending/Complete/Failed (all `$N::text::jsonb` discipline), plus `finalizeWriteAccounting`: derives pages_attempted/written/failed from the job's put_page ledger rows (settled only — pending counts toward neither), merges them into every SubagentResult, and throws UnrecoverableError on require_writes jobs with no settled successful write, including zero-attempt clean finishes; `scopeToolUseIdPrefix` narrows the scan to the oneshot invocation family. Fresh `brain_put_page` rejects are normalized by `src/core/minions/tools/put-page-result.ts` before ledger settlement; accounting reclassifies rejected historical completed envelopes (including JSON strings) without changing the stored rows. Unchanged-page saves and persisted pages whose embedding failed still count as writes.
- `src/core/minions/handlers/subagent-aggregator.ts` — `subagent_aggregator` handler. Claims AFTER all children resolve (queue guarantees every terminal child posts a `child_done` inbox message with outcome). Reads inbox via `ctx.readInbox()`, builds a deterministic mixed-outcome markdown summary. No LLM call.
- `src/core/minions/handlers/subagent-audit.ts` — JSONL audit + heartbeat writer at `~/.gbrain/audit/subagent-jobs-YYYY-Www.jsonl`. Events: `submission` (one per submit) + `heartbeat` (per turn boundary: `llm_call_started | llm_call_completed | tool_called | tool_result | tool_failed`, plus the oneshot markers `oneshot_fallback | oneshot_timeout`; oneshot-path events carry `mode: 'oneshot'` and fallback events a `reason` — both rendered by `gbrain agent logs`). Never logs prompts or tool inputs. `readSubagentAuditForJob(jobId, {sinceIso})` is the readback for `gbrain agent logs`.
- `src/core/minions/rate-leases.ts` — lease-based concurrency cap for outbound providers (default key `anthropic:messages`, max via `GBRAIN_ANTHROPIC_MAX_INFLIGHT`). Owner-tagged rows with `expires_at` auto-prune on acquire; `pg_advisory_xact_lock` guards check-then-insert; CASCADE on owning job deletion. `renewLeaseWithBackoff` retries 3x (250/500/1000ms). Canonical home of `RateLeaseUnavailableError` (thrown when acquire finds no slot; the worker and the inline dream drain both recognize it and requeue WITHOUT burning an attempt — lease-full is a scheduling condition, not a failure; `subagent.ts` re-exports it for compatibility) and `leaseFullBackoffMs()` (the shared 1–3s jittered lease-full requeue backoff `worker.ts` and `inline-drain.ts` both use, so the two curves cannot silently desync).
@@ -378,7 +378,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/commands/agent.ts` — `gbrain agent run|logs|register` dispatcher. `run` submits `subagent` (or N children + 1 aggregator) under `{allowProtectedSubmit: true}`; single-entry `--fanout-manifest` short-circuits; children get `on_child_fail: 'continue'` + `max_stalled: 3`; `--follow` is the default on TTY (streams logs + polls `waitForCompletion` in parallel; Ctrl-C detaches, does not cancel). `logs` delegates to `agent-logs.ts`; `register` lazy-imports `agent-register.ts`. Subcommand-aware help is answered BEFORE any engine or queue work and STOPS at the `--` terminator (`agent run -- --help` submits the LITERAL prompt); on a brainless machine (null engine) help still prints while real `run`/`logs` invocations refuse with an init hint.
- `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/agent-register.ts` — `gbrain agent register <name> --harness claude-code|codex|opencode|openclaw`: mints a scoped OAuth client + access token and prints the exact harness wiring in one step (CLI-only, never an MCP op). Composes existing parts — `registerScopedClient` (auth.ts), `exchangeClientCredentials`, the mcp-registration argv builders, `renderCodexHttpServerBlock`, `openclawThinClientBlock` — no new auth machinery. Order is load-bearing: cli.ts pre-connect guards (thin-client refusal + PGLite live-serve probe) → pure parse (exit 2) → preset resolve → source validation (existence + not-archived, engine lane `ANY($1::text[])`) → column pre-flight OUTSIDE any tx (25P02 forbids in-tx degrade) → ONE `engine.transaction` (name-scoped `pg_advisory_xact_lock` → duplicate-name pre-check → `ensureWorkspaceSource` create-or-reuse-only-when-truly-empty (refuses page-, fact-, or file-bearing and archived sources) → `registerScopedClient` with ttl + surface) → COMMIT → post-commit fail-open surface audit → token exchange on the OUTER engine (the tx sql is dead) → serve probe (`probeServeHealth` + the unconditional `SCOPES_MIN_SERVE_VERSION` floor line): a probe-PROVEN pre-scopes serve REFUSES registration (`serve_too_old`) unless `--allow-old-serve` — such a serve verifies scoped tokens as full access; an unreachable serve stays a warning, and the reissue lane warns instead of refusing (the secret is already rotated by that point) → render + print (human, or ONE JSON doc carrying `probe_note` + `serve_warning` from the probe; secrets redacted unless `--show-token`). Presets: `daily-driver` (write one source; federated reads = SNAPSHOT of non-archived sources at registration, EXCLUDING other agents' `*-workspace` scratch sources — a workspace named explicitly in `--federated-read` is still granted, and the print counts the exclusions) and `coding-agent` (write-isolated derived `<name>-workspace` DB-only source; requires `--federated-read`); both default the client to the `starter` surface — override with `--surface` at registration or widen per client via `gbrain auth rescope-client`. Always writes `token_ttl` (default 30 days — the server default is 1 hour and would kill a pasted config). `--url|--port` required (every block embeds the brain URL). A scope blocklist keeps operator-grade scopes on `auth register-client`. `--reissue <client-id>` rotates the secret under the same advisory lock and reprints the block (headed by the stored client_name); rotation is not revocation — outstanding tokens live until expiry. Failure after COMMIT prints the client_id + the exact revoke command (never a false "nothing was created"). openclaw renders the honest thin-client CLI block (no native remote-MCP client upstream yet). Pinned by `test/agent-register.test.ts`.
-- `src/commands/jobs.ts` — `gbrain jobs` CLI subcommands + `gbrain jobs work` daemon. Help is real and guarded: `JOBS_HELP` (full block incl. watch/stats/smoke flags + a footer naming exactly the five subcommands with dedicated help) and `JOBS_SUBCOMMAND_HELP` (work/supervisor/submit/watch/prune) print from a guard at the TOP of `runJobs`, BEFORE the thin-client refusal and the subcommand switch — `jobs work --help` can never start a daemon; only `--help`/`-h` are help tokens (bare `help` can be a job name); cli.ts routes it engine-free via `SELF_HELP_WITHOUT_ENGINE` + `CLI_ONLY_SELF_HELP`. `formatJobDetail` prints the effective wall-clock budget (`Timeout:`/`Deadline:` — 1x deadline kill when claimed, 2x wall-clock backstop, or which default applies) with a Date|string-defensive renderer; `timeout_at` is in `JOB_DATE_FIELDS` for thin-client rehydration. `jobs stats` prints a `Backpressure (24h)` line (per-name coalesce counts from the backpressure audit, current+previous ISO-week files, queue-filtered, best-effort) plus a suppressed-by hint naming the in-flight live-lock job when waiting=0 past the shared `GBRAIN_WEDGED_QUEUE_WARN_MINUTES` threshold — the read-only visibility for maxPending single-flight suppression. Pinned by `test/jobs-subcommand-help.serial.test.ts`, `test/jobs-format-detail.test.ts`, `test/jobs-stats-backpressure.serial.test.ts`. `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 `MinionJobInput` retry/backoff/timeout/idempotency surface as flags: `--max-stalled`, `--backoff-type fixed|exponential`, `--backoff-delay`, `--backoff-jitter`, `--timeout-ms`, `--idempotency-key`, `--max-waiting` (`maxPending` is deliberately internal-only — no flag; see TODOS). `jobs smoke --sigkill-rescue` is the SIGKILL-rescue 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) 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 `MAINTENANCE_PHASES` (mixed ∪ global) 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` 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 includes 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). The `extract` handler routes `{stale: true}` jobs (submitted by performSync's size-gate defer branch) through `extractStaleFromDB` scoped to `data.sourceId`, chaining a continuation job (no maxWaiting — same NULL-sourceId coalesce hazard; timeout derived from `STALE_TIME_BUDGET_MS`) when the sweep's budget leaves `staleRemaining > 0` with forward progress. `parseJobIsolationFlag(args, env?)` (`--job-isolation`, space/= forms, `GBRAIN_JOB_ISOLATION` fallback, default inline); `case 'work'` resolves + fail-fast validates the child CLI invocation and warns when `--max-rss` is combined with isolation (watchdog covers the worker only); `case 'run-child'` is the INTERNAL child entrypoint (quiet registerBuiltinHandlers incl. plugin discovery, CLI owns disconnect+exit); startup warning when a Supabase-shaped engine runs single-pool (kill-switch collapse made loud); the `db_dead` fatal text is verdict-aware (pool starved vs server unreachable). Generic `jobs submit` normalizes the job name once before trust, queueing, handler lookup, and audit; after the admission check and dry-run return, its explicit `ensureSchema()` preflight still runs before shell/handler validation so stale brains retain the canonical init/migration error precedence. On PGLite, `jobs submit embed-backfill` refuses with `no_worker_surface` and a paste-ready inline embed command before any queue access; `--dry-run` evaluates the same read-only feasibility gate and never says “Would submit” for an impossible job. `--follow` is the sole CLI exception because it starts and awaits the inline worker; padded names follow the same normalized path and cannot strand a row. The MCP `submit_job` operation applies the same gate (including dry-run), translates the expected refusal to branchable `OperationError('no_worker_surface')`, and never emits `internal_error` for this capability miss. The `sync` handler forwards `job.data.github_item` ({repo, number, kind}) into `performSync` for github-kind single-item webhook refreshes.
+- `src/commands/jobs.ts` — `gbrain jobs` CLI subcommands + `gbrain jobs work` daemon. Help is real and guarded: `JOBS_HELP` (full block incl. watch/stats/smoke flags + a footer naming exactly the five subcommands with dedicated help) and `JOBS_SUBCOMMAND_HELP` (work/supervisor/submit/watch/prune) print from a guard at the TOP of `runJobs`, BEFORE the thin-client refusal and the subcommand switch — `jobs work --help` can never start a daemon; only `--help`/`-h` are help tokens (bare `help` can be a job name); cli.ts routes it engine-free via `SELF_HELP_WITHOUT_ENGINE` + `CLI_ONLY_SELF_HELP`. `formatJobDetail` prints the effective wall-clock budget (`Timeout:`/`Deadline:` — 1x deadline kill when claimed, 2x wall-clock backstop, or which default applies) with a Date|string-defensive renderer; `timeout_at` is in `JOB_DATE_FIELDS` for thin-client rehydration. `jobs stats` prints a `Backpressure (24h)` line (per-name coalesce counts from the backpressure audit, current+previous ISO-week files, queue-filtered, best-effort) plus a suppressed-by hint naming the in-flight live-lock job when waiting=0 past the shared `GBRAIN_WEDGED_QUEUE_WARN_MINUTES` threshold — the read-only visibility for maxPending single-flight suppression. Pinned by `test/jobs-subcommand-help.serial.test.ts`, `test/jobs-format-detail.test.ts`, `test/jobs-stats-backpressure.serial.test.ts`. `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 `MinionJobInput` retry/backoff/timeout/idempotency surface as flags: `--max-stalled`, `--backoff-type fixed|exponential`, `--backoff-delay`, `--backoff-jitter`, `--timeout-ms`, `--idempotency-key`, `--max-waiting` (`maxPending` is deliberately internal-only — no flag; see TODOS). `jobs smoke --sigkill-rescue` is the SIGKILL-rescue 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) 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 `MAINTENANCE_PHASES` (mixed ∪ global) once (no `sourceId`, `pull:false`) and stamps `autopilot.last_global_at` only when no phase failed, no synthesis/pattern child is incomplete, no work was explicitly budget/triage-deferred, and the run was neither aborted nor lock-stolen; benign warning-only runs remain eligible. `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` 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 includes 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). The `extract` handler routes `{stale: true}` jobs (submitted by performSync's size-gate defer branch) through `extractStaleFromDB` scoped to `data.sourceId`, chaining a continuation job (no maxWaiting — same NULL-sourceId coalesce hazard; timeout derived from `STALE_TIME_BUDGET_MS`) when the sweep's budget leaves `staleRemaining > 0` with forward progress. `parseJobIsolationFlag(args, env?)` (`--job-isolation`, space/= forms, `GBRAIN_JOB_ISOLATION` fallback, default inline); `case 'work'` resolves + fail-fast validates the child CLI invocation and warns when `--max-rss` is combined with isolation (watchdog covers the worker only); `case 'run-child'` is the INTERNAL child entrypoint (quiet registerBuiltinHandlers incl. plugin discovery, CLI owns disconnect+exit); startup warning when a Supabase-shaped engine runs single-pool (kill-switch collapse made loud); the `db_dead` fatal text is verdict-aware (pool starved vs server unreachable). Generic `jobs submit` normalizes the job name once before trust, queueing, handler lookup, and audit; after the admission check and dry-run return, its explicit `ensureSchema()` preflight still runs before shell/handler validation so stale brains retain the canonical init/migration error precedence. On PGLite, `jobs submit embed-backfill` refuses with `no_worker_surface` and a paste-ready inline embed command before any queue access; `--dry-run` evaluates the same read-only feasibility gate and never says “Would submit” for an impossible job. `--follow` is the sole CLI exception because it starts and awaits the inline worker; padded names follow the same normalized path and cannot strand a row. The MCP `submit_job` operation applies the same gate (including dry-run), translates the expected refusal to branchable `OperationError('no_worker_surface')`, and never emits `internal_error` for this capability miss. The `sync` handler forwards `job.data.github_item` ({repo, number, kind}) into `performSync` for github-kind single-item webhook refreshes.
- `src/commands/features.ts` — `gbrain features --json --auto-fix`: usage scan + feature adoption salesman.
- `src/commands/autopilot.ts` — `gbrain autopilot --install`: self-maintaining brain daemon (sync+extract+embed). Freshness sync jobs always send an explicit positive-polarity `pull` value derived from the source's parsed `remote_url`, so local-only sources skip pull and PGLite JSON-string configs behave like Postgres objects. Consumes `detectTini()` from `src/core/minions/spawn-helpers.ts`, resolved once at startup. Composes a `ChildWorkerSupervisor` instance for spawn-and-respawn with `--max-rss 2048` and `maxCrashes: 5`. `onMaxCrashesExceeded` routes through autopilot's own `shutdown('max_crashes')` so the autopilot lockfile gets cleaned up. `shutdown()` drains via `childSupervisor.killChild('SIGTERM')` + `awaitChildExit(35_000)`. Pinned by `test/autopilot-fanout-wiring.test.ts` and `test/autopilot-supervisor-wiring.test.ts` (6 static-shape guards: composes ChildWorkerSupervisor not legacy names, `--max-rss 2048` in argv, `maxCrashes: 5` literal, shutdown-via-callback, no workerProc reference). tick body invokes `runNightlyQualityProbe` when `cfg.autopilot.nightly_quality_probe.enabled === true` (default OFF — opt-in to protect API spend). NO scheduler-side rate-limit check — `runNightlyQualityProbe`'s internal `shouldRunNightly` (reading the audit JSONL) is the single source of truth. Probe call wrapped in try/catch that logs via `logError` and does NOT bump `consecutiveErrors` (probe failure is informational, never crashes the loop). Default `max_usd` cap = 5. Pinned by `test/autopilot-nightly-probe-wiring.test.ts`. per-source `extract_atoms` auto-drain. Postgres-only block after the freshness fan-out: gated on `autopilot.auto_drain.enabled` (default true) AND `!packDeclaresPhase(engine,'extract_atoms')` (the silent-backlog condition) AND per-source `countExtractAtomsBacklog > threshold` (default 25) AND a daily cap `floor(max_usd_per_day / ~$0.30)`. Enumerates `loadAllSources`. Submits the PROTECTED `extract-atoms-drain` job (`{allowProtectedSubmit:true}`) with a UTC-day time-sloted idempotency key `autopilot-extract-atoms-drain:<src.id>:<utcDay>` (a static key would block the source after the first job completed). `src/core/minions/protected-names.ts` lists `extract-atoms-drain`; `src/commands/jobs.ts` registers the handler (thin wrapper over `runExtractAtomsDrainForSource`, `LockUnavailableError` → `{deferred:true}`; a `provider_failure` result throws `formatDrainProviderFailure(result)` — batches/remaining plus the drain's sanitized `last_error` — so the dead-lettered job's `error_text` names the cause, e.g. a missing provider key); `src/core/config.ts` carries the `autopilot.auto_drain.*` config keys + the `autopilot.` key prefix. Pinned by `test/extract-atoms-drain-handler.test.ts`, `test/autopilot-auto-drain-wiring.test.ts`. federated-brain co-existence + launchd hygiene. (1) `LOCK_PATH` resolves via `gbrainPath('autopilot.lock')` so it honors `GBRAIN_HOME` (two brains can run autopilot simultaneously without lock-stealing); lock file stores PID, startup checks `kill -0 <pid>` before refusing to start (a stale lock from a crashed process does not block). (2) exported `classifyReconnectError(err)` returns `'recoverable' | 'unrecoverable'`; unrecoverable causes `process.exit(0)` so launchd backs off instead of looping `config.database_url undefined`. (3) exported pure `generateLaunchdPlist(wrapperPath, home)` sets `ThrottleInterval=300` so launchd respects the exit-0 backoff. Pinned by `test/autopilot-lock-path.test.ts` + `test/autopilot-reconnect-classifier.test.ts`. targeted-submit loop instead of blanket `autopilot-cycle` dispatch. Each tick: cheap `engine.getHealth()` (single SQL count) + `computeRecommendations()`, then route by shape — `score >= 95 AND no plan AND <60min since last full` → sleep; `score >= 95 AND >=60min` → submit `autopilot-cycle` (60-min floor exercises phase-coupling invariants on healthy brains); `plan <= 3 steps AND est <5min` → submit individual handlers; `plan large OR score < 70` → submit full `autopilot-cycle`. The `gbrain-cycle` lock ensures targeted submissions and the full cycle can't run concurrently. `maxWaiting: 1` per submit closes the queue-fan-out vector. daemon env lane: `writeWrapperScript` additively sources `<gbrainDir>/env` (honors `GBRAIN_HOME`) after the shell profiles with a `set -a` wrap so dotenv-style `KEY=value` lines export too, and creates a fully-commented 0600 template on install (never overwritten, never chmod'd, never removed by uninstall; template excludes `GBRAIN_HOME` — the wrapper bakes it AFTER sourcing). Exported pure `chatBootWarning(chatAvailable, gbrainDir)` derives both remediation paths from the passed dir and prints via `console.log` at daemon boot (stdout is the autopilot.log sink on all four targets; stderr lands in the unsurfaced autopilot.err) using the bare global-model `isAvailable('chat')` probe on purpose (mirrors the bare-gated phases; facts extraction is model-aware and doctor owns it). Install is reload-safe so the warning's re-run-`--install` remediation is true: launchd unloads before load (bare load errors on a loaded agent), systemd `try-restart`s after `enable --now`, cron/container print a residual-process notice instead of auto-killing. Pinned by `test/autopilot-install.test.ts` (16 cases incl. real-bash wrapper execution).
- `src/mcp/instructions.ts` — canonical MCP initialize-time agent operating contract. It is compile-time source text (no runtime filesystem dependency; static imports of pure core leaves are fine — the rule bans filesystem/dynamic loading) and is imported by the stdio SDK server, OAuth HTTP SDK server, and legacy raw HTTP initialize path so all transports return the same instructions without drift. The contract covers skill routing, untrusted-content posture, source scope, and the `put_page` whole-page replacement/read-before-write rule. Two append-only extensions compose on top of it, in a fixed order: `buildMcpInstructions({writeback?})` adds the opt-in ambient-writeback section (from `src/core/facts/writeback-instructions.ts`) when `memory.auto_writeback` is enabled — absent/off is BYTE-IDENTICAL to `GBRAIN_MCP_INSTRUCTIONS`, and three exact-equality transport pins depend on that; `resolveMcpInstructions(config, env?, { writeback? })` takes that composed base and appends the operator-set deployment identity LAST under a `Deployment identity:` banner (no transport can weaken the contract): `GBRAIN_MCP_INSTRUCTIONS` env wins when non-blank, else `mcp.instructions` from the FILE plane (`~/.gbrain/config.json`; `gbrain config set|unset mcp.instructions` route there via `FILE_PLANE_DOTTED_KEYS` in `src/commands/config.ts`); an empty or whitespace-only env value is UNSET, not an override, and blank identity + writeback off returns the byte-identical canonical contract. Every transport calls `resolveMcpInstructions` with its own writeback opts: stdio once at boot via the fail-closed resolver (restart-to-flip, the strict-params posture; read failure = OFF bundle, never a wrong visibility posture; a running `gbrain serve` also needs a restart to pick up a new identity); OAuth per request (write-scope-gated, and the section renders only when THIS token's actual visible set — surface filter + bound-client fence — can call `remember`; `extract_facts` advertised under the same predicates); legacy bearer per initialize (surface-clamped: a surface without `remember` gets no section). All three route availability through `ambientOptsFrom(wb, {remember, extractFacts})`. Pinned over a real SDK `StdioClientTransport` by `test/e2e/serve-stdio-roundtrip.test.ts`, over raw HTTP by `test/http-transport.test.ts`, the identity plane (incl. the three-way composition order) by `test/mcp-server-identity.test.ts` + `test/config-set-mcp-instructions.test.ts`, and the enabled-state builder/parity matrix by `test/mcp-instructions-writeback.test.ts`.
@@ -393,7 +393,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/mcp-usage.ts` — `readClientOpUsage(engine, {days})`: the ONE shared reader over `mcp_request_log`, consumed by `gbrain auth clients --usage`, the advisor `mcp-client-fit` collector, and `scripts/derive-starter-ops.ts`. Encodes the row-hygiene rules once (`normalizeLoggedOperation`): JSON-RPC method rows (`tools/list`, `initialize`, …) and `surface_change` audit rows drop; the legacy `tools/call:<name>` prefix strips to the op name, and the hygiene check re-runs on the stripped name (`tools/call:tools/list` is still not an op call). Only `status IN ('success','success_with_warnings')` rows count as usage — denied or erroring traffic cannot "use" its way into starter derivation or advisor fit findings. Windows on `created_at` (rides `idx_mcp_log_time_agent`); plain SQL through `engine.executeRaw`, both engines. Behavioral automation classification: `likely_automation` = >90% of calls are `context_pack`/`delta` boundary verbs (the hook lane is stdio and never logs, so there is no name convention to key on). Sees HTTP clients ONLY — stdio never writes the log. Pinned by test/mcp-usage.test.ts.
- `docs/protocol/MCP_META_CHANNELS.md` — normative `_meta` conventions for MCP tool responses: one producer per top-level key, additive-forever within a key, producer isolation, and the registered-keys table (`brain_hot_memory`, `retrieval`, `warnings`). Anything the model must SEE rides a content block (mainstream harnesses don't feed `_meta` to the model); `_meta` serves structured consumers. Add a key by registering it in the table — one producer, additive-forever.
- `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. `refund(key)` returns one consumed token (capped at the limit) — the `request_tools` persist path refunds when a race-lost 0-row UPDATE (concurrent operator pin) means no write actually happened; dry-run previews never draw a token at all (the limiter meters actual writes only).
-- `src/commands/serve-http.ts` — Express 5 HTTP MCP server with OAuth 2.1, admin dashboard, and SSE live activity feed. The legacy `POST /ingest` queue refuses operation-snapshot clients; they use approved MCP writes so execution stays inside the shared grant contract. Started via `gbrain serve --http [--port N] [--token-ttl N] [--enable-dcr] [--public-url URL] [--bind HOST] [--log-full-params]`. Combines MCP SDK's `mcpAuthRouter` (authorize/token/register/revoke), a custom `client_credentials` handler running BEFORE the router (SDK's token endpoint throws `UnsupportedGrantTypeError` for CC; custom handler falls through for `auth_code` / `refresh_token`), `requireBearerAuth` middleware for `/mcp` with scope enforcement + `localOnly` rejection before op dispatch, and `express-rate-limit` at 50 req / 15 min on `/token`. Serves the built admin SPA from `admin/dist/` with SPA fallback. `/admin/events` SSE broadcasts every MCP request. `cookie-parser` wired (Express 5 has no built-in). Startup logging prints port, engine, issuer URL (honors `--public-url`), client count, DCR status, and the admin bootstrap token line — but the generated token's raw value only prints when stderr is an interactive TTY (`shouldSuppressBootstrapPrint`): a non-TTY (containerized/piped) start hides it so the secret never lands in centralized log storage, env-sourced tokens (`$GBRAIN_ADMIN_BOOTSTRAP_TOKEN`) are always hidden, `--print-admin-token` forces the raw value on a trusted terminal, and `--suppress-bootstrap-token` hides everything. The `/mcp` request handler's OperationContext literal sets `remote: true` explicitly (without it `submit_job`'s protected-name guard would see a falsy undefined and a `read+write`-scoped OAuth token could submit `shell` jobs). `summarizeMcpParams` from `src/mcp/dispatch.ts` feeds both `mcp_request_log` writes and the SSE feed by default (raw via `--log-full-params`). Cookie `Secure` flag set behind HTTPS or a public-URL proxy; magic-link nonce store LRU-bounded; DCR disable routes through the `GBrainOAuthProvider` `dcrDisabled` constructor option (not a router monkey-patch); `transport.handleRequest` wrapped in try/catch to return a JSON-RPC 500 envelope; OperationError + unexpected exceptions unified through `buildError` / `serializeError` so `/mcp` always returns the same envelope. `/health` is liveness-only via `probeLiveness(engine, engineName, version, timeoutMs)` racing `engine.executeRaw('SELECT 1', undefined, { signal })` against the exported `HEALTH_TIMEOUT_MS = 3000`; when the timeout wins, an `AbortController` cancels the Postgres query (PGLite can only discard its eventual result) before the same tagged `ProbeHealthResult` 503 envelope is returned (single timer-cleanup site); body shape `{status, version, engine}` only. Full stats live at admin-only `/admin/api/full-stats` (gated by `requireAdmin`, calls `probeHealth(engine, ...)`) — keeps `getStats()`'s 6× count(*) off the public route so a saturated pool doesn't trigger orchestrator restart cascades. OAuth/admin/audit SQL outside the abortable liveness probe routes through `sqlQueryForEngine(engine)` from `src/core/sql-query.ts` so it works against PGLite; the four `mcp_request_log.params` INSERT sites (success / auth_failed / scope_denied / server-error) go through `executeRawJsonb(engine, ...)` so the column stores real objects (`params->>'op'` returns `search`, not the quoted string). `--bind HOST` defaults `127.0.0.1` (self-hosters pass `--bind 0.0.0.0`); a stderr WARN fires when `--public-url` is set without `--bind`; the banner prints a `Bind:` line. `AuthInfo.sourceId` + `AuthInfo.allowedSources` + `AuthInfo.takesHoldersAllowList` are the typed source of truth, populated by `oauth-provider.ts:verifyAccessToken` (source scope from the `oauth_clients` row; takes-holders from `access_tokens.permissions.takes_holders` for legacy bearer tokens). The `/mcp` dispatch site reads `authInfo.takesHoldersAllowList ?? ['world']` — absent grants (OAuth-client tokens, pre-v29 brains) fail closed to world-only takes visibility, while an explicit `[]` grant is preserved as deny-all; pinned end-to-end by `test/e2e/serve-http-takes-holders.test.ts`. The HTTP MCP `tools/list` handler at `:837-849` uses `paramDefToSchema(v)` from `src/mcp/tool-defs.ts` so array params keep `items` (strict-mode OAuth clients otherwise reject the whole tool list). `POST /ingest` enforces the slug-prefix write fence at the ROUTE, not the op layer: the route hands its payload to the `ingest_capture` minion handler, which deliberately bypasses `put_page`, so no `OperationContext` exists and `enforceClientSlugFence` never runs — a slug-bound client must therefore supply `X-Gbrain-Slug` and it must satisfy `slugUnderBoundPrefixes`, else 403 (without the check a bound client could overwrite any page inside its granted source). The write source is resolved server-side as `authInfo.sourceId ?? 'default'` and travels on the job as `job.data.sourceId`; the caller-supplied `X-Gbrain-Source-Id` header routes nothing and only names the emitter (`webhook-<clientId>`), which is what the event's `source_id` and the 202's back-compat `source_id` field carry. The 202 additionally reports the routed destination as `write_source_id`, and the resolved write source joins the queue idempotency key so a rescoped client lands a new capture instead of deduping against its old job. confidential revoke: a pre-router `/revoke` handler validates the RFC 7009 body, verifies hash-only secrets for both `client_secret_post` and `client_secret_basic`, rejects mixed authentication, preserves the SDK path for public clients, and separates opaque client-auth failures from retryable/backend failures. OAuth metadata advertises both confidential methods. Pinned by `test/e2e/serve-http-oauth.test.ts`. three admin routes: `/admin/api/calibration/profile`, `/admin/api/calibration/charts/:type` (image/svg+xml; type in {brier-trend, domain-bars, pattern-statements, abandoned-threads}), `/admin/api/calibration/pattern/:id` (drill-down). The manual mint route `/admin/api/register-client` accepts optional `source` + `federatedRead` bindings mirroring the CLI's `--source`/`--federated-read` (validated via `normalizeSourceInput`/`normalizeFederatedReadInput` from `src/core/source-id.ts`; omitting both preserves the default binding `source_id='default'` / `federated_read=[source_id]`, invalid values return a structured 400 `invalid_source`), so an admin SPA or provisioning proxy can mint a source-confined client over HTTP. The route mirrors the CLI lane end to end: structured 400s for `unknown_source` / `archived_source` (one batched `ANY($1::text[])` existence check), `invalid_token_ttl` (shared `TOKEN_TTL_MIN/MAX_SECONDS` bounds, integer-validated BEFORE the tx), and `brain_too_old` (column pre-flight OUTSIDE the tx — a pre-scoped-clients brain refuses up front instead of aborting mid-transaction); the duplicate-name pre-check + INSERT run in ONE transaction under the SAME name-scoped advisory lock the CLI takes (`registerClientNameLockKey`), returning 409 `duplicate_name` with the existing `client_id`; the INSERT composes `registerScopedClient` (the CLI's registration core) so the two paths cannot drift; any post-commit failure includes the created `client_id` so the operator can revoke (never a false "nothing was created"). Pinned by `test/register-client-source-normalize.test.ts`. The `/mcp` tools/list is the honest catalog: per-request filters (token scope incl. the `agentCallable` carve-out, bound-client fence via `opAllowedForBoundClient`, publish gates via `disabledOpsForPublishGates`) over the surface-filtered op set, schemas via `buildToolDefs` (strict emission when `mcp.strict_params` resolves reject); the tools/list `mcp_request_log` row records the listed size as `params.tool_count`. Call-time op-level denials the list should have prevented — the inline scope deny, publish-gate backstop (`config_key=...`), fence op-level deny (`fence=op`, classified via `isListLevelDenialEnvelope`) — log `status='denied_after_list'` instead of `'error'` (the trend-to-zero honest-catalog metric, see docs/operations/mcp-surface-runbook.md) — every tools/call row's status resolves through `requestLogStatusForResult` (dispatch.ts) on BOTH transports. The admin health-indicators error rate counts `status NOT IN ('success','success_with_warnings')` and excludes `operation='surface_change'` audit rows from numerator AND denominator (audit rows record operator/self actions, not traffic). Per-request surface resolution lives in `resolveEffectiveSurface`: a `verbs` ceiling skips the default-surface config read, and a failed read applies the last successfully read default per process (fail-closed — a transient config outage cannot widen a NULL-surface client). OAuth protected-resource metadata (RFC 9728) names `/mcp` as the resource (`resourceServerUrl`), so the SDK mounts the PRM at `/.well-known/oauth-protected-resource/mcp` and the 401 `resource_metadata` URL is derived from the same value; the bare root path is kept as an alias by rewriting `req.url` onto the SDK's handler (same document, same CORS). Shutdown: `waitForHttpServerLifecycle` tracks accepted sockets weakly (`trackServerSockets`; Bun never emits socket `close`, so a strong set leaked one per request), severs the still-reachable ones right after `server.close()`, and bounds the close wait at `CLOSE_TIMEOUT_MS` (5s) — a collected keep-alive wrapper whose native handle keeps `close()` from returning gets one stderr line and shutdown proceeds instead of hanging.
+- `src/commands/serve-http.ts` — Express 5 HTTP MCP server with OAuth 2.1, admin dashboard, and SSE live activity feed. The legacy `POST /ingest` queue refuses operation-snapshot clients; they use approved MCP writes so execution stays inside the shared grant contract. Started via `gbrain serve --http [--port N] [--token-ttl N] [--enable-dcr] [--public-url URL] [--bind HOST] [--log-full-params]`. Discovery omits operator-only `agent` scope while DCR still rejects explicit delegation. Combines MCP SDK's `mcpAuthRouter` (authorize/token/register/revoke), a custom `client_credentials` handler running BEFORE the router (SDK's token endpoint throws `UnsupportedGrantTypeError` for CC; custom handler falls through for `auth_code` / `refresh_token`), `requireBearerAuth` middleware for `/mcp` with scope enforcement + `localOnly` rejection before op dispatch, and `express-rate-limit` at 50 req / 15 min on `/token`. Serves the built admin SPA from `admin/dist/` with SPA fallback. `/admin/events` SSE broadcasts every MCP request. `cookie-parser` wired (Express 5 has no built-in). Startup logging prints port, engine, issuer URL (honors `--public-url`), client count, DCR status, and the admin bootstrap token line — but the generated token's raw value only prints when stderr is an interactive TTY (`shouldSuppressBootstrapPrint`): a non-TTY (containerized/piped) start hides it so the secret never lands in centralized log storage, env-sourced tokens (`$GBRAIN_ADMIN_BOOTSTRAP_TOKEN`) are always hidden, `--print-admin-token` forces the raw value on a trusted terminal, and `--suppress-bootstrap-token` hides everything. The `/mcp` request handler's OperationContext literal sets `remote: true` explicitly (without it `submit_job`'s protected-name guard would see a falsy undefined and a `read+write`-scoped OAuth token could submit `shell` jobs). `summarizeMcpParams` from `src/mcp/dispatch.ts` feeds both `mcp_request_log` writes and the SSE feed by default (raw via `--log-full-params`). Cookie `Secure` flag set behind HTTPS or a public-URL proxy; magic-link nonce store LRU-bounded; DCR disable routes through the `GBrainOAuthProvider` `dcrDisabled` constructor option (not a router monkey-patch); `transport.handleRequest` wrapped in try/catch to return a JSON-RPC 500 envelope; OperationError + unexpected exceptions unified through `buildError` / `serializeError` so `/mcp` always returns the same envelope. `/health` is liveness-only via `probeLiveness(engine, engineName, version, timeoutMs)` racing `engine.executeRaw('SELECT 1', undefined, { signal })` against the exported `HEALTH_TIMEOUT_MS = 3000`; when the timeout wins, an `AbortController` cancels the Postgres query (PGLite can only discard its eventual result) before the same tagged `ProbeHealthResult` 503 envelope is returned (single timer-cleanup site); body shape `{status, version, engine}` only. Full stats live at admin-only `/admin/api/full-stats` (gated by `requireAdmin`, calls `probeHealth(engine, ...)`) — keeps `getStats()`'s 6× count(*) off the public route so a saturated pool doesn't trigger orchestrator restart cascades. OAuth/admin/audit SQL outside the abortable liveness probe routes through `sqlQueryForEngine(engine)` from `src/core/sql-query.ts` so it works against PGLite; the four `mcp_request_log.params` INSERT sites (success / auth_failed / scope_denied / server-error) go through `executeRawJsonb(engine, ...)` so the column stores real objects (`params->>'op'` returns `search`, not the quoted string). `--bind HOST` defaults `127.0.0.1` (self-hosters pass `--bind 0.0.0.0`); a stderr WARN fires when `--public-url` is set without `--bind`; the banner prints a `Bind:` line. `AuthInfo.sourceId` + `AuthInfo.allowedSources` + `AuthInfo.takesHoldersAllowList` are the typed source of truth, populated by `oauth-provider.ts:verifyAccessToken` (source scope from the `oauth_clients` row; takes-holders from `access_tokens.permissions.takes_holders` for legacy bearer tokens). The `/mcp` dispatch site reads `authInfo.takesHoldersAllowList ?? ['world']` — absent grants (OAuth-client tokens, pre-v29 brains) fail closed to world-only takes visibility, while an explicit `[]` grant is preserved as deny-all; pinned end-to-end by `test/e2e/serve-http-takes-holders.test.ts`. The HTTP MCP `tools/list` handler at `:837-849` uses `paramDefToSchema(v)` from `src/mcp/tool-defs.ts` so array params keep `items` (strict-mode OAuth clients otherwise reject the whole tool list). `POST /ingest` enforces the slug-prefix write fence at the ROUTE, not the op layer: the route hands its payload to the `ingest_capture` minion handler, which deliberately bypasses `put_page`, so no `OperationContext` exists and `enforceClientSlugFence` never runs — a slug-bound client must therefore supply `X-Gbrain-Slug` and it must satisfy `slugUnderBoundPrefixes`, else 403 (without the check a bound client could overwrite any page inside its granted source). The write source is resolved server-side as `authInfo.sourceId ?? 'default'` and travels on the job as `job.data.sourceId`; the caller-supplied `X-Gbrain-Source-Id` header routes nothing and only names the emitter (`webhook-<clientId>`), which is what the event's `source_id` and the 202's back-compat `source_id` field carry. The 202 additionally reports the routed destination as `write_source_id`, and the resolved write source joins the queue idempotency key so a rescoped client lands a new capture instead of deduping against its old job. confidential revoke: a pre-router `/revoke` handler validates the RFC 7009 body, verifies hash-only secrets for both `client_secret_post` and `client_secret_basic`, rejects mixed authentication, preserves the SDK path for public clients, and separates opaque client-auth failures from retryable/backend failures. OAuth metadata advertises both confidential methods. Pinned by `test/e2e/serve-http-oauth.test.ts`. three admin routes: `/admin/api/calibration/profile`, `/admin/api/calibration/charts/:type` (image/svg+xml; type in {brier-trend, domain-bars, pattern-statements, abandoned-threads}), `/admin/api/calibration/pattern/:id` (drill-down). The manual mint route `/admin/api/register-client` accepts optional `source` + `federatedRead` bindings mirroring the CLI's `--source`/`--federated-read` (validated via `normalizeSourceInput`/`normalizeFederatedReadInput` from `src/core/source-id.ts`; omitting both preserves the default binding `source_id='default'` / `federated_read=[source_id]`, invalid values return a structured 400 `invalid_source`), so an admin SPA or provisioning proxy can mint a source-confined client over HTTP. The route mirrors the CLI lane end to end: structured 400s for `unknown_source` / `archived_source` (one batched `ANY($1::text[])` existence check), `invalid_token_ttl` (shared `TOKEN_TTL_MIN/MAX_SECONDS` bounds, integer-validated BEFORE the tx), and `brain_too_old` (column pre-flight OUTSIDE the tx — a pre-scoped-clients brain refuses up front instead of aborting mid-transaction); the duplicate-name pre-check + INSERT run in ONE transaction under the SAME name-scoped advisory lock the CLI takes (`registerClientNameLockKey`), returning 409 `duplicate_name` with the existing `client_id`; the INSERT composes `registerScopedClient` (the CLI's registration core) so the two paths cannot drift; any post-commit failure includes the created `client_id` so the operator can revoke (never a false "nothing was created"). Pinned by `test/register-client-source-normalize.test.ts`. The `/mcp` tools/list is the honest catalog: per-request filters (token scope incl. the `agentCallable` carve-out, bound-client fence via `opAllowedForBoundClient`, publish gates via `disabledOpsForPublishGates`) over the surface-filtered op set, schemas via `buildToolDefs` (strict emission when `mcp.strict_params` resolves reject); the tools/list `mcp_request_log` row records the listed size as `params.tool_count`. Call-time op-level denials the list should have prevented — the inline scope deny, publish-gate backstop (`config_key=...`), fence op-level deny (`fence=op`, classified via `isListLevelDenialEnvelope`) — log `status='denied_after_list'` instead of `'error'` (the trend-to-zero honest-catalog metric, see docs/operations/mcp-surface-runbook.md) — every tools/call row's status resolves through `requestLogStatusForResult` (dispatch.ts) on BOTH transports. The admin health-indicators error rate counts `status NOT IN ('success','success_with_warnings')` and excludes `operation='surface_change'` audit rows from numerator AND denominator (audit rows record operator/self actions, not traffic). Per-request surface resolution lives in `resolveEffectiveSurface`: a `verbs` ceiling skips the default-surface config read, and a failed read applies the last successfully read default per process (fail-closed — a transient config outage cannot widen a NULL-surface client). OAuth protected-resource metadata (RFC 9728) names `/mcp` as the resource (`resourceServerUrl`), so the SDK mounts the PRM at `/.well-known/oauth-protected-resource/mcp` and the 401 `resource_metadata` URL is derived from the same value; the bare root path is kept as an alias by rewriting `req.url` onto the SDK's handler (same document, same CORS). Shutdown: `waitForHttpServerLifecycle` tracks accepted sockets weakly (`trackServerSockets`; Bun never emits socket `close`, so a strong set leaked one per request), severs the still-reachable ones right after `server.close()`, and bounds the close wait at `CLOSE_TIMEOUT_MS` (5s) — a collected keep-alive wrapper whose native handle keeps `close()` from returning gets one stderr line and shutdown proceeds instead of hanging.
- `src/core/sql-query.ts` — engine-aware tagged-template SQL adapter for OAuth/admin/auth infrastructure. `sqlQueryForEngine(engine)` returns a `SqlQuery` (`(strings, ...values) => Promise<rows[]>`) that walks the template, builds `$N` positional SQL, asserts every value is a `SqlValue` (string | number | bigint | boolean | Date | null), and routes through `engine.executeRaw(sql, params)` (Postgres via postgres.js `unsafe(sql, params)`, PGLite via `db.query(sql, params)`). Deliberately narrower than postgres.js's `sql` tag: no nested fragments, `sql.json()`, `sql.unsafe()`, `sql.begin()`, or array binding — the narrow scalar-only surface is the feature (keeps it from drifting into a partial postgres.js clone). JSONB writes go through `executeRawJsonb(engine, sql, scalarParams, jsonbParams)` which composes positional `$N::jsonb` casts and passes JS **objects** through; an object reaches the wire with the correct type oid, so executeRawJsonb is safe (verified by `test/sql-query.test.ts` on PGLite, `test/e2e/auth-permissions.test.ts:67` on Postgres). Positional binding is NOT universally immune, though: binding a `JSON.stringify(x)` **string** to a bare `$N::jsonb` via `unsafe()` double-encodes it into a jsonb string scalar on real Postgres (PGLite hides it). Fixes: pass a raw object (executeRawJsonb / `sql.json`), or cast through `$N::text::jsonb`. `scripts/check-jsonb-pattern.sh` (template grep) doesn't fire on `executeRawJsonb(...)` because it passes objects; the positional `$N::jsonb` + `JSON.stringify` form is caught by `scripts/check-jsonb-params.mjs`. Also exports `FILES_METADATA_MERGE_SQL`, the one `ON CONFLICT (storage_path)` merge fragment every files upsert (`src/commands/files.ts` x4, `src/core/ops/files.ts` `file_upload`) interpolates: it resets a non-object `files.metadata` to `{}` before the jsonb `||` merge, because `||` array-wraps a non-object left operand and would turn a legacy string-scalar row into `["{}", {...}]` that `gbrain repair-jsonb` can no longer see (pinned by `test/file-upload-fail-closed.test.ts`). Consumed by `src/commands/auth.ts`, `src/commands/serve-http.ts`, `src/core/oauth-provider.ts`, `src/commands/files.ts`, `src/mcp/http-transport.ts` so all five work uniformly against PGLite and Postgres.
- `src/commands/serve.ts` — `gbrain serve` stdio MCP entrypoint with idempotent shutdown across every parent-disconnect signal. Stdio EOF, SIGTERM, SIGINT, SIGHUP, and parent-process death (every reparent case — PID 1, launchd subreaper, systemd, tmux, or a parent shell with `PR_SET_CHILD_SUBREAPER`) all funnel into one `cleanup(reason)` that first awaits `shutdownDelegatedSync()` (idempotent shared promise; a running delegated sync is aborted and settles its checkpoint against the live engine, with the cleanup deadline extended by `GBRAIN_SERVE_SYNC_SETTLE_MS` only while a job runs) and then releases the engine and the PGLite write-lock dir within 5 seconds (otherwise the lock is held indefinitely after Claude Desktop / Cursor / launchd-managed gateways disconnect, forcing a 5-minute stale-lock wait on next start). Watchdog reparent check is `getParentPid() !== initialParentPid` (the `=== 1` check missed the subreaper case under launchd/systemd). Bun's `process.ppid` cache is stale across reparenting ([oven-sh/bun#30305](https://github.com/oven-sh/bun/issues/30305)) so `getParentPid()` runs `spawnSync('ps', ['-o', 'ppid=', '-p', PID])` per tick. Startup probe verifies `ps` is on PATH; if not (stripped containers, busybox), the watchdog skips installing AND emits a loud `[gbrain serve] watchdog disabled: ps unavailable ...` stderr line so operators see the degraded mode. The idle maintenance sweep skips ticks while a delegated sync runs and drains deferred embeds afterwards (`maybeDrainDeferredEmbeds`); it targets the source `resolveMcpStdioSourceScope` resolves (GBRAIN_SOURCE > `.gbrain-source` dotfile > local_path > `sources.default` > …) — the SAME ladder as stdio dispatch and the startup sweep, so dotfile/local_path-scoped serves reconcile their in-session MCP writes (pinned by `test/serve-idle-sweep-source.serial.test.ts`). Both stdin activity listeners (the default-on idle sweep and the opt-in `--stdio-idle-timeout`) attach only AFTER the MCP SDK transport's own stdin listener — the sweep on its first interval tick, the idle timeout through the activator `installStdioLifecycle` returns, which `runServe` invokes once `startMcpServer` resolves (and which re-arms the countdown so boot time does not eat into the idle window) — so neither can flip stdin into flowing mode and consume a fast client's initialize frame before the SDK sees it. Pinned by `test/serve-stdio-lifecycle.test.ts` (22 cases).
- `src/core/oauth-provider.ts` — `GBrainOAuthProvider` implementing the MCP SDK's `OAuthServerProvider` + `OAuthRegisteredClientsStore`. Backed by raw SQL (works on both PGLite and Postgres — OAuth is infrastructure, not a BrainEngine concern). Full OAuth 2.1: `authorize` + `exchangeAuthorizationCode` with PKCE, `client_credentials`, `refresh_token` with rotation, `revokeToken`, `registerClient` (DCR validates redirect_uri is `https://` or loopback per RFC 6749 §3.1.2.1). All tokens + client secrets SHA-256 hashed before storage. Owner-approved authorization codes have a 10-minute TTL. Grant transactions lock the active client row before consuming codes or refresh tokens and creating replacements; revocation uses the same lock. Provider-side S256 PKCE validation is mandatory (`skipLocalPkceValidation=true` prevents the SDK from discarding the verifier first). Existing active-client grants remain usable. `pgArray()` escapes commas/quotes/braces so a comma-bearing redirect_uri can't smuggle a second array element. Legacy `access_tokens` fallback in `verifyAccessToken` honors the original-schema `scopes TEXT[]` column via `normalizeTokenScopes` (NULL = grandfathered `read+write+admin`, so every pre-scopes token is byte-identical; an array is filtered to known scopes and honored as-is, `[]`/all-unknown preserved as deny — a dedicated column is structurally immune to the permissions-object-replacement wipe class), and threads BOTH stored grants off the token's `permissions` JSONB: `source_id` via `parseLegacyTokenScope` and `takes_holders` via `parseTakesHoldersAllowList` (both in `src/core/legacy-token-scope.ts`, shared with the legacy HTTP transport so the two transports cannot drift; `[]` takes-holders preserved as explicit deny-all, missing/non-array → undefined → the `/mcp` dispatch site's fail-closed `['world']`; OAuth-client tokens carry no takes-holders grant pending per-client storage — TODOS.md). `sweepExpiredTokens()` runs on startup in try/catch and returns the count via `RETURNING 1` + array length. RFC hardening: `client_id` folded atomically into the `DELETE WHERE` for both auth-code exchange and refresh rotation (wrong-client paths don't burn the row); refresh-scope-subset enforced against the original grant on the row (RFC 6749 §6, so revoking a scope shrinks existing refresh tokens); `client_id` bound on `revokeToken` (RFC 7009 §2.1); `/token` `redirect_uri` validated against the `/authorize` value (RFC 6749 §4.1.3, empty-string treated as missing not wildcard); `verifyAccessToken`/`getClient` catch only `isUndefinedColumnError` from `src/core/utils.ts` (only SQLSTATE 42703 falls through to legacy; lock timeouts/network blips throw); `dcrDisabled` constructor option lets `serve-http.ts` disable `/register` without monkey-patching the router. Module-private `coerceTimestamp()` normalizes postgres-driver-as-string BIGINT columns to JS numbers at 5 read sites (`getClient` for RFC 7591 §3.2.1 numeric timestamps, `exchangeRefreshToken` + `verifyAccessToken` for the SDK's `typeof === 'number'` check); throws on NaN/Infinity (fail loud at boundary), returns undefined for SQL NULL (callers treat NULL as expired). Not promoted to `utils.ts` — generic BIGINT precision-loss risk. `registerClient` honors `token_endpoint_auth_method: "none"` (RFC 7591 §3.2.1): public PKCE clients store `client_secret_hash = NULL` and the response omits `client_secret`; confidential clients (`client_secret_post` / `client_secret_basic`) keep their one-time-reveal shape; `getClient` normalizes NULL `client_secret_hash` to JS `undefined` so the SDK's clientAuth path accepts public clients. `verifyAccessToken` JOINs `oauth_clients.source_id` (write scope, scalar) + `oauth_clients.federated_read` (read scope, TEXT[]) + `oauth_clients.bound_slug_prefixes` (write fence, TEXT[] — consumed by `enforceClientSlugFence` in `operations.ts`) onto the returned `AuthInfo`; legacy brains degrade via `isUndefinedColumnError` fallback, dropping the newest projection first. `rescopeClient(clientId, {sourceId?, federatedRead?, boundSlugPrefixes?})` is the trusted-operator rescope (CLI `gbrain auth rescope-client`, admin `POST /admin/api/rescope-client`); `boundSlugPrefixes` is tri-state — undefined leaves the binding untouched, `null` clears it, a non-empty array replaces it (explicit empty array rejected as ambiguous deny-all) — so roster churn updates the write fence in place without rotating secrets. with `src/commands/serve-http.ts`: custom `/token` middleware that runs BEFORE the MCP SDK's `clientAuth`. The SDK does plaintext compare against the request's `client_secret`; gbrain stores SHA-256 hashes only, so every confidential-client `/token` request would fail. The middleware detects confidential auth via `Authorization: Basic` header OR `client_secret_post` form body (both shapes per RFC 6749 §2.3.1), verifies via `verifyClient(client_id, presented_secret)` (SHA-256 hash compare), and falls through to the SDK for public PKCE clients (which the SDK's clientAuth still accepts via NULL-`client_secret_hash` normalization). Pinned by `test/oauth-confidential-client.test.ts` (both `client_secret_basic` and `client_secret_post`).
@@ -415,7 +415,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `test/fixtures/whoknows-eval.jsonl` — 10-row synthetic placeholder demonstrating the eval-fixture schema (`{query, expected_top_3_slugs, notes?}` JSONL). End users replace with their own real queries; placeholder uses obviously-example slugs (`wiki/people/example-alice`). Drives `test/e2e/whoknows.test.ts` (seeds a matching synthetic brain, asserts the >=80% gate) and the `whoknows_health` doctor check.
- `src/core/skillopt/` + `src/commands/skillopt.ts` + `skills/skill-optimizer/` — self-evolving skill optimization grounded in the SkillOpt paper (arXiv 2605.23904). `gbrain skillopt <skill>` treats `SKILL.md` as trainable parameters of a frozen agent: validation-gated (median-of-3 + epsilon=0.05), budget-capped (preflight estimator), per-skill DB-locked (`tryAcquireDbLock('skillopt:<name>', 60min)`), atomic-versioned (history-intent-first 5-step commit), body-only mutations (frontmatter forbidden). Rollouts use `gateway.toolLoop` directly with no-op persistence callbacks (zero `subagent_messages` pollution) + a read-only tool allowlist derived from `BRAIN_TOOL_ALLOWLIST` minus `put_page`/`submit_job`/`file_upload`. Two reflect calls per step; rejected-edit buffer LRU-bounded to 100; bundled-skill gate; bootstrap workflow (sentinel + `--bootstrap-reviewed`); D_sel floor (>=5 with `--split` override); audit JSONL via `audit-writer.ts`. Added to `ALL_PHASES` after `patterns` (default OFF; opt-in via `gbrain config set cycle.skillopt.enabled true`); cycle phase wrapper at `src/core/skillopt/cycle-phase.ts` walks stale skills with per-skill ($0.50) + brain-wide ($2.00) caps. Added to `PROTECTED_JOB_NAMES`. Surface: dream-cycle phase wrapper; `--all` batch mode (`src/core/skillopt/batch.ts:runBatchAll`); `--target-models` fleet (`runFleet` parallel per-model receipts under `skillopt/fleet/<slug>/`); MCP op `run_skillopt` (admin scope + per-skill `skillopt.allowed_skills` allowlist, NOT localOnly, validates `skill_name` kebab-only + confines caller-supplied benchmark/held-out paths to skillsDir for remote callers); Minion `skillopt` handler + `--background` with `allowProtectedSubmit: true`; write-flavored optimization via `src/core/skillopt/write-capture.ts:buildWriteCaptureRegistry` (virtual `put_page`/`submit_job`/`file_upload` captured in-memory; `--write-capture` flag); held-out real-user test set via `src/core/skillopt/held-out.ts` (capture infra at `~/.gbrain/skillopt-captures/<skill>/<run>.jsonl`, `--held-out <path>` flag, `runHeldOutGate` candidate >= baseline). Hermetic via DI seams (`opts.chatFn` for optimizer + judge; `opts.toolLoopFn` for rollouts; no `mock.module`). `--bootstrap-from-skill` → `runBootstrapFromSkill` in `src/core/skillopt/bootstrap-benchmark.ts`: reads `SKILL.md` directly (no `routing-eval.jsonl`), makes ONE LLM call emitting a full starter benchmark (tasks + rule judges) as JSONL, parsed line-by-line with skip-bad-line salvage and a min-2-valid-checks-per-task drop; provider/transport errors PROPAGATE (not collapsed to `bootstrap_empty`). `--bootstrap-tasks N` (default 15, capped 50); `maxTokens` scales `min(8000, max(4000, N*220))`. The stderr REVIEW line prints the literal `gbrain skillopt <name> --bootstrap-reviewed --split 1:1:1` — load-bearing because the default `4:1:5` split makes a 15-task starter's `D_sel = floor(15/10) = 1`, below the `>=5` floor, so a 15-task benchmark needs `--split 1:1:1`. Both bootstrap generators share `assertBenchmarkAbsent` + `readSkillBodyOrThrow`; `--bootstrap-from-skill` is mutually exclusive with `--bootstrap-from-routing`/`--benchmark`/`--all`/`--target-models`/`--resume`. Generated rule judges are explicitly WEAK DRAFTS to be strengthened during the review gate. The held-out gate is wired: `--held-out <path>` is parsed and threaded through every caller (CLI main + `--background` `held_out_path` + batch/fleet `heldOutPath` + the `run_skillopt` `held_out_path` param), running at CHECKPOINT ACCEPTANCE so no-mutate/fleet paths can't promote a held-out-failing candidate. `assertBundledMutationHeldOut` in bundled-skill-gate.ts: bundled + `--allow-mutate-bundled` requires a NON-EMPTY held-out (`MIN_HELD_OUT_SIZE = D_SEL_MIN_SIZE` = 5, derived so they can't desync) or hard-refuses (exit 2), for ALL callers (they funnel through `runSkillOpt`); held-out must be task_id-DISJOINT from the benchmark (overlap rejected — can't catch overfitting). `receipt.baseline_sel_score` populated + a real final-test eval (`test_score` + `baseline_test_score`) scoring best + baseline on `split.test`; shared `scoreSkillOnTasks` primitive (validate-gate.ts) backs baseline/final-test/held-out scoring. `--no-mutate` writes proposed.md via `writeProposed` in version-store.ts. `maxRuntimeMin` ENFORCED (wall-clock deadline between steps → `skillopt_runtime_exceeded` → outcome aborted). Three eval-internal ablation opts on `SkillOptOpts` (NOT on CLI): `reflectMode` (`'both'`/`'failure-only'`), `disableValidationGate` (greedy-accept), `optimizerMode` (`'reflect'`/`'one-shot-rewrite'`), recorded in `RunReceipt` + audit `run_start` for replayability; `ROLLOUT_SUCCESS_THRESHOLD = 0.5` named constant for the partition; one-shot fence-strip is anchored (`^```...```$`) so an embedded code sample isn't truncated. Claude Haiku 4.5's dateless canonical id `claude-haiku-4-5` is in `src/core/anthropic-pricing.ts` (a `BudgetTracker`-capped run on Haiku would otherwise throw `no_pricing` on the FIRST `chat()` of every rollout); `runValidationGate` (validate-gate.ts) scans settled results for `isMustAbortError(error)` (from `worker-pool.ts`; `BUDGET_EXHAUSTED` is in `MUST_ABORT_ERROR_TAGS`) and re-throws so the caller aborts loudly instead of recording a hollow `selScore:0` — ordinary non-abort rollout errors still fail-open to `score:0` (judge-hiccup posture preserved), but a 100%-failed gate (every task errored — e.g. a logged-out `claude-cli` child — or every rollout carrying a `judge_error`) throws `skillopt_all_rollouts_failed` / `skillopt_all_judge_errors` (constants exported from validate-gate.ts) so a dead provider ends the run `errored` with the first provider message as `abort_detail` instead of a plausible `no_improvement` at 0.000; the orchestrator's zero-candidate step (reflect produced/parsed no edits) logs audit reason `no_edits_proposed[: <first reflect error>]` + one stderr line, distinct from the apply-rejected `no_edits_applied`, and does not touch the rejected buffer. `GBRAIN_CLAUDE_CLI_HERMETIC_CONFIG=1` (empty config dir) logs the child out on every platform, macOS included — docs/comment make no keychain-survives claim (pinned by `test/skillopt/deadline-and-hermetic.test.ts`). Pinned by 152 tests across 18 files (foundation + adversarial + v2 surface + E2E PGLite serial), `test/skillopt/bootstrap-from-skill.test.ts` (20 cases), `test/skillopt/rollout.test.ts`, `test/skillopt/validate-gate-abort.test.ts` (7 cases), held-out ENFORCE + one-shot-rewrite unit cases, and e2e (held-out block/allow, bundled no-mutate, runtime deadline, receipt honesty, held-out disjointness, no-DB-pollution). Drives the Track B SkillOpt benchmark suite in the sibling `gbrain-evals` repo.
- `src/core/brainstorm/{domain-bank,orchestrator,judges}.ts` + `src/commands/{brainstorm,lsd,eval-brainstorm}.ts` + `src/core/last-retrieved.ts` — bisociation-grounded idea generation pair: `gbrain brainstorm <question>` (defensible, cite-heavy, 4 close × 6 far, judge threshold 4.0/5, save by default) and `gbrain lsd <question>` (Lateral Synaptic Drift — inverted judge rejecting ideas with resistance >4.5 "too obvious", stale-page bias via `pages.last_retrieved_at`, 2 close × 12 far, axiomatic inversions required, ephemeral by default). The "domain bank" is prefix-stratified sampling from the user's own brain (`SELECT DISTINCT substring(slug from '^[^/]+/[^/]+')` cached 1h-TTL in `config` per source) tiebroken by `JOIN page_links` connection_count, with corpus-sampling fallback when fewer prefixes than M exist. Distance normalized to [0,1] via `1 - clamp(cosine_distance, 0, 2) / 2`. `judges.ts` exports `runJudge(config, ideas)` + two configs (`BRAINSTORM_JUDGE_CONFIG` weighted originality/resistance/thesis_density/concrete_grounding/cognitive_load 0.25/0.20/0.20/0.20/0.15 vs `LSD_JUDGE_CONFIG` cognitive_load 0.50 + inversion rule). Calibration cold-start fallback: when `calibration_profiles.active_bias_tags` is empty, judge runs without anti-bias context AND stderr-warns. Op-layer write-back in `src/core/operations.ts` `search`/`query`/`get_page` handlers fires `bumpLastRetrievedAt(engine, pageIds)` (fire-and-forget, 5-min throttled via SQL clause, default-on with `search.track_retrieval` config escape hatch); internal callers (sync, migrations, dream cycle) bypass the op layer so the LSD stale signal stays clean. The fire-and-forget IIFE is tracked in a module-scoped `Set<Promise<unknown>>`; `awaitPendingLastRetrievedWrites(timeoutMs?: number): Promise<{outcome, pending}>` resolves once all tracked promises settle, bounded by a 5s `Promise.race` timeout that stderr-warns the pending count. `src/cli.ts` awaits the drain unconditionally for every op in the op-dispatch finally block BEFORE `engine.disconnect()`, then a fallback `process.exit(0)` fires ONLY when `outcome === 'timeout'` AND `shouldForceExitAfterMain(argv)` (excludes `serve` so daemons stay alive) — so the IIFE cannot race disconnect and leave PGLite's WASM keeping Bun's event loop alive. `pages.last_retrieved_at TIMESTAMPTZ NULL` has a full (NOT partial) B-tree index covering both NULL and range branches; full forward-reference bootstrap probe on both engines. Frontmatter `mode: lsd` makes the dream-cycle synthesize phase skip LSD output via `isLsdOutput()` in `src/core/cycle/transcript-discovery.ts` short-circuiting `isDreamOutput()`. `gbrain eval brainstorm <fixture.jsonl>` is a three-axis conjunctive gate (distance + usefulness + grounding — distance alone is gameable). `gbrain doctor` has a `brainstorm_health` check (migration applied, `search.track_retrieval` setting, calibration cold-start status). `judges.ts` computes the judge token budget via `computeJudgeMaxTokens(ideaCount, modelId)` (named constants `TOKEN_BUDGET_PER_IDEA`, `TOKEN_BUDGET_ENVELOPE`, `LEGACY_MIN_MAX_TOKENS`, `MAX_OUTPUT_TOKENS_CEIL`; `ANTHROPIC_OUTPUT_CAPS` map: Opus 4.7 32K, Sonnet 4.6 / Haiku 4.5 64K, legacy Claude 3.5 8K) so a large multi-call judge doesn't truncate mid-JSON; with no `modelOverride` the cap routes through the gateway's actual configured chat model via `getChatModel()`. `--save` for both commands persists through the canonical ingestion path: `persistSavedIdea(engine, {slug, content, provenanceVia})` calls `importFromContent({noEmbed:true, sourcePath})` (chunked + tagged + content_hash so search finds it, no embedding cost at save) THEN renders the saved row to disk via the shared `writePageThrough` helper (file rendered FROM the row so the two sinks can't diverge and `gbrain sync` doesn't churn it). `formatSaveOutcome(outcome, ctx)` returns an honest per-branch message (both-sinks, DB-only when no `sync.repo_path`/repo-not-a-dir, DB-saved-but-file-errored, total-failure → loud `save FAILED … NOT persisted` on stderr + nonzero exit) — `--save` never prints "Saved" when the DB write failed. `buildIdeaSlug(question, label, nonce?)` adds a random nonce suffix (injectable for tests) so two same-day runs sharing the first 60 slug chars don't clobber. `--json` callers stay DB-only. `buildBrainstormFrontmatterObject(result)` in orchestrator.ts returns the object form for `serializeMarkdown`. Pinned by `test/last-retrieved.test.ts`, `test/e2e/pglite-cli-exit.serial.test.ts` (IRON-RULE: real `bun src/cli.ts` subprocess against a hermetic PGLite tempdir asserts search/get/query exit 0 in <15s + daemon-survival), `test/fix-wave-structural.test.ts` (asserts the drain `await` is textually BEFORE `engine.disconnect`), `test/brainstorm/{distance,lsd-mode-skip,eval-brainstorm,judges-maxtokens,save}.test.ts`. Open Collider source: `github.com/CL-ML/open-collider`.
-- `src/core/write-through.ts` — shared atomic disk write-through for the canonical ingestion path. `resolvePageWriteTarget(engine, slug, sourceId)` is the exported single source of truth for the ONE file a (source, slug) pair lives in on disk: a source with its own `local_path` writes at that tree's ROOT (never nested under `.sources/`); a source without one nests under the host repo (`sync.repo_path`, default at root, non-default under `.sources/<id>/`) unless that path is another source's own working tree (leak guard → `source_repo_belongs_to_other_source`); the page's recorded `source_path` (or a contained `file://` `source_uri`) is preferred over a slug-derived name so writes land in the file of record instead of minting a twin; and `isWriteTargetContained` rejects hostile rows escaping the tree (`path_escapes_source_root`). The ok-result also carries `sourcePathToBind` — the target expressed in the file scanner's `source_path` convention (GIT-ROOT-relative when the scan root sits inside a git repo, so a subdirectory-scoped `local_path` binds the same form delete-reconcile keys on; scan-root-relative otherwise). The resolver is shared by `writePageThrough`, the facts fence writer (`src/core/facts/fence-write.ts`), and fence forget (`src/core/facts/forget.ts`) — the fence appends to the page's file, so all writers MUST compute the identical path or the fence lands in a file sync never reads back and the next extract_facts reconcile deletes the fence-owned DB rows. `writePageThrough(engine, slug, {sourceId?, frontmatterOverrides?, logger?})` resolves the target through it, re-reads the just-written DB row (`getPage`), renders it via `serializePageToMarkdown`, and writes the `.md` so the brain has a committable artifact that round-trips through `gbrain sync`. Rendering FROM the row means file and row cannot diverge. ATOMIC: writes to a unique temp sibling (`<file>.tmp.<pid>.<rand>`) + `renameSync`, cleaning up temp on any failure, so a crash or concurrent `gbrain sync`/autopilot walking the live git tree never reads a half-written `.md` (matches the `.tmp + rename` convention in import-checkpoint.ts / op-checkpoint.ts). After a successful rename, a row whose `source_path` is still NULL is immediately bound to `sourcePathToBind` (pages born via put/capture/reverse-write otherwise stay `source_path=NULL` forever because mtime-watermark incremental sync never rescans an untouched file); NULL-guarded so a scanner-recorded path is never rewritten, best-effort so a failed bind never fails the write. Never throws — returns `WriteThroughResult { written, path?, skipped?: 'disabled_by_config' | 'no_repo_configured' | 'repo_not_found' | 'source_repo_belongs_to_other_source' | 'page_not_found_after_write' | 'path_escapes_source_root' | 'case_insensitive_collision', warning?, error? }` so the caller decides messaging + exit codes. `withNoRepoWriteThroughWarning(result, sourceId)` decorates an unwritten `no_repo_configured` result with `warning` (the write landed only in the database; bind the token/server to a git-backed source or configure `local_path`/`sync.repo_path`); `put_page` applies it for untrusted callers only (`ctx.remote !== false`), so local CLI responses and the `disabled_by_config` operator opt-out stay silent. `isWriteThroughDisabled` (shared with the fence lane, ~30s per-engine cache) honors the `sync.write_through` opt-out. Trust gating (subagent sandbox, dry-run) stays at the CALLER. On a durability-hardened repo (`isDurabilityHardened` — the gbrain post-commit hook is installed, i.e. the user ran `gbrain sources harden`), a successful write is best-effort COMMITTED via `commitWriteThroughFile` (path-limited `git commit -- <file>`, never sweeps unrelated edits; the hook then background-pushes) so write-through content reaches git instead of accumulating uncommitted forever; result carries `committed?: boolean`. Unhardened repos keep write-only behavior. `deletePageThrough(engine, slug, {sourceId?, target?, logger?})` is the delete-side sink (sole caller: the `delete_page` op): resolves the same target, unlinks the `.md`, and on a hardened repo best-effort commits the removal path-limited through the same helper with subject `gbrain: delete write-through <slug>`, reporting `committed?: boolean` on `DeleteThroughResult` (absent when unhardened or when the commit did not land — the unlink still stands; a never-committed page leaves nothing to commit, so no empty commit). Pinned by `test/delete-write-through-commit.serial.test.ts`. Consumers: `put_page` op and `gbrain brainstorm/lsd --save` via `persistSavedIdea`. Pinned by `test/write-through.test.ts` + `test/write-through-commit.serial.test.ts`. The `put_page` op is that deciding caller for direct writes: a skip outside the deliberate DB-only set (`no_repo_configured`/`disabled_by_config`/`subagent_sandbox`/`dry_run`) throws `storage_error`, deleting a just-created row first so "created" is never answered for a page with no file backing.
+- `src/core/write-through.ts` — shared atomic disk write-through for the canonical ingestion path. `resolvePageWriteTarget(engine, slug, sourceId)` is the exported single source of truth for the ONE file a (source, slug) pair lives in on disk: a source with its own `local_path` writes at that tree's ROOT (never nested under `.sources/`); a source without one nests under the host repo (`sync.repo_path`, default at root, non-default under `.sources/<id>/`) unless that path is another source's own working tree (leak guard → `source_repo_belongs_to_other_source`); the page's recorded `source_path` (or a contained `file://` `source_uri`) is preferred over a slug-derived name so writes land in the file of record instead of minting a twin; and `isWriteTargetContained` rejects hostile rows escaping the tree (`path_escapes_source_root`). The ok-result also carries `sourcePathToBind` — the target expressed in the file scanner's `source_path` convention (GIT-ROOT-relative when the scan root sits inside a git repo, so a subdirectory-scoped `local_path` binds the same form delete-reconcile keys on; scan-root-relative otherwise). The resolver is shared by `writePageThrough`, the facts fence writer (`src/core/facts/fence-write.ts`), and fence forget (`src/core/facts/forget.ts`) — the fence appends to the page's file, so all writers MUST compute the identical path or the fence lands in a file sync never reads back and the next extract_facts reconcile deletes the fence-owned DB rows. `writePageThrough(engine, slug, {sourceId?, frontmatterOverrides?, logger?})` resolves the target through it, re-reads the just-written DB row (`getPage`), renders it via `serializePageToMarkdown`, and writes the `.md` so the brain has a committable artifact that round-trips through `gbrain sync`. Rendering from the row keeps the serialized content consistent at write time. The fsync-backed `atomicWriteFileSync` stages and renames the file after required source-path bookkeeping; lock/lease checks run before publication. `put_page` holds the root lock before importing and invokes write-through inside its database transaction, so ordinary filesystem rejection rolls back existing content, tags, chunks, and versions. A crash or database COMMIT failure after rename can still leave canonical Markdown ahead of the index; this is not distributed ACID or a durable queue. Never throws — returns `WriteThroughResult { written, path?, skipped?: 'disabled_by_config' | 'no_repo_configured' | 'repo_not_found' | 'source_repo_belongs_to_other_source' | 'page_not_found_after_write' | 'path_escapes_source_root' | 'case_insensitive_collision', warning?, error? }` so the caller decides messaging + exit codes. `withNoRepoWriteThroughWarning(result, sourceId)` decorates an unwritten `no_repo_configured` result with `warning` (the write landed only in the database; bind the token/server to a git-backed source or configure `local_path`/`sync.repo_path`); `put_page` applies it for untrusted callers only (`ctx.remote !== false`), so local CLI responses and the `disabled_by_config` operator opt-out stay silent. `isWriteThroughDisabled` (shared with the fence lane, ~30s per-engine cache) honors the `sync.write_through` opt-out. Trust gating (subagent sandbox, dry-run) stays at the CALLER. On a durability-hardened repo (`isDurabilityHardened` — the gbrain post-commit hook is installed, i.e. the user ran `gbrain sources harden`), a successful write is best-effort COMMITTED via `commitWriteThroughFile` (path-limited `git commit -- <file>`, never sweeps unrelated edits; the hook then background-pushes) so write-through content reaches git instead of accumulating uncommitted forever; result carries `committed?: boolean`. Unhardened repos keep write-only behavior. `deletePageThrough(engine, slug, {sourceId?, target?, logger?})` is the delete-side sink (sole caller: the `delete_page` op): resolves the same target, unlinks the `.md`, and on a hardened repo best-effort commits the removal path-limited through the same helper with subject `gbrain: delete write-through <slug>`, reporting `committed?: boolean` on `DeleteThroughResult` (absent when unhardened or when the commit did not land — the unlink still stands; a never-committed page leaves nothing to commit, so no empty commit). Pinned by `test/delete-write-through-commit.serial.test.ts`. Consumers: `put_page` op and `gbrain brainstorm/lsd --save` via `persistSavedIdea`. Pinned by `test/write-through.test.ts` + `test/write-through-commit.serial.test.ts`. The `put_page` op is that deciding caller for direct writes: a skip outside the deliberate DB-only set (`no_repo_configured`/`disabled_by_config`/`subagent_sandbox`/`dry_run`) throws `storage_error` inside the import transaction, rolling back the page revision, tags, chunks and version snapshot instead of deleting a just-created row afterward.
- `src/core/model-id.ts` — `splitProviderModelId(input: string | null | undefined): {provider: string | null, model: string}` shared parser for the pricing side. Splits on `:` first, then `/`. Defensive contract: null/undefined/empty/whitespace returns `{provider: null, model: ''}`. Five sites consume it (`src/core/anthropic-pricing.ts:estimateMaxCostUsd`, `src/core/budget/budget-tracker.ts:lookupPricing`, `src/core/eval-contradictions/cost-tracker.ts:pricingFor`, `src/core/minions/batch-projection.ts` at two call sites, `src/core/model-config.ts:isAnthropicProvider`) so the pricing + classification surface has no parallel re-implementations of `provider:model` splitting — slash-form ids (`anthropic/claude-sonnet-4-6`) classify correctly instead of falling through to "unknown model". Distinct from the gateway-side `parseModelId` in `src/core/ai/model-resolver.ts`, which throws on bare names because routing needs an explicit provider; this one returns `{provider: null, model: 'bare'}` because pricing lookups happen against bare model ids. Pinned by `test/model-id.test.ts`.
- `src/commands/recall.ts` — the `gbrain recall` CLI (facts-first read; local engine or thin-client). Entity→text fallback: a bare positional is entity-first, but when the entity arm matches ZERO facts (and no `--grep`/`--supersessions`/`--session-id` narrows the read) the query retries as the SQL-level fact-text grep with a one-line stderr note — so keyless/casual usage (`gbrain recall coffee`) finds the fact either way. One gating predicate + one note formatter (`entityTextFallbackApplies`/`noteEntityTextFallback`) shared by the local path and the thin-client mirror so the two can't drift; explicit `--grep` callers keep exact semantics (their filter already ran, no fallback surprise). `--since` composes with the positional entity and with `--session-id` through `engine.listFactsSince({entitySlug, sessionId})` (one query, cutoff before LIMIT, event time unless `--since-last-run`), mirroring the `recall` op's composition in `src/core/ops/facts.ts`; pinned by `test/facts-recall-since-composition.test.ts`.
- `src/commands/transcripts.ts` — the transcripts command family, all local-only (`ctx.remote=false` by construction). `recent`: raw `.txt` corpus reads via `listRecentTranscripts` (same library as the gated `get_recent_transcripts` op). `ingest <path-or-glob>`: the cross-harness session importer — resolves ONE source id (6-tier chain), threads activePack once, streams progress (phase `transcripts.ingest`), and calls `runTranscriptsIngest`; embedding is OFF by default (embed backfill is the catch-up lane; the embed flag opts in); the max-bytes flag (validated size string, e.g. `4gb`) overrides the per-format file/store byte caps for oversized stores while omission preserves each adapter's native default; the since-last watermark is an op-checkpoint (op `transcripts-ingest`, fingerprint = source + pathspec + format + adapter version + any explicit byte cap via `ingestCheckpointFingerprintInput` — a checkpoint written under one cap is never silently reused under another, so a capped run's skipped tail can't read as scanned; the pathspec binds the user-stated paths resolved + sorted, and the no-arg/all lane substitutes hostname + sorted harness roots so DB-backed checkpoints shared across a brain's machines never let one machine inherit another's watermark and skip sessions it never scanned) advanced ONLY after a clean, untruncated, non-dry scan; no-arg = confined discovery table, the all flag imports the discovered set. `status`: found-vs-imported gap table (disk scan vs ONE conversation-pages frontmatter query — `executeRaw`, both engines — in `src/core/transcripts/discover.ts`) — the correctness surface that catches late-arriving sessions no watermark can. The facts flag hands EVERY touched slug (including hash-skipped) to `src/core/transcripts/ingest-facts.ts`. Registered in CLI_ONLY + CLI_ONLY_SELF_HELP + SELF_HELP_WITHOUT_ENGINE (engine-free help). `expandTilde(raw)` (bare `~`, leading `~/` or `~\\` → home dir; `~user` forms and a mid-string `~` stay literal) is the one tilde expansion `expandPaths` applies to every path spec.
@@ -437,7 +437,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/sort-newest-first.ts` — single source of truth for the descending-lex sort that `gbrain import` and `gbrain sync` both apply. Mutates in place (Array.prototype.sort semantics), returns the same array reference for fluent chaining. Empty/single-element inputs short-circuit. Future ordering changes flip one line here instead of touching two CLI commands. Pinned by `test/sort-newest-first.test.ts` (descending order, mixed prefixes, empty, single-element, in-place-mutation contract).
- `src/core/cycle.ts` — brain maintenance cycle primitive (23 phases; `ALL_PHASES` is the ordered source of truth). `runCycle(engine: BrainEngine | null, opts: CycleOpts): Promise<CycleReport>` composes phases in semantic order along the core spine lint → backlinks → sync → synthesize → extract → patterns → recompute_emotional_weight → embed → orphans, with the extraction/graph/consolidation phases (extract_facts, extract_atoms, resolve_symbol_edges, …) slotted between per the ordering comments on `ALL_PHASES`. `synthesize` runs after sync (cross-references see a fresh brain) and before extract (auto-link materializes its writes); `patterns` runs after extract so it reads a fresh graph (subagent put_page sets `ctx.remote=true` and skips auto-link/timeline by default, so extract is the canonical materialization); `recompute_emotional_weight` sees the union of `syncPagesAffected` + `synthesizeWrittenSlugs` incrementally, or all pages when neither anchor is set (full backfill via `gbrain dream --phase recompute_emotional_weight`). `CycleReport.schema_version: "1"` is stable; `totals` is additive (`pages_emotional_weight_recomputed`, `transcripts_processed`, `synth_pages_written`, `patterns_written`). Three callers: `gbrain dream` CLI, `gbrain autopilot` daemon inline path, the Minions `autopilot-cycle` handler. Coordination via `gbrain_cycle_locks` DB table + `~/.gbrain/cycle.lock` file lock with PID-liveness for PGLite; the two handles compose into ONE lock whose `refresh()` treats the fenced DB row as the authoritative multi-writer identity and the file half as best-effort freshness — the file lock is refreshed ONLY while the fenced DB refresh reports ownership, so a losing holder can never clobber the successor's file lock on the very tick it detects the steal. A dedicated serialized refresher — `startCycleLockRefresher(lock, controller, lockId)` (exported; unref'd `setInterval` at `max(15s, TTL/6)`, env-only override `GBRAIN_CYCLE_LOCK_REFRESH_MS`, in-flight guard so a slow refresh never overlaps the next tick) — heartbeats the lock through long phases (synthesis/patterns/consolidation waits routinely outlive the TTL with no other heartbeat). A fenced miss aborts the controller with `LockStolenError`; that steal signal combines with the worker's external signal via the exported `anyAbortSignal(signals)` (duck-type-tolerant — stubs without `addEventListener` are observed by poll; returns `{signal, dispose}` and dispose detaches the caller-signal listener + clears the poll timer so daemons don't leak), and the run stops at the next phase boundary with a structured partial report carrying `reason: 'lock_stolen'` (for the 5 long phases — synthesize / extract_atoms / patterns / synthesize_concepts / consolidate — the steal races the phase promise and stops the WAIT immediately; their in-flight work runs to its own bounded timeout because their opts can't carry a signal yet). Transient refresh errors log and retry next tick (the TTL stays the backstop). `yieldBetweenPhases` runs between phases; `yieldDuringPhase` is in-phase keepalive. Engine nullable; lock-skip on read-only phase selections. `CycleOpts.signal?: AbortSignal` propagates the worker's abort signal with `checkAborted()` between every phase. `CycleOpts.deadlineAtMs` (the enclosing minion job's ABSOLUTE wall-clock deadline, threaded from `MinionJobContext.deadlineAtMs` by the autopilot-cycle handler; null for direct `gbrain dream` callers) flows into patterns, propose_takes, AND synthesize so time-spending phases derive their deadlines from the REAL remaining job budget instead of duplicated literals that collide with the job's own kill timer. Pinned by `test/cycle-lock-steal.serial.test.ts` (mid-run steal → partial report, no further phases, successor row intact) + `test/cycle-any-abort-signal.test.ts` + `test/db-lock-fencing.test.ts`. `runPhaseSync` returns `pagesAffected` via `SyncPhaseResult` (threaded to `runPhaseExtract` as the 4th arg) and takes `willRunExtractPhase: boolean` setting `noExtract: phases.includes('extract')` so `gbrain dream --phase sync` doesn't silently lose extraction. The extract phase calls `runExtractCore` and `extractStaleFromDB` with `quiet: true` (and `jsonMode: false`), so the helpers' human summaries never land on stdout ahead of the `dream --json` CycleReport while batch-loss diagnostics stay human-readable on stderr (`quiet` is its own knob on `ExtractOpts` — using `jsonMode: true` as a stand-in flipped the stderr channel to JSON events in a plain `gbrain dream`); `totals.pages_extracted` counts pages (`pages_processed` from the targeted pass + `stale_pages_drained`), not links created. `resolveSourceForDir(engine, brainDir)` threads `sourceId` to `performSync()` so sync reads the per-source `sources.last_commit` anchor (not the drift-prone global `config.sync.last_commit`). `CycleOpts.brainDir` is `string | null`; when null (checkout-less postgres/Supabase brain) the 6 filesystem phases (lint/backlinks/sync/synthesize/extract/patterns) skip with `details.reason: 'no_brain_dir'` and the DB-only phases run; `resolveSourceForDir` is null-tolerant. `cycleSourceId = opts.sourceId ?? resolveSourceForDir(engine, brainDir)` is the canonical per-source scope for `extract_facts`/`extract_atoms`/calibration — and for `synthesize` (threaded as `SynthesizePhaseOpts.sourceId` so synthesized pages land in the cycle's resolved source, not `'default'`) — so `gbrain dream --source repo-a` reconciles repo-a's facts even with no checkout (instead of scoping to `'default'` while stamping repo-a fresh). `deriveStatus` counts `edges_resolved`/`edges_ambiguous` as work so an edges-only cycle reports `ok` not `clean`, and scores ONLY attempted phases — the implicit source-cycle exclusion skip-records are bookkeeping and never dilute failure aggregation; the `jobs.ts` `autopilot-cycle` + phase-wrapper handlers pass `null` (not `'.'`) when no repo is configured. The cycle is SPLIT for autopilot fan-out along the `PHASE_SCOPE` taxonomy in `src/core/cycle/phase-scope.ts` (see its entry): cycle.ts derives `SOURCE_PHASES` / `MIXED_PHASES` / `GLOBAL_PHASES` / `MAINTENANCE_PHASES` (mixed ∪ global, original cycle order) plus `SOURCE_FRESHNESS_PHASES` (deterministic, non-LLM: lint/backlinks/sync/extract/extract_facts/recompute_emotional_weight — defined in phase-scope.ts) and `SOURCE_BACKGROUND_PHASES` (LLM-backed/unbounded source work = SOURCE minus FRESHNESS). `resolveCyclePhases(requested, sourceId)` at the shared runCycle boundary: default/no-source → `requested ?? ALL_PHASES` (the canonical `default` cycle remains full); a named non-default source with NO explicit phases → `SOURCE_FRESHNESS_PHASES` only (the freshness keeper's implicit `dream --source X` path must stamp freshness without first draining LLM-backed maintenance); explicit phase lists are honored VERBATIM — `dream --source X --phase synthesize` (and `--input <file>`, which implies synthesize) is deliberate operator intent, and `--phase orphans --source X` still narrows orphans via `forceGlobalOrphans`. The N-way duplication guard lives at the QUEUE boundary instead: the `autopilot-cycle` handler intersects queued per-source payloads with `SOURCE_FRESHNESS_PHASES` (queued payloads may carry mixed+background phases; an all-rejected or empty list is an explicit no-op skip with reason `all_phases_rejected_by_normalization`, never an implicit run, and rejected phases surface on the job result as `phases_rejected_by_normalization`). On the implicit path, excluded phases surface as `skipped` with `details.reason: 'excluded_from_implicit_source_cycle'` + `phase_scope`. Per-source `autopilot-cycle` jobs enqueue `phases: SOURCE_FRESHNESS_PHASES` and stamp `last_source_cycle_at`; the single `autopilot-global-maintenance` job runs `MAINTENANCE_PHASES` (no `sourceId`) and stamps the brain-level `autopilot.last_global_at` config key (`LAST_GLOBAL_AT_KEY`). SOURCE_BACKGROUND phases have NO automatic lane on multi-source brains (the legacy full-cycle job fires only when the brain has no sources rows) — run them explicitly (`gbrain dream --source X --phase extract_atoms`) until the background lane lands (see TODOS). The freshness stamp gate is `opts.sourceId && phases.length > 0 && engine && !dryRun && !aborted && status ∈ {ok, clean, partial}`; `last_full_cycle_at` is still written alongside `last_source_cycle_at` on a per-source success for doctor/legacy readers (not a gate for the brain-wide phases). Pinned by `test/dream-postgres.serial.test.ts` + `test/jobs-autopilot-cycle-braindir.serial.test.ts` + `test/autopilot-global-maintenance.test.ts` + `test/cycle-enabled-phase-completeness.test.ts`. `runPhaseLint` + `runPhaseBacklinks` carry the `export` keyword so behavioral tests can drive them directly (internal helpers exposed for test-only consumption; downstream code should NOT depend on them). Pinned by `test/cycle-legacy-phases.test.ts` (11 cases across both phases: clean run → status='ok', partial fix → status='warn' with `dryRun` in details, dry-run path doesn't write, throw-from-lib → status='fail' with the wrapper's try/catch envelope populated). with `src/core/cycle/extract-atoms.ts` + `src/core/cycle/synthesize-concepts.ts` + `src/commands/extract.ts` + `src/commands/doctor.ts` + `src/core/op-checkpoint.ts`: six daily-driver ops behaviors. (1) Batch idempotency: `atomsExistingForHashes(engine, sourceId, hashes[])` (exported from `src/core/cycle/extract-atoms.ts`) answers in one batched SQL roundtrip (never a per-hash loop) returning already-extracted `content_hash16` values; fail-open (SQL error → empty set, extraction proceeds); powered by migration v104 `pages_atom_source_hash_idx` (partial expression index on `frontmatter->>'source_hash'` for atom rows where `deleted_at IS NULL`; Postgres `CREATE INDEX CONCURRENTLY` with invalid-remnant pre-drop, PGLite plain). (2) Cycle lock TTL + heartbeat: `LOCK_TTL_MINUTES = 5`; `buildYieldDuringPhase(lock, outer)` (exported, with `LockHandle`) calls `lock.refresh()` + any external hook on every fire, throttled to 30s via `maybeYield`, firing both in the main loop AND immediately after every `await chat(...)`; `synthesize_concepts` uses the same throttled hook. A crashed cycle releases its lock within one short TTL, while the dedicated `startCycleLockRefresher` interval (see the coordination sentence above) keeps a healthy long-running cycle alive even across a single multi-minute `await chat(...)` — the timer fires during awaits, so no single slow call can silently expire the lock. (3) Progress wiring: `progress?: ProgressReporter` opt on `ExtractAtomsOpts` and `SynthesizeConceptsOpts`; cycle.ts passes its phase-level reporter down (NOT a child reporter, which would collide on `cycle.extract_atoms.extract_atoms.work`); phases only call `tick()`/`heartbeat()`, cycle.ts owns `start()`/`finish()`. (4) `by-mention` resume: `mentionsFingerprint({source, type, since, gazetteerHash})` in `src/core/op-checkpoint.ts` — the gazetteer hash (`hashGazetteer` in `src/core/by-mention.ts` — every entry's source_id/slug/title/tokens, not just the first-token bucket keys, so a new "Acme Labs" beside an existing "Acme Corp" moves it) is load-bearing (adding entity pages mid-pause shifts the hash → new fingerprint → fresh scan against the new gazetteer, never silent skip); `findMentionedEntities` keys its self-link guard and first-mention dedup on `(source_id, slug)`, so under `link_resolution.cross_source` a foreign namesake of the scanning page is a real target and same-slug pages in two sources both link; the gazetteer itself is entity-page titles PLUS live-verified `page_aliases` entries joined to entity-typed pages (ambiguous aliases and alias-vs-title collisions within a source are skipped), so body mentions of a documented alias link too; `gbrain extract links --by-mention` resumes via `op_checkpoints` with `flushAndCheckpoint` ordering (links flush to DB FIRST, page keys commit to checkpoint SECOND, persist THIRD, so a crash mid-batch leaves the page un-checkpointed and resume re-scans it); persist every 1000 items OR 30s; clean exit clears the checkpoint; `--dry-run` skips both load and write. (5) `sync_consolidation` doctor check (multi-source brains see a paste-ready `gbrain sync --all --parallel 4 --workers 4 --skip-failed`; single-source "not applicable"; SQL errors return `warn` via the check's own try/catch). (6) Test-isolation: `test/cycle-last-full-cycle-at.test.ts` + `test/schema-cli.test.ts` use per-test `GBRAIN_HOME=tempdir`. Pinned by `test/cycle/extract-atoms-batch.test.ts`, `test/cycle/cycle-lock-ttl.test.ts` (pins `LOCK_TTL_MINUTES === 5`), `test/op-checkpoint-mentions-fingerprint.test.ts`, `test/cycle/extract-atoms-progress.test.ts`, `test/cycle/synthesize-concepts-progress.test.ts`, `test/cycle/yield-during-phase-refresh.test.ts`, `test/cycle/yield-during-phase-throttle.test.ts`, `test/extract-by-mention-resume.test.ts`, `test/doctor-sync-consolidation.test.ts`. Companion `sync --all` recipe block in `skills/cron-scheduler/SKILL.md`. `synthesize_concepts` writes concept pages through `importFromContent` (the same parse→chunk→embed pipeline put_page uses, with put_page's `isAvailable('embedding')` → `noEmbed` gate) so `concepts/` pages carry `content_chunks` + embeddings and are reachable by retrieval (where `source-boost.ts` weights them 1.3×). `purge` phase (soft-delete TTLs) also GCs stale `op_checkpoints` rows older than 7 days. Non-fatal on pre-v67 brains (DROP-target-table check before DELETE). The cycle threads its abort signal into the embed phase (`runPhaseEmbed(engine, dryRun, signal)`) so a timed-out cycle's long embed phase honors cancellation and releases `gbrain_cycle_locks` right away instead of after a full backlog run.
- `src/core/cycle/phase-scope.ts` — the phase-scope taxonomy: `PHASE_SCOPE: Record<CyclePhase, 'source'|'mixed'|'global'>` maps each of the 23 phases (source: safe to parallelize per source; global: must serialize across the brain; mixed: brain-wide read + page write, so it stays in the default/global-maintenance lane until decomposed), plus `SOURCE_FRESHNESS_PHASES` — the deterministic, non-LLM subset (lint, backlinks, sync, extract, extract_facts, recompute_emotional_weight) that alone defines source freshness, so LLM-backed enrichment can never hold a freshness stamp hostage. cycle.ts re-exports both and derives the scheduling lists from them (see the cycle.ts entry). Consumed by `runCycle`'s `resolveCyclePhases` boundary, the autopilot fanout's per-source enqueue (`src/commands/autopilot-fanout.ts`), the jobs global-maintenance handler, and doctor's routing-federation phase-scope surface (`src/commands/doctor/checks/routing-federation.ts`). Pinned by `test/autopilot-global-maintenance.test.ts` (SOURCE ∪ MIXED ∪ GLOBAL == ALL_PHASES with no overlap; FRESHNESS ∪ BACKGROUND == SOURCE; resolveCyclePhases boundary semantics).
-- `src/core/cycle/synthesize.ts` — Synthesize phase: conversation-transcript-to-brain pipeline, a two-stage cascade where cheap scored triage gates frontier synthesis. Reads `dream.synthesize.session_corpus_dir`, runs `runTriagePass` (exported; bounded pool `dream.triage.concurrency` default 4, wall-clock cache-MISS budget `dream.triage.max_ms` default 5 min — cache hits are free and deferred files report `deferred: true`, never cached, so the next pass continues) whose judge `judgeSignificance` emits `{score 0-1 ordinal salience, content_type, segments ≤8 verbatim quotes, entities ≤12, reasons}` (non-overlapping bands LOW 0-0.29 / MEDIUM 0.30-0.69 / HIGH 0.70-1.0; head 50%/middle 20%/tail 30% sample within `dream.triage.max_chars` default 24K via `safeSplitIndex`; out-of-[0,1] scores are `unparseable`, never clamped) cached in `dream_verdicts` with the judging `model` + `TRIAGE_VERSION` — cache validity requires BOTH to match (switching `models.dream.triage` re-judges; `max_chars`/`max_tokens` deliberately excluded from validity — `dream retriage --force` re-judges under new sampling knobs). Degenerate verdicts (`truncated`/`refusal`/`unparseable`) are never cached. THE gate is `passesTriageGate` (triage-rescue.ts): `score >= dream.triage.threshold` (default 0.5) OR the verified-segment rescue, applied at report construction inside `runTriagePass` at READ time — retuning the threshold or rescue knobs re-gates with zero re-judging; the stored `worth_processing` boolean derives from the fixed `DEFAULT_TRIAGE_THRESHOLD` constant (back-compat only, never the live dial). Passing files fan out one subagent per chunk with `max_turns` from `dream.synthesize.max_turns` (default 16) and a bounded advisory `buildTriageMapBlock` (exported; score/type/entities + chunk-filtered segments, '' for legacy/degraded verdicts so the prompt is unchanged for those) spliced into `buildSynthesisPrompt`, with `allowed_slug_prefixes` (sourced from `skills/_brain-filing-rules.json` `dream_synthesize_paths.globs`; when `dream.synthesize.output_root` is set, `loadAllowedSlugPrefixes(outputRoot)` remaps the `wiki/`-rooted globs to the configured namespace, and the same root drives the prompt slug templates; default 'wiki', validated against the slug grammar via the exported `loadOutputRoot`). The phase is source-scoped: cycle.ts threads `cycleSourceId` as `opts.sourceId` → each child's `SubagentHandlerData.source_id` → the subagent tool registry's `OperationContext.sourceId`, so put_page writes, collected refs, the summary page, and reverse-writes all target the cycle's resolved source ('default' when unscoped; reverse-writes for the cycle's own source land at `brainDir/<slug>.md`, foreign sources under `brainDir/.sources/<id>/`). Orchestrator collects slugs from `subagent_tool_executions` (NOT `pages.updated_at`) and reverse-renders DB → markdown via `serializeMarkdown`. Cooldown via `dream.synthesize.last_completion_ts`, written ONLY on success. Idempotency keys `dream:synth-v2:<enc source>:filename:<enc basename>:<hash16>[:c<i>of<n>]` (byte-stable, pinned by `test/e2e/dream-synthesize-chunking.test.ts`; grammar parsed by exported `parseSynthV2Key`). Fan-out self-heals idempotency-coalesced rows stranded `waiting` in a FOREIGN dead `dream-inline-*` queue (cancel releases the key slot → re-add into the live run's queue) instead of burning the 35-min wait on a row no worker will ever claim. Opt-in per-source daily submission cap `dream.synthesize.max_submissions_per_source_per_day` (default 0 = off; skips whole files — never partial chunk sets; bypassed for explicit `--input/--date/--from/--to` targets; count-query failure fails OPEN with a stderr warn). `--dry-run` runs triage, skips synthesis; deferral-aware headlines append "(N not yet triaged — time budget...)" so a time-boxed cold pass never reads as mass rejection. `details.triage` (threshold/judged/cache_hits/unreliable/degraded/deferred/below_threshold + rescue_band/rescue_checked/rescue_fired + tokens_in/tokens_out/cost_usd) + `details.synthesis` (jobs/avg_turns/max_turns_config + quote_verify/spend/children_zero_pages) carry the phase telemetry. Subagent never gets fs-write access. `renderPageToMarkdown` (exported) stamps `dream_generated: true` + `dream_cycle_date` into every reverse-write's frontmatter; `writeSummaryPage` does the same on the summary index — this marker is the explicit identity surface `isDreamOutput` checks in `transcript-discovery.ts`. `stampDreamProvenance` additionally persists the same marker into the `pages.frontmatter` JSONB row (merge via `executeRawJsonb`, raw object bound to `$N::jsonb`) for every child-written page BEFORE reverse-rendering, so generated pages are DB-queryable and a later put_page write-through (which re-renders from the DB row) can't erase the stamp. `judgeSignificance`, `JudgeClient`, `runTriagePass`, `buildTriageMapBlock`, `parseSynthV2Key`, `loadSynthConfig`, `TRIAGE_VERSION`, and `DEFAULT_TRIAGE_THRESHOLD` are exported; the triage model resolves via an explicit pre-read of `models.dream.triage` (preferred; through exported `resolveAlias`) falling back to the standard `resolveModel` chain (`models.dream.synthesize_verdict` → deprecated `dream.synthesize.verdict_model` → tier `utility`). `splitTranscriptByBudget(content, contentHash, maxChars)` splits oversized transcripts at paragraph boundaries (`## Topic:` → `---` → `\n` ladder) using a deterministic offset seeded from the first 32 bits of `contentHash` so retries chunk identically; per-chunk char budget = `MODEL_CONTEXT_TOKENS[resolvedModel] × 0.9 × 3.5 chars/token` (non-Anthropic ids fall back to a 180K-token safe default + once-per-process stderr warn); operator overrides `dream.synthesize.max_prompt_tokens` (floor 100K, wins) and `dream.synthesize.max_chunks_per_transcript` (default 24); per-chunk subagent job/wait timeouts are `dream.synthesize.subagent_timeout_ms` / `dream.synthesize.subagent_wait_timeout_ms` (defaults 30/35 min). Legacy `dream:synth:` keys are never produced — `loadSuccessfulSynthesisKeys(engine, sourceId, keyPrefix)` reads the completed rows of BOTH key families once per phase, so existing brains skip with `already_synthesized_legacy_single_chunk`/`_chunked` instead of re-spending the synthesis model, and a transcript whose synth-v2 children already completed skips with `already_synthesized_v2_single_chunk`/`_chunked` (`findSynthV2Completion`; a cancelled row never counts) BEFORE its link manifest is built — otherwise queue.add's idempotency fast path coalesces onto the completed children and they re-enter writtenRefs, so their old pages get quote-repaired, restamped, reverse-written and re-embedded every night. `collectChildPutPageSlugs` raw-fetches every (job_id, slug) pair (not `SELECT DISTINCT`) and rewrites bare-hash6 slugs to `<hash6>-c<idx>` for chunked children (orchestrator-side, zero Sonnet trust). Cap-hit skips write nothing new to `dream_verdicts` (the pass's cached triage verdict remains — a free cache hit on retry) and record no synthesis job, so raising the cap on next run re-attempts cleanly. Bounds INITIAL prompt size only; tool-loop turn-N accumulation is caught by terminal-error classification in `subagent.ts`. Verdict routing is gateway-routed: `makeJudgeClient(verdictModel)` (exported) mirrors `tryBuildGatewayClient` in `src/core/think/index.ts` — a construction-time provider/key probe returns `null` on a clear miss (unknown provider id via `resolveRecipe` AIConfigError, or Anthropic provider with no key via `hasAnthropicKey()`). The verdict loop wraps `judgeSignificance` in try/catch for `AIConfigError` so mid-run provider failures surface as per-transcript `worth=false, reasons=['gateway error: ...']` instead of crashing the phase. Canonical config key `models.dream.synthesize_verdict` (per `PER_TASK_KEYS` in `src/core/model-config.ts`); `JudgeClient` signature preserved verbatim for test-seam stability; CI guard `scripts/check-gateway-routed-no-direct-anthropic.sh` prevents reintroducing `new Anthropic()` here or in `think/index.ts`. At the queue.add boundary a conditional `anthropic:` prefix is applied ONLY when the resolved model has no colon AND starts with `claude-` (because `resolveModel` returns bare ids from `TIER_DEFAULTS`/`DEFAULT_ALIASES` and the subagent validator requires `provider:model` form) — avoids changing the shared constants which would ripple across every `resolveModel` caller. Pinned by `test/cycle/synthesize-gateway-adapter.test.ts`, `test/e2e/dream-synthesize-pglite.test.ts` (gateway-adapter mid-run AIConfigError catch), `test/cycle/regression-pr-wave-r1-r2-r4.test.ts`. Drain-loop lock renewal runs through exported `runDrainRenewalTick` (per-call AbortSignal + timeout + re-entrancy guard) — a hung renewLock cannot stack one checked-out slot per interval firing. Pinned by `test/cycle-drain-renewal.test.ts`. Execution mode: `dream.synthesize.mode` (default `oneshot`) threads to every child as `data.mode` alongside `oneshot_slug_suffix` (the structural suffix contract) and `require_writes: true`; `details.synthesis` adds mode/oneshot_jobs/fallback_jobs/agentic_jobs/fallback_reasons plus the drain telemetry (inline_concurrency_config/effective, drain_ms, queue-wait + runtime p50/p95, dead_jobs, degraded). Pre-retrieval LINK CANDIDATES manifest (link-manifest.ts, `dream.synthesize.link_manifest` default on) is built once per transcript from the cached triage entities/segment notes and spliced into `buildSynthesisPrompt` together with an ALLOWED WRITE PATHS block rendered from the trusted allow-list (the oneshot path never sees a tool schema, so the fence lives in the prompt; rule 2 points at the candidates first). Phase outcome gate: ALL children dead/cancelled → phase fails with SYNTH_ALL_CHILDREN_DEAD (fan-out details preserved on the failure); ANY non-completed child → the cooldown stamp is skipped so released idempotency keys retry next run; 'timeout' (parent stopped waiting) degrades but never triggers the all-dead error. Phase-end deferred-embed closure: whenever the phase wrote pages (regardless of mode — an agentic revert still sweeps debt left by earlier oneshot runs), a 120s-bounded `embedStalePages` (embed-stale.ts) embeds the NULL-embedding chunks of exactly the pages this phase wrote — never a source-wide sweep; the pre-existing stale backlog stays with the budget-tracked embed-backfill machinery — closing the gap on invocation shapes that never reach the global embed phase (`--phase synthesize`, autopilot per-source NON_GLOBAL_PHASES). Best-effort (never fails a phase that wrote its pages) and stamps the current embedding signature on fully-re-embedded pages so they stay inside the model-drift invalidation contract. The inline drain lives in `src/core/cycle/inline-drain.ts` (re-exported here for patterns.ts + `__testing`). Budget clamping: clamped to the remaining parent-job budget when `opts.deadlineAtMs` is threaded (via patterns.ts's `clampSubagentBudgets` template): the clamp re-runs against the live clock PER SUBMIT (the phase is a fan-out with claim-time-anchored child kill switches, so one phase-start clamp only bounds the first child); under the minimum child budget the phase skips honestly (`insufficient_cycle_budget`) or defers the remaining transcripts (`details.budget_deferred_transcripts`), the inline drain stops CLAIMING when the budget can't fit another child and unclaimed children are cancelled + deferred (they'd otherwise strand forever in the run's private queue), each completion wait is additionally bounded by the remaining parent budget (floored at 1s so already-terminal children still resolve), and a deferring run neither writes the 12h cooldown timestamp nor counts deferred transcripts as processed — deferral genuinely retries next cycle. THE gate is `passesTriageGate` (triage-rescue.ts) applied at report construction inside `runTriagePass`: threshold pass OR the verified-segment rescue for band scores `[dream.triage.rescue_floor (0.30), threshold)` with content_type in `dream.triage.rescue_content_types` and ≥ `dream.triage.rescue_min_segments` (default 2; 0 = off) of the judge's segments verifying as normalized transcript substrings (≥40 chars, deduped) — reports carry `rescued`/`verified_segments`, `details.triage` adds rescue_band/rescue_checked/rescue_fired + judge tokens_in/tokens_out/cost_usd (null when unpriced), and dream-retriage's reconcile/audit read the SAME predicate. TRIAGE_VERSION is 2 (peak-not-average rubric; segment selection prefers concrete facts/decisions). After slug collection and BEFORE the provenance stamp/reverse-write/embed sweep, the quote verify/repair pass (synthesize-verify.ts, `dream.synthesize.quote_verify` default on) runs on newly-created pages; the phase is wrapped in `withChatPhase('phase:synthesize')` (children keep their own job tag — minion_jobs stays the child-spend authority) and `details.synthesis` adds `quote_verify`, `children_zero_pages` (completed children with zero put_page writes — the rule-D disposition), and `spend` (`cost_basis: 'in+out+cache_read'`; children summed from minion_jobs tokens_input/output/cache_read priced at the configured synth model, triage from the pass usage; total_usd null unless both price) `buildSynthesisPrompt` is mode-aware (`mode: 'agentic' | 'oneshot'`, passed from `config.mode` at the sole submit site): agentic children keep the search-tool and final-summary guidance; tool-less oneshot children receive neither, so the prompt never contradicts `ONESHOT_SYSTEM`'s JSON-only rule (the oneshot prompt is stored as `data.prompt` and reused verbatim by the in-job agentic fallback, whose tools stay in the schema). Pinned by `test/cycle-dream-output-root.test.ts`.
+- `src/core/cycle/synthesize.ts` — Synthesize phase: conversation-transcript-to-brain pipeline, a two-stage cascade where cheap scored triage gates frontier synthesis. Reads `dream.synthesize.session_corpus_dir`, runs `runTriagePass` (exported; bounded pool `dream.triage.concurrency` default 4, wall-clock cache-MISS budget `dream.triage.max_ms` default 5 min — cache hits are free and deferred files report `deferred: true`, never cached, so the next pass continues) whose judge `judgeSignificance` emits `{score 0-1 ordinal salience, content_type, segments ≤8 verbatim quotes, entities ≤12, reasons}` (non-overlapping bands LOW 0-0.29 / MEDIUM 0.30-0.69 / HIGH 0.70-1.0; head 50%/middle 20%/tail 30% sample within `dream.triage.max_chars` default 24K via `safeSplitIndex`; out-of-[0,1] scores are `unparseable`, never clamped) cached in `dream_verdicts` with the judging `model` + `TRIAGE_VERSION` — cache validity requires BOTH to match (switching `models.dream.triage` re-judges; `max_chars`/`max_tokens` deliberately excluded from validity — `dream retriage --force` re-judges under new sampling knobs). Degenerate verdicts (`truncated`/`refusal`/`unparseable`) are never cached. THE gate is `passesTriageGate` (triage-rescue.ts): `score >= dream.triage.threshold` (default 0.5) OR the verified-segment rescue, applied at report construction inside `runTriagePass` at READ time — retuning the threshold or rescue knobs re-gates with zero re-judging; the stored `worth_processing` boolean derives from the fixed `DEFAULT_TRIAGE_THRESHOLD` constant (back-compat only, never the live dial). Passing files fan out one subagent per chunk with `max_turns` from `dream.synthesize.max_turns` (default 16) and a bounded advisory `buildTriageMapBlock` (exported; score/type/entities + chunk-filtered segments, '' for legacy/degraded verdicts so the prompt is unchanged for those) spliced into `buildSynthesisPrompt`, with `allowed_slug_prefixes` (sourced from `skills/_brain-filing-rules.json` `dream_synthesize_paths.globs`; when `dream.synthesize.output_root` is set, `loadAllowedSlugPrefixes(outputRoot)` remaps the `wiki/`-rooted globs to the configured namespace, and the same root drives the prompt slug templates; default 'wiki', validated against the slug grammar via the exported `loadOutputRoot`). The phase is source-scoped: cycle.ts threads `cycleSourceId` as `opts.sourceId` → each child's `SubagentHandlerData.source_id` → the subagent tool registry's `OperationContext.sourceId`, so put_page writes, collected refs, the summary page, and reverse-writes all target the cycle's resolved source ('default' when unscoped; reverse-writes for the cycle's own source land at `brainDir/<slug>.md`, foreign sources under `brainDir/.sources/<id>/`). Orchestrator collects slugs from `subagent_tool_executions` (NOT `pages.updated_at`) and reverse-renders DB → markdown via `serializeMarkdown`. Cooldown via `dream.synthesize.last_completion_ts`, written only when children completed and neither synthesis-budget nor triage-budget deferrals remain. Idempotency keys `dream:synth-v2:<enc source>:filename:<enc basename>:<hash16>[:c<i>of<n>]` (byte-stable, pinned by `test/e2e/dream-synthesize-chunking.test.ts`; grammar parsed by exported `parseSynthV2Key`). Fan-out self-heals idempotency-coalesced rows stranded `waiting` in a FOREIGN dead `dream-inline-*` queue (cancel releases the key slot → re-add into the live run's queue) instead of burning the 35-min wait on a row no worker will ever claim. Opt-in per-source daily submission cap `dream.synthesize.max_submissions_per_source_per_day` (default 0 = off; skips whole files — never partial chunk sets; bypassed for explicit `--input/--date/--from/--to` targets; count-query failure fails OPEN with a stderr warn). `--dry-run` runs triage, skips synthesis; deferral-aware headlines append "(N not yet triaged — time budget...)" so a time-boxed cold pass never reads as mass rejection. `details.triage` (threshold/judged/cache_hits/unreliable/degraded/deferred/below_threshold + rescue_band/rescue_checked/rescue_fired + tokens_in/tokens_out/cost_usd) + `details.synthesis` (jobs/avg_turns/max_turns_config + quote_verify/spend/children_zero_pages) carry the phase telemetry. Subagent never gets fs-write access. `renderPageToMarkdown` (exported) stamps `dream_generated: true` + `dream_cycle_date` into every reverse-write's frontmatter; `writeSummaryPage` does the same on the summary index — this marker is the explicit identity surface `isDreamOutput` checks in `transcript-discovery.ts`. `stampDreamProvenance` additionally persists the same marker into the `pages.frontmatter` JSONB row (merge via `executeRawJsonb`, raw object bound to `$N::jsonb`) for every child-written page BEFORE reverse-rendering, so generated pages are DB-queryable and a later put_page write-through (which re-renders from the DB row) can't erase the stamp. `judgeSignificance`, `JudgeClient`, `runTriagePass`, `buildTriageMapBlock`, `parseSynthV2Key`, `loadSynthConfig`, `TRIAGE_VERSION`, and `DEFAULT_TRIAGE_THRESHOLD` are exported; the triage model resolves via an explicit pre-read of `models.dream.triage` (preferred; through exported `resolveAlias`) falling back to the standard `resolveModel` chain (`models.dream.synthesize_verdict` → deprecated `dream.synthesize.verdict_model` → tier `utility`). `splitTranscriptByBudget(content, contentHash, maxChars)` splits oversized transcripts at paragraph boundaries (`## Topic:` → `---` → `\n` ladder) using a deterministic offset seeded from the first 32 bits of `contentHash` so retries chunk identically; per-chunk char budget = `MODEL_CONTEXT_TOKENS[resolvedModel] × 0.9 × 3.5 chars/token` (non-Anthropic ids fall back to a 180K-token safe default + once-per-process stderr warn); operator overrides `dream.synthesize.max_prompt_tokens` (floor 100K, wins) and `dream.synthesize.max_chunks_per_transcript` (default 24); per-chunk subagent job/wait timeouts are `dream.synthesize.subagent_timeout_ms` / `dream.synthesize.subagent_wait_timeout_ms` (defaults 30/35 min). Legacy `dream:synth:` keys are never produced — `loadSuccessfulSynthesisKeys(engine, sourceId, keyPrefix)` reads the completed rows of BOTH key families once per phase, so existing brains skip with `already_synthesized_legacy_single_chunk`/`_chunked` instead of re-spending the synthesis model, and a transcript whose synth-v2 children already completed skips with `already_synthesized_v2_single_chunk`/`_chunked` (`findSynthV2Completion`; a cancelled row never counts) BEFORE its link manifest is built — otherwise queue.add's idempotency fast path coalesces onto the completed children and they re-enter writtenRefs, so their old pages get quote-repaired, restamped, reverse-written and re-embedded every night. `collectChildPutPageSlugs` raw-fetches every (job_id, slug) pair (not `SELECT DISTINCT`) and rewrites bare-hash6 slugs to `<hash6>-c<idx>` for chunked children (orchestrator-side, zero Sonnet trust). Cap-hit skips write nothing new to `dream_verdicts` (the pass's cached triage verdict remains — a free cache hit on retry) and record no synthesis job, so raising the cap on next run re-attempts cleanly. Bounds INITIAL prompt size only; tool-loop turn-N accumulation is caught by terminal-error classification in `subagent.ts`. Verdict routing is gateway-routed: `makeJudgeClient(verdictModel)` (exported) mirrors `tryBuildGatewayClient` in `src/core/think/index.ts` — a construction-time provider/key probe returns `null` on a clear miss (unknown provider id via `resolveRecipe` AIConfigError, or Anthropic provider with no key via `hasAnthropicKey()`). The verdict loop wraps `judgeSignificance` in try/catch for `AIConfigError` so mid-run provider failures surface as per-transcript `worth=false, reasons=['gateway error: ...']` instead of crashing the phase. Canonical config key `models.dream.synthesize_verdict` (per `PER_TASK_KEYS` in `src/core/model-config.ts`); `JudgeClient` signature preserved verbatim for test-seam stability; CI guard `scripts/check-gateway-routed-no-direct-anthropic.sh` prevents reintroducing `new Anthropic()` here or in `think/index.ts`. At the queue.add boundary a conditional `anthropic:` prefix is applied ONLY when the resolved model has no colon AND starts with `claude-` (because `resolveModel` returns bare ids from `TIER_DEFAULTS`/`DEFAULT_ALIASES` and the subagent validator requires `provider:model` form) — avoids changing the shared constants which would ripple across every `resolveModel` caller. Pinned by `test/cycle/synthesize-gateway-adapter.test.ts`, `test/e2e/dream-synthesize-pglite.test.ts` (gateway-adapter mid-run AIConfigError catch), `test/cycle/regression-pr-wave-r1-r2-r4.test.ts`. Drain-loop lock renewal runs through exported `runDrainRenewalTick` (per-call AbortSignal + timeout + re-entrancy guard) — a hung renewLock cannot stack one checked-out slot per interval firing. Pinned by `test/cycle-drain-renewal.test.ts`. Execution mode: `dream.synthesize.mode` (default `oneshot`) threads to every child as `data.mode` alongside `oneshot_slug_suffix` (the structural suffix contract) and `require_writes: true`; `details.synthesis` adds mode/oneshot_jobs/fallback_jobs/agentic_jobs/fallback_reasons plus the drain telemetry (inline_concurrency_config/effective, drain_ms, queue-wait + runtime p50/p95, dead_jobs, degraded). Pre-retrieval LINK CANDIDATES manifest (link-manifest.ts, `dream.synthesize.link_manifest` default on) is built once per transcript from the cached triage entities/segment notes and spliced into `buildSynthesisPrompt` together with an ALLOWED WRITE PATHS block rendered from the trusted allow-list (the oneshot path never sees a tool schema, so the fence lives in the prompt; rule 2 points at the candidates first). Phase outcome gate: ALL children dead/cancelled → phase fails with SYNTH_ALL_CHILDREN_DEAD (fan-out details preserved on the failure); ANY non-completed child → the cooldown stamp is skipped so released idempotency keys retry next run; 'timeout' (parent stopped waiting) degrades but never triggers the all-dead error. Phase-end deferred-embed closure: whenever the phase wrote pages (regardless of mode — an agentic revert still sweeps debt left by earlier oneshot runs), a 120s-bounded `embedStalePages` (embed-stale.ts) embeds the NULL-embedding chunks of exactly the pages this phase wrote — never a source-wide sweep; the pre-existing stale backlog stays with the budget-tracked embed-backfill machinery — closing the gap on invocation shapes that never reach the global embed phase (`--phase synthesize`, autopilot per-source NON_GLOBAL_PHASES). Best-effort (never fails a phase that wrote its pages) and stamps the current embedding signature on fully-re-embedded pages so they stay inside the model-drift invalidation contract. The inline drain lives in `src/core/cycle/inline-drain.ts` (re-exported here for patterns.ts + `__testing`). Budget clamping: clamped to the remaining parent-job budget when `opts.deadlineAtMs` is threaded (via patterns.ts's `clampSubagentBudgets` template): the clamp re-runs against the live clock PER SUBMIT (the phase is a fan-out with claim-time-anchored child kill switches, so one phase-start clamp only bounds the first child); under the minimum child budget the phase skips honestly (`insufficient_cycle_budget`) or defers the remaining transcripts (`details.budget_deferred_transcripts`), the inline drain stops CLAIMING when the budget can't fit another child and unclaimed children are cancelled + deferred (they'd otherwise strand forever in the run's private queue), each completion wait is additionally bounded by the remaining parent budget (floored at 1s so already-terminal children still resolve), and a deferring run neither writes the 12h cooldown timestamp nor counts deferred transcripts as processed — deferral genuinely retries next cycle. THE gate is `passesTriageGate` (triage-rescue.ts) applied at report construction inside `runTriagePass`: threshold pass OR the verified-segment rescue for band scores `[dream.triage.rescue_floor (0.30), threshold)` with content_type in `dream.triage.rescue_content_types` and ≥ `dream.triage.rescue_min_segments` (default 2; 0 = off) of the judge's segments verifying as normalized transcript substrings (≥40 chars, deduped) — reports carry `rescued`/`verified_segments`, `details.triage` adds rescue_band/rescue_checked/rescue_fired + judge tokens_in/tokens_out/cost_usd (null when unpriced), and dream-retriage's reconcile/audit read the SAME predicate. TRIAGE_VERSION is 2 (peak-not-average rubric; segment selection prefers concrete facts/decisions). After slug collection and BEFORE the provenance stamp/reverse-write/embed sweep, the quote verify/repair pass (synthesize-verify.ts, `dream.synthesize.quote_verify` default on) runs on newly-created pages; the phase is wrapped in `withChatPhase('phase:synthesize')` (children keep their own job tag — minion_jobs stays the child-spend authority) and `details.synthesis` adds `quote_verify`, `children_zero_pages` (completed children with zero put_page writes — the rule-D disposition), and `spend` (`cost_basis: 'in+out+cache_read'`; children summed from minion_jobs tokens_input/output/cache_read priced at the configured synth model, triage from the pass usage; total_usd null unless both price) `buildSynthesisPrompt` is mode-aware (`mode: 'agentic' | 'oneshot'`, passed from `config.mode` at the sole submit site): agentic children keep the search-tool and final-summary guidance; tool-less oneshot children receive neither, so the prompt never contradicts `ONESHOT_SYSTEM`'s JSON-only rule (the oneshot prompt is stored as `data.prompt` and reused verbatim by the in-job agentic fallback, whose tools stay in the schema). Pinned by `test/cycle-dream-output-root.test.ts`.
- `src/core/cycle/cycle-date.ts` — the dream-cycle calendar-date policy: `resolveCycleDate` resolves explicit `--date` > `cycle.timezone` config > host IANA timezone > UTC, so a run after local midnight buckets into the day the user actually lived instead of rewriting yesterday's UTC-day summary. `isValidTimeZone` gates configured values (config.ts also validates at `gbrain config set` time); an invalid configured timezone falls back loudly instead of killing the cycle. `utcDate` is retained for source-date fallbacks and legacy pages.
- `src/core/cycle/extract-atoms.ts` — the extract_atoms lens phase: mines eligible pages into `atoms/<date>/<stem>-<hash>` pages. Eligibility is `COALESCE(frontmatter->>'atoms_scan_hash','') <> substring(content_hash from 1 for 16)`; the completion marker (`ATOMS_SCAN_HASH_KEY` in utils.ts) is EXCLUDED from `contentHash()`'s input so stamping it can't re-arm the very page it marks (and import-file.ts strips it from untrusted `remote===true` frontmatter so a remote writer can't suppress mining). Atom identity: page-derived atoms fold the source-page slug into the slug hash (8 chars, NUL-separated) so two same-date pages emitting the same title get DISTINCT slugs; the source CONTENT hash is deliberately NOT folded (a reworded source still upserts rather than duping); transcript atoms keep the legacy title-only 6-char hash. `resolvePageAtomSlug` adopts a legacy-slug atom with a compatible binding in place on re-extraction (upgrade idempotency — no migration, no duplicate), while `assertAtomImportBinding` fail-closed refuses to reuse a slug bound to a DIFFERENT source locator. Both share `isCompatibleAtomBinding(frontmatter, sourcePageSlug)` — the ONE definition of compatible: bound to THIS source page, or carrying no `source_slug`/`source_path` at all (pre-binding-era adoption, not a clobber); a `source_path`-bound legacy transcript atom or a different `source_slug` is a different origin, and a non-atom page squatting on the slug is refused. `source_quote` is verified at extraction time against the exact `truncateUtf8` prompt prefix the model saw (`locateQuote` advances by full code points): located quotes persist original characters + [start,end) offsets + `source_quote_verified`; unlocatable quotes are dropped with the atom kept. Edges write before the completion flip; per-item drain failures stay typed (bounded, sanitized, reconcilable). Transcript items carry the same failure-count/tombstone machinery as pages, in the `extract_atoms_transcript_state` table (migration `extract_atoms_transcript_state_table`; keyed `(source_id, file_path, content_hash)` with the 16-char hash prefix, so an edit is a new row and re-eligibilizes): `recordItemFailureCount` counts a transcript's malformed output toward `MAX_DETERMINISTIC_FAILURES`, a zero-yield transcript tombstones immediately (the page `atoms_scan_hash` semantics), and `tombstonedTranscriptsForHashes` is the batch read-side gate mirroring `atomsExistingForHashes` (fail-open on error). Reported as `tombstoned_transcripts` (paths), separate from the page-slug `tombstoned_for_failures`.
- `src/core/cycle/extract-atoms-cost-gate.ts` — pure cost-gate decision for the extract_atoms `BudgetTracker`. `resolveExtractAtomsCostGate(extractModel, embedModel, overrides?, {explicitBudget?})` returns `{enforceCap, unpricedModel?, unpricedKind?, zeroPricedEmbedModel?, pricingOverrides?}`: the cap is enforceable only when EVERY model billed under the phase's tracker is priceable — the extraction chat model AND the embedding model the atom import (`importFromContent`, inside the same `withBudgetTracker` scope) calls — with operator `pricing.overrides` consulted first, matching `BudgetTracker.reserve()`. `resolveEmbedModelForCostGate()` mirrors the write site's `isAvailable('embedding')` gate (null when embedding is unavailable, so the import runs `noEmbed` and nothing embeds). Only a DEFAULT cap may be dropped that way: when the operator SET `cycle.extract_atoms.budget_usd` (`explicitBudget`), an unpriced EMBED route keeps the cap and is priced at $0 via the returned `pricingOverrides` (the caller's map plus the $0 row); an unpriced CHAT model drops the cap either way. The phase passes the decision into `maxCostUsd` and hands the gate's overrides (or its own) to the tracker; it warns once either way (unpriced: kind + model + the `pricing.overrides` remedy, running uncapped rather than latching `budget_exhausted` on the first item; zero-priced: the embed model + the rate remedy). Pinned by `test/extract-atoms-embed-cost-gate.test.ts` (pure cases + a PGLite round-trip with a $0 chat model and an unpriced embed route).
@@ -451,7 +451,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/cycle/extract-facts.ts` — extract_facts cycle phase. Fence is canonical: per-page wipe (`deleteFactsForPage`) + reinsert from `parseFactsFence` + `extractFactsFromFenceText` + `engine.insertFacts`. The reconcile is a no-op when the page's fence-owned DB rows already match the fence; drift on any dimension — content key `(claim, source)`, `row_num`, expiry/supersession state, or the `visibility` / `notability` cells — routes the page through the atomic wipe+reinsert (confidence is not compared). The per-page wipe passes `excludeSourcePrefixes: ['cli:']` so conversation facts (written by `extract-conversation-facts`, on pages with NO `## Facts` fence to recreate them from) survive the reconcile instead of being deleted-with-nothing-to-reinsert. The destructive phase never inherits a failed sync's full-brain walk: `slugs: []` (a real incremental no-op) is distinguished from `slugs: undefined` (full-walk intent) by presence, not length. `runPhaseExtractFacts` (cycle.ts) surfaces a `warn` (`net_fact_deletion`) when the reconcile deletes at least `NET_DELETION_WARN_FLOOR` (50) more facts than it reinserts — the exact signature of a conversation-facts wipe. Empty-fence guard refuses when legacy rows (`row_num IS NULL AND entity_slug IS NOT NULL`) pend backfill (status: warn, hint: `gbrain apply-migrations --yes`). A phantom-redirect pre-pass runs AFTER the legacy-row guard, BEFORE the main reconcile loop: when `opts.brainDir` is set, `runPhantomRedirectPass(engine, brainDir, sourceId, dryRun)` walks unprefixed-slug pages capped by `GBRAIN_PHANTOM_REDIRECT_LIMIT` (default 50). The pass returns `touched_canonicals` — canonical slugs whose disk fence merged with phantom rows; `runExtractFacts` UNIONs them into the main reconcile slug set so canonical's DB facts derive from the merged fence in the same cycle (handles phantom-had-only-on-disk-fence). `ExtractFactsResult` carries six phantom fields: `phantomsScanned`, `phantomsRedirected`, `phantomsAmbiguous`, `phantomsSkippedDrift`, `phantomsLockBusy`, `phantomsMorePending`. Three bubble to `CycleReport.totals` (`phantoms_redirected`, `phantoms_ambiguous`, `phantoms_skipped_drift`).
- `src/core/facts-fence.ts` — the `## Facts` fence primitives: parse (`parseFactsFence`), render (`renderFactsTable`), and strip (`stripFactsFence({keepVisibility})` — the remote-read privacy boundary `get_page`/`fetch_page`/the chunker apply), plus the remote write-back merge, plus the ONE fence-placement rule: `replaceOrInsertFactsFence(body, fenceBlock)` replaces an existing fence in place or inserts a fresh `## Facts` section ABOVE the timeline sentinel (`timelineSentinelOffset`, #4756 — below it splitBody() files the fence into page.timeline where extract_facts refuses to reconcile it), EOF only when the page has no sentinel; every writer that materializes a fence (`upsertFactRow`, the phantom-redirect canonical append, the importer's hidden-row merge) routes through it, so no writer can re-grow its own EOF append. `restoreHiddenFactRows(incoming, existing)` is the row-level, visibility-aware merge `import-file.ts` applies per fence-bearing column (compiled_truth AND timeline) when a remote caller writes back a page it read with hidden rows stripped — without it, a remote get→edit→put round-trip would silently drop every non-`world` fact row. Rules: only non-`world` rows of the existing fence are restoration candidates (a caller's deletion of a VISIBLE row stays honored — world rows are never restored); a hidden row whose rowNum is absent from the incoming fence is restored at its stable rowNum (cross-page `#F<N>` refs survive); a rowNum collision (a caller-authored addition landing on a hidden number the caller never saw) keeps the hidden row's number and renumbers the CALLER's row onto fresh appended numbers (upsertFactRow's append-only contract); same rowNum + same claim keeps the incoming version (idempotent full-content write-throughs); either side parsing with warnings returns null — re-rendering a fence that didn't fully parse would drop the caller's unparsed rows — and `factsGapWarning` surfaces exactly that residual loss. Pure and side-effect-free. Pinned by `test/facts-fence.test.ts` + the remote write-back describes in `test/privacy-strip-and-forget.test.ts` (row-level merge, world-only deletion honored, timeline-embedded fence round-trip).
- `src/core/fence-shared.ts` — shared pipe-table primitives for the `## Takes` (`takes-fence.ts`) and `## Facts` (`facts-fence.ts`) fences: `parseRowCells`, `isSeparatorRow`, `stripStrikethrough`, `parseStringCell`, `escapeFenceCell`. `parseRowCells` is escape-aware: `\|` stays inside its cell and decodes back to a literal `|` (exact inverse of `escapeFenceCell`), while any other backslash passes through verbatim so existing fence text (e.g. Windows paths) is byte-stable across a render → parse cycle. This matters because the fence is canonical and reconcile is wipe-and-reinsert — a pipe inside a cell shifting the column layout would corrupt every row behind it on the next reconcile. Pinned by the escape cases in `test/facts-fence.test.ts` + the full render → parse → reconcile round-trip in `test/e2e/facts-fence-reconcile-postgres.test.ts`.
-- `src/core/entities/resolve.ts` — Free-form entity name → canonical slug resolution. `resolveEntitySlug(engine, source_id, raw)`: exact slug → alias-exact (an unambiguous `page_aliases` hit via `resolveAliases`, verified against LIVE pages since `page_aliases` has no FK — a stale alias row can never point at a deleted page; fail-open on pre-v110 brains missing the table; `ResolutionSource` reports `alias_exact`) → unambiguous bare-name prefix expansion across `people/<token>-%` + `companies/<token>-%` → high-specificity fuzzy match for multi-token input (pg_trgm @ 0.7 threshold) → deterministic `slugify` holding fallback. Bare-name collisions never use popularity as confidence; shared-token company names below the threshold remain unresolved. Two helpers for the phantom-redirect pass: `resolvePhantomCanonical(engine, sourceId, phantomSlug)` SKIPS the exact-slug step (a phantom slug `'alice'` would exact-match itself and no-op the redirect); returns the canonical only when non-null AND contains `/`. `findPrefixCandidates(engine, sourceId, token)` is a standalone SQL query returning ALL candidates across `PREFIX_EXPANSION_DIRS` (hardcoded `['people', 'companies']`) via `slug LIKE ANY($N::text[])` over patterns `dir/token` + `dir/token-%`, cap of 10 ordered by `connection_count DESC, slug ASC`. Pinned by `test/entity-resolve.test.ts` (explicit, unique, ambiguous-person, and shared-token-company cases) plus `test/phantom-redirect.test.ts` (resolvePhantomCanonical 3 cases + findPrefixCandidates 6 cases incl. multi-dir ambiguity and the `people/aliceberg`-doesn't-match-`alice` false-positive guard).
+- `src/core/entities/resolve.ts` — Free-form entity name → canonical slug resolution. `resolveEntitySlug(engine, source_id, raw)`: exact slug → alias-exact (an unambiguous `page_aliases` hit via `resolveAliases`, verified against LIVE pages since `page_aliases` has no FK — a stale alias row can never point at a deleted page; fail-open on pre-v110 brains missing the table; `ResolutionSource` reports `alias_exact`) → unique source-scoped full-basename match for multi-token names across people/companies/hosts/projects/concepts → unambiguous bare-name prefix expansion across `people/<token>-%` + `companies/<token>-%` → high-specificity fuzzy match for multi-token input (pg_trgm @ 0.7 threshold) → deterministic `slugify` holding fallback. Bare-name collisions never use popularity as confidence; shared-token company names below the threshold remain unresolved. Two helpers for the phantom-redirect pass: `resolvePhantomCanonical(engine, sourceId, phantomSlug)` SKIPS the exact-slug step (a phantom slug `'alice'` would exact-match itself and no-op the redirect); returns the canonical only when non-null AND contains `/`. `findPrefixCandidates(engine, sourceId, token)` is a standalone SQL query returning ALL candidates across `PREFIX_EXPANSION_DIRS` (hardcoded `['people', 'companies']`) via `slug LIKE ANY($N::text[])` over patterns `dir/token` + `dir/token-%`, cap of 10 ordered by `connection_count DESC, slug ASC`. Pinned by `test/entity-resolve.test.ts` (explicit, unique, ambiguous-person, and shared-token-company cases) plus `test/phantom-redirect.test.ts` (resolvePhantomCanonical 3 cases + findPrefixCandidates 6 cases incl. multi-dir ambiguity and the `people/aliceberg`-doesn't-match-`alice` false-positive guard).
- `src/core/cycle/phantom-redirect.ts` — Phantom-redirect orchestrator. Exports `runPhantomRedirectPass(engine, brainDir, sourceId, dryRun): Promise<PhantomPassResult>` (per-cycle wrapper acquiring the `gbrain-sync` writer lock once for the whole pass, 30s bounded retry, walks up to `GBRAIN_PHANTOM_REDIRECT_LIMIT` unprefixed phantoms) + `tryRedirectPhantom(engine, page, sourceId, brainDir, dryRun): Promise<RedirectResult>` + `stripFenceAndFrontmatterAndLeadingH1` (pure body-shape gate helper — strips facts fence incl. preceding `## Facts` heading and the leading H1; zero residue = phantom). Handler order: body-shape gate → `resolvePhantomCanonical` (bypasses exact-self-match) → `findPrefixCandidates` ambiguity check → `fenceDbDrift` bi-directional check → dry-run early exit → materialize canonical via `serializeMarkdown` if DB-only → append phantom fence rows to canonical's disk fence with `(claim, valid_from)` dedup-guard + row_num continuation → `engine.refreshPageBody` with SHA-256 content_hash recomputed via the import-file shape → `engine.migrateFactsToCanonical` (lossless) → `engine.rewriteLinks` (DB FK rewrite; wiki-link text rewrite is a documented follow-up) → `engine.softDeletePage` + `engine.deleteFactsForPage(phantom)` + `fs.unlinkSync(phantomPath)`. `RedirectResult.canonical` populated on `'redirected'` (incl. dry-run preview) so the caller builds `touched_canonicals`. Idempotent on re-run: phantom soft-deleted → predicate fails (`deleted_at IS NULL`); migrate UPDATE matches no rows; dedup-guard prevents double-append.
- `src/core/facts/phantom-audit.ts` — JSONL audit at `${resolveAuditDir()}/phantoms-YYYY-Www.jsonl`. Pattern copy of `src/core/audit-slug-fallback.ts` (ISO-week rotation, honors `GBRAIN_AUDIT_DIR`). Exports `logPhantomEvent(record)` + `readRecentPhantomEvents(days)` + `computePhantomAuditFilename(now?)`. Records every outcome: `redirected | ambiguous | drift | no_canonical | not_phantom_has_residue | pass_skipped_lock_busy`. Best-effort writes — stderr warn on failure, never throws. Separate file from `stub-guard-audit.ts` (distinct consumer + lifecycle: stub-guard logs PREVENTIVE blocks; phantom-audit logs CLEANUP decisions, to be read by a future `phantoms_pending` doctor check).
- `src/core/cycle/emotional-weight.ts` — Pure function `computeEmotionalWeight({tags, takes}, {highEmotionTags?, userHolder?})`. Deterministic 0..1 score: tag-emotion boost (max 0.5, case-insensitive match against `HIGH_EMOTION_TAGS` seed list), take density (0.1/take, capped at 0.3), take avg weight (0..0.1), user-holder ratio (0..0.1 over active takes; default holder `'garry'`). Total clamped to [0..1]. Anglocentric / personal-life-biased seed list intentional; override via config `emotional_weight.high_tags` (JSON array). `userHolder` overridable via `emotional_weight.user_holder`.
@@ -534,7 +534,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/destructive-guard.ts` — three-layer protection against accidental data loss. `assessDestructiveImpact(engine, sourceId)` counts pages/chunks/embeddings/files/facts for a source (a fact-only source — a revoked agent's workspace, since facts are the primary agent write lane — is data at stake, not empty; pre-facts brains degrade to 0), plus `oauthClientCount` — OAuth clients whose `source_id` references it. `checkDestructiveConfirmation(impact, opts)` is the fail-closed gate (`--confirm-destructive` required when data is present; `--yes` alone is rejected). FK-RESTRICT lifecycle: `clientsReferencingSource(engine, sourceId)` lists ALL physical OAuth-client rows referencing a source via `oauth_clients.source_id` — the FK is PHYSICAL (ON DELETE RESTRICT ignores `deleted_at`), so soft-deleted (revoked-but-retained) rows BLOCK a hard delete too and come back tagged `deleted`; pre-migration brains without `deleted_at` fall back to untagged referents (42703-retry idiom) and brains without the table have none by construction. `formatClientReferentsBlock` renders the shared refusal `sources remove`/`sources purge` print (naming each client — `[revoked, retained]` for soft-deleted rows — + the revoke command) so the raw Postgres FK violation never reaches the operator. `softDeleteSource` / `restoreSource` / `listArchivedSources` / `purgeExpiredSources` drive the source-level archive lifecycle via `sources.archived BOOLEAN`, `archived_at TIMESTAMPTZ`, `archive_expires_at TIMESTAMPTZ`; `purgeExpiredSources` SKIPS client-referenced sources via a physical `NOT EXISTS` (soft-deleted clients count) so recurring maintenance keeps sweeping the rest instead of aborting. Page-level analog: `BrainEngine.softDeletePage` / `restorePage` / `purgeDeletedPages` plus `pages.deleted_at TIMESTAMPTZ` and a partial purge index. The MCP `delete_page` op rewires to `softDeletePage`; ops `restore_page` (`scope: write`) and `purge_deleted_pages` (`scope: admin`, `localOnly: true`) round out the surface. `get_page`/`delete_page`/`restore_page` (`src/core/ops/pages.ts`) accept an explicit per-call `source_id` that is honored or rejected loudly, never silently dropped: `get_page` resolves it through the caller's read grant (`'__all__'` spans every source for trusted local callers, the granted sources for remote callers), while `delete_page`/`restore_page` reject `'__all__'`, target exactly one source, and — for every caller other than trusted local CLI (`ctx.remote === false`) — accept only the caller's write authority (`ctx.auth.sourceId`, falling back to `ctx.sourceId` for legacy tokens and unauthenticated transports; the federated read grant `allowedSources` confers no delete/restore access), echoing the targeted `source_id` in the response. Pinned by `test/pages-source-scoping-4329.test.ts`. Search visibility (`buildVisibilityClause` in `src/core/search/sql-ranking.ts`) hides soft-deleted pages and archived sources from `searchKeyword` / `searchKeywordChunks` / `searchVector` in both engines. The autopilot cycle's `purge` phase calls `purgeExpiredSources` + `engine.purgeDeletedPages(72)` so the 72h TTL is real.
- `src/commands/pages.ts` — `gbrain purge-deleted [--older-than HOURS|Nd] [--dry-run] [--json]` operator escape hatch. Mirror of `gbrain sources purge` for the page-level lifecycle. Hard-deletes pages whose `deleted_at` is older than the cutoff; cascades to content_chunks/page_links/chunk_relations.
- `src/core/op-checkpoint.ts` — DB-backed checkpoint primitive for long-running ops. Migration v67 introduces `op_checkpoints (op TEXT, fingerprint TEXT, completed_keys JSONB, updated_at TIMESTAMPTZ, PK(op, fingerprint))`. Per-op fingerprint helpers (`embedFingerprint`, `extractFingerprint`, `reindexFingerprint`, `integrityFingerprint`, `purgeFingerprint`) compute `sha8(canonical-JSON(relevant-params))` so re-running with the same params resumes from `completed_keys` and re-running with different params (e.g. `--limit 100` vs `--limit 200`) starts fresh. Cross-worker safe on Postgres (DB row, no file-lock race); PGLite degrades gracefully. The 7-day TTL GC runs in the cycle's `purge` phase. All writes (`recordCompleted`, `clearOpCheckpoint`) route through `engine.executeRawDirect` + `withRetry(BULK_RETRY_OPTS)` so they survive Supavisor pool exhaustion, and `recordCompleted` returns `boolean` (banked vs failed-after-retries) — the 9 non-sync consumers keep its REPLACE-into-`completed_keys` semantics. Resumable sync uses the additive `appendCompleted(key, deltaKeys)` / `appendCompletedOnce` (the latter no-retry for the SIGTERM path) which INSERT a delta into the `op_checkpoint_paths` child table (migration v115: `(op, fingerprint, path)` PK, FK to `op_checkpoints` ON DELETE CASCADE) via a single writable-CTE `unnest($3::text[])` write — O(delta), never an O(N²) full-set rewrite. `loadOpCheckpoint` returns the `UNION ALL` of legacy `completed_keys` + child-table paths (deduped in JS), so an in-flight upgrade loses nothing. The legacy arm is gated on `jsonb_typeof(completed_keys) = 'array'` so a non-array (scalar) parent row can't make `jsonb_array_elements_text` throw "cannot extract elements from a scalar" and take down the whole union (which would discard the valid child rows and lose all banked progress for the key); a third union arm flags the corruption so the loader logs it once and keeps the child rows. Migration v119 adds the `op_checkpoints_completed_keys_array` CHECK (`jsonb_typeof(completed_keys) = 'array'`) — a DB-enforced, always-on guard that makes the scalar-corruption class structurally impossible going forward; the migration repairs any pre-existing scalar to `'[]'` under `LOCK TABLE ... IN SHARE ROW EXCLUSIVE MODE` and `src/core/schema-embedded.generated.ts` + `src/core/pglite-schema.ts` ship the same CHECK on fresh installs (a loader hit implies schema drift, a disabled constraint, or an out-of-band writer). `recordCompleted` binds its array through `$3::text::jsonb` (NOT a bare `$3::jsonb`) so postgres.js `.unsafe()` doesn't double-encode `JSON.stringify(sorted)` into the scalar string that CHECK rejects (PGLite parses it silently, so only real Postgres surfaces the bug). A DATABASE_URL-gated `test/e2e/op-checkpoint-jsonb-parity.test.ts` (its own CI job) asserts the array shape on real Postgres. `syncFingerprint({sourceId, lastCommit})` keys the sync rows. Pinned by `test/op-checkpoint.test.ts` (incl. delta-append, union read, cascade clear, durable-write boolean, and the scalar-parent guard). `import-checkpoint.ts` stays a separate file-backed checkpoint — both systems coexist without conflict (unifying them would mean async-propagating the four sync call sites in `src/commands/import.ts`; deferred).
-- `src/core/brain-score-recommendations.ts` — pure data layer consumed by both `gbrain doctor --remediation-plan` / `--remediate` and `gbrain features`. `computeRecommendations(checks, opts)` returns `Remediation[]` with stable `id`, content-hash `idempotency_key`, `severity`, `est_seconds`, `est_usd_cost`, `depends_on` (references stable ids, not check names — so plan order is reproducible). `classifyChecks(report)` triages every doctor check three-state into `remediable | human_only | blocked` (`human_only` covers RLS warnings and other human-judgment gates; `blocked` covers dependency chains where a parent check failed). `maxReachableScore(checks)` computes the ceiling for empty/under-configured brains (no entity pages → graph_coverage caps at 70; no embedding key → embedding_coverage caps at 60). Cost estimates pull from `anthropic-pricing.ts` (synthesize/patterns/consolidate) and `embedding-pricing.ts` (embed jobs). Pinned by `test/brain-score-recommendations.test.ts` (~27 cases incl. determinism, content-hash idempotency, DB-backed checkpoint provenance, three-state triage).
+- `src/core/brain-score-recommendations.ts` — pure data layer consumed by both `gbrain doctor --remediation-plan` / `--remediate` and `gbrain features`. Extraction-watermark staleness produces source-scoped `extract.stale` against database pages, including DB-only pages without a checkout; it does not imply a filesystem sync or block embedding on one. `computeRecommendations(checks, opts)` returns `Remediation[]` with stable `id`, content-hash `idempotency_key`, `severity`, `est_seconds`, `est_usd_cost`, `depends_on` (references stable ids, not check names — so plan order is reproducible). `classifyChecks(report)` triages every doctor check three-state into `remediable | human_only | blocked` (`human_only` covers RLS warnings and other human-judgment gates; `blocked` covers dependency chains where a parent check failed). `maxReachableScore(checks)` computes the ceiling for empty/under-configured brains (no entity pages → graph_coverage caps at 70; no embedding key → embedding_coverage caps at 60). Cost estimates pull from `anthropic-pricing.ts` (synthesize/patterns/consolidate) and `embedding-pricing.ts` (embed jobs). Pinned by `test/brain-score-recommendations.test.ts` (~27 cases incl. determinism, content-hash idempotency, DB-backed checkpoint provenance, three-state triage).
- `src/core/abort-check.ts` — one canonical place for cooperative-abort checks across gbrain's long loops. `isAborted(signal?)` → boolean (for loops that `break` and return partial progress). `throwIfAborted(signal?, label?)` throws an `AbortError` (`name === 'AbortError'`) at phase boundaries, preferring the signal's `reason` ('wall-clock'/'lock-lost'/'shutdown') so the unwind self-describes. `anySignal(internal, external?)` composes two signals into one that fires when EITHER does (platform `AbortSignal.any` with a manual-relay fallback), returning the internal unchanged when there's no external so non-aborting callers pay nothing. Threading these checks through `runPhaseEmbed → runEmbedCore → embedAll(Stale)/embedPage` lets the embed phase bail and release `gbrain_cycle_locks` immediately (an embed phase that ignored its abort signal would hold the lock and make later autopilot cycles skip with `cycle_already_running`). Coverage spans every long cycle-reachable phase: `extract` (incremental `extractForSlugs` + the full-walk `extractLinksFromDir`/`extractTimelineFromDir`, all via `runSlidingPool`'s signal), `extract_facts` (per-page loop + the per-page `embed` signal + `runPhantomRedirectPass`'s 30s lock-retry), `consolidate`'s bucket loop, and `lint` (which is synchronous, so it `await`s a periodic yield to let the signal land). `runCycle` adds a terminal abort check before stamping `last_full_cycle_at` so a cancelled cycle never reports a completed full run, plus a per-phase `duration_ms` warning that names any phase overrunning the worker's 30s force-evict deadline. Pinned by `test/abort-check.test.ts` + `test/cycle-abort.test.ts`.
- `openclaw.plugin.json` — ClawHub bundle plugin manifest
- `.codex-plugin/plugin.json` + `.codex-plugin/mcp.json` + `.agents/plugins/marketplace.json` — the Codex plugin lane: manifest (skills → the committed `plugin/` tree; mcpServers → the NON-root mcp.json), the MCP declaration (`serve --surface starter --source-guard`, code-derived `env_vars` passthrough), and the codex-native marketplace. Version lockstep with package.json + the claude/openclaw manifests pinned by `test/codex-plugin-manifest.test.ts`.
@@ -731,10 +731,13 @@ operation: `skills/google-loops/SKILL.md`.
- `src/commands/google-setup.ts` + `google-setup-tail.ts` — the one-command orchestrator behind `gbrain google setup`: connect (skipped when tokens exist) → source registration (skipped when registered) → first bounded sync under a wall-clock budget (the newest-first backfill floor means whatever lands is the NEWEST mail — exactly what `waiting` needs; the remainder resumes on every later sync, and setup says so honestly) → the first `gbrain waiting` digest in the same session as consent. Split in two so the connect half stays engine-free. Every step idempotent; re-running resumes wherever the last run stopped.
- `src/commands/doctor/checks/google-oauth.ts` — the `google_oauth` doctor check: zero-network vault health (live refresh probes belong to `gbrain google status`; doctor stays fast and offline-safe). fail: a connected account with an expired access token AND no successful refresh in >2 days (refresh is broken — revoked, rotated client, or the Testing-mode expiry already hit); warn: a consent screen not known Production whose last proof of life is ≥5 days old (the proactive day-6 re-auth demand, cheaper than a dead pipeline on day 8); ok: accounts healthy or nothing connected (the connector is optional, not an error).
-- `src/core/agent-install/` + `scripts/setup-in-agent.sh` — Package-versioned non-root installation into a verified persistent root. Absolute launchers isolate ambient routing and credentials, receipts track ownership, pending enablement, non-secret failure codes, and an exact repair command, and repair retains database contents. Upgrades journal pending schema migrations before switching runtime metadata; retries use schema-only initialization without invoking host orchestration. Busy results remain structured and retryable without deleting live locks. Native instructions/routines remain pending until observed in the actual harness.
+- `src/core/agent-install/` + `scripts/setup-in-agent.sh` — Package-versioned non-root installation into a verified persistent root. Absolute launchers isolate ambient routing and credentials; local launchers pin the host brain and installed source, while thin-client launchers leave unqualified routing to the remote grant and preserve explicit CLI arguments. Receipts track ownership, pending enablement, non-secret failure codes, and an exact repair command, and repair retains database contents. Upgrades journal pending schema migrations before switching runtime metadata; retries use schema-only initialization without invoking host orchestration. Busy results remain structured and retryable without deleting live locks. Native instructions/routines remain pending until observed in the actual harness.
- `src/core/backup/archive.ts` + `src/core/backup/snapshot.ts` — Private bounded full-PGLite snapshots with file inventories, checksums, credential-reference exclusions and fresh-root restoration. Hold the database lock, detect changing inventories, validate private staging before publication, rebase managed paths, detach external roots, and quarantine nonterminal restored jobs without deleting spending evidence. Never replace the source installation.
- `src/core/harness/registry.ts` — Canonical adapter identities, supported transports, credential-delivery mechanisms, guide links and dated evidence; legacy connection/register vocabularies derive their facts here. `scripts/build-harness-docs.ts` emits the user-facing adapter reference.
- `src/core/harness/credentials.ts` + `delivery.ts` + `install.ts` — Private credential handoff and host delivery journal, ownership-preserving native configuration and isolated thin launchers. A committed active client and matching current secret are prerequisites for recovery. Configuration removal and server revocation are separate actions.
- `src/core/harness/capabilities.ts` + `src/mcp/capabilities.ts` — Shared effective-grant orientation for OAuth whoami and authenticated `gbrain://capabilities`. The resource preserves the exact seven-tool surface; source, operation, scope, fence and server-gate restrictions remain enforced at dispatch. No worker probe or per-tool database query during discovery.
- `src/core/harness/verify.ts` — Randomized server-side memory verification with separate transport, identity, authority, read, write/readback, delegation and cleanup verdicts. Lost mutation responses are reconciled before retry; server success never certifies native-harness activation or cross-conversation behavior.
- `src/commands/mcp.ts` + `mcp-provision.ts` + `harness-connect.ts` — Host-side grant/preview/CAS and recoverable private delivery, followed by installation inside the intended harness. Running PGLite hosts are administered through their authenticated API, never by opening a second database process. CLI status uses the delivery-aware exit verdict.
+
+- `src/core/facts/backstop.ts` + `src/core/entities/resolve-on-save.ts` — saved facts retain their content and provenance but use a NULL entity target when resolution falls back to slugification. The conversation save caller also clears the target on ordinary resolution errors, preserves diagnostic counters, and propagates abort/budget failures. It never treats an invented slug as a verified page.
+- `src/commands/migrations/v0_32_2.ts` — fences live legacy facts only onto an existing source-scoped page and its recorded canonical file. Missing pages/files are counted as `skipped_no_page`, never materialized as stubs. Dirty-tree checks stay inside the source subdirectory; fence row allocation respects both database-owned row numbers and the parsed fence, preserving idempotent recovery without collisions. Dry runs use the same eligibility checks, and historical drift remains visible rather than silently repaired.
diff --git a/docs/architecture/schema-packs.md b/docs/architecture/schema-packs.md
index fff2402466..702b1752d4 100644
--- a/docs/architecture/schema-packs.md
+++ b/docs/architecture/schema-packs.md
@@ -56,6 +56,11 @@ gbrain schema validate # validate a manifest's shape
gbrain schema use <pack> # activate a pack (writes ~/.gbrain/config.json)
```
+`gbrain config set schema_pack <pack>` sets the brain-wide database override,
+which takes precedence over the file setting written by `gbrain schema use`.
+Use `gbrain config unset schema_pack` to remove that database override, then
+`gbrain schema active` to confirm the resolved pack and its selection tier.
+
Authoring + discovery verbs:
```bash
diff --git a/docs/architecture/system-of-record.md b/docs/architecture/system-of-record.md
index d12b0c1d6c..5a93431da5 100644
--- a/docs/architecture/system-of-record.md
+++ b/docs/architecture/system-of-record.md
@@ -1,8 +1,8 @@
# System of record
-**The GitHub repo (markdown + frontmatter) is the system of record.
-The Postgres/PGLite database is a derived cache. We do not back up
-the database — we rebuild it from the repo.**
+**Canonical Markdown and frontmatter are the system of record for file-backed
+knowledge. Their database indexes can be rebuilt from those files. DB-only
+knowledge and operational state still need a separate backup.**
This document is the canonical reference for that contract. Every code
path that writes user-knowledge state should match the pattern
@@ -13,22 +13,23 @@ enforces it programmatically.
The DB is a derived index over the markdown content. It exists to make
search fast, to dedup embedding-similar claims, to materialize the
-cross-page graph. None of that data is irreplaceable — as long as the
-markdown is intact, `gbrain sync && gbrain extract all` rebuilds the
-entire DB from scratch.
+cross-page graph. `gbrain sync && gbrain extract all` rebuilds the indexes
+represented by intact Markdown; it does not recover DB-only knowledge,
+credentials, or page revision history.
This means:
- **Disaster recovery is a short, boring sequence.** If your DB volume
corrupts, if Postgres eats itself, if PGLite's WASM lock wedges — you
- don't need a backup. You wipe the derived tables (on PGLite,
+ first verify your backups and which state exists only in the database.
+ After preserving that state, you can wipe derived tables (on PGLite,
`gbrain reinit-pglite` wipes the whole embedded DB), re-import from
your brain repo with `gbrain sync`, and `gbrain extract all`
regenerates the derived state. See "Disaster recovery" below for the
exact commands.
- **Multi-machine sync is git.** Your brain is a repo. Push from one
machine, pull from another, and the second machine's DB rebuilds on
- its next sync. No "back up the database" step.
+ its next sync. This does not transfer DB-only state or gitignored files.
- **Privacy is in your hands.** Sensitive entity pages can be
gitignored (via `gbrain.yml` `db_only` paths or per-page) and they
stay on disk but not in git. The fence respects whatever git
@@ -39,16 +40,16 @@ This means:
## The three categories
-Every table in the gbrain schema belongs to exactly one of three
-categories. The category determines how it gets rebuilt during
-disaster recovery.
+Use these categories to distinguish reconstructible file-backed records
+from state that needs a database backup. A table can contain both: the
+facts table, for example, also holds unresolved facts without a fence.
### FS-canonical (markdown is the source of truth)
-These are user-authored knowledge. The DB row is a derived index over
-the markdown — wipe the table and `gbrain extract` rebuilds it
-identically. The CI gate keeps direct DB writes from drifting away
-from the markdown contract.
+For knowledge preserved in canonical files, the DB row is a derived index
+over the Markdown. Reconciliation rebuilds the represented fields; it does
+not promise identical database rows or recover records absent from the files.
+The CI gate constrains direct DB writes to the documented paths.
| Category | How it's stored in markdown | Derived DB table | Reconciler |
|---|---|---|---|
@@ -74,9 +75,9 @@ chunker + embedder rebuild these on import.
### DB-only by design (named exceptions)
-These hold runtime / infrastructure state that's intentionally not in
-the repo. The architectural rule still holds — these aren't
-"user knowledge" — but they're DB-only by design.
+These hold runtime or infrastructure state intentionally kept outside the
+repo. This list does not cover every DB-only record: pages and facts can
+also contain knowledge absent from canonical files and must be backed up.
| Category | Why it's OK to be DB-only |
|---|---|
@@ -97,6 +98,31 @@ question is: does it belong in this DB-only-by-design list? If not,
it's FS-canonical and needs a fence (or frontmatter field) plus a
reconciler.
+## Page-write persistence boundary
+
+For a file-backed `put_page`, the root worktree lock is acquired before importing
+the revision. If that acquisition times out, `storage_busy` means the write was
+not applied and was not queued. Canonical Markdown is staged with fsync and
+renamed inside the import's database transaction, after required source-path
+bookkeeping. Ordinary filesystem rejection rolls back the imported page, tags,
+chunks, and version snapshot.
+
+This is not a distributed transaction between the filesystem and database. A
+crash or database COMMIT failure after rename can leave the Markdown ahead of
+the index. It is also not a durable write queue or a caller-supplied revision
+precondition. The page operation releases its own worktree lock before optional
+embedding, so a slow provider does not block other writes to the same worktree.
+Embedding is page-scoped, rejects superseded page/chunk generations, and reports
+failure separately without undoing a saved page or exposing provider exception
+text. A lock owned by a surrounding caller remains that caller's responsibility.
+
+The rebuild contract above applies only to knowledge actually preserved in
+canonical files. DB-only pages, unresolved facts not written to a fence, audit
+history, and site-local credentials are not recoverable from Markdown alone.
+Keep an appropriate database backup before any destructive recovery, and do
+not delete historical unmatched facts or generate empty pages to make them
+appear file-backed.
+
## The privacy boundary
Private knowledge in a fence still lives in the markdown file. If the
@@ -143,10 +169,15 @@ remove the row. The next `extract_facts` cycle wipes the DB row.
## Disaster recovery
-The promise the rule makes:
+This example is only for a database whose affected facts, takes, links and
+timeline entries have been verified to exist in canonical files. Before running
+the destructive commands, stop writers and verify a restorable database backup
+plus source-file backups. Do not use this recipe on unresolved DB-only facts or
+assume a repository backup covers gitignored files.
```bash
-# Snapshot what's there
+# File-backed state only: verify restorable DB + source backups before proceeding.
+# Record counts for comparison; this is not a backup.
gbrain stats > /tmp/before.txt
# Wipe and rebuild — delete the derived tables (pages + content_chunks
@@ -156,13 +187,14 @@ psql -c 'DELETE FROM facts; DELETE FROM takes; DELETE FROM links; DELETE FROM ti
gbrain sync
gbrain extract all
-# Counts match
+# Compare file-backed counts and investigate differences; full DB parity is not promised.
gbrain stats > /tmp/after.txt
diff /tmp/before.txt /tmp/after.txt
```
The invariant E2E test at `test/e2e/system-of-record-invariant.test.ts`
-exercises this exact flow on every CI run.
+proves reconstruction of its file-backed facts/takes fixture. It does not prove
+recovery of DB-only knowledge, operational state, or every production database.
## Rule for new code
diff --git a/docs/architecture/thin-client.md b/docs/architecture/thin-client.md
index 36ea369c09..bf30097d8c 100644
--- a/docs/architecture/thin-client.md
+++ b/docs/architecture/thin-client.md
@@ -10,6 +10,13 @@ empty local PGLite, so a populated remote brain can't silently return
"No results." Local-only commands refuse with a pinpoint hint instead of
falling through.
+Installed thin-client launchers clear inherited brain and source overrides without
+adding `--brain host` or pinning the grant's write source onto reads. Unqualified
+reads use the host grant's readable sources; explicit `--source` remains subject
+to host authorization. Local PGLite launchers retain their host/source binding.
+The generic `gbrain call` dispatcher is host-only and refuses before opening a
+local engine; use the named CLI command or an authorized MCP tool instead.
+
**Surface posture:** thin CLI clients use the full MCP surface for remote
command compatibility. Bootstrap pins `--surface full`; managed thin CLI grants
for OpenClaw, Grok Bot, and Muse also select `full`. Surface visibility does not
@@ -17,6 +24,13 @@ grant authority: profiles, token scopes, operation snapshots, sources, and write
fences still restrict requests. A `memory-writer` thin client gains neither
administration nor delegation from its full surface.
+OAuth bootstrap challenges advertise `scope="read"` without enforcing it as a
+literal transport requirement. Existing writer, administrator, and delegated
+tokens keep their granted authority. New generic connections following the
+hint start read-only; writing requires an explicit authorized scope request.
+Discovery excludes `agent`, which DCR cannot grant, while explicit DCR requests
+for delegation remain rejected.
+
Keep general-purpose thin-client OAuth rows at `full` (or NULL). Native MCP
configurations can deliberately use starter/verbs to expose fewer tools. Stdio
serves the server-resolved surface directly, without a client row; per-client
diff --git a/docs/embedding-migrations.md b/docs/embedding-migrations.md
index 8b1a8f6072..de471a0512 100644
--- a/docs/embedding-migrations.md
+++ b/docs/embedding-migrations.md
@@ -30,11 +30,14 @@ is needed. gbrain stamps an embedding-provenance
signature (`<provider:model>:<dims>`) onto each page when its chunks are
embedded. After you point the config at the new model, the stored
signatures differ from the current one, and `gbrain embed --stale`
-re-embeds exactly those pages:
+revisits those pages. Chunks already matching the target model, current text
+hash, and vector width keep their embeddings. A fully current page can have
+its signature restamped without another provider call; interrupted batches
+do not discard completed current vectors.
```bash
# After switching to the new same-dim model in your config:
-gbrain embed --stale # re-embeds signature-drifted pages
+gbrain embed --stale # embeds stale chunks; preserves current vectors
gbrain embed --stale --dry-run # preview the count without re-embedding
```
diff --git a/docs/guides/sub-agent-routing.md b/docs/guides/sub-agent-routing.md
index 27eb3c34ba..f8cab6b1a0 100644
--- a/docs/guides/sub-agent-routing.md
+++ b/docs/guides/sub-agent-routing.md
@@ -7,8 +7,8 @@ multiples on cost without sacrificing quality.
## What the User Gets
-Without this: every sub-agent runs on your most expensive model. Entity
-detection fires on every message at top-tier rates; research tasks cost
+Without this: every sub-agent runs on your most expensive model. Consented
+entity detection runs at top-tier rates; research tasks cost
several dollars each.
With this: entity detection runs on a cheap fast model, research execution
@@ -51,10 +51,17 @@ routing policy; this guide is the cost rationale behind it.
### The Signal Detector Pattern
-Spawn a lightweight sub-agent on EVERY inbound message. This is mandatory.
+Automatic capture is off by default. Only after the user opts in, spawn a
+lightweight signal detector for inbound messages covered by that consent.
+Ordinary recall and explicit requests to remember do not require this detector.
+Paid enrichment and delegation require their own authority.
```
on_every_message(text):
+ if not automatic_capture_opted_in or chat_only(text):
+ return
+ if not authorized_delegation:
+ return
// Spawn async — don't block the response
spawn_subagent({
task: `SIGNAL DETECTION — scan this message:
@@ -63,7 +70,7 @@ on_every_message(text):
1. IDEAS FIRST: Is the user expressing an original thought?
If yes -> create/update brain/originals/ with EXACT phrasing
2. ENTITIES: Extract person names, company names, media titles
- For each -> check brain, create/enrich if notable
+ For each -> check brain; enrich only with separate authorization
3. FACTS: New info about existing entities -> update timeline
4. CITATIONS: Every fact needs [Source: ...] attribution
5. Sync changes to brain repo`,
@@ -97,7 +104,7 @@ budget-model cost for 80% of the work.
| Situation | Spawn? | Model |
|-----------|--------|-------|
-| Every inbound message | YES (mandatory) | Sonnet |
+| Inbound message covered by automatic-capture consent | Only after opt-in | Sonnet |
| Research request | YES | DeepSeek for execution |
| Quick lookup / fact check | YES | Fast model (Groq) |
| Complex analysis | NO -- handle in main session | Opus |
@@ -123,8 +130,8 @@ fraction of the main session model's cost.
message while entity detection completes. Spawn and forget. The user sees
a response immediately.
-3. **Cost optimization is multiplicative.** Entity detection runs on every
- single message, so the per-call price difference compounds across 50+
+3. **Cost optimization is multiplicative.** After capture opt-in, entity
+ detection on covered messages can compound the per-call price across 50+
messages/day. Routing detection from Opus-class ($5/MTok in) to
Haiku-class ($1/MTok in) is a flat 5x cut on your highest-frequency LLM
call — over a month, the wrong model choice for detection alone costs
@@ -132,7 +139,7 @@ fraction of the main session model's cost.
## How to Verify
-1. **Spawn a signal detector and check the model.** Send a message and verify
+1. **After capture opt-in, check the detector's model.** Send a covered message and verify
the sub-agent was spawned on Sonnet-class, not Opus. Check the model field
in the sub-agent config or logs.
diff --git a/docs/mcp/CHATGPT.md b/docs/mcp/CHATGPT.md
index d983aaadd7..97b7c32037 100644
--- a/docs/mcp/CHATGPT.md
+++ b/docs/mcp/CHATGPT.md
@@ -74,6 +74,19 @@ surface area.
Recommended ChatGPT scope: `read write`. Leave `admin` for your local CLI
and the admin dashboard.
+The initial MCP authentication challenge requests only `read`. Clients that
+follow that hint bootstrap with read access, even when their registration
+allows `read write`; registration is a ceiling, not automatic authorization
+for every listed scope. Saving requires the client to explicitly request
+`write` and the operator to approve it. Existing authorized writer sessions
+keep their permissions.
+
+OAuth discovery omits the operator-only `agent` scope so clients that register
+using advertised scopes do not request unsupported delegation. Explicit DCR
+requests for `agent` still fail; delegation requires a separately approved
+host grant. The server's SDK/HTTP tests cover these flows, not a live ChatGPT
+or Claude connector session.
+
## Deep research
ChatGPT's **deep research** mode has a stricter MCP contract than normal
diff --git a/llms-full.txt b/llms-full.txt
index 912fa0ecf2..0a23ab87af 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -914,9 +914,10 @@ writing or reviewing an operation, consult `src/core/operations.ts` for the cont
- **Drive the brain to a target health score:** the one-command
loop. `gbrain doctor --remediation-plan --json` previews what would be
fixed; `gbrain doctor --remediate --yes --target-score 90 --max-usd 5`
- walks a dependency-ordered plan (sync before extract, embed after
- consolidate), re-checking score between every step, refusing to spend
- past the cost cap. Empty brains (no entity pages) or unconfigured embedding
+ walks a dependency-ordered plan, re-checking score between every step and
+ refusing to spend past the cost cap. Stale extraction uses source-scoped
+ database pages, including DB-only pages; it does not require a repository
+ sync first. Empty brains (no entity pages) or unconfigured embedding
keys hit a `max_reachable_score` ceiling and bail with what's missing.
Three phase handlers (synthesize / patterns / consolidate) are
PROTECTED — only trusted local callers can submit them; MCP cannot.
@@ -2921,7 +2922,7 @@ echo "from a pipe" | gbrain capture --stdin
SLUG=$(gbrain capture "..." --quiet)
```
-The page lands in the database and on disk in one move. Default slug `inbox/YYYY-MM-DD-<hash8>` so captures cluster in a predictable triage location. On thin-client installs the verb routes through MCP to the server: same command, same UX.
+For a file-backed source, the page is saved to the database and canonical Markdown before optional embedding. Ordinary file-write failures roll back the database revision; this is not a crash-atomic transaction across files and the database. A source without a configured repository can hold DB-only pages, which need a database backup. See the [persistence boundary](docs/architecture/system-of-record.md#page-write-persistence-boundary). Default slug `inbox/YYYY-MM-DD-<hash8>` so captures cluster in a predictable triage location. On thin-client installs the verb routes through MCP to the server.
**Say to your agent:** *"Remember this: ..."* — *"Save this thought to my brain"* — *"Capture this."* And to fill an empty brain from your existing life: *"Fill my brain"* (the cold-start skill walks your email, calendar, contacts, and archives one consented step at a time).
@@ -3051,7 +3052,7 @@ Want to see a tutorial that isn't here yet? [Open an issue](https://github.com/g
- **Signal detector**, after you opt in, captures durable ideas and entity mentions from substantive messages. Explicit remembering works without automatic capture; paid enrichment is a separate choice.
- **Brain-first lookup** before any external API call. The cheapest, fastest, most personal information source you have.
-- **Auto-link** fires on every page write. No LLM calls; pure pattern matching on `[[wiki/people/bob]]` style references. New entity → new page stub → graph grows.
+- **Auto-link** extracts graph links for trusted local page writes. No LLM calls; pure pattern matching on page references such as `[[people/alice-example]]`. Unresolved extracted facts keep their provenance without inventing a backing page.
- **Cron-driven enrichment** runs while you sleep: dedup people pages, fix citations, score salience, find contradictions, prep tomorrow's tasks.
The whole loop is described in [`docs/architecture/topologies.md`](docs/architecture/topologies.md) with diagrams.
@@ -3186,7 +3187,7 @@ flowchart LR
**Two engines, one contract.** PGLite (Postgres 17 via WASM, zero-config, default) for personal brains up to ~50K pages. Postgres + pgvector (Supabase or self-hosted) for shared / large / multi-machine deployments. The contract-first `BrainEngine` interface in [`src/core/engine.ts`](src/core/engine.ts) defines the 140+ methods both engines implement; CLI and MCP server are generated from one source.
-**Brain repo is the system of record.** Your knowledge lives in a regular git repo (your "brain repo") as markdown files. GBrain syncs the repo into Postgres for retrieval; deletes in git become soft-deletes in DB. You can publish public subsets, share team mounts, run thin-client setups pointing at a colleague's brain server. Topologies in [`docs/architecture/topologies.md`](docs/architecture/topologies.md).
+**Canonical files preserve file-backed knowledge.** Your brain repo holds Markdown that GBrain indexes for retrieval; deletes in git become soft-deletes in the database. DB-only pages, unresolved facts, revision history, and operational state need a separate database backup. See the [system-of-record contract](docs/architecture/system-of-record.md). You can publish public subsets, share team mounts, and run thin-client setups pointing at a colleague's brain server. Topologies in [`docs/architecture/topologies.md`](docs/architecture/topologies.md).
**Two organizational axes (brain ⊥ source).** A *brain* is a database (your personal brain, a team mount you joined). A *source* is a repo inside that brain (wiki, gstack, an essay, a knowledge base). Routing lives in `.gbrain-source` dotfiles and resolves via a documented 6-tier precedence chain. Full diagrams in [`docs/architecture/brains-and-sources.md`](docs/architecture/brains-and-sources.md).
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index ca10f5bf55..1159932c51 100644
--- a/openclaw.plugin.json
+++ b/openclaw.plugin.json
@@ -1,7 +1,7 @@
{
"id": "gbrain-context-engine",
"name": "gbrain",
- "version": "0.50.1.0",
+ "version": "0.50.2.0",
"description": "Personal knowledge brain with Postgres + pgvector hybrid search",
"family": "bundle-plugin",
"configSchema": {
diff --git a/package.json b/package.json
index 9061677602..7e141680ff 100644
--- a/package.json
+++ b/package.json
@@ -174,7 +174,7 @@
"bun": ">=1.3.11"
},
"license": "MIT",
- "version": "0.50.1.0",
+ "version": "0.50.2.0",
"overrides": {
"@ai-sdk/provider-utils": "4.0.33",
"@hono/node-server": "^2.0.5",
diff --git a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json
index 433d6db3fb..563a69c950 100644
--- a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json
+++ b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain-coding",
- "version": "0.50.1.0",
+ "version": "0.50.2.0",
"description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 20 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json
index 10282cfe0b..3db97b05f0 100644
--- a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json
+++ b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain-coding",
- "version": "0.50.1.0",
+ "version": "0.50.2.0",
"description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 20 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-coding/README.md b/plugin-variants/gbrain-coding/README.md
index 505be6c2aa..ef469a5b65 100644
--- a/plugin-variants/gbrain-coding/README.md
+++ b/plugin-variants/gbrain-coding/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.50.1.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.50.2.0 -->
# gbrain-coding (generated persona variant — do not hand-edit)
Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant.
diff --git a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
index e4cf5439c6..f350c1f86c 100644
--- a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
+++ b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain-daily",
- "version": "0.50.1.0",
+ "version": "0.50.2.0",
"description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 19 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json
index 94fe2c7ac1..a50d1e6813 100644
--- a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json
+++ b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain-daily",
- "version": "0.50.1.0",
+ "version": "0.50.2.0",
"description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 19 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-daily/README.md b/plugin-variants/gbrain-daily/README.md
index cbab857c08..9866c61b44 100644
--- a/plugin-variants/gbrain-daily/README.md
+++ b/plugin-variants/gbrain-daily/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.50.1.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.50.2.0 -->
# gbrain-daily (generated persona variant — do not hand-edit)
Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant.
diff --git a/plugin/README.md b/plugin/README.md
index 3cedcc2e59..2941f91505 100644
--- a/plugin/README.md
+++ b/plugin/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.50.1.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.50.2.0 -->
# gbrain plugin skill tree (generated — do not hand-edit)
This tree is the curated skill set for the gbrain Codex and Claude Code
diff --git a/scripts/check-wasm-embedded.sh b/scripts/check-wasm-embedded.sh
index 67ff9e2aa0..fdeafd10d5 100755
--- a/scripts/check-wasm-embedded.sh
+++ b/scripts/check-wasm-embedded.sh
@@ -76,4 +76,10 @@ if [[ "$OUTPUT" != *'"calculateScore"'* ]]; then
exit 1
fi
+if [[ "$OUTPUT" != *'"has_bash_case_symbol": true'* ]]; then
+ echo "[check-wasm-embedded] FAIL: Bash case statement lost its function symbol." >&2
+ echo "$OUTPUT" >&2
+ exit 1
+fi
+
echo "[check-wasm-embedded] OK — compiled binary produced real semantic chunks."
diff --git a/scripts/chunker-smoketest.ts b/scripts/chunker-smoketest.ts
index 68c06304ff..b7eb426b2b 100644
--- a/scripts/chunker-smoketest.ts
+++ b/scripts/chunker-smoketest.ts
@@ -42,10 +42,18 @@ export type UserId = string;
const result = await chunkCodeText(src, 'smoketest.ts');
const hasSymbolNames = result.some(c => c.metadata.symbolName !== null);
const hasTypeScriptHeader = result.some(c => c.text.startsWith('[TypeScript]'));
+const bash = await chunkCodeText(`dispatch() {
+ case "$1" in
+ start|stop) printf '%s\\n' "$1" ;;
+ *) printf '%s\\n' 'unknown command' ;;
+ esac
+}
+`, 'smoketest.sh');
console.log(JSON.stringify({
count: result.length,
has_symbol_names: hasSymbolNames,
has_typescript_header: hasTypeScriptHeader,
first_header: result[0]?.text.split('\n')[0],
symbol_names: result.map(c => c.metadata.symbolName),
+ has_bash_case_symbol: bash.some(c => c.metadata.symbolName === 'dispatch' && c.text.includes('case "$1" in')),
}, null, 2));
diff --git a/scripts/e2e-test-map.ts b/scripts/e2e-test-map.ts
index e986907d3f..fe16278153 100644
--- a/scripts/e2e-test-map.ts
+++ b/scripts/e2e-test-map.ts
@@ -44,7 +44,7 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
// Concrete content and derived-information read policy parity.
"src/core/remote-body.ts": ["test/e2e/engine-content-privacy.test.ts", "test/e2e/remote-privacy-journeys.test.ts", "test/e2e/legacy-chunk-privacy.test.ts", "test/e2e/chunk-canonical-text-privacy.test.ts"],
"src/core/entity-identity.ts": ["test/e2e/engine-content-privacy.test.ts", "test/e2e/remote-privacy-journeys.test.ts"],
- "src/core/ops/**": ["test/e2e/engine-content-privacy.test.ts", "test/e2e/remote-privacy-journeys.test.ts", "test/e2e/read-enrichment-privacy.test.ts", "test/e2e/legacy-chunk-privacy.test.ts", "test/e2e/chunk-canonical-text-privacy.test.ts"],
+ "src/core/ops/**": ["test/e2e/engine-content-privacy.test.ts", "test/e2e/remote-privacy-journeys.test.ts", "test/e2e/read-enrichment-privacy.test.ts", "test/e2e/legacy-chunk-privacy.test.ts", "test/e2e/chunk-canonical-text-privacy.test.ts", "test/e2e/put-page-persistence-postgres.test.ts"],
"src/commands/whoknows.ts": ["test/e2e/read-enrichment-privacy.test.ts"],
"src/commands/orphans.ts": ["test/e2e/engine-content-privacy.test.ts", "test/e2e/remote-privacy-journeys.test.ts"],
// Source-aware ranking, hybrid search, intent classification.
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 052fc48299..726e313fd9 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -3,13 +3,13 @@
# Raising a ceiling is a conscious, reviewer-visible act. Lower ceilings in
# the same commit as any peel (the guard fails on >50 lines of stale slack).
# Columns: path max_lines policy note
-src/cli.ts 4087 ratchet +48 fix wave: get_versions --json + honest ellipsis (#4692), boolean-flag literal true/false consume (#4602); grown v0.46.26.0 megawave: SIGCHLD reaper install, silent-failure surfacing, confirm-race gate (#2443 #2898 #2297); grown wave-g (#4488 #4508): in-band error exit codes + think --source validation; grown db-availability loop: engine/db-repair dispatch, degraded-serve catch, marker choke points (bottom handler + no-config exit + doctor fallback), engine-free config-set dispatch; fix cycle: static classifier imports, resolved-brain degraded gate, guarded reconnect, help rows; +chat-connectors wiring (master merge); wave-k +24 for #4083 auth self-help entry + top-level auth usage lines + takes self-help branch; +master-merge true-up; +20 gbrain backup pre-engine dispatch + startup backup nag rail (monthly backup check); wave-k: +24 for #4083 auth self-help entry + top-level auth usage lines + takes self-help branch; +3: doctor --no-migrate probeOnly seam (#4364); +37 v0.47 gmail-loops: google/creds dispatch + waiting/loops cases + self-help entries + OPEN LOOPS help section; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: CLI combines hosted access and explicit legacy queue review
+src/cli.ts 4088 ratchet +48 fix wave: get_versions --json + honest ellipsis (#4692), boolean-flag literal true/false consume (#4602); grown v0.46.26.0 megawave: SIGCHLD reaper install, silent-failure surfacing, confirm-race gate (#2443 #2898 #2297); grown wave-g (#4488 #4508): in-band error exit codes + think --source validation; grown db-availability loop: engine/db-repair dispatch, degraded-serve catch, marker choke points (bottom handler + no-config exit + doctor fallback), engine-free config-set dispatch; fix cycle: static classifier imports, resolved-brain degraded gate, guarded reconnect, help rows; +chat-connectors wiring (master merge); wave-k +24 for #4083 auth self-help entry + top-level auth usage lines + takes self-help branch; +master-merge true-up; +20 gbrain backup pre-engine dispatch + startup backup nag rail (monthly backup check); wave-k: +24 for #4083 auth self-help entry + top-level auth usage lines + takes self-help branch; +3: doctor --no-migrate probeOnly seam (#4364); +37 v0.47 gmail-loops: google/creds dispatch + waiting/loops cases + self-help entries + OPEN LOOPS help section; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: CLI combines hosted access and explicit legacy queue review; +1 host-only call refusal hint (#5102)
src/commands/autopilot.ts 2671 ratchet grown v0.46.26.0 megawave (#4300 #4285 #3696) + master v0.46.27.0 env-file lane + boot warning + reload-safe install (#2608 #4443) + 1 nosemgrep dataflow annotation (path-traversal audit); +chat-connectors wiring; +20 #4728 wrapper exec guard (baked CLI path gone -> PATH fallback / --install hint); +5 #4952 (refs #4399): syncEnabled=false skip in the freshness dispatch loop
src/commands/doctor.ts 4641 ratchet grown v0.46.26.0 megawave: silent-death checks, self-upgrade honesty, noise pruning (#3944 #3925 #3958); +21 lines (#4518: don't assert "supervisor not running" when the --fast mode DB-lock fallback was never attempted); +12 lines (#2036/#4484: schema_version warns on forward DB skew); +12 lines (#4476: oversized_pages excludes embed_skip pages via canonical EMBED_SKIP_FILTER_FRAGMENT); merged wave-g-prs (#4421 #4425 #4517 #4519): one in-branch live-column diff on detectMissingColumns + engine-aware superseded upgrade-error suppression (explicit ok); grown db-availability loop: classified connection check + synthesized total-outage entry + hoisted pgbouncer helper + engine-fit check wiring + report engine/db_url_source fields; +chat-connectors wiring (master merge); +12 lines (#2036/#4484: schema_version warns on forward DB skew via schemaVersionHealth); merged wave-g-prs (#4421 #4425 #4517 #4519): in-branch live-column diff + engine-aware superseded upgrade-error suppression; wave-k: schema_columns emitted as its own check inside the ledger-current branch (gbrain#4421), schema_version via schemaVersionHealth module, conversation_format_coverage peeled to doctor/checks/conversation-coverage.ts (#4193); +7 backup_coverage check registration (monthly backup check); +master-merge true-up; wave-k: schema_columns emitted as its own check inside the ledger-current branch (gbrain#4421), schema_version via schemaVersionHealth module, conversation_format_coverage peeled to doctor/checks/conversation-coverage.ts (#4193); +9 v0.47 gmail-loops: google_oauth vault-health check dispatch; +17 (#4712: git-root-pinned source skip note wiring + all-skipped warn-not-ok status for multi_source_drift); +8 memorable_relay_health wiring (check itself is a peel: doctor/checks/integrations-memorable.ts); +9 ambient-writeback WP6: memory_writeback check registration (logic lives in doctor/checks/memory-writeback.ts); +14 default_source_local_path registration (#4739 — check body peeled to doctor/checks/default-source-path.ts); +9 atom_provenance_drift registration (#4566 — check body lives in doctor/checks/extraction-sync.ts); master: | merged v0.48.1.0 true-up
src/commands/embed.ts 2147 ratchet lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment)
src/commands/extract-conversation-facts.ts 2105 ratchet grown v0.46.x per-provider gateway-unavailable copy; grown wave-g (#4482): expected budget/deadline caps classified apart from error halts; wave-k: save-time resolution caller (#4052/#3729 — supersedes wave-g's per-row resolveEntitySlug mapper); +1: key-aware llm-fallback default (#3813); +1: pricingOverrides wiring into the owned BudgetTracker (#4633 adoption); +3: #4869 snapshot-mismatch counts as pages_failed
src/commands/extract.ts 2643 ratchet grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges
-src/commands/jobs.ts 3177 ratchet +3 #4786 x #2139 pre-landing: sync handler gates embed-backfill on syncProducedEmbeddableContent (no_new_content skip reason); grown v0.46.26.0 megawave (#4098 #2308) + master v0.46.26.0 worker startup recovery + stats gating; +typed provider-failure logging on the facts-absorb catch (#4308); +chat-connectors wiring (master merge); +16 v0.47 gmail-loops: loops_extract handler + gateway-refresh entry; +8 refs #4599: embed + embed-catch-up handlers fail the job on a stall_timeout result (assertEmbedNotStalled); security: durable queued authority and confined filesystem dispatch; drained cancellation and lease-safe partial results; queued import failures remain failures; master integration: grown v0.46.26.0 megawave (#4098 #2308) + master v0.46.26.0 worker startup recovery + stats gating; +typed provider-failure logging on the facts-absorb catch (#4308); +chat-connectors wiring (master merge); +16 v0.47 gmail-loops: loops_extract handler + gateway-refresh entry; +8 refs #4599: embed + embed-catch-up handlers fail the job on a stall_timeout result (assertEmbedNotStalled)
+src/commands/jobs.ts 3189 ratchet +3 #4786 x #2139 pre-landing: sync handler gates embed-backfill on syncProducedEmbeddableContent (no_new_content skip reason); grown v0.46.26.0 megawave (#4098 #2308) + master v0.46.26.0 worker startup recovery + stats gating; +typed provider-failure logging on the facts-absorb catch (#4308); +chat-connectors wiring (master merge); +16 v0.47 gmail-loops: loops_extract handler + gateway-refresh entry; +8 refs #4599: embed + embed-catch-up handlers fail the job on a stall_timeout result (assertEmbedNotStalled); security: durable queued authority and confined filesystem dispatch; drained cancellation and lease-safe partial results; queued import failures remain failures; master integration: grown v0.46.26.0 megawave (#4098 #2308) + master v0.46.26.0 worker startup recovery + stats gating; +typed provider-failure logging on the facts-absorb catch (#4308); +chat-connectors wiring (master merge); +16 v0.47 gmail-loops: loops_extract handler + gateway-refresh entry; +8 refs #4599: embed + embed-catch-up handlers fail the job on a stall_timeout result (assertEmbedNotStalled); +12 global freshness excludes explicit incomplete children and deferred maintenance
src/commands/serve-http.ts 3382 ratchet lowered to the merged line count after master v0.50.0.0 shrank the file; +20 #4866: RFC 9728 PRM resource=/mcp + root-path alias rewrite; grown v0.46.25.0 D2: /mcp per-request teardown (#2844); grown wave-g (#4474): resolve-IPC socket under --http via shared helper; +15: metrics wiring — tracker mount + admin-gated /metrics route, helpers live in serve-http-metrics.ts (#3893); +7 test-gap wave C6: adminAuthRateLimiter on admin login + magic-link issuance, 429 JSON envelope; +29 ambient-writeback: per-request buildMcpInstructions (writeback bundle + write-scope gate + allowed-ops extract_facts probe); +6 adversarial fix wave: remember-op bound-client fence probe gates the ambient section; +2 #4748: startup resolveMcpInstructions (deployment identity) threaded into the per-request MCP server | merged v0.48.1.0: master #4788 writeback resolve + wave #4748 identity; master: | merged v0.48.1.0 true-up; +40 #4955: trackServerSockets() holds accepted sockets via WeakRef — Bun never emits socket close on server-side sockets, so the strong Set retained one socket per connection forever; +19 pre-landing review: bounded close() backstop in waitForHttpServerLifecycle (WeakRef-collected keep-alive wrappers leave native handles close() waits on); +10 pre-landing review r2: a close() error landing after the deadline is logged, not dropped
src/core/ai/gateway.ts 4914 ratchet +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback)
src/commands/sync.ts 5967 ratchet +1 #4786/#3068 pre-landing: pullFailed early return reports the sweep count (comment line); +1 #4786 x #2139 pre-landing: both embed-backfill submit gates require syncProducedEmbeddableContent (import line); re-summed after merging master v0.50.0.0 with the wave (include_hidden, sweep count, cost-gate envelope); +1 wave review: sync trigger --json emits {job_id} JSON; grown v0.46.26.0 megawave: image sync, ingest-log gating, dry-run purity, checkpoint honesty (#2683 #4342 #3875) + 3 nosemgrep dataflow annotations (path-traversal audit); +#2683 residual: status-error failure recording at both import sites; +143 wave G #3974: working-tree drift surfacing + opt-in --working-tree import; grown wave-g (#4412 #4543): break-lock ambient source resolution + named failing files; grown db-availability loop: GBRAIN_DB_ACCESS marker on checkpoint-dead aborts; fix cycle: marker via shared DB_ACCESS_MARKER_PREFIX + shouldEmitDbAccessMarker; wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +master-merge true-up; +25 post-sync backup-coverage stale-only refresh (monthly backup check); wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +1: #4412 refinement — explicit --source stays resolver-free (deleted-source locks breakable); +10 v0.47 gmail-loops: google source-kind dispatch branch; +48 #4667 adoption: persisted sync.exclude config union hoisted above the performFullSync early returns; +22 #4587: all 7 delete lanes swapped to softDeletePages (72h recovery window), decompose comments + summary wording; +16 #4583: seed_default write refusal on bulk-non-default brains (assessDefaultWriteGuard call site + escape-hatch comment); composition true-up (fix-wave multi-train); +33 #4597: trackedSlugIndex.anchorOnlyPaths (slug -> anchor paths that alone proved it) + the self-referential from-path rule in slugLiveness so a fallback rename's own pre-rename duplicate converges under incremental sync; +12 #4888: runSync wraps runSyncInner in withHumanLogsToStderr under --json (stdout = JSON lines only) + help text; wave composition: #4903 stored-strategy honor + #4597 fallback-rename duplicate convergence + #4888 --json stdout purity summed; security: durable queued authority and confined filesystem dispatch; drained cancellation and lease-safe partial results; master integration: +1 wave review: sync trigger --json emits {job_id} JSON; grown v0.46.26.0 megawave: image sync, ingest-log gating, dry-run purity, checkpoint honesty (#2683 #4342 #3875) + 3 nosemgrep dataflow annotations (path-traversal audit); +#2683 residual: status-error failure recording at both import sites; +143 wave G #3974: working-tree drift surfacing + opt-in --working-tree import; grown wave-g (#4412 #4543): break-lock ambient source resolution + named failing files; grown db-availability loop: GBRAIN_DB_ACCESS marker on checkpoint-dead aborts; fix cycle: marker via shared DB_ACCESS_MARKER_PREFIX + shouldEmitDbAccessMarker; wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +master-merge true-up; +25 post-sync backup-coverage stale-only refresh (monthly backup check); wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +1: #4412 refinement — explicit --source stays resolver-free (deleted-source locks breakable); +10 v0.47 gmail-loops: google source-kind dispatch branch; +48 #4667 adoption: persisted sync.exclude config union hoisted above the performFullSync early returns; +22 #4587: all 7 delete lanes swapped to softDeletePages (72h recovery window), decompose comments + summary wording; +16 #4583: seed_default write refusal on bulk-non-default brains (assessDefaultWriteGuard call site + escape-hatch comment); composition true-up (fix-wave multi-train); +33 #4597: trackedSlugIndex.anchorOnlyPaths (slug -> anchor paths that alone proved it) + the self-referential from-path rule in slugLiveness so a fallback rename's own pre-rename duplicate converges under incremental sync; +12 #4888: runSync wraps runSyncInner in withHumanLogsToStderr under --json (stdout = JSON lines only) + help text; wave composition: #4903 stored-strategy honor + #4597 fallback-rename duplicate convergence + #4888 --json stdout purity summed
@@ -17,7 +17,7 @@ src/core/cycle.ts 3207 ratchet grown v0.46.26.0 megawave (#4102 #2608) + master
src/core/cycle/synthesize.ts 3216 ratchet merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance)
src/core/cycle/extract-atoms.ts 1742 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once
src/core/engine.ts 2645 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc
-src/core/import-file.ts 2278 ratchet +3 pre-landing review: refreshSourcePath short-circuits on the getPage-projected source_path (no per-unchanged-file UPDATE); re-summed to the merged line count after merging master v0.50.0.0 with the wave; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); +24 #4588: refreshSourcePath heals a drifted source_path on the import skip path
+src/core/import-file.ts 2332 ratchet +3 pre-landing review: refreshSourcePath short-circuits on the getPage-projected source_path (no per-unchanged-file UPDATE); re-summed to the merged line count after merging master v0.50.0.0 with the wave; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); +24 #4588: refreshSourcePath heals a drifted source_path on the import skip path; +48 transactional write-through and post-persistence embedding; +4 typed deferred completion lets page-owned locks release before enrichment; +2 verify the indexed revision before canonical publication
src/core/migrate.ts 712 region-exempt runner-region count re-summed after merging master v0.50.0.0 with the wave; append-only MIGRATIONS array grows freely; runner logic is ratcheted — grown v0.46.26.0: repair-handler hooks (#3957 pages-upsert-arbiter); wave-k v142 takes-embedding resize is in-region (renumbered from v141; master consumed v141 for #4482); +19 (#4613: links_link_source_check every-pass self-heal wiring, logic lives in link-source-check-repair.ts); +3 (#4613 pre-landing review: ledger gate >= v114 around the self-heal)
src/core/operations.ts 321 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS
src/core/pglite-engine.ts 6126 ratchet re-summed to the merged line count after merging master v0.50.0.0 with the wave; +6 #4881: ontology provenance-page visibility gate (getOntology/findOntologyConflicts); grown v0.46.26.0 megawave parity twins + master v0.46.26.0 private-queue columns; +#3754 traverseGraph soft-delete filters; grown wave-g (#4524 #4527): canonical islanded orphans + timestamp-preserving migrate; wave-k: +1 semantic takes retrieval delegate (#3776), +5 NUL-sanitize shared chunk_text local (#3998), +7 getAllConfig bulk read (#3980); +22: pre-close WAL CHECKPOINT in disconnect (#3893); +10: #4109 atomic link/timeline mutation + typed per-endpoint miss (parity); +1: getBacklinkCounts page-id keying comment (#4380); +14: dream-verdict TTL expiry predicate + sweep (#4069); +7 test-gap-wave merge true-up; +23: softDeletePages batch soft-delete primitive (#4587, parity twin); +51: #4592 source-scoped getStats/getHealth (bound $1 scope, both-endpoint link rule); +5 file-bytes snapshot hash (coverage-immune — CI shards were silently cold-initting); +7 2026-09 fix wave (#3617 follow-up): OR-fallback rows tagged keyword_relaxed in searchKeyword + title arm (fusion demotion reads it); cold-initting); +11: #4280 orphan/health served-memory denominators (quarantine + leaf-type metadata); composition true-up (fix-wave multi-train); +14: traversePathsDetailed row cap (LIMIT + truncated probe, parity twin); +7: resolveSlugWithAliasDetailed (owning source_id, parity twin) | merged v0.48.1.0 true-up; corrective release: shared batched enrichment peel; concrete content and Chronicle authorization; +2: #4681 listPages projects updated_at_iso (microsecond keyset cursor); master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: grant and authority schema bootstrap parity
@@ -36,7 +36,7 @@ src/core/embedding-migration.ts 1545 ratchet new row: crossed 1500 in v0.46.25.0
src/core/github-source.ts 1560 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment)
src/commands/hook.ts 1881 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking
src/core/chunkers/code.ts 1582 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES
-src/core/config.ts 1842 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown)
+src/core/config.ts 1843 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); +1 schema_pack key registration (#5104)
src/core/bootstrap/harness.ts 2443 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched)
src/core/oauth-provider.ts 1235 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies
src/core/ops/pages.ts 1484 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression
diff --git a/scripts/vendor-bash-wasm.sh b/scripts/vendor-bash-wasm.sh
new file mode 100644
index 0000000000..bdfe965f9d
--- /dev/null
+++ b/scripts/vendor-bash-wasm.sh
@@ -0,0 +1,14 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
+WORK="$(mktemp -d)"
+trap 'rm -rf "$WORK"' EXIT
+
+curl --fail --location --silent --show-error \
+ https://github.com/tree-sitter/tree-sitter-bash/releases/download/v0.23.3/tree-sitter-bash.wasm \
+ -o "$WORK/tree-sitter-bash.wasm"
+printf '%s %s\n' \
+ d1844429a58620f306b6f42aebe92298243ca8120cd833a3ab5d87c7a2e7b9fd \
+ "$WORK/tree-sitter-bash.wasm" | shasum -a 256 --check
+cp "$WORK/tree-sitter-bash.wasm" "$REPO_ROOT/src/assets/wasm/grammars/tree-sitter-bash.wasm"
diff --git a/skills/migrations/v0.32.2.md b/skills/migrations/v0.32.2.md
index 224d9fcbec..ee5c2e7423 100644
--- a/skills/migrations/v0.32.2.md
+++ b/skills/migrations/v0.32.2.md
@@ -2,7 +2,7 @@
version: 0.32.2
feature_pitch:
headline: "Facts join the system-of-record — your hot memory now lives in markdown"
- description: "v0.31 added hot-memory facts but they lived only in the database. v0.32.2 fences them in markdown so they survive `gbrain rebuild`. Migration v0_32_2 backfills existing facts to entity-page fences. Plus a 3-layer privacy strip and a CI gate that enforces the rule going forward."
+ description: "Backfills eligible legacy facts to existing canonical entity-page fences. Facts without a verified page or file remain in the database and need a database backup. Includes a 3-layer privacy strip and a CI gate for canonical write paths."
recipe: null
tiers: null
---
@@ -11,30 +11,33 @@ feature_pitch:
## What this is
-v0.32.2 closes a gap that's existed since v0.31 shipped hot-memory facts.
-Facts were DB-only — drop the `facts` table and the data was gone. v0.32.2
-makes them FS-canonical: every fact write lands in a `## Facts` fence on
-the entity page first, then stamps the DB index. The DB is now a true
-derived cache for facts.
+This guide describes the current v0.32.2 orchestrator, including its safety
+checks in v0.50.2.0. Eligible legacy facts are copied into a `## Facts`
+fence on an existing canonical entity page. Unresolved facts and other
+DB-only knowledge are not reconstructible from Markdown alone; preserve a
+restorable database backup as well as source files.
## What the agent needs to do
-**For existing v0.31 brains (most users):**
-
-1. Run `gbrain apply-migrations --yes` to invoke the v0_32_2 orchestrator.
-2. The orchestrator runs in two phases:
- - **phaseAFenceFacts** walks every legacy fact row (row_num IS NULL,
- entity_slug IS NOT NULL) and appends it to the entity's markdown
- fence atomically. Dry-run by default — runs in dry-run mode first,
- reports what WOULD happen, then runs again with `--write` after
- user confirms (or pass `--write` directly to skip the
- confirmation step).
- - **phaseBVerify** re-parses every touched fence + diffs against
- the DB. Mismatch → marks the migration partial; user runs
- `gbrain apply-migrations --force-retry 51`.
-3. Refuses to run when any source's local_path has uncommitted git
- changes. Mirrors the v0.14.1 `dry-fix` safety posture so the user
- can review the diff before committing.
+**For hosts with pending legacy facts:**
+
+1. If upgrading from before v0.50.0.0, complete the
+ [coordinated authorization cutover](v0.50.0.0.md) first. On a compatible
+ host, inspect `gbrain apply-migrations --list` and preview the plan with
+ `gbrain apply-migrations --migration 0.32.2 --dry-run`. After reviewing
+ backups and affected sources, run
+ `gbrain apply-migrations --migration 0.32.2 --yes`.
+2. The orchestrator checks the schema, fences eligible facts, then verifies
+ fence row counts. Only live legacy rows with an existing source-scoped
+ page and canonical file are eligible. Missing targets are reported as
+ `skipped_no_page`; no stub is created. Existing fence and database row
+ numbers remain reserved. Count verification is not full content parity.
+ `--dry-run` previews the migration plan; there is no `--write` flag.
+3. Dirty-tree refusal applies only to the source subtrees receiving writes.
+ If verification fails, inspect the reported drift before retrying. For a
+ wedged orchestrator, `gbrain apply-migrations --force-retry 0.32.2` resets
+ its retry marker; rerun the selected migration afterward. `51` is a schema
+ migration number, not the orchestrator version accepted by `--force-retry`.
4. After completion: `git diff` shows the new fences; user can commit
them and the facts now live in git alongside the rest of the brain.
@@ -42,15 +45,15 @@ derived cache for facts.
The schema migration v51 creates the columns from the start (fresh-install
parity via the v40 CREATE TABLE block). The v0_32_2 orchestrator has
-nothing to backfill (no legacy rows). It runs phaseA + phaseB and
-no-ops cleanly.
+nothing to backfill (no legacy rows). Its schema, fencing, and verification
+phases complete without creating fact rows.
-**For thin-client installs (no sources.local_path):**
+**For thin-client installs:**
-Facts continue to write to the DB directly with a once-per-process stderr
-warning naming the missing `sources.local_path`. The architecture doc
-names this as the explicit DB-only exception. To enable fence writes,
-configure `local_path` via the source setup.
+Run migrations on the brain host, not the thin client. Host sources without
+a local path are counted as `skipped_no_local_path`; their facts remain in
+the database. Do not invent entity pages or delete unmatched facts to make
+the migration appear complete.
## Things that changed for the agent
@@ -92,8 +95,8 @@ configure `local_path` via the source setup.
After the agent runs the migration:
```bash
-# Migration ran cleanly
-gbrain apply-migrations --yes
+# Inspect migration status without applying other pending work
+gbrain apply-migrations --list
# No fence write failures
test ! -f ~/.gbrain/facts.write_failures.jsonl || echo "WARN: some failures recorded"
diff --git a/skills/migrations/v0.50.2.0.md b/skills/migrations/v0.50.2.0.md
new file mode 100644
index 0000000000..cac0023858
--- /dev/null
+++ b/skills/migrations/v0.50.2.0.md
@@ -0,0 +1,80 @@
+# v0.50.2.0: verify saved writes and resume unfinished maintenance
+
+Keep the agent's identity, unrelated instructions, capture consent, and existing
+grants unchanged. These steps do not authorize paid enrichment or deletion of
+historical data. Run host-only maintenance on the brain host, not a thin client.
+
+1. **Check the starting version.** Run `gbrain --version`. If the installation
+ predates v0.50.0.0, follow [that coordinated cutover](v0.50.0.0.md) before this
+ upgrade. Do not start old workers against a newer authorization schema.
+
+2. **Upgrade and verify the host.** On an already-compatible v0.50 host, run
+ `gbrain upgrade`, restart its services through their normal service manager,
+ then run `gbrain --version` and `gbrain doctor`. This release adds no schema
+ migration. If doctor reports a partial earlier migration, inspect the exact
+ failure and use the existing migration recovery procedure; do not run a
+ destructive cleanup or authorize queued jobs in bulk.
+
+3. **Restart old PGLite holders safely.** Stop and restart the owning service
+ normally so the new lock records structured arguments. Live legacy locks
+ without provable identity intentionally refuse automatic PID-reuse reaping.
+ Never delete a live lock or run two processes against the same embedded
+ database to bypass that refusal.
+
+4. **Repair affected hosted launchers without expanding access.** If the recorded
+ launcher still exports a write source or passes `--brain host` for a hosted
+ connection, rerun the original `gbrain connect ... --install` workflow with
+ the existing private handoff, harness, and installation root. Keep credentials
+ local and private. Do not mint a broader grant or replace the agent's unrelated
+ instructions. Verify through the absolute recorded launcher: an unqualified
+ read may use the grant's readable sources; an explicit source and every write
+ remain subject to host authorization. `gbrain call` is intentionally host-only.
+
+5. **Recover affected code sources with an explicit full walk.** Identify the
+ source whose Bash parsing or Windows subdirectory sync failed and back up its
+ files. Replace the example source ID before running:
+
+ ```bash
+ gbrain sync --source code-example --full --no-embed
+ gbrain doctor
+ ```
+
+ The code chunker version advances to 7, but an incremental run after new
+ commits can still skip historical files. Check representative Bash functions
+ and changed files after the full walk. `--no-embed` avoids authorizing paid
+ embedding here; review the remaining embedding work with the operator before
+ running it. Do not re-embed the whole brain merely to update a page signature.
+
+6. **Preserve facts that cannot yet be attached to a canonical page.** New
+ unresolved references keep their fact/provenance with a NULL entity target.
+ The legacy fence migration reports `skipped_no_page` rather than creating
+ stubs. Historical orphan facts, prior stubs, and fence drift are not repaired
+ automatically. Keep a restorable database backup as well as source backups;
+ Markdown alone cannot recover DB-only facts. Do not delete them or invent
+ entity pages merely to clear a diagnostic.
+
+7. **Interpret write and maintenance results accurately.** `storage_busy` on
+ worktree acquisition means the write was not applied and was not queued. Read
+ the latest page before retrying the complete revision. A saved page can
+ separately report embedding failure or supersession; do not overwrite a newer
+ page to retry enrichment. There is no durable acceptance queue, caller revision
+ precondition, or crash-atomic file/database commit in this release.
+
+ A job with `require_writes: true` must save a page. Prose-only and rejected
+ imports fail that requirement; use optional-write behavior only for genuinely
+ optional work. Global maintenance and synthesis cooldowns now leave explicitly
+ incomplete or budget-deferred work due for retry. Inspect
+ `gbrain jobs stats --json` and the relevant job results before restoring
+ unattended schedules.
+
+8. **Verify OAuth scopes without broadening them.** A generic client following
+ the default challenge starts with `read`, even if its registration permits
+ more. Saving requires an explicit authorized `write` request and operator
+ approval. Preserve existing authorized sessions; do not purge tokens or
+ re-register every client. Discovery no longer advertises `agent`, and explicit
+ DCR requests for it remain rejected. SDK/HTTP tests are not evidence of a new
+ live ChatGPT or Claude session; verify the intended harness separately.
+
+Report failures with sanitized diagnostics, the installed version, source ID,
+and failing step. Keep credentials, private page contents, and private handoffs
+out of public issues.
diff --git a/skills/skills.lock.json b/skills/skills.lock.json
index 0e7c6e74a0..ebb9c88873 100644
--- a/skills/skills.lock.json
+++ b/skills/skills.lock.json
@@ -119,7 +119,7 @@
"migrations/v0.27.1.md": "719dd4ebcc7ac81413ee79af20f80de5141577e3860e5049a49fc8f6d09ddf89",
"migrations/v0.28.0.md": "21929a392af2e1f454272e80aade6c58c5f6ccd7253d24344d08c6b53bcdf4f9",
"migrations/v0.29.1.md": "7b85373a62a8500ee8c4238ffc9878318b44ee62543adb8b2462049c6c0cd1f8",
- "migrations/v0.32.2.md": "101623fa48f946242d7edc8f126967822563c3fb30a6ad50d029894f5fe3499d",
+ "migrations/v0.32.2.md": "7dc1198c02ab37534e04604c93c7e9a854ca9f04872af2a7c1fd4c0c8b78fbeb",
"migrations/v0.32.6.md": "e9438a910afe8a1f7861c5222fd7db04a0f8d8b8283778476b07b7c3d539d3f0",
"migrations/v0.33.0.md": "11710cb11d6eb7dc3ea54b764e3c4a25f8679cf76590acd330f97bfa1c684945",
"migrations/v0.33.3.0.md": "188a03ca86a97a9aa697cbbc83cc8ca37843fab24db2bd82f1383c400173d5bd",
@@ -137,6 +137,7 @@
"migrations/v0.49.0.0.md": "adf719246c3d6bcc7a1e5d24badb9968fe636651183a75c18d534e16aaa33ee8",
"migrations/v0.5.0.md": "5e0dabc451595295c4d971e19bcb33c258a127223d25859d8321cb7e1ce60711",
"migrations/v0.50.0.0.md": "f221a6c907437a7500d2ad8ee9fdc5e14821514d4c1e72164b7aafac0bd5d89b",
+ "migrations/v0.50.2.0.md": "ff1aab621479eeda5f210e026169ba584a1c402536cabddc7c387a617934b6f1",
"migrations/v0.7.0.md": "97c2740445a10b1c5c7123c17dbd625fa27a94095b85d27c2b278da756c4c59a",
"migrations/v0.8.0.md": "1919ff8b8f3680612ff888e7cfcc0d86ece5d5304ae19af4497bdf40b050561a",
"migrations/v0.8.1.md": "fad7341cfb5e02545fb8a23221d12ab395fc3d8db15d1d8ee8a18844aea6563a",
diff --git a/src/assets/wasm/README.md b/src/assets/wasm/README.md
new file mode 100644
index 0000000000..d4994bacf8
--- /dev/null
+++ b/src/assets/wasm/README.md
@@ -0,0 +1,39 @@
+# Vendored tree-sitter assets
+
+`src/core/chunkers/code.ts` embeds the runtime and grammar files directly with
+Bun file imports. Its `LANGUAGE_MANIFEST` records paths, not content hashes;
+replacing a grammar at the same path does not require regenerating a manifest.
+Run `bun run check:wasm` to verify semantic parsing in the compiled binary.
+
+## Bash (#5082)
+
+`grammars/tree-sitter-bash.wasm` is the official
+[`tree-sitter/tree-sitter-bash` v0.23.3 release asset](https://github.com/tree-sitter/tree-sitter-bash/releases/tag/v0.23.3),
+not a binary taken from a contributor branch or the npm `tree-sitter-wasms` bundle.
+
+- Upstream source tag: `v0.23.3`, commit
+ `487734f87fd87118028a65a4599352fa99c9cde8` (MIT license).
+- SHA-256: `d1844429a58620f306b6f42aebe92298243ca8120cd833a3ab5d87c7a2e7b9fd`.
+- Size: 1,364,404 bytes. Language ABI: 14, compatible with the pinned
+ `[email protected]` runtime (ABI 13–14).
+- The release source archive's `src/scanner.c` matches the tagged source
+ (Git blob `748cf1bc4c928a52b4e6f9c27bc9a2bb4eeb6bce`). It uses `iswalpha` and
+ `iswalnum`, exported by the runtime, instead of the previous binary's missing
+ `isalpha` import. The remaining unresolved `__assert_fail` import is an
+ assertion-only path; this update does not change the runtime's libc exports.
+
+Re-vendor the pinned official asset, verifying its checksum before replacement:
+
+```sh
+bash scripts/vendor-bash-wasm.sh
+bun test test/chunkers/code-bash.test.ts
+bun run check:wasm
+```
+
+This is a verified upstream prebuilt, not a claim of a byte-reproducible local
+build. The regression suite checks imports, ABI compatibility, real `case`,
+heredoc and loop parsing, and semantic function preservation. `CHUNKER_VERSION`
+advances to 7 to trigger the existing re-chunk gate when Git HEAD is unchanged.
+That gate does not force a full walk when new commits are present; use
+`gbrain sync --source <id> --full` to recover all previously affected files in
+an active repository rather than relying on an incremental sync.
diff --git a/src/assets/wasm/grammars/tree-sitter-bash.wasm b/src/assets/wasm/grammars/tree-sitter-bash.wasm
index 214d0a73a4..28e2869fad 100755
Binary files a/src/assets/wasm/grammars/tree-sitter-bash.wasm and b/src/assets/wasm/grammars/tree-sitter-bash.wasm differ
diff --git a/src/cli.ts b/src/cli.ts
index 157dd324f6..5dcdadbc99 100755
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -1946,7 +1946,7 @@ export function formatResult(
// work on any install shape.
export const THIN_CLIENT_REFUSED_COMMANDS = new Set([
'sync', 'embed', 'extract', 'extract-conversation-facts', 'enrich', 'migrate', 'retrieval-upgrade', 'apply-migrations',
- 'repair-jsonb', 'orphans', 'integrity', 'serve',
+ 'repair-jsonb', 'orphans', 'integrity', 'serve', 'call',
// v0.43 (#2095): watch streams against a LOCAL engine; thin clients get
// the volunteer_context MCP op instead.
'watch',
@@ -1994,6 +1994,7 @@ export const THIN_CLIENT_REFUSED_COMMANDS = new Set([
* place during code review.
*/
const THIN_CLIENT_REFUSE_HINTS: Record<string, string> = {
+ call: '`call` dispatches against a local engine. Use the named CLI command or an authorized MCP tool through your agent, or run `gbrain call` on the host.',
sync: 'sync runs on the host. Use the dedicated `sync_brain` MCP operation, or run `gbrain sync` on the host.',
embed: 'embed runs on the host. Run `gbrain embed` or `gbrain cycle` on the host machine.',
extract: 'extract runs on the host. Run `gbrain extract` or `gbrain cycle` on the host machine.',
diff --git a/src/commands/eval-longmemeval.ts b/src/commands/eval-longmemeval.ts
index 77873126d3..e0b2a154e8 100644
--- a/src/commands/eval-longmemeval.ts
+++ b/src/commands/eval-longmemeval.ts
@@ -486,6 +486,7 @@ function printHelp(): void {
}
export interface RunOpts {
+ exitOnError?: boolean;
/** Inject a chat client for tests; defaults to the gateway-routed client (#4636). */
client?: ThinkLLMClient;
/** Separate stub for the Haiku claim extractor (defaults to the same gateway client). */
@@ -608,19 +609,23 @@ function gitShort(argv: readonly string[], fallback: string): string {
}
export async function runEvalLongMemEval(args: string[], runOpts: RunOpts = {}): Promise<void> {
+ const fail = (code: number): never => {
+ if (runOpts.exitOnError !== false) process.exit(code);
+ throw new Error(`longmemeval failed (exit ${code}); see evaluation diagnostics`);
+ };
let opts: ParsedArgs;
try {
opts = parseArgs(args);
} catch (err: any) {
process.stderr.write(`Error: ${err.message ?? err}\n`);
- process.exit(1);
+ fail(1);
return;
}
if (opts.help) { printHelp(); return; }
if (!opts.datasetPath) {
process.stderr.write(`Error: <dataset.jsonl> is required.\n\n`);
printHelp();
- process.exit(1);
+ fail(1);
return;
}
@@ -630,7 +635,7 @@ export async function runEvalLongMemEval(args: string[], runOpts: RunOpts = {}):
({ questions, sha256: datasetSha256 } = loadDataset(opts.datasetPath, HUGGINGFACE_URL));
} catch (err: any) {
process.stderr.write(`Error: ${err.message ?? err}\n`);
- process.exit(1);
+ fail(1);
return;
}
const datasetQuestionCount = questions.length;
@@ -666,7 +671,7 @@ export async function runEvalLongMemEval(args: string[], runOpts: RunOpts = {}):
questions = questions.filter(q => want.has(q.question_id));
} catch (err: any) {
process.stderr.write(`Error: ${err.message ?? err}\n`);
- process.exit(1);
+ fail(1);
return;
}
}
@@ -675,7 +680,7 @@ export async function runEvalLongMemEval(args: string[], runOpts: RunOpts = {}):
}
if (questions.length === 0) {
process.stderr.write(`Error: dataset contains no questions.\n`);
- process.exit(1);
+ fail(1);
return;
}
@@ -883,7 +888,7 @@ export async function runEvalLongMemEval(args: string[], runOpts: RunOpts = {}):
persistRunRecord(repoRoot, record, runOpts.recordDir);
process.stderr.write(`[longmemeval] recorded ${record.run_id} (${record.status})\n`);
}
- if (exitCode !== 0) process.exit(exitCode);
+ if (exitCode !== 0) fail(exitCode);
};
// --resume-from: filter out already-answered question_ids before any
@@ -902,7 +907,7 @@ export async function runEvalLongMemEval(args: string[], runOpts: RunOpts = {}):
`(${check.foreign.map(h => h.slice(0, 12)).join(', ')} vs this run's ${retrievalHash.slice(0, 12)}).`;
if (!opts.allowMixedRunConfig) {
process.stderr.write(`${msg} Refusing to mix runs; pass --allow-mixed-run-config to override.\n`);
- process.exit(1);
+ fail(1);
return;
}
process.stderr.write(`${msg} Continuing (--allow-mixed-run-config).\n`);
@@ -925,14 +930,14 @@ export async function runEvalLongMemEval(args: string[], runOpts: RunOpts = {}):
`(${sel.foreign.map(h => h.slice(0, 12)).join(', ')} vs this run's ${runJudgeHash.slice(0, 12)}).`;
if (!opts.allowMixedRunConfig) {
process.stderr.write(`${msg} Refusing to mix judge configs; pass --allow-mixed-run-config to override.\n`);
- process.exit(1);
+ fail(1);
return;
}
process.stderr.write(`${msg} Continuing (--allow-mixed-run-config).\n`);
}
if (sel.retrievalOnly > 0) {
process.stderr.write(`Error: --judge: ${sel.retrievalOnly} row(s) in ${opts.resumeFromPath} were produced with --retrieval-only and carry no reader hypothesis to judge.\n`);
- process.exit(1);
+ fail(1);
return;
}
if (sel.missingFromDataset > 0) process.stderr.write(`[longmemeval] WARN judge backfill: ${sel.missingFromDataset} row(s) not in this dataset — left unjudged\n`);
@@ -989,7 +994,7 @@ export async function runEvalLongMemEval(args: string[], runOpts: RunOpts = {}):
replay = loadExpansionReplay(opts.expansionReplayPath);
} catch (err: any) {
process.stderr.write(`Error: ${err.message ?? err}\n`);
- process.exit(1);
+ fail(1);
return;
}
process.stderr.write(`[longmemeval] expansion replay: ${replay.size} recorded variant set(s) from ${opts.expansionReplayPath}\n`);
@@ -1008,6 +1013,15 @@ export async function runEvalLongMemEval(args: string[], runOpts: RunOpts = {}):
})
: '';
+ if (runOpts.exitOnError === false) {
+ if (!opts.retrievalOnly && !runOpts.client && !isAvailable('chat', model)) {
+ throw new Error(`longmemeval reader chat provider not configured for ${model}; configure this model's provider or models.eval.longmemeval`);
+ }
+ if (trajectoryEnabled && !runOpts.extractorClient && !isAvailable('chat', extractorModel)) {
+ throw new Error(`longmemeval extractor chat provider not configured for ${extractorModel}; configure this model's provider or its utility tier`);
+ }
+ }
+
// --judge preflight (Phase D): availability → pricing → estimate → cap.
// Runs before the brain connects so a refused run costs nothing.
let judgeCtx: JudgeLaneContext | null = null;
@@ -1025,7 +1039,7 @@ export async function runEvalLongMemEval(args: string[], runOpts: RunOpts = {}):
});
if (!pre.ok) {
process.stderr.write(`Error: ${pre.message}\n`);
- process.exit(pre.exitCode);
+ fail(pre.exitCode);
return;
}
for (const line of pre.lines) process.stderr.write(`${line}\n`);
@@ -1135,7 +1149,7 @@ export async function runEvalLongMemEval(args: string[], runOpts: RunOpts = {}):
const r = await probe(engine, pins.reranker.model);
if (!r.readiness.ready) {
process.stderr.write(`[longmemeval] reranker not ready (${r.plane} plane): ${describeRerankerFix(r.readiness) ?? 'not ready'}\n`);
- process.exit(2);
+ fail(2);
return;
}
}
diff --git a/src/commands/extract-conversation-facts.ts b/src/commands/extract-conversation-facts.ts
index d60be876f3..b3a19b6809 100644
--- a/src/commands/extract-conversation-facts.ts
+++ b/src/commands/extract-conversation-facts.ts
@@ -1124,7 +1124,7 @@ async function processPage(
(raw, message) => {
process.stderr.write(
`[extract-conversation-facts] ${page.slug} segment ${seg.startIso}..${seg.endIso} ` +
- `entity resolution failed for ${JSON.stringify(raw)}: ${message}; keeping raw value\n`,
+ `entity resolution failed for ${JSON.stringify(raw)}: ${message}; preserving fact without an entity target\n`,
);
},
);
@@ -2054,10 +2054,10 @@ export async function runExtractConversationFacts(
console.log(` Cleaned ${aggregate.orphan_facts_cleaned} orphan fact(s) from prior partial runs (D11 replay safety).`);
}
if (aggregate.fallback_slugify_count > 0) {
- console.log(` Minted ${aggregate.fallback_slugify_count} entity slug(s) via fallback_slugify.`);
+ console.log(` Preserved ${aggregate.fallback_slugify_count} fact(s) without an entity target after unresolved fallback_slugify.`);
}
if (aggregate.resolution_errors > 0) {
- console.log(` Kept ${aggregate.resolution_errors} raw entity value(s) after best-effort resolution errors.`);
+ console.log(` Preserved ${aggregate.resolution_errors} fact(s) without an entity target after best-effort resolution errors.`);
}
if (anyBudgetExhausted) {
console.log(` Budget cap reached. Re-run with a higher --max-cost-usd to continue.`);
diff --git a/src/commands/jobs.ts b/src/commands/jobs.ts
index 3094cde477..ebc25f0947 100644
--- a/src/commands/jobs.ts
+++ b/src/commands/jobs.ts
@@ -2787,9 +2787,21 @@ export async function registerBuiltinHandlers(
yieldBetweenPhases: async () => { await new Promise<void>((r) => setImmediate(r)); },
});
- // Stamp last_global_at only on a non-failed run so a failed pass stays stale
- // and re-dispatches next tick (self-healing retry).
- if (report.status === 'ok' || report.status === 'clean' || report.status === 'partial') {
+ if ((report.status === 'ok' || report.status === 'clean' || report.status === 'partial')
+ && !report.phases.some(phase => {
+ if (phase.status === 'fail') return true;
+ if (phase.phase !== 'synthesize' && phase.phase !== 'patterns') return false;
+ if (phase.details.reason === 'insufficient_cycle_budget') return true;
+ if (phase.phase === 'patterns') {
+ return typeof phase.details.child_outcome === 'string' && phase.details.child_outcome !== 'completed';
+ }
+ const synthesis = phase.details.synthesis as { non_completed_jobs?: number } | undefined;
+ const triage = phase.details.triage as { deferred?: number } | undefined;
+ return (synthesis?.non_completed_jobs ?? 0) > 0
+ || (triage?.deferred ?? 0) > 0
+ || (Array.isArray(phase.details.budget_deferred_transcripts) && phase.details.budget_deferred_transcripts.length > 0);
+ })
+ && report.reason !== 'aborted' && report.reason !== 'lock_stolen') {
try {
await engine.setConfig(LAST_GLOBAL_AT_KEY, new Date().toISOString());
} catch (e) {
diff --git a/src/commands/migrations/v0_32_2.ts b/src/commands/migrations/v0_32_2.ts
index 0a3b463cfe..89e753c611 100644
--- a/src/commands/migrations/v0_32_2.ts
+++ b/src/commands/migrations/v0_32_2.ts
@@ -30,8 +30,7 @@
* forever; they live in the legacy keyspace permanently.
*/
-import { existsSync, mkdirSync, readFileSync, writeFileSync, renameSync } from 'node:fs';
-import { join, dirname } from 'node:path';
+import { existsSync, readFileSync, writeFileSync, renameSync } from 'node:fs';
import { execFileSync } from 'node:child_process';
import type {
@@ -40,7 +39,8 @@ import type {
import type { BrainEngine } from '../../core/engine.ts';
import { loadConfig, toEngineConfig } from '../../core/config.ts';
import { createEngine } from '../../core/engine-factory.ts';
-import { upsertFactRow, parseFactsFence } from '../../core/facts-fence.ts';
+import { parseFactsFence, renderFactsTable, replaceOrInsertFactsFence } from '../../core/facts-fence.ts';
+import { resolvePageWriteTarget } from '../../core/write-through.ts';
let testEngineOverride: BrainEngine | null = null;
export function __setTestEngineOverride(engine: BrainEngine | null): void {
@@ -114,6 +114,7 @@ interface LegacyFactRow {
valid_until: Date | null;
source: string;
confidence: number;
+ page_exists: boolean;
}
interface SourceLookup {
@@ -126,6 +127,7 @@ interface PhaseBOutcome {
fenced: number;
skipped_no_entity: number;
skipped_no_local_path: number;
+ skipped_no_page: number;
pages_touched: number;
failed_pages: string[];
}
@@ -137,7 +139,7 @@ interface PhaseBOutcome {
*/
function isLocalPathDirty(localPath: string): boolean {
try {
- const out = execFileSync('git', ['-C', localPath, 'status', '--porcelain'], {
+ const out = execFileSync('git', ['-C', localPath, 'status', '--porcelain', '--', '.'], {
encoding: 'utf-8',
timeout: 10_000,
});
@@ -154,28 +156,6 @@ async function phaseBFenceFacts(
engine: BrainEngine | null,
opts: OrchestratorOpts,
): Promise<OrchestratorPhaseResult> {
- if (opts.dryRun) {
- // Dry-run: report what WOULD happen without touching FS or DB.
- if (!engine) return { name: 'fence_facts', status: 'skipped', detail: 'no_brain_configured' };
- try {
- const counts = await engine.executeRaw<{ n: string }>(
- `SELECT COUNT(*) AS n FROM facts WHERE row_num IS NULL`,
- );
- const total = parseInt(counts[0]?.n ?? '0', 10);
- const noEntity = await engine.executeRaw<{ n: string }>(
- `SELECT COUNT(*) AS n FROM facts WHERE row_num IS NULL AND entity_slug IS NULL`,
- );
- const noEntityCount = parseInt(noEntity[0]?.n ?? '0', 10);
- return {
- name: 'fence_facts',
- status: 'skipped',
- detail: `dry-run: would fence ${total - noEntityCount} rows; ${noEntityCount} unfenceable (NULL entity_slug)`,
- };
- } catch (e) {
- return { name: 'fence_facts', status: 'failed', detail: e instanceof Error ? e.message : String(e) };
- }
- }
-
if (!engine) {
return { name: 'fence_facts', status: 'skipped', detail: 'no_brain_configured' };
}
@@ -192,9 +172,11 @@ async function phaseBFenceFacts(
// atomic writes.
const legacy = await engine.executeRaw<LegacyFactRow>(
`SELECT id, source_id, entity_slug, fact, kind, visibility, notability,
- context, valid_from, valid_until, source, confidence
- FROM facts
- WHERE row_num IS NULL
+ context, valid_from, valid_until, source, confidence,
+ EXISTS (SELECT 1 FROM pages p WHERE p.source_id = f.source_id
+ AND p.slug = f.entity_slug AND p.deleted_at IS NULL) AS page_exists
+ FROM facts f
+ WHERE row_num IS NULL AND expired_at IS NULL
ORDER BY source_id, entity_slug, id`,
);
@@ -203,6 +185,7 @@ async function phaseBFenceFacts(
fenced: 0,
skipped_no_entity: 0,
skipped_no_local_path: 0,
+ skipped_no_page: 0,
pages_touched: 0,
failed_pages: [],
};
@@ -220,12 +203,37 @@ async function phaseBFenceFacts(
outcome.skipped_no_local_path += 1;
continue;
}
+ if (!row.page_exists) {
+ outcome.skipped_no_page += 1;
+ continue;
+ }
const key = `${row.source_id}\0${row.entity_slug}`;
const list = groups.get(key) ?? [];
list.push(row);
groups.set(key, list);
}
+ const filePaths = new Map<string, string>();
+ for (const [key, group] of groups) {
+ const [sourceId, entitySlug] = key.split('\0');
+ const target = await resolvePageWriteTarget(engine, entitySlug, sourceId);
+ if (!target.ok || !existsSync(target.filePath)) {
+ outcome.skipped_no_page += group.length;
+ groups.delete(key);
+ continue;
+ }
+ filePaths.set(key, target.filePath);
+ }
+
+ if (opts.dryRun) {
+ const fenceable = [...groups.values()].reduce((n, group) => n + group.length, 0);
+ return {
+ name: 'fence_facts', status: 'skipped',
+ detail: `dry-run: would fence ${fenceable} rows; ${outcome.skipped_no_entity} unfenceable (NULL entity_slug); ` +
+ `skipped_no_page=${outcome.skipped_no_page} skipped_no_local_path=${outcome.skipped_no_local_path}`,
+ };
+ }
+
// Dirty-tree refusal: check ONLY the sources we are about to write
// into. A dirty tree in an unrelated source (or zero fenceable rows
// at all) must not block a no-op or a targeted backfill (#927).
@@ -243,27 +251,11 @@ async function phaseBFenceFacts(
for (const [key, group] of groups) {
const [sourceId, entitySlug] = key.split('\0');
- const localPath = localPathById.get(sourceId)!;
- const filePath = join(localPath, `${entitySlug}.md`);
+ const filePath = filePaths.get(key)!;
const tmpPath = `${filePath}.tmp`;
try {
- // Read existing body or stub-create with minimum frontmatter.
- let body: string;
- if (existsSync(filePath)) {
- body = readFileSync(filePath, 'utf-8');
- } else {
- mkdirSync(dirname(filePath), { recursive: true });
- const prefix = entitySlug.split('/')[0];
- const type =
- prefix === 'people' ? 'person' :
- prefix === 'companies' ? 'company' :
- prefix === 'deals' ? 'deal' :
- /* fallback */ 'concept';
- const tail = entitySlug.split('/').slice(1).join('/');
- const title = tail.replace(/[-_/]+/g, ' ').replace(/\b\w/g, c => c.toUpperCase()) || entitySlug;
- body = `---\ntype: ${type}\ntitle: ${title}\nslug: ${entitySlug}\n---\n\n# ${title}\n`;
- }
+ let body = readFileSync(filePath, 'utf-8');
// Append each legacy row, collecting the assigned row_nums.
// Already-fenced rows (row_num already set) are skipped at the
@@ -273,21 +265,32 @@ async function phaseBFenceFacts(
// existing row and append a duplicate. We dedup on (claim,
// source) before append to handle this.
const existingFence = parseFactsFence(body);
- const existingKeySet = new Set(existingFence.facts.map(f => `${f.claim}\0${f.source ?? ''}`));
+ if (existingFence.warnings.length > 0) {
+ outcome.failed_pages.push(`${entitySlug} (${existingFence.warnings.join('; ')})`);
+ continue;
+ }
+ const occupiedRows = await engine.executeRaw<{ row_num: number; fact: string; source: string | null }>(
+ `SELECT row_num, fact, source FROM facts
+ WHERE source_id = $1 AND source_markdown_slug = $2 AND row_num IS NOT NULL`,
+ [sourceId, entitySlug],
+ );
+ const occupied = new Map(occupiedRows.map(row => [Number(row.row_num), row]));
+ let nextRowNum = Math.max(0, ...occupied.keys(), ...existingFence.facts.map(f => f.rowNum)) + 1;
+ const claimed = new Set<number>();
const assignments: Array<{ id: string; row_num: number }> = [];
for (const row of group) {
- const key = `${row.fact}\0${row.source ?? ''}`;
- if (existingKeySet.has(key)) {
- // Already fenced (idempotent re-run). Find the existing
- // row_num and assign it to this DB row.
- const existing = existingFence.facts.find(f =>
- f.claim === row.fact && (f.source ?? '') === (row.source ?? ''),
- );
- if (existing) {
- assignments.push({ id: row.id, row_num: existing.rowNum });
- continue;
- }
+ const existing = existingFence.facts.find(f => {
+ const owner = occupied.get(f.rowNum);
+ return f.active && !claimed.has(f.rowNum) && f.claim === row.fact &&
+ (f.source ?? '') === (row.source ?? '') &&
+ (!owner || owner.fact !== f.claim || (owner.source ?? '') !== (f.source ?? ''));
+ });
+ if (existing) {
+ if (occupied.has(existing.rowNum)) existing.rowNum = nextRowNum++;
+ assignments.push({ id: row.id, row_num: existing.rowNum });
+ claimed.add(existing.rowNum);
+ continue;
}
// Append a new row.
const validFromStr = (row.valid_from instanceof Date ? row.valid_from : new Date(row.valid_from))
@@ -296,7 +299,10 @@ async function phaseBFenceFacts(
? (row.valid_until instanceof Date ? row.valid_until : new Date(row.valid_until))
.toISOString().slice(0, 10)
: undefined;
- const { body: updated, rowNum } = upsertFactRow(body, {
+ const rowNum = nextRowNum++;
+ existingFence.facts.push({
+ rowNum,
+ active: true,
claim: row.fact,
kind: row.kind,
confidence: row.confidence,
@@ -307,10 +313,10 @@ async function phaseBFenceFacts(
source: row.source,
context: row.context ?? undefined,
});
- body = updated;
- existingKeySet.add(key);
assignments.push({ id: row.id, row_num: rowNum });
+ claimed.add(rowNum);
}
+ body = replaceOrInsertFactsFence(body, renderFactsTable(existingFence.facts));
// Atomic write: .tmp + parse + rename.
writeFileSync(tmpPath, body, 'utf-8');
@@ -340,7 +346,7 @@ async function phaseBFenceFacts(
const detail = `scanned=${outcome.scanned} fenced=${outcome.fenced} ` +
`pages=${outcome.pages_touched} skipped_no_entity=${outcome.skipped_no_entity} ` +
- `skipped_no_local_path=${outcome.skipped_no_local_path}` +
+ `skipped_no_local_path=${outcome.skipped_no_local_path} skipped_no_page=${outcome.skipped_no_page}` +
(outcome.failed_pages.length > 0 ? ` failed=${outcome.failed_pages.length}` : '');
if (outcome.failed_pages.length > 0) {
@@ -392,12 +398,12 @@ async function phaseCVerify(
for (const g of groups) {
const localPath = localPathById.get(g.source_id);
if (!localPath) continue;
- const filePath = join(localPath, `${g.source_markdown_slug}.md`);
- if (!existsSync(filePath)) {
+ const target = await resolvePageWriteTarget(engine, g.source_markdown_slug, g.source_id);
+ if (!target.ok || !existsSync(target.filePath)) {
mismatches.push(`${g.source_markdown_slug} (file missing)`);
continue;
}
- const body = readFileSync(filePath, 'utf-8');
+ const body = readFileSync(target.filePath, 'utf-8');
const parsed = parseFactsFence(body);
const fenceCount = parsed.facts.length;
const dbCount = parseInt(g.n, 10);
diff --git a/src/commands/serve-http-oauth.ts b/src/commands/serve-http-oauth.ts
index 9f3c171eed..985ef29182 100644
--- a/src/commands/serve-http-oauth.ts
+++ b/src/commands/serve-http-oauth.ts
@@ -8,6 +8,31 @@ import { OAuthConsentError } from '../core/oauth-grants.ts';
import { safeHexEqual } from '../core/timing-safe.ts';
import { isRetryableError } from '../core/retry-matcher.ts';
+export function withBearerScopeHint(middleware: RequestHandler, scopes: readonly string[]): RequestHandler {
+ const scope = scopes.join(' ');
+ return async (req, res, next) => {
+ const originalSet = res.set;
+ res.set = function (this: Response, field: string | Record<string, string | string[]>, value?: string | string[]) {
+ if (typeof field === 'string'
+ && field.toLowerCase() === 'www-authenticate'
+ && typeof value === 'string'
+ && /^Bearer(?:\s|$)/i.test(value)
+ && !/(?:^|,)\s*scope=/i.test(value)) {
+ value += `, scope="${scope}"`;
+ }
+ if (typeof field === 'string') {
+ return originalSet.call(this, field, value as string);
+ }
+ return originalSet.bind(this)(field);
+ } as typeof res.set;
+ try {
+ await middleware(req, res, next);
+ } finally {
+ res.set = originalSet;
+ }
+ };
+}
+
function sendOAuthError(res: Response, error: unknown): void {
if (error instanceof OAuthError) {
res.status(error instanceof InvalidClientError ? 401 : 400).json(error.toResponseObject());
diff --git a/src/commands/serve-http.ts b/src/commands/serve-http.ts
index 2a02b43bcb..f69df61833 100644
--- a/src/commands/serve-http.ts
+++ b/src/commands/serve-http.ts
@@ -28,7 +28,7 @@ import { ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprot
import { mcpAuthRouter, getOAuthProtectedResourceMetadataUrl } from '@modelcontextprotocol/sdk/server/auth/router.js';
import { requireBearerAuth } from '@modelcontextprotocol/sdk/server/auth/middleware/bearerAuth.js';
import { InvalidTokenError } from '@modelcontextprotocol/sdk/server/auth/errors.js';
-import { mountConfidentialOAuth, mountOAuthConsent } from './serve-http-oauth.ts';
+import { mountConfidentialOAuth, mountOAuthConsent, withBearerScopeHint } from './serve-http-oauth.ts';
import type { BrainEngine } from '../core/engine.ts';
import { operations, OperationError, opAllowedForBoundClient } from '../core/operations.ts';
import type { OperationContext, AuthInfo } from '../core/operations.ts';
@@ -1216,11 +1216,7 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOption
const authRouterOptions: any = {
provider: oauthProvider,
issuerUrl,
- // v0.28: scopesSupported sourced from ALLOWED_SCOPES_LIST so MCP clients
- // (Claude Desktop, ChatGPT, Perplexity) can discover sources_admin and
- // users_admin via /.well-known/oauth-authorization-server. The legacy
- // ['read','write','admin'] list left those new scopes invisible.
- scopesSupported: [...ALLOWED_SCOPES_LIST],
+ scopesSupported: ALLOWED_SCOPES_LIST.filter(scope => scope !== 'agent'),
resourceName: 'GBrain MCP Server',
// Advertise /mcp as the protected resource (see mcpResourceUrl above).
resourceServerUrl: mcpResourceUrl,
@@ -2308,7 +2304,9 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOption
res.status(405).json({ jsonrpc: '2.0', error: { code: -32000, message: 'Method not allowed' }, id: null });
});
- app.post('/mcp', requireBearerAuth({ verifier: resourceVerifier, resourceMetadataUrl }), async (req: Request, res: Response) => {
+ app.post('/mcp', withBearerScopeHint(
+ requireBearerAuth({ verifier: resourceVerifier, resourceMetadataUrl }), ['read'],
+ ), async (req: Request, res: Response) => {
const startTime = Date.now();
const authInfo = (req as any).auth as AuthInfo;
diff --git a/src/commands/sync.ts b/src/commands/sync.ts
index a69253a440..dc8f2dd0d5 100644
--- a/src/commands/sync.ts
+++ b/src/commands/sync.ts
@@ -116,6 +116,7 @@ import {
isWithinRoot,
resolveNoEmbed,
discoverGitRoot,
+ gitRelativePath,
} from '../core/sync-git.ts';
import {
readSyncAnchor,
@@ -1567,8 +1568,7 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<Sy
`Refusing to sync: possible path traversal via --src-subpath.`,
);
}
- // Relative path from git root to sync scope ('' when scope == root).
- const syncScopeRelPath = syncScopeRoot === gitContextRoot ? '' : relative(gitContextRoot, syncScopeRoot);
+ const syncScopeRelPath = gitRelativePath(gitContextRoot, syncScopeRoot);
const scoped = syncScopeRelPath !== '';
// Anchor written back to sync state (sources.local_path / sync.repo_path):
// the SCOPE path, so a follow-up bare `gbrain sync` auto-discovers the same
@@ -4309,7 +4309,7 @@ async function performFullSync(
// whose source_path lives outside the subpath (e.g. from an earlier
// root-level sync of this source) are out of this walk's sight and must
// not be treated as stale.
- const scopePrefix = slugRoot ? relative(gitContextRoot, syncScopeRoot) + '/' : '';
+ const scopePrefix = slugRoot ? gitRelativePath(gitContextRoot, syncScopeRoot) + '/' : '';
// 'malformed-path' rows ARE reconcile-eligible: junk filenames (bracket /
// control-char paths minted by misbehaving producers) can never be
// re-imported, so their rows are permanent search pollution unless the
diff --git a/src/core/agent-install/launcher.ts b/src/core/agent-install/launcher.ts
index c0519f1388..5fcfac07e9 100644
--- a/src/core/agent-install/launcher.ts
+++ b/src/core/agent-install/launcher.ts
@@ -2,10 +2,14 @@ import { shellQuote } from '../mcp-registration.ts';
import { AGENT_ENV_SHELL_PATTERN } from './environment.ts';
/** Shared by local PGLite and hosted thin-client installs. No shell profiles or cwd routing. */
-export function renderAgentLauncher(p: { root: string; bunPath: string; cliPath?: string; sourceId?: string; repairHint?: string }): string {
+export function renderAgentLauncher(p: { root: string; bunPath: string; cliPath?: string; sourceId?: string; repairHint?: string; mode?: 'local' | 'thin-client' }): string {
const missing = `! -x ${shellQuote(p.bunPath)}` + (p.cliPath ? ` || ! -f ${shellQuote(p.cliPath)}` : '');
const invocation = shellQuote(p.bunPath) + (p.cliPath ? ` --no-env-file ${shellQuote(p.cliPath)}` : '');
const repair = p.repairHint ?? 'Restore the runtime used by this launcher, then repeat this installation.';
+ const routing = p.mode === 'thin-client'
+ ? ''
+ : `export GBRAIN_BRAIN_ID=host\nexport GBRAIN_SOURCE=${shellQuote(p.sourceId ?? 'default')}\n`;
+ const brainArg = p.mode === 'thin-client' ? '' : ' --brain host';
return `#!/usr/bin/env bash
set -euo pipefail
# This launcher belongs to the GBrain installation named below.
@@ -15,9 +19,7 @@ for gbrain_env_name in $(compgen -e); do
esac
done
export GBRAIN_HOME=${shellQuote(p.root)}
-export GBRAIN_BRAIN_ID=host
-export GBRAIN_SOURCE=${shellQuote(p.sourceId ?? 'default')}
-export GBRAIN_SKIP_STARTUP_HOOKS=1
+${routing}export GBRAIN_SKIP_STARTUP_HOOKS=1
# Empty, present keys also prevent .gbrain/.env from redirecting this installation.
export DATABASE_URL='' GBRAIN_DATABASE_URL=''
cd ${shellQuote(p.root)}
@@ -25,6 +27,6 @@ if [[ ${missing} ]]; then
printf '%s\\n' ${shellQuote(`GBrain runtime is missing. ${repair}`)} >&2
exit 1
fi
-exec ${invocation} --brain host "$@"
+exec ${invocation}${brainArg} "$@"
`;
}
diff --git a/src/core/brain-score-recommendations.ts b/src/core/brain-score-recommendations.ts
index e41765eff6..49e971503f 100644
--- a/src/core/brain-score-recommendations.ts
+++ b/src/core/brain-score-recommendations.ts
@@ -231,25 +231,6 @@ export function computeRecommendations(
const out: Remediation[] = [];
const source = ctx.sourceId ?? 'default';
- // ---------------------------------------------------------------------
- // sync.repo — fires when sync hasn't run recently OR pages are stale
- // ---------------------------------------------------------------------
- if (ctx.repoPath && health.stale_pages > 0) {
- const params = { repoPath: ctx.repoPath, sourceId: ctx.sourceId, noEmbed: true };
- out.push({
- id: 'sync.repo',
- job: 'sync',
- params,
- idempotency_key: idemKey(source, 'sync', params),
- severity: health.stale_pages > 50 ? 'high' : 'medium',
- est_seconds: Math.min(600, 30 + health.stale_pages * 0.5),
- est_usd_cost: 0, // sync is fs+DB only
- depends_on: [],
- rationale: `${health.stale_pages} stale page${health.stale_pages === 1 ? '' : 's'} on disk`,
- status: 'remediable',
- });
- }
-
// ---------------------------------------------------------------------
// embed.stale — missing embeddings AND/OR the NULL-signature cohort
// (unknown-provenance vectors that the grandfather clause would otherwise
@@ -295,8 +276,7 @@ export function computeRecommendations(
severity: 'critical',
est_seconds: Math.min(3600, 5 + (health.missing_embeddings + nullSigCohort) * 0.05),
est_usd_cost,
- // sync should run first so embed sees fresh pages.
- depends_on: ctx.repoPath && health.stale_pages > 0 ? ['sync.repo'] : [],
+ depends_on: [],
rationale: rationaleParts.join('; '),
status: 'remediable',
});
@@ -321,26 +301,18 @@ export function computeRecommendations(
});
}
- // ---------------------------------------------------------------------
- // extract.all — runs after sync to materialize links + timeline.
- // Triggered when sync.repo fires (because sync was set to noEmbed:true,
- // and noExtract:true after T5 lands → extract job is the materializer).
- // ---------------------------------------------------------------------
- if (ctx.repoPath && health.stale_pages > 0) {
- // #3957: carry the source id so the extract job's fs-walk rows land in
- // (and its watermark stamp targets) the brain source that owns repoPath —
- // not the 'default' fallback that silently no-ops on federated brains.
- const params = { mode: 'all', dir: ctx.repoPath, ...(ctx.sourceId ? { sourceId: ctx.sourceId } : {}) };
+ if (health.stale_pages > 0) {
+ const params = { stale: true, ...(ctx.sourceId ? { sourceId: ctx.sourceId } : {}) };
out.push({
- id: 'extract.all',
+ id: 'extract.stale',
job: 'extract',
params,
idempotency_key: idemKey(source, 'extract', params),
- severity: 'medium',
- est_seconds: Math.min(600, 30 + health.page_count * 0.01),
+ severity: health.stale_pages > 50 ? 'high' : 'medium',
+ est_seconds: Math.min(600, 30 + health.stale_pages * 0.01),
est_usd_cost: 0,
- depends_on: ['sync.repo'],
- rationale: 'Materialize link + timeline edges from fresh pages',
+ depends_on: [],
+ rationale: `Materialize link + timeline edges for ${health.stale_pages} stale database page${health.stale_pages === 1 ? '' : 's'}`,
status: 'remediable',
});
}
diff --git a/src/core/chunkers/code.ts b/src/core/chunkers/code.ts
index 8f390eb135..6a80b359a6 100644
--- a/src/core/chunkers/code.ts
+++ b/src/core/chunkers/code.ts
@@ -140,7 +140,7 @@ import G_ZIG from '../../assets/wasm/grammars/tree-sitter-zig.wasm' with { type:
// top-level defs indexed to ZERO symbols). Chunk boundaries change for every
// previously-merged file, so the bump forces a re-chunk that recovers the
// erased symbols.
-export const CHUNKER_VERSION = 6;
+export const CHUNKER_VERSION = 7;
// Lazy-loaded tree-sitter module (v0.22.x API: Parser is default export)
let Parser: typeof import('web-tree-sitter') | null = null;
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 50f23a8f6f..4dcab78fc3 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -25,7 +25,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'bench': ['--baseline', '--brain', '--force', '--from', '--help', '--json', '--label', '--limit', '--source', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-top1', '--to', '--tool'],
'book-mirror': ['--access', '--allow-empty', '--asof', '--author', '--background', '--bound-slug-prefixes', '--brain', '--chapters-dir', '--context-file', '--date', '--days', '--dry-run', '--entities', '--explain', '--file', '--follow', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--max-turns', '--mode', '--model', '--multimodal', '--no-confirm', '--no-follow', '--once', '--page', '--path', '--progress-interval', '--progress-json', '--quiet', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--surface', '--timeout', '--timeout-ms', '--title', '--trusted-extraction', '--types', '--url', '--yes'],
'bootstrap': ['--abbrev-ref', '--abort', '--accept-visibility-change-consequences', '--active', '--all', '--allow-unverified-remote', '--auto', '--brain', '--branch', '--cached', '--confirm', '--count', '--delete-brain', '--diff-filter', '--dim', '--env', '--error-unmatch', '--exclude-standard', '--file', '--force', '--gbrain-bin', '--get', '--git-dir', '--git-path', '--harness', '--heads', '--help', '--home', '--hostname', '--http', '--id', '--init', '--install', '--is-inside-work-tree', '--jq', '--json', '--local', '--mcp-even-if-plugin', '--minimal', '--name', '--name-only', '--no-capture', '--no-cron', '--no-hooks', '--no-verify', '--only', '--others', '--pat-file', '--path', '--pglite', '--porcelain', '--port', '--private', '--project', '--pure', '--push-only', '--quiet', '--rebase', '--remove', '--repair', '--scope', '--scopes', '--set', '--short', '--show', '--show-toplevel', '--skip', '--source', '--status', '--surface', '--to', '--token', '--token-name', '--unset-all', '--url', '--verify', '--version', '--visibility', '--workspace', '--yes'],
- 'brainstorm': ['--brain', '--force-rechunk', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--markdown', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],
+ 'brainstorm': ['--brain', '--force-rechunk', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--markdown', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--no-save', '--resume', '--save', '--source', '--stale', '--strict-budget', '--yes'],
'cache': ['--brain', '--help', '--json', '--source', '--yes'],
'calibration': ['--access', '--allow-empty', '--asof', '--bound-slug-prefixes', '--brain', '--date', '--days', '--dry-run', '--entities', '--file', '--full', '--help', '--holder', '--http', '--image', '--json', '--key-prefix', '--kind', '--limit', '--mode', '--multimodal', '--once', '--page', '--path', '--phase', '--regenerate', '--scrub-gstack', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--surface', '--trusted-extraction', '--types', '--undo-wave', '--url', '--with-calibration', '--yes'],
'call': ['--brain', '--help', '--json', '--source'],
@@ -90,7 +90,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'recall': ['--access', '--allow-empty', '--as-context', '--asof', '--bound-slug-prefixes', '--brain', '--budget-tokens', '--date', '--days', '--entities', '--file', '--full', '--grep', '--help', '--http', '--image', '--include-expired', '--json', '--kind', '--limit', '--mcp-only', '--mode', '--multimodal', '--once', '--page', '--path', '--pending', '--query', '--reason', '--rollup', '--session', '--session-id', '--since', '--since-last-run', '--slug', '--slugs', '--source', '--stats', '--supersessions', '--surface', '--today', '--trusted-extraction', '--types', '--url', '--watch', '--yes'],
'reconcile-links': ['--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout'],
'reindex': ['--aliases', '--background', '--brain', '--concurrency', '--cost-estimate', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--force-rechunk', '--help', '--json', '--limit', '--markdown', '--multimodal', '--no-embed', '--no-embedding', '--pglite', '--progress-interval', '--progress-json', '--quiet', '--repo', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--type', '--workers', '--yes'],
- 'reindex-code': ['--background', '--brain', '--concurrency', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--force-rechunk', '--help', '--json', '--markdown', '--max-cost', '--max-cost-usd', '--max-runtime', '--no-embed', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--to', '--workers', '--yes'],
+ 'reindex-code': ['--background', '--brain', '--concurrency', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--force-rechunk', '--help', '--json', '--markdown', '--max-cost', '--max-cost-usd', '--max-runtime', '--no-embed', '--progress-interval', '--progress-json', '--quiet', '--source', '--stale', '--timeout', '--to', '--workers', '--yes'],
'reindex-frontmatter': ['--brain', '--concurrency', '--dry-run', '--force', '--help', '--json', '--slug-prefix', '--source', '--workers', '--yes'],
'reindex-search-vector': ['--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--yes'],
'reinit-pglite': ['--abbrev-ref', '--all', '--allow-create-db', '--allow-docker', '--allow-empty', '--brain', '--break-lock', '--cached', '--chat-model', '--concurrency', '--confirm-destructive', '--diff-filter', '--embedding-dimensions', '--embedding-model', '--empty', '--entity', '--exclude', '--exclude-standard', '--expansion-model', '--filters', '--fix', '--force', '--force-break-lock', '--format', '--full', '--full-history', '--grant-types', '--hard-deadline', '--help', '--http', '--include-gitignored', '--include-hidden', '--interval', '--is-ancestor', '--is-shallow-repository', '--issuer-url', '--json', '--key', '--local-postgres', '--max-age', '--max-sources', '--mcp-only', '--mcp-url', '--migrate-only', '--missing-path', '--model', '--name-only', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-renames', '--no-schema-pack', '--no-sync', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--others', '--parallel', '--path', '--pglite', '--prefer-postgres', '--priority', '--provenance', '--quiet', '--repo', '--retry-failed', '--schema-pack', '--scopes', '--serial', '--show-toplevel', '--skip-embed-check', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--strategy', '--supabase', '--surface', '--timeout', '--to', '--url', '--verify', '--version', '--watch', '--workers', '--working-tree', '--yes'],
diff --git a/src/core/config.ts b/src/core/config.ts
index a1b57a41b4..8e3a54178f 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1297,6 +1297,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
'protocol_installed_at',
'provider_chat_options',
'storage',
+ 'schema_pack',
'eval',
'eval.capture',
'eval.scrub_pii',
diff --git a/src/core/cycle/nightly-probe-adapters.ts b/src/core/cycle/nightly-probe-adapters.ts
index 6aecaf8afe..a52549829b 100644
--- a/src/core/cycle/nightly-probe-adapters.ts
+++ b/src/core/cycle/nightly-probe-adapters.ts
@@ -48,16 +48,14 @@ export interface CrossModalBatchSummary {
* The CLI's first positional arg is `<dataset.jsonl>` (fixturePath).
* `--output PATH` writes per-question rows.
*
- * The CLI calls `process.exit(1)` on errors. The adapter doesn't trap
- * exit — the caller (nightly-quality-probe phase) wraps in try/catch and
- * treats any exit-style failure as a probe failure that doesn't crash
- * autopilot.
+ * Embedded failures throw so the nightly phase can audit the failure
+ * without terminating autopilot. Standalone CLI invocations still exit.
*/
export async function runLongMemEvalForProbe(args: LongMemEvalProbeArgs): Promise<void> {
const { runEvalLongMemEval } = await import('../../commands/eval-longmemeval.ts');
await runEvalLongMemEval(
[args.fixturePath, '--output', args.outputPath],
- { searchConfigSnapshot: args.searchConfigSnapshot },
+ { searchConfigSnapshot: args.searchConfigSnapshot, exitOnError: false },
);
}
diff --git a/src/core/cycle/synthesize.ts b/src/core/cycle/synthesize.ts
index 341d881584..11818bda90 100644
--- a/src/core/cycle/synthesize.ts
+++ b/src/core/cycle/synthesize.ts
@@ -1232,11 +1232,11 @@ async function runPhaseSynthesizeInner(
// still-unknown keys) AND nothing was budget-deferred (#4168 adversarial:
// "deferred transcripts retry next cycle" is a lie if the next cycle is
// cooldown-skipped for half a day).
- if (failedChildren.length === 0 && budgetExhaustedDeferrals.length === 0) {
+ if (failedChildren.length === 0 && budgetExhaustedDeferrals.length === 0 && pass.deferred === 0) {
await engine.setConfig('dream.synthesize.last_completion_ts', new Date().toISOString());
} else {
process.stderr.write(
- `[dream] synthesize: ${failedChildren.length}/${childOutcomes.length} child job(s) incomplete + ${budgetExhaustedDeferrals.length} deferred — cooldown NOT stamped so the next run retries them.\n`,
+ `[dream] synthesize: ${failedChildren.length}/${childOutcomes.length} child job(s) incomplete + ${budgetExhaustedDeferrals.length} synthesis-budget deferred + ${pass.deferred} triage-deferred — cooldown NOT stamped so the next run retries them.\n`,
);
}
diff --git a/src/core/embed-stale.ts b/src/core/embed-stale.ts
index 5267800934..08ac6b9fbc 100644
--- a/src/core/embed-stale.ts
+++ b/src/core/embed-stale.ts
@@ -22,7 +22,7 @@ import type { Chunk, ChunkInput } from './types.ts';
import { embedBatchWithBackoff, restampIfDemotedToTitleTier } from './embed-retry.ts';
import { wrapChunkTextsForStoredMode } from './embedding-context.ts';
import { healOversizedPageChunks, healedChunksToStaleRows } from './embed-oversize-heal.ts';
-import { invalidateStaleSignatureEmbeddingsGuarded } from './embedding-invalidation.ts';
+import { invalidateStaleSignatureEmbeddingsGuarded, splitEmbeddingSignature, currentSpaceChunkPredicate } from './embedding-invalidation.ts';
import {
resolveActiveEmbeddingColumnFromEngine,
quoteIdentifier,
@@ -157,7 +157,8 @@ export async function resolveProvenanceStamp(
/**
* Stamp `pages.embedding_signature` once EVERY chunk on the page carries an
* active-column vector written by the signature's model against the CURRENT
- * chunk_text (`embedded_text_hash = md5(chunk_text)`). Judged from DB state,
+ * chunk_text (`embedded_text_hash = md5(chunk_text)`) at the signature's vector
+ * width. Judged from DB state,
* not from the caller's batch: `listStaleChunks` pages by ROW with no page
* alignment, so a page straddling a batch boundary is never wholly in one
* batch — the batch that lands its last chunk stamps it here. A partially
@@ -174,17 +175,14 @@ export async function stampIfPageProvenanceComplete(
): Promise<boolean> {
// Signature is `<provider:model>:<dims>`; the model part is what
// upsertChunks records in content_chunks.model.
- const model = signature.slice(0, signature.lastIndexOf(':'));
+ const { model, dims } = splitEmbeddingSignature(signature);
const colId = quoteIdentifier(column);
const rows = await engine.executeRaw<{ complete: boolean }>(
`SELECT count(*) > 0
- AND bool_and(COALESCE(
- cc.${colId} IS NOT NULL
- AND cc.model = $1
- AND cc.embedded_text_hash = md5(cc.chunk_text), false)) AS complete
+ AND bool_and(${currentSpaceChunkPredicate(colId, 1, 4)}) AS complete
FROM content_chunks cc JOIN pages p ON p.id = cc.page_id
WHERE p.slug = $2 AND p.source_id = $3`,
- [model, slug, sourceId],
+ [model, slug, sourceId, dims],
);
if (rows[0]?.complete !== true) return false;
await engine.setPageEmbeddingSignature(slug, { sourceId, signature });
diff --git a/src/core/embedding-invalidation.ts b/src/core/embedding-invalidation.ts
index a1b0b04b32..a76a527506 100644
--- a/src/core/embedding-invalidation.ts
+++ b/src/core/embedding-invalidation.ts
@@ -4,8 +4,8 @@
* (PGLite and Postgres accept the SQL identically).
*
* #4306 — embed_skip-aware stale-signature invalidation.
- * `engine.invalidateStaleSignatureEmbeddings` NULLs mismatched-signature
- * vectors on EVERY page, but every stale/backfill selector
+ * `engine.invalidateStaleSignatureEmbeddings` NULLs non-current vectors on
+ * mismatched-signature pages, but every stale/backfill selector
* (buildStaleChunkWhere / listStaleChunks, both engines) excludes pages whose
* frontmatter carries `embed_skip`. Invalidate-then-hide: vectors retained on
* an embed_skip page (embedded BEFORE the marker appeared, e.g. the
@@ -13,8 +13,9 @@
* could never be re-embedded — permanent, silent loss.
* `invalidateStaleSignatureEmbeddingsGuarded` is the ONE invalidation entry
* point for the migration and embed paths: identical semantics to the engine
- * method PLUS the same NOT-embed_skip predicate the selectors use, so the two
- * halves can never disagree again. Never NULL what nothing will re-embed.
+ * method PLUS the same NOT-embed_skip predicate the selectors use and a
+ * restamp for pages whose chunks are all current. Model, text hash, and
+ * vector width must match to preserve progress across interrupted drains.
*
* #4305 — chunk-model truth cross-check. `pages.embedding_signature` is
* separate state that can disagree with the vectors it describes: a page
@@ -31,6 +32,23 @@ import {
quoteIdentifier,
} from './search/embedding-column.ts';
+export function splitEmbeddingSignature(signature: string): { model: string; dims: number | null } {
+ const separator = signature.lastIndexOf(':');
+ const suffix = signature.slice(separator + 1);
+ const dims = Number(suffix);
+ if (separator <= 0 || !/^\d+$/.test(suffix) || !Number.isSafeInteger(dims) || dims <= 0 || dims > 2147483647) {
+ return { model: signature, dims: null };
+ }
+ return { model: signature.slice(0, separator), dims };
+}
+
+export function currentSpaceChunkPredicate(colId: string, modelParam: number, dimsParam: number): string {
+ return `COALESCE(cc.${colId} IS NOT NULL
+ AND cc.model = $${modelParam}
+ AND cc.embedded_text_hash = md5(cc.chunk_text)
+ AND vector_dims(cc.${colId}) = $${dimsParam}::int, false)`;
+}
+
/**
* `<provider:model>:<dims>` — the one-line shape of
* embedding-migration.ts:migrationSignature, duplicated here so this module
@@ -131,7 +149,9 @@ export async function invalidateStaleSignatureEmbeddingsGuarded(
opts: { signature: string; sourceId?: string; includeNullSignature?: boolean },
): Promise<number> {
const colId = await activeColId(engine);
- const params: unknown[] = [opts.signature];
+ const { model, dims } = splitEmbeddingSignature(opts.signature);
+ const params: unknown[] = [opts.signature, model, dims];
+ const currentChunk = currentSpaceChunkPredicate(colId, 2, 3);
let srcClause = '';
if (opts.sourceId !== undefined) {
params.push(opts.sourceId);
@@ -149,10 +169,23 @@ export async function invalidateStaleSignatureEmbeddingsGuarded(
FROM pages p
WHERE cc.page_id = p.id
AND cc.${colId} IS NOT NULL
+ AND NOT ${currentChunk}
AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')
AND ${sigClause}${srcClause}
RETURNING cc.page_id`,
params,
);
+ await engine.executeRaw(
+ `UPDATE pages p SET embedding_signature = $1
+ WHERE ${sigClause}${srcClause}
+ AND p.deleted_at IS NULL
+ AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')
+ AND EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id)
+ AND NOT EXISTS (
+ SELECT 1 FROM content_chunks cc
+ WHERE cc.page_id = p.id AND NOT ${currentChunk}
+ )`,
+ params,
+ );
return (rows as unknown[]).length;
}
diff --git a/src/core/entities/resolve-on-save.ts b/src/core/entities/resolve-on-save.ts
index d5d530e1ba..21b9203afe 100644
--- a/src/core/entities/resolve-on-save.ts
+++ b/src/core/entities/resolve-on-save.ts
@@ -70,8 +70,8 @@ function isAbortError(err: unknown): boolean {
* resolver. Mutates `facts` in place. Sequential so a PGLite-pinned
* transaction sees one alias probe at a time.
*
- * Ordinary resolver failures keep the raw value and increment
- * resolution_errors. Abort and BudgetExhausted propagate.
+ * Unresolved references keep the fact unparented. Ordinary resolver failures
+ * increment resolution_errors. Abort and BudgetExhausted propagate.
*/
export async function resolveExtractedEntitiesForSave(
engine: BrainEngine,
@@ -85,7 +85,7 @@ export async function resolveExtractedEntitiesForSave(
if (raw === null) continue;
try {
const resolved = await resolveEntitySlugWithSource(engine, sourceId, raw);
- facts[i] = { ...facts[i], entity_slug: resolved?.slug ?? null };
+ facts[i] = { ...facts[i], entity_slug: resolved?.source === 'fallback_slugify' ? null : resolved?.slug ?? null };
if (!resolved) continue;
stats.counts[resolved.source] = (stats.counts[resolved.source] ?? 0) + 1;
if (resolved.source === 'fallback_slugify') {
@@ -93,6 +93,7 @@ export async function resolveExtractedEntitiesForSave(
}
} catch (err) {
if (isAbortError(err) || err instanceof BudgetExhausted) throw err;
+ facts[i] = { ...facts[i], entity_slug: null };
stats.resolution_errors++;
const message = err instanceof Error ? err.message : String(err);
onError?.(raw, message);
diff --git a/src/core/entities/resolve.ts b/src/core/entities/resolve.ts
index 7b250c563b..0e8e91bd5b 100644
--- a/src/core/entities/resolve.ts
+++ b/src/core/entities/resolve.ts
@@ -65,6 +65,10 @@ export async function resolveEntitySlug(
const aliased = await tryAliasExact(engine, source_id, trimmed);
if (aliased) return aliased;
+ const basenames = await findExactBasenameCandidates(engine, source_id, trimmed);
+ if (basenames.length === 1) return basenames[0].slug;
+ if (basenames.length > 1) return fallbackSlugify(trimmed);
+
// 2. Prefix-expansion match: when the input looks like a bare first name
// (no slash, no prefix, slugifies to a single short token), try
// `people/<token>-%` then `companies/<token>-%`. Short bare names
@@ -161,6 +165,25 @@ function isBareName(raw: string): boolean {
// doc would trip the ambiguity gate and re-break bare-token resolution.
const PREFIX_EXPANSION_DIRS = ['people', 'companies', 'hosts', 'projects'] as const;
+async function findExactBasenameCandidates(
+ engine: BrainEngine,
+ source_id: string,
+ raw: string,
+): Promise<Array<{ slug: string }>> {
+ const token = slugify(raw);
+ if (raw.includes('/') || !token.includes('-')) return [];
+ try {
+ return await engine.executeRaw<{ slug: string }>(
+ `SELECT slug FROM pages
+ WHERE source_id = $1 AND deleted_at IS NULL AND slug = ANY($2::text[])
+ LIMIT 2`,
+ [source_id, [...PREFIX_EXPANSION_DIRS, 'concepts'].map(dir => `${dir}/${token}`)],
+ );
+ } catch {
+ return [];
+ }
+}
+
/**
* v0.40.2.0 — resolution-source-tagged variant for trajectory routing.
*
@@ -199,6 +222,10 @@ export async function resolveEntitySlugWithSource(
const aliased = await tryAliasExact(engine, source_id, trimmed);
if (aliased) return { slug: aliased, source: 'alias_exact' };
+ const basenames = await findExactBasenameCandidates(engine, source_id, trimmed);
+ if (basenames.length === 1) return { slug: basenames[0].slug, source: 'fuzzy_match' };
+ if (basenames.length > 1) return { slug: fallbackSlugify(trimmed), source: 'fallback_slugify' };
+
if (isBareName(trimmed)) {
const expanded = await tryUnambiguousPrefixExpansion(engine, source_id, slugify(trimmed));
if (expanded) return { slug: expanded, source: 'fuzzy_match' };
diff --git a/src/core/facts/backstop.ts b/src/core/facts/backstop.ts
index 25a773f49d..74b23b4d30 100644
--- a/src/core/facts/backstop.ts
+++ b/src/core/facts/backstop.ts
@@ -628,7 +628,7 @@ async function runPipelineBodyInner(
const resolved = f.entity_slug
? await resolveEntitySlugWithSource(ctx.engine, ctx.sourceId, f.entity_slug)
: null;
- const resolvedSlug = resolved?.slug ?? null;
+ const resolvedSlug = resolved?.source === 'fallback_slugify' ? null : resolved?.slug ?? null;
const resolutionSource = resolved?.source ?? null;
// Dedup against DB candidates (correct per Codex Q7: fence rows
diff --git a/src/core/harness/install.ts b/src/core/harness/install.ts
index 5eb3e20cb9..8e8ff42497 100644
--- a/src/core/harness/install.ts
+++ b/src/core/harness/install.ts
@@ -123,7 +123,7 @@ async function installThinClient(c: HarnessCredentials, opts: InstallOptions, co
const launcher = join(root, 'bin', 'gbrain');
const files = [
{ path: '.gbrain/config.json', text: `${JSON.stringify(config, null, 2)}\n`, mode: 0o600 },
- { path: 'bin/gbrain', text: renderAgentLauncher({ root, bunPath: process.execPath, cliPath: sourceCli.includes('$bunfs') ? undefined : sourceCli, sourceId: c.source_id,
+ { path: 'bin/gbrain', text: renderAgentLauncher({ root, bunPath: process.execPath, cliPath: sourceCli.includes('$bunfs') ? undefined : sourceCli, mode: 'thin-client',
repairHint: `Reinstall GBrain in this environment, then repeat: gbrain connect ${shellQuote(c.mcp_url)} --harness ${shellQuote(opts.harness)} --credentials-file <private-handoff-file> --root ${shellQuote(root)} --install` }), mode: 0o700 },
{ path: 'GBRAIN-INSTRUCTIONS.md', text: `${GBRAIN_MCP_INSTRUCTIONS}\n\nRun commands with the absolute launcher: ${launcher}\nThis is a hosted connection. The host grant controls sources and permissions.\n`, mode: 0o600 },
];
diff --git a/src/core/import-file.ts b/src/core/import-file.ts
index 0b2ca3538d..e8aae49843 100644
--- a/src/core/import-file.ts
+++ b/src/core/import-file.ts
@@ -231,6 +231,11 @@ export interface ParsedPage {
tags: string[];
}
+export interface ImportEmbeddingResult {
+ status: 'embedded' | 'failed' | 'superseded';
+ error?: string;
+}
+
export interface ImportResult {
slug: string;
status: 'imported' | 'skipped' | 'error';
@@ -304,7 +309,9 @@ async function refreshSourcePath(engine: BrainEngine, slug: string, sourceId: st
/**
* Import content from a string. Core pipeline:
- * parse -> hash -> embed (external) -> transaction(version + putPage + tags + chunks)
+ * parse -> hash -> transaction(version + putPage + tags + chunks + beforeCommit).
+ * Embedding normally precedes persistence; onPostCommitEmbedding lets callers
+ * enrich outside their filesystem lock with page/chunk revision checks.
*
* Used by put_page operation and importFromFile.
*
@@ -388,6 +395,8 @@ export async function importFromContent(
* and reindex leave it unset so the guard stays armed.
*/
allowEmptyOverwrite?: boolean;
+ beforeCommit?: (tx: BrainEngine, slug: string) => Promise<void>;
+ onPostCommitEmbedding?: (complete: () => Promise<ImportEmbeddingResult>) => void;
} = {},
): Promise<ImportResult> {
// Normalize BEFORE any tx write: putPage lowercases via validateSlug but
@@ -753,8 +762,19 @@ export async function importFromContent(
tags: parsed.tags,
};
+ const persistUnchanged = async (refreshBody = false) => {
+ const write = async (tx: BrainEngine) => {
+ if (refreshBody) await tx.refreshPageBody(slug, sourceId ?? 'default', parsed.compiled_truth, parsed.timeline || '', hash);
+ await refreshSourcePath(tx, slug, sourceId, opts.sourcePath, existing?.source_path);
+ if (opts.beforeCommit) await verifyPageReadable(tx, slug, hash, sourceId, 'importFromContent');
+ await opts.beforeCommit?.(tx, slug);
+ };
+ if (opts.beforeCommit) await engine.transaction(write);
+ else await write(engine);
+ };
+
if (existing?.content_hash === hash && !opts.forceRechunk) {
- await refreshSourcePath(engine, slug, sourceId, opts.sourcePath, existing?.source_path);
+ await persistUnchanged();
return { slug, status: 'skipped', chunks: 0, parsedPage, ...(typeWarning ? { type_warning: typeWarning } : {}) };
}
@@ -772,14 +792,7 @@ export async function importFromContent(
frontmatter: parsed.frontmatter,
});
if (existing.content_hash === legacyHash) {
- await engine.refreshPageBody(
- slug,
- sourceId ?? 'default',
- parsed.compiled_truth,
- parsed.timeline || '',
- hash,
- );
- await refreshSourcePath(engine, slug, sourceId, opts.sourcePath, existing?.source_path);
+ await persistUnchanged(true);
return { slug, status: 'skipped', chunks: 0, parsedPage, ...(typeWarning ? { type_warning: typeWarning } : {}) };
}
}
@@ -884,9 +897,8 @@ export async function importFromContent(
}
}
- // Embed BEFORE the transaction (external API call).
- // v0.14+ (Codex C2): embedding failure PROPAGATES. Silent drop accumulates
- // unembedded pages invisibly. Caller can pass opts.noEmbed=true to skip.
+ // Embedding failures propagate unless onPostCommitEmbedding lets the caller
+ // report enrichment separately from the already-persisted content.
//
// v0.40.3.0 contextual retrieval wrapper (D20-T1 chunk_text separation):
// - Resolve effective CR mode via the page/source/global override chain.
@@ -942,7 +954,8 @@ export async function importFromContent(
effectiveCRMode = resolution.mode === 'per_chunk_synopsis' ? 'title' : resolution.mode;
}
- if (!opts.noEmbed && chunks.length > 0) {
+ const embedChunks = async () => {
+ if (opts.noEmbed || chunks.length === 0) return;
const safeTitle = sanitizeTitle(parsed.title);
const prefix =
modeRequiresWrapper(effectiveCRMode) && !modeRequiresSynopsis(effectiveCRMode)
@@ -958,7 +971,8 @@ export async function importFromContent(
// reflects what we actually sent to the embedder.
chunks[i].token_count = Math.ceil(wrappedTexts[i].length / 4);
}
- }
+ };
+ if (!opts.onPostCommitEmbedding) await embedChunks();
// v0.40.3.0: corpus_generation hash for D27 P1-5 cache invalidation.
// Only set when we actually applied a wrapper; 'none' tier writes NULL
@@ -976,11 +990,12 @@ export async function importFromContent(
// the service layer.
});
- // Transaction wraps all DB writes. Every per-page tx call carries the
+ // Transaction wraps the canonical DB writes. Every per-page tx call carries the
// caller's sourceId so writes target (sourceId, slug) rather than the
// schema DEFAULT — required for multi-source brains; harmless ('default')
// for single-source callers.
const txOpts = { sourceId: sourceId ?? 'default' };
+ let persistedRevision: { id: number; generation: string; chunk_id: number } | undefined;
await engine.transaction(async (tx) => {
if (existing) await tx.createVersion(slug, txOpts);
@@ -1030,7 +1045,7 @@ export async function importFromContent(
// UPDATE that runs after putPage's INSERT/UPDATE so the row exists.
// For opts.noEmbed callers, we skip stamping — the next embed pass
// (gbrain embed --stale or contextual reindex Minion) will set it.
- if (!opts.noEmbed) {
+ if (!opts.noEmbed && !opts.onPostCommitEmbedding) {
await tx.updatePageContextualRetrievalState(
slug,
sourceId ?? 'default',
@@ -1072,7 +1087,7 @@ export async function importFromContent(
// embedded (not --no-embed), so a later model/dims swap is detectable
// as stale via embed --stale. The deferred/backfill + per-slug embed
// paths stamp too; this covers the inline import/sync path.
- if (!opts.noEmbed) {
+ if (!opts.noEmbed && !opts.onPostCommitEmbedding) {
// D9: signature is null when the gateway is unconfigured — skip the
// stamp (a wrong signature is worse than none).
const importSig = currentEmbeddingSignature();
@@ -1125,6 +1140,17 @@ export async function importFromContent(
);
} catch { /* same reason — silent skip */ }
}
+ if (opts.onPostCommitEmbedding && !opts.noEmbed && chunks.length > 0) {
+ const rows = await tx.executeRaw<{ id: number; generation: string; chunk_id: number }>(
+ `SELECT id, generation::text AS generation,
+ (SELECT MIN(id) FROM content_chunks WHERE page_id = pages.id) AS chunk_id
+ FROM pages WHERE source_id = $1 AND slug = $2`,
+ [txOpts.sourceId, slug],
+ );
+ persistedRevision = rows[0];
+ }
+ if (opts.beforeCommit) await verifyPageReadable(tx, slug, hash, sourceId, 'importFromContent');
+ await opts.beforeCommit?.(tx, slug);
}).catch(async (err: unknown) => {
// #4287: name the dimension-mismatch rollback instead of letting the bare
// pgvector message ("expected N dimensions, not M") surface with no code,
@@ -1174,6 +1200,34 @@ export async function importFromContent(
// reads (get_page, search, query) until someone notices the gap manually.
await verifyPageReadable(engine, slug, hash, sourceId, 'importFromContent');
+ if (opts.onPostCommitEmbedding && !opts.noEmbed && chunks.length > 0) {
+ opts.onPostCommitEmbedding(async () => {
+ try {
+ await embedChunks();
+ return await engine.transaction(async (tx) => {
+ const rows = await tx.executeRaw<{ id: number; generation: string; chunk_id: number }>(
+ `SELECT id, generation::text AS generation,
+ (SELECT MIN(id) FROM content_chunks WHERE page_id = pages.id) AS chunk_id
+ FROM pages WHERE source_id = $1 AND slug = $2 AND deleted_at IS NULL FOR UPDATE`,
+ [txOpts.sourceId, slug],
+ );
+ const current = rows[0];
+ if (!persistedRevision || !current || current.id !== persistedRevision.id
+ || current.generation !== persistedRevision.generation || current.chunk_id !== persistedRevision.chunk_id) {
+ return { status: 'superseded' as const };
+ }
+ await tx.upsertChunks(slug, chunks, txOpts);
+ await tx.updatePageContextualRetrievalState(slug, txOpts.sourceId, effectiveCRMode, corpusGeneration);
+ const signature = currentEmbeddingSignature();
+ if (signature) await tx.setPageEmbeddingSignature(slug, { sourceId: txOpts.sourceId, signature });
+ return { status: 'embedded' as const };
+ });
+ } catch {
+ return { status: 'failed', error: 'Page content was saved, but embedding failed. Check the embedding provider and database on the brain host, then run gbrain embed --stale --source <source-id>.' };
+ }
+ });
+ }
+
return {
slug,
status: 'imported',
diff --git a/src/core/minions/handlers/subagent-persistence.ts b/src/core/minions/handlers/subagent-persistence.ts
index ab5a004a7e..ad795241e8 100644
--- a/src/core/minions/handlers/subagent-persistence.ts
+++ b/src/core/minions/handlers/subagent-persistence.ts
@@ -11,6 +11,7 @@
import type { BrainEngine } from '../../engine.ts';
import type { ContentBlock, SubagentResult } from '../types.ts';
import { UnrecoverableError } from '../types.ts';
+import { putPageRejection } from '../tools/put-page-result.ts';
export interface PersistedMessage {
message_idx: number;
@@ -230,8 +231,8 @@ export async function persistToolExecComplete(
* dispatches that never settled) count toward NEITHER side.
*
* When the submitter set `require_writes` (dream synthesize / patterns
- * fan-out — jobs whose entire purpose is writing pages), attempted > 0 with
- * zero successes throws UnrecoverableError: retrying is provably futile (the
+ * fan-out — jobs whose entire purpose is writing pages), zero successes
+ * throws UnrecoverableError: retrying is provably futile (the
* replay path short-circuits to the persisted terminal turn and can never
* re-run the failed tools), so the job routes straight to dead and the
* idempotency key releases for the next cycle.
@@ -246,13 +247,13 @@ export async function finalizeWriteAccounting(
result: SubagentResult,
opts: { requireWrites: boolean; scopeToolUseIdPrefix?: string },
): Promise<SubagentResult> {
- let rows: Array<{ status: string; error: string | null }>;
+ let rows: Array<{ status: string; error: string | null; output: unknown }>;
try {
- rows = await engine.executeRaw<{ status: string; error: string | null }>(
+ rows = await engine.executeRaw<{ status: string; error: string | null; output: unknown }>(
opts.scopeToolUseIdPrefix
- ? `SELECT status, error FROM subagent_tool_executions
+ ? `SELECT status, error, output FROM subagent_tool_executions
WHERE job_id = $1 AND tool_name = 'brain_put_page' AND tool_use_id LIKE $2`
- : `SELECT status, error FROM subagent_tool_executions
+ : `SELECT status, error, output FROM subagent_tool_executions
WHERE job_id = $1 AND tool_name = 'brain_put_page'`,
opts.scopeToolUseIdPrefix ? [jobId, `${opts.scopeToolUseIdPrefix}%`] : [jobId],
);
@@ -271,8 +272,12 @@ export async function finalizeWriteAccounting(
process.stderr.write(`[subagent] write accounting read failed for job ${jobId}: ${e instanceof Error ? e.message : String(e)}\n`);
return result;
}
- const written = rows.filter(r => r.status === 'complete').length;
- const failed = rows.filter(r => r.status === 'failed').length;
+ const settled = rows.filter(r => r.status === 'complete' || r.status === 'failed').map(row => {
+ const rejection = row.status === 'complete' ? putPageRejection(row.output) : null;
+ return rejection ? { ...row, status: 'failed', error: rejection } : row;
+ });
+ const written = settled.filter(r => r.status === 'complete').length;
+ const failed = settled.filter(r => r.status === 'failed').length;
const attempted = written + failed;
const accounted: SubagentResult = {
...result,
@@ -281,19 +286,16 @@ export async function finalizeWriteAccounting(
pages_failed: failed,
};
if (opts.requireWrites && attempted > 0 && written === 0) {
- const firstError = rows.find(r => r.status === 'failed' && r.error)?.error ?? 'unknown write error';
+ const firstError = settled.find(r => r.status === 'failed' && r.error)?.error ?? 'unknown write error';
throw new UnrecoverableError(
`all ${failed} put_page write(s) failed — job produced zero pages (first error: ${firstError})`,
);
}
- // Zero attempts is legitimate ONLY as a clean-finish skip (Task D ends
- // 'end_turn' with prose). A truncated / refused / turn-capped / errored
- // run that never reached put_page is a failure wearing a completion — it
- // would consume the idempotency key and stamp the cooldown, silently
- // dropping the transcript. Dead-letter it (key releases; nightly retries).
- if (opts.requireWrites && attempted === 0 && result.stop_reason !== 'end_turn') {
+ if (opts.requireWrites && attempted === 0) {
throw new UnrecoverableError(
- `job produced zero put_page writes and did not finish cleanly (stop_reason: ${result.stop_reason}) — not a legitimate skip`,
+ result.stop_reason === 'end_turn'
+ ? 'job produced zero required put_page writes — a clean model finish does not satisfy require_writes'
+ : `job produced zero put_page writes and did not finish cleanly (stop_reason: ${result.stop_reason}) — not a legitimate skip`,
);
}
return accounted;
diff --git a/src/core/minions/tools/brain-allowlist.ts b/src/core/minions/tools/brain-allowlist.ts
index 4373261c6b..33bd524c42 100644
--- a/src/core/minions/tools/brain-allowlist.ts
+++ b/src/core/minions/tools/brain-allowlist.ts
@@ -33,6 +33,7 @@ import { parseMarkdown, serializeMarkdown } from '../../markdown.ts';
import { loadActivePackForWriteVocabulary } from '../../schema-pack/write-vocabulary.ts';
import { classifyStoredType, sanitizeTypeForDisplay } from '../../schema-pack/type-usage.ts';
import type { ToolCtx, ToolDef } from '../types.ts';
+import { putPageRejection } from './put-page-result.ts';
/**
* v0.15 brain-tool allow-list. Review carefully when extending. Op names
@@ -325,7 +326,10 @@ export function buildBrainTools(opts: BuildBrainToolsOpts): ToolDef[] {
if (op.name === 'put_page' && opts.allowedSlugPrefixes?.length) {
await pinUndeclaredType(params, opCtx);
}
- return op.handler(opCtx, params);
+ const output = await op.handler(opCtx, params);
+ const rejection = op.name === 'put_page' ? putPageRejection(output) : null;
+ if (rejection) throw new Error(rejection);
+ return output;
},
};
});
diff --git a/src/core/minions/tools/put-page-result.ts b/src/core/minions/tools/put-page-result.ts
new file mode 100644
index 0000000000..a58b089143
--- /dev/null
+++ b/src/core/minions/tools/put-page-result.ts
@@ -0,0 +1,12 @@
+export function putPageRejection(output: unknown): string | null {
+ if (typeof output === 'string') {
+ try { output = JSON.parse(output); } catch { return null; }
+ }
+ if (!output || typeof output !== 'object' || Array.isArray(output)) return null;
+ const result = output as Record<string, unknown>;
+ if (result.status === 'error'
+ || (result.status === 'skipped' && typeof result.error === 'string' && result.error.length > 0)) {
+ return 'brain_put_page: page content was rejected before persistence. Check the page size and YAML frontmatter, then retry.';
+ }
+ return null;
+}
diff --git a/src/core/minions/types.ts b/src/core/minions/types.ts
index cb065c36a1..f83317ee9a 100644
--- a/src/core/minions/types.ts
+++ b/src/core/minions/types.ts
@@ -558,9 +558,9 @@ export interface SubagentHandlerData {
*/
source_id?: string;
/**
- * #4217 — when true, a job whose put_page writes were ALL attempted-and-
- * failed FAILS (UnrecoverableError → dead, idempotency key released)
- * instead of reporting `completed` with zero pages. Set by the dream
+ * When true, a job must complete at least one put_page write or FAIL
+ * (UnrecoverableError → dead, idempotency key released) instead of
+ * reporting `completed` with zero pages. Set by the dream
* synthesize + patterns fan-outs (jobs whose entire purpose is writing
* pages). Left unset for open-ended `gbrain agent run` jobs, where one
* rejected write plus a useful read-only answer is a legitimate
diff --git a/src/core/ops/pages.ts b/src/core/ops/pages.ts
index 431f2dfd99..8d78343998 100644
--- a/src/core/ops/pages.ts
+++ b/src/core/ops/pages.ts
@@ -10,9 +10,11 @@
import type { BrainEngine } from '../engine.ts';
import { clampSearchLimit } from '../engine.ts';
import type { Page, PageType } from '../types.ts';
-import { importFromContent } from '../import-file.ts';
+import { importFromContent, type ImportEmbeddingResult } from '../import-file.ts';
import { serializePageToMarkdown } from '../markdown.ts';
-import { writePageThrough, deletePageThrough, resolvePageWriteTarget, withNoRepoWriteThroughWarning, type WriteThroughResult } from '../write-through.ts';
+import { writePageThrough, deletePageThrough, resolvePageWriteTarget, isWriteThroughDisabled, withNoRepoWriteThroughWarning, type WriteThroughResult } from '../write-through.ts';
+import { hasSourceFilesystemLock, withSourceFilesystemLock, assertSourceFilesystemActive } from '../minions/source-filesystem.ts';
+import { LockUnavailableError } from '../db-lock.ts';
import { extractPageLinks, isAutoLinkEnabled, isAutoTimelineEnabled, isGlobalBasenameEnabled, parseTimelineEntries, makeResolver, type UnresolvedFrontmatterRef } from '../link-extraction.ts';
// #3190: pack-aware link typing on the put_page auto-link path.
import { loadActivePackForLocalEngine } from '../schema-pack/best-effort.ts';
@@ -349,7 +351,7 @@ const put_page: Operation = {
},
mutating: true,
scope: 'write',
- handler: async (ctx, p) => {
+ handler: async function putPage(ctx, p, deferEmbedding?: (complete: () => Promise<ImportEmbeddingResult>) => void): Promise<Record<string, unknown>> {
const slug = p.slug as string;
validatePageSlug(slug);
@@ -390,6 +392,32 @@ const put_page: Operation = {
if (ctx.dryRun) return { dry_run: true, action: 'put_page', slug: p.slug };
+ const isSandboxSubagent = ctx.viaSubagent === true
+ && !(Array.isArray(ctx.allowedSlugPrefixes) && ctx.allowedSlugPrefixes.length > 0);
+ if (!isSandboxSubagent && !(await isWriteThroughDisabled(ctx.engine))) {
+ const target = await resolvePageWriteTarget(ctx.engine, slug.toLowerCase(), ctx.sourceId ?? 'default');
+ if (!target.ok) {
+ requirePageWriteThrough({ written: false, skipped: target.skipped });
+ } else if (!hasSourceFilesystemLock(target.writeRoot)) {
+ let entered = false;
+ let completeEmbedding: (() => Promise<ImportEmbeddingResult>) | undefined;
+ try {
+ const result = await withSourceFilesystemLock(ctx.engine, target.writeRoot, () => {
+ entered = true;
+ return putPage(ctx, p, complete => { completeEmbedding = complete; });
+ });
+ return { ...result, ...(completeEmbedding ? { embedding: await completeEmbedding() } : {}) };
+ } catch (err) {
+ if (entered || !(err instanceof LockUnavailableError)) throw err;
+ throw new OperationError(
+ 'storage_busy',
+ 'put_page: the source worktree is busy. This write was not applied and was not queued.',
+ 'Wait for the current source operation to finish, then read the latest page and retry. No durable write queue is available.',
+ );
+ }
+ }
+ }
+
// Empty-overwrite guard: empty/whitespace-only content over an existing
// non-empty page is almost always an input-plumbing failure (e.g. a
// caller that meant file input — put has no --file flag — so the missing
@@ -444,8 +472,23 @@ const put_page: Operation = {
// Pack load failed; fall through to legacy inferType behavior.
activePack = undefined;
}
+ let writeThrough: (Omit<WriteThroughResult, 'skipped'> & { skipped?: WriteThroughResult['skipped'] | 'subagent_sandbox' }) | undefined;
+ const persistPage = async (engine: BrainEngine, resolvedSlug: string) => {
+ const via = ctx.remote === false ? 'put_page' : 'mcp:put_page';
+ const written = await writePageThrough(engine, resolvedSlug, {
+ sourceId: ctx.sourceId ?? 'default',
+ frontmatterOverrides: { ingested_via: via, ingested_at: new Date().toISOString(), source_kind: via },
+ logger: ctx.logger,
+ });
+ requirePageWriteThrough(written);
+ assertSourceFilesystemActive();
+ writeThrough = written;
+ };
+ let completeEmbedding: (() => Promise<ImportEmbeddingResult>) | undefined;
const result = await importFromContent(ctx.engine, slug, p.content as string, {
noEmbed,
+ onPostCommitEmbedding: complete => { completeEmbedding = complete; },
+ ...(!isSandboxSubagent ? { beforeCommit: persistPage } : {}),
// v0.42 (#1699): untrusted callers can't smuggle gate-owned frontmatter
// markers (quarantine/content_flag/embed_skip). Fail-closed — anything
// not strictly local is remote (matches CV6 / v0.26.9 F7b posture).
@@ -528,76 +571,10 @@ const put_page: Operation = {
}
}
- // v0.38 put_page write-through (ingestion cathedral):
- // After importFromContent succeeds, if `sync.repo_path` resolves to a
- // real directory, persist the markdown file to disk alongside the DB
- // row. A failure here is fatal to the call (see the check right below)
- // except for the deliberate DB-only configurations.
- //
- // Trust gating:
- // - Subagent sandbox (viaSubagent without allowedSlugPrefixes) → DB-only.
- // - All other writes → write-through.
- // put_page's own trust-gating produces two skip reasons ('subagent_sandbox',
- // 'dry_run') that never come out of writePageThrough itself — widen the
- // field rather than losing the commit/pushed/lastPushStatus typing.
- let writeThrough: (Omit<WriteThroughResult, 'skipped'> & { skipped?: WriteThroughResult['skipped'] | 'subagent_sandbox' | 'dry_run' }) | undefined;
- const isSandboxSubagent = ctx.viaSubagent === true
- && !(Array.isArray(ctx.allowedSlugPrefixes) && ctx.allowedSlugPrefixes.length > 0);
- if (!ctx.dryRun && result.status !== 'error' && !isSandboxSubagent) {
- const sourceId = ctx.sourceId ?? 'default';
- const provenanceVia = ctx.remote === false ? 'put_page' : 'mcp:put_page';
- // Shared canonical write-through (also used by `gbrain brainstorm/lsd
- // --save`). Renders the file from the saved DB row and writes it
- // atomically; never throws (failures land in skipped/error).
- writeThrough = await writePageThrough(ctx.engine, result.slug, {
- sourceId,
- frontmatterOverrides: {
- ingested_via: provenanceVia,
- ingested_at: new Date().toISOString(),
- source_kind: provenanceVia,
- },
- logger: ctx.logger,
- });
+ if (!writeThrough && result.parsedPage && result.status !== 'error' && !isSandboxSubagent) {
+ await persistPage(ctx.engine, result.slug);
} else if (isSandboxSubagent) {
writeThrough = { written: false, skipped: 'subagent_sandbox' };
- } else if (ctx.dryRun) {
- writeThrough = { written: false, skipped: 'dry_run' };
- }
-
- // The markdown file is the system of record (docs/architecture/
- // system-of-record.md); the DB row is a derived cache. The deliberate,
- // by-design DB-only outcomes are `no_repo_configured` (no `sync.repo_path`
- // set at all), `disabled_by_config` (operator opted out via
- // `sync.write_through=false`), `subagent_sandbox`, and `dry_run` (no real
- // write was supposed to happen). Every other non-written outcome — a
- // thrown write error, or a guard that REFUSED to write into an existing
- // repo (missing dir, sibling-source collision, escaped path, case-fold
- // clash, unreadable row) — means a file was supposed to exist and
- // doesn't, so put_page must not report success.
- if (writeThrough && !writeThrough.written
- && writeThrough.skipped !== 'no_repo_configured'
- && writeThrough.skipped !== 'disabled_by_config'
- && writeThrough.skipped !== 'subagent_sandbox'
- && writeThrough.skipped !== 'dry_run') {
- // Roll back rather than leave an index-only orphan, but only when this
- // call is what created the row: created_at === updated_at is set by
- // the SAME insert statement (the ON CONFLICT UPDATE branch never
- // touches created_at), so equality here means "brand new, this call."
- // An update (or a dedup hit resolved to a pre-existing page) is left
- // alone — the prior file on disk still matches the prior DB content.
- try {
- const row = await ctx.engine.getPage(result.slug, { sourceId: ctx.sourceId ?? 'default' });
- if (row && row.created_at.getTime() === row.updated_at.getTime()) {
- await ctx.engine.deletePage(result.slug, { sourceId: ctx.sourceId ?? 'default' });
- }
- } catch {
- // best-effort; the error thrown below still surfaces the failure
- }
- throw new OperationError(
- 'storage_error',
- `put_page: the page content could not be written to disk (${writeThrough.skipped ?? writeThrough.error}).`,
- 'Check that the configured repo path exists and is writable, then retry.',
- );
}
// Auto-link post-hook: runs AFTER importFromContent (which is its own
@@ -815,10 +792,16 @@ const put_page: Operation = {
}
}
+ let embedding: ImportEmbeddingResult | undefined;
+ if (completeEmbedding) {
+ if (deferEmbedding) deferEmbedding(completeEmbedding);
+ else embedding = await completeEmbedding();
+ }
return {
slug: result.slug,
status: result.status === 'imported' ? 'created_or_updated' : result.status,
chunks: result.chunks,
+ ...(embedding ? { embedding } : {}),
// #3984: a skipped/error status without the reason is a silent no-op to
// MCP callers (e.g. the >5MB size guard returned bare status 'skipped'
// and the agent had no idea why the page never appeared). Thread
@@ -837,6 +820,15 @@ const put_page: Operation = {
cliHints: { name: 'put', positional: ['slug'], stdin: 'content' },
};
+function requirePageWriteThrough(result: WriteThroughResult): void {
+ if (result.written || result.skipped === 'no_repo_configured' || result.skipped === 'disabled_by_config') return;
+ throw new OperationError(
+ 'storage_error',
+ `put_page: the page content could not be written to disk (${result.skipped ?? result.error}).`,
+ 'Check that the configured repo path exists and is writable, then retry.',
+ );
+}
+
// v0.31.2: isFactsBackstopEligible moved to src/core/facts/eligibility.ts
// so sync.ts, file_upload, code_import, and runFactsBackstop all share one
// predicate. Imported above.
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index fdfd962634..4f1a343fc2 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -70,6 +70,7 @@ import { acquireLock, releaseLock, type LockHandle } from './pglite-lock.ts';
// connect() catch. No cycle: pglite-repair.ts imports nothing from this file.
import { attemptWalRepairAndRetry, closeRepairEpisodeIfOpen, type WalRepairReceipt } from './pglite-repair.ts';
import { getFtsLanguage } from './fts-language.ts';
+import { splitEmbeddingSignature, currentSpaceChunkPredicate } from './embedding-invalidation.ts';
import type {
Page, PageInput, PageFilters, PageType,
Chunk, ChunkInput, StaleChunkRow, StalePageRow, ChunklessPageRow,
@@ -3423,15 +3424,9 @@ export class PGLiteEngine implements BrainEngine {
}
async invalidateStaleSignatureEmbeddings(opts: { signature: string; sourceId?: string; includeNullSignature?: boolean }): Promise<number> {
- // NULL out embeddings whose page signature is set AND differs from the
- // current model signature. GRANDFATHER: NULL signature untouched —
- // UNLESS includeNullSignature (#3391): provider migrations must not
- // leave pre-stamp pages in the old embedding space. Feeds the existing
- // NULL-embedding cursor so listStaleChunks stays unchanged. S2: keyed on
- // the registry-ACTIVE column (loud resolver failure — destructive writes
- // never guess).
const colId = await this.activeEmbeddingColId();
- const params: unknown[] = [opts.signature];
+ const { model, dims } = splitEmbeddingSignature(opts.signature);
+ const params: unknown[] = [opts.signature, model, dims];
let srcClause = '';
if (opts.sourceId !== undefined) {
params.push(opts.sourceId);
@@ -3447,6 +3442,7 @@ export class PGLiteEngine implements BrainEngine {
FROM pages p
WHERE cc.page_id = p.id
AND cc.${colId} IS NOT NULL
+ AND NOT ${currentSpaceChunkPredicate(colId, 2, 3)}
AND ${sigClause}${srcClause}
RETURNING cc.page_id`,
params,
diff --git a/src/core/pglite-lock.ts b/src/core/pglite-lock.ts
index 94fb41049d..2921220ab7 100644
--- a/src/core/pglite-lock.ts
+++ b/src/core/pglite-lock.ts
@@ -18,6 +18,7 @@ import { mkdirSync, existsSync, readFileSync, writeFileSync, rmSync, statSync, r
import { join } from 'path';
import { execFileSync } from 'node:child_process';
import { parseGlobalFlags } from './cli-options.ts';
+import { readProcessCommand, type ProcessCommandProbeDeps } from './autopilot-lock.ts';
const LOCK_DIR_NAME = '.gbrain-lock';
const LOCK_FILE = 'lock';
@@ -237,12 +238,14 @@ export function isProcessAlive(pid: number): boolean {
* Read a process's full command line, or null when it can't be determined.
* `ps -o args=` works on Linux + macOS (same pattern as autopilot-lock's
* readProcessCommand); the /proc fallback covers minimal Linux containers
- * where `ps` is absent (cf. #4300). Null means "unknowable" — callers must
- * treat it as ALIVE, never as evidence of death.
+ * where `ps` is absent (cf. #4300). Windows uses the shared CIM probe.
+ * Null means "unknowable" — callers must treat it as ALIVE, never as death.
*/
-function readProcessArgs(pid: number): string | null {
+function readProcessArgs(pid: number, deps?: ProcessCommandProbeDeps): string | null {
+ if ((deps?.platform ?? process.platform) === 'win32') return readProcessCommand(pid, deps);
+ const exec = deps?.execFile ?? execFileSync;
try {
- const out = execFileSync('ps', ['-p', String(pid), '-o', 'args='], {
+ const out = exec('ps', ['-p', String(pid), '-o', 'args='], {
encoding: 'utf8',
stdio: ['ignore', 'pipe', 'ignore'],
timeout: 1000,
@@ -250,8 +253,8 @@ function readProcessArgs(pid: number): string | null {
if (out.length > 0) return out;
} catch { /* fall through to /proc */ }
try {
- const raw = readFileSync(`/proc/${pid}/cmdline`, 'utf-8');
- const args = raw.replace(/\0/g, ' ').trim();
+ const raw = (deps?.readCmdlineFile ?? readFileSync)(`/proc/${pid}/cmdline`);
+ const args = raw.toString().replace(/\0/g, ' ').trim();
if (args.length > 0) return args;
} catch { /* unreadable — unknowable */ }
return null;
@@ -294,33 +297,37 @@ function readBootId(): string | null {
* the PID — a dead holder's PID can be recycled by an unrelated program
* (docker-proxy, a shell, a supervisor's next child), which previously wedged
* the lock until acquire timeout with no automatic recovery. A command line
- * that matches neither "gbrain" nor the recorded command's first token is
- * affirmative proof the original holder is gone — equivalent to an ESRCH
- * verdict — so the lock can be reaped.
+ * that matches neither "gbrain" nor the structured argv's script identity
+ * can prove reuse. Legacy command-only locks cannot preserve path boundaries
+ * and never authorize cmdline-based reaping; ESRCH still recovers dead holders.
*
* Fail-safe like isProcessAlive: ANY doubt reads as "not reused" (alive) —
* unreadable/missing command line, a same-process PID (#1963 semantics: a
* second acquire from the holder process still waits out the timeout), or
* missing/mismatched namespace markers. On Linux the cmdline verdict REQUIRES
- * affirmative same-namespace proof (lock's recorded pid_ns === ours; boot_id
- * must also match when both are recorded): legacy locks without markers are
+ * affirmative same-namespace proof (both recorded pid_ns and boot_id must be
+ * readable and match ours): legacy locks without markers are
* never cmdline-reaped (ESRCH reaps still apply). Platforms without namespace
* markers (macOS) have no reachable cross-namespace data-dir sharing — a
* Docker VM's PIDs aren't visible to host `ps` at all — so the cmdline
* verdict stands alone there.
*/
-function isPidReusedByOtherProgram(
+export function isPidReusedByOtherProgram(
pid: number,
- recordedCommand: unknown,
+ recordedArgv: unknown,
recordedPidNs: unknown,
recordedBootId: unknown,
+ deps?: ProcessCommandProbeDeps,
): boolean {
if (!Number.isInteger(pid) || pid <= 0) return false;
// Same-process re-acquire: WE are the recorded holder, so the PID is by
// definition not recycled. (Also keeps non-gbrain test harnesses that hold a
// lock with their own PID from reaping themselves.)
if (pid === process.pid) return false;
- if (process.platform === 'linux') {
+ if (!Array.isArray(recordedArgv) || recordedArgv.length === 0
+ || !recordedArgv.every(arg => typeof arg === 'string')
+ || recordedArgv[0].trim().length === 0) return false;
+ if ((deps?.platform ?? process.platform) === 'linux') {
// Linux: cmdline evidence is only meaningful within one PID namespace on
// one host, so EVERY marker must be readable AND matching — pid_ns rules
// out other containers, boot_id rules out other hosts (pid_ns inode
@@ -333,25 +340,16 @@ function isPidReusedByOtherProgram(
if (recordedPidNs !== ourNs) return false;
if (recordedBootId !== ourBoot) return false;
}
- const cmdline = readProcessArgs(pid);
+ const cmdline = readProcessArgs(pid, deps);
if (cmdline === null) return false; // unknowable — cannot prove reuse
- if (cmdline.includes('gbrain')) return false;
- if (typeof recordedCommand === 'string' && recordedCommand.length > 0) {
- const firstToken = recordedCommand.trim().split(/\s+/)[0];
- if (firstToken && cmdline.includes(firstToken)) return false;
- // False-steal hardening: the recorded first token is often an ABSOLUTE
- // script path (Bun normalizes argv[1]) while `ps`/procfs report the
- // spawn-time RELATIVE form (`bun run src/cli.ts serve …`), so the literal
- // includes() above never matches and a LIVE holder gets classified as
- // recycled — observed as a harness mint stealing a running serve's lock
- // and writing its token to a second PGLite instance the serve never
- // sees. Compare the token's basename too: an unrelated program that
- // genuinely recycled the PID is no more likely to carry `cli.ts` in its
- // argv than the full path, so precision holds.
- const baseToken = firstToken ? firstToken.split('/').pop() : undefined;
- if (baseToken && baseToken.length > 0 && cmdline.includes(baseToken)) return false;
- }
- return true;
+ const isWin32 = (deps?.platform ?? process.platform) === 'win32';
+ const normalize = (s: string) => isWin32 ? s.toLowerCase().replace(/\\/g, '/') : s;
+ const normalizedCommand = normalize(cmdline);
+ if (normalizedCommand.includes('gbrain')) return false;
+ const scriptPath = recordedArgv[0];
+ if (normalizedCommand.includes(normalize(scriptPath))) return false;
+ const scriptName = scriptPath.split(/[\\/]/).pop();
+ return !!scriptName && !normalizedCommand.includes(normalize(scriptName));
}
const REAP_CLAIM_TTL_MS = 30_000;
@@ -571,7 +569,7 @@ export async function acquireLock(dataDir: string | undefined, opts?: { timeoutM
// dead PID (ESRCH) or a PID provably recycled by a non-gbrain program
// (cmdline mismatch under affirmative same-namespace proof) is.
const alive = isProcessAlive(lockPid)
- && !isPidReusedByOtherProgram(lockPid, lockData.command, lockData.pid_ns, lockData.boot_id);
+ && !isPidReusedByOtherProgram(lockPid, lockData.argv, lockData.pid_ns, lockData.boot_id);
if (!alive) {
// Holder process is gone — reap and try to acquire. This verdict is
// affirmative (kill-0 threw ESRCH; EPERM reads as alive), so no
@@ -643,6 +641,7 @@ export async function acquireLock(dataDir: string | undefined, opts?: { timeoutM
acquired_at: now,
refreshed_at: now,
command: process.argv.slice(1).join(' '),
+ argv: process.argv.slice(1),
subcommand: parseGlobalFlags(process.argv.slice(2)).rest[0] ?? null,
pid_ns: readPidNs(),
boot_id: readBootId(),
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index 41d2ccce58..232a1d63bd 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -58,6 +58,7 @@ import {
EmbeddingColumnNotRegisteredError,
} from './search/embedding-column.ts';
import { getFtsLanguage, applyFtsLanguagePolicy } from './fts-language.ts';
+import { splitEmbeddingSignature, currentSpaceChunkPredicate } from './embedding-invalidation.ts';
import { SAFE_FENCE_CHUNKER_VERSION, bodyWriteChunkVersion, chunkWriteInvalidation, requiresSafeChunks, safeChunksFilter } from './search/safe-chunks.ts';
import type {
Page, PageInput, PageFilters, PageType,
@@ -2642,14 +2643,9 @@ export class PostgresEngine implements BrainEngine {
}
async invalidateStaleSignatureEmbeddings(opts: { signature: string; sourceId?: string; includeNullSignature?: boolean }): Promise<number> {
- // NULL embeddings whose page signature is set AND differs from current.
- // GRANDFATHER: NULL signature untouched — UNLESS includeNullSignature
- // (#3391): provider migrations must not leave pre-stamp pages in the old
- // embedding space. Feeds the NULL-embedding cursor so listStaleChunks
- // stays unchanged. RETURNING → row count. S2: keyed on the registry-
- // ACTIVE column (loud resolver failure — destructive writes never guess).
const colId = await this.activeEmbeddingColId();
- const params: unknown[] = [opts.signature];
+ const { model, dims } = splitEmbeddingSignature(opts.signature);
+ const params: unknown[] = [opts.signature, model, dims];
let srcClause = '';
if (opts.sourceId !== undefined) {
params.push(opts.sourceId);
@@ -2665,6 +2661,7 @@ export class PostgresEngine implements BrainEngine {
FROM pages p
WHERE cc.page_id = p.id
AND cc.${colId} IS NOT NULL
+ AND NOT ${currentSpaceChunkPredicate(colId, 2, 3)}
AND ${sigClause}${srcClause}
RETURNING cc.page_id`,
params as Parameters<typeof this.sql.unsafe>[1],
diff --git a/src/core/sync-git.ts b/src/core/sync-git.ts
index 08a04f7a8b..c6c1692a4d 100644
--- a/src/core/sync-git.ts
+++ b/src/core/sync-git.ts
@@ -604,6 +604,14 @@ interface PathContainmentOps {
const nativePathContainmentOps: PathContainmentOps = { relative, isAbsolute, sep };
+export function gitRelativePath(
+ from: string,
+ to: string,
+ pathOps: Pick<PathContainmentOps, 'relative'> = nativePathContainmentOps,
+): string {
+ return pathOps.relative(from, to).replace(/\\/g, '/');
+}
+
export function isWithinRoot(
childReal: string,
rootReal: string,
diff --git a/src/core/sync-reconcile.ts b/src/core/sync-reconcile.ts
index 7fd88b6344..1a2889ddfb 100644
--- a/src/core/sync-reconcile.ts
+++ b/src/core/sync-reconcile.ts
@@ -61,7 +61,7 @@ export function planReconcileDeletes(
const current = new Set<string>();
for (const f of currentFiles) current.add(normalizeReconcilePath(f));
const reconcilable = rows.filter(
- r => r.source_path != null && isSyncablePath(r.source_path),
+ r => r.source_path != null && isSyncablePath(normalizeReconcilePath(r.source_path)),
);
const staleSlugs = reconcilable
.filter(r => !current.has(normalizeReconcilePath(r.source_path as string)))
diff --git a/src/core/write-through.ts b/src/core/write-through.ts
index fe931b2d98..a42367b79b 100644
--- a/src/core/write-through.ts
+++ b/src/core/write-through.ts
@@ -22,9 +22,9 @@ import { hasSourceFilesystemLock, withSourceFilesystemLock, assertSourceFilesyst
* only does "row exists + repo is a real dir → render + atomic write".
*/
-import { existsSync, statSync, mkdirSync, writeFileSync, renameSync, unlinkSync, readdirSync } from 'fs';
+import { existsSync, statSync, mkdirSync, unlinkSync, readdirSync } from 'fs';
import { basename, dirname, isAbsolute, join, relative, resolve } from 'path';
-import { randomBytes } from 'crypto';
+import { atomicWriteFileSync } from './atomic-write.ts';
import type { BrainEngine } from './engine.ts';
import { serializePageToMarkdown, resolvePageFilePath, resolveSourceLocalFilePath } from './markdown.ts';
import { isWriteTargetContained, msysToNativePath } from './path-confine.ts';
@@ -364,8 +364,8 @@ export async function resolvePageWriteTarget(
/**
* Render the DB row for `slug` to markdown and atomically write it under
* `sync.repo_path`. Never throws — failures are reported via the result's
- * `skipped` / `error` fields (the DB write is the durable sink; the file is
- * best-effort and reconciled by the next `gbrain sync`).
+ * `skipped` / `error` fields. put_page calls it before its transaction commits
+ * and rejects non-deliberate skips so a file failure rolls back the DB write.
*/
export async function writePageThrough(
engine: BrainEngine,
@@ -432,42 +432,17 @@ export async function writePageThrough(
assertSourceFilesystemActive();
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
- // Atomic write: unique temp sibling + rename. Unique name (pid + random)
- // so two concurrent saves to the same target can't clobber each other's
- // temp file. Clean up the temp on any failure so we never leak a stray
- // `.tmp` next to the real file.
- const tmpPath = `${filePath}.tmp.${process.pid}.${randomBytes(4).toString('hex')}`;
- try {
- writeFileSync(tmpPath, md, 'utf8');
- renameSync(tmpPath, filePath);
- } catch (writeErr) {
- try {
- if (existsSync(tmpPath)) unlinkSync(tmpPath);
- } catch {
- // best-effort cleanup; surface the original write error below
- }
- throw writeErr;
- }
-
- // #4247: a page born via put/capture/reverse-write keeps source_path=NULL
- // forever — mtime-watermark incremental sync never rescans an untouched
- // file — so bind the just-materialized file of record now. NULL-guarded so
- // a scanner-recorded path is never rewritten; best-effort because row and
- // file are already durable and a full sync can still heal the bookkeeping.
- try {
- await engine.executeRaw(
- `UPDATE pages
- SET source_path = $1
- WHERE source_id = $2
- AND slug = $3
- AND deleted_at IS NULL
- AND source_path IS NULL`,
- [sourcePathToBind, sourceId, slug],
- );
- } catch (bindErr) {
- const msg = bindErr instanceof Error ? bindErr.message : String(bindErr);
- opts.logger?.warn(`[write-through] wrote ${slug} but could not bind source_path: ${msg}`);
- }
+ await engine.executeRaw(
+ `UPDATE pages
+ SET source_path = $1
+ WHERE source_id = $2
+ AND slug = $3
+ AND deleted_at IS NULL
+ AND source_path IS NULL`,
+ [sourcePathToBind, sourceId, slug],
+ );
+ assertSourceFilesystemActive();
+ atomicWriteFileSync(filePath, md, { verify: () => assertSourceFilesystemActive() });
// #2426: on a durability-hardened repo (user ran `gbrain sources harden`),
// commit the artifact so it reaches git — pre-fix, write-through content
diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.md
index a693ecd295..425f748745 100644
--- a/templates/bootstrap/template-repo/README.md
+++ b/templates/bootstrap/template-repo/README.md
@@ -1,6 +1,6 @@
# gbrain agent workspace — template
-<!-- gbrain-template-stamp: 0.50.1.0 -->
+<!-- gbrain-template-stamp: 0.50.2.0 -->
This repository is the **"Use this template"** distribution artifact for a
[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the same
diff --git a/test/autopilot-global-maintenance.test.ts b/test/autopilot-global-maintenance.test.ts
index 8f53d1b9e2..4275464dfb 100644
--- a/test/autopilot-global-maintenance.test.ts
+++ b/test/autopilot-global-maintenance.test.ts
@@ -332,7 +332,8 @@ describe('autopilot-global-maintenance handler stamps last_global_at (PGLite)',
expect(ranPhases).toContain('synthesize');
expect(ranPhases).toContain('patterns');
expect(ranPhases).not.toContain('sync');
- expect(await engine.getConfig(LAST_GLOBAL_AT_KEY)).not.toBeNull();
+ expect(result.report.phases.some((p: any) => p.status === 'fail')).toBe(true);
+ expect(await engine.getConfig(LAST_GLOBAL_AT_KEY)).toBeNull();
}, 60_000);
test('runs global phases (no source_id) and stamps autopilot.last_global_at on success', async () => {
@@ -350,14 +351,15 @@ describe('autopilot-global-maintenance handler stamps last_global_at (PGLite)',
// runCycle (worker jobs always carry one).
const result = await handler!({
id: 4102,
- data: { phases: ['orphans', 'embed'], repoPath },
+ data: { phases: ['orphans'], repoPath },
signal: undefined,
});
// The cycle ran the requested global phases (DB-only on an empty brain).
const orphans = result.report.phases.find((p: any) => p.phase === 'orphans');
expect(orphans).toBeTruthy();
expect(orphans.details.source_id).toBeUndefined();
- expect(['ok', 'clean', 'partial']).toContain(result.report.status);
+ expect(result.report.phases.some((p: any) => p.status === 'fail')).toBe(false);
+ expect(['ok', 'clean']).toContain(result.report.status);
// Freshness stamped so the dispatch gate backs off.
const stamped = await engine.getConfig(LAST_GLOBAL_AT_KEY);
expect(stamped).not.toBeNull();
diff --git a/test/brain-score-recommendations.test.ts b/test/brain-score-recommendations.test.ts
index c3ebc191b5..5c503c1803 100644
--- a/test/brain-score-recommendations.test.ts
+++ b/test/brain-score-recommendations.test.ts
@@ -170,7 +170,7 @@ describe('computeRecommendations', () => {
expect(recs.find((r) => r.id === 'embed.stale')).toBeUndefined();
});
- test('stale pages + dead links produce sync + backlinks + extract', () => {
+ test('stale pages + dead links produce backlinks + DB extraction without filesystem sync', () => {
const health = makeHealth({
stale_pages: 25,
dead_links: 8,
@@ -178,26 +178,27 @@ describe('computeRecommendations', () => {
});
const recs = computeRecommendations(health, { repoPath: '/brain', embeddingProviderConfigured: true });
const ids = recs.map((r) => r.id);
- expect(ids).toContain('sync.repo');
+ expect(ids).not.toContain('sync.repo');
expect(ids).toContain('backlinks.fix');
- expect(ids).toContain('extract.all');
+ expect(ids).toContain('extract.stale');
});
- test('extract.all depends on sync.repo (D14: stable ids)', () => {
+ test('extract.stale can clear extraction watermarks without a sync dependency', () => {
const health = makeHealth({ stale_pages: 10 });
const recs = computeRecommendations(health, { repoPath: '/brain', embeddingProviderConfigured: true });
- const extract = recs.find((r) => r.id === 'extract.all');
- expect(extract?.depends_on).toContain('sync.repo');
+ const extract = recs.find((r) => r.id === 'extract.stale');
+ expect(extract?.params).toEqual({ stale: true });
+ expect(extract?.depends_on).toEqual([]);
});
- test('embed.stale depends on sync.repo when sync also needed', () => {
+ test('embed.stale is not blocked by unrelated extraction watermarks', () => {
const health = makeHealth({
stale_pages: 10,
missing_embeddings: 100,
});
const recs = computeRecommendations(health, { repoPath: '/brain', embeddingProviderConfigured: true });
const embed = recs.find((r) => r.id === 'embed.stale');
- expect(embed?.depends_on).toContain('sync.repo');
+ expect(embed?.depends_on).toEqual([]);
});
test('embed.stale has no sync dependency when nothing stale', () => {
diff --git a/test/chunker-version-gate.test.ts b/test/chunker-version-gate.test.ts
index 7a0bcef35b..75d9a10792 100644
--- a/test/chunker-version-gate.test.ts
+++ b/test/chunker-version-gate.test.ts
@@ -15,7 +15,7 @@ import { describe, test, expect } from 'bun:test';
import { CHUNKER_VERSION } from '../src/core/chunkers/code.ts';
describe('Layer 12 — CHUNKER_VERSION constant', () => {
- test('bumped to 6 for the definition-preserving merge guard (#4511)', () => {
+ test('bumped to 7 for the compatible Bash grammar (#5082)', () => {
// v3: v0.19.0 Chonkie parity (tokenizer + small-sibling merge).
// v4: v0.20.0 Cathedral II (qualified names + parent scope + doc_comment
// + fence extraction + chunk-grain FTS). Folded into content_hash
@@ -25,14 +25,14 @@ describe('Layer 12 — CHUNKER_VERSION constant', () => {
// v6: #4511 mergeSmallSiblings stopped erasing symbol_name on short
// definitions; the bump re-chunks previously-merged files so the
// lost symbols come back.
- expect(CHUNKER_VERSION).toBe(6);
+ expect(CHUNKER_VERSION).toBe(7);
});
test('is stable across imports (not recomputed at call time)', async () => {
const a = (await import('../src/core/chunkers/code.ts')).CHUNKER_VERSION;
const b = (await import('../src/core/chunkers/code.ts')).CHUNKER_VERSION;
expect(a).toBe(b);
- expect(a).toBe(6);
+ expect(a).toBe(7);
});
});
diff --git a/test/chunkers/code-bash.test.ts b/test/chunkers/code-bash.test.ts
new file mode 100644
index 0000000000..0f2cbd9c3b
--- /dev/null
+++ b/test/chunkers/code-bash.test.ts
@@ -0,0 +1,78 @@
+import { describe, expect, test } from 'bun:test';
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import Parser from 'web-tree-sitter';
+import { CHUNKER_VERSION, chunkCodeText, chunkCodeTextFull } from '../../src/core/chunkers/code.ts';
+
+const assets = join(import.meta.dir, '../../src/assets/wasm');
+const source = `#!/usr/bin/env bash
+dispatch() {
+ case "$1" in
+ start|stop) printf '%s\\n' "$1" ;;
+ *) printf '%s\\n' 'unknown command' ;;
+ esac
+}
+
+print_help() {
+ cat <<'HELP'
+Usage: example.sh start|stop
+HELP
+}
+
+for action in start stop; do
+ dispatch "$action"
+done
+`;
+
+describe('Bash case statements retain semantic chunks (#5082)', () => {
+ test('the vendored grammar has no unresolved normal-path libc imports', async () => {
+ const runtime = await WebAssembly.compile(readFileSync(join(assets, 'tree-sitter.wasm')));
+ const exports = new Set(WebAssembly.Module.exports(runtime).map(e => e.name));
+ const grammar = await WebAssembly.compile(readFileSync(join(assets, 'grammars/tree-sitter-bash.wasm')));
+ const missingFunctions = WebAssembly.Module.imports(grammar).filter(i =>
+ i.module === 'env' && i.kind === 'function' &&
+ !exports.has(i.name) && !exports.has('_' + i.name));
+ expect(missingFunctions.map(i => i.name)).toEqual(['__assert_fail']);
+ });
+
+ test('the pinned runtime parses case, heredoc and loop syntax without errors', async () => {
+ await Parser.init({ locateFile: () => join(assets, 'tree-sitter.wasm') });
+ const language = await Parser.Language.load(join(assets, 'grammars/tree-sitter-bash.wasm'));
+ expect(language.version).toBe(14);
+ const parser = new Parser();
+ try {
+ parser.setLanguage(language);
+ const tree = parser.parse(source);
+ try {
+ expect(tree.rootNode.hasError).toBe(false);
+ expect(tree.rootNode.descendantsOfType('case_statement')).toHaveLength(1);
+ expect(tree.rootNode.descendantsOfType('heredoc_body')).toHaveLength(1);
+ expect(tree.rootNode.descendantsOfType('for_statement')).toHaveLength(1);
+ } finally {
+ tree.delete();
+ }
+ } finally {
+ parser.delete();
+ }
+ });
+
+ for (const path of ['example.sh', 'example.bash']) {
+ test(`${path} keeps functions and their bodies instead of whole-file text fallback`, async () => {
+ const chunks = await chunkCodeText(source, path);
+ expect(chunks.find(c => c.metadata.symbolName === 'dispatch')?.metadata.symbolType).toBe('function');
+ expect(chunks.find(c => c.metadata.symbolName === 'dispatch')?.text).toContain('case "$1" in');
+ expect(chunks.find(c => c.metadata.symbolName === 'print_help')?.text).toContain('Usage: example.sh');
+ expect(chunks.every(c => c.metadata.symbolType !== 'text')).toBe(true);
+ });
+ }
+
+ test('the full chunk-and-edge entrypoint preserves Bash symbols', async () => {
+ const { chunks } = await chunkCodeTextFull(source, 'example.sh');
+ expect(chunks.find(c => c.metadata.symbolName === 'dispatch')?.metadata.language).toBe('bash');
+ expect(chunks.find(c => c.metadata.symbolName === 'print_help')).toBeDefined();
+ });
+
+ test('existing indexes are invalidated to recover lost Bash symbols', () => {
+ expect(CHUNKER_VERSION).toBeGreaterThanOrEqual(7);
+ });
+});
diff --git a/test/chunkers/code.test.ts b/test/chunkers/code.test.ts
index 34b9433b26..2ef4d541cf 100644
--- a/test/chunkers/code.test.ts
+++ b/test/chunkers/code.test.ts
@@ -10,8 +10,8 @@ import { describe, test, expect } from 'bun:test';
import { chunkCodeText, detectCodeLanguage, CHUNKER_VERSION } from '../../src/core/chunkers/code.ts';
describe('CHUNKER_VERSION', () => {
- test('#4511 definition-preserving merge guard bumped to 6', () => {
- expect(CHUNKER_VERSION).toBe(6);
+ test('#5082 Bash grammar refresh bumped to 7', () => {
+ expect(CHUNKER_VERSION).toBe(7);
});
});
diff --git a/test/cycle-write-path-mini-eval.test.ts b/test/cycle-write-path-mini-eval.test.ts
index 757ecda1d3..8bac8ef2cb 100644
--- a/test/cycle-write-path-mini-eval.test.ts
+++ b/test/cycle-write-path-mini-eval.test.ts
@@ -258,7 +258,7 @@ describe('F-Eval: hermetic write-path mini-eval (real phase, scripted transport)
}
}, 120_000);
- test('kill switch: quote_verify=false leaves fabricated quotes intact and reports quote_verify null; a declining child counts in children_zero_pages', async () => {
+ test('kill switch: quote_verify=false leaves fabricated quotes intact and reports quote_verify null; a declining required-write child stays incomplete', async () => {
const brainDir2 = mkdtempSync(join(tmpdir(), 'gbrain-minieval-brain2-'));
const corpusDir2 = mkdtempSync(join(tmpdir(), 'gbrain-minieval-corpus2-'));
try {
@@ -295,9 +295,12 @@ describe('F-Eval: hermetic write-path mini-eval (real phase, scripted transport)
const result = await withEnv({ ANTHROPIC_API_KEY: 'sk-test-mini-eval' }, () =>
runPhaseSynthesize(engine, { brainDir: brainDir2, dryRun: false }));
expect(result.status).toBe('ok');
- const d = result.details as { written_slugs: string[]; synthesis: { quote_verify: unknown; children_zero_pages: number } };
+ const d = result.details as { written_slugs: string[]; child_outcomes: Array<{ status: string }>; synthesis: { quote_verify: unknown; children_zero_pages: number; non_completed_jobs: number } };
expect(d.synthesis.quote_verify).toBeNull(); // pass skipped entirely
- expect(d.synthesis.children_zero_pages).toBe(1); // rule-D decliner counted
+ expect(d.synthesis.children_zero_pages).toBe(0);
+ expect(d.synthesis.non_completed_jobs).toBe(1);
+ expect(d.child_outcomes.filter(child => child.status !== 'completed')).toEqual([expect.objectContaining({ status: 'dead' })]);
+ expect(await engine.getConfig('dream.synthesize.last_completion_ts')).toBe('');
const killSlug = d.written_slugs.find(s => s.includes('killswitch'));
expect(killSlug).toBeDefined();
const page = await engine.getPage(killSlug!, { sourceId: 'default' });
diff --git a/test/cycle/global-freshness-postcondition.serial.test.ts b/test/cycle/global-freshness-postcondition.serial.test.ts
new file mode 100644
index 0000000000..58bcb06d4b
--- /dev/null
+++ b/test/cycle/global-freshness-postcondition.serial.test.ts
@@ -0,0 +1,351 @@
+import { afterAll, beforeAll, beforeEach, describe, expect, mock, spyOn, test } from 'bun:test';
+import { createHash } from 'node:crypto';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import * as realEmbed from '../../src/commands/embed.ts';
+import * as realGateway from '../../src/core/ai/gateway.ts';
+import * as realInlineDrain from '../../src/core/cycle/inline-drain.ts';
+import type { CycleReport } from '../../src/core/cycle.ts';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { MinionQueue } from '../../src/core/minions/queue.ts';
+import type { MinionJobContext, MinionJobStatus } from '../../src/core/minions/types.ts';
+import { TIER_DEFAULTS } from '../../src/core/model-config.ts';
+import { resetPgliteState } from '../helpers/reset-pglite.ts';
+import { withEnv } from '../helpers/with-env.ts';
+
+let abortDuringEmbed: AbortController | undefined;
+let stealDuringEmbed = false;
+mock.module('../../src/commands/embed.ts', () => ({
+ ...realEmbed,
+ runEmbedCore: async (engine: BrainEngine, opts: { signal?: AbortSignal }) => {
+ if (stealDuringEmbed) {
+ await engine.executeRaw(
+ `UPDATE gbrain_cycle_locks SET acquired_at = acquired_at + INTERVAL '1 millisecond'
+ WHERE id = 'gbrain-cycle'`,
+ );
+ await new Promise<void>(resolve => {
+ if (opts.signal?.aborted) resolve();
+ else opts.signal?.addEventListener('abort', () => resolve(), { once: true });
+ });
+ return { embedded: 0, skipped: 0, would_embed: 0, total_chunks: 0, pages_processed: 0 };
+ }
+ if (abortDuringEmbed) {
+ abortDuringEmbed.abort();
+ return { embedded: 0, skipped: 0, would_embed: 0, total_chunks: 0, pages_processed: 0 };
+ }
+ throw new Error('synthetic required phase failure');
+ },
+}));
+
+mock.module('../../src/core/ai/gateway.ts', () => ({
+ ...realGateway,
+ probeChatModel: () => ({ ok: true }),
+ chat: async () => { throw new Error('unexpected model call in global freshness test'); },
+}));
+
+let childStatuses: MinionJobStatus[] = [];
+let writtenChildSlug: string | undefined;
+mock.module('../../src/core/cycle/inline-drain.ts', () => ({
+ ...realInlineDrain,
+ runSubagentsInline: async (engine: BrainEngine, _queue: MinionQueue, queueName: string) => {
+ const jobs = await engine.executeRaw<{ id: number }>(
+ `SELECT id FROM minion_jobs WHERE queue = $1 ORDER BY id`, [queueName],
+ );
+ for (const [index, job] of jobs.entries()) {
+ if (writtenChildSlug) {
+ await engine.putPage(writtenChildSlug, {
+ title: 'Synthetic pattern', type: 'note', compiled_truth: 'A recurring synthetic theme.', timeline: '',
+ });
+ await engine.executeRaw(
+ `INSERT INTO subagent_tool_executions (job_id, message_idx, tool_use_id, tool_name, input, status)
+ VALUES ($1, 0, 'fixture-write', 'brain_put_page', $2::jsonb, 'complete')`,
+ [job.id, { slug: writtenChildSlug }],
+ );
+ }
+ await engine.executeRaw(
+ `UPDATE minion_jobs SET status = $2, finished_at = NOW() WHERE id = $1`,
+ [job.id, childStatuses[index] ?? 'completed'],
+ );
+ }
+ },
+}));
+
+const { PGLiteEngine } = await import('../../src/core/pglite-engine.ts');
+const { registerBuiltinHandlers } = await import('../../src/commands/jobs.ts');
+const { LAST_GLOBAL_AT_KEY } = await import('../../src/core/cycle.ts');
+const { isGlobalMaintenanceStale } = await import('../../src/commands/autopilot-fanout.ts');
+const { TRIAGE_VERSION } = await import('../../src/core/cycle/synthesize.ts');
+const engine = new PGLiteEngine();
+const repoPath = mkdtempSync(join(tmpdir(), 'global-postcondition-'));
+const corpusPath = join(repoPath, 'corpus');
+const priorHome = process.env.GBRAIN_HOME;
+let schemaVersion: string;
+let ownerJobId: number;
+let handler: (job: MinionJobContext) => Promise<{ report: CycleReport }>;
+
+beforeAll(async () => {
+ await engine.connect({ database_url: '' });
+ await engine.initSchema();
+ schemaVersion = (await engine.getConfig('version'))!;
+ process.env.GBRAIN_HOME = join(repoPath, 'home');
+ await registerBuiltinHandlers({ register: (name: string, fn: typeof handler) => {
+ if (name === 'autopilot-global-maintenance') handler = fn;
+ } } as never, engine);
+}, 60_000);
+
+afterAll(async () => {
+ await engine.disconnect();
+ if (priorHome === undefined) delete process.env.GBRAIN_HOME;
+ else process.env.GBRAIN_HOME = priorHome;
+ rmSync(repoPath, { recursive: true, force: true });
+});
+
+beforeEach(async () => {
+ await resetPgliteState(engine);
+ await engine.setConfig('version', schemaVersion);
+ ownerJobId = (await new MinionQueue(engine).add('autopilot-global-maintenance', {})).id;
+ await engine.putPage('atoms/example', { title: 'Example', type: 'note', compiled_truth: 'A synthetic note.', timeline: '' });
+ rmSync(corpusPath, { recursive: true, force: true });
+ mkdirSync(corpusPath);
+ childStatuses = [];
+ writtenChildSlug = undefined;
+});
+
+async function seedTranscripts(count: number): Promise<void> {
+ await engine.setConfig('dream.synthesize.enabled', 'true');
+ await engine.setConfig('dream.synthesize.session_corpus_dir', corpusPath);
+ await engine.setConfig('dream.synthesize.summary_file_write', 'false');
+ for (let i = 0; i < count; i++) {
+ const filePath = join(corpusPath, `2026-08-01-example-${i}.txt`);
+ const content = `Synthetic transcript ${i} line.\n`.repeat(250);
+ writeFileSync(filePath, content);
+ await engine.putDreamVerdict(filePath, createHash('sha256').update(content).digest('hex'), {
+ worth_processing: true, reasons: ['synthetic fixture'], score: 0.9,
+ content_type: null, segments: [], entities: [], model: TIER_DEFAULTS.utility,
+ triage_version: TRIAGE_VERSION,
+ });
+ }
+}
+
+async function seedReflections(): Promise<void> {
+ await engine.setConfig('dream.patterns.enabled', 'true');
+ await engine.setConfig('models.dream.patterns', 'anthropic:claude-sonnet-4-6');
+ for (let i = 0; i < 3; i++) {
+ await engine.putPage(`wiki/personal/reflections/example-${i}`, {
+ title: `Reflection ${i}`, type: 'note', compiled_truth: `Recurring synthetic theme ${i}.`, timeline: '',
+ });
+ }
+}
+
+describe('global maintenance freshness postcondition (#5089)', () => {
+ test('a required-phase failure stays due even when another phase succeeds', async () => {
+ const result = await handler({ id: ownerJobId, data: { phases: ['orphans', 'embed'], repoPath } } as unknown as MinionJobContext);
+ expect(result.report.status).toBe('partial');
+ expect(result.report.phases.find(p => p.phase === 'embed')?.status).toBe('fail');
+ const stamp = await engine.getConfig(LAST_GLOBAL_AT_KEY);
+ expect(stamp).toBeNull();
+ expect(isGlobalMaintenanceStale(stamp, Date.now() + 60_000, 60)).toBe(true);
+ }, 60_000);
+
+ test('a successful read-only maintenance run stamps freshness', async () => {
+ const result = await handler({ id: ownerJobId, data: { phases: ['orphans'], repoPath } } as unknown as MinionJobContext);
+ expect(result.report.phases.some(p => p.status === 'fail')).toBe(false);
+ expect(await engine.getConfig(LAST_GLOBAL_AT_KEY)).not.toBeNull();
+ }, 60_000);
+
+ test('a warning-only partial stamps freshness instead of rerunning every tick', async () => {
+ for (const slug of ['people/example-a', 'people/example-b']) {
+ await engine.putPage(slug, { title: slug, type: 'person', compiled_truth: 'An isolated synthetic page.', timeline: '' });
+ }
+ const result = await handler({ id: ownerJobId, data: { phases: ['orphans'], repoPath } } as unknown as MinionJobContext);
+ expect(result.report.status).toBe('partial');
+ expect(result.report.phases[0].status).toBe('warn');
+ expect(await engine.getConfig(LAST_GLOBAL_AT_KEY)).not.toBeNull();
+ }, 60_000);
+
+ test('mixed completed and dead synthesis children stay due despite an ok phase', async () => {
+ await seedTranscripts(2);
+ childStatuses = ['completed', 'dead'];
+ const result = await handler({ id: ownerJobId, data: { phases: ['synthesize'], repoPath } } as unknown as MinionJobContext);
+ const phase = result.report.phases[0];
+ expect(phase.status).toBe('ok');
+ expect(phase.details.child_outcomes).toEqual([
+ expect.objectContaining({ status: 'completed' }), expect.objectContaining({ status: 'dead' }),
+ ]);
+ expect(phase.details.synthesis).toMatchObject({ non_completed_jobs: 1, degraded: true });
+ expect(await engine.getConfig('dream.synthesize.last_completion_ts')).toBeNull();
+ const stamp = await engine.getConfig(LAST_GLOBAL_AT_KEY);
+ expect(stamp).toBeNull();
+ expect(isGlobalMaintenanceStale(stamp, Date.now(), 60)).toBe(true);
+ }, 60_000);
+
+ test('budget-deferred transcripts stay due even when every submitted child completed', async () => {
+ await seedTranscripts(2);
+ const now = Date.now();
+ const clock = spyOn(Date, 'now').mockReturnValue(now);
+ const realAdd = MinionQueue.prototype.add;
+ const submit = spyOn(MinionQueue.prototype, 'add').mockImplementation(async function (this: MinionQueue, ...args) {
+ const child = await realAdd.apply(this, args);
+ clock.mockReturnValue(now + 4 * 60_000);
+ return child;
+ });
+ let result;
+ try {
+ result = await handler({
+ id: ownerJobId, data: { phases: ['synthesize'], repoPath }, deadlineAtMs: now + 5 * 60_000,
+ } as unknown as MinionJobContext);
+ } finally {
+ submit.mockRestore();
+ clock.mockRestore();
+ }
+ const phase = result.report.phases[0];
+ expect(phase.status).toBe('ok');
+ expect(phase.details.synthesis).toMatchObject({ non_completed_jobs: 0, degraded: false });
+ expect(phase.details.children_submitted).toBe(1);
+ expect(phase.details.budget_deferred_transcripts).toHaveLength(1);
+ expect(await engine.getConfig('dream.synthesize.last_completion_ts')).toBeNull();
+ expect(await engine.getConfig(LAST_GLOBAL_AT_KEY)).toBeNull();
+ }, 60_000);
+
+ test('triage-deferred transcripts stay due without submitting children', async () => {
+ await seedTranscripts(1);
+ await engine.executeRaw('TRUNCATE dream_verdicts');
+ await engine.setConfig('dream.triage.max_ms', '1');
+ const realGet = engine.getDreamVerdict.bind(engine);
+ const lookup = spyOn(engine, 'getDreamVerdict').mockImplementation(async (...args) => {
+ await new Promise(resolve => setTimeout(resolve, 10));
+ return realGet(...args);
+ });
+ let result;
+ try {
+ result = await handler({ id: ownerJobId, data: { phases: ['synthesize'], repoPath } } as unknown as MinionJobContext);
+ } finally {
+ lookup.mockRestore();
+ }
+ expect(result.report.phases[0].status).toBe('ok');
+ expect(result.report.phases[0].details.triage).toMatchObject({ deferred: 1, degraded: 0 });
+ expect(await engine.getConfig(LAST_GLOBAL_AT_KEY)).toBeNull();
+ }, 60_000);
+
+ test('mixed completed synthesis and triage deferral retries only unfinished work next tick', async () => {
+ await seedTranscripts(2);
+ const deferredPath = join(corpusPath, '2026-08-01-example-1.txt');
+ await engine.executeRaw('DELETE FROM dream_verdicts WHERE file_path = $1', [deferredPath]);
+ await engine.setConfig('dream.triage.max_ms', '1');
+ const realGet = engine.getDreamVerdict.bind(engine);
+ const lookup = spyOn(engine, 'getDreamVerdict').mockImplementation(async (...args) => {
+ if (args[0] === deferredPath) await new Promise(resolve => setTimeout(resolve, 10));
+ return realGet(...args);
+ });
+ const job = { id: ownerJobId, data: { phases: ['synthesize'], repoPath } } as unknown as MinionJobContext;
+ let first;
+ try {
+ first = await handler(job);
+ } finally {
+ lookup.mockRestore();
+ }
+ expect(first.report.phases[0]).toMatchObject({
+ status: 'ok',
+ details: {
+ triage: { cache_hits: 1, deferred: 1 }, children_submitted: 1,
+ synthesis: { non_completed_jobs: 0, degraded: false }, budget_deferred_transcripts: [],
+ },
+ });
+ const firstCooldown = await engine.getConfig('dream.synthesize.last_completion_ts');
+ expect(await engine.getConfig(LAST_GLOBAL_AT_KEY)).toBeNull();
+
+ await seedTranscripts(2);
+ const retry = await handler(job);
+ expect(retry.report.phases[0].details.reason).not.toBe('cooldown_active');
+ expect(firstCooldown).toBeNull();
+ expect(retry.report.phases[0]).toMatchObject({
+ status: 'ok', details: { triage: { deferred: 0 }, children_submitted: 1 },
+ });
+ expect(retry.report.phases[0].details.skips).toEqual([
+ expect.objectContaining({ reason: 'already_synthesized_v2_single_chunk' }),
+ ]);
+ expect(await engine.getConfig('dream.synthesize.last_completion_ts')).not.toBeNull();
+ expect(await engine.getConfig(LAST_GLOBAL_AT_KEY)).not.toBeNull();
+ }, 60_000);
+
+ test.each(['synthesize', 'patterns'] as const)('%s skipped for an insufficient cycle budget stays due', async phase => {
+ await seedTranscripts(1);
+ await seedReflections();
+ const result = await handler({
+ id: ownerJobId, data: { phases: [phase], repoPath }, deadlineAtMs: Date.now() + 30_000,
+ } as unknown as MinionJobContext);
+ expect(result.report.phases[0]).toMatchObject({ status: 'skipped', details: { reason: 'insufficient_cycle_budget' } });
+ expect(await engine.getConfig(LAST_GLOBAL_AT_KEY)).toBeNull();
+ }, 60_000);
+
+ test.each(['dead', 'cancelled'] as const)('patterns child %s after writing a page stays due despite a warning', async status => {
+ await seedReflections();
+ childStatuses = [status];
+ writtenChildSlug = 'wiki/personal/patterns/example';
+ const result = await handler({ id: ownerJobId, data: { phases: ['patterns'], repoPath } } as unknown as MinionJobContext);
+ expect(result.report.status).toBe('partial');
+ expect(result.report.phases[0]).toMatchObject({
+ status: 'warn', details: { child_outcome: status, patterns_written: 1 },
+ });
+ expect(await engine.getPage(writtenChildSlug)).not.toBeNull();
+ expect(await engine.getConfig('dream.patterns.last_evidence_ts')).toBeNull();
+ expect(await engine.getConfig(LAST_GLOBAL_AT_KEY)).toBeNull();
+ }, 60_000);
+
+ test('fully completed synthesis children stamp freshness, including a later cooldown skip', async () => {
+ await seedTranscripts(2);
+ const job = { id: ownerJobId, data: { phases: ['synthesize'], repoPath } } as unknown as MinionJobContext;
+ const result = await handler(job);
+ expect(result.report.phases[0].details.synthesis).toMatchObject({ non_completed_jobs: 0, degraded: false });
+ expect(result.report.phases[0].details.budget_deferred_transcripts).toEqual([]);
+ expect(await engine.getConfig(LAST_GLOBAL_AT_KEY)).not.toBeNull();
+ await engine.unsetConfig(LAST_GLOBAL_AT_KEY);
+ const cooled = await handler(job);
+ expect(cooled.report.phases[0].details.reason).toBe('cooldown_active');
+ expect(await engine.getConfig(LAST_GLOBAL_AT_KEY)).not.toBeNull();
+ }, 60_000);
+
+ test('completed patterns with zero writes stamp freshness, including unchanged evidence', async () => {
+ await seedReflections();
+ const job = { id: ownerJobId, data: { phases: ['patterns'], repoPath } } as unknown as MinionJobContext;
+ const result = await handler(job);
+ expect(result.report.phases[0]).toMatchObject({
+ status: 'ok', details: { child_outcome: 'completed', patterns_written: 0 },
+ });
+ expect(await engine.getConfig(LAST_GLOBAL_AT_KEY)).not.toBeNull();
+ await engine.unsetConfig(LAST_GLOBAL_AT_KEY);
+ const unchanged = await handler(job);
+ expect(unchanged.report.phases[0].details.reason).toBe('no_new_evidence');
+ expect(await engine.getConfig(LAST_GLOBAL_AT_KEY)).not.toBeNull();
+ }, 60_000);
+
+ test('an aborted run does not stamp freshness', async () => {
+ const controller = new AbortController();
+ abortDuringEmbed = controller;
+ try {
+ const result = await handler({ id: ownerJobId, data: { phases: ['embed'], repoPath }, signal: controller.signal } as unknown as MinionJobContext);
+ expect(result.report.reason).toBe('aborted');
+ expect(result.report.phases.some(p => p.status === 'fail')).toBe(false);
+ expect(await engine.getConfig(LAST_GLOBAL_AT_KEY)).toBeNull();
+ } finally {
+ abortDuringEmbed = undefined;
+ }
+ }, 60_000);
+
+ test('a lock-stolen run does not stamp freshness or release its successor lock', async () => {
+ stealDuringEmbed = true;
+ try {
+ await withEnv({ GBRAIN_CYCLE_LOCK_REFRESH_MS: '20' }, async () => {
+ const result = await handler({ id: ownerJobId, data: { phases: ['embed', 'orphans'], repoPath } } as unknown as MinionJobContext);
+ expect(result.report.reason).toBe('lock_stolen');
+ expect(result.report.phases.some(p => p.status === 'fail')).toBe(false);
+ expect(await engine.getConfig(LAST_GLOBAL_AT_KEY)).toBeNull();
+ const locks = await engine.executeRaw(`SELECT id FROM gbrain_cycle_locks WHERE id = 'gbrain-cycle'`);
+ expect(locks).toHaveLength(1);
+ });
+ } finally {
+ stealDuringEmbed = false;
+ }
+ }, 60_000);
+});
diff --git a/test/e2e/dream-synthesize-pglite.test.ts b/test/e2e/dream-synthesize-pglite.test.ts
index 2874ff968c..6a602b7e07 100644
--- a/test/e2e/dream-synthesize-pglite.test.ts
+++ b/test/e2e/dream-synthesize-pglite.test.ts
@@ -1081,16 +1081,20 @@ describe('E2E synthesize — oneshot mode (#4216, DEFAULT)', () => {
const content = 'User: routine chat that the model mangles\n'.repeat(120);
const filePath = join(rig.corpusDir, '2026-08-16-mangled.txt');
writeFileSync(filePath, content);
- await seedVerdictFor(rig, filePath, content);
+ const hash = await seedVerdictFor(rig, filePath, content);
+ const slug = `wiki/personal/reflections/2026-08-16-fallback-${hash.slice(0, 6)}`;
let calls = 0;
__setChatTransportForTests(async () => {
calls++;
- const text = calls === 1 ? 'sure! here are your pages, enjoy' : 'nothing worth writing';
+ const text = calls === 1 ? 'sure! here are your pages, enjoy' : 'saved';
return {
- text,
- blocks: [{ type: 'text', text }],
- stopReason: 'end',
+ text: calls === 2 ? '' : text,
+ blocks: calls === 2 ? [{
+ type: 'tool-call', toolCallId: 'fallback-save', toolName: 'brain_put_page',
+ input: { slug, content: '---\ntitle: Fallback synthesis\ntype: reflection\n---\n\nSaved through the fallback loop.' },
+ }] : [{ type: 'text', text }],
+ stopReason: calls === 2 ? 'tool_calls' : 'end',
usage: { input_tokens: 100, output_tokens: 20, cache_read_tokens: 0, cache_creation_tokens: 0 },
model: 'anthropic:claude-sonnet-4-6',
providerId: 'anthropic',
@@ -1110,6 +1114,9 @@ describe('E2E synthesize — oneshot mode (#4216, DEFAULT)', () => {
const jr = (typeof jobs[0]!.result === 'string' ? JSON.parse(jobs[0]!.result as string) : jobs[0]!.result) as Record<string, unknown>;
expect(jr.synth_mode_used).toBe('agentic_fallback');
expect(jr.fallback_reason).toBe('unparseable');
+ expect(jr.pages_written).toBe(1);
+ expect((await rig.engine.getPage(slug))?.compiled_truth).toContain('Saved through the fallback loop.');
+ expect(readFileSync(join(rig.brainDir, `${slug}.md`), 'utf8')).toContain('Saved through the fallback loop.');
} finally {
if (savedKey === undefined) delete process.env.ANTHROPIC_API_KEY;
else process.env.ANTHROPIC_API_KEY = savedKey;
@@ -1131,14 +1138,20 @@ describe('E2E synthesize — oneshot mode (#4216, DEFAULT)', () => {
const content = 'User: agentic-dial conversation\n'.repeat(120);
const filePath = join(rig.corpusDir, '2026-08-16-agentic-dial.txt');
writeFileSync(filePath, content);
- await seedVerdictFor(rig, filePath, content);
+ const hash = await seedVerdictFor(rig, filePath, content);
+ const slug = `wiki/personal/reflections/2026-08-16-agentic-${hash.slice(0, 6)}`;
+ let calls = 0;
__setChatTransportForTests(async () => {
- const text = 'nothing to write';
+ calls++;
+ const text = 'saved';
return {
- text,
- blocks: [{ type: 'text', text }],
- stopReason: 'end',
+ text: calls === 1 ? '' : text,
+ blocks: calls === 1 ? [{
+ type: 'tool-call', toolCallId: 'agentic-save', toolName: 'brain_put_page',
+ input: { slug, content: '---\ntitle: Agentic synthesis\ntype: reflection\n---\n\nSaved through the agentic loop.' },
+ }] : [{ type: 'text', text }],
+ stopReason: calls === 1 ? 'tool_calls' : 'end',
usage: { input_tokens: 100, output_tokens: 10, cache_read_tokens: 0, cache_creation_tokens: 0 },
model: 'anthropic:claude-sonnet-4-6',
providerId: 'anthropic',
@@ -1152,6 +1165,8 @@ describe('E2E synthesize — oneshot mode (#4216, DEFAULT)', () => {
expect(synthesis.agentic_jobs).toBe(1);
expect(synthesis.oneshot_jobs).toBe(0);
expect(synthesis.fallback_jobs).toBe(0);
+ expect((await rig.engine.getPage(slug))?.compiled_truth).toContain('Saved through the agentic loop.');
+ expect(readFileSync(join(rig.brainDir, `${slug}.md`), 'utf8')).toContain('Saved through the agentic loop.');
} finally {
if (savedKey === undefined) delete process.env.ANTHROPIC_API_KEY;
else process.env.ANTHROPIC_API_KEY = savedKey;
diff --git a/test/e2e/put-page-persistence-postgres.test.ts b/test/e2e/put-page-persistence-postgres.test.ts
new file mode 100644
index 0000000000..538d0ac8fd
--- /dev/null
+++ b/test/e2e/put-page-persistence-postgres.test.ts
@@ -0,0 +1,129 @@
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { getEngine, hasDatabase, setupDB, teardownDB } from './helpers.ts';
+import { resetPgliteStateNarrow } from '../helpers/reset-pglite.ts';
+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../../src/core/ai/gateway.ts';
+import { dispatchToolCall } from '../../src/mcp/dispatch.ts';
+import { withSourceFilesystemLock } from '../../src/core/minions/source-filesystem.ts';
+import { _resetWriteThroughCacheForTest } from '../../src/core/write-through.ts';
+
+const d = hasDatabase() ? describe : describe.skip;
+let root: string;
+const slug = 'notes/persistence-example';
+const content = (body: string) => `---\ntitle: Example\ntype: note\n---\n\n${body}`;
+
+async function put(body: string, pageSlug = slug) {
+ const response = await dispatchToolCall(getEngine(), 'put_page', { slug: pageSlug, content: content(body) }, {
+ remote: true,
+ sourceId: 'default',
+ auth: { token: 'fixture', clientId: 'fixture-client', scopes: ['read', 'write'], sourceId: 'default' },
+ logger: { info() {}, warn() {}, error() {} },
+ });
+ return { response, payload: JSON.parse((response.content[0] as { text: string }).text) };
+}
+
+d('Postgres put_page persistence', () => {
+ beforeAll(async () => { await setupDB(); });
+ afterAll(async () => { await teardownDB(); });
+ beforeEach(async () => {
+ await resetPgliteStateNarrow(getEngine(), ['pages', 'config', 'gbrain_cycle_locks', 'minion_jobs']);
+ resetGateway();
+ _resetWriteThroughCacheForTest();
+ root = mkdtempSync(join(tmpdir(), 'gbrain-put-pg-'));
+ await getEngine().setConfig('sync.repo_path', root);
+ });
+ afterEach(() => {
+ __setEmbedTransportForTests(null);
+ resetGateway();
+ _resetWriteThroughCacheForTest();
+ rmSync(root, { recursive: true, force: true });
+ });
+
+ test('remote lock contention preserves the prior revision and the MCP error is retryable', async () => {
+ await put('Original canonical revision.');
+ const engine = getEngine();
+ const before = await engine.getPage(slug, { sourceId: 'default' });
+ const disk = readFileSync(join(root, `${slug}.md`), 'utf8');
+ const entered = Promise.withResolvers<void>();
+ const release = Promise.withResolvers<void>();
+ const holder = withSourceFilesystemLock(engine, root, async () => {
+ entered.resolve();
+ await release.promise;
+ });
+ await entered.promise;
+ try {
+ const failed = await put('Rejected revision.');
+ expect(await engine.getPage(slug, { sourceId: 'default' })).toEqual(before);
+ expect(readFileSync(join(root, `${slug}.md`), 'utf8')).toBe(disk);
+ expect(failed.response.isError).toBe(true);
+ expect(failed.payload.error).toBe('storage_busy');
+ expect(failed.payload.message).toContain('not queued');
+ } finally {
+ release.resolve();
+ await holder;
+ }
+ expect((await put('Accepted revision.')).response.isError).not.toBe(true);
+ }, 15_000);
+
+ test('file rename failure rolls back page, chunks, and version in the real transaction', async () => {
+ await put('Before failed rename.');
+ const engine = getEngine();
+ const before = await engine.getPage(slug, { sourceId: 'default' });
+ const chunks = await engine.getChunks(slug, { sourceId: 'default' });
+ const file = join(root, `${slug}.md`);
+ renameSync(file, `${file}.original`);
+ mkdirSync(file);
+ const failed = await put('Rejected replacement.');
+ expect(failed.response.isError).toBe(true);
+ expect(failed.payload.error).toBe('storage_error');
+ expect(await engine.getPage(slug, { sourceId: 'default' })).toEqual(before);
+ expect(await engine.getChunks(slug, { sourceId: 'default' })).toEqual(chunks);
+ expect(await engine.executeRaw('SELECT id FROM page_versions')).toHaveLength(0);
+ });
+
+ test('pgvector failure is reported after the canonical write, without rolling back the page', async () => {
+ const engine = getEngine();
+ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: 1536, env: { OPENAI_API_KEY: 'sk-test' } });
+ __setEmbedTransportForTests(async ({ values }) => {
+ expect((await engine.getPage(slug, { sourceId: 'default' }))?.compiled_truth).toBe('Persists before vector validation.');
+ expect(readFileSync(join(root, `${slug}.md`), 'utf8')).toContain('Persists before vector validation.');
+ return { values, warnings: [], embeddings: values.map(() => [0.1, 0.2]), usage: { tokens: 1 } };
+ });
+ const result = await put('Persists before vector validation.');
+ expect(result.response.isError).not.toBe(true);
+ expect(result.payload.status).toBe('created_or_updated');
+ expect(result.payload.embedding.status).toBe('failed');
+ expect(result.payload.write_through.written).toBe(true);
+ expect((await engine.getChunks(slug, { sourceId: 'default' })).every(chunk => chunk.embedding_is_null)).toBe(true);
+ });
+
+ test('slow embedding releases the worktree before other writes and rejects superseded vectors', async () => {
+ const engine = getEngine();
+ const started = Promise.withResolvers<void>();
+ const release = Promise.withResolvers<void>();
+ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: 1536, env: { OPENAI_API_KEY: 'sk-test' } });
+ __setEmbedTransportForTests(async ({ values }) => {
+ if (values.some(value => value.includes('Older pending revision.'))) {
+ started.resolve();
+ await release.promise;
+ }
+ return { values, warnings: [], embeddings: values.map(() => new Array(1536).fill(0.1)), usage: { tokens: 1 } };
+ });
+ const pending = put('Older pending revision.');
+ await started.promise;
+ try {
+ expect(readFileSync(join(root, `${slug}.md`), 'utf8')).toContain('Older pending revision.');
+ expect((await put('Independent saved page.', 'notes/independent')).response.isError).not.toBe(true);
+ expect((await put('Replacement saved revision.')).response.isError).not.toBe(true);
+ } finally {
+ release.resolve();
+ await pending;
+ }
+ expect((await pending).payload.embedding).toEqual({ status: 'superseded' });
+ expect((await engine.getPage(slug, { sourceId: 'default' }))?.compiled_truth).toBe('Replacement saved revision.');
+ expect(readFileSync(join(root, `${slug}.md`), 'utf8')).toContain('Replacement saved revision.');
+ expect((await engine.getChunks(slug, { sourceId: 'default' })).map(chunk => chunk.chunk_text)).toEqual(['Replacement saved revision.']);
+ }, 15_000);
+});
diff --git a/test/e2e/serve-http-oauth.test.ts b/test/e2e/serve-http-oauth.test.ts
index 7130e9e408..d04f79bb27 100644
--- a/test/e2e/serve-http-oauth.test.ts
+++ b/test/e2e/serve-http-oauth.test.ts
@@ -14,6 +14,8 @@
import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
import { createHash } from 'crypto';
+import { auth, extractWWWAuthenticateParams, type OAuthClientProvider } from '@modelcontextprotocol/sdk/client/auth.js';
+import type { OAuthTokens } from '@modelcontextprotocol/sdk/shared/auth.js';
import { hasDatabase } from './helpers.ts';
import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';
@@ -444,6 +446,115 @@ describeE2E('serve-http OAuth 2.1 E2E (v0.26.1 + v0.26.2 + v0.26.3)', () => {
expect((await meta.json() as any).resource).toBe(`${BASE}/mcp`);
});
+ test('scope discovery permits DCR without requesting operator-only delegation', async () => {
+ const metadata = await (await fetch(`${BASE}/.well-known/oauth-authorization-server`)).json() as any;
+ const response = await fetch(metadata.registration_endpoint, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ client_name: 'e2e-discovered-scopes',
+ redirect_uris: ['https://example.test/callback'],
+ grant_types: ['authorization_code', 'refresh_token'],
+ response_types: ['code'],
+ token_endpoint_auth_method: 'none',
+ scope: metadata.scopes_supported.join(' '),
+ }),
+ });
+ const client = await response.json() as any;
+ if (client.client_id) dcrClientIds.push(client.client_id);
+ expect(response.status).toBe(201);
+ expect(client.scope.split(' ')).toEqual(metadata.scopes_supported);
+ expect(metadata.scopes_supported).not.toContain('agent');
+ for (const path of ['/.well-known/oauth-protected-resource/mcp', '/.well-known/oauth-protected-resource']) {
+ const resource = await (await fetch(`${BASE}${path}`)).json() as any;
+ expect(resource.scopes_supported).toEqual(metadata.scopes_supported);
+ }
+ });
+
+ test.each(['agent', 'read write agent'])('DCR still rejects explicit delegation scope %s', async scope => {
+ const name = `e2e-refused-delegation-${scope.replaceAll(' ', '-')}`;
+ const response = await fetch(`${BASE}/register`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ client_name: name, redirect_uris: ['https://example.test/callback'],
+ grant_types: ['authorization_code'], token_endpoint_auth_method: 'none', scope }),
+ });
+ expect(response.status).toBe(400);
+ expect(await response.json()).toMatchObject({ error: 'invalid_client_metadata' });
+ await withSql(async sql => {
+ expect(await sql`SELECT client_id FROM oauth_clients WHERE client_name = ${name}`).toHaveLength(0);
+ });
+ });
+
+ for (const [label, registeredScope, explicitScope, expectedRequest] of [
+ ['read-only discovery', 'read', undefined, 'read'],
+ ['read-only overbroad hint', 'read', 'read write', 'read write'],
+ ['explicit writer request', 'read write', 'read write', 'read write'],
+ ] as const) {
+ test(`SDK scope selection and owner-approved PKCE: ${label}`, async () => {
+ const redirectUri = 'https://example.test/callback';
+ const metadata = { client_name: `e2e-scope-${label}`, redirect_uris: [redirectUri],
+ grant_types: ['authorization_code', 'refresh_token'], response_types: ['code'],
+ token_endpoint_auth_method: 'none', scope: registeredScope };
+ const registration = await fetch(`${BASE}/register`, { method: 'POST',
+ headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(metadata) });
+ expect(registration.status).toBe(201);
+ const client = await registration.json() as any;
+ dcrClientIds.push(client.client_id);
+ const challenge = await mcpCall('', 'tools/list');
+ expect(challenge.status).toBe(401);
+ const discovered = extractWWWAuthenticateParams(challenge);
+ let verifier = '';
+ let authorizationUrl: URL | undefined;
+ let tokens: OAuthTokens | undefined;
+ const provider: OAuthClientProvider = {
+ redirectUrl: redirectUri, clientMetadata: metadata,
+ clientInformation: () => client, tokens: () => tokens,
+ saveTokens: value => { tokens = value; },
+ saveCodeVerifier: value => { verifier = value; }, codeVerifier: () => verifier,
+ redirectToAuthorization: value => { authorizationUrl = value; },
+ };
+ expect(await auth(provider, { serverUrl: `${BASE}/mcp`,
+ resourceMetadataUrl: discovered.resourceMetadataUrl, scope: explicitScope ?? discovered.scope })).toBe('REDIRECT');
+ expect(authorizationUrl!.searchParams.get('scope')).toBe(expectedRequest);
+ const pending = await fetch(authorizationUrl!, { redirect: 'manual' });
+ expect(pending.status).toBe(302);
+ const requestId = new URL(pending.headers.get('location')!, BASE).searchParams.get('oauth_request');
+ expect(requestId).toBeTruthy();
+ const login = await fetch(`${BASE}/admin/login`, { method: 'POST',
+ headers: { 'Content-Type': 'application/json', 'X-Forwarded-For': '192.0.2.51' },
+ body: JSON.stringify({ token: ADMIN_BOOTSTRAP_TOKEN }) });
+ expect(login.status).toBe(200);
+ const session = login.headers.get('set-cookie')?.match(/gbrain_admin=([^;]+)/);
+ expect(session).toBeTruthy();
+ const cookie = `gbrain_admin=${session![1]}`;
+ const detailsResponse = await fetch(`${BASE}/admin/api/oauth-requests/${requestId}`, {
+ headers: { Cookie: cookie, 'X-Forwarded-For': '192.0.2.51' } });
+ expect(detailsResponse.status).toBe(200);
+ const details = await detailsResponse.json() as any;
+ expect(details.scopes).toEqual(registeredScope.split(' '));
+ const approval = await fetch(`${BASE}/admin/api/oauth-requests/${requestId}`, { method: 'POST',
+ headers: { Cookie: cookie, 'Content-Type': 'application/json', 'X-Forwarded-For': '192.0.2.51' },
+ body: JSON.stringify({ decision: 'approve', csrf: details.csrf }) });
+ expect(approval.status).toBe(200);
+ const code = new URL((await approval.json() as any).redirectUrl).searchParams.get('code')!;
+ expect(await auth(provider, { serverUrl: `${BASE}/mcp`, authorizationCode: code })).toBe('AUTHORIZED');
+ expect(tokens!.scope).toBe(registeredScope);
+ if (label === 'read-only overbroad hint') expect(tokens!.scope).not.toBe(expectedRequest);
+ else expect(tokens!.scope).toBe(expectedRequest);
+ const listed = await mcpToolResult(tokens!.access_token, 'tools/list');
+ expect(listed.tools.some((tool: any) => tool.name === 'get_page')).toBe(true);
+ if (registeredScope === 'read') {
+ expect(listed.tools.some((tool: any) => tool.name === 'put_page')).toBe(false);
+ const denied = await mcpToolResult(tokens!.access_token, 'tools/call', {
+ name: 'put_page', arguments: { slug: 'e2e-scope-denied', content: '# Not permitted' },
+ });
+ expect(denied.isError).toBe(true);
+ expect(denied.content[0].text).toContain('insufficient_scope');
+ }
+ });
+ }
+
// =========================================================================
// Fix 3: Express 5 compatibility
// =========================================================================
diff --git a/test/e2e/source-boundary-mutation-postgres.test.ts b/test/e2e/source-boundary-mutation-postgres.test.ts
index 937191cc71..0742f6cbf0 100644
--- a/test/e2e/source-boundary-mutation-postgres.test.ts
+++ b/test/e2e/source-boundary-mutation-postgres.test.ts
@@ -71,12 +71,14 @@ describePg('#4109 source-boundary mutation deletion races — Postgres', () => {
const mutation = getEngine().addLink(from, to).finally(() => {
settled = true;
});
+ const settledMutation = mutation.catch(() => undefined);
// The FOR KEY SHARE endpoint lookup must block on the open delete.
await Bun.sleep(50);
expect(settled).toBeFalse();
releaseDelete.resolve();
await deletion;
+ await settledMutation;
await expect(mutation).rejects.toThrow(
`addLink failed: to page "${to}" (source=default) not found`,
);
@@ -105,11 +107,13 @@ describePg('#4109 source-boundary mutation deletion races — Postgres', () => {
.finally(() => {
settled = true;
});
+ const settledMutation = mutation.catch(() => undefined);
await Bun.sleep(50);
expect(settled).toBeFalse();
releaseDelete.resolve();
await deletion;
+ await settledMutation;
await expect(mutation).rejects.toThrow(
`addTimelineEntry failed: page "${slug}" (source=default) not found`,
);
diff --git a/test/e2e/upsert-chunks-registry-column.test.ts b/test/e2e/upsert-chunks-registry-column.test.ts
index 7e136f24ca..0f7a6fe93b 100644
--- a/test/e2e/upsert-chunks-registry-column.test.ts
+++ b/test/e2e/upsert-chunks-registry-column.test.ts
@@ -53,6 +53,39 @@ async function columnTruth(
// ---- Shared scenario, run against both engines (parity) -----------------
function registryWriteScenario(name: string, getEngine: () => BrainEngine) {
+ for (const column of ['embedding_test8', 'embedding_hv8']) {
+ test(`${name}: resumed invalidation preserves proven current ${column} vectors (#5051)`, async () => {
+ const engine = getEngine();
+ const slug = 'docs/resumed-signature';
+ const signature = 'voyage:voyage-3-large:8';
+ await engine.setConfig('embedding_columns', REGISTRY_JSON);
+ await engine.setConfig('search_embedding_column', column);
+ try {
+ for (const guarded of [false, true]) {
+ for (const includeNullSignature of [false, true]) {
+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: '# resumed' });
+ await engine.upsertChunks(slug, [0, 1].map((i) => ({
+ chunk_index: i, chunk_text: `resumed chunk ${i}`, chunk_source: 'compiled_truth',
+ embedding: VEC8, model: i === 0 ? 'voyage:voyage-3-large' : 'foreign:model',
+ })));
+ if (!includeNullSignature) await engine.setPageEmbeddingSignature(slug, { signature: 'old:model:8' });
+ const opts = { signature, includeNullSignature };
+ const invalidated = guarded
+ ? await invalidateStaleSignatureEmbeddingsGuarded(engine, opts)
+ : await engine.invalidateStaleSignatureEmbeddings(opts);
+ expect(invalidated).toBe(1);
+ const chunks = await engine.getChunks(slug);
+ expect(chunks.map((chunk) => chunk.embedding_is_null)).toEqual([false, true]);
+ await engine.deletePage(slug);
+ }
+ }
+ } finally {
+ await engine.deletePage(slug);
+ await engine.setConfig('search_embedding_column', 'embedding_test8');
+ }
+ });
+ }
+
test(`${name}: registry-routed write lands in the active column, not legacy embedding`, async () => {
const engine = getEngine();
await engine.setConfig('search_embedding_column', 'embedding_test8');
diff --git a/test/embed-stale-signature-pagination.serial.test.ts b/test/embed-stale-signature-pagination.serial.test.ts
index 07d601cd37..d617af0a40 100644
--- a/test/embed-stale-signature-pagination.serial.test.ts
+++ b/test/embed-stale-signature-pagination.serial.test.ts
@@ -17,6 +17,7 @@ import {
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import type { ChunkInput } from '../src/core/types.ts';
import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { embedStaleForSource, EMBED_PROBE_TEXT } from '../src/core/embed-stale.ts';
const DIMS = 1536;
const MODEL = 'openai:text-embedding-3-large';
@@ -101,6 +102,51 @@ beforeEach(async () => {
});
describe('embed --stale page-level signature reconciliation', () => {
+ test('signature drift preserves completed chunks across interrupted source drains (#5051)', async () => {
+ await seedPage('interrupted-page', [0, 1, 2].map((i) => embeddedChunk(i, 'old:model')));
+ await engine.setPageEmbeddingSignature('interrupted-page', { signature: `old:model:${DIMS}` });
+ const controller = new AbortController();
+ const first = await embedStaleForSource(engine, 'default', {
+ embeddingSignature: SIGNATURE,
+ batchSize: 1,
+ signal: controller.signal,
+ embedFn: async (texts) => texts.map(() => new Float32Array(DIMS).fill(0.003)),
+ onProgress: () => controller.abort(),
+ });
+ expect(first.invalidated).toBe(3);
+ expect(first.embedded).toBe(1);
+ expect(await pageSignature('interrupted-page')).toBe(`old:model:${DIMS}`);
+
+ const inputs: string[] = [];
+ const second = await embedStaleForSource(engine, 'default', {
+ embeddingSignature: SIGNATURE,
+ batchSize: 1,
+ embedFn: async (texts) => {
+ inputs.push(...texts.filter((text) => text !== EMBED_PROBE_TEXT));
+ return texts.map(() => new Float32Array(DIMS).fill(0.004));
+ },
+ });
+ expect(second.invalidated).toBe(0);
+ expect(second.embedded).toBe(2);
+ expect(inputs).toEqual(['embedded chunk 1', 'embedded chunk 2']);
+ expect(second.done).toBe(true);
+ expect(await pageSignature('interrupted-page')).toBe(SIGNATURE);
+ });
+
+ test('fully current vectors with a stale page stamp converge without re-embedding (#5051)', async () => {
+ await seedPage('current-vectors', [embeddedChunk(0), embeddedChunk(1)]);
+ await engine.setPageEmbeddingSignature('current-vectors', { signature: `old:model:${DIMS}` });
+ let embeddedInputs = 0;
+ transportBehavior = async (input) => {
+ embeddedInputs += input.values.filter((text) => text !== EMBED_PROBE_TEXT).length;
+ return fakeTransport(input);
+ };
+ const result = await runEmbedCore(engine, { stale: true, catchUp: true, quiet: true });
+ expect(result.embedded).toBe(0);
+ expect(embeddedInputs).toBe(0);
+ expect(await pageSignature('current-vectors')).toBe(SIGNATURE);
+ });
+
test('page split across the 2,000-row cursor boundary is stamped after the pass', async () => {
for (let page = 0; page < 40; page++) {
const chunkCount = page === 39 ? 49 : 50;
diff --git a/test/embed-stale.serial.test.ts b/test/embed-stale.serial.test.ts
index c346bdcaea..f51eb0316b 100644
--- a/test/embed-stale.serial.test.ts
+++ b/test/embed-stale.serial.test.ts
@@ -430,6 +430,8 @@ describe('signature invalidation is probe-gated (#4283)', () => {
// The re-embed stamps only a signature naming the model the vectors were
// actually written under (#4825), so the target names the recorded model.
const target = `${await recordedModel('p1')}:1536`;
+ await engine.executeRaw(`UPDATE content_chunks SET model = 'old:model'
+ WHERE page_id = (SELECT id FROM pages WHERE slug = 'p1' AND source_id = 'default')`);
const seen: string[] = [];
const result = await embedStaleForSource(engine, 'default', {
embeddingSignature: target,
diff --git a/test/embedding-signature-stale.test.ts b/test/embedding-signature-stale.test.ts
index c7d3e626e6..e053c1f721 100644
--- a/test/embedding-signature-stale.test.ts
+++ b/test/embedding-signature-stale.test.ts
@@ -17,6 +17,8 @@ import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:tes
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { resetPgliteState } from './helpers/reset-pglite.ts';
import type { ChunkInput } from '../src/core/types.ts';
+import { invalidateStaleSignatureEmbeddingsGuarded } from '../src/core/embedding-invalidation.ts';
+import { stampIfPageProvenanceComplete } from '../src/core/embed-stale.ts';
let engine: PGLiteEngine;
let colDim: number;
@@ -63,6 +65,57 @@ async function seedEmbedded(slug: string, text: string, signature: string | null
}
describe('embedding_signature stale semantics', () => {
+ for (const guarded of [false, true]) {
+ for (const includeNullSignature of [false, true]) {
+ test(`preserves only proven current chunks (guarded=${guarded}, null=${includeNullSignature}) (#5051)`, async () => {
+ const model = 'ollama:example-model:latest';
+ const signature = `${model}:${colDim}`;
+ const slug = 'mixed-provenance';
+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: '# mixed' });
+ await engine.upsertChunks(slug, Array.from({ length: 5 }, (_, i) => ({
+ chunk_index: i, chunk_text: `chunk ${i}`, chunk_source: 'compiled_truth',
+ embedding: new Float32Array(colDim).fill(0.1), model,
+ })));
+ if (!includeNullSignature) await engine.setPageEmbeddingSignature(slug, { signature: 'old:model:1' });
+ await engine.executeRaw(`UPDATE content_chunks SET
+ model = CASE WHEN chunk_index = 1 THEN 'foreign:model' WHEN chunk_index = 2 THEN 'example-model:latest' ELSE model END,
+ embedded_text_hash = CASE WHEN chunk_index = 3 THEN NULL WHEN chunk_index = 4 THEN 'changed' ELSE embedded_text_hash END
+ WHERE page_id = (SELECT id FROM pages WHERE slug = $1 AND source_id = 'default')`, [slug]);
+ const opts = { signature, sourceId: 'default', includeNullSignature };
+ const invalidated = guarded
+ ? await invalidateStaleSignatureEmbeddingsGuarded(engine, opts)
+ : await engine.invalidateStaleSignatureEmbeddings(opts);
+ expect(invalidated).toBe(4);
+ const rows = await engine.executeRaw<{ chunk_index: number }>(
+ `SELECT chunk_index FROM content_chunks WHERE embedding IS NOT NULL ORDER BY chunk_index`,
+ );
+ expect(rows.map((row) => row.chunk_index)).toEqual([0]);
+ });
+ }
+ }
+
+ test('matching model and text cannot preserve vectors of the wrong width (#5051)', async () => {
+ await seedEmbedded('wrong-width', 'text', 'old:model:1');
+ await engine.executeRaw(`UPDATE content_chunks SET model = 'target:model', embedded_text_hash = md5(chunk_text)`);
+ expect(await invalidateStaleSignatureEmbeddingsGuarded(engine, {
+ signature: `target:model:${colDim + 1}`,
+ })).toBe(1);
+ });
+
+ test('completion stamps require matching vector width (#5051)', async () => {
+ await seedEmbedded('wrong-width-stamp', 'text', 'old:model:1');
+ await engine.executeRaw(`UPDATE content_chunks SET model = 'target:model', embedded_text_hash = md5(chunk_text)`);
+ expect(await stampIfPageProvenanceComplete(engine, 'wrong-width-stamp', 'default', {
+ signature: `target:model:${colDim + 1}`, column: 'embedding',
+ })).toBe(false);
+ });
+
+ test('unparseable signatures never claim provenance or preserve unknown widths (#5051)', async () => {
+ await seedEmbedded('unknown-width', 'text', 'old:model:1');
+ await engine.executeRaw(`UPDATE content_chunks SET model = 'target:model', embedded_text_hash = md5(chunk_text)`);
+ expect(await invalidateStaleSignatureEmbeddingsGuarded(engine, { signature: 'target:model' })).toBe(1);
+ });
+
test('R-4 GRANDFATHER: NULL signature is never stale', async () => {
await seedEmbedded('legacy', 'abcde', null); // embedded, NULL signature
// No NULL embeddings, NULL signature → not stale under any signature.
diff --git a/test/entity-resolve.test.ts b/test/entity-resolve.test.ts
index 6a2806d1fa..43edad54c6 100644
--- a/test/entity-resolve.test.ts
+++ b/test/entity-resolve.test.ts
@@ -172,6 +172,51 @@ describe('resolveEntitySlug — prefix expansion', () => {
});
});
+describe('source-scoped full basename resolution', () => {
+ it('resolves hyphenated names and concepts without relying on title similarity', async () => {
+ for (const slug of ['companies/acme-example', 'concepts/retrieval-testing']) {
+ await engine.putPage(slug, {
+ type: 'note', title: 'Unrelated display title', compiled_truth: 'Existing page', frontmatter: {},
+ }, { sourceId: 'default' });
+ const basename = slug.split('/')[1];
+ for (const raw of [basename, basename.replaceAll('-', ' ')]) {
+ expect(await resolveEntitySlug(engine, 'default', raw)).toBe(slug);
+ expect(await resolveEntitySlugWithSource(engine, 'default', raw)).toEqual({
+ slug, source: 'fuzzy_match',
+ });
+ }
+ }
+ });
+
+ it('refuses same-basename ambiguity even if one title is a perfect fuzzy match', async () => {
+ for (const slug of ['companies/shared-example', 'projects/shared-example']) {
+ await engine.putPage(slug, {
+ type: 'note', title: slug.startsWith('companies/') ? 'shared-example' : 'Other title',
+ compiled_truth: 'Existing page', frontmatter: {},
+ }, { sourceId: 'default' });
+ }
+ expect(await resolveEntitySlug(engine, 'default', 'shared-example')).toBe('shared-example');
+ expect(await resolveEntitySlugWithSource(engine, 'default', 'shared-example')).toEqual({
+ slug: 'shared-example', source: 'fallback_slugify',
+ });
+ });
+
+ it('ignores same-basename pages in other sources and deleted pages', async () => {
+ await engine.executeRaw(`INSERT INTO sources (id, name) VALUES ('basename-other', 'Other')`);
+ await engine.putPage('companies/scoped-example', {
+ type: 'company', title: 'Unrelated title', compiled_truth: 'Other source', frontmatter: {},
+ }, { sourceId: 'basename-other' });
+ await engine.putPage('companies/scoped-example', {
+ type: 'company', title: 'Unrelated title', compiled_truth: 'Deleted page', frontmatter: {},
+ }, { sourceId: 'default' });
+ await engine.softDeletePage('companies/scoped-example', { sourceId: 'default' });
+ expect((await resolveEntitySlugWithSource(engine, 'default', 'scoped-example'))?.source)
+ .toBe('fallback_slugify');
+ expect(await resolveEntitySlug(engine, 'basename-other', 'scoped-example'))
+ .toBe('companies/scoped-example');
+ });
+});
+
describe('slugify', () => {
it('lowercases and hyphenates', () => {
expect(slugify('Alice Example')).toBe('alice-example');
diff --git a/test/extract-conversation-facts-entity-resolution.test.ts b/test/extract-conversation-facts-entity-resolution.test.ts
index 0da1654915..c0fb867551 100644
--- a/test/extract-conversation-facts-entity-resolution.test.ts
+++ b/test/extract-conversation-facts-entity-resolution.test.ts
@@ -162,7 +162,7 @@ describe('conversation backfill entity resolution', () => {
expect(await dataEntities()).toEqual([
'people/brian-example',
- 'unlisted-person',
+ null,
null,
]);
expect(result.fallback_slugify_count).toBe(1);
@@ -256,11 +256,11 @@ describe('conversation backfill entity resolution', () => {
}]),
});
- expect(await dataEntities()).toEqual(['spectre']);
+ expect(await dataEntities()).toEqual([null]);
expect(result.fallback_slugify_count).toBe(1);
});
- test('best-effort resolver failure keeps the raw value and later segments checkpoint', async () => {
+ test('best-effort resolver failure keeps the fact unparented and later segments checkpoint', async () => {
await seedConversation(TWO_SEGMENT_BODY);
const original = resolve.resolveEntitySlugWithSource;
const spy = spyOn(resolve, 'resolveEntitySlugWithSource').mockImplementation(
@@ -286,7 +286,7 @@ describe('conversation backfill entity resolution', () => {
expect(await dataEntities()).toEqual([
'people/brian-example',
- 'Unlisted Person',
+ null,
'people/brian-example',
null,
]);
@@ -302,7 +302,7 @@ describe('conversation backfill entity resolution', () => {
const stderr = writeSpy.mock.calls.map((call) => String(call[0])).join('');
expect(stderr).toContain('entity resolution failed for "Unlisted Person"');
- expect(stderr).toContain('keeping raw value');
+ expect(stderr).toContain('preserving fact without an entity target');
} finally {
spy.mockRestore();
writeSpy.mockRestore();
diff --git a/test/facts-backstop-integration.test.ts b/test/facts-backstop-integration.test.ts
index 3f3ad8d97f..6107f3e717 100644
--- a/test/facts-backstop-integration.test.ts
+++ b/test/facts-backstop-integration.test.ts
@@ -126,6 +126,48 @@ describe('runFactsPipeline (extract_facts MCP op path) — response shape stabil
expect(r.entity_slugs).toEqual([]);
});
+ test('unresolved entity references stay unparented with provenance in every storage mode', async () => {
+ const { mkdtempSync, readdirSync, rmSync } = await import('node:fs');
+ const { tmpdir } = await import('node:os');
+ const { join } = await import('node:path');
+ const { _resetWriteThroughCacheForTest } = await import('../src/core/write-through.ts');
+ const dir = mkdtempSync(join(tmpdir(), 'unresolved-facts-'));
+ try {
+ for (const mode of ['thin-client', 'local', 'disabled']) {
+ await engine.executeRaw(`UPDATE sources SET local_path = $1 WHERE id = 'default'`,
+ [mode === 'thin-client' ? null : dir]);
+ await engine.setConfig('sync.write_through', mode === 'disabled' ? 'false' : 'true');
+ _resetWriteThroughCacheForTest();
+ chatStub(['Unresolved Example', 'people/missing-example'].map(entity => ({
+ fact: `${mode}: ${entity} supplied a useful fact`, entity, kind: 'fact', notability: 'high',
+ })));
+ const result = await runFactsPipeline('A conversation with unresolved entities', {
+ engine, sourceId: 'default', sessionId: `unresolved-${mode}`, source: 'mcp:extract_facts',
+ sourceSlug: 'meetings/provenance-example',
+ });
+ expect(result.inserted).toBe(2);
+ expect(result.entity_slugs).toEqual([]);
+ const rows = await engine.executeRaw<{
+ entity_slug: string | null; source: string; context: string | null; row_num: number | null;
+ }>(`SELECT entity_slug, source, context, row_num FROM facts WHERE source_id = 'default' AND source_session = $1`,
+ [`unresolved-${mode}`]);
+ expect(rows).toHaveLength(2);
+ for (const row of rows) {
+ expect(row.entity_slug).toBeNull();
+ expect(row.source).toBe('mcp:extract_facts');
+ expect(row.context).toBe('meetings/provenance-example');
+ expect(row.row_num).toBeNull();
+ }
+ expect(readdirSync(dir)).toEqual([]);
+ }
+ } finally {
+ await engine.executeRaw(`UPDATE sources SET local_path = NULL WHERE id = 'default'`);
+ await engine.unsetConfig('sync.write_through');
+ _resetWriteThroughCacheForTest();
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
test('empty extraction → zero counts (no NaN, no undefined)', async () => {
chatStub([]);
const r = await runFactsPipeline('nothing claim-worthy here', {
diff --git a/test/facts-backstop.test.ts b/test/facts-backstop.test.ts
index 92ed198458..59eac4dbe6 100644
--- a/test/facts-backstop.test.ts
+++ b/test/facts-backstop.test.ts
@@ -297,9 +297,6 @@ describe('runFactsBackstop — dedup fast-path', () => {
describe('runFactsBackstop — stub guard routing (v0.34.5)', () => {
test('bare-name entity routes to legacy DB-only path (no phantom page)', async () => {
- // Set up: configure default source with a real local_path so the
- // backstop reaches Phase 5 (fence write) instead of Phase 4 (legacy).
- // This is the scenario where the stub guard actually fires.
const { mkdtempSync, rmSync, existsSync } = await import('node:fs');
const { tmpdir } = await import('node:os');
const { join } = await import('node:path');
@@ -319,9 +316,6 @@ describe('runFactsBackstop — stub guard routing (v0.34.5)', () => {
// 2. fuzzy match → miss (no title contains noresolvable)
// 3. prefix expansion → miss (no people/noresolvable-* rows)
// 4. slugify fallback → 'noresolvable' (bare)
- // The bare slug then trips the stub guard in writeFactsToFence,
- // which returns stubGuardBlocked: true, and backstop routes the
- // fact to engine.insertFact (DB-only).
chatStub([
{ fact: 'said hello at the meeting', kind: 'event', notability: 'high', entity: 'noresolvable' },
]);
@@ -337,14 +331,12 @@ describe('runFactsBackstop — stub guard routing (v0.34.5)', () => {
// No phantom file at the brain root (this is the whole point of the guard).
expect(existsSync(join(brainDir, 'noresolvable.md'))).toBe(false);
- // The fact is in the DB with the bare entity_slug. Query directly to
- // confirm — the routing is the contract under test.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const rows = await (engine as any).db.query(
`SELECT entity_slug, fact, source_markdown_slug FROM facts WHERE id = $1`,
[r.fact_ids[0]],
);
- expect(rows.rows[0].entity_slug).toBe('noresolvable');
+ expect(rows.rows[0].entity_slug).toBeNull();
expect(rows.rows[0].fact).toBe('said hello at the meeting');
// source_markdown_slug is the fence-tracking column; under DB-only
// fallback it stays null (no .md file backs the row).
@@ -367,8 +359,9 @@ describe('runFactsBackstop — sync.write_through opt-out', () => {
const brainDir = mkdtempSync(join(tmpdir(), 'backstop-write-through-flag-'));
try {
- // Fence-eligible setup: local_path set AND a prefixed entity slug —
- // without the flag this would stub-create people/flag-test.md.
+ await engine.putPage('people/flag-test', {
+ type: 'person', title: 'Flag Test', compiled_truth: '# Existing entity', frontmatter: {},
+ }, { sourceId: 'default' });
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await (engine as any).db.query(
`UPDATE sources SET local_path = $1 WHERE id = 'default'`,
diff --git a/test/migrations-v0_32_2.test.ts b/test/migrations-v0_32_2.test.ts
index 386a5d33ef..900b977124 100644
--- a/test/migrations-v0_32_2.test.ts
+++ b/test/migrations-v0_32_2.test.ts
@@ -18,7 +18,7 @@ import { execFileSync } from 'node:child_process';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { v0_32_2, __setTestEngineOverride, __testing } from '../src/commands/migrations/v0_32_2.ts';
-import { parseFactsFence } from '../src/core/facts-fence.ts';
+import { parseFactsFence, upsertFactRow } from '../src/core/facts-fence.ts';
let engine: PGLiteEngine;
let brainDir: string;
@@ -39,6 +39,7 @@ beforeEach(async () => {
brainDir = mkdtempSync(join(tmpdir(), 'mig-v0_32_2-test-'));
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await (engine as any).db.query('DELETE FROM facts');
+ await engine.executeRaw('DELETE FROM pages');
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await (engine as any).db.query(
`UPDATE sources SET local_path = $1 WHERE id = 'default'`,
@@ -55,7 +56,24 @@ async function seedLegacyFact(input: {
source_id?: string;
visibility?: 'private' | 'world';
notability?: 'high' | 'medium' | 'low';
+ withPage?: boolean;
}): Promise<number> {
+ const sourceId = input.source_id ?? 'default';
+ if (input.entity_slug && input.withPage !== false &&
+ !await engine.getPage(input.entity_slug, { sourceId })) {
+ await engine.putPage(input.entity_slug, {
+ type: 'note', title: input.entity_slug, compiled_truth: '# Existing page\n', frontmatter: {},
+ }, { sourceId });
+ const sources = await engine.executeRaw<{ local_path: string | null }>(
+ 'SELECT local_path FROM sources WHERE id = $1', [sourceId],
+ );
+ const root = sources[0]?.local_path;
+ if (root) {
+ const path = join(root, `${input.entity_slug}.md`);
+ mkdirSync(join(path, '..'), { recursive: true });
+ if (!existsSync(path)) writeFileSync(path, '# Existing page\n');
+ }
+ }
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const r = await (engine as any).db.query(
`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, notability,
@@ -105,8 +123,8 @@ describe('phaseBFenceFacts — dry-run reporting', () => {
expect(r.detail).toContain('would fence 2 rows'); // 3 total - 1 unparented
expect(r.detail).toContain('1 unfenceable');
- // No files created.
- expect(existsSync(join(brainDir, 'people/alice.md'))).toBe(false);
+ expect(readFileSync(join(brainDir, 'people/alice.md'), 'utf8')).toBe('# Existing page\n');
+ expect(readFileSync(join(brainDir, 'people/bob.md'), 'utf8')).toBe('# Existing page\n');
// DB rows still have NULL row_num.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const rows = await (engine as any).db.query(
@@ -126,7 +144,7 @@ describe('phaseBFenceFacts — happy path backfill', () => {
expect(r.detail).toContain('fenced=2');
expect(r.detail).toContain('pages=1');
- // Stub-page exists with fence content.
+ // Existing page now has fence content.
const filePath = join(brainDir, 'people/alice.md');
expect(existsSync(filePath)).toBe(true);
const body = readFileSync(filePath, 'utf-8');
@@ -239,6 +257,182 @@ describe('phaseBFenceFacts — happy path backfill', () => {
});
});
+describe('phaseBFenceFacts — missing pages and occupied fence rows', () => {
+ const slug = 'people/alice-example';
+
+ async function page(body = '# Existing notes\n', sourcePath = `${slug}.md`): Promise<string> {
+ await engine.putPage(slug, {
+ type: 'person', title: 'Alice Example', compiled_truth: body, frontmatter: {}, source_path: sourcePath,
+ }, { sourceId: 'default' });
+ const filePath = join(brainDir, sourcePath);
+ mkdirSync(join(filePath, '..'), { recursive: true });
+ writeFileSync(filePath, body);
+ return filePath;
+ }
+
+ test('skips unresolved root slugs and missing page files without creating stubs or deleting facts', async () => {
+ const existingPath = await page();
+ await seedLegacyFact({ entity_slug: slug, fact: 'Existing page fact' });
+ await seedLegacyFact({ entity_slug: 'missing-example', fact: 'Unresolved root fact', withPage: false });
+ await seedLegacyFact({ entity_slug: 'projects/missing-example', fact: 'Missing prefixed fact', withPage: false });
+ await engine.putPage('projects/missing-example', {
+ type: 'project', title: 'Missing Example', compiled_truth: 'DB-only page', frontmatter: {},
+ }, { sourceId: 'default' });
+ const result = await __testing.phaseBFenceFacts(engine, OPTS);
+ expect(result.status).toBe('complete');
+ expect(result.detail).toContain('skipped_no_page=2');
+ expect(result.detail).toContain('fenced=1');
+ expect(existsSync(join(brainDir, 'missing-example.md'))).toBe(false);
+ expect(existsSync(join(brainDir, 'projects/missing-example.md'))).toBe(false);
+ expect(readFileSync(existingPath, 'utf8')).toContain('# Existing notes');
+ const rows = await engine.executeRaw<{ fact: string; row_num: number | null }>(
+ `SELECT fact, row_num FROM facts ORDER BY id`,
+ );
+ expect(rows).toEqual([
+ { fact: 'Existing page fact', row_num: 1 },
+ { fact: 'Unresolved root fact', row_num: null },
+ { fact: 'Missing prefixed fact', row_num: null },
+ ]);
+ });
+
+ test('requires a live entity page in the fact source even when an orphan file exists', async () => {
+ await engine.executeRaw(`INSERT INTO sources (id, name) VALUES ('migration-other', 'Other') ON CONFLICT DO NOTHING`);
+ await engine.putPage('foreign-example', {
+ type: 'note', title: 'Foreign Example', compiled_truth: 'Other source', frontmatter: {},
+ }, { sourceId: 'migration-other' });
+ const orphan = join(brainDir, 'foreign-example.md');
+ writeFileSync(orphan, '# Local orphan file\n');
+ await seedLegacyFact({ entity_slug: 'foreign-example', fact: 'Keep unparented', withPage: false });
+ const result = await __testing.phaseBFenceFacts(engine, OPTS);
+ expect(result.detail).toContain('skipped_no_page=1');
+ expect(readFileSync(orphan, 'utf8')).toBe('# Local orphan file\n');
+ });
+
+ test('dry-run reports missing pages and a dirty source containing only unfenceable facts is a no-op', async () => {
+ execFileSync('git', ['-C', brainDir, 'init', '-q']);
+ writeFileSync(join(brainDir, 'unrelated.md'), '# Uncommitted notes\n');
+ await seedLegacyFact({ entity_slug: 'missing-example', fact: 'No target', withPage: false });
+ const dry = await __testing.phaseBFenceFacts(engine, DRY_OPTS);
+ expect(dry.status).toBe('skipped');
+ expect(dry.detail).toContain('would fence 0 rows');
+ expect(dry.detail).toContain('skipped_no_page=1');
+ const write = await __testing.phaseBFenceFacts(engine, OPTS);
+ expect(write.status).toBe('complete');
+ expect(write.detail).toContain('skipped_no_page=1');
+ expect(existsSync(join(brainDir, 'missing-example.md'))).toBe(false);
+ });
+
+ test('writes and verifies the recorded page path instead of creating a slug-named twin', async () => {
+ const path = await page('# Existing notes\n', 'People/Alice Example.md');
+ await seedLegacyFact({ entity_slug: slug, fact: 'Recorded file fact' });
+ expect((await __testing.phaseBFenceFacts(engine, OPTS)).status).toBe('complete');
+ expect(parseFactsFence(readFileSync(path, 'utf8')).facts[0]?.claim).toBe('Recorded file fact');
+ expect(existsSync(join(brainDir, `${slug}.md`))).toBe(false);
+ expect((await __testing.phaseCVerify(engine, OPTS)).status).toBe('complete');
+ });
+
+ test('allocates above DB-owned numbers after a markdown fence disappeared', async () => {
+ await page();
+ await engine.executeRaw(
+ `INSERT INTO facts (source_id, entity_slug, fact, kind, source, row_num, source_markdown_slug)
+ VALUES ('default', $1, 'Already indexed', 'fact', 'mcp:put_page', 7, $1)`, [slug],
+ );
+ await seedLegacyFact({ entity_slug: slug, fact: 'Needs fencing' });
+ const result = await __testing.phaseBFenceFacts(engine, OPTS);
+ expect(result.status).toBe('complete');
+ expect(await engine.executeRaw(`SELECT fact, row_num FROM facts ORDER BY row_num`)).toEqual([
+ { fact: 'Already indexed', row_num: 7 }, { fact: 'Needs fencing', row_num: 8 },
+ ]);
+ });
+
+ test('moves a stranded colliding row without dropping an earlier appended fact', async () => {
+ const body = upsertFactRow('# Existing notes\n', {
+ rowNum: 1, claim: 'Stranded fact', kind: 'fact', confidence: 1, visibility: 'private',
+ notability: 'medium', source: 'mcp:put_page',
+ }).body;
+ const path = await page(body);
+ await engine.executeRaw(
+ `INSERT INTO facts (source_id, entity_slug, fact, kind, source, row_num, source_markdown_slug)
+ VALUES ('default', $1, 'Already indexed', 'fact', 'mcp:put_page', 1, $1)`, [slug],
+ );
+ await seedLegacyFact({ entity_slug: slug, fact: 'Append before stranded' });
+ await seedLegacyFact({ entity_slug: slug, fact: 'Stranded fact' });
+ expect((await __testing.phaseBFenceFacts(engine, OPTS)).status).toBe('complete');
+ const facts = parseFactsFence(readFileSync(path, 'utf8')).facts;
+ expect(facts.map(f => [f.claim, f.rowNum])).toEqual([
+ ['Stranded fact', 3], ['Append before stranded', 2],
+ ]);
+ expect(await engine.executeRaw(`SELECT fact, row_num FROM facts ORDER BY row_num`)).toEqual([
+ { fact: 'Already indexed', row_num: 1 },
+ { fact: 'Append before stranded', row_num: 2 },
+ { fact: 'Stranded fact', row_num: 3 },
+ ]);
+ });
+
+ test('never lets two legacy rows claim the same stranded fence row', async () => {
+ const path = await page(upsertFactRow('# Notes\n', {
+ rowNum: 5, claim: 'Same claim', kind: 'fact', confidence: 1, visibility: 'private',
+ notability: 'medium', source: 'mcp:put_page',
+ }).body);
+ await seedLegacyFact({ entity_slug: slug, fact: 'Same claim' });
+ await seedLegacyFact({ entity_slug: slug, fact: 'Same claim', visibility: 'world' });
+ expect((await __testing.phaseBFenceFacts(engine, OPTS)).status).toBe('complete');
+ expect(parseFactsFence(readFileSync(path, 'utf8')).facts.map(f => f.rowNum)).toEqual([5, 6]);
+ expect((await __testing.phaseCVerify(engine, OPTS)).status).toBe('complete');
+ });
+
+ test('preserves a legitimate DB-owned matching fence row and appends the separate legacy fact', async () => {
+ const path = await page(upsertFactRow('# Notes\n', {
+ rowNum: 4, claim: 'Shared claim', kind: 'fact', confidence: 0.8, visibility: 'private',
+ notability: 'high', source: 'mcp:put_page', context: 'Original provenance',
+ claimMetric: 'count', claimValue: 8,
+ }).body);
+ await engine.executeRaw(
+ `INSERT INTO facts (source_id, entity_slug, fact, kind, source, row_num, source_markdown_slug)
+ VALUES ('default', $1, 'Shared claim', 'fact', 'mcp:put_page', 4, $1)`, [slug],
+ );
+ await seedLegacyFact({ entity_slug: slug, fact: 'Shared claim', visibility: 'world' });
+ expect((await __testing.phaseBFenceFacts(engine, OPTS)).status).toBe('complete');
+ const facts = parseFactsFence(readFileSync(path, 'utf8')).facts;
+ expect(facts).toHaveLength(2);
+ expect(facts[0]).toMatchObject({
+ rowNum: 4, claim: 'Shared claim', confidence: 0.8, visibility: 'private',
+ notability: 'high', context: 'Original provenance', claimMetric: 'count', claimValue: 8,
+ });
+ expect(facts[1]).toMatchObject({ rowNum: 5, claim: 'Shared claim', visibility: 'world' });
+ expect((await __testing.phaseCVerify(engine, OPTS)).status).toBe('complete');
+ });
+
+ test('does not re-fence soft-expired facts or rewrite a malformed existing fence', async () => {
+ const path = await page();
+ const id = await seedLegacyFact({ entity_slug: slug, fact: 'Withdrawn fact' });
+ await engine.executeRaw('UPDATE facts SET expired_at = now() WHERE id = $1', [id]);
+ expect((await __testing.phaseBFenceFacts(engine, OPTS)).status).toBe('complete');
+ expect(readFileSync(path, 'utf8')).toBe('# Existing notes\n');
+ expect((await engine.executeRaw<{ row_num: number | null }>(
+ 'SELECT row_num FROM facts WHERE id = $1', [id],
+ ))[0].row_num).toBeNull();
+
+ const malformed = '# Notes\n\n## Facts\n<!--- gbrain:facts:begin -->\n| not a valid header |\n<!--- gbrain:facts:end -->\n';
+ writeFileSync(path, malformed);
+ await seedLegacyFact({ entity_slug: slug, fact: 'New fact' });
+ expect((await __testing.phaseBFenceFacts(engine, OPTS)).status).toBe('failed');
+ expect(readFileSync(path, 'utf8')).toBe(malformed);
+ });
+});
+
+describe('subdirectory source dirty check', () => {
+ test('ignores sibling changes but refuses changes inside the source', async () => {
+ execFileSync('git', ['-C', brainDir, 'init', '-q']);
+ const sourcePath = join(brainDir, 'source');
+ mkdirSync(sourcePath);
+ writeFileSync(join(brainDir, 'sibling.md'), 'Unrelated change');
+ expect(__testing.isLocalPathDirty(sourcePath)).toBe(false);
+ writeFileSync(join(sourcePath, 'local.md'), 'Local change');
+ expect(__testing.isLocalPathDirty(sourcePath)).toBe(true);
+ });
+});
+
describe('phaseBFenceFacts — dirty-tree refusal scoping (#927)', () => {
let dirtyDir: string;
@@ -353,7 +547,7 @@ describe('orchestrator end-to-end', () => {
});
test('dry-run returns 3 phases all skipped (no FS or DB changes)', async () => {
- await seedLegacyFact({ entity_slug: 'people/alice', fact: 'Should not get fenced' });
+ await seedLegacyFact({ entity_slug: 'people/alice', fact: 'Should not get fenced', withPage: false });
const result = await v0_32_2.orchestrator(DRY_OPTS);
expect(result.status).toBe('complete');
diff --git a/test/nightly-probe-exit-isolation.test.ts b/test/nightly-probe-exit-isolation.test.ts
new file mode 100644
index 0000000000..e963896311
--- /dev/null
+++ b/test/nightly-probe-exit-isolation.test.ts
@@ -0,0 +1,79 @@
+import { describe, expect, test } from 'bun:test';
+import { spawnSync } from 'node:child_process';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+function run(script: string) {
+ const home = mkdtempSync(join(tmpdir(), 'probe-exit-home-'));
+ try {
+ return spawnSync(process.execPath, ['-e', script], {
+ cwd: join(import.meta.dir, '..'),
+ encoding: 'utf-8',
+ timeout: 90_000,
+ env: { ...process.env, GBRAIN_HOME: home, GBRAIN_MODEL: '', GBRAIN_SKIP_STARTUP_HOOKS: '1' },
+ });
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+}
+
+describe('embedded nightly probe failures (#5095)', () => {
+ test('missing chat configuration is audited before embedding work and rate-limited', () => {
+ const child = run(`
+ import { configureGateway } from './src/core/ai/gateway.ts';
+ import { runLongMemEvalForProbe } from './src/core/cycle/nightly-probe-adapters.ts';
+ import { runNightlyQualityProbe } from './src/core/cycle/nightly-quality-probe.ts';
+ configureGateway({ env: {} });
+ const deps = {
+ isEnabled: () => true,
+ hasEmbeddingProvider: () => true,
+ resolveMaxUsd: () => 0,
+ resolveRepoRoot: () => process.cwd(),
+ runLongMemEval: runLongMemEvalForProbe,
+ runCrossModalBatch: async () => { throw new Error('judge must not run'); },
+ now: () => new Date(),
+ };
+ console.log(JSON.stringify(await runNightlyQualityProbe(deps)));
+ console.log(JSON.stringify(await runNightlyQualityProbe(deps)));
+ `);
+ expect(child.status, child.stderr).toBe(0);
+ expect(child.stdout).toContain('"outcome":"error"');
+ expect(child.stdout).toContain('"outcome":"rate_limited"');
+ expect(child.stdout).toContain('chat provider not configured');
+ expect(child.stderr).not.toContain('connecting in-memory brain');
+ }, 90_000);
+
+ test('the real adapter rejects an invalid fixture without exiting its host', () => {
+ const child = run(`
+ import { runLongMemEvalForProbe } from './src/core/cycle/nightly-probe-adapters.ts';
+ try {
+ await runLongMemEvalForProbe({ fixturePath: '/nonexistent-nightly-fixture.jsonl', outputPath: '/unused.jsonl' });
+ } catch (error) {
+ console.log('HOST_SURVIVED', String(error));
+ }
+ `);
+ expect(child.status, child.stderr).toBe(0);
+ expect(child.stdout).toContain('HOST_SURVIVED');
+ }, 90_000);
+
+ test('an all-error embedded evaluation rejects instead of terminating the host', () => {
+ const child = run(`
+ import { runEvalLongMemEval } from './src/commands/eval-longmemeval.ts';
+ try {
+ await runEvalLongMemEval([
+ './test/fixtures/longmemeval-mini.jsonl', '--keyword-only', '--no-trajectory', '--limit', '2'
+ ], {
+ exitOnError: false,
+ client: { create: async () => { throw new Error('synthetic provider unavailable'); } }
+ });
+ } catch (error) {
+ console.log('HOST_SURVIVED', String(error));
+ }
+ `);
+ expect(child.status, child.stderr).toBe(0);
+ expect(child.stderr).toContain('FAIL every question errored (2/2)');
+ expect(child.stderr).toContain('synthetic provider unavailable');
+ expect(child.stdout).toContain('HOST_SURVIVED');
+ }, 90_000);
+});
diff --git a/test/oauth-scope-hint.test.ts b/test/oauth-scope-hint.test.ts
new file mode 100644
index 0000000000..d6252e555d
--- /dev/null
+++ b/test/oauth-scope-hint.test.ts
@@ -0,0 +1,95 @@
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import express, { type RequestHandler } from 'express';
+import { requireBearerAuth } from '@modelcontextprotocol/sdk/server/auth/middleware/bearerAuth.js';
+import { InvalidTokenError } from '@modelcontextprotocol/sdk/server/auth/errors.js';
+import { withBearerScopeHint } from '../src/commands/serve-http-oauth.ts';
+
+let server: ReturnType<ReturnType<typeof express>['listen']>;
+let base: string;
+const resourceMetadataUrl = 'https://example.test/.well-known/oauth-protected-resource/mcp';
+
+beforeAll(async () => {
+ const app = express();
+ const verifier = {
+ async verifyAccessToken(token: string) {
+ if (token === 'invalid') throw new InvalidTokenError('Invalid token');
+ if (token === 'unavailable') throw new Error('Storage unavailable');
+ return { token, clientId: 'scope-hint-test', scopes: token === 'empty' ? [] : [token],
+ expiresAt: Math.floor(Date.now() / 1000) + (token === 'expired' ? -60 : 60) };
+ },
+ };
+ app.post('/mcp', withBearerScopeHint(requireBearerAuth({ verifier, resourceMetadataUrl }), ['read']), (req, res) => {
+ res.json({ scopes: req.auth!.scopes });
+ });
+ app.post('/write', withBearerScopeHint(requireBearerAuth({ verifier, resourceMetadataUrl, requiredScopes: ['write'] }), ['read']), (_req, res) => {
+ res.json({ ok: true });
+ });
+ await new Promise<void>(resolve => { server = app.listen(0, '127.0.0.1', () => resolve()); });
+ const address = server.address();
+ if (!address || typeof address === 'string') throw new Error('Expected TCP listener');
+ base = `http://127.0.0.1:${address.port}`;
+});
+
+afterAll(async () => {
+ if (server) await new Promise<void>((resolve, reject) => server.close(error => error ? reject(error) : resolve()));
+});
+
+describe('withBearerScopeHint with SDK HTTP middleware', () => {
+ test.each([undefined, 'Basic invalid', 'Bearer invalid', 'Bearer expired'])('hints read without weakening bearer validation: %s', async authorization => {
+ const response = await fetch(`${base}/mcp`, { method: 'POST',
+ headers: authorization ? { Authorization: authorization } : {} });
+ expect(response.status).toBe(401);
+ const challenge = response.headers.get('www-authenticate')!;
+ expect(challenge).toContain('scope="read"');
+ expect(challenge).toContain(`resource_metadata="${resourceMetadataUrl}"`);
+ expect(await response.json()).toMatchObject({ error: 'invalid_token' });
+ });
+
+ test.each(['read', 'write', 'agent', 'admin', 'sources_admin', 'users_admin', 'empty'])('does not enforce or enlarge a valid %s grant', async token => {
+ const response = await fetch(`${base}/mcp`, { method: 'POST', headers: { Authorization: `Bearer ${token}` } });
+ expect(response.status).toBe(200);
+ expect(response.headers.get('www-authenticate')).toBeNull();
+ expect(await response.json()).toEqual({ scopes: token === 'empty' ? [] : [token] });
+ });
+
+ test('preserves a real insufficient-scope challenge and enforcement', async () => {
+ const response = await fetch(`${base}/write`, { method: 'POST', headers: { Authorization: 'Bearer read' } });
+ expect(response.status).toBe(403);
+ const challenge = response.headers.get('www-authenticate')!;
+ expect(challenge.match(/scope=/g)).toHaveLength(1);
+ expect(challenge).toContain('scope="write"');
+ expect(await response.json()).toMatchObject({ error: 'insufficient_scope' });
+ });
+
+ test('does not turn verifier failures into authorization challenges', async () => {
+ const response = await fetch(`${base}/mcp`, { method: 'POST', headers: { Authorization: 'Bearer unavailable' } });
+ expect(response.status).toBe(500);
+ expect(response.headers.get('www-authenticate')).toBeNull();
+ expect(await response.json()).toMatchObject({ error: 'server_error' });
+ });
+});
+
+describe('withBearerScopeHint response adapter', () => {
+ test('preserves object-form headers and restores the setter after success', async () => {
+ const calls: unknown[][] = [];
+ const response = { set(...args: unknown[]) { calls.push(args); return response; } };
+ const originalSet = response.set;
+ const middleware: RequestHandler = (_req, res) => { res.set({ 'Cache-Control': 'no-store' }); };
+ await withBearerScopeHint(middleware, ['read'])({} as any, response as any, () => {});
+ expect(calls).toEqual([[{ 'Cache-Control': 'no-store' }]]);
+ expect(response.set).toBe(originalSet);
+ });
+
+ test('preserves other authentication schemes and restores the setter after failure', async () => {
+ const calls: unknown[][] = [];
+ const response = { set(...args: unknown[]) { calls.push(args); return response; } };
+ const originalSet = response.set;
+ const middleware: RequestHandler = (_req, res) => {
+ res.set('WWW-Authenticate', 'Basic realm="gbrain"');
+ throw new Error('synthetic failure');
+ };
+ await expect(withBearerScopeHint(middleware, ['read'])({} as any, response as any, () => {})).rejects.toThrow('synthetic failure');
+ expect(calls).toEqual([['WWW-Authenticate', 'Basic realm="gbrain"']]);
+ expect(response.set).toBe(originalSet);
+ });
+});
diff --git a/test/pglite-lock-process-probe.test.ts b/test/pglite-lock-process-probe.test.ts
new file mode 100644
index 0000000000..a8c3f72d23
--- /dev/null
+++ b/test/pglite-lock-process-probe.test.ts
@@ -0,0 +1,88 @@
+import { describe, expect, test } from 'bun:test';
+import { isPidReusedByOtherProgram } from '../src/core/pglite-lock.ts';
+import type { ProcessCommandProbeDeps } from '../src/core/autopilot-lock.ts';
+
+const PID = process.pid + 1000;
+
+function probe(command: string, platform: NodeJS.Platform = 'win32') {
+ const calls: string[] = [];
+ const deps: ProcessCommandProbeDeps = {
+ platform,
+ readCmdlineFile: () => { calls.push('proc'); throw new Error('unavailable'); },
+ execFile: (file, args, options) => {
+ calls.push(file);
+ if (platform === 'win32') {
+ if (file !== 'powershell.exe') throw new Error('unavailable');
+ expect(args).toContain('-NonInteractive');
+ expect(args.join(' ')).toContain(`ProcessId=${PID}`);
+ expect(options.windowsHide).toBe(true);
+ }
+ return command;
+ },
+ };
+ return { deps, calls };
+}
+
+describe('PGLite process command probes', () => {
+ test('Windows reclaims an unrelated PID using CIM, not POSIX probes (#5065)', () => {
+ const { deps, calls } = probe('C:\\Windows\\System32\\notepad.exe');
+ expect(isPidReusedByOtherProgram(PID, ['C:\\bin\\cli.ts', 'serve'], null, null, deps)).toBe(true);
+ expect(calls).toEqual(['powershell.exe']);
+ });
+
+ for (const argv of [undefined, ['C:\\Users\\Example User\\project\\src\\CLI.TS', 'serve']]) {
+ test(`Windows case and separator drift does not steal a live holder (structured=${!!argv})`, () => {
+ const { deps } = probe('"C:\\Program Files\\Bun\\bun.exe" run src/cli.ts serve');
+ expect(isPidReusedByOtherProgram(PID, argv, null, null, deps)).toBe(false);
+ });
+ }
+
+ test('structured argv still proves a genuinely unrelated process', () => {
+ const { deps } = probe('C:\\Windows\\System32\\notepad.exe');
+ const argv = ['C:\\Users\\Example User\\project\\src\\cli.ts', 'serve'];
+ expect(isPidReusedByOtherProgram(PID, argv, null, null, deps)).toBe(true);
+ });
+
+ test('Windows paths match a relative command by backslash-delimited basename', () => {
+ const { deps } = probe('bun cli.ts serve');
+ expect(isPidReusedByOtherProgram(PID, ['C:\\project\\src\\cli.ts', 'serve'], null, null, deps)).toBe(false);
+ });
+
+ for (const argv of [undefined, null, [], [42], [''], ['cli.ts', 42], 'cli.ts']) {
+ test(`malformed structured argv cannot prove reuse: ${JSON.stringify(argv)}`, () => {
+ const { deps } = probe('bun other.ts', 'darwin');
+ expect(isPidReusedByOtherProgram(PID, argv, null, null, deps)).toBe(false);
+ });
+ }
+
+ test('unreadable or empty Windows command lines cannot prove reuse', () => {
+ for (const output of [null, '', ' ']) {
+ const { deps } = probe('');
+ deps.execFile = () => { if (output === null) throw new Error('denied'); return output; };
+ expect(isPidReusedByOtherProgram(PID, ['cli.ts', 'serve'], null, null, deps)).toBe(false);
+ }
+ });
+
+ test('non-Windows retains ps first and proc fallback', () => {
+ const { deps, calls } = probe('sleep 60', 'darwin');
+ expect(isPidReusedByOtherProgram(PID, ['cli.ts', 'serve'], null, null, deps)).toBe(true);
+ expect(calls).toEqual(['ps']);
+ calls.length = 0;
+ deps.execFile = () => { calls.push('ps'); throw new Error('unavailable'); };
+ deps.readCmdlineFile = () => { calls.push('proc'); return 'bun\0src/cli.ts\0serve\0'; };
+ expect(isPidReusedByOtherProgram(PID, ['cli.ts', 'serve'], null, null, deps)).toBe(false);
+ expect(calls).toEqual(['ps', 'proc']);
+ });
+
+ test('the current PID and unverified Linux namespace never trigger a command probe', () => {
+ const { deps, calls } = probe('other', 'linux');
+ expect(isPidReusedByOtherProgram(process.pid, ['cli.ts', 'serve'], null, null, deps)).toBe(false);
+ expect(isPidReusedByOtherProgram(PID, ['cli.ts', 'serve'], null, null, deps)).toBe(false);
+ expect(calls).toEqual([]);
+ });
+
+ test('non-Windows path comparisons remain case sensitive', () => {
+ const { deps } = probe('bun OTHER.ts', 'darwin');
+ expect(isPidReusedByOtherProgram(PID, ['other.ts', 'serve'], null, null, deps)).toBe(true);
+ });
+});
diff --git a/test/pglite-lock.test.ts b/test/pglite-lock.test.ts
index 5c9f78e6e3..84f4e8e491 100644
--- a/test/pglite-lock.test.ts
+++ b/test/pglite-lock.test.ts
@@ -86,6 +86,16 @@ describe('pglite-lock', () => {
await releaseLock(lock);
});
+ test('lock file preserves argv boundaries (#5072)', async () => {
+ const lock = await acquireLock(TEST_DIR);
+ try {
+ const lockData = JSON.parse(readFileSync(join(TEST_DIR, '.gbrain-lock', 'lock'), 'utf-8'));
+ expect(lockData.argv).toEqual(process.argv.slice(1));
+ } finally {
+ await releaseLock(lock);
+ }
+ });
+
test('releases lock on disconnect even if DB close fails', async () => {
const lock = await acquireLock(TEST_DIR);
expect(lock.acquired).toBe(true);
@@ -474,7 +484,7 @@ describe('pglite-lock PID-reuse detection', () => {
try { return readlinkSync('/proc/self/ns/pid'); } catch { return null; }
}
- function writeHolderAt(dataDir: string, pid: number, command: string, opts?: { subcommand?: string; bootId?: string | null; pidNs?: string | null }) {
+ function writeHolderAt(dataDir: string, pid: number, command: string, opts?: { subcommand?: string; bootId?: string | null; pidNs?: string | null; argv?: unknown }) {
const lockDir = join(dataDir, '.gbrain-lock');
mkdirSync(lockDir, { recursive: true });
const now = Date.now();
@@ -483,6 +493,7 @@ describe('pglite-lock PID-reuse detection', () => {
acquired_at: now - 60_000,
refreshed_at: now - 60_000,
command,
+ argv: opts?.argv,
boot_id: opts?.bootId === undefined ? currentBootId() : opts.bootId,
pid_ns: opts?.pidNs === undefined ? currentPidNs() : opts.pidNs,
...(opts?.subcommand === undefined ? {} : { subcommand: opts.subcommand }),
@@ -509,12 +520,46 @@ describe('pglite-lock PID-reuse detection', () => {
throw new Error(`child ${pid} never exec'd into ${pattern}`);
}
+ for (const [script, structured] of [
+ ['/Users/Example User/project/src/cli.ts', true],
+ ['/Users/Example User/project/src/cli.ts', false],
+ ['C:\\Users\\Example User\\project\\src\\cli.ts', true],
+ ['C:\\Users\\Example User\\project\\src\\cli.ts', false],
+ ] as const) {
+ test.skipIf(!canProbe)(`does not reap a live holder with ${structured ? 'structured' : 'legacy'} argv path ${script} (#5072)`, async () => {
+ const holder = Bun.spawn(['bash', '-c', 'exec -a "bun run src/cli.ts serve --http" sleep 60'], {
+ stdout: 'ignore', stderr: 'ignore',
+ });
+ try {
+ await waitForExec(holder.pid, /src\/cli\.ts/);
+ writeHolderAt(TEST_DIR, holder.pid, `${script} serve --http`, {
+ subcommand: 'serve', argv: structured ? [script, 'serve', '--http'] : undefined,
+ });
+ let stolen: LockHandle | undefined;
+ try {
+ await expect((async () => { stolen = await acquireLock(TEST_DIR, { timeoutMs: 200 }); })())
+ .rejects.toThrow(/already open through `gbrain serve`/);
+ const data = JSON.parse(readFileSync(join(TEST_DIR, '.gbrain-lock', 'lock'), 'utf-8'));
+ expect(data.pid).toBe(holder.pid);
+ } finally {
+ if (stolen) await releaseLock(stolen);
+ }
+ } finally {
+ holder.kill();
+ await holder.exited;
+ rmSync(join(TEST_DIR, '.gbrain-lock'), { recursive: true, force: true });
+ }
+ });
+ }
+
test.skipIf(!canProbe)('reaps a lock whose PID was recycled by an unrelated program', async () => {
// `sleep` is a live process that is provably NOT the gbrain holder.
const squatter = Bun.spawn(['sleep', '60'], { stdout: 'ignore', stderr: 'ignore' });
try {
await waitForExec(squatter.pid, /sleep/);
- writeHolderAt(TEST_DIR, squatter.pid, '/home/user/.bun/bin/gbrain serve --http', { subcommand: 'serve' });
+ writeHolderAt(TEST_DIR, squatter.pid, '/home/user/.bun/bin/gbrain serve --http', {
+ subcommand: 'serve', argv: ['/home/user/.bun/bin/gbrain', 'serve', '--http'],
+ });
const lock = await acquireLock(TEST_DIR, { timeoutMs: 5000 });
try {
@@ -538,7 +583,9 @@ describe('pglite-lock PID-reuse detection', () => {
const holder = Bun.spawn(['bash', '-c', 'sleep 60; exit 0', 'gbrain-fake-holder'], { stdout: 'ignore', stderr: 'ignore' });
try {
await waitForExec(holder.pid, /gbrain-fake-holder/);
- writeHolderAt(TEST_DIR, holder.pid, 'gbrain-fake-holder embed', { subcommand: 'embed' });
+ writeHolderAt(TEST_DIR, holder.pid, 'gbrain-fake-holder embed', {
+ subcommand: 'embed', argv: ['gbrain-fake-holder', 'embed'],
+ });
await expect(acquireLock(TEST_DIR, { timeoutMs: 1200 })).rejects.toThrow(/Timed out/);
// Live holder's lock was never stolen.
@@ -560,7 +607,9 @@ describe('pglite-lock PID-reuse detection', () => {
const holder = Bun.spawn(['bash', '-c', 'sleep 60; exit 0', 'bun run src/cli.ts serve --http'], { stdout: 'ignore', stderr: 'ignore' });
try {
await waitForExec(holder.pid, /cli\.ts/);
- writeHolderAt(TEST_DIR, holder.pid, '/home/user/checkouts/brain-project/src/cli.ts serve --http', { subcommand: 'serve' });
+ writeHolderAt(TEST_DIR, holder.pid, '/home/user/checkouts/brain-project/src/cli.ts serve --http', {
+ subcommand: 'serve', argv: ['/home/user/checkouts/brain-project/src/cli.ts', 'serve', '--http'],
+ });
await expect(acquireLock(TEST_DIR, { timeoutMs: 1200 })).rejects.toThrow(/already open through `gbrain serve`/);
expect(existsSync(join(TEST_DIR, '.gbrain-lock'))).toBe(true);
@@ -576,7 +625,9 @@ describe('pglite-lock PID-reuse detection', () => {
const squatter = Bun.spawn(['sleep', '60'], { stdout: 'ignore', stderr: 'ignore' });
try {
await waitForExec(squatter.pid, /sleep/);
- writeHolderAt(TEST_DIR, squatter.pid, '/home/user/.bun/bin/gbrain serve --http', { subcommand: 'serve', pidNs: 'pid:[1]' });
+ writeHolderAt(TEST_DIR, squatter.pid, '/home/user/.bun/bin/gbrain serve --http', {
+ subcommand: 'serve', pidNs: 'pid:[1]', argv: ['/home/user/.bun/bin/gbrain', 'serve', '--http'],
+ });
await expect(acquireLock(TEST_DIR, { timeoutMs: 1200 })).rejects.toThrow(/already open through `gbrain serve`/);
expect(existsSync(join(TEST_DIR, '.gbrain-lock'))).toBe(true);
@@ -608,7 +659,9 @@ describe('pglite-lock PID-reuse detection', () => {
const squatter = Bun.spawn(['sleep', '60'], { stdout: 'ignore', stderr: 'ignore' });
try {
await waitForExec(squatter.pid, /sleep/);
- writeHolderAt(TEST_DIR, squatter.pid, '/home/user/.bun/bin/gbrain serve --http', { subcommand: 'serve', bootId: null });
+ writeHolderAt(TEST_DIR, squatter.pid, '/home/user/.bun/bin/gbrain serve --http', {
+ subcommand: 'serve', bootId: null, argv: ['/home/user/.bun/bin/gbrain', 'serve', '--http'],
+ });
await expect(acquireLock(TEST_DIR, { timeoutMs: 1200 })).rejects.toThrow(/already open through `gbrain serve`/);
expect(existsSync(join(TEST_DIR, '.gbrain-lock'))).toBe(true);
@@ -633,7 +686,9 @@ describe('pglite-lock PID-reuse detection', () => {
const squatter = Bun.spawn(['sleep', '60'], { stdout: 'ignore', stderr: 'ignore' });
try {
await waitForExec(squatter.pid, /sleep/);
- writeHolderAt(TEST_DIR, squatter.pid, '/home/user/.bun/bin/gbrain serve --http', { subcommand: 'serve' });
+ writeHolderAt(TEST_DIR, squatter.pid, '/home/user/.bun/bin/gbrain serve --http', {
+ subcommand: 'serve', argv: ['/home/user/.bun/bin/gbrain', 'serve', '--http'],
+ });
const results = await Promise.allSettled([
acquireLock(TEST_DIR, { timeoutMs: 5000 }),
diff --git a/test/put-page-persistence.test.ts b/test/put-page-persistence.test.ts
new file mode 100644
index 0000000000..b1acfa3107
--- /dev/null
+++ b/test/put-page-persistence.test.ts
@@ -0,0 +1,338 @@
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { withSourceFilesystemLock } from '../src/core/minions/source-filesystem.ts';
+import { _resetWriteThroughCacheForTest } from '../src/core/write-through.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { contentHashLegacy } from '../src/core/utils.ts';
+
+let engine: PGLiteEngine;
+let root: string;
+const auth = { token: 'fixture', clientId: 'fixture-client', scopes: ['read', 'write'], sourceId: 'default', boundSlugPrefixes: ['notes'] };
+const content = (body: string, tags = 'original') => `---\ntitle: Example\ntype: note\ntags: [${tags}]\n---\n\n${body}`;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ await resetPgliteState(engine);
+ resetGateway();
+ _resetWriteThroughCacheForTest();
+ root = mkdtempSync(join(tmpdir(), 'gbrain-put-persistence-'));
+ await engine.setConfig('sync.repo_path', root);
+});
+
+afterEach(() => {
+ __setEmbedTransportForTests(null);
+ resetGateway();
+ _resetWriteThroughCacheForTest();
+ rmSync(root, { recursive: true, force: true });
+});
+
+async function put(slug: string, body: string, sourceId = 'default') {
+ const response = await dispatchToolCall(engine, 'put_page', { slug, content: body }, {
+ remote: true,
+ sourceId,
+ auth: { ...auth, sourceId },
+ logger: { info() {}, warn() {}, error() {} },
+ });
+ return { response, payload: JSON.parse((response.content[0] as { text: string }).text) };
+}
+
+async function snapshot(slug: string) {
+ return {
+ page: await engine.getPage(slug, { sourceId: 'default' }),
+ tags: await engine.getTags(slug, { sourceId: 'default' }),
+ chunks: await engine.getChunks(slug, { sourceId: 'default' }),
+ versions: await engine.executeRaw('SELECT * FROM page_versions ORDER BY id'),
+ };
+}
+
+describe('put_page persistence boundary', () => {
+ test('contended worktree rejects existing and new pages without publishing either, while another root writes', async () => {
+ const slug = 'notes/existing';
+ await put(slug, content('Original durable body.'));
+ const before = await snapshot(slug);
+ const disk = readFileSync(join(root, `${slug}.md`), 'utf8');
+ const otherRoot = mkdtempSync(join(tmpdir(), 'gbrain-put-independent-'));
+ await engine.executeRaw("INSERT INTO sources (id, name, local_path) VALUES ('other', 'other', $1)", [otherRoot]);
+ const entered = Promise.withResolvers<void>();
+ const release = Promise.withResolvers<void>();
+ const holder = withSourceFilesystemLock(engine, root, async () => {
+ entered.resolve();
+ await release.promise;
+ });
+ await entered.promise;
+ try {
+ const writes = Promise.all([
+ put(slug, content('Rejected replacement.', 'replacement')),
+ put('notes/new', content('Rejected creation.')),
+ ]);
+ const independent = await put('notes/independent', content('Independent content.'), 'other');
+ expect(independent.response.isError).not.toBe(true);
+ expect(readFileSync(join(otherRoot, 'notes/independent.md'), 'utf8')).toContain('Independent content.');
+ const rejected = await writes;
+ expect(await snapshot(slug)).toEqual(before);
+ expect(await engine.getPage('notes/new', { sourceId: 'default' })).toBeNull();
+ expect(readFileSync(join(root, `${slug}.md`), 'utf8')).toBe(disk);
+ expect(existsSync(join(root, 'notes/new.md'))).toBe(false);
+ for (const result of rejected) {
+ expect(result.response.isError).toBe(true);
+ expect(result.payload.error).toBe('storage_busy');
+ expect(result.payload.suggestion).toContain('retry');
+ expect(result.payload.message).toContain('not queued');
+ }
+ } finally {
+ release.resolve();
+ await holder;
+ rmSync(otherRoot, { recursive: true, force: true });
+ }
+ expect((await put(slug, content('Accepted replacement.'))).response.isError).not.toBe(true);
+ expect(readFileSync(join(root, `${slug}.md`), 'utf8')).toContain('Accepted replacement.');
+ }, 15_000);
+
+ test('rename failure rolls back the existing page, tags, chunks, and version snapshot', async () => {
+ const slug = 'notes/rename-failure';
+ await put(slug, content('Original before failed rename.'));
+ const before = await snapshot(slug);
+ const file = join(root, `${slug}.md`);
+ const original = readFileSync(file, 'utf8');
+ renameSync(file, `${file}.original`);
+ mkdirSync(file);
+ const failed = await put(slug, content('Must not replace the visible page.', 'rejected'));
+ expect(failed.response.isError).toBe(true);
+ expect(failed.payload.error).toBe('storage_error');
+ expect(await snapshot(slug)).toEqual(before);
+ expect(readFileSync(`${file}.original`, 'utf8')).toBe(original);
+ });
+
+ test('an unchanged legacy-hash page also rolls back when its canonical file is refused', async () => {
+ const slug = 'notes/legacy-hash';
+ const body = content('Unchanged legacy body.');
+ await put(slug, body);
+ const page = (await engine.getPage(slug, { sourceId: 'default' }))!;
+ await engine.executeRaw('UPDATE pages SET content_hash = $1 WHERE id = $2', [contentHashLegacy(page), page.id]);
+ const before = await snapshot(slug);
+ const file = join(root, `${slug}.md`);
+ renameSync(file, `${file}.original`);
+ mkdirSync(file);
+ const failed = await put(slug, body);
+ expect(failed.response.isError).toBe(true);
+ expect(await snapshot(slug)).toEqual(before);
+ });
+
+ test('source-path bookkeeping failure rejects before replacing the canonical file', async () => {
+ const slug = 'notes/source-path-failure';
+ await put(slug, content('Original canonical content.'));
+ await engine.executeRaw('UPDATE pages SET source_path = NULL WHERE slug = $1', [slug]);
+ const before = await snapshot(slug);
+ const file = join(root, `${slug}.md`);
+ const originalFile = readFileSync(file, 'utf8');
+ const executeRaw = engine.executeRaw;
+ let rejected = false;
+ engine.executeRaw = function<T>(sql: string, params?: unknown[]): Promise<T[]> {
+ if (sql.includes('SET source_path = $1')) {
+ rejected = true;
+ throw new Error('fixture source-path write rejected');
+ }
+ return executeRaw.call(this, sql, params) as Promise<T[]>;
+ };
+ try {
+ const result = await put(slug, content('Rejected replacement.', 'replacement'));
+ expect(rejected).toBe(true);
+ expect(result.response.isError).toBe(true);
+ expect(result.payload.error).toBe('storage_error');
+ } finally {
+ engine.executeRaw = executeRaw;
+ }
+ expect(await snapshot(slug)).toEqual(before);
+ expect(readFileSync(file, 'utf8')).toBe(originalFile);
+ });
+
+ test('a waiter sees no visible mutation until the holder releases, then writes exactly once', async () => {
+ const slug = 'notes/short-wait';
+ await put(slug, content('Before waiting.'));
+ const before = await snapshot(slug);
+ const entered = Promise.withResolvers<void>();
+ const release = Promise.withResolvers<void>();
+ const holder = withSourceFilesystemLock(engine, root, async () => {
+ entered.resolve();
+ await release.promise;
+ });
+ await entered.promise;
+ const pending = put(slug, content('After waiting.'));
+ try {
+ await Bun.sleep(100);
+ expect(await snapshot(slug)).toEqual(before);
+ expect(readFileSync(join(root, `${slug}.md`), 'utf8')).toContain('Before waiting.');
+ } finally {
+ release.resolve();
+ await holder;
+ await pending;
+ }
+ expect((await pending).response.isError).not.toBe(true);
+ expect((await snapshot(slug)).versions).toHaveLength(1);
+ expect(readFileSync(join(root, `${slug}.md`), 'utf8')).toContain('After waiting.');
+ });
+
+ test('canonical page is committed before an embedding failure and remains a successful persisted write', async () => {
+ const slug = 'notes/embed-failure';
+ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: 1536, env: { OPENAI_API_KEY: 'sk-test' } });
+ let calls = 0;
+ let observedCommitted = false;
+ __setEmbedTransportForTests(async () => {
+ calls++;
+ observedCommitted = (await engine.getPage(slug, { sourceId: 'default' }))?.compiled_truth.includes('Survives embedding failure.') === true
+ && existsSync(join(root, `${slug}.md`))
+ && readFileSync(join(root, `${slug}.md`), 'utf8').includes('Survives embedding failure.');
+ throw new Error('fixture embedding rejected');
+ });
+ const result = await put(slug, content('Survives embedding failure.'));
+ expect(calls).toBeGreaterThan(0);
+ expect(observedCommitted).toBe(true);
+ expect(result.response.isError).not.toBe(true);
+ expect(result.payload.status).toBe('created_or_updated');
+ expect(result.payload.embedding?.status).toBe('failed');
+ expect(result.payload.write_through.written).toBe(true);
+ expect((await engine.getChunks(slug, { sourceId: 'default' })).every(chunk => chunk.embedding_is_null)).toBe(true);
+ expect(await engine.executeRaw('SELECT id FROM minion_jobs')).toHaveLength(0);
+ });
+
+ test('successful post-persistence embeddings fill only the written page', async () => {
+ const slug = 'notes/embed-success';
+ await put('notes/unrelated', content('Unrelated unembedded body.'));
+ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: 1536, env: { OPENAI_API_KEY: 'sk-test' } });
+ __setEmbedTransportForTests(async ({ values }) => {
+ expect(readFileSync(join(root, `${slug}.md`), 'utf8')).toContain('Page-scoped enrichment.');
+ expect((await engine.getPage(slug, { sourceId: 'default' }))?.compiled_truth).toBe('Page-scoped enrichment.');
+ return { values, warnings: [], embeddings: values.map(() => new Array(1536).fill(0.1)), usage: { tokens: 1 } };
+ });
+ const result = await put(slug, content('Page-scoped enrichment.'));
+ expect(result.response.isError).not.toBe(true);
+ expect(result.payload.embedding).toEqual({ status: 'embedded' });
+ expect((await engine.getChunks(slug, { sourceId: 'default' })).every(chunk => !chunk.embedding_is_null)).toBe(true);
+ expect((await engine.getChunks('notes/unrelated', { sourceId: 'default' })).every(chunk => chunk.embedding_is_null)).toBe(true);
+ expect(await engine.executeRaw('SELECT id FROM minion_jobs')).toHaveLength(0);
+ });
+
+ test('slow optional embedding releases the worktree and cannot overwrite a newer file-backed revision', async () => {
+ const slug = 'notes/slow-embedding';
+ const started = Promise.withResolvers<void>();
+ const release = Promise.withResolvers<void>();
+ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: 1536, env: { OPENAI_API_KEY: 'sk-test' } });
+ __setEmbedTransportForTests(async ({ values }) => {
+ if (values.some(value => value.includes('Older revision waiting for embedding.'))) {
+ started.resolve();
+ await release.promise;
+ }
+ return { values, warnings: [], embeddings: values.map(() => new Array(1536).fill(0.1)), usage: { tokens: 1 } };
+ });
+ const pending = put(slug, content('Older revision waiting for embedding.'));
+ await started.promise;
+ try {
+ expect(readFileSync(join(root, `${slug}.md`), 'utf8')).toContain('Older revision waiting for embedding.');
+ const independent = await put('notes/independent-embedding', content('Another page in the same worktree.'));
+ expect(independent.response.isError).not.toBe(true);
+ expect(independent.payload.embedding).toEqual({ status: 'embedded' });
+ const replacement = await put(slug, content('Newer file-backed revision.'));
+ expect(replacement.response.isError).not.toBe(true);
+ expect(replacement.payload.embedding).toEqual({ status: 'embedded' });
+ } finally {
+ release.resolve();
+ await pending;
+ }
+ expect((await pending).payload.embedding).toEqual({ status: 'superseded' });
+ expect(readFileSync(join(root, `${slug}.md`), 'utf8')).toContain('Newer file-backed revision.');
+ expect((await engine.getPage(slug, { sourceId: 'default' }))?.compiled_truth).toBe('Newer file-backed revision.');
+ expect((await engine.getChunks(slug, { sourceId: 'default' })).map(chunk => chunk.chunk_text)).toEqual(['Newer file-backed revision.']);
+ }, 15_000);
+
+ test('successful MCP persistence never returns credentials from an embedding error', async () => {
+ const slug = 'notes/embed-error-redaction';
+ const credentialUrl = 'https://fixture-user:[email protected]/v1?token=fixture-private-token';
+ const bearer = 'Bearer fixture-private-bearer';
+ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: 1536, env: { OPENAI_API_KEY: 'sk-test' } });
+ __setEmbedTransportForTests(async () => {
+ throw new Error(`Embedding request failed at ${credentialUrl}; Authorization: ${bearer}`);
+ });
+ const result = await put(slug, content('Persisted without disclosing provider credentials.'));
+ expect(result.response.isError).not.toBe(true);
+ expect(result.payload.status).toBe('created_or_updated');
+ expect(result.payload.embedding.status).toBe('failed');
+ const responseText = JSON.stringify(result.response);
+ for (const sensitive of [credentialUrl, 'fixture-user', 'PLACEHOLDER', 'embed.example', 'fixture-private-token', bearer, 'fixture-private-bearer']) {
+ expect(responseText.includes(sensitive)).toBe(false);
+ }
+ expect(result.payload.embedding.error).toBe('Page content was saved, but embedding failed. Check the embedding provider and database on the brain host, then run gbrain embed --stale --source <source-id>.');
+ expect((await engine.getPage(slug, { sourceId: 'default' }))?.compiled_truth).toBe('Persisted without disclosing provider credentials.');
+ expect(readFileSync(join(root, `${slug}.md`), 'utf8')).toContain('Persisted without disclosing provider credentials.');
+ expect((await engine.getChunks(slug, { sourceId: 'default' })).every(chunk => chunk.embedding_is_null)).toBe(true);
+ });
+
+ test('a concurrent DB-only revision cannot receive stale post-persistence chunks', async () => {
+ const slug = 'notes/embed-superseded';
+ await engine.setConfig('sync.repo_path', '');
+ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: 1536, env: { OPENAI_API_KEY: 'sk-test' } });
+ __setEmbedTransportForTests(async ({ values }) => {
+ await importFromContent(engine, slug, content('Intervening revision.'), { noEmbed: true, sourceId: 'default' });
+ return { values, warnings: [], embeddings: values.map(() => new Array(1536).fill(0.1)), usage: { tokens: 1 } };
+ });
+ const result = await put(slug, content('Older revision being embedded.'));
+ expect(result.response.isError).not.toBe(true);
+ expect(result.payload.embedding).toEqual({ status: 'superseded' });
+ expect((await engine.getPage(slug, { sourceId: 'default' }))?.compiled_truth).toBe('Intervening revision.');
+ const chunks = await engine.getChunks(slug, { sourceId: 'default' });
+ expect(chunks.map(chunk => chunk.chunk_text)).toEqual(['Intervening revision.']);
+ expect(chunks.every(chunk => chunk.embedding_is_null)).toBe(true);
+ });
+
+ test('rechunking unchanged content cannot be undone by an older embedding completion', async () => {
+ const slug = 'notes/rechunk-superseded';
+ const body = content('Content with a replaced chunk generation.');
+ await engine.setConfig('sync.repo_path', '');
+ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: 1536, env: { OPENAI_API_KEY: 'sk-test' } });
+ __setEmbedTransportForTests(async ({ values }) => {
+ await importFromContent(engine, slug, body, { noEmbed: true, sourceId: 'default', forceRechunk: true });
+ return { values, warnings: [], embeddings: values.map(() => new Array(1536).fill(0.1)), usage: { tokens: 1 } };
+ });
+ const result = await put(slug, body);
+ expect(result.response.isError).not.toBe(true);
+ expect(result.payload.embedding).toEqual({ status: 'superseded' });
+ expect((await engine.getChunks(slug, { sourceId: 'default' })).every(chunk => chunk.embedding_is_null)).toBe(true);
+ });
+
+ for (const action of ['soft-delete', 'hard-delete', 'recreate'] as const) {
+ test(`late embedding cannot revive or replace a ${action} page`, async () => {
+ const slug = 'notes/deleted-embedding';
+ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: 1536, env: { OPENAI_API_KEY: 'sk-test' } });
+ __setEmbedTransportForTests(async ({ values }) => {
+ if (action === 'soft-delete') await engine.softDeletePage(slug, { sourceId: 'default' });
+ else await engine.deletePage(slug, { sourceId: 'default' });
+ if (action === 'recreate') {
+ await importFromContent(engine, slug, content('Recreated content.'), { noEmbed: true, sourceId: 'default' });
+ }
+ return { values, warnings: [], embeddings: values.map(() => new Array(1536).fill(0.1)), usage: { tokens: 1 } };
+ });
+ expect((await put(slug, content('Old page content.'))).payload.embedding).toEqual({ status: 'superseded' });
+ const page = await engine.getPage(slug, { sourceId: 'default' });
+ if (action === 'recreate') {
+ expect(page?.compiled_truth).toBe('Recreated content.');
+ expect((await engine.getChunks(slug, { sourceId: 'default' })).every(chunk => chunk.embedding_is_null)).toBe(true);
+ } else {
+ expect(page).toBeNull();
+ }
+ });
+ }
+});
diff --git a/test/remediation-run-loop.serial.test.ts b/test/remediation-run-loop.serial.test.ts
index 5dff5ab1de..9e13c21d57 100644
--- a/test/remediation-run-loop.serial.test.ts
+++ b/test/remediation-run-loop.serial.test.ts
@@ -83,7 +83,7 @@ describe('runRemediation idempotency-key rotation (#3626)', () => {
attemptedJobs.length = 0;
submittedKeys.length = 0;
seededRows.clear();
- const health = makeHealth();
+ const health = { ...makeHealth(), missing_embeddings: 1 };
const engine = {
kind: 'postgres',
getHealth: async () => health,
@@ -108,7 +108,7 @@ describe('runRemediation idempotency-key rotation (#3626)', () => {
// Steps 1+2 re-ran for REAL under rotated keys; step 3 deduped onto the
// in-flight waiting row with no rotated resubmit.
- expect(attemptedJobs).toEqual(['backlinks', 'sync']);
+ expect(attemptedJobs).toEqual(['embed', 'backlinks']);
expect(submittedKeys).toEqual([
baseKeys[0]!,
`${baseKeys[0]!}:r:${result.doctor_run_id}`,
@@ -147,11 +147,10 @@ describe('runRemediation recheck loop guard', () => {
const result = await runRemediation(engine, { maxJobs: 4 });
expect(attemptedJobs.filter((name) => name === 'backlinks')).toHaveLength(1);
- expect(attemptedJobs).toEqual(['backlinks', 'sync', 'extract']);
+ expect(attemptedJobs).toEqual(['backlinks', 'extract']);
expect(result.submitted.map((step) => step.id)).toEqual([
'backlinks.fix',
- 'sync.repo',
- 'extract.all',
+ 'extract.stale',
]);
});
});
diff --git a/test/schema-pack-config-key.test.ts b/test/schema-pack-config-key.test.ts
new file mode 100644
index 0000000000..6906d68148
--- /dev/null
+++ b/test/schema-pack-config-key.test.ts
@@ -0,0 +1,27 @@
+import { afterEach, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { runCli } from './helpers/cli-spawn.ts';
+
+const homes: string[] = [];
+afterEach(() => { for (const home of homes.splice(0)) rmSync(home, { recursive: true, force: true }); });
+
+test('documented schema_pack config command writes and reads the brain-wide DB tier without force', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-schema-config-'));
+ homes.push(home);
+ mkdirSync(join(home, '.gbrain'));
+ const configPath = join(home, '.gbrain', 'config.json');
+ const config = JSON.stringify({ engine: 'pglite', database_path: join(home, 'brain.pglite') });
+ writeFileSync(configPath, config);
+ const set = await runCli(['config', 'set', 'schema_pack', 'gbrain-creator'], { home });
+ expect(set.exitCode).toBe(0);
+ expect(set.stderr).not.toContain('Unknown config key');
+ const get = await runCli(['config', 'get', 'schema_pack'], { home });
+ expect(get.exitCode).toBe(0);
+ expect(get.stdout.trim()).toBe('gbrain-creator');
+ const active = await runCli(['schema', 'active'], { home, env: { GBRAIN_SCHEMA_PACK: undefined } });
+ expect(active.exitCode).toBe(0);
+ expect(active.stdout).toContain('Active pack: gbrain-creator');
+ expect(readFileSync(configPath, 'utf8')).toBe(config);
+});
diff --git a/test/stale-extraction-recommendation.test.ts b/test/stale-extraction-recommendation.test.ts
new file mode 100644
index 0000000000..e52c1fc21b
--- /dev/null
+++ b/test/stale-extraction-recommendation.test.ts
@@ -0,0 +1,50 @@
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { computeRecommendations } from '../src/core/brain-score-recommendations.ts';
+import { registerBuiltinHandlers } from '../src/commands/jobs.ts';
+import type { MinionJobContext } from '../src/core/minions/types.ts';
+
+let engine: PGLiteEngine;
+const repoPath = mkdtempSync(join(tmpdir(), 'stale-recommendation-'));
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({ database_url: '' });
+ await engine.initSchema();
+ await engine.executeRaw("INSERT INTO sources (id, name) VALUES ('repo-a', 'repo-a'), ('repo-b', 'repo-b')");
+}, 60_000);
+
+afterAll(async () => {
+ await engine?.disconnect();
+ rmSync(repoPath, { recursive: true, force: true });
+});
+
+describe('DB extraction recommendations (#5112)', () => {
+ test('the recommended handler stamps DB-only pages in the selected source and converges', async () => {
+ for (const sourceId of ['repo-a', 'repo-b']) {
+ for (const slug of ['atoms/example', 'extracts/example', 'notes/example']) {
+ await engine.putPage(slug, { title: slug, type: 'note', compiled_truth: 'A synthetic note.', timeline: '' }, { sourceId });
+ }
+ }
+ const context = { sourceId: 'repo-a', repoPath, embeddingProviderConfigured: false };
+ const before = await engine.getHealth({ sourceId: 'repo-a' });
+ expect(before.stale_pages).toBe(3);
+ const recommendations = computeRecommendations(before, context);
+ expect(recommendations.map(r => r.id)).toEqual(['extract.stale']);
+ const recommendation = recommendations[0];
+ expect(recommendation.params).toEqual({ stale: true, sourceId: 'repo-a' });
+ expect(recommendation.depends_on).toEqual([]);
+ expect(computeRecommendations(before, { ...context, repoPath: undefined }).map(r => r.id)).toEqual(['extract.stale']);
+
+ const handlers = new Map<string, (job: MinionJobContext) => Promise<unknown>>();
+ await registerBuiltinHandlers({ register: (name: string, handler: (job: MinionJobContext) => Promise<unknown>) => handlers.set(name, handler) } as never, engine);
+ await handlers.get(recommendation.job)!({ id: 1, data: recommendation.params } as MinionJobContext);
+ const after = await engine.getHealth({ sourceId: 'repo-a' });
+ expect(after.stale_pages).toBe(0);
+ expect(computeRecommendations(after, context)).toEqual([]);
+ expect((await engine.getHealth({ sourceId: 'repo-b' })).stale_pages).toBe(3);
+ }, 60_000);
+});
diff --git a/test/subagent-handler.test.ts b/test/subagent-handler.test.ts
index 14369aeb1b..3a3b57ca6e 100644
--- a/test/subagent-handler.test.ts
+++ b/test/subagent-handler.test.ts
@@ -862,6 +862,37 @@ describe('handler-entry capability gate on the config-resolved model', () => {
// ── #4217 structural write accounting ───────────────────────
describe('write accounting (#4217)', () => {
+ test('gateway text-only completion fails required writes and replay spends no more tokens (#5098)', async () => {
+ const { configureGateway, resetGateway, __setChatTransportForTests } = await import('../src/core/ai/gateway.ts');
+ configureGateway({ env: {} });
+ let calls = 0;
+ __setChatTransportForTests(async () => {
+ calls++;
+ return {
+ model: 'openai:gpt-5.2', providerId: 'openai', text: 'brain_put_page({"slug":"notes/example"})',
+ blocks: [{ type: 'text', text: 'brain_put_page({"slug":"notes/example"})' }], stopReason: 'end',
+ usage: { input_tokens: 10, output_tokens: 5, cache_read_tokens: 0, cache_creation_tokens: 0 },
+ };
+ });
+ await engine.setConfig('agent.use_gateway_loop', 'true');
+ try {
+ const handler = makeSubagentHandler({ engine, client: new FakeMessagesClient([]), toolRegistry: [makePutPageTool('ok')] });
+ const ctx = await makeCtx({ prompt: 'write a page', model: 'openai:gpt-5.2', require_writes: true });
+ await expect(handler(ctx)).rejects.toThrow('zero required put_page writes');
+ await expect(handler(ctx)).rejects.toThrow('zero required put_page writes');
+ expect(calls).toBe(1);
+ expect(await engine.executeRaw('SELECT id FROM subagent_tool_executions WHERE job_id = $1', [ctx.id])).toEqual([]);
+ const readOnly = await handler({ ...ctx, data: { ...ctx.data, require_writes: false } });
+ expect(readOnly.stop_reason).toBe('end_turn');
+ expect(readOnly.pages_written).toBe(0);
+ expect(calls).toBe(1);
+ } finally {
+ __setChatTransportForTests(null);
+ resetGateway();
+ await engine.unsetConfig('agent.use_gateway_loop');
+ }
+ });
+
function makePutPageTool(behavior: 'ok' | 'fail' | ((input: unknown) => 'ok' | 'fail')): ToolDef {
return {
name: 'brain_put_page',
@@ -922,13 +953,17 @@ describe('write accounting (#4217)', () => {
expect(result.pages_failed).toBe(1);
});
- test('zero attempts (Task-D skip) stays completed even with require_writes', async () => {
+ test('zero attempts cannot satisfy require_writes even when the model claims a skip', async () => {
const client = new FakeMessagesClient([
{ content: [{ type: 'text', text: 'nothing met the bar' }] as any, stop_reason: 'end_turn' },
]);
const handler = makeSubagentHandler({ engine, client, toolRegistry: [makePutPageTool('ok')] });
const ctx = await makeCtx({ prompt: 'write pages', require_writes: true });
- const result = await handler(ctx);
+ await expect(handler(ctx)).rejects.toThrow('zero required put_page writes');
+ await expect(handler(ctx)).rejects.toThrow('zero required put_page writes');
+ expect(client.calls).toHaveLength(1);
+
+ const result = await handler({ ...ctx, data: { ...ctx.data, require_writes: false } });
expect(result.result).toBe('nothing met the bar');
expect(result.pages_attempted).toBe(0);
expect(result.pages_written).toBe(0);
@@ -942,7 +977,8 @@ describe('write accounting (#4217)', () => {
]);
const handler = makeSubagentHandler({ engine, client, toolRegistry: [makeThrowingTool('broken')] });
const ctx = await makeCtx({ prompt: 'do stuff', require_writes: true });
- const result = await handler(ctx);
+ await expect(handler(ctx)).rejects.toThrow('zero required put_page writes');
+ const result = await handler({ ...ctx, data: { ...ctx.data, require_writes: false } });
expect(result.pages_attempted).toBe(0);
});
});
@@ -1199,8 +1235,9 @@ describe('finalizeWriteAccounting read-error posture (CX-A3)', () => {
const truncated = { ...result, stop_reason: 'max_tokens' };
await expect(finalizeWriteAccounting(okEngine, 999, truncated, { requireWrites: true }))
.rejects.toThrow(/did not finish cleanly.*max_tokens/);
- // Clean-finish zero-attempt (Task-D skip) still completes.
- const out = await finalizeWriteAccounting(okEngine, 999, result, { requireWrites: true });
+ await expect(finalizeWriteAccounting(okEngine, 999, result, { requireWrites: true }))
+ .rejects.toThrow('zero required put_page writes');
+ const out = await finalizeWriteAccounting(okEngine, 999, result, { requireWrites: false });
expect(out.pages_attempted).toBe(0);
});
});
diff --git a/test/subagent-put-page-rejection.serial.test.ts b/test/subagent-put-page-rejection.serial.test.ts
new file mode 100644
index 0000000000..83b6d32b3c
--- /dev/null
+++ b/test/subagent-put-page-rejection.serial.test.ts
@@ -0,0 +1,215 @@
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, spyOn, test } from 'bun:test';
+import type Anthropic from '@anthropic-ai/sdk';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { MinionQueue } from '../src/core/minions/queue.ts';
+import { operations } from '../src/core/operations.ts';
+import { MAX_FILE_SIZE } from '../src/core/import-file.ts';
+import { buildBrainTools } from '../src/core/minions/tools/brain-allowlist.ts';
+import { makeSubagentHandler, type MessagesClient } from '../src/core/minions/handlers/subagent.ts';
+import { finalizeWriteAccounting } from '../src/core/minions/handlers/subagent-persistence.ts';
+import { __setChatTransportForTests, configureGateway, resetGateway, type ChatResult } from '../src/core/ai/gateway.ts';
+import type { MinionJobContext, SubagentResult } from '../src/core/minions/types.ts';
+
+let engine: PGLiteEngine;
+let queue: MinionQueue;
+const config = { engine: 'pglite' as const };
+const slug = 'wiki/personal/reflections/rejected-abc123';
+const input = { slug, content: '---\ntype: note\ntitle: Example\n---\nA saved note.' };
+const putPage = operations.find(op => op.name === 'put_page')!;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({ database_url: '' });
+ await engine.initSchema();
+ queue = new MinionQueue(engine);
+}, 60_000);
+
+beforeEach(async () => {
+ await engine.executeRaw('DELETE FROM subagent_tool_executions');
+ await engine.executeRaw('DELETE FROM subagent_messages');
+ await engine.executeRaw('DELETE FROM subagent_rate_leases');
+ await engine.executeRaw('DELETE FROM minion_jobs');
+ await engine.executeRaw('DELETE FROM pages');
+});
+
+afterEach(async () => {
+ __setChatTransportForTests(null);
+ resetGateway();
+ await engine.unsetConfig('agent.use_gateway_loop');
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+async function makeContext(lane: 'anthropic' | 'gateway' | 'oneshot'): Promise<MinionJobContext> {
+ const data = {
+ prompt: 'Write a note.', require_writes: true,
+ model: lane === 'gateway' ? 'openai:gpt-5.2' : 'anthropic:claude-sonnet-4-6',
+ allowed_tools: ['put_page'], allowed_slug_prefixes: ['wiki/personal/reflections/*'],
+ ...(lane === 'oneshot' ? { mode: 'oneshot', oneshot_slug_suffix: 'abc123' } : {}),
+ };
+ const job = await queue.add('subagent', data, {}, { allowProtectedSubmit: true });
+ return {
+ id: job.id, name: job.name, data, attempts_made: 0, deadlineAtMs: null,
+ signal: new AbortController().signal, shutdownSignal: new AbortController().signal,
+ async updateProgress() {}, async updateTokens() {}, async log() {},
+ async isActive() { return true; }, async readInbox() { return []; },
+ };
+}
+
+function chatResult(text: string, blocks: ChatResult['blocks']): ChatResult {
+ return {
+ model: 'openai:gpt-5.2', providerId: 'openai', text, blocks, stopReason: 'end',
+ usage: { input_tokens: 10, output_tokens: 5, cache_read_tokens: 0, cache_creation_tokens: 0 },
+ };
+}
+
+describe('put_page result normalization', () => {
+ test('invalid YAML and oversized content reject without creating a page', async () => {
+ const tool = buildBrainTools({ subagentId: 1, engine, config, deferEmbeds: true })
+ .find(tool => tool.name === 'brain_put_page')!;
+ for (const content of ['---\ntitle: [\n---\nbody', 'x'.repeat(MAX_FILE_SIZE + 1)]) {
+ await expect(tool.execute({ slug: 'wiki/agents/1/rejected', content }, { engine, jobId: 1, remote: true }))
+ .rejects.toThrow('page content was rejected before persistence');
+ expect(await engine.getPage('wiki/agents/1/rejected', { sourceId: 'default' })).toBeNull();
+ }
+ });
+
+ test('saving the same persisted page again remains a successful unchanged skip', async () => {
+ const tool = buildBrainTools({ subagentId: 1, engine, config, deferEmbeds: true })
+ .find(tool => tool.name === 'brain_put_page')!;
+ const page = { ...input, slug: 'wiki/agents/1/saved' };
+ expect(await tool.execute(page, { engine, jobId: 1, remote: true }))
+ .toMatchObject({ status: 'created_or_updated' });
+ expect(await tool.execute(page, { engine, jobId: 1, remote: true }))
+ .toMatchObject({ status: 'skipped' });
+ expect(await engine.getPage(page.slug, { sourceId: 'default' })).not.toBeNull();
+ });
+
+ test('scoped accounting reads JSON-string rejects without borrowing a prior invocation success', async () => {
+ const ctx = await makeContext('oneshot');
+ for (const [toolUseId, output] of [
+ ['oneshot-aaaaaaaa-p0', { status: 'created_or_updated' }],
+ ['oneshot-bbbbbbbb-p0', JSON.stringify({ status: 'skipped', error: 'Content rejected' })],
+ ] as const) {
+ await engine.executeRaw(
+ `INSERT INTO subagent_tool_executions (job_id, message_idx, tool_use_id, tool_name, input, status, output)
+ VALUES ($1, 1, $2, 'brain_put_page', $3::text::jsonb, 'complete', $4::text::jsonb)`,
+ [ctx.id, toolUseId, JSON.stringify(input), JSON.stringify(output)],
+ );
+ }
+ const result: SubagentResult = {
+ result: 'done', stop_reason: 'end_turn', turns_count: 1,
+ tokens: { in: 10, out: 5, cache_read: 0, cache_create: 0 },
+ };
+ await expect(finalizeWriteAccounting(engine, ctx.id, result, {
+ requireWrites: true, scopeToolUseIdPrefix: 'oneshot-bbbbbbbb-',
+ })).rejects.toThrow('all 1 put_page write(s) failed');
+ expect(await finalizeWriteAccounting(engine, ctx.id, result, {
+ requireWrites: false, scopeToolUseIdPrefix: 'oneshot-bbbbbbbb-',
+ })).toMatchObject({ pages_attempted: 1, pages_written: 0, pages_failed: 1 });
+ expect(await finalizeWriteAccounting(engine, ctx.id, result, { requireWrites: true }))
+ .toMatchObject({ pages_attempted: 2, pages_written: 1, pages_failed: 1 });
+ });
+
+ for (const output of [
+ { slug, status: 'skipped', chunks: 0 },
+ { slug, status: 'created_or_updated', embedding: { status: 'failed', error: 'Embedding unavailable' } },
+ ]) {
+ test(`successful persisted envelope is preserved: ${output.status}`, async () => {
+ const mocked = spyOn(putPage, 'handler').mockResolvedValue(output);
+ try {
+ const tool = buildBrainTools({ subagentId: 1, engine, config }).find(tool => tool.name === 'brain_put_page')!;
+ expect(await tool.execute(input, { engine, jobId: 1, remote: true })).toEqual(output);
+ } finally {
+ mocked.mockRestore();
+ }
+ });
+ }
+});
+
+for (const lane of ['anthropic', 'gateway', 'oneshot'] as const) {
+ for (const status of ['error', 'skipped'] as const) {
+ test(`${lane} settles ${status} rejections as failed, including optional-write replay`, async () => {
+ const mocked = spyOn(putPage, 'handler').mockResolvedValue({ slug, status, error: 'Import rejected', chunks: 0 });
+ let calls = 0;
+ const client: MessagesClient = {
+ async create(params) {
+ calls++;
+ return {
+ id: `message-${calls}`, type: 'message', role: 'assistant', model: params.model, stop_sequence: null,
+ content: calls === 1
+ ? [{ type: 'tool_use', id: 'put-1', name: 'brain_put_page', input }]
+ : [{ type: 'text', text: 'done' }],
+ stop_reason: calls === 1 ? 'tool_use' : 'end_turn',
+ usage: { input_tokens: 10, output_tokens: 5, cache_read_input_tokens: 0, cache_creation_input_tokens: 0 },
+ } as Anthropic.Message;
+ },
+ };
+ try {
+ configureGateway({ env: {} });
+ await engine.setConfig('agent.use_gateway_loop', lane === 'gateway' ? 'true' : 'false');
+ __setChatTransportForTests(async () => {
+ calls++;
+ return calls === 1
+ ? { ...chatResult('', [{ type: 'tool-call', toolCallId: 'put-1', toolName: 'brain_put_page', input }]), stopReason: 'tool_calls' }
+ : chatResult('done', [{ type: 'text', text: 'done' }]);
+ });
+ const handler = makeSubagentHandler({
+ engine, config, client,
+ _chat: async () => {
+ calls++;
+ const text = JSON.stringify({ pages: [{ slug, body: 'A note about [[people/alice-example]].' }], skipped: false });
+ return chatResult(text, [{ type: 'text', text }]);
+ },
+ });
+ const ctx = await makeContext(lane);
+ await expect(handler(ctx)).rejects.toThrow('all 1 put_page write(s) failed');
+ const rows = await engine.executeRaw<{ status: string; error: string }>(
+ 'SELECT status, error FROM subagent_tool_executions WHERE job_id = $1', [ctx.id],
+ );
+ expect(rows).toHaveLength(1);
+ expect(rows[0].status).toBe('failed');
+ expect(rows[0].error).toContain('page content was rejected before persistence');
+ expect(rows[0].error).not.toContain('Import rejected');
+ expect(mocked).toHaveBeenCalledTimes(1);
+ const callsBeforeReplay = calls;
+ const optional = await handler({ ...ctx, data: { ...ctx.data, require_writes: false } });
+ expect(optional.pages_attempted).toBe(1);
+ expect(optional.pages_written).toBe(0);
+ expect(optional.pages_failed).toBe(1);
+ expect(calls).toBe(callsBeforeReplay);
+ } finally {
+ mocked.mockRestore();
+ }
+ });
+ }
+
+ test(`${lane} historical completed rejection cannot satisfy required writes`, async () => {
+ const ctx = await makeContext(lane);
+ await engine.setConfig('agent.use_gateway_loop', lane === 'gateway' ? 'true' : 'false');
+ await engine.executeRaw(
+ `INSERT INTO subagent_messages (job_id, message_idx, role, content_blocks, tokens_out)
+ VALUES ($1, 0, 'user', $2::text::jsonb, NULL), ($1, 1, 'assistant', $3::text::jsonb, 5)`,
+ [ctx.id, JSON.stringify([{ type: 'text', text: 'Write a note.' }]), JSON.stringify([{ type: 'text', text: 'done' }])],
+ );
+ await engine.executeRaw(
+ `INSERT INTO subagent_tool_executions (job_id, message_idx, tool_use_id, tool_name, input, status, output)
+ VALUES ($1, 1, $2, 'brain_put_page', $3::text::jsonb, 'complete', $4::text::jsonb)`,
+ [ctx.id, lane === 'oneshot' ? 'oneshot-abcd1234-p0' : 'put-1', JSON.stringify(input),
+ JSON.stringify({ slug, status: 'skipped', error: 'Content rejected', chunks: 0 })],
+ );
+ let calls = 0;
+ const handler = makeSubagentHandler({
+ engine, config,
+ client: { async create() { calls++; throw new Error('Unexpected replay model call'); } },
+ _chat: async () => { calls++; throw new Error('Unexpected replay model call'); },
+ });
+ await expect(handler(ctx)).rejects.toThrow('all 1 put_page write(s) failed');
+ const optional = await handler({ ...ctx, data: { ...ctx.data, require_writes: false } });
+ expect(optional.pages_written).toBe(0);
+ expect(optional.pages_failed).toBe(1);
+ expect(calls).toBe(0);
+ });
+}
diff --git a/test/subagent-required-writes.test.ts b/test/subagent-required-writes.test.ts
new file mode 100644
index 0000000000..e459a0a234
--- /dev/null
+++ b/test/subagent-required-writes.test.ts
@@ -0,0 +1,79 @@
+import { describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { SubagentResult } from '../src/core/minions/types.ts';
+import { finalizeWriteAccounting } from '../src/core/minions/handlers/subagent-persistence.ts';
+
+const result: SubagentResult = {
+ result: 'I will call brain_put_page now.',
+ turns_count: 1,
+ stop_reason: 'end_turn',
+ tokens: { in: 10, out: 5, cache_read: 0, cache_create: 0 },
+};
+
+function ledger(rows: Array<{ status: string; error: string | null; output?: unknown }>): BrainEngine {
+ return { executeRaw: async () => rows } as unknown as BrainEngine;
+}
+
+describe('required-write postcondition (#5098)', () => {
+ test('a clean prose-only finish cannot satisfy required writes', async () => {
+ await expect(finalizeWriteAccounting(ledger([]), 1, result, { requireWrites: true }))
+ .rejects.toThrow('required put_page write');
+ });
+
+ test('an unsettled write cannot satisfy required writes', async () => {
+ await expect(finalizeWriteAccounting(ledger([{ status: 'pending', error: null }]), 1, result, { requireWrites: true }))
+ .rejects.toThrow('required put_page write');
+ });
+
+ test('read-only and no-op jobs still finish without inferring unsupported tools', async () => {
+ const actual = await finalizeWriteAccounting(ledger([]), 1, result, { requireWrites: false });
+ expect(actual.stop_reason).toBe('end_turn');
+ expect(actual.pages_written).toBe(0);
+ });
+
+ test('a settled successful write satisfies the postcondition', async () => {
+ const actual = await finalizeWriteAccounting(ledger([{ status: 'complete', error: null }]), 1, result, { requireWrites: true });
+ expect(actual.pages_written).toBe(1);
+ });
+
+ for (const output of [
+ { status: 'error', error: 'Invalid YAML frontmatter', chunks: 0 },
+ { status: 'error', chunks: 0 },
+ { status: 'skipped', error: 'Content too large', chunks: 0 },
+ JSON.stringify({ status: 'skipped', error: 'Content rejected', chunks: 0 }),
+ ]) {
+ test(`a historical completed rejection is a failed write: ${JSON.stringify(output)}`, async () => {
+ const engine = ledger([{ status: 'complete', error: null, output }]);
+ await expect(finalizeWriteAccounting(engine, 1, result, { requireWrites: true }))
+ .rejects.toThrow('all 1 put_page write(s) failed');
+ const optional = await finalizeWriteAccounting(engine, 1, result, { requireWrites: false });
+ expect(optional.pages_attempted).toBe(1);
+ expect(optional.pages_written).toBe(0);
+ expect(optional.pages_failed).toBe(1);
+ });
+ }
+
+ for (const output of [
+ { status: 'skipped', chunks: 0 },
+ { status: 'created_or_updated', embedding: { status: 'failed', error: 'Embedding unavailable' } },
+ JSON.stringify({ status: 'skipped', chunks: 0 }),
+ ]) {
+ test(`persisted and unchanged pages remain successful: ${JSON.stringify(output)}`, async () => {
+ const actual = await finalizeWriteAccounting(ledger([{ status: 'complete', error: null, output }]), 1, result, { requireWrites: true });
+ expect(actual.pages_attempted).toBe(1);
+ expect(actual.pages_written).toBe(1);
+ expect(actual.pages_failed).toBe(0);
+ });
+ }
+
+ test('historical rejects do not hide a separate successful write', async () => {
+ const actual = await finalizeWriteAccounting(ledger([
+ { status: 'complete', error: null, output: { status: 'error' } },
+ { status: 'complete', error: null, output: { status: 'skipped' } },
+ { status: 'pending', error: null, output: { status: 'error' } },
+ ]), 1, result, { requireWrites: true });
+ expect(actual.pages_attempted).toBe(2);
+ expect(actual.pages_written).toBe(1);
+ expect(actual.pages_failed).toBe(1);
+ });
+});
diff --git a/test/sync-git-paths.test.ts b/test/sync-git-paths.test.ts
new file mode 100644
index 0000000000..64a6ac1439
--- /dev/null
+++ b/test/sync-git-paths.test.ts
@@ -0,0 +1,55 @@
+import { describe, expect, test } from 'bun:test';
+import { posix, win32 } from 'node:path';
+import { gitRelativePath } from '../src/core/sync-git.ts';
+import { planReconcileDeletes } from '../src/core/sync-reconcile.ts';
+import { buildSyncManifest } from '../src/core/sync.ts';
+
+describe('Git-relative sync scope paths (#5108)', () => {
+ for (const [name, paths, root] of [
+ ['Windows drive', win32, 'C:\\repo'],
+ ['Windows UNC', win32, '\\\\server\\share\\repo'],
+ ['POSIX', posix, '/repo'],
+ ] as const) {
+ test(`${name}: nested scopes match Git paths without admitting siblings`, () => {
+ const scope = gitRelativePath(root, paths.join(root, 'docs', 'brain'), paths);
+ expect(scope).toBe('docs/brain');
+ const manifest = buildSyncManifest([
+ 'A\tdocs/brain/added.md',
+ 'M\tdocs/brain/nested/changed.md',
+ 'D\tdocs/brain/deleted.md',
+ 'R100\tdocs/brain/old.md\tdocs/brain/new.md',
+ 'A\tdocs/brain-other/outside.md',
+ 'M\tdocs/other/outside.md',
+ 'D\toutside.md',
+ ].join('\n'));
+ const inScope = (p: string) => p === scope || p.startsWith(scope + '/');
+ expect(manifest.added.filter(inScope)).toEqual(['docs/brain/added.md']);
+ expect(manifest.modified.filter(inScope)).toEqual(['docs/brain/nested/changed.md']);
+ expect(manifest.deleted.filter(inScope)).toEqual(['docs/brain/deleted.md']);
+ expect(manifest.renamed.filter(r => inScope(r.to))).toEqual([
+ { from: 'docs/brain/old.md', to: 'docs/brain/new.md' },
+ ]);
+ expect(manifest.modified[0]!.slice(scope.length + 1)).toBe('nested/changed.md');
+ });
+
+ test(`${name}: root scopes stay empty, including trailing separators`, () => {
+ expect(gitRelativePath(root, root, paths)).toBe('');
+ expect(gitRelativePath(root + paths.sep, root, paths)).toBe('');
+ });
+
+ test(`${name}: full reconcile normalizes scope and stored paths before filtering`, () => {
+ const scopePrefix = gitRelativePath(root, paths.join(root, 'docs', 'brain'), paths) + '/';
+ const plan = planReconcileDeletes([
+ { slug: 'present', source_path: 'docs/brain/present.md' },
+ { slug: 'gone-posix', source_path: 'docs/brain/gone-posix.md' },
+ { slug: 'gone-windows', source_path: 'docs\\brain\\gone-windows.md' },
+ { slug: 'other-source', source_path: 'docs/brain-other/outside.md' },
+ { slug: 'other-strategy', source_path: 'docs/brain/code.ts' },
+ ], [paths.join('docs', 'brain', 'present.md')],
+ p => p.startsWith(scopePrefix) && p.endsWith('.md'));
+ expect(plan.staleSlugs).toEqual(['gone-posix', 'gone-windows']);
+ expect(plan.reconcilableCount).toBe(3);
+ expect(plan.massDelete).toBe(false);
+ });
+ }
+});
diff --git a/test/thin-client-launcher-routing.test.ts b/test/thin-client-launcher-routing.test.ts
new file mode 100644
index 0000000000..e2219ddd1b
--- /dev/null
+++ b/test/thin-client-launcher-routing.test.ts
@@ -0,0 +1,64 @@
+import { afterEach, beforeEach, expect, test } from 'bun:test';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { renderAgentLauncher } from '../src/core/agent-install/launcher.ts';
+import { installHarnessConnection } from '../src/core/harness/install.ts';
+import { runCli } from './helpers/cli-spawn.ts';
+
+let home: string;
+beforeEach(() => { home = mkdtempSync(join(tmpdir(), 'gbrain-thin-launcher-')); });
+afterEach(() => { rmSync(home, { recursive: true, force: true }); });
+
+test.each([
+ { args: ['search', 'known marker'] },
+ { args: ['search', 'known marker', '--source', 'notes'] },
+ { args: ['put', 'notes/example', '--content', 'example'] },
+])('thin launcher preserves explicit arguments without pinning the grant write source: %j', async ({ args }) => {
+ const executable = join(home, 'probe');
+ writeFileSync(executable, '#!/usr/bin/env bash\nprintf "%s\\n" "${GBRAIN_BRAIN_ID-unset}" "${GBRAIN_SOURCE-unset}" "$@"\n', { mode: 0o700 });
+ const launcher = join(home, 'gbrain');
+ writeFileSync(launcher, renderAgentLauncher({ root: home, bunPath: executable, sourceId: 'isolated-write', mode: 'thin-client' }), { mode: 0o700 });
+ const child = Bun.spawn(['bash', launcher, ...args], {
+ cwd: '/', env: { ...process.env, HOME: home, GBRAIN_HOME: home, GBRAIN_SOURCE: 'foreign', GBRAIN_BRAIN_ID: 'foreign' },
+ stdout: 'pipe', stderr: 'pipe',
+ });
+ const output = await new Response(child.stdout).text();
+ expect(await child.exited).toBe(0);
+ expect(output.split('\n')).toEqual(['unset', 'unset', ...args, '']);
+});
+
+test('installed hosted launcher executes the real CLI without a local brain override', async () => {
+ const root = join(home, 'hosted');
+ await installHarnessConnection({
+ version: 1, mcp_url: 'https://brain.example/mcp', issuer_url: 'https://brain.example',
+ client_id: 'fixture-client', client_secret: 'fixture-secret', profile: 'memory-reader',
+ harness: 'muse', source_id: 'isolated-write',
+ }, { harness: 'muse', root });
+ const launcher = join(root, 'bin', 'gbrain');
+ const child = Bun.spawn([launcher, '--version'], {
+ env: { ...process.env, HOME: home, GBRAIN_HOME: home }, stdout: 'pipe', stderr: 'pipe',
+ });
+ const output = await new Response(child.stdout).text();
+ expect(await child.exited).toBe(0);
+ expect(output).toMatch(/^gbrain \d/);
+ const script = readFileSync(launcher, 'utf8');
+ expect(script).not.toContain('export GBRAIN_SOURCE=');
+ expect(script).not.toContain('--brain host');
+ expect(existsSync(join(root, '.gbrain', 'brain.pglite'))).toBe(false);
+});
+
+test.each(['postgres', 'pglite'])('call refuses on a %s thin client before connecting a local engine', async engine => {
+ mkdirSync(join(home, '.gbrain'));
+ const databasePath = join(home, 'unexpected.pglite');
+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({
+ engine, database_path: databasePath,
+ remote_mcp: { mcp_url: 'https://brain.example/mcp', issuer_url: 'https://brain.example', oauth_client_id: 'fixture', oauth_client_secret: 'fixture-secret' },
+ }));
+ const result = await runCli(['call', 'list_skills', '{}'], { home, env: { GBRAIN_REMOTE_CLIENT_SECRET: undefined } });
+ expect(result.exitCode).toBe(1);
+ expect(result.stderr).toContain('`gbrain call` is not routable');
+ expect(result.stderr).toContain('host');
+ expect(result.stderr).not.toContain('No database URL');
+ expect(existsSync(databasePath)).toBe(false);
+});
diff --git a/test/track1-save-time-entity-resolution.test.ts b/test/track1-save-time-entity-resolution.test.ts
index 087d8140b1..5114220c75 100644
--- a/test/track1-save-time-entity-resolution.test.ts
+++ b/test/track1-save-time-entity-resolution.test.ts
@@ -58,6 +58,37 @@ describe('save-time resolution vocabulary', () => {
describe('resolveExtractedEntitiesForSave', () => {
const engine = {} as BrainEngine;
+ for (const outcome of ['fallback', 'error'] as const) {
+ test(`${outcome} preserves the complete fact and provenance without an unverified target`, async () => {
+ const spy = stubResolve(async () => {
+ if (outcome === 'error') throw new Error('resolver unavailable');
+ return { slug: 'people/unverified-example', source: 'fallback_slugify' };
+ });
+ try {
+ const original: ExtractedFact = {
+ ...fact('people/unverified-example', 'An unverified participant committed to follow up'),
+ source: 'cli:extract-conversation-facts:seg', source_session: 'session-example',
+ context: 'from sessions/example segment 2026-01-01',
+ valid_from: new Date('2026-01-01T00:00:00Z'), embedding: new Float32Array([0.25, 0.75]),
+ };
+ const facts = [{ ...original }];
+ const errors: Array<{ raw: string; message: string }> = [];
+ const stats = await resolveExtractedEntitiesForSave(engine, 'source-example', facts,
+ (raw, message) => errors.push({ raw, message }));
+ expect(facts).toEqual([{ ...original, entity_slug: null }]);
+ expect(spy).toHaveBeenCalledWith(engine, 'source-example', original.entity_slug);
+ expect(stats).toEqual(outcome === 'fallback'
+ ? { counts: { fallback_slugify: 1 }, fallback_slugify_count: 1, resolution_errors: 0 }
+ : { counts: {}, fallback_slugify_count: 0, resolution_errors: 1 });
+ expect(errors).toEqual(outcome === 'fallback' ? [] : [{
+ raw: 'people/unverified-example', message: 'resolver unavailable',
+ }]);
+ } finally {
+ spy.mockRestore();
+ }
+ });
+ }
+
test('rewrites slugs, preserves null, and counts fallback_slugify', async () => {
const spy = stubResolve(async (raw) => {
if (raw === 'Brian') {
@@ -77,7 +108,7 @@ describe('resolveExtractedEntitiesForSave', () => {
const stats = await resolveExtractedEntitiesForSave(engine, 'default', facts);
expect(facts.map((row) => row.entity_slug)).toEqual([
'people/brian-example',
- 'unlisted-person',
+ null,
null,
]);
expect(stats.counts).toEqual({
@@ -92,7 +123,7 @@ describe('resolveExtractedEntitiesForSave', () => {
}
});
- test('best-effort resolver failure keeps the raw value', async () => {
+ test('best-effort resolver failure keeps the fact unparented', async () => {
const spy = stubResolve(async (raw) => {
if (raw === 'Unlisted Person') throw new Error('resolver unavailable');
return { slug: 'people/brian-example', source: 'alias_exact' };
@@ -108,7 +139,7 @@ describe('resolveExtractedEntitiesForSave', () => {
);
expect(facts.map((row) => row.entity_slug)).toEqual([
'people/brian-example',
- 'Unlisted Person',
+ null,
]);
expect(stats.resolution_errors).toBe(1);
expect(stats.fallback_slugify_count).toBe(0);