From 3464179ce9000111da02c5b61c1c836c0610f198 Mon Sep 17 00:00:00 2001 From: Garry Tan Date: Thu, 27 Aug 2026 13:09:55 -0700 Subject: [PATCH] =?UTF-8?q?v0.46.35.0=20fix:=20wave-k=20maintainer=20train?= =?UTF-8?q?=20=E2=80=94=2031=20red-proven=20fixes=20(5=20fix-wave-j=20salv?= =?UTF-8?q?ages,=2011=20verified=20issues,=2015=20credited=20reimplementat?= =?UTF-8?q?ions)=20(#4650)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Wave K's maintainer train: 31 red-proven fixes — 5 salvaged from fix-wave-j (#4363), 11 newly verified open issues, and 15 community PRs reimplemented with credit. Every fix carries a regression test proven RED at its base commit and passed an independent fresh-context review (32/32 approved). Retargeted across the megawave, wave-g, backup-coverage, and db-availability trains with zero suite regressions vs a same-sandbox master comparator; verify 54/54; PR CI 28/28 green. Behavior change: `gbrain config get` now redacts secrets by default (--raw opts out) — see skills/migrations/v0.46.35.0.md. Migration v143 (dream_verdicts_ttl). Full-E2E note: PR CI ran Tier 1+2; the nightly full-suite validates this head post-merge (merge authorized by maintainer). Closes #3910, #4041, #3943, #4107, #4108, #4365, #4385, #4366, #4373, #4392, #4394, #4412, #4364, #4375, #4376, #4380. Completes #4363. Co-authored-by: Aditya Vikram Singh <247195684+avs-io@users.noreply.github.com> Co-authored-by: Claude Fable 5 Co-authored-by: DarkNightForge Co-authored-by: DarkNightForge Co-authored-by: Dr Deeb Co-authored-by: Kkkkkuro <180382840+Kkkkkuro@users.noreply.github.com> Co-authored-by: francisco guzman <49572136+Crackde@users.noreply.github.com> Co-authored-by: harshsahrawat-commits <233312378+harshsahrawat-commits@users.noreply.github.com> Co-authored-by: jared-voss <262417861+jared-voss@users.noreply.github.com> Co-authored-by: kyle944 <297432264+kyle944@users.noreply.github.com> Co-authored-by: leihaozhou Co-authored-by: miroslavb <31091373+miroslavb@users.noreply.github.com> Co-authored-by: y2688 <172344182+y2688@users.noreply.github.com> --- .claude-plugin/plugin.json | 2 +- .codex-plugin/plugin.json | 2 +- BOOTSTRAP_FOR_AGENTS.md | 2 +- CHANGELOG.md | 47 +++ TODOS.md | 48 ++- VERSION | 2 +- bunfig.toml | 13 +- docker-compose.ci.yml | 4 + docs/architecture/KEY_FILES.md | 7 +- docs/architecture/brains-and-sources.md | 34 ++ openclaw.plugin.json | 2 +- package.json | 2 +- .../gbrain-coding/.claude-plugin/plugin.json | 2 +- .../gbrain-coding/.codex-plugin/plugin.json | 2 +- plugin-variants/gbrain-coding/README.md | 2 +- .../gbrain-daily/.claude-plugin/plugin.json | 2 +- .../gbrain-daily/.codex-plugin/plugin.json | 2 +- plugin-variants/gbrain-daily/README.md | 2 +- plugin/README.md | 2 +- scripts/e2e-test-map.ts | 3 + scripts/module-size-limits.tsv | 42 +- scripts/structural-suites.tsv | 6 + skills/migrations/v0.46.35.0.md | 13 + skills/skills.lock.json | 1 + src/cli.ts | 11 +- src/commands/apply-migrations.ts | 67 +++- src/commands/capture.ts | 19 + src/commands/config.ts | 15 +- src/commands/doctor.ts | 24 +- src/commands/doctor/checks/calibration.ts | 8 +- src/commands/embed.ts | 50 ++- src/commands/eval-suspected-contradictions.ts | 11 +- src/commands/extract-conversation-facts.ts | 5 +- src/commands/extract.ts | 97 ++++- src/commands/files.ts | 184 ++++++--- src/commands/init.ts | 26 +- src/commands/notability-eval.ts | 4 +- src/commands/schema.ts | 1 + src/commands/self-upgrade.ts | 6 +- src/commands/serve-http-metrics.ts | 100 +++++ src/commands/serve-http.ts | 17 + src/commands/sync.ts | 5 +- src/commands/takes.ts | 12 +- src/commands/upgrade.ts | 41 +- src/core/ai/build-gateway-config.ts | 1 + src/core/ai/gateway.ts | 66 +++- src/core/ai/provider-env.ts | 6 + src/core/ai/recipes/ollama.ts | 10 + src/core/ai/types.ts | 7 + src/core/budget/budget-tracker.ts | 50 ++- src/core/capture-content.ts | 84 +++- src/core/cli-flag-registry.generated.ts | 14 +- src/core/code-graph-readiness.ts | 9 +- src/core/config-db-merge.ts | 2 + src/core/config.ts | 28 +- src/core/cycle.ts | 13 +- src/core/cycle/extract-atoms.ts | 10 +- src/core/cycle/grade-takes.ts | 21 +- src/core/cycle/inline-drain.ts | 27 +- src/core/cycle/patterns.ts | 29 +- src/core/cycle/synthesize.ts | 85 ++++- src/core/engine-errors.ts | 32 ++ src/core/engine.ts | 29 +- src/core/entities/resolve.ts | 8 +- src/core/eval-contradictions/runner.ts | 7 +- src/core/facts/backstop.ts | 40 +- src/core/facts/fence-write.ts | 82 ++-- src/core/facts/stub-guard-audit.ts | 19 +- src/core/facts/write-single.ts | 14 +- src/core/gbrain-env-file.ts | 57 +++ src/core/import-file.ts | 22 +- src/core/link-extraction.ts | 37 ++ src/core/migrate.ts | 30 ++ src/core/model-config.ts | 8 +- src/core/ops/code-intel.ts | 17 +- src/core/ops/context.ts | 122 ++++++ src/core/ops/contract.ts | 3 +- src/core/ops/facts.ts | 12 +- src/core/ops/links.ts | 33 +- src/core/ops/pages.ts | 38 +- src/core/ops/schema-packs.ts | 6 +- src/core/ops/timeline.ts | 35 +- src/core/page-summary.ts | 12 +- src/core/pglite-engine.ts | 177 +++++---- src/core/pglite-engine/facts.ts | 15 +- src/core/postgres-engine.ts | 149 +++++--- src/core/postgres-engine/facts.ts | 19 + src/core/schema-embedded.generated.ts | 4 + src/core/schema-pack/index.ts | 1 + src/core/schema-pack/load-active.ts | 12 + src/core/search/hybrid.ts | 12 +- src/core/sweep.ts | 13 +- src/core/think/cite-render.ts | 27 +- src/core/think/index.ts | 50 ++- src/core/transcripts/ingest.ts | 7 +- src/core/transcripts/render.ts | 6 +- src/core/types.ts | 8 +- src/core/verbs.ts | 3 +- src/core/verbs/entity-card.ts | 2 +- src/core/write-through.ts | 140 ++++++- src/schema.sql | 4 + templates/bootstrap/template-repo/README.md | 2 +- test/ai/build-gateway-config.test.ts | 56 +++ test/ai/embed-env-batch-cap.test.ts | 132 +++++++ test/ai/embed-keyless-base-url.test.ts | 88 +++++ test/ai/gateway-chat.test.ts | 35 ++ test/ai/ocr-model-routing.test.ts | 159 ++++++++ test/ai/ollama-library-tag-dims.test.ts | 97 +++++ ...ly-migrations-list-db-state.serial.test.ts | 71 ++++ test/apply-migrations-list-db-state.test.ts | 39 ++ test/apply-migrations.test.ts | 9 +- test/backlink-count-mention-filter.test.ts | 84 ++-- test/benchmark-graph-quality.ts | 17 +- test/capture-runcapture.test.ts | 68 +++- test/cite-render-closure.test.ts | 157 ++++++++ test/config-gbrain-env-file.test.ts | 122 ++++++ test/config-get-plane.test.ts | 59 ++- test/core/budget/budget-tracker.test.ts | 64 ++++ test/cycle-abort.test.ts | 41 ++ test/cycle-patterns-source-scope.test.ts | 40 ++ test/cycle/extract-atoms-progress.test.ts | 37 +- test/cycle/synthesize-gateway-adapter.test.ts | 72 ++++ test/default-alias-liveness.test.ts | 74 ++++ ...-abandoned-threads-month-precision.test.ts | 68 ++++ test/doctor-no-migrate.serial.test.ts | 116 ++++++ test/dream-verdict-cache-ttl.test.ts | 157 ++++++++ test/e2e/code-intel-mcp-ops-pglite.test.ts | 27 ++ test/e2e/dream-synthesize-pglite.test.ts | 103 +++++ test/e2e/graph-quality.test.ts | 14 +- .../source-boundary-mutation-postgres.test.ts | 117 ++++++ test/embed-quarantine.serial.test.ts | 169 +++++++++ test/entity-resolve-prefix-dirs.test.ts | 75 ++++ test/eval-contradictions-runner.test.ts | 21 + ...tract-cross-source-links-db.serial.test.ts | 198 ++++++++++ test/extract-cross-source-links.test.ts | 171 +++++++++ ...ss-source-resolution-observability.test.ts | 11 +- test/extract-source-aware.test.ts | 30 ++ test/extract-stale.test.ts | 55 +++ test/facts-classify.test.ts | 33 +- test/facts-fallback-stub-guard.test.ts | 185 +++++++++ test/facts-recall-audit-rows.test.ts | 42 +- test/facts-recall-grep-sql.test.ts | 133 +++++++ test/fence-write.test.ts | 149 ++++++-- test/files.test.ts | 50 ++- .../preload-guard/operator-env-probe.test.ts | 29 ++ test/grade-takes.test.ts | 57 +++ test/helpers/operator-env-preload.ts | 75 ++++ test/import-file-content-sanity.test.ts | 22 +- test/init-force-engine-preservation.test.ts | 146 +++++++ test/operator-env-preload.test.ts | 165 ++++++++ test/pglite-disconnect-checkpoint.test.ts | 59 +++ test/pglite-engine.test.ts | 21 +- test/schema-bootstrap-coverage.test.ts | 8 + test/schema-lint-extends.test.ts | 175 +++++++++ test/search.test.ts | 91 +++-- test/search/attribution-stamping.test.ts | 8 +- test/serve-http-metrics.test.ts | 160 ++++++++ test/source-boundary-mutation-errors.test.ts | 358 ++++++++++++++++++ test/source-id-tx-regression.test.ts | 35 +- test/source-scope-resolver.test.ts | 74 ++++ test/sync-break-lock-source.test.ts | 114 ++++++ test/think-max-output-tokens.test.ts | 101 ++++- test/timeline-write-through.test.ts | 6 +- test/transcripts-nul.test.ts | 171 +++++++++ test/upgrade.serial.test.ts | 144 ++++++- test/write-through.test.ts | 242 +++++++++++- 166 files changed, 7795 insertions(+), 634 deletions(-) create mode 100644 skills/migrations/v0.46.35.0.md create mode 100644 src/commands/serve-http-metrics.ts create mode 100644 src/core/engine-errors.ts create mode 100644 src/core/gbrain-env-file.ts create mode 100644 test/ai/embed-env-batch-cap.test.ts create mode 100644 test/ai/embed-keyless-base-url.test.ts create mode 100644 test/ai/ocr-model-routing.test.ts create mode 100644 test/ai/ollama-library-tag-dims.test.ts create mode 100644 test/apply-migrations-list-db-state.serial.test.ts create mode 100644 test/apply-migrations-list-db-state.test.ts create mode 100644 test/cite-render-closure.test.ts create mode 100644 test/config-gbrain-env-file.test.ts create mode 100644 test/default-alias-liveness.test.ts create mode 100644 test/doctor-abandoned-threads-month-precision.test.ts create mode 100644 test/doctor-no-migrate.serial.test.ts create mode 100644 test/dream-verdict-cache-ttl.test.ts create mode 100644 test/e2e/source-boundary-mutation-postgres.test.ts create mode 100644 test/embed-quarantine.serial.test.ts create mode 100644 test/entity-resolve-prefix-dirs.test.ts create mode 100644 test/extract-cross-source-links-db.serial.test.ts create mode 100644 test/extract-cross-source-links.test.ts create mode 100644 test/facts-fallback-stub-guard.test.ts create mode 100644 test/facts-recall-grep-sql.test.ts create mode 100644 test/fixtures/preload-guard/operator-env-probe.test.ts create mode 100644 test/helpers/operator-env-preload.ts create mode 100644 test/init-force-engine-preservation.test.ts create mode 100644 test/operator-env-preload.test.ts create mode 100644 test/pglite-disconnect-checkpoint.test.ts create mode 100644 test/schema-lint-extends.test.ts create mode 100644 test/serve-http-metrics.test.ts create mode 100644 test/source-boundary-mutation-errors.test.ts create mode 100644 test/sync-break-lock-source.test.ts create mode 100644 test/transcripts-nul.test.ts diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 6a72b81d..70ac04c8 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "gbrain", - "version": "0.46.34.0", + "version": "0.46.35.0", "description": "Personal knowledge brain for your coding agent \u2014 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 7b7f17fe..09321b05 100644 --- a/.codex-plugin/plugin.json +++ b/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "gbrain", - "version": "0.46.34.0", + "version": "0.46.35.0", "description": "Personal knowledge brain for your coding agent \u2014 hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.", "author": { "name": "Garry Tan", diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.md index 45a7b7fb..e0e9e228 100644 --- a/BOOTSTRAP_FOR_AGENTS.md +++ b/BOOTSTRAP_FOR_AGENTS.md @@ -1,4 +1,4 @@ - + diff --git a/CHANGELOG.md b/CHANGELOG.md index 82db343a..b6da714b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,53 @@ All notable changes to GBrain will be documented in this file. +## [0.46.35.0] - 2026-08-27 + +**The maintainer train: 31 red-proven fixes, every one adversarially verified.** +Wave K's second train, retargeted onto the merged community train (v0.46.32.0): +5 fixes salvaged from the stale fix-wave-j PR (#4363), 16 newly verified open +issues fixed, and 10 community PRs reimplemented with credit where the direction +was right but the code had rotted. Every fix carries a regression test proven +RED at its base commit before the fix (captured evidence, not assertion) and +passed an independent fresh-context review — 32/32 approved, zero rejections +(6 fixes were later superseded by the wave-g reconciliation and yielded to +master's versions during retarget). + +### Behavior changes +- **`gbrain config get` now redacts secrets by default** (matching `show`/`set`); + pass `--raw` (either position) for automation that needs the plain value. + Salvaged from #4363, fixes #3943. See `skills/migrations/v0.46.35.0.md`. +- `runUpgrade` now FAILS (exit 1, remediation recorded) when a self-upgrade + leaves the resolved version below the fetched target, instead of reporting + false success (#4366). +- Migration **v143** adds `dream_verdicts_ttl` (#4069, reimplemented from + @avs-io's PR). + +### Fixed (highlights — full list in the PR body) +- BudgetTracker admits concurrent reservations against cumulative + outstanding + spend, closing the N-way `--max-cost-usd` breach race (#4365). +- Judge parse failures retry next cycle instead of minting durable cached + `unresolvable` verdicts (#3910); `abandoned_threads` accepts month-precision + `since:` dates (#4041); `embedding_image_ocr_model` is honored end-to-end + (#4107); fallback-slugified facts can no longer mint canonical stub pages — + `FenceTarget.resolutionSource` is now required (#4108). +- think: max_tokens truncation is labeled `LLM_OUTPUT_TRUNCATED` with 16K + output headroom for the Anthropic 4-x family (#4375); inline citations + always parse with a warning on mismatch (#4376). +- Search: backlink counts key on page identity, not colliding bare slugs + (#4380); OpenAI-compatible local embedding endpoints honor OPENAI_BASE_URL + without demanding a real OpenAI key (#4385). +- Transcripts ingest strips NULs at the render boundary instead of aborting + the run (#4392); `--pending` counts exclude audit checkpoint rows (#4394); + break-lock resolves its target source correctly under serve delegation, and + explicit `--source` can still break a deleted source's leftover lock (#4412); + schema lint resolves extends-inherited page types on the MCP op (#4373); + `apply-migrations --list/--dry-run` print the DB probe state with a + `--require-db` gate (#4364). +- Reimplemented-with-credit fixes across dream/search/sync/cli/facts from PRs + #3478 #3622 #3753 #3815 #3851 #3893 #3904 #3908 #4011 #4022 #4023 #4069 + #4077 #4109 #4255 — each author credited in the commit trailers. + ## [0.46.34.0] - 2026-08-26 The db-availability wave: gbrain now detects which engine a brain runs on, diff --git a/TODOS.md b/TODOS.md index cce737aa..e67ebab5 100644 --- a/TODOS.md +++ b/TODOS.md @@ -74,12 +74,11 @@ Per-source `gbrain sync --source X` delegates today, so this is convenience, not capability. Start: `src/commands/sync-delegate.ts` (the `--all` refusal), `src/core/serve-sync-runner.ts`. Effort: M (CC: S). Priority: P3. -- [ ] **P3 — `serve --http` sync IPC.** **What:** register the resolve-IPC - listener (and the sync kinds) on the HTTP serve path. **Why:** delegation is - stdio-serve-only — an HTTP serve still forces stop-the-serve syncs. - **Context:** `src/commands/serve-http.ts` is at its module-size cap; the - wiring needs its own module. The IPC block in `src/mcp/server.ts:186` is the - shape to extract/share. Effort: M (CC: S). Priority: P3. +- [x] **P3 — `serve --http` sync IPC.** DONE (#4474): the stdio IPC block is + extracted to `src/mcp/resolve-ipc-binding.ts` (`bindResolveIpcForServe`) and + both serve transports bind it — resolve/turn_context/context_pack AND the + sync/sweep kinds now work under `serve --http`. Pinned by + `test/resolve-ipc-binding.test.ts`. - [ ] **P3 — delegated post-sync steps.** **What:** the direct-CLI post-steps (`manageGitignoreAtGitRoot`, the extraction-lag nudge) don't run for delegated syncs. **Why:** both need an engine or repo-adjacent context the @@ -7924,3 +7923,40 @@ covers DEAD logs; go-forward capture beyond Claude Code is deliberately absent. doctor's non-fallback DB errors mid-run, extract/import bulk loops, jobs work loop). Sweep the catch sites, route message text through the redactors, and emit the marker where `isDbAccessFailure` says so. Effort: M. +## Wave-K follow-ups (filed from v0.46.30.0 wave-k) + +- [ ] **P3 — Wave-orchestration tooling: `scripts/wave-manifest.ts`.** + **What:** a script that owns the fix-wave snapshot → manifest → absorb + pipeline (enumerate approved fix branches, emit the ordered pick manifest + with shas/files/kind, verify each pick's reachability, and record + absorb/defer outcomes). **Why:** every wave re-derives this by hand — + pass coordination facts, tsv-ownership rows, and pick order live in ad-hoc + JSON + prompts, and a transcription slip silently reorders or drops a fix. + **Context:** follow-up from v0.46.30.0 wave-k; see + `.context/wave-k/trainB-assembly.json` for the shape a generator should + emit. **Effort:** M. + +- [ ] **P3 — GitHub label-system consolidation.** **What:** collapse the old + `p0/p1/p2` + `verified-real` label family into the newer `triage:*` scheme + (one migration pass over open issues, then delete the legacy labels). + **Why:** wave triage currently matches BOTH families, so a query against + one family undercounts and severity sorts disagree between tools. + **Context:** follow-up from v0.46.30.0 wave-k. **Effort:** S. + +- [ ] **P2 — PR-triggered full-e2e opt-in label for wave-scale PRs.** + **What:** a `ci:full-e2e` (name TBD) PR label that runs the full 202-file + e2e matrix on the PR head instead of waiting for nightly. **Why:** wave + trains land tens of picks per PR; today the full matrix is nightly-only, so + a train-wide e2e regression surfaces a day after merge instead of on the + PR. **Context:** follow-up from v0.46.30.0 wave-k; blocked on + workflow-scope push credentials (the workflow file change can't ship from + a fix branch without them). **Effort:** M. + +- [ ] **P3 — #4364 verify note: `--list` DB probe misclassifies an empty + brain.** **What:** `apply-migrations --list`'s probe labels a + reachable-but-uninitialized DB "UNREACHABLE (relation config does not + exist)". Classify post-connect query errors (undefined table/relation) as + connected-uninitialized instead of unreachable. **Why:** the current label + sends operators debugging connectivity when the fix is `gbrain init`. + **Context:** follow-up from v0.46.30.0 wave-k, filed by #4364's verifier; + `src/commands/apply-migrations.ts` probe branch. **Effort:** S. diff --git a/VERSION b/VERSION index dc39c850..cb146569 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.46.34.0 \ No newline at end of file +0.46.35.0 diff --git a/bunfig.toml b/bunfig.toml index 09884e93..59bcbab4 100644 --- a/bunfig.toml +++ b/bunfig.toml @@ -28,6 +28,17 @@ timeout = 60_000 # GBRAIN_TEST_ALLOW_DATABASE_URL=1 opt-in that the e2e wrappers set at their # own subprocess boundary. See test/helpers/database-url-guard-preload.ts. # +# operator-env-preload (#4023): drop the operator's ambient CONDUCTOR_/MCP_/ +# OPENCLAW_ workspace context and GBRAIN_ config overrides (a stray +# GBRAIN_SOURCE, GBRAIN_CYCLE_FRESHNESS_WARN_HOURS, ...) that run-e2e.sh +# already scrubs for the E2E lane but the unit lane inherited. Runs right +# after the database-url guard so every later preload — especially +# legacy-embedding-preload's `env: {...process.env}` snapshot — sees the +# scrubbed environment. Test-machinery vars the runners/CI export +# (GBRAIN_TEST_*, GBRAIN_CI_*, GBRAIN_E2E_*, GBRAIN_REAL_*, GBRAIN_HOME, +# GBRAIN_DATABASE_URL, snapshot/bin fast paths) survive via keep-lists. See +# test/helpers/operator-env-preload.ts. +# # gbrain-home-preload: point GBRAIN_HOME at per-run scratch so tests never # read (or clobber) the operator's real ~/.gbrain config/brain — the live # config.json changing mid-day flipped 27 config-honoring cycle/dream tests @@ -46,4 +57,4 @@ timeout = 60_000 # 183 failures + 15-minute retry hangs on an OPENAI-only shell). The e2e # wrapper sets GBRAIN_TEST_KEEP_PROVIDER_KEYS=1 to opt back in. See # test/helpers/provider-keys-preload.ts. -preload = ["./test/helpers/database-url-guard-preload.ts", "./test/helpers/provider-keys-preload.ts", "./test/helpers/legacy-embedding-preload.ts", "./test/helpers/audit-dir-preload.ts", "./test/helpers/sync-failures-preload.ts", "./test/helpers/gbrain-home-preload.ts", "./test/helpers/git-hermetic-preload.ts"] +preload = ["./test/helpers/database-url-guard-preload.ts", "./test/helpers/operator-env-preload.ts", "./test/helpers/provider-keys-preload.ts", "./test/helpers/legacy-embedding-preload.ts", "./test/helpers/audit-dir-preload.ts", "./test/helpers/sync-failures-preload.ts", "./test/helpers/gbrain-home-preload.ts", "./test/helpers/git-hermetic-preload.ts"] diff --git a/docker-compose.ci.yml b/docker-compose.ci.yml index c8604f26..bdb96d3f 100644 --- a/docker-compose.ci.yml +++ b/docker-compose.ci.yml @@ -127,6 +127,10 @@ services: # #4479: pinned to the host bun version by default (see header comment). image: oven/bun:${GBRAIN_CI_BUN_TAG:-1.3.14} working_dir: /app + # #3893 (reimplemented from @y2688): give a TERM'd runner up to 600s to + # drain in-flight bun test shards and flush their results before docker + # SIGKILLs the container mid-write (compose default grace is 10s). + stop_grace_period: 600s depends_on: postgres-1: condition: service_healthy diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.md index fb40b8ff..a8f654e1 100644 --- a/docs/architecture/KEY_FILES.md +++ b/docs/architecture/KEY_FILES.md @@ -11,7 +11,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this - `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. Exports upload validators `validateUploadPath`, `validatePageSlug`, `validateFilename`, plus `matchesSlugAllowList(slug, prefixes)` (glob matcher: `/*` matches recursive children; bare `` 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//...` namespace check applies. Both `put_page` and `add_timeline_entry` (subagent-allowlisted) route through it. Auto-link skipped only when `remote=true && !trustedWorkspace`. `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. Plain-startsWith semantics matching `submit_agent`'s check for the same column (NOT the glob grammar of the subagent allow-list); 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 let a mixed-case slug commit and only then trip the resolved-slug re-check), accepts BOTH the trailing-slash and the v85 `/*` glob spelling via `normalizeSlugPrefix` (the column predates this fence as submit_agent's binding, so one stored value must mean one span of slugs on both paths), 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` applies the same boundary-aware rule when validating a requested prefix against the binding, normalizes trailing-slash prefixes to the glob form `matchesSlugAllowList` expects before handing them to the child job, and collapses an EXPLICIT empty `allowed_tools`/`allowed_slug_prefixes` to the binding (the worker reads empty as "full registry" / "legacy `wiki/agents//` namespace", so `??` — which only substitutes null/undefined — left a vacuous-subset bypass). `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` but NO `auth`, so an auth-only test 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 (closes the HTTP MCP shell-job RCE where a read+write OAuth token could 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`). `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 (#1941): `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: `/*` matches recursive children; bare `` 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//...` namespace check applies. Both `put_page` and `add_timeline_entry` (subagent-allowlisted) route through it. Auto-link skipped only when `remote=true && !trustedWorkspace`. `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. Plain-startsWith semantics matching `submit_agent`'s check for the same column (NOT the glob grammar of the subagent allow-list); 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 let a mixed-case slug commit and only then trip the resolved-slug re-check), accepts BOTH the trailing-slash and the v85 `/*` glob spelling via `normalizeSlugPrefix` (the column predates this fence as submit_agent's binding, so one stored value must mean one span of slugs on both paths), 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` applies the same boundary-aware rule when validating a requested prefix against the binding, normalizes trailing-slash prefixes to the glob form `matchesSlugAllowList` expects before handing them to the child job, and collapses an EXPLICIT empty `allowed_tools`/`allowed_slug_prefixes` to the binding (the worker reads empty as "full registry" / "legacy `wiki/agents//` namespace", so `??` — which only substitutes null/undefined — left a vacuous-subset bypass). `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` but NO `auth`, so an auth-only test 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 (closes the HTTP MCP shell-job RCE where a read+write OAuth token could 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`). `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 (#1941): `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 `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/engine.ts` — Pluggable engine interface (BrainEngine). `clampSearchLimit(limit, default, cap)` takes an explicit cap so per-operation caps can be tighter than `MAX_SEARCH_LIMIT`. Exports `LinkBatchInput`/`TimelineBatchInput` for the bulk-insert API (`addLinksBatch`/`addTimelineEntriesBatch`). `readonly kind: 'postgres' | 'pglite'` discriminator lets `src/core/migrate.ts` and others branch without `instanceof` + dynamic imports. Methods: `batchLoadEmotionalInputs(slugs?)` (CTE-shaped read with per-table aggregates so page × N tags × M takes never produces N×M rows), `setEmotionalWeightBatch(rows)` (`UPDATE FROM unnest($1::text[],$2::text[],$3::real[])` composite-keyed on `(slug, source_id)`), `getRecentSalience(opts)`, `findAnomalies(opts)`. `PageFilters` has `sort?: 'updated_desc'|'updated_asc'|'created_desc'|'slug'` + `PAGE_SORT_SQL` whitelist consumed by both engines. `listAllPageRefs(): Promise>` ordered by `(source_id, slug)` — cheap cross-source enumeration replacing the `getAllSlugs()→getPage(slug)` N+1 (which silently defaulted to `source_id='default'`); parity across postgres-engine.ts + pglite-engine.ts; Pinned by `test/e2e/multi-source-bug-class.test.ts`. `SearchOpts`+`PageFilters` add `sourceIds?: string[]` (federated read axis; both engines apply `WHERE source_id = ANY($N::text[])` when set, preserve scalar `sourceId` fast path when unset); `traverseGraph(slug, depth, opts?)` and `traversePaths(slug, opts?)` accept `opts.sourceId`/`opts.sourceIds`. The by-slug read methods carry the same federated axis: `getTags`/`getLinks`/`getBacklinks`/`getChunks` opts and `TimelineOpts` (consumed by `getTimeline`) accept `sourceIds?: string[]` taking precedence over the scalar `sourceId` (`source_id = ANY($::text[])` scoping the slug→page-id lookup); `getChunks` falls back to the `'default'` source when neither is set (importCodeFile's incremental-embedding reuse relies on it) and SELECTs an explicit non-vector column list — embedding vectors never ride the payload since rowToChunk discards them (`getChunksWithEmbeddings` stays scalar-only by design: engine-internal, zero remote-reachable callers); the link reads (`getLinks`/`getBacklinks`) scope ALL THREE endpoints (from/to/origin) on the federated branch while the scalar branch scopes only the near endpoint for trusted internal cross-source callers. `traverseGraph` opts has `frontierCap?: number` (per-iteration recursive-CTE cap, approx per-BFS-layer); return type `Promise` for MCP wire stability; export `TraverseGraphOpts`; Postgres uses parenthesized `LIMIT N ORDER BY (slug, id)` inside the recursive term, PGLite mirrors with positional params; Pinned by `test/regressions/v0_36_frontier_cap.test.ts`. Phantom-redirect methods: `refreshPageBody(slug, sourceId, compiled_truth, timeline, content_hash)` narrow-UPDATEs three columns + updated_at, skipping soft-deleted rows (content_hash refresh required so `gbrain sync` sees the canonical as unchanged after fence merge); `migrateFactsToCanonical(phantomSlug, canonicalSlug, sourceId)` UPDATEs `entity_slug`+`source_markdown_slug` on every active fact row keyed on the phantom, preserving embedding/validUntil/kind/status/source_session/confidence; parity at `test/phantom-redirect-engine-parity.test.ts`. `getAdjacencyBoosts(pageIds): Promise>` powers the per-query graph-signals stage — one SQL query returning inbound-link counts among top-K plus a cross-source count (links from differing `source_id`); `COALESCE(p.source_id,'default')` null safety, `HAVING >= 1`, cross-source CASE-WHEN excludes the target's own source; parity SQL across both engines; `SearchResult` gains optional `base_score`, `backlink_boost`, `salience_boost`, `recency_boost`, `exact_match_boost`, `graph_adjacency_boost`, `graph_cross_source_boost`, `session_demote_factor`, `reranker_delta` + internal staging fields; Pinned by `test/e2e/graph-signals-engine.test.ts`. Two REQUIRED methods: `deletePages(slugs, {sourceId}): Promise` (single-batch primitive returning slugs actually deleted) and `resolveSlugsByPaths(paths, {sourceId}): Promise>` (batch path→slug lookup); `sourceId` REQUIRED on both at the type level (asymmetric with single-row `deletePage` which keeps optional/'default'); both short-circuit on empty input and throw when `> DELETE_BATCH_SIZE`. Embedding-signature stale-detection quartet: `countStaleChunks(opts?)` gains optional `signature?: string` widening the stale predicate from `embedding IS NULL` to ALSO include chunks whose JOINed page `embedding_signature IS NOT NULL AND <> $signature` (NULL signature is GRANDFATHERED, never counted; omit `signature` for the legacy NULL-only count); `sumStaleChunkChars(opts?: {sourceId?, signature?}): Promise` = `SUM(LENGTH(chunk_text))` over stale chunks (same predicate + embed_skip filter + optional sourceId scope), used by `gbrain sync --all` cost preview via `estimateCostFromChars`; `setPageEmbeddingSignature(slug, {sourceId?, signature})` stamps `pages.embedding_signature` after a page's chunks (re)embed, idempotent no-op when page absent; `invalidateStaleSignatureEmbeddings({signature, sourceId?}): Promise` NULLs `embedding`+`embedded_at` on every chunk whose page signature is set AND differs, returning the count, called BEFORE `listStaleChunks` so signature-drift pages flow through the NULL-embedding keyset cursor unchanged (NULL never invalidated). Widens `findOrphanPages(opts?: {sourceId?, sourceIds?})` (candidate-side scoping only; inbound links counted from any source). Pinned by `test/sum-stale-chunk-chars.test.ts`, `test/embedding-signature-stale.test.ts`, `test/e2e/engine-parity.test.ts`. Free-text alias layer: `resolveAliases(aliasNorms, opts?): Promise>>` (READ; maps each normalized alias to declaring `(slug, source_id)` pairs, source-scoped) and `setPageAliases(slug, sourceId, aliasNorms)` (WRITE; replaces the full alias set, delete-then-insert, empty clears, idempotent on the unique triple), called by the `importFromContent` ingest projection and the `reindex --aliases` backfill; parity across both engines, Pinned by `test/search/page-aliases-engine.test.ts`. `searchVector` in both engines injects the shared `buildBestPerPagePoolCte` per-page max-pool so a page surfaces on its strongest chunk. `executeRawDirect(sql, params?, opts?)` is the lock-hot-path sibling of `executeRaw`: same single-statement contract, but routes to the direct session-mode pool when dual-pool is active (Postgres/Supabase port 5432) so a long-held lock heartbeat survives the transaction pooler's per-transaction connection recycling; PGLite delegates straight to `executeRaw` (no pooler). Both engines implement it; the Minion lock path (`claim`/`renewLock`) is the consumer. `reconnect(ctx?: {error?})` is a REQUIRED lifecycle method on BOTH engines: it recovers a dropped connection using the config captured at the last `connect()`, so callers (autopilot health probe, `batchRetry`) never `disconnect()` + bare `connect()` (which loses the config and throws `database_url undefined` forever, and opens a null-connection window). PostgresEngine rebuilds its pool with a `_reconnecting` reentrancy guard and emits pool-recovery audit; PGLite is single-writer in-process so it just restores the saved data dir for parity. Plus two interface members: (1) optional `findDuplicatePage?(sourceId, {hash, frontmatterId?}): Promise<{slug, id} | null>` (identity precedence is content_hash OR frontmatter->>'id', both with `deleted_at IS NULL`); (2) `resolveSlugs(partial, opts?)` extended with `{sourceId?, sourceIds?}` so the MCP fuzzy `get_page` path scopes by source (field names match `sourceScopeOpts(ctx)` output so handlers spread directly; back-compatible — no opts gives prior behavior). Plus a stable tiebreaker `ORDER BY score DESC, page_id ASC, chunk_id ASC` in `searchVector` in both engines: on a score tie (basis-vector eval fixtures) older `page_id` wins, closing the planner-non-determinism class where a new index on `pages` could flip ranking on tied scores. - `src/core/engine-constants.ts` — single source of truth for engine batch-sizing constants. Exports `DELETE_BATCH_SIZE = 500` consumed by both engines' `deletePages` + `resolveSlugsByPaths` and by the sync delete + rename loops. Lives outside `engine.ts` (the interface module) to avoid circular-import worry — bounded per-statement work for predictable lock hold time + write amplification. @@ -147,9 +147,9 @@ per-release `**vX.Y.Z:**` narration — CI enforces this - `src/core/sync-delta.ts` — the single "what changed since last_commit" helper (#2139), consumed by BOTH `performSyncInner` (sync executor) and `estimateInlineNewTokens` (cost estimator) so the gate's dollar figure can't drift from what the sync imports. `computeSyncDelta(repoPath, fromCommit, toCommit, {detachedManifest?, detached?})` → `{status:'ok', manifest}` | `{status:'unavailable', reason:'anchor_missing'|'diff_failed'}`. Anchor reachability via `git cat-file -t` (#1970 discipline — a gc'd bookmark is `anchor_missing`, but a present-but-non-ancestor bookmark is still diffed tree-to-tree), then `git diff --name-status -M from..to` parsed by `buildSyncManifest`; merges the detached working-tree manifest when detached (`buildDetachedWorkingTreeManifest`, relocated here from sync.ts). NO dirty/untracked probe in the estimator — pricing dirty files would re-introduce phantom costs on a busy brain. The executor imports only the commit diff on attached HEADs BY DEFAULT, but now counts uncommitted working-tree files (untracked + dirty) as `SyncResult.uncommitted` drift and, with `--working-tree` / config `sync.include_working_tree`, merges the working-tree manifest into the delta so attached repos can import uncommitted state (the estimator does not price that opt-in). `execFileSync` array-args (shell-injection safe), 30s / 100 MiB budget. Test seam `_setGitRunnerForTests`. Pinned by `test/sync-delta.test.ts`. - `src/core/spend-posture.ts` — spend-control surface (#2139). `resolveSpendPosture(engine): 'gated'|'tokenmax'` (DB-plane `spend.posture`, fail-open `gated`); `tokenmax` makes every cost gate informational across sync/reindex/enrich/onboard (spend still ledgered — removes the ceiling, not the accounting). `parseUsdLimit(raw, def, {allowZero?})` accepts `off`/`unlimited`/`none` → `Infinity`; `formatUsdLimit(n)` renders `Infinity` as the string `'unlimited'` (never raw — `JSON.stringify(Infinity)` is `null`); `usdLimitToCap(n)` maps `Infinity` → `undefined` at the BudgetTracker boundary so ledger rows never serialize null. `normalizeSpendPosture`/`isValidSpendPosture` back the `config set` validation. Doc: `docs/operations/spend-controls.md`. Pinned by `test/sync-cost-preview.test.ts` + `test/spend-off-switch.test.ts`. - `src/core/ai/dims.ts` — per-provider `providerOptions` resolver for embed-time dimension passthrough; the single source of truth for "which provider needs which knob to produce `vector(N)`". Exports `dimsProviderOptions(implementation, modelId, dims)` (called by `embed()` in `gateway.ts`), `VOYAGE_OUTPUT_DIMENSION_MODELS` (private const — the 7 hosted Voyage models that accept `output_dimension`: `voyage-4-large`, `voyage-4`, `voyage-4-lite`, `voyage-3-large`, `voyage-3.5`, `voyage-3.5-lite`, `voyage-code-3` — nano deliberately excluded), `VOYAGE_VALID_OUTPUT_DIMS = [256, 512, 1024, 2048] as const`, `supportsVoyageOutputDimension(modelId)`, `isValidVoyageOutputDim(dims)`. Voyage path uses the SDK-supported `dimensions` field (`{ openaiCompatible: { dimensions: N } }`), NOT Voyage's `output_dimension` wire-key — the `voyageCompatFetch` shim in `gateway.ts:541` translates `dimensions → output_dimension` before the HTTP body is built (the AI SDK's openai-compatible adapter doesn't recognize the wire-key, so sending it from here would be silently dropped and Voyage would return its default 1024-dim). Runtime guard: when a Voyage flexible-dim model is configured with `dims` outside `VOYAGE_VALID_OUTPUT_DIMS`, throws `AIConfigError` with a paste-ready `gbrain config set embedding_dimensions <256|512|1024|2048>` hint at the embed boundary (most common trigger: `embedding_model: voyage:voyage-4-large` without `embedding_dimensions`, falling back to `DEFAULT_EMBEDDING_DIMENSIONS=1536`, an OpenAI default not a Voyage one). Every lookup in this module folds through the private `modelMatchKey` (trim + lowercase, #4123) so cased hub-form ids (`Qwen/Qwen3-Embedding-4B`) match the all-lowercase tables — the folded key is a MATCH key only, never sent to a provider (wire model ids are case-sensitive; error messages keep the original id so they stay paste-ready); the Qwen3-Embedding native-width table lives at module scope alongside the other dim tables. Consequence, deliberate: a cased Voyage/ZeroEntropy/Perplexity config that used to skip validation (and silently produce wrong-width vectors) now matches and fails loudly at init when its `dims` is invalid. -- `src/core/ai/types.ts` — provider/recipe types. `EmbeddingTouchpoint` has optional `chars_per_token` (default 4, matching OpenAI tiktoken on English) and `safety_factor` (default 0.8, budget-utilization ceiling), both consulted only when `max_batch_tokens` is also set; Voyage declares `chars_per_token=1` + `safety_factor=0.5` to handle dense payloads (CJK/JSON/base64). Pre-split budget = `max_batch_tokens × safety_factor / chars_per_token`. `EmbeddingTouchpoint.multimodal_models?: string[]` model-level allow-list for recipes mixing text-only + multimodal models under one touchpoint (Voyage's 12 models share `supports_multimodal: true` but only `voyage-multimodal-3` accepts `/multimodalembeddings`); when omitted, recipe-level `supports_multimodal` is sufficient. `AIGatewayConfig.embedding_multimodal_model?: string` lets `embedMultimodal()` route to a different model than `embedding_model` (OpenAI text + Voyage images without flipping the primary pipeline). `EmbeddingTouchpoint.trust_custom_dims?: true` — passthrough tier for a user-declared `--embedding-dimensions` on local / bring-your-own-backend recipes (ollama, llama-server, litellm) where the model catalog can't be enumerated; consumed by `isCustomDimValidForProvider` in `src/core/embedding-dim-check.ts` AFTER Tier 1 (recipe `dims_options`) and Tier 2 (provider Matryoshka allowlists), so a recipe that declares fixed options (openrouter) is still governed by those and fixed-dim hosted providers (openai/voyage/zeroentropy) stay fail-closed; the provider's `/embeddings` response-dim validation catches a genuine mismatch pre-storage. `Recipe.default_headers?: Record` (static) and `Recipe.resolveDefaultHeaders?(env)` (env-templated) seam for per-recipe headers riding alongside auth on every openai-compat touchpoint; mutually exclusive (declaring both throws `AIConfigError` at gateway-configure time); keys conflicting with the resolved auth header (`Authorization`, the resolver's custom header) rejected at `applyResolveAuth` call time so defaults can't shadow auth. Used by OpenRouter for the `HTTP-Referer` + `X-OpenRouter-Title` + `X-Title` attribution triple. +- `src/core/ai/types.ts` — provider/recipe types. `EmbeddingTouchpoint` has optional `chars_per_token` (default 4, matching OpenAI tiktoken on English) and `safety_factor` (default 0.8, budget-utilization ceiling), both consulted only when `max_batch_tokens` is also set; Voyage declares `chars_per_token=1` + `safety_factor=0.5` to handle dense payloads (CJK/JSON/base64). Pre-split budget = `max_batch_tokens × safety_factor / chars_per_token`. `EmbeddingTouchpoint.multimodal_models?: string[]` model-level allow-list for recipes mixing text-only + multimodal models under one touchpoint (Voyage's 12 models share `supports_multimodal: true` but only `voyage-multimodal-3` accepts `/multimodalembeddings`); when omitted, recipe-level `supports_multimodal` is sufficient. `AIGatewayConfig.embedding_multimodal_model?: string` lets `embedMultimodal()` route to a different model than `embedding_model` (OpenAI text + Voyage images without flipping the primary pipeline). `AIGatewayConfig.embedding_image_ocr_model?: string` is its OCR sibling (#4107): `generateOcrText()` routes to it instead of the expansion model; a direct `provider:model` string, never `models.tier`-resolved. `EmbeddingTouchpoint.trust_custom_dims?: true` — passthrough tier for a user-declared `--embedding-dimensions` on local / bring-your-own-backend recipes (ollama, llama-server, litellm) where the model catalog can't be enumerated; consumed by `isCustomDimValidForProvider` in `src/core/embedding-dim-check.ts` AFTER Tier 1 (recipe `dims_options`) and Tier 2 (provider Matryoshka allowlists), so a recipe that declares fixed options (openrouter) is still governed by those and fixed-dim hosted providers (openai/voyage/zeroentropy) stay fail-closed; the provider's `/embeddings` response-dim validation catches a genuine mismatch pre-storage. `Recipe.default_headers?: Record` (static) and `Recipe.resolveDefaultHeaders?(env)` (env-templated) seam for per-recipe headers riding alongside auth on every openai-compat touchpoint; mutually exclusive (declaring both throws `AIConfigError` at gateway-configure time); keys conflicting with the resolved auth header (`Authorization`, the resolver's custom header) rejected at `applyResolveAuth` call time so defaults can't shadow auth. Used by OpenRouter for the `HTTP-Referer` + `X-OpenRouter-Title` + `X-Title` attribution triple. - `src/core/ai/defaults.ts` — leaf module holding the embedding/reranker default constants (no gateway import, so schema + registry helpers can read them without loading provider SDKs). Split-default: `NEW_INSTALL_DEFAULT_EMBEDDING_MODEL` (`voyage:voyage-4`) + `NEW_INSTALL_DEFAULT_EMBEDDING_DIMENSIONS` (1024) feed every new-install surface — init auto-pick canonical tiebreak, the interactive picker default, the no-keys hint, keyless fresh-install schema sizing (passed as an explicit init param), and all recommendation copy (playbook, banners, doctor fix-hints, advisor). `NEW_INSTALL_DEFAULT_RERANKER_MODEL` (`voyage:rerank-2.5`) is written as explicit `search.reranker.model` config at init whenever a Voyage key is present on either plane (env or `~/.gbrain/config.json`), regardless of which embedding provider was picked (`init.ts:writeNewInstallRerankerDefault`, shared by the PGLite + Postgres paths); keyed non-Voyage installs get explicit `search.reranker.enabled false` instead (never inherit the doomed legacy bundle fallback they have no key for), keyless installs get NO reranker write (the documented keyless-recovery re-init must find virgin reranker config so its override still lands), deliberate `zeroentropyai:*` installs are left on the legacy bundle, and an existing explicit reranker choice is never clobbered. Quoted by the migration playbook; the runtime reranker defaults (gateway `DEFAULT_RERANKER_MODEL` + the mode-bundle values) stay on `zerank-2` until the September removal. `DEFAULT_EMBEDDING_MODEL` (`zeroentropyai:zembed-1`) + `DEFAULT_EMBEDDING_DIMENSIONS` (1280) serve ONLY as the configless runtime fallback for brains with no `embedding_model` in file config — their stored vectors live in ZE's 1280d space, so flipping the fallback under them would break retrieval before the provider dies; the September removal release deletes the fallback and hard-errors unmigrated configless brains with the migrate command. `ZEROENTROPY_SUNSET_DATE` (`'2026-09-04'`) is the single source of truth for the upgrade banners, the `provider_sunset` doctor check, and the ZE recipe's `sunset` metadata. -- `src/core/ai/gateway.ts` — unified seam for every AI call. `embedQuery(text, opts?)` and `isAvailable(touchpoint, modelOverride?)` accept a model override so the resolved-column path embeds via the column's provider (Voyage / ZeroEntropy / OpenAI) instead of the global default; the hybrid path passes `{embeddingModel: resolved.provider, dimensions: resolved.dimensions}` and the gateway resolves the matching recipe via `instantiateEmbedding()`. `isAvailable('embedding', 'voyage:voyage-3-large')` checks the override's recipe (not the default) so hybrid skips vector search only when the active column's provider is actually down. `zeroEntropyCompatFetch` shim (sibling to `voyageCompatFetch`) handles ZE's non-OpenAI-compatible wire shape — rewrites the request URL `/embeddings → /models/embed`, injects `input_type` (default `'document'`; the threaded `'query'|'document'` crosses the SDK boundary via the module-level `__embedInputTypeStore` AsyncLocalStorage populated in `embedSubBatch()`, because the AI SDK's openai-compatible adapter strips `input_type` from `providerOptions` before building the wire body — #1400; `voyageCompatFetch` injects it opt-in the same way, and `openAICompatAsymmetricFetch` is the fallthrough shim for every other openai-compat recipe — llama-server/litellm/ollama — a strict pass-through when nothing was threaded) and explicit `encoding_format: 'float'`, and rewrites the response `{results: [{embedding}], usage: {total_bytes, total_tokens}}` → `{data: [{embedding, index}], usage: {prompt_tokens, total_tokens}}` so the SDK's openai-compatible Zod schema validates. Layer 1 (Content-Length) + Layer 2 (per-embedding) OOM caps via tagged `ZeroEntropyResponseTooLargeError` (kept separate from `VoyageResponseTooLargeError` because `test/voyage-response-cap.test.ts` does structural source-text greps pinning the Voyage name). Wired in `instantiateEmbedding()` via the `recipe.id === 'zeroentropyai'` branch. `gateway.rerank()` native HTTP path (no AI-SDK reranking abstraction): resolves the configured reranker via `getRerankerModel()`, posts to the recipe's reranker path (`touchpoints.reranker.path`, default `/models/rerank`; Voyage declares `/rerank`) with bearer auth — the request's top-N key is recipe-pluggable via `touchpoints.reranker.top_param` (default `top_n`; Voyage `top_k`) — and returns `RerankResult[]` sorted by relevance. `warnSunsetOnce(recipe, touchpoint)`: once-per-(recipe,touchpoint) stderr DEPRECATED warning for recipes carrying `sunset` metadata, fired on actual use (embedding resolution + the rerank path) so brains still riding a dying provider hear about it on every process, not only at upgrade time; prints the sunset date plus the migrate / `search.reranker.model` fix, never throws, `_resetSunsetWarningsForTest()` is the test seam. `RerankError.reason` classifier: `auth | rate_limit | network | timeout | payload_too_large | unknown`. 5s default timeout (search hot path). Pre-flight payload guard rejects bodies over `recipe.touchpoints.reranker.max_payload_bytes` with `reason: 'payload_too_large'`. `_rerankTransport` test seam mirrors `_embedTransport`. `embedQuery(text)` threads `inputType: 'query'` through `dimsProviderOptions()` (4-arg). `getRerankerModel()` accessor + `isAvailable('reranker')` branch; `configureGateway` + `reconfigureGatewayWithEngine` thread `reranker_model`; `applyResolveAuth` + `defaultResolveAuth` widen touchpoint param to include `'reranker'`. `embedMultimodalOpenAICompat()` routes recipes with `implementation: 'openai-compatible'` (LiteLLM, Anyscale, vLLM, Gemini multimodal via proxy) through the standard `/embeddings` endpoint with content arrays carrying `image_url` entries; the Voyage `/multimodalembeddings` path is unchanged (gateway selects by recipe `implementation` tag). Runtime dimension validation throws `AIConfigError` (with model id + observed + expected) before the vector reaches storage when the provider returns a width that doesn't match the recipe's `default_dims` or the brain's `embedding_dimensions`. Pinned by `test/openai-compat-multimodal.test.ts`. Module-scoped `_embedTransport` defaults to AI SDK `embedMany`, with `__setEmbedTransportForTests(fn)` test seam so tests drive `embed()` with a stubbed transport. `splitByTokenBudget` and `isTokenLimitError` exported `@internal` (pure functions reused by the test file). Module-level `_shrinkState: Map` halves the recipe's effective `safety_factor` on token-limit miss (floor 0.05) and heals back ×1.5 after `SHRINK_HEAL_AFTER=10` consecutive successes. `configureGateway()` walks every registered recipe at construction and emits a once-per-process stderr warning for any embedding touchpoint missing `max_batch_tokens` (excluding the canonical OpenAI fast-path). `resetGateway()` clears `_shrinkState`, the warned-set, and restores the real transport. `embedMultimodal()` reads `cfg.embedding_multimodal_model` first (falls back to `cfg.embedding_model`); after the recipe-level `supports_multimodal` fast-fail, validates the resolved model against `touchpoint.multimodal_models` when declared (closes the Voyage-text-only-into-multimodal-endpoint footgun before any HTTP call). `getMultimodalModel()` accessor mirrors `getEmbeddingModel` / `getChatModel`. Exported `VoyageResponseTooLargeError` tagged class: `voyageCompatFetch`'s two OOM-defense caps (Layer 1 Content-Length, Layer 2 per-embedding base64) throw it; the inbound response-rewriter's try/catch (which swallows parse failures so misshaped responses fall through to the SDK parser) checks `instanceof VoyageResponseTooLargeError` and rethrows so the cap is actually effective (regression assertion in `test/voyage-response-cap.test.ts` pins the `instanceof ⇒ throw err` line). AI SDK v6 toolLoop compat (`gbrain skillopt` rollouts AND production background `subagent` jobs both route through `chat()` / `toolLoop`): in `chat()`, tool defs wrap the raw JSON Schema with the SDK's `jsonSchema()` helper (`inputSchema: jsonSchema(t.inputSchema)`) — v6's `asSchema()` treats a bare `{jsonSchema: ...}` object as a thunk and throws "schema is not a function"; new exported pure `toModelMessages(messages: ChatMessage[]): unknown[]` converts gbrain's provider-neutral `ChatMessage[]` into v6 `ModelMessage[]` — tool results (pushed by `toolLoop` as `role:'user'` with bare-value tool-result blocks) become a dedicated `role:'tool'` message with structured `output:{type:'json'|'text'|'error-text', value}` parts; `null` output preserved as `{type:'json', value:null}` (not dropped); text/tool-call blocks pass through with v6 field names (`toolCallId`/`toolName`/`input`); applied at the `generateText` call (`messages: toModelMessages(opts.messages)`). The converter is the load-bearing fix for the production subagent path, not just skillopt. Pinned by `test/gateway-model-messages.test.ts`. Companion fix in `src/core/skillopt/rollout.ts`: the inline `paramsToSchema` dropped `items` on array params; it now uses the shared `paramDefToSchema` from `src/mcp/tool-defs.ts` (single source of truth, recursive on items/enum/default). Provider-agnostic plumbing: `resolveNativeBaseUrl(provider, cfg)` normalizes a configured `ANTHROPIC_BASE_URL` / `OPENAI_BASE_URL` to carry the `/v1` suffix and is passed explicitly at every native `createAnthropic` / `createOpenAI` site (chat/expansion/embedding), so an env-injected bare host doesn't 404; returns `undefined` when unset so the SDK default is preserved (Google deferred until its native suffix is verified). `diagnoseEmbedding` fails closed with `user_provided_dims_unset` when a user-provided / zero-default recipe (litellm/llama-server) has no configured `embedding_dimensions` — this REPLACED the old `user_provided_model_unset` guard, which was structurally unreachable (parseModelId throws on a bare provider) and only ever false-positived for `litellm:`, silently disabling vector search. `configureGateway` no longer backfills `embedding_dimensions` (readers default it themselves), keeping the "no dims set" signal honest for that guard and the multimodal skip. `withBudgetTracker`: gateway-layer enforcement via `AsyncLocalStorage`. `withBudgetTracker(tracker, fn)` installs the tracker on the module-internal store; every `gateway.chat / embed / rerank` call inside the scope auto-composes (reserve before, record in try/finally). Outside-scope calls are budget no-ops. Nested scopes restore the outer tracker on exit. `getCurrentBudgetTracker()` is the test seam. The chat path uses the pessimistic fallback on error paths; the embed path estimates input tokens from char count × recipe's `chars_per_token` because the AI SDK doesn't surface per-batch embed token usage; the rerank path estimates char count of query+docs. Pinned by 6 unit cases. `reconfigureGatewayWithEngine(engine)` (async, called from `cli.ts` after `engine.connect()`, before every command except `CLI_ONLY` no-DB commands) re-resolves expansion + chat defaults through `resolveModel()` so `models.tier.*` and `models.default` overrides apply to both. `DEFAULT_CHAT_MODEL` is `anthropic:claude-sonnet-4-6`. `__setChatTransportForTests` mirrors `__setEmbedTransportForTests` so tests drive `chat()` with a stubbed transport. `toolLoop` per-turn permit hook (#4194/CDX-7): optional `acquireTurnPermit()` acquires a provider permit before EVERY round-trip and releases in finally; a lease-full throw propagates without consuming the turn (the subagent path wires it to the rate leases with provider-derived keys — Anthropic models share `anthropic:messages`, others get `:chat`). `ToolLoopStopReason` includes `'length'` (#4088): a zero-tool-call turn that hit the output cap propagates 'length' instead of folding into 'end', so truncation is never reported as a clean finish. Per-part provider state (#4201): `ChatBlock` variants carry optional `providerMetadata` captured from SDK parts in `chat()` and re-emitted as `providerOptions` on the rebuilt parts in `toModelMessages()` (attached only when present — metadata-free blocks stay byte-identical); this is the Gemini 3.x thoughtSignature echo. `isThinkingByDefaultModel(modelStr)` (exported, #4087) matches Claude 5-family ids behind any provider-prefix chain with a letters-only family segment (never `claude-3-5-*`) and drives `defaultMaxOutputTokens`'s 32k thinking headroom; think/index.ts shares it. `expand()` and `generateOcrText()` also record on the ambient tracker (#4121 — they call generateObject/generateText directly and never pass through `chat()`'s `_recordBudget`, so their spend was previously invisible to every cap and ledger): record-only, no reserve — a breach surfaces on the NEXT reserving call, matching `chat()`'s swallow of `BudgetExhausted` from `record()`. Successes record normalized SDK usage via `normalizeSdkUsage` (the ONE home for the v6/legacy usage shapes, used by chat's success path too; first FINITE field wins so a NaN v6 field can't shadow a real legacy value or poison the running total); failures record pessimistically under `gateway.expand.failed` / `gateway.ocr.failed` (a rejected attempt still billed provider tokens — one expand() can legitimately produce two records when the structured-output attempt fails and the text fallback runs). A recipe whose declared structured-output support is rejected at call time is remembered for the process lifetime (`_structuredOutputRejectedRecipes`) so the rejected attempt isn't re-paid on every call. OCR's input estimate is prompt text + a fixed per-image token constant, never base64 length (bytes are not tokens). `__setGenerateObjectTransportForTests` mirrors the generateText seam. + `test/core/budget/expand-records-budget.test.ts` + `test/ai/gateway-ocr-budget.test.ts` +- `src/core/ai/gateway.ts` — unified seam for every AI call. `embedQuery(text, opts?)` and `isAvailable(touchpoint, modelOverride?)` accept a model override so the resolved-column path embeds via the column's provider (Voyage / ZeroEntropy / OpenAI) instead of the global default; the hybrid path passes `{embeddingModel: resolved.provider, dimensions: resolved.dimensions}` and the gateway resolves the matching recipe via `instantiateEmbedding()`. `isAvailable('embedding', 'voyage:voyage-3-large')` checks the override's recipe (not the default) so hybrid skips vector search only when the active column's provider is actually down. `zeroEntropyCompatFetch` shim (sibling to `voyageCompatFetch`) handles ZE's non-OpenAI-compatible wire shape — rewrites the request URL `/embeddings → /models/embed`, injects `input_type` (default `'document'`; the threaded `'query'|'document'` crosses the SDK boundary via the module-level `__embedInputTypeStore` AsyncLocalStorage populated in `embedSubBatch()`, because the AI SDK's openai-compatible adapter strips `input_type` from `providerOptions` before building the wire body — #1400; `voyageCompatFetch` injects it opt-in the same way, and `openAICompatAsymmetricFetch` is the fallthrough shim for every other openai-compat recipe — llama-server/litellm/ollama — a strict pass-through when nothing was threaded) and explicit `encoding_format: 'float'`, and rewrites the response `{results: [{embedding}], usage: {total_bytes, total_tokens}}` → `{data: [{embedding, index}], usage: {prompt_tokens, total_tokens}}` so the SDK's openai-compatible Zod schema validates. Layer 1 (Content-Length) + Layer 2 (per-embedding) OOM caps via tagged `ZeroEntropyResponseTooLargeError` (kept separate from `VoyageResponseTooLargeError` because `test/voyage-response-cap.test.ts` does structural source-text greps pinning the Voyage name). Wired in `instantiateEmbedding()` via the `recipe.id === 'zeroentropyai'` branch. `gateway.rerank()` native HTTP path (no AI-SDK reranking abstraction): resolves the configured reranker via `getRerankerModel()`, posts to the recipe's reranker path (`touchpoints.reranker.path`, default `/models/rerank`; Voyage declares `/rerank`) with bearer auth — the request's top-N key is recipe-pluggable via `touchpoints.reranker.top_param` (default `top_n`; Voyage `top_k`) — and returns `RerankResult[]` sorted by relevance. `warnSunsetOnce(recipe, touchpoint)`: once-per-(recipe,touchpoint) stderr DEPRECATED warning for recipes carrying `sunset` metadata, fired on actual use (embedding resolution + the rerank path) so brains still riding a dying provider hear about it on every process, not only at upgrade time; prints the sunset date plus the migrate / `search.reranker.model` fix, never throws, `_resetSunsetWarningsForTest()` is the test seam. `RerankError.reason` classifier: `auth | rate_limit | network | timeout | payload_too_large | unknown`. 5s default timeout (search hot path). Pre-flight payload guard rejects bodies over `recipe.touchpoints.reranker.max_payload_bytes` with `reason: 'payload_too_large'`. `_rerankTransport` test seam mirrors `_embedTransport`. `embedQuery(text)` threads `inputType: 'query'` through `dimsProviderOptions()` (4-arg). `getRerankerModel()` accessor + `isAvailable('reranker')` branch; `configureGateway` + `reconfigureGatewayWithEngine` thread `reranker_model`; `applyResolveAuth` + `defaultResolveAuth` widen touchpoint param to include `'reranker'`. `embedMultimodalOpenAICompat()` routes recipes with `implementation: 'openai-compatible'` (LiteLLM, Anyscale, vLLM, Gemini multimodal via proxy) through the standard `/embeddings` endpoint with content arrays carrying `image_url` entries; the Voyage `/multimodalembeddings` path is unchanged (gateway selects by recipe `implementation` tag). Runtime dimension validation throws `AIConfigError` (with model id + observed + expected) before the vector reaches storage when the provider returns a width that doesn't match the recipe's `default_dims` or the brain's `embedding_dimensions`. Pinned by `test/openai-compat-multimodal.test.ts`. Module-scoped `_embedTransport` defaults to AI SDK `embedMany`, with `__setEmbedTransportForTests(fn)` test seam so tests drive `embed()` with a stubbed transport. `splitByTokenBudget` and `isTokenLimitError` exported `@internal` (pure functions reused by the test file). Module-level `_shrinkState: Map` halves the recipe's effective `safety_factor` on token-limit miss (floor 0.05) and heals back ×1.5 after `SHRINK_HEAL_AFTER=10` consecutive successes. `configureGateway()` walks every registered recipe at construction and emits a once-per-process stderr warning for any embedding touchpoint missing `max_batch_tokens` (excluding the canonical OpenAI fast-path). `resetGateway()` clears `_shrinkState`, the warned-set, and restores the real transport. `embedMultimodal()` reads `cfg.embedding_multimodal_model` first (falls back to `cfg.embedding_model`); after the recipe-level `supports_multimodal` fast-fail, validates the resolved model against `touchpoint.multimodal_models` when declared (closes the Voyage-text-only-into-multimodal-endpoint footgun before any HTTP call). `getMultimodalModel()` accessor mirrors `getEmbeddingModel` / `getChatModel`. Exported `VoyageResponseTooLargeError` tagged class: `voyageCompatFetch`'s two OOM-defense caps (Layer 1 Content-Length, Layer 2 per-embedding base64) throw it; the inbound response-rewriter's try/catch (which swallows parse failures so misshaped responses fall through to the SDK parser) checks `instanceof VoyageResponseTooLargeError` and rethrows so the cap is actually effective (regression assertion in `test/voyage-response-cap.test.ts` pins the `instanceof ⇒ throw err` line). AI SDK v6 toolLoop compat (`gbrain skillopt` rollouts AND production background `subagent` jobs both route through `chat()` / `toolLoop`): in `chat()`, tool defs wrap the raw JSON Schema with the SDK's `jsonSchema()` helper (`inputSchema: jsonSchema(t.inputSchema)`) — v6's `asSchema()` treats a bare `{jsonSchema: ...}` object as a thunk and throws "schema is not a function"; new exported pure `toModelMessages(messages: ChatMessage[]): unknown[]` converts gbrain's provider-neutral `ChatMessage[]` into v6 `ModelMessage[]` — tool results (pushed by `toolLoop` as `role:'user'` with bare-value tool-result blocks) become a dedicated `role:'tool'` message with structured `output:{type:'json'|'text'|'error-text', value}` parts; `null` output preserved as `{type:'json', value:null}` (not dropped); text/tool-call blocks pass through with v6 field names (`toolCallId`/`toolName`/`input`); applied at the `generateText` call (`messages: toModelMessages(opts.messages)`). The converter is the load-bearing fix for the production subagent path, not just skillopt. Pinned by `test/gateway-model-messages.test.ts`. Companion fix in `src/core/skillopt/rollout.ts`: the inline `paramsToSchema` dropped `items` on array params; it now uses the shared `paramDefToSchema` from `src/mcp/tool-defs.ts` (single source of truth, recursive on items/enum/default). Provider-agnostic plumbing: `resolveNativeBaseUrl(provider, cfg)` normalizes a configured `ANTHROPIC_BASE_URL` / `OPENAI_BASE_URL` to carry the `/v1` suffix and is passed explicitly at every native `createAnthropic` / `createOpenAI` site (chat/expansion/embedding), so an env-injected bare host doesn't 404; returns `undefined` when unset so the SDK default is preserved (Google deferred until its native suffix is verified). `diagnoseEmbedding` fails closed with `user_provided_dims_unset` when a user-provided / zero-default recipe (litellm/llama-server) has no configured `embedding_dimensions` — this REPLACED the old `user_provided_model_unset` guard, which was structurally unreachable (parseModelId throws on a bare provider) and only ever false-positived for `litellm:`, silently disabling vector search. `configureGateway` no longer backfills `embedding_dimensions` (readers default it themselves), keeping the "no dims set" signal honest for that guard and the multimodal skip. `withBudgetTracker`: gateway-layer enforcement via `AsyncLocalStorage`. `withBudgetTracker(tracker, fn)` installs the tracker on the module-internal store; every `gateway.chat / embed / rerank` call inside the scope auto-composes (reserve before, record in try/finally). Outside-scope calls are budget no-ops. Nested scopes restore the outer tracker on exit. `getCurrentBudgetTracker()` is the test seam. The chat path uses the pessimistic fallback on error paths; the embed path estimates input tokens from char count × recipe's `chars_per_token` because the AI SDK doesn't surface per-batch embed token usage; the rerank path estimates char count of query+docs. Pinned by 6 unit cases. `reconfigureGatewayWithEngine(engine)` (async, called from `cli.ts` after `engine.connect()`, before every command except `CLI_ONLY` no-DB commands) re-resolves expansion + chat defaults through `resolveModel()` so `models.tier.*` and `models.default` overrides apply to both. `DEFAULT_CHAT_MODEL` is `anthropic:claude-sonnet-4-6`. `__setChatTransportForTests` mirrors `__setEmbedTransportForTests` so tests drive `chat()` with a stubbed transport. `toolLoop` per-turn permit hook (#4194/CDX-7): optional `acquireTurnPermit()` acquires a provider permit before EVERY round-trip and releases in finally; a lease-full throw propagates without consuming the turn (the subagent path wires it to the rate leases with provider-derived keys — Anthropic models share `anthropic:messages`, others get `:chat`). `ToolLoopStopReason` includes `'length'` (#4088): a zero-tool-call turn that hit the output cap propagates 'length' instead of folding into 'end', so truncation is never reported as a clean finish. Per-part provider state (#4201): `ChatBlock` variants carry optional `providerMetadata` captured from SDK parts in `chat()` and re-emitted as `providerOptions` on the rebuilt parts in `toModelMessages()` (attached only when present — metadata-free blocks stay byte-identical); this is the Gemini 3.x thoughtSignature echo. `isThinkingByDefaultModel(modelStr)` (exported, #4087) matches Claude 5-family ids behind any provider-prefix chain with a letters-only family segment (never `claude-3-5-*`) and drives `defaultMaxOutputTokens`'s 32k thinking headroom; think/index.ts shares it. `expand()` and `generateOcrText()` also record on the ambient tracker (#4121 — they call generateObject/generateText directly and never pass through `chat()`'s `_recordBudget`, so their spend was previously invisible to every cap and ledger): record-only, no reserve — a breach surfaces on the NEXT reserving call, matching `chat()`'s swallow of `BudgetExhausted` from `record()`. Successes record normalized SDK usage via `normalizeSdkUsage` (the ONE home for the v6/legacy usage shapes, used by chat's success path too; first FINITE field wins so a NaN v6 field can't shadow a real legacy value or poison the running total); failures record pessimistically under `gateway.expand.failed` / `gateway.ocr.failed` (a rejected attempt still billed provider tokens — one expand() can legitimately produce two records when the structured-output attempt fails and the text fallback runs). A recipe whose declared structured-output support is rejected at call time is remembered for the process lifetime (`_structuredOutputRejectedRecipes`) so the rejected attempt isn't re-paid on every call. OCR's input estimate is prompt text + a fixed per-image token constant, never base64 length (bytes are not tokens). `generateOcrText()` routes to `getImageOcrModel()` — `embedding_image_ocr_model` when set, else the expansion model — gated by `isAvailable('expansion', )` so a misconfigured OCR model (provider without an expansion touchpoint, or unkeyed) fails closed to `''` instead of silently OCRing with the expansion model (#4107); the accessor mirrors `getMultimodalModel()`, `configureGateway`/`buildGatewayConfig` thread the field, and an unconfigured gateway stays a silent `''` no-op. Pinned by `test/ai/ocr-model-routing.test.ts`. `__setGenerateObjectTransportForTests` mirrors the generateText seam. + `test/core/budget/expand-records-budget.test.ts` + `test/ai/gateway-ocr-budget.test.ts` - `src/core/ai/recipes/zeroentropyai.ts` — ZeroEntropy openai-compatible recipe declaring BOTH `embedding` (`zembed-1`, 7 Matryoshka dims: 2560/1280/640/320/160/80/40) AND `reranker` (`zerank-2` flagship + `zerank-1` + `zerank-1-small`, 5MB payload cap) touchpoints. `implementation: 'openai-compatible'` (pinned by regression in `test/ai/zeroentropy-recipe.test.ts`). `base_url_default: 'https://api.zeroentropy.dev/v1'` already ends with `/v1`, so the `zeroEntropyCompatFetch` URL rewrite `/embeddings → /models/embed` produces `…/v1/models/embed` (NOT `…/v1/v1/…` — pinned by regression). `chars_per_token: 1` + `safety_factor: 0.5` match Voyage's dense-content hedge. Carries `sunset` metadata (`ZEROENTROPY_SUNSET_DATE` + replacement models from `ai/defaults.ts`) that drives init picker/auto-pick exclusion, the gateway's once-per-process warn-on-use, and every `gbrain providers` rendering via the shared `sunsetMarker` in `src/commands/providers.ts` (`list` status cell, ⚠ `explain` rows, and the `env` deprecation block that replaces the signup funnel); the recipe itself is deleted in the September removal release. - `src/core/ai/recipes/llama-server-reranker.ts` — sibling of `llama-server` (the embedding recipe) for llama.cpp in `--reranking` mode. Distinct recipe rather than dual-touchpoint extension because `--reranking` and `--embeddings` are mutually exclusive at server-launch time, so the two backends need independent base URLs (default 8081 here vs 8080 there). Declares `reranker` touchpoint with `models: []` (user-provided id matching the `--alias` the user launched with), `path: '/rerank'` (leaf-only; consumes `RerankerTouchpoint.path` override; gateway concatenates with `base_url_default` which ends in `/v1`, producing `…/v1/rerank`), `default_timeout_ms: 30_000` (consumed by `src/core/search/mode.ts`'s reranker timeout chain — CPU-only first-call warmup headroom; the 5s mode-bundle default would fail-open as `timeout`), `cost_per_1m_tokens_usd: 0` (recognized by `FREE_LOCAL_RERANK_PROVIDERS` in `src/core/budget/budget-tracker.ts` so `--max-cost` callers don't hard-fail on local rerank). Setup hint emphasizes `--alias` because llama-server's `/v1/models` defaults model id to the gguf file path without it. Covers Qwen3-Reranker via llama.cpp AND self-hosted ZE weights via llama.cpp — same recipe, different `--model` at launch. Pinned by `test/ai/recipe-llama-server-reranker.test.ts`. Voyage / Cohere / vLLM rerankers stay out of scope (different wire shapes). Same wave adds: `path?: string` + `default_timeout_ms?: number` on `RerankerTouchpoint` in `src/core/ai/types.ts`; consumed by the URL build at `src/core/ai/gateway.ts:rerank()` and by mode-resolution at `src/core/search/mode.ts:resolveSearchMode` (precedence: per-call > config-key > recipe touchpoint default > mode bundle); `LLAMA_SERVER_RERANKER_BASE_URL` env passthrough in `src/cli.ts:buildGatewayConfig`; `FREE_LOCAL_RERANK_PROVIDERS` set in `src/core/budget/budget-tracker.ts:lookupPricing` (rerank-kind-only zero-pricing for the local provider prefix); doctor-fix at `src/commands/models.ts:probeRerankerConfig` reads `search.reranker.model` via `loadSearchModeConfig` + `resolveSearchMode` (closes file-plane / DB-plane divergence where doctor said "not configured" while live search was actively reranking — the field-plane `getRerankerModel()` read nothing writes); `probeRerankerReachability` reads the recipe's `default_timeout_ms` so CPU-only cold-start doesn't false-fail. - `src/core/ai/recipes/nan.ts` — nan.builders openai-compatible reranker recipe. `POST {base}/v1/rerank` → `results[{index, relevance_score}]`, leaf-only (`base_url_default` ends `/v1`; bare `/rerank` and `/compatible-api/v1/reranks` both 404). Model id is the literal `rerank` (a Qwen3-Reranker-8B deployment). `auth_env.required: ['NAN_API_KEY']`. @@ -352,6 +352,7 @@ v0.46: the `sync` handler forwards `job.data.github_item` ({repo, number, kind}) - `src/core/skillopt/` + `src/commands/skillopt.ts` + `skills/skill-optimizer/` — self-evolving skill optimization grounded in the SkillOpt paper (arXiv 2605.23904). `gbrain skillopt ` 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:', 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//`); 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//.jsonl`, `--held-out ` 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 --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 F11 held-out gate is wired: `--held-out ` 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. Budget no-pricing fix: 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 otherwise threw `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). 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` (3 cases), held-out ENFORCE + one-shot-rewrite unit cases, and e2e (F11 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 ` (defensible, cite-heavy, 4 close × 6 far, judge threshold 4.0/5, save by default) and `gbrain lsd ` (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>`; `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) — closes the PGLite CLI search/query/get-hang class where the IIFE raced disconnect and PGLite's WASM kept 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 ` 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) — closes the silent-false-success class where `--save` printed "Saved" unconditionally even 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` (string `buildBrainstormFrontmatter` untouched). 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//`) unless that path is another source's own working tree (#2018 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 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 (#4204). `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 (`.tmp..`) + `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). 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', error? }` so the caller decides messaging + exit codes. `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 -- `, never sweeps unrelated edits; the hook then background-pushes) so write-through content reaches git instead of accumulating uncommitted forever (#2426); result carries `committed?: boolean`. Unhardened repos keep write-only behavior. 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//`) unless that path is another source's own working tree (#2018 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 (#774: 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 (#4204). `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 (`.tmp..`) + `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` (#4247: 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', error? }` so the caller decides messaging + exit codes. `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 -- `, never sweeps unrelated edits; the hook then background-pushes) so write-through content reaches git instead of accumulating uncommitted forever (#2426); result carries `committed?: boolean`. Unhardened repos keep write-only behavior. 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`. - `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/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 `: 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). - `src/core/transcripts/` (directory) — the cathedral-4 transcript-adapter seam. `types.ts`: the `TranscriptAdapter` contract — `parse(path): AsyncGenerator` (one FILE may hold many sessions; the generator RETURN value carries bytes/skipped-lines/zero-session diagnostics so an empty file explains itself), format-specific byte caps (JSONL 50MB hard cap — the 10MB default in `claude-code-jsonl.ts` belongs to the hook-lane tail reader, not imports; monolithic export JSON rejects-not-truncates at 200MB), and the ONE `buildTranscriptSlug` helper (per-provider dirs matching the conversation-archive layout; id suffixes are sha256 prefixes of the session id — hash12 in slugs, hash16 for the dedup identity — never a cleaned prefix of the source id, which let same-prefix session ids collide). `detect.ts`: adapter registry + head-sample detection (explicit format wins; symlinks lstat-rejected) + injectable `harnessRoots` (the confined discovery surface). Adapters, each with a DATED `SPEC_TARGET` + scrubbed fixture + `bytes>0 && sessions==0` drift alarm: `claude-code.ts` (thin wrapper over the shipped `claude-code-jsonl.ts`, which gained the ADDITIVE full-file `parseClaudeSessionFile` with real per-message timestamps — hook-lane `parseTranscript` output is regression-pinned byte-identical), `codex.ts` (turn selection is STRUCTURAL: user turns from `event_msg` user_message, assistant from `response_item` output_text; role user/developer response_items are injected preambles and never leak), `openclaw.ts` (session header + message lines; `.checkpoint.*.jsonl` snapshots rejected), `hermes.ts` (COPY-THEN-READ of state.db + wal/shm sidecars — readonly WAL opens need -shm write access and lock against a live writer; schema from the installed hermes-agent source; PROVISIONAL), `chatgpt-export.ts` (the `mapping`-tree current_node walk; branches dropped by design, orphaned parents terminate quietly, latest-leaf fallback; extracted conversations.json only) + `claude-export.ts` (flat chat_messages); both export adapters load through the shared `export-json.ts` (monolithic JSON over the cap REJECTS with a split hint; a zip or wrong-shape file gets the unzip-first hint) and give id-less conversations content-derived fallback ids so two id-less exports cannot dedup-skip or overwrite each other. `render.ts`: session → part pages — imessage-slack line format with the regex IMPORTED from `conversation-parser/builtins.ts` (round-trip pinned), REAL timestamps (missing ones carry forward; zero-timestamp sessions refused — provenance is never fabricated), anchor-shaped BODY lines backslash-escaped (hostile message content cannot forge speakers), fail-closed redaction (secret-scan + `harvest-private-patterns.txt` user patterns, slack-channel default excluded because it eats issue refs; imperatives COUNTED into hash-covered `transcript_import` frontmatter, never content_flag), ~300KB message-boundary splitting with 2-message overlap (under the embed-skip threshold), part 1 keeps the base slug, `frontmatter.id` unique per part. `ingest.ts`: the engine-facing core — SESSION atomicity (failed sessions skip; integrity failures abort the run), stale-part reconciliation (deletes `part > of` leftovers), session metadata banked in the base page's raw_data as the REDACTED copy and healed by content-compare even on hash-skipped re-runs (a run that died before `putRawData`, or a private pattern added after first import, repairs on the next pass), `cleanScan`/`maxSessionTs` for the watermark. `ingest-facts.ts`: ONE `runExtractConversationFactsCore` invocation (batch `slugs` selector) inside ONE `withBudgetTracker`, `isFactsExtractionEnabled` pre-checked. Pinned by `test/transcript-adapters.test.ts`, `test/transcript-render.test.ts`, `test/e2e/transcripts-ingest-pglite.test.ts`, `test/e2e/transcripts-writeback-fidelity.test.ts` (raw files through the adapters into the gold-extractor facts path — the BrainBench bypass closer). diff --git a/docs/architecture/brains-and-sources.md b/docs/architecture/brains-and-sources.md index f94a4789..a9b4deaa 100644 --- a/docs/architecture/brains-and-sources.md +++ b/docs/architecture/brains-and-sources.md @@ -266,6 +266,40 @@ write ops are local-only in v1. Retrieval-side union — `get_links` / by the `entity_identity.union` config key (default off) and never widens a federated caller's source grant. +## What confines remote callers (and what does not) + +When a brain is served to remote agents (HTTP MCP, stdio MCP treated as +remote), these are the enforcement surfaces — everything on this list is +fail-closed and tested: + +- **Source isolation** — every read resolves through the source-scope ladder + (federated grant array > scalar source floor > nothing). A caller without a + grant for a source cannot read its pages, chunks, or edges. +- **Facts visibility** — facts carry `private`/`world` visibility; remote + callers see `world` only. +- **Takes holders** — per-token allow-lists (`gbrain auth permissions + set-takes-holders ...`) scope which held takes a remote caller sees. +- **Write-side slug fences** — a client bound to slug prefixes can only write + under them, and only a small fenced allow-list of write operations + (`put_page`, `add_link`, `add_timeline_entry`, …) is available to + slug-bound clients; every other non-read operation is refused (fail-closed: + a write op added later is denied until it is fenced and allow-listed). + +One known soft edge: the backlink-count ranking boost counts referrers +without source filtering, so the *existence* of out-of-grant referrers can +nudge result ordering (a count-only signal — no slug or content crosses the +boundary; direct edge reads are fully scoped). Scoping that counter is a +filed follow-up. + +**Not an enforcement surface: page-level `visibility:` frontmatter.** A +`visibility: local` (or any other value) key in a page's frontmatter is inert +metadata — no schema column stores it, no query filters on it, and a remote +caller with a source grant retrieves the page like any other. If a page must +not be readable by remote callers, put it in a source those callers have no +grant for; that is the supported boundary. (A read-side per-page/per-prefix +ACL was proposed and declined — it is a new authorization surface that +belongs to the mounts/brains access-policy design, not a bolt-on filter.) + ## Further reading - [`topologies.md`](./topologies.md) — where the DB lives (operator recipes diff --git a/openclaw.plugin.json b/openclaw.plugin.json index 2cab27be..4b3ef35d 100644 --- a/openclaw.plugin.json +++ b/openclaw.plugin.json @@ -1,7 +1,7 @@ { "id": "gbrain-context-engine", "name": "gbrain", - "version": "0.46.34.0", + "version": "0.46.35.0", "description": "Personal knowledge brain with Postgres + pgvector hybrid search", "family": "bundle-plugin", "configSchema": { diff --git a/package.json b/package.json index 9fd33bf1..94053c66 100644 --- a/package.json +++ b/package.json @@ -171,7 +171,7 @@ "bun": ">=1.3.10" }, "license": "MIT", - "version": "0.46.34.0", + "version": "0.46.35.0", "overrides": { "@hono/node-server": "^2.0.5", "fast-uri": "^3.1.5", diff --git a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json index 99d53a22..4a3aa13b 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.46.34.0", + "version": "0.46.35.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 c49fea7a..dbb3b4d7 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.46.34.0", + "version": "0.46.35.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 58a75c7c..7c36036b 100644 --- a/plugin-variants/gbrain-coding/README.md +++ b/plugin-variants/gbrain-coding/README.md @@ -1,4 +1,4 @@ - + # 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 2fce3338..4b008f3b 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.46.34.0", + "version": "0.46.35.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 b4861411..470c9752 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.46.34.0", + "version": "0.46.35.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 1edfbf03..5fbcced4 100644 --- a/plugin-variants/gbrain-daily/README.md +++ b/plugin-variants/gbrain-daily/README.md @@ -1,4 +1,4 @@ - + # 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 4516083a..a8124146 100644 --- a/plugin/README.md +++ b/plugin/README.md @@ -1,4 +1,4 @@ - + # 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/e2e-test-map.ts b/scripts/e2e-test-map.ts index 5a07e58a..a75074ea 100644 --- a/scripts/e2e-test-map.ts +++ b/scripts/e2e-test-map.ts @@ -101,6 +101,8 @@ export const E2E_TEST_MAP: Record = { "test/e2e/schema-drift.test.ts", // #3391: includeNullSignature stale predicates (engine parity). "test/e2e/migrate-embeddings-postgres.test.ts", + // #4109: FOR KEY SHARE deletion-race behavior of addLink/addTimelineEntry. + "test/e2e/source-boundary-mutation-postgres.test.ts", ], // PGLite bootstrap path + parity guard. "src/core/pglite-engine.ts": [ @@ -117,6 +119,7 @@ export const E2E_TEST_MAP: Record = { "test/e2e/engine-parity.test.ts", "test/e2e/schema-drift.test.ts", "test/e2e/migrate-embeddings-postgres.test.ts", + "test/e2e/source-boundary-mutation-postgres.test.ts", ], "src/core/pglite-engine/**": [ "test/e2e/postgres-bootstrap.test.ts", diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv index 8147be28..14390b2a 100644 --- a/scripts/module-size-limits.tsv +++ b/scripts/module-size-limits.tsv @@ -3,38 +3,38 @@ # 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/commands/doctor.ts 4585 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 -src/core/operations.ts 316 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge) -src/core/postgres-engine.ts 5625 ratchet lowered wave-g: #4477 bootstrap peel to src/core/postgres-engine/ modules (ratchet holds the win); +2 on wave-g-prs merge true-up; wave-k: +2 semantic takes retrieval (#3776), +5 NUL-sanitize shared chunk_text local (#3998), +11 getAllConfig bulk read (#3980) -src/core/pglite-engine.ts 6110 ratchet 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) -src/core/migrate.ts 687 region-exempt append-only MIGRATIONS array grows freely; runner logic is ratcheted — grown v0.46.26.0: repair-handler hooks (#3957 pages-upsert-arbiter); wave-k v142 takes-embedding resize is in-region (renumbered from v141; master consumed v141 for #4482) -src/commands/sync.ts 5693 ratchet 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) -src/core/ai/gateway.ts 4568 ratchet 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) -src/cli.ts 3954 ratchet 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) -src/core/cycle.ts 3186 ratchet grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k) -src/commands/serve-http.ts 3319 ratchet grown v0.46.25.0 D2: /mcp per-request teardown (#2844); grown wave-g (#4474): resolve-IPC socket under --http via shared helper -src/commands/jobs.ts 3127 ratchet grown v0.46.26.0 megawave (#4098 #2308) + master v0.46.26.0 worker startup recovery + stats gating; +typed provider-failure logging on the facts-absorb catch (#4308); +chat-connectors wiring (master merge) -src/core/search/hybrid.ts 2969 ratchet grown v0.46.26.0 megawave: CRAG escalation seam, degradation visibility, excludePrivate knobs-fold v23 (#1663 #3873 #4352); grown #4356: semantic-cache-hit slice honors resolved mode searchLimit (double-resolution caveat); grown #4414: offset!==0 cache-skip widening + knobs-hash v24; grown #4487: chunkless rows join the cosine blend (no raw-score head start); grown wave-g (#4480 #4415): shared salience/recency resolution + pattern-aware cache keying; grown db-availability loop: all-lexical-arms-dead access-error rethrow (a dead DB must never return an empty success) — refined to both-arms-FAILED (a succeeded-but-empty arm proves the DB is alive) -src/core/engine.ts 2527 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) +src/cli.ts 3957 ratchet 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) src/commands/autopilot.ts 2648 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 -src/commands/extract.ts 2385 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 -src/commands/extract-conversation-facts.ts 2098 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) -src/core/import-file.ts 2181 ratchet 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 -src/core/cycle/synthesize.ts 2818 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 -src/commands/embed.ts 1901 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 +src/commands/doctor.ts 4585 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) +src/commands/embed.ts 1949 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 +src/commands/extract-conversation-facts.ts 2099 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) +src/commands/extract.ts 2458 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 +src/commands/jobs.ts 3127 ratchet grown v0.46.26.0 megawave (#4098 #2308) + master v0.46.26.0 worker startup recovery + stats gating; +typed provider-failure logging on the facts-absorb catch (#4308); +chat-connectors wiring (master merge) +src/commands/serve-http.ts 3334 ratchet 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) +src/commands/sync.ts 5694 ratchet 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) +src/core/ai/gateway.ts 4618 ratchet 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) +src/core/cycle.ts 3193 ratchet grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading +src/core/cycle/synthesize.ts 2873 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 +src/core/engine.ts 2550 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) +src/core/import-file.ts 2189 ratchet 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 +src/core/migrate.ts 687 region-exempt append-only MIGRATIONS array grows freely; runner logic is ratcheted — grown v0.46.26.0: repair-handler hooks (#3957 pages-upsert-arbiter); wave-k v142 takes-embedding resize is in-region (renumbered from v141; master consumed v141 for #4482) +src/core/operations.ts 316 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge) +src/core/pglite-engine.ts 6157 ratchet 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) +src/core/postgres-engine.ts 5652 ratchet lowered wave-g: #4477 bootstrap peel to src/core/postgres-engine/ modules (ratchet holds the win); +2 on wave-g-prs merge true-up; wave-k: +2 semantic takes retrieval (#3776), +5 NUL-sanitize shared chunk_text local (#3998), +11 getAllConfig bulk read (#3980); +13: #4109 atomic FOR KEY SHARE link/timeline mutation + typed per-endpoint miss; +2: getBacklinkCounts page-id keying comment (#4380); +12: dream-verdict TTL expiry predicate + sweep (#4069) +src/core/search/hybrid.ts 2971 ratchet grown v0.46.26.0 megawave: CRAG escalation seam, degradation visibility, excludePrivate knobs-fold v23 (#1663 #3873 #4352); grown #4356: semantic-cache-hit slice honors resolved mode searchLimit (double-resolution caveat); grown #4414: offset!==0 cache-skip widening + knobs-hash v24; grown #4487: chunkless rows join the cosine blend (no raw-score head start); grown wave-g (#4480 #4415): shared salience/recency resolution + pattern-aware cache keying; grown db-availability loop: all-lexical-arms-dead access-error rethrow (a dead DB must never return an empty success) — refined to both-arms-FAILED (a succeeded-but-empty arm proves the DB is alive); grown v0.46.26.0 megawave: CRAG escalation seam, degradation visibility, excludePrivate knobs-fold v23 (#1663 #3873 #4352); grown #4356: semantic-cache-hit slice honors resolved mode searchLimit (double-resolution caveat); grown #4414: offset!==0 cache-skip widening + knobs-hash v24; grown #4487: chunkless rows join the cosine blend (no raw-score head start); grown wave-g (#4480 #4415): shared salience/recency resolution + pattern-aware cache keying; +2: backlink-boost counts page-id keying doc (#4380) src/core/types.ts 1955 ratchet grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867) src/core/minions/queue.ts 2442 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease -src/commands/init.ts 2002 ratchet grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up +src/commands/init.ts 2026 ratchet grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close) src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900) src/core/minions/handlers/subagent.ts 1834 ratchet merged: master v131 settle rework + dream-wave C5 peel + C6 accounting + C7 lease heartbeats/lost-lease aborts + C9 oneshot dispatch + adversarial fix batches; grown by #4078 subagent-loop capability fix; +6 lines (reasoning-item replay: adaptContentBlocksToChatBlocks handles 'reasoning' blocks); +3 wave G #4514: Anthropic-via-OpenRouter allowed on the subagent loop src/commands/bootstrap.ts 2015 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness); +5 for the harnessDetect test seam (bulk lives in core/bootstrap/harness.ts) src/core/minions/worker.ts 1560 ratchet grandfathered at merge (grew past the 1500 cap on master, #4170); grown v0.46.11.0 five-issue wave src/commands/sources.ts 1790 ratchet grown v0.46.22.0 phone wave: github source kind (#4104) -src/core/link-extraction.ts 1681 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737) +src/core/link-extraction.ts 1718 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder src/core/embedding-migration.ts 1545 ratchet new row: crossed 1500 in v0.46.25.0 fix waves (#4305 #4306 chunk-model truth helpers) 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 1667 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) src/core/chunkers/code.ts 1575 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 -src/core/config.ts 1574 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; grown db-availability fix cycle: envShadowDetected single-home (#427 predicate); +chat-connectors wiring (master merge); +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +master-merge true-up; +8 backup.check_enabled/check_interval_days file-plane keys (monthly backup check) +src/core/config.ts 1600 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) src/core/bootstrap/harness.ts 1951 ratchet +4 at megawave/wave-k merge src/core/oauth-provider.ts 1552 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard) diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsv index 246a8708..8dbc95f3 100644 --- a/scripts/structural-suites.tsv +++ b/scripts/structural-suites.tsv @@ -68,6 +68,7 @@ test/connection-resilience.test.ts Eng-review D3 — executeRaw has no per-call test/contextual-retrieval-service-pure.test.ts inline import contextual synopsis containment 1 readFileSync test/conversation-facts-type-allowlist-drift.test.ts (file-level) 18 readFileSync test/cycle-abort.test.ts #1972 — complete cooperative-abort coverage 3 readFileSync +test/cycle-abort.test.ts #4077 — synthesize/patterns cooperative-abort threading 3 readFileSync test/cycle-abort.test.ts CycleOpts.signal contract (v0.20.5) 4 readFileSync test/cycle-abort.test.ts autopilot-cycle handler contract (v0.20.5) 3 readFileSync test/cycle-drain-renewal.test.ts db-lock heartbeat wiring (structural — issue #6 cancellation) 1 readFileSync @@ -136,6 +137,10 @@ test/extract-workers.test.ts extract.ts → workers wiring (T7) 10 readFileSync test/facts-backstop-remedy-verb.test.ts facts backstop thin-client-fallback remedy verb (#4489) 3 readFileSync test/features.test.ts CLI routing 2 bun-file test/fence-extraction.test.ts Layer 8 D2 — markdown fence extraction 18 readFileSync +test/files.test.ts collectFiles (production import) 9 readFileSync +test/files.test.ts files upload-raw git-storage branch (#2297) 3 readFileSync +test/files.test.ts files verify git lane (per-source root resolution) 1 readFileSync +test/files.test.ts storage precondition — the silent-no-op class (#4022) 3 readFileSync test/filing-rules-resolution.serial.test.ts per-source filing-rules resolution 3 readFileSync test/fix-wave-structural.test.ts #2084 — cli.ts owns process-exit teardown via finishCliTeardown 4 readFileSync test/fix-wave-structural.test.ts #2955 — sync multi-source repoPath routes through msysToNativePath 1 readFileSync @@ -220,6 +225,7 @@ test/scripts/run-verify-parallel.test.ts guard registration ⇒ execution covera test/scripts/test-shard.slow.test.ts test-shard.sh — LPT balance contract 5 readFileSync test/serve-http-github-webhook.test.ts handler wiring (source pin) 1 readFileSync test/serve-http-mcp-transport-cleanup.test.ts POST /mcp transport cleanup (#2844) 2 readFileSync +test/serve-http-metrics.test.ts serve-http.ts wiring (structural — the two defects of the original PR) 2 readFileSync test/serve-stdin-eof-drain.test.ts serve-sync-runner stays off the boot path (#4409) 1 readFileSync test/skillify-scaffold.test.ts 11-item scaffold contract (T9 + Phase 3 cross-modal eval) 1 readFileSync test/skillify-scaffold.test.ts applyScaffold 3 readFileSync diff --git a/skills/migrations/v0.46.35.0.md b/skills/migrations/v0.46.35.0.md new file mode 100644 index 00000000..6848cc94 --- /dev/null +++ b/skills/migrations/v0.46.35.0.md @@ -0,0 +1,13 @@ +# v0.46.34.0 + +## `gbrain config get` redacts secrets by default (#3943) + +Before: `gbrain config get anthropic_api_key` printed the raw value while +`config show` and `config set` redacted. After: `get` redacts like its +siblings. Automation that needs the plain value passes `--raw` (either +argument position): + + gbrain config get anthropic_api_key --raw + +Scripts that parsed the raw value from `config get` output MUST add `--raw`. +Everything else is unchanged. diff --git a/skills/skills.lock.json b/skills/skills.lock.json index a24b2fc1..229d013e 100644 --- a/skills/skills.lock.json +++ b/skills/skills.lock.json @@ -131,6 +131,7 @@ "migrations/v0.40.5.md": "b9837d52a030517698dfb31c439f562cde60a1015ae488dab09be2c16ff182e5", "migrations/v0.41.11.0.md": "5c6873ab969d14def4a450d792f070f1259d08b3aca43bc7825d0a9114b2b36b", "migrations/v0.46.3.0.md": "0438f52f423b8f99832d0098fde94188af38eff603a956c67014e5e9bb8572f6", + "migrations/v0.46.35.0.md": "4f492de8a7d4902010794e4f24b57e48116c6d746387a978edac6013387cd642", "migrations/v0.5.0.md": "5e0dabc451595295c4d971e19bcb33c258a127223d25859d8321cb7e1ce60711", "migrations/v0.7.0.md": "97c2740445a10b1c5c7123c17dbd625fa27a94095b85d27c2b278da756c4c59a", "migrations/v0.8.0.md": "1919ff8b8f3680612ff888e7cfcc0d86ece5d5304ae19af4497bdf40b050561a", diff --git a/src/cli.ts b/src/cli.ts index 8e30b5fd..93307d37 100755 --- a/src/cli.ts +++ b/src/cli.ts @@ -2345,7 +2345,10 @@ async function handleCliOnly(command: string, args: string[]) { // teardown are a pre-existing class, tracked as a TODOS.md follow-up. let eng: BrainEngine | null = null; try { - eng = await connectEngine(); + // #4364: --no-migrate keeps doctor observational — probeOnly skips + // connectEngine's auto-migrate block so a clean/behind DB is reported + // on as-is instead of being migrated before the health checks run. + eng = await connectEngine({ probeOnly: args.includes('--no-migrate') }); await runDoctor(eng, args); } catch (e) { // DB unavailable OR the DB-backed run threw — still run filesystem @@ -3649,9 +3652,9 @@ async function connectEngine(opts?: { probeOnly?: boolean }): Promise Set minion_mode without prompting. --host-dir Include this directory in host-file walk (default scope: \$HOME/.claude + \$HOME/.openclaw). @@ -171,8 +177,29 @@ function buildPlan(idx: CompletedIndex, installed: string, filterVersion?: strin return plan; } -function printList(plan: Plan, installed: string): void { - console.log(`Installed gbrain version: ${installed}\n`); +/** + * #4364: pre-flight DB probe outcome. Surfaced on --list/--dry-run so an + * unreachable database is distinguishable from a clean one — both used to + * print the identical all-pending plan at exit 0. + */ +type DbProbeOutcome = + | { status: 'connected'; schemaVer: number; latest: number } + | { status: 'unreachable'; reason: string } + | { status: 'skipped'; reason: string }; + +function formatDbProbeLine(probe: DbProbeOutcome): string { + if (probe.status === 'connected') { + return `Database: connected, schema v${probe.schemaVer} (latest ${probe.latest})`; + } + if (probe.status === 'unreachable') { + return `Database: UNREACHABLE (${probe.reason})`; + } + return `Database: not probed (${probe.reason})`; +} + +function printList(plan: Plan, installed: string, dbProbe: DbProbeOutcome): void { + console.log(`Installed gbrain version: ${installed}`); + console.log(`${formatDbProbeLine(dbProbe)}\n`); console.log(' Status Version Headline'); console.log(' ------- -------- -----------------------------------------'); const rows: Array<{ status: string; m: Migration }> = [ @@ -197,8 +224,9 @@ function printList(plan: Plan, installed: string): void { } } -function printDryRun(plan: Plan, installed: string): void { +function printDryRun(plan: Plan, installed: string, dbProbe: DbProbeOutcome): void { console.log(`Dry run — installed gbrain version: ${installed}`); + console.log(formatDbProbeLine(dbProbe)); console.log(''); if (plan.applied.length) { console.log('Already applied:'); @@ -364,6 +392,7 @@ export async function runApplyMigrations(args: string[]): Promise { // --yes/--non-interactive we apply them here; otherwise we warn and make // sure the run does NOT report "All migrations up to date" with exit 0. let schemaBehind = false; + let dbProbe: DbProbeOutcome = { status: 'skipped', reason: 'no probe attempted' }; try { const { LATEST_VERSION } = await import('../core/migrate.ts'); const { loadConfig: lc, toEngineConfig } = await import('../core/config.ts'); @@ -378,11 +407,14 @@ export async function runApplyMigrations(args: string[]): Promise { // schema lifecycle internally on PGLite (phase A routes in-process), // so the warning here adds no information for PGLite users. const skipPreflight = cfg.engine === 'pglite'; - if (!skipPreflight) { + if (skipPreflight) { + dbProbe = { status: 'skipped', reason: 'pglite manages schema in-process' }; + } else { const eng = await createEngine(toEngineConfig(cfg)); await eng.connect(toEngineConfig(cfg)); const verStr = await eng.getConfig('version'); const schemaVer = parseInt(verStr || '1', 10); + dbProbe = { status: 'connected', schemaVer, latest: LATEST_VERSION }; const { runMigrations } = await import('../core/migrate.ts'); schemaBehind = await resolveSchemaBehind({ schemaVer, @@ -395,9 +427,17 @@ export async function runApplyMigrations(args: string[]): Promise { await eng.disconnect(); } } - } catch { - // Non-fatal: if DB is unreachable, orchestrator migrations can still - // run their filesystem-only phases. + } catch (err) { + // Non-fatal by default: if DB is unreachable, orchestrator migrations can + // still run their filesystem-only phases. #4364: keep the (redacted) + // reason so --list/--dry-run say UNREACHABLE and --require-db fails hard — + // connect errors are exactly what users paste into issues and CI logs. + const { redactUrlsInText } = await import('../core/url-redact.ts'); + const { redactConnectionInfo } = await import('../core/audit/redact-connection-info.ts'); + dbProbe = { + status: 'unreachable', + reason: redactConnectionInfo(redactUrlsInText(err instanceof Error ? err.message : String(err))), + }; } const completed = loadCompletedMigrations(); @@ -422,8 +462,16 @@ export async function runApplyMigrations(args: string[]): Promise { process.exit(2); } - if (cli.list) { printList(plan, installed); process.exit(0); } - if (cli.dryRun) { printDryRun(plan, installed); process.exit(0); } + // #4364: --require-db turns an unreachable DB into a hard failure instead + // of a filesystem-only plan that renders identically to a clean database. + const listExit = cli.requireDb && dbProbe.status === 'unreachable' ? 1 : 0; + if (cli.list) { printList(plan, installed, dbProbe); process.exit(listExit); } + if (cli.dryRun) { printDryRun(plan, installed, dbProbe); process.exit(listExit); } + if (cli.requireDb && dbProbe.status === 'unreachable') { + console.error(formatDbProbeLine(dbProbe)); + console.error('--require-db: database is unreachable; aborting before orchestrators run.'); + process.exit(1); + } const toRun: Migration[] = [...plan.partial, ...plan.pending]; if (toRun.length === 0) { @@ -526,4 +574,5 @@ export const __testing = { indexCompleted, statusForVersion, resolveSchemaBehind, + formatDbProbeLine, }; diff --git a/src/commands/capture.ts b/src/commands/capture.ts index 785db345..d3bb021d 100644 --- a/src/commands/capture.ts +++ b/src/commands/capture.ts @@ -44,6 +44,7 @@ import { resolveSourceWithTier } from '../core/source-resolver.ts'; import { defaultSlug, detectBinaryNullByte, + detectBinarySignature, normalizeForHash, deriveTitle, mergeCaptureFrontmatter, @@ -285,6 +286,23 @@ export async function runCapture(engine: BrainEngine | null, args: string[]): Pr process.exit(1); } + // #4022 magic-byte guard runs FIRST: it names the actual format, and it + // catches the containers the NUL scan structurally cannot (an ASCII-armored + // PDF has no NUL in its head, so pre-fix it was decoded to mojibake and + // stored as a page body with its real text silently dropped). + const binaryFormat = detectBinarySignature(rawBuffer!); + if (binaryFormat !== null) { + console.error( + `gbrain capture: refusing to capture ${binaryFormat} content from ${inputLabel}\n` + + ` Detected by magic bytes. Storing it would write UTF-8 replacement characters as the\n` + + ` page body — for container formats the real text is compressed, so it would be lost\n` + + ` entirely while the command reported success.\n` + + ` Extract the text first, then capture that. For a PDF:\n` + + ` pdftotext ${inputLabel === 'stdin' ? 'input.pdf' : inputLabel} - | gbrain capture --stdin --slug `, + ); + process.exit(1); + } + // CV10 binary guard. Scans the first 8KB for NUL bytes; rejects with a // friendly message before UTF-8 decode mangles arbitrary bytes. const nullByteOffset = detectBinaryNullByte(rawBuffer!); @@ -486,6 +504,7 @@ export const __testing = { deriveTitle, parseArgs, detectBinaryNullByte, + detectBinarySignature, normalizeForHash, maybeRewriteSourceFkError, }; diff --git a/src/commands/config.ts b/src/commands/config.ts index dc819e84..2a1f1560 100644 --- a/src/commands/config.ts +++ b/src/commands/config.ts @@ -57,6 +57,8 @@ export const FILE_PLANE_API_KEYS: readonly string[] = [ 'openrouter_api_key', 'voyage_api_key', 'dashscope_api_key', + 'litellm_api_key', + 'together_api_key', 'google_api_key', 'azure_openai_api_key', // #4031: mergedProviderEnv reads the file plane only ]; @@ -246,8 +248,12 @@ export async function runConfig(engine: BrainEngine, args: string[]) { return; } - const key = args[1]; - const value = args[2]; + // #3943: `--raw` (get's redaction opt-out) may appear before the key, so + // strip it from the positional scan rather than reading args[1] blindly. + const rawFlag = args.includes('--raw'); + const positionals = args.filter((a) => a !== '--raw'); + const key = positionals[1]; + const value = positionals[2]; if (action === 'get' && key) { // #2120: `get` used to read only the DB plane, so a runtime-effective key @@ -267,7 +273,10 @@ export async function runConfig(engine: BrainEngine, args: string[]) { const dbVal = await engine.getConfig(key); const val = fileVal !== undefined && fileVal !== null ? fileVal : dbVal; if (val !== null && val !== undefined) { - console.log(typeof val === 'string' ? val : JSON.stringify(val)); + // #3943: redact by default like `show`/`set` — `get` output lands in + // agent transcripts and shell history; scripts opt out with the flag. + const out = typeof val === 'string' ? val : JSON.stringify(val); + console.log(rawFlag ? out : redactConfigValue(key, out)); if (fileVal !== undefined && fileVal !== null) { const shadow = dbVal !== null && dbVal !== undefined ? ' — a DB-plane value also exists and is shadowed at runtime' diff --git a/src/commands/doctor.ts b/src/commands/doctor.ts index 4e0d4d8c..a978ae65 100644 --- a/src/commands/doctor.ts +++ b/src/commands/doctor.ts @@ -1200,12 +1200,12 @@ export async function buildChecks( } // 3b-tris. Stub-guard fire count (last 24h). The v0.34.5 stub guard in - // fence-write.ts refuses to spawn unprefixed entity pages (e.g. bare - // `alice.md` at brain root). Each fire is appended to - // ~/.gbrain/audit/stub-guard-YYYY-Www.jsonl. This check is the operator - // visibility surface for the guard's v0.36 sunset criterion: when the - // 24h count is consistently low, the prefix-expansion in - // resolveEntitySlug is doing its job and the guard can be removed. + // fence-write.ts refuses to spawn unprefixed entity pages (bare `alice.md` + // at brain root); the #4108 arm refuses pages for fallback-resolved slugs + // no live page backs. Fires append per-arm `reason` lines to + // ~/.gbrain/audit/stub-guard-YYYY-Www.jsonl (pre-#4108 lines lack one and + // count as unprefixed). The v0.36 sunset criterion covers 'unprefixed' + // ONLY; the fallback_resolution arm never sunsets. // // WARN at >10 fires/24h — at that rate the resolver is probably missing // a case (typo prefix, alias, non-Latin script). Operators should grep @@ -1214,20 +1214,20 @@ export async function buildChecks( try { const { readRecentStubGuardEvents } = await import('../core/facts/stub-guard-audit.ts'); const events = readRecentStubGuardEvents({ sinceMs: 24 * 60 * 60 * 1000 }); + const fallbackCount = events.filter((e) => e.reason === 'fallback_resolution').length; + const reasonSplit = `unprefixed=${events.length - fallbackCount}, fallback_resolution=${fallbackCount}`; if (events.length > 10) { // Surface the top 3 slugs that hit it so operators have somewhere to start. const slugCounts = new Map(); for (const e of events) slugCounts.set(e.slug, (slugCounts.get(e.slug) ?? 0) + 1); const topSlugs = [...slugCounts.entries()] - .sort((a, b) => b[1] - a[1]) - .slice(0, 3) - .map(([slug, n]) => `${slug}(${n})`) - .join(', '); + .sort((a, b) => b[1] - a[1]).slice(0, 3) + .map(([slug, n]) => `${slug}(${n})`).join(', '); checks.push({ name: 'stub_guard_24h', status: 'warn', message: - `Stub guard fired ${events.length}x in last 24h (top: ${topSlugs}). ` + + `Stub guard fired ${events.length}x in last 24h (${reasonSplit}; top: ${topSlugs}). ` + `If this stays elevated, the prefix-expansion in resolveEntitySlug is ` + `missing a case. Check ~/.gbrain/audit/stub-guard-*.jsonl for the slugs ` + `that hit it.`, @@ -1236,7 +1236,7 @@ export async function buildChecks( checks.push({ name: 'stub_guard_24h', status: 'ok', - message: `Stub guard fired ${events.length}x in last 24h (below WARN threshold of 10).`, + message: `Stub guard fired ${events.length}x in last 24h (${reasonSplit}; below WARN threshold of 10).`, }); } // Zero hits is the goal — emit no check at all so the doctor output stays clean. diff --git a/src/commands/doctor/checks/calibration.ts b/src/commands/doctor/checks/calibration.ts index 3b20d5c5..116f1451 100644 --- a/src/commands/doctor/checks/calibration.ts +++ b/src/commands/doctor/checks/calibration.ts @@ -319,13 +319,19 @@ export async function checkLinkResolutionOpportunity( export async function checkAbandonedThreads(engine: BrainEngine): Promise { try { const rows = await engine.executeRaw<{ count: number }>( + // since_date is TEXT and may be month-precision ('YYYY-MM'); 'YYYY-MM'::date + // throws "invalid input syntax for type date", so normalize to the 1st + // before casting — same guarded cast as the detail query in serve-http.ts + // (`gbrain calibration` abandoned-threads), which must stay in lockstep so + // the doctor count matches the listing it points users at. `SELECT COUNT(*)::int AS count FROM takes WHERE active = true AND resolved_at IS NULL AND superseded_by IS NULL AND weight >= 0.7 AND since_date IS NOT NULL - AND since_date::date < (now() - INTERVAL '12 months')`, + AND (since_date || CASE WHEN length(since_date) = 7 THEN '-01' ELSE '' END)::date + < (now() - INTERVAL '12 months')`, ); const count = rows[0]?.count ?? 0; if (count === 0) { diff --git a/src/commands/embed.ts b/src/commands/embed.ts index 2b796ea2..15e243a9 100644 --- a/src/commands/embed.ts +++ b/src/commands/embed.ts @@ -73,6 +73,42 @@ function recordFailure(result: EmbedResult, chunkCount: number, slug: string, e: } } +/** + * #3622: failure quarantine for the --stale path. A page whose embed makes + * NO progress keeps all its NULL chunks, so every stale pass re-sends the + * identical request — a page that fails deterministically (e.g. always + * outlives a local server's timeout) is retried forever, and against a + * serial embedding server (ollama `-np 1`) the abandoned work compounds + * into congestion collapse. After GBRAIN_EMBED_QUARANTINE_AFTER consecutive + * zero-progress attempts (default 3) a page is skipped for the rest of this + * process; an attempt that embeds ANY chunk resets its counter (#3037 + * partial progress shrinks the stale set, so the next pass sends a smaller + * request, not the identical doomed one). Process-lifetime by design: a + * long-lived autopilot stops re-sending doomed pages every cycle, while a + * restart (or frontmatter.embed_skip for a permanent block) lets the + * operator retry deliberately. Keyed `${source_id}::${slug}` to match the + * stale-batch grouping. + */ +const _embedFailureCounts = new Map(); + +/** Test seam: clear quarantine state between test runs. */ +export function _resetEmbedQuarantineForTest(): void { + _embedFailureCounts.clear(); +} + +function embedQuarantineThreshold(): number { + const raw = parseInt(process.env.GBRAIN_EMBED_QUARANTINE_AFTER || '3', 10); + return Number.isFinite(raw) && raw > 0 ? raw : 3; +} + +/** #3622: count a zero-progress attempt; announce the page's quarantine once. */ +function noteEmbedQuarantineFailure(key: string, slug: string): void { + const failures = (_embedFailureCounts.get(key) ?? 0) + 1; + _embedFailureCounts.set(key, failures); + if (failures === embedQuarantineThreshold()) { + serr(`\n [embed] ${slug}: ${failures} consecutive failed attempt(s) — quarantined for the rest of this process`); + } +} export interface EmbedOpts { /** Embed ALL pages (every chunk). */ all?: boolean; @@ -1691,7 +1727,15 @@ async function embedAllStale( else byKey.set(key, [row]); } - const keys = Array.from(byKey.keys()); + // #3622: keep quarantined pages out of the pool. The keyset cursor + // still advances past their rows, so a fully-quarantined batch can + // never spin the loop. + const QUARANTINE_AFTER = embedQuarantineThreshold(); + const allKeys = Array.from(byKey.keys()); + const keys = allKeys.filter(k => (_embedFailureCounts.get(k) ?? 0) < QUARANTINE_AFTER); + if (keys.length < allKeys.length) { + serr(`\n [embed] skipping ${allKeys.length - keys.length} page(s) quarantined after ${QUARANTINE_AFTER} consecutive failed embed attempts (this process); set frontmatter.embed_skip to skip permanently, or restart to retry`); + } result.total_chunks += batch.length; async function embedOneKey(key: string) { @@ -1757,12 +1801,16 @@ async function embedAllStale( recordFailure(result, failed, slug, firstError); serr(`\n ${slug}: ${failed} chunk(s) failed to embed; embedded the other ${stale.length - failed}`); } + // #3622: reaching here means at least one chunk persisted (a total + // embed failure throws) — progress, so the quarantine counter resets. + _embedFailureCounts.delete(key); } catch (e: unknown) { // Budget/abort-fired cancellations are expected on the way out; don't // spam per-page "Error embedding" lines when we're shutting down. if (effectiveSignal.aborted) return; recordFailure(result, stale.length, slug, e); serr(`\n Error embedding ${slug}: ${e instanceof Error ? e.message : e}`); + noteEmbedQuarantineFailure(key, slug); } totalProcessedPages++; result.pages_processed++; diff --git a/src/commands/eval-suspected-contradictions.ts b/src/commands/eval-suspected-contradictions.ts index 02bdf784..abe19cf8 100644 --- a/src/commands/eval-suspected-contradictions.ts +++ b/src/commands/eval-suspected-contradictions.ts @@ -30,7 +30,7 @@ import { readFileSync } from 'node:fs'; import type { BrainEngine } from '../core/engine.ts'; -import { resolveModel } from '../core/model-config.ts'; +import { resolveModel, resolveTierDefault } from '../core/model-config.ts'; import { PreFlightBudgetError, runContradictionProbe, @@ -323,15 +323,16 @@ async function runRun(engine: BrainEngine, f: ParsedFlags): Promise { } // v0.34 / Lane C: route the judge model through resolveModel so the user's - // models.eval.contradictions_judge config key + Haiku-tier default + global - // models.default override + env var all compose correctly. The --judge CLI - // flag still wins as the highest-precedence override. + // models.eval.contradictions_judge config key + key-aware utility-tier + // default + global models.default override + env var all compose correctly. + // The --judge CLI flag still wins as the highest-precedence override. const judgeModel = await resolveModel(engine, { cliFlag: f.judge, configKey: 'models.eval.contradictions_judge', tier: 'utility', envVar: 'GBRAIN_CONTRADICTIONS_JUDGE_MODEL', - fallback: 'anthropic:claude-haiku-4-5', + // #3813: last-resort fallback stays key-aware, never hardcoded Anthropic. + fallback: resolveTierDefault('utility'), }); // #1784: annotate the budget when it's the silent non-TTY default ($1) so the diff --git a/src/commands/extract-conversation-facts.ts b/src/commands/extract-conversation-facts.ts index f7929ff0..d6a6d6ed 100644 --- a/src/commands/extract-conversation-facts.ts +++ b/src/commands/extract-conversation-facts.ts @@ -401,7 +401,7 @@ import { } from '../core/conversation-parser/parse.ts'; import { readConversationBodyForParsing } from '../core/conversation-parser/body.ts'; import { runLlmFallback } from '../core/conversation-parser/llm-fallback.ts'; -import { resolveModel } from '../core/model-config.ts'; +import { resolveModel, resolveTierDefault } from '../core/model-config.ts'; /** * v0.41.13.0 — back-compat shape for direct callers + the existing @@ -1352,7 +1352,8 @@ export async function runExtractConversationFactsCore( const llmFallbackModel = llmFallbackEnabled ? await resolveModel(engine, { tier: 'utility', - fallback: 'anthropic:claude-haiku-4-5-20251001', + // #3813: last-resort fallback stays key-aware, never hardcoded Anthropic. + fallback: resolveTierDefault('utility'), }) : null; diff --git a/src/commands/extract.ts b/src/commands/extract.ts index 9523d2d9..1013a993 100644 --- a/src/commands/extract.ts +++ b/src/commands/extract.ts @@ -46,7 +46,7 @@ import type { PageType } from '../core/types.ts'; import { parseMarkdown } from '../core/markdown.ts'; import { extractPageLinks, parseTimelineEntries, deriveTimelineAnchor, inferLinkType, makeResolver, - extractFrontmatterLinks, isGlobalBasenameEnabled, LINK_EXTRACTOR_VERSION_TS, + extractFrontmatterLinks, isGlobalBasenameEnabled, isCrossSourceLinksEnabled, LINK_EXTRACTOR_VERSION_TS, WIKILINK_BASENAME_LINK_TYPE, buildBasenameIndex, queryBasenameIndex, stripCodeBlocks, normalizeBasename, parseInlineCitationTimelineEntries, @@ -79,6 +79,7 @@ import { createHash } from 'crypto'; import { runSlidingPool } from '../core/worker-pool.ts'; import { isAborted } from '../core/abort-check.ts'; import { parseWorkers, resolveWorkersWithClamp } from '../core/sync-concurrency.ts'; +import { loadAllSources } from '../core/sources-load.ts'; // Batch size for addLinksBatch / addTimelineEntriesBatch. // Postgres bind-parameter limit is 65535. Links use 4 cols/row → 16K hard ceiling; @@ -198,7 +199,7 @@ function refsWithSnapshotStamps( * then picks from_source_id / to_source_id: prefer the origin page's source, * fall back to 'default', else skip (never push a wrong-source edge). Shared * by extractLinksFromDB and extractStaleFromDB so the F10 multi-source - * resolution can't drift. + * resolution and the source-isolation policy can't drift. * * v0.46.28.0 (#2589): the failure case now carries a `reason` instead of a * bare `null`. A target that resolves via `global_basename` to a page that @@ -208,6 +209,19 @@ function refsWithSnapshotStamps( * exist". This stays default-deny by design: cross-source edges remain * unwritten (source isolation — see CLAUDE.md), but callers can now * attribute the drop correctly instead of reporting a wrong reason. + * + * #3478: only a federated origin source may fall back to 'default'; when + * `allowCrossSource` is false both endpoints must live in the page's own + * source, else skip with reason 'cross_source' (never push a wrong-source + * edge). + * + * #3908: `opts.crossSource` (the `link_resolution.cross_source` config flag) + * is the explicit operator opt-in — it supersedes the ambient federation + * gate, which only exists to stop DEFAULT-ON silent cross-source regrowth. + * With it on, a cross-source-only candidate resolves with the + * lexicographically smallest matching source (deterministic, so repeated + * extracts and both engines converge on the same edge under the + * (source_id, slug) composite key) instead of dropping with 'cross_source'. */ export type CandidateSourceResolution = | { ok: true; fromSlug: string; fromSourceId: string; toSourceId: string } @@ -219,19 +233,44 @@ export function resolveCandidateSources( pageSourceId: string, allSlugs: Set, slugToSources: Map, + allowCrossSource: boolean, + opts: { crossSource?: boolean } = {}, ): CandidateSourceResolution { const fromSlug = c.fromSlug ?? pageSlug; if (!allSlugs.has(c.targetSlug)) return { ok: false, reason: 'missing_target' }; if (!allSlugs.has(fromSlug)) return { ok: false, reason: 'missing_from' }; const fromSources = slugToSources.get(fromSlug) ?? []; + const targetSources = slugToSources.get(c.targetSlug) ?? []; + if (!allowCrossSource && !opts.crossSource) { + if (!fromSources.includes(pageSourceId) || !targetSources.includes(pageSourceId)) { + // #3478 isolation × #2589 counting: both endpoints exist but not in + // the origin's own source — a counted cross-source drop, never an edge. + return { ok: false, reason: 'cross_source' }; + } + return { ok: true, fromSlug, fromSourceId: pageSourceId, toSourceId: pageSourceId }; + } const fromSourceId = fromSources.includes(pageSourceId) ? pageSourceId : (fromSources.includes('default') ? 'default' : fromSources[0]); - const targetSources = slugToSources.get(c.targetSlug) ?? []; let toSourceId: string; if (targetSources.includes(fromSourceId)) { toSourceId = fromSourceId; } else if (targetSources.includes('default')) { toSourceId = 'default'; + } else if (targetSources.length > 0) { + // #2589: the target exists ONLY in other sources. Historically this was + // a silent null (indistinguishable from a missing endpoint — multi-source + // graphs went sparse with dead_links stuck at 0). Behind the opt-in + // `link_resolution.cross_source` flag the edge is allowed with a + // DETERMINISTIC pick (lexicographically smallest source, so repeated + // extracts and both engines converge on the same edge under the + // (source_id, slug) composite key); off, callers get the distinguishable + // 'cross_source' reason to COUNT the drop instead of burying it. + if (!opts.crossSource) return { ok: false, reason: 'cross_source' }; + // Allocation-free deterministic min (bulk loops call this per candidate; + // in the motivating federated topology most candidates hit this branch). + let min = targetSources[0]; + for (const s of targetSources) if (s < min) min = s; + toSourceId = min; } else { return { ok: false, reason: 'cross_source' }; } @@ -274,6 +313,9 @@ interface ExtractResult { links_created: number; timeline_entries_created: number; pages_processed: number; + /** #2589: drop counters, present on the DB links path only (additive). */ + skipped_missing_target?: number; + skipped_cross_source?: number; } // --- Shared walker --- @@ -1119,6 +1161,10 @@ export async function runExtract(engine: BrainEngine, args: string[]) { const r = await extractLinksFromDB(engine, dryRun, jsonMode, typeFilter, since, { includeFrontmatter, sourceIdFilter, stampWatermark: subcommand === 'all' }); result.links_created = r.created; result.pages_processed = r.pages; + // #2589: "counted, never silent" reaches the --json summary too — + // additive fields, only present on the DB links path. + result.skipped_missing_target = r.skippedMissingTarget; + result.skipped_cross_source = r.skippedCrossSource; } if (subcommand === 'timeline' || subcommand === 'all') { const r = await extractTimelineFromDB(engine, dryRun, jsonMode, typeFilter, since, { sourceIdFilter, inferDates }); @@ -1582,7 +1628,7 @@ async function extractLinksFromDB( typeFilter: PageType | undefined, since: string | undefined, opts?: { includeFrontmatter?: boolean; sourceIdFilter?: string; stampWatermark?: boolean }, -): Promise<{ created: number; pages: number; unresolved: UnresolvedFrontmatterRef[] }> { +): Promise<{ created: number; pages: number; unresolved: UnresolvedFrontmatterRef[]; skippedMissingTarget: number; skippedCrossSource: number }> { const includeFrontmatter = opts?.includeFrontmatter ?? false; const sourceIdFilter = opts?.sourceIdFilter; // C3 (D6): the links_extracted_at watermark covers links AND timeline, so a @@ -1610,6 +1656,9 @@ async function extractLinksFromDB( // verbs (link_types[].inference) + frontmatter_links apply during // extraction instead of being silently ignored. Null = legacy inference. const pack = (await loadActivePackForLocalEngine(engine))?.manifest ?? null; + // Issue #2589: opt-in cross-source edges (deterministic to_source_id pick); + // off, cross-source-only candidates are counted, never silently dropped. + const crossSource = await isCrossSourceLinksEnabled(engine); // v0.32.8: listAllPageRefs enumerates (slug, source_id) so we can thread // sourceId to getPage AND build a cross-source resolution map for link // disambiguation. Pre-fix used getAllSlugs() which collapsed @@ -1648,12 +1697,19 @@ async function extractLinksFromDB( // The resolver maps above are built from the UNFILTERED refs — link // targets outside the window must still resolve. const walkRefs = filterRefsSince(allRefs, since); + // #3478: the 'default' fallback in resolveCandidateSources is a federation + // feature — an isolated source must not regrow cross-source edges on every + // sweep. Sources absent from the table (or archived) fail closed to isolated. + const federatedSourceIds = new Set( + (await loadAllSources(engine, { federatedOnly: true })).map(source => source.id), + ); let processed = 0, created = 0; // #2576: skipped-candidate counter — see extractStaleFromDB's twin. let skippedMissingTarget = 0; // #2589: target resolved (via global_basename) to a page that exists only // in a source other than the origin's or 'default' — default-deny by - // design (source isolation), but distinct from a genuinely missing target. + // design (source isolation) unless the #3908 flag is on, but distinct + // from a genuinely missing target. let skippedCrossSource = 0; // v0.42.7 (#1696): pages whose links we extracted this run — stamped after // the loop so a manual `gbrain extract links|all --source db` clears the @@ -1705,8 +1761,11 @@ async function extractLinksFromDB( // helper in v0.42.7 (#1696) so extract --stale reuses the exact same // endpoint-validation + from/to source-id picking. #2589: the reason // is now distinguished (missing endpoint vs. target only in a - // non-origin/non-default source) so the two don't get counted as one. - const resolved = resolveCandidateSources(c, slug, source_id, allSlugs, slugToSources); + // non-origin/non-default source) so the two don't get counted as one; + // the #3908 crossSource flag resolves the edge instead of dropping it. + const resolved = resolveCandidateSources( + c, slug, source_id, allSlugs, slugToSources, federatedSourceIds.has(source_id), { crossSource }, + ); if (!resolved.ok) { if (resolved.reason === 'cross_source') skippedCrossSource++; else skippedMissingTarget++; @@ -1772,7 +1831,7 @@ async function extractLinksFromDB( console.log(`Skipped ${skippedMissingTarget} candidate(s) whose target page doesn't exist (references to non-pages are never persisted).`); } if (skippedCrossSource > 0) { - console.log(`Skipped ${skippedCrossSource} candidate(s) whose target page exists only in another source (cross-source edges are not written — see docs/architecture/brains-and-sources.md).`); + console.log(`Skipped ${skippedCrossSource} cross-source candidate(s) — target exists only in another source. Enable with \`gbrain config set link_resolution.cross_source true\` — see docs/architecture/brains-and-sources.md (#2589).`); } if (includeFrontmatter && unresolved.length > 0) { // Top-20 preview of unresolvable frontmatter names so the user can @@ -1789,7 +1848,10 @@ async function extractLinksFromDB( } } } - return { created, pages: processed, unresolved }; + // #2589: the counters ride the return value so machine consumers (and the + // --json path, which has no summary event on this path) can see the drops — + // "counted, never silent" must hold beyond human-mode console lines. + return { created, pages: processed, unresolved, skippedMissingTarget, skippedCrossSource }; } async function extractTimelineFromDB( @@ -1964,6 +2026,8 @@ export async function extractStaleFromDB( const globalBasename = await isGlobalBasenameEnabled(engine); // #3190: pack-aware verbs + frontmatter_links (see extractLinksFromDB). const pack = (await loadActivePackForLocalEngine(engine))?.manifest ?? null; + // Issue #2589: mirrors extractLinksFromDB (see resolveCandidateSources). + const crossSource = await isCrossSourceLinksEnabled(engine); const allRefs = await engine.listAllPageRefs(); const allSlugs = new Set(); const slugToSources = new Map(); @@ -1973,6 +2037,11 @@ export async function extractStaleFromDB( list.push(ref.source_id); slugToSources.set(ref.slug, list); } + // #3478: mirrors extractLinksFromDB — only federated sources keep the + // cross-source 'default' fallback; absent/archived rows fail closed. + const federatedSourceIds = new Set( + (await loadAllSources(engine, { federatedOnly: true })).map(source => source.id), + ); const progress = createProgress(cliOptsToProgressOptions(getCliOptions())); progress.start('extract.stale', totalStale); @@ -1987,7 +2056,8 @@ export async function extractStaleFromDB( let skippedMissingTarget = 0; // #2589: target resolved (via global_basename) to a page that exists only // in a source other than the origin's or 'default' — default-deny by - // design (source isolation), but distinct from a genuinely missing target. + // design (source isolation) unless the #3908 flag is on, but distinct + // from a genuinely missing target. let skippedCrossSource = 0; for (;;) { @@ -2007,7 +2077,10 @@ export async function extractStaleFromDB( { skipFrontmatter: !includeFrontmatter, globalBasename, pack }, ); for (const c of extracted.candidates) { - const r = resolveCandidateSources(c, page.slug, page.source_id, allSlugs, slugToSources); + const r = resolveCandidateSources( + c, page.slug, page.source_id, allSlugs, slugToSources, + federatedSourceIds.has(page.source_id), { crossSource }, + ); if (!r.ok) { if (r.reason === 'cross_source') skippedCrossSource++; else skippedMissingTarget++; @@ -2081,7 +2154,7 @@ export async function extractStaleFromDB( console.log(`Skipped ${skippedMissingTarget} candidate(s) whose target page doesn't exist (references to non-pages are never persisted).`); } if (skippedCrossSource > 0) { - console.log(`Skipped ${skippedCrossSource} candidate(s) whose target page exists only in another source (cross-source edges are not written — see docs/architecture/brains-and-sources.md).`); + console.log(`Skipped ${skippedCrossSource} cross-source candidate(s) — target exists only in another source. Enable with \`gbrain config set link_resolution.cross_source true\`, then run \`gbrain extract links --source db\` — a --stale re-run will NOT revisit these pages (their extraction watermark is already stamped) — see docs/architecture/brains-and-sources.md (#2589).`); } if (budgetHit && staleRemaining > 0) { console.log(`Time budget reached — ${staleRemaining} page(s) still stale. Re-run 'gbrain extract --stale' (or pass --catch-up) to continue.`); diff --git a/src/commands/files.ts b/src/commands/files.ts index 930e1165..64a02445 100644 --- a/src/commands/files.ts +++ b/src/commands/files.ts @@ -2,6 +2,7 @@ import { readFileSync, readdirSync, statSync, lstatSync, existsSync, writeFileSy import { join, relative, extname, basename, dirname, resolve } from 'path'; import { createHash } from 'crypto'; import type { BrainEngine } from '../core/engine.ts'; +import type { StorageBackend, StorageConfig } from '../core/storage.ts'; import { sqlQueryForEngine, executeRawJsonb } from '../core/sql-query.ts'; import { humanSize } from '../core/file-resolver.ts'; import { createProgress } from '../core/progress.ts'; @@ -52,6 +53,44 @@ export function formatFileSizeKb(rawSizeBytes: number | bigint | string | null): : '?'; } +/** + * The message every storage-dependent `files` subcommand prints when there is + * no backend. Exported so tests assert the contract without spawning a CLI. + */ +export function noStorageBackendMessage(op: string): string { + return ( + `gbrain files ${op}: no storage backend configured — refusing to continue.\n` + + ` The files table records metadata only (there is no blob column), so without a\n` + + ` backend the bytes go nowhere while the DB claims they are stored.\n` + + ` Fix: configure storage (see gbrain init storage settings), or keep the binary\n` + + ` outside the brain and capture its extracted text instead.` + ); +} + +/** + * Single precondition for every storage-dependent `files` subcommand (#4022). + * + * Class fix (see `noStorageBackendMessage`): `upload`, `sync`, and `redirect` + * each tested storage permissively (`if (config?.storage)`) and then carried on + * when the answer was "no" — inserting rows, printing "uploaded", and in + * `redirect` unlinking local originals whose bytes had never left the machine. + * Storage-dependent work must refuse up front rather than half-succeed, so this + * exits BEFORE any DB write or local mutation. + */ +async function requireStorageBackend( + op: string, +): Promise<{ storage: StorageBackend; storageConfig: StorageConfig }> { + const { loadConfig } = await import('../core/config.ts'); + const config = loadConfig(); + if (!config?.storage) { + console.error(noStorageBackendMessage(op)); + process.exit(1); + } + const { createStorage } = await import('../core/storage.ts'); + const storageConfig = config.storage as StorageConfig; + return { storage: await createStorage(storageConfig), storageConfig }; +} + export async function runFiles(engine: BrainEngine, args: string[]) { const subcommand = args[0]; @@ -140,6 +179,11 @@ async function uploadFile(engine: BrainEngine, args: string[]) { process.exit(1); } + // Precondition first: a backend-less upload can only produce a phantom row + // (metadata for bytes that were never stored), so refuse before touching the + // DB or reporting anything as uploaded. + const { storage } = await requireStorageBackend('upload'); + const stat = statSync(filePath); const hash = fileHash(filePath); const filename = basename(filePath); @@ -148,20 +192,6 @@ async function uploadFile(engine: BrainEngine, args: string[]) { const sql = sqlQueryForEngine(engine); - // #4302 (fail-closed honesty, mirror of the file_upload op): a files row - // must never claim bytes that were stored nowhere. No storage backend → - // refuse before any insert instead of recording a phantom upload. - const { loadConfig } = await import('../core/config.ts'); - const config = loadConfig(); - if (!config?.storage) { - console.error('No storage backend configured — `files upload` would record a row with no stored bytes.'); - console.error('Configure `storage` in your gbrain config (supabase | s3 | local),'); - console.error('or use `gbrain files upload-raw --page ` for git-tracked small files.'); - process.exit(1); - } - const { createStorage } = await import('../core/storage.ts'); - const storage = await createStorage(config.storage as any); - // Check for existing file by hash — but only trust the row when the // BACKEND really holds the object (#4302); vanished bytes must re-upload. const existing = await sql`SELECT id FROM files WHERE content_hash = ${hash} AND storage_path = ${storagePath}`; @@ -175,14 +205,19 @@ async function uploadFile(engine: BrainEngine, args: string[]) { console.log(`Uploading ${humanSize(stat.size)} via ${method}...`); await storage.upload(storagePath, content, mimeType || undefined); - await sql` - INSERT INTO files (page_slug, filename, storage_path, mime_type, size_bytes, content_hash, metadata) - VALUES (${pageSlug}, ${filename}, ${storagePath}, ${mimeType}, ${stat.size}, ${hash}, ${'{}'}::jsonb) - ON CONFLICT (storage_path) DO UPDATE SET - content_hash = EXCLUDED.content_hash, - size_bytes = EXCLUDED.size_bytes, - mime_type = EXCLUDED.mime_type - `; + // files.metadata is JSONB — bind a real object via executeRawJsonb instead + // of casting a string into ::jsonb (the #2339 double-encode class). + await executeRawJsonb( + engine, + `INSERT INTO files (page_slug, filename, storage_path, mime_type, size_bytes, content_hash, metadata) + VALUES ($1, $2, $3, $4, $5, $6, $7::jsonb) + ON CONFLICT (storage_path) DO UPDATE SET + content_hash = EXCLUDED.content_hash, + size_bytes = EXCLUDED.size_bytes, + mime_type = EXCLUDED.mime_type`, + [pageSlug, filename, storagePath, mimeType, stat.size, hash], + [{}], + ); console.log(`Uploaded: ${storagePath} (${humanSize(stat.size)})`); } @@ -372,6 +407,11 @@ async function syncFiles(engine: BrainEngine, dir?: string) { process.exit(1); } + // Pre-fix this command inserted a `files` row per file and reported them as + // "uploaded" without ever calling the storage backend — every row it produced + // was a phantom, even on a brain WITH storage configured. + const { storage } = await requireStorageBackend('sync'); + const files = collectFiles(dir); console.log(`Found ${files.length} files to sync`); @@ -404,14 +444,22 @@ async function syncFiles(engine: BrainEngine, dir?: string) { const pathParts = relativePath.split('/'); const pageSlug = pathParts.length > 1 ? pathParts.slice(0, -1).join('/') : null; - await sql` - INSERT INTO files (page_slug, filename, storage_path, mime_type, size_bytes, content_hash, metadata) - VALUES (${pageSlug}, ${filename}, ${storagePath}, ${mimeType}, ${stat.size}, ${hash}, ${'{}'}::jsonb) - ON CONFLICT (storage_path) DO UPDATE SET - content_hash = EXCLUDED.content_hash, - size_bytes = EXCLUDED.size_bytes, - mime_type = EXCLUDED.mime_type - `; + // Actually put the bytes in storage before recording them as stored. + await storage.upload(storagePath, readFileSync(filePath), mimeType || undefined); + + // files.metadata is JSONB — bind a real object via executeRawJsonb instead + // of casting a string into ::jsonb (the #2339 double-encode class). + await executeRawJsonb( + engine, + `INSERT INTO files (page_slug, filename, storage_path, mime_type, size_bytes, content_hash, metadata) + VALUES ($1, $2, $3, $4, $5, $6, $7::jsonb) + ON CONFLICT (storage_path) DO UPDATE SET + content_hash = EXCLUDED.content_hash, + size_bytes = EXCLUDED.size_bytes, + mime_type = EXCLUDED.mime_type`, + [pageSlug, filename, storagePath, mimeType, stat.size, hash], + [{}], + ); uploaded++; } @@ -430,9 +478,21 @@ async function verifyFiles(engine: BrainEngine) { return; } + // Pre-fix this loop asked only "does the ROW carry a hash and a path" — true + // for any row an INSERT produced — and then printed a hardcoded + // "0 mismatches, 0 missing". `missing` was declared and never incremented. + // So the one command whose job is catching un-stored files reported phantom + // rows as "verified". The check that matters is byte existence at + // storage_path, which requires the backend (#4022) — except git-lane rows + // (#4302), which verify against the brain repo on disk. let verified = 0; let mismatches = 0; let missing = 0; + // #4022: cloud rows with no configured (or constructible) backend are + // UNVERIFIABLE, never "verified" — almost certainly phantoms left by a + // backend-less upload/sync. Counted per row so a git-lane-only brain + // still passes without a backend. + let unverifiable = 0; // #4302: verify against the actual bytes, not just DB row shape. Cloud rows // are probed via storage.exists (+ hash-checked via download for small @@ -510,18 +570,24 @@ async function verifyFiles(engine: BrainEngine) { } verified++; } else { - // No backend configured: DB-shape check only (legacy behavior), but say so. - verified++; + // #4022: no backend — byte existence cannot be checked; report, never vouch. + unverifiable++; + console.error(` UNVERIFIABLE: ${row.storage_path} (no storage backend configured)`); } } - if (!storage) { - console.error('Note: no storage backend configured — backend existence/hash checks skipped.'); + if (unverifiable > 0) { + console.error( + `gbrain files verify: ${unverifiable} cloud file row(s) recorded, but no storage backend is configured.\n` + + ` Byte existence cannot be checked and these rows cannot be retrieved, so they are\n` + + ` reported as UNVERIFIABLE rather than "verified" — almost certainly phantoms left by\n` + + ` a backend-less upload/sync. Configure storage, or delete the rows.`, + ); } - if (mismatches === 0 && missing === 0) { - console.log(`${verified} files verified, 0 mismatches, 0 missing`); - } else { - console.error(`VERIFY FAILED: ${mismatches} mismatches, ${missing} missing.`); + // Always report the real counts — never a hardcoded pair. + console.log(`${verified} files verified, ${mismatches} mismatches, ${missing} missing, ${unverifiable} unverifiable`); + if (mismatches > 0 || missing > 0 || unverifiable > 0) { + console.error(`VERIFY FAILED: ${mismatches} mismatches, ${missing} missing, ${unverifiable} unverifiable.`); console.error(`Run: gbrain files sync --retry-failed`); process.exit(1); } @@ -536,13 +602,8 @@ async function mirrorFiles(args: string[]) { const dryRun = args.includes('--dry-run'); if (!dir || !existsSync(dir)) { console.error('Usage: gbrain files mirror [--dry-run]'); process.exit(1); } - const { createStorage } = await import('../core/storage.ts'); - const { loadConfig } = await import('../core/config.ts'); const { stringify } = await import('../core/yaml-lite.ts'); - const config = loadConfig(); - if (!config?.storage) { console.error('No storage backend configured. Run gbrain init with storage settings.'); process.exit(1); } - - const storage = await createStorage(config.storage as any); + const { storage, storageConfig } = await requireStorageBackend('mirror'); const files = collectFiles(dir); console.log(`Found ${files.length} files to mirror`); @@ -564,7 +625,7 @@ async function mirrorFiles(args: string[]) { // Write .supabase marker const marker = stringify({ synced_at: new Date().toISOString(), - bucket: (config.storage as { bucket?: string })?.bucket || 'brain-files', + bucket: storageConfig?.bucket || 'brain-files', prefix: basename(dir) + '/', file_count: uploaded, }); @@ -607,14 +668,16 @@ async function redirectFiles(args: string[]) { return; } - // Verify remote files exist before deleting locals - const { loadConfig } = await import('../core/config.ts'); - const config = loadConfig(); - let storage: any = null; - if (config?.storage) { - const { createStorage } = await import('../core/storage.ts'); - storage = await createStorage(config.storage as any); - } + // Verify remote files exist before deleting locals. + // + // This is the destructive path: it unlinks the local original and leaves a + // `supabase://` pointer behind. Pre-fix, `storage` was only built when a + // backend happened to be configured (`if (config?.storage)`) and the + // existence check was correspondingly conditional (`if (storage)`) — so with + // no backend the guard was skipped entirely and the loop deleted originals + // while writing pointers to bytes that had never been uploaded. Data loss, + // not a phantom row. The backend is now mandatory here. + const { storage } = await requireStorageBackend('redirect'); let redirected = 0; let skippedMissing = 0; @@ -622,14 +685,13 @@ async function redirectFiles(args: string[]) { const relPath = relative(dir, filePath); const hash = fileHash(filePath); - // Verify remote exists before deleting local - if (storage) { - const remoteExists = await storage.exists(relPath); - if (!remoteExists) { - console.error(` Skipping ${relPath}: not found in remote storage (would lose data)`); - skippedMissing++; - continue; - } + // Unconditional: never unlink a local original we have not confirmed + // exists remotely. + const remoteExists = await storage.exists(relPath); + if (!remoteExists) { + console.error(` Skipping ${relPath}: not found in remote storage (would lose data)`); + skippedMissing++; + continue; } const stat = statSync(filePath); diff --git a/src/commands/init.ts b/src/commands/init.ts index 6b5a7077..6c37ea5d 100644 --- a/src/commands/init.ts +++ b/src/commands/init.ts @@ -129,8 +129,28 @@ export async function runInit(args: string[]) { }); } + // #3753: a --force re-init with NO explicit engine choice preserves the + // configured engine — the D5 persisted-config-wins rule extended to the + // engine field. Pre-fix, the PGLite default branch below swallowed a + // postgres config: following the deferred-setup hint verbatim + // (`gbrain init --force --embedding-model ...`) silently rewrote + // config.json to engine=pglite, orphaning the postgres data behind a + // config that no longer pointed at it. Switching engines stays available + // by saying so (--pglite / --supabase / --url). loadConfigFileOnly, NOT + // loadConfig: a transient env DATABASE_URL must not count as a configured + // engine here (CDX2-7); the env plane keeps its existing precedence in + // the non-interactive branch below. + let preservedPostgresUrl: string | null = null; + if (isForce && !isPGLite && !isSupabase && !manualUrl) { + const fileCfg = loadConfigFileOnly(); + if (fileCfg?.engine === 'postgres' && fileCfg.database_url) { + preservedPostgresUrl = fileCfg.database_url; + console.error('[init] Existing postgres engine preserved (pass --pglite to switch engines).'); + } + } + // Explicit PGLite mode - if (isPGLite || (!isSupabase && !manualUrl && !isNonInteractive)) { + if (!preservedPostgresUrl && (isPGLite || (!isSupabase && !manualUrl && !isNonInteractive))) { // Smart detection: scan for .md files unless --pglite flag forces it if (!isPGLite && !isSupabase) { const fileCount = countMarkdownFiles(process.cwd()); @@ -160,10 +180,14 @@ export async function runInit(args: string[]) { const envUrl = effectiveEnvDatabaseUrl(); if (envUrl) { databaseUrl = envUrl; + } else if (preservedPostgresUrl) { + databaseUrl = preservedPostgresUrl; } else { console.error('--non-interactive requires --url or GBRAIN_DATABASE_URL env var'); process.exit(1); } + } else if (preservedPostgresUrl) { + databaseUrl = preservedPostgresUrl; } else { databaseUrl = await supabaseWizard(); } diff --git a/src/commands/notability-eval.ts b/src/commands/notability-eval.ts index 5a9d052f..063fc073 100644 --- a/src/commands/notability-eval.ts +++ b/src/commands/notability-eval.ts @@ -238,6 +238,7 @@ async function classifyBatch(paragraphs: string[]): Promise { } // Apply: delegate to the hardcoded upgrade path (full swap + post-upgrade). - await runUpgrade([]); + // Pass the fetched target so runUpgrade can detect exact-tag no-op + // "upgrades" instead of reporting false success (#4366). + await runUpgrade([], { + targetVersion: latest && isValidVersionString(latest) ? latest : undefined, + }); } diff --git a/src/commands/serve-http-metrics.ts b/src/commands/serve-http-metrics.ts new file mode 100644 index 00000000..c2ea2885 --- /dev/null +++ b/src/commands/serve-http-metrics.ts @@ -0,0 +1,100 @@ +/** + * Request metrics for `gbrain serve --http` (#3893, reimplemented from + * @y2688's community PR). + * + * In-process counters plus a Prometheus text exposition (format 0.0.4). + * Kept out of serve-http.ts so the module-size ratchet keeps its teeth; the + * runServeHttp closure wires exactly three seams: + * + * - `createMetricsCounters()` once per server, + * - `app.use(metricsTrackingMiddleware(counters))` BEFORE every route — + * Express only applies `app.use` middleware to routes registered after + * it (the original PR mounted the tracker after most routes, so they + * were never counted), + * - `GET /metrics` behind requireAdmin, rendering + * `renderPrometheusMetrics(counters)` — request/error/latency series + * profile a personal brain's usage, so the exposition is not public. + */ +import type { NextFunction, Request, RequestHandler, Response } from 'express'; + +export interface MetricsCounters { + requests: number; + errors: number; + latencySamples: number[]; + /** Epoch ms when the counters were created (server start). */ + startedAt: number; +} + +// Memory bound for a long-lived daemon: once the buffer exceeds MAX, keep +// only the newest KEEP samples (percentiles then cover a recent window). +const MAX_LATENCY_SAMPLES = 10_000; +const KEEP_LATENCY_SAMPLES = 5_000; + +export function createMetricsCounters(now: number = Date.now()): MetricsCounters { + return { requests: 0, errors: 0, latencySamples: [], startedAt: now }; +} + +export function recordCompletedRequest( + counters: MetricsCounters, + statusCode: number, + latencyMs: number, +): void { + if (statusCode >= 400) counters.errors += 1; + counters.latencySamples.push(latencyMs); + if (counters.latencySamples.length > MAX_LATENCY_SAMPLES) { + counters.latencySamples = counters.latencySamples.slice(-KEEP_LATENCY_SAMPLES); + } +} + +export function metricsTrackingMiddleware(counters: MetricsCounters): RequestHandler { + return (req: Request, res: Response, next: NextFunction) => { + // Scrapes are excluded so a tight Prometheus interval doesn't skew the + // request/error ratios it is trying to observe. + if (req.path === '/metrics') { next(); return; } + counters.requests += 1; + const start = Date.now(); + res.on('finish', () => { + recordCompletedRequest(counters, res.statusCode, Date.now() - start); + }); + next(); + }; +} + +export function renderPrometheusMetrics( + counters: MetricsCounters, + now: number = Date.now(), +): string { + const sorted = [...counters.latencySamples].sort((a, b) => a - b); + const p50 = sorted.length > 0 ? sorted[Math.floor(sorted.length * 0.5)] ?? 0 : 0; + const p99 = sorted.length > 0 ? sorted[Math.floor(sorted.length * 0.99)] ?? 0 : 0; + const errorRatio = counters.requests > 0 + ? (counters.errors / counters.requests).toFixed(4) + : '0'; + const uptimeSeconds = ((now - counters.startedAt) / 1000).toFixed(1); + return [ + '# HELP gbrain_requests_total Total HTTP requests served.', + '# TYPE gbrain_requests_total counter', + `gbrain_requests_total ${counters.requests}`, + '', + '# HELP gbrain_errors_total Total HTTP responses with status >= 400.', + '# TYPE gbrain_errors_total counter', + `gbrain_errors_total ${counters.errors}`, + '', + '# HELP gbrain_error_ratio Errors / requests since server start.', + '# TYPE gbrain_error_ratio gauge', + `gbrain_error_ratio ${errorRatio}`, + '', + '# HELP gbrain_latency_ms_p50 Request latency p50 (ms) over the retained window.', + '# TYPE gbrain_latency_ms_p50 gauge', + `gbrain_latency_ms_p50 ${p50}`, + '', + '# HELP gbrain_latency_ms_p99 Request latency p99 (ms) over the retained window.', + '# TYPE gbrain_latency_ms_p99 gauge', + `gbrain_latency_ms_p99 ${p99}`, + '', + '# HELP gbrain_uptime_seconds Seconds since the HTTP server started.', + '# TYPE gbrain_uptime_seconds gauge', + `gbrain_uptime_seconds ${uptimeSeconds}`, + '', + ].join('\n'); +} diff --git a/src/commands/serve-http.ts b/src/commands/serve-http.ts index ca236e39..dc2cb523 100644 --- a/src/commands/serve-http.ts +++ b/src/commands/serve-http.ts @@ -19,6 +19,7 @@ import rateLimit from 'express-rate-limit'; import { randomBytes, createHash, createHmac } from 'crypto'; import { safeHexEqual } from '../core/timing-safe.ts'; import { isValidRepoName } from '../core/github-source.ts'; +import { createMetricsCounters, metricsTrackingMiddleware, renderPrometheusMetrics } from './serve-http-metrics.ts'; import { readFileSync } from 'node:fs'; import { join } from 'node:path'; import { Server } from '@modelcontextprotocol/sdk/server/index.js'; @@ -980,6 +981,14 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOption // --------------------------------------------------------------------------- app.use(cookieParser()); + // #3893 (reimplemented from @y2688): request metrics. Mounted here, BEFORE + // every route — Express only applies `app.use` middleware to routes + // registered after it, and the original PR mounted the tracker after most + // routes, so they were never counted. The /metrics route itself lives + // below requireAdmin's definition. + const metricsCounters = createMetricsCounters(); + app.use(metricsTrackingMiddleware(metricsCounters)); + // --------------------------------------------------------------------------- // CORS (v0.41.3, T7 — default-deny on every OAuth endpoint) // --------------------------------------------------------------------------- @@ -1486,6 +1495,14 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOption next(); } + // #3893 (reimplemented from @y2688): Prometheus exposition. Admin-gated — + // request/error/latency series profile a personal brain's usage, so this + // is not a public surface (the original PR served it unauthenticated). + app.get('/metrics', requireAdmin, (_req: Request, res: Response) => { + res.set('Content-Type', 'text/plain; version=0.0.4'); + res.send(renderPrometheusMetrics(metricsCounters)); + }); + // --------------------------------------------------------------------------- // Admin API endpoints // --------------------------------------------------------------------------- diff --git a/src/commands/sync.ts b/src/commands/sync.ts index 97097285..1535632e 100644 --- a/src/commands/sync.ts +++ b/src/commands/sync.ts @@ -4473,9 +4473,10 @@ See also: // gbrain-sync:default — absent — printed "nothing to break", exit 0, and // left the dead holder's row on gbrain-sync:; the follow-up sync // then refused for the 60s takeover grace. Resolve the SAME source the - // sync would lock. + // sync would lock. Explicit --source keeps the resolver-free path (no + // assertSourceExists) so leftover locks of deleted sources stay breakable. const { resolveSourceWithTier: resolveBreakSource } = await import('../core/source-resolver.ts'); - const sourceId = (await resolveBreakSource(engine, sourceArg || null)).source_id; + const sourceId = sourceArg ?? (await resolveBreakSource(engine, null)).source_id; const lockKey = `gbrain-sync:${sourceId}`; const exit = await runBreakLock(engine, lockKey, sourceId, { force: forceBreakLock, diff --git a/src/commands/takes.ts b/src/commands/takes.ts index b106743f..efea4c8e 100644 --- a/src/commands/takes.ts +++ b/src/commands/takes.ts @@ -708,8 +708,18 @@ async function cmdExtract(engine: BrainEngine, rest: string[]): Promise { process.exit(2); } if (!dryRun && !skipConfirm) { + // Name the model the extraction actually uses (extract-takes-from-pages + // resolves getChatModel()), not a hardcoded "Haiku" — the gateway may be + // unconfigured at this consent gate, so resolve defensively. + let modelLabel = 'the configured chat model'; + try { + const { getChatModel } = await import('../core/ai/gateway.ts'); + modelLabel = getChatModel(); + } catch { + // Gateway unconfigured — keep the generic label. + } process.stderr.write( - `[takes extract] sends concept/atom/lore/briefing/writing/originals page content to Haiku.\n` + + `[takes extract] sends concept/atom/lore/briefing/writing/originals page content to ${modelLabel}.\n` + `Pass --yes to proceed (or --dry-run to preview).\n`, ); process.exit(1); diff --git a/src/commands/upgrade.ts b/src/commands/upgrade.ts index b0fe23ed..b0b49c6d 100644 --- a/src/commands/upgrade.ts +++ b/src/commands/upgrade.ts @@ -1,11 +1,31 @@ import { execSync, execFileSync } from 'child_process'; import { existsSync, readFileSync, writeFileSync, mkdirSync, appendFileSync, realpathSync } from 'fs'; import { basename, join, dirname, resolve } from 'path'; +import { parseSemver, semverGt } from '../core/semver.ts'; +import { setCliExitVerdict } from '../core/cli-force-exit.ts'; import { VERSION } from '../version.ts'; const GBRAIN_GITHUB_REPO = 'garrytan/gbrain'; -export async function runUpgrade(args: string[]) { +/** + * Compare the post-swap resolved version against the caller's target (#4366). + * `bun update` exits 0 without upgrading exact-tag Git installs (the pin + * wins), so exit status alone cannot prove a swap happened. 'unverified' + * (missing/unparseable observed version) keeps legacy fail-open behavior — + * only a confirmed still-older version is a 'mismatch'. + */ +export function assessUpgradeOutcome( + target: string | undefined, + observed: string, +): 'ok' | 'mismatch' | 'unverified' { + if (!target) return 'ok'; + const t = parseSemver(target); + const o = parseSemver(observed.trim()); + if (!t || !o) return 'unverified'; + return semverGt(t, o) ? 'mismatch' : 'ok'; +} + +export async function runUpgrade(args: string[], opts: { targetVersion?: string } = {}) { if (args.includes('--help') || args.includes('-h')) { console.log('Usage: gbrain upgrade [--swap-only]\n\nSelf-update the CLI.\n\nDetects install method (bun, binary, clawhub) and runs the appropriate update.\nAfter upgrading, shows what\'s new and offers to set up new features.\n\n--swap-only Perform ONLY the binary/source swap and skip post-upgrade\n (migrations run on the next launch). Used by the autopilot\n silent self-upgrade channel so the daemon can swap + relaunch\n without a 30-min blocking post-upgrade inside its tick.'); return; @@ -128,6 +148,25 @@ export async function runUpgrade(args: string[]) { if (upgraded) { const newVersion = verifyUpgrade(); + // #4366: a still-older resolved version means the swap never happened + // (exact-tag Git pins make `bun update` a successful no-op). Fail loudly + // and return BEFORE the breadcrumb/cache bookkeeping below, so the + // pending-upgrade marker survives and keeps nagging. + const target = opts.targetVersion; + if (target && assessUpgradeOutcome(target, newVersion) === 'mismatch') { + console.error(`Upgrade did not take effect: still running ${newVersion}, expected ${target}.`); + console.error('Exact-tag Git installs stay pinned through `bun update`. Reinstall with:'); + console.error(` bun add -g github:garrytan/gbrain#v${target}`); + recordUpgradeError({ + phase: 'verify-target', + fromVersion: oldVersion, + toVersion: target, + error: `still running ${newVersion} after upgrade`, + hint: `bun add -g github:garrytan/gbrain#v${target}`, + }); + setCliExitVerdict(1); + return; + } // Save old version for post-upgrade migration detection saveUpgradeState(oldVersion, newVersion); diff --git a/src/core/ai/build-gateway-config.ts b/src/core/ai/build-gateway-config.ts index e2cd4bca..6b99daa8 100644 --- a/src/core/ai/build-gateway-config.ts +++ b/src/core/ai/build-gateway-config.ts @@ -98,6 +98,7 @@ export function buildGatewayConfig(c: GBrainConfig): AIGatewayConfig { embedding_model: c.embedding_model, embedding_dimensions: c.embedding_dimensions, embedding_multimodal_model: c.embedding_multimodal_model, + embedding_image_ocr_model: c.embedding_image_ocr_model, expansion_model: c.expansion_model, chat_model: c.chat_model, chat_fallback_chain: c.chat_fallback_chain, diff --git a/src/core/ai/gateway.ts b/src/core/ai/gateway.ts index 555c2059..91068358 100644 --- a/src/core/ai/gateway.ts +++ b/src/core/ai/gateway.ts @@ -470,6 +470,9 @@ export function configureGateway(config: AIGatewayConfig): void { // fail with a cryptic wrong-width error at embed time. Keep it honest. embedding_dimensions: config.embedding_dimensions, embedding_multimodal_model: config.embedding_multimodal_model, + // #4107: stays undefined when unset so getImageOcrModel() keeps the + // "fall back to the expansion model" signal honest. + embedding_image_ocr_model: config.embedding_image_ocr_model, expansion_model: config.expansion_model ?? DEFAULT_EXPANSION_MODEL, chat_model: config.chat_model ?? DEFAULT_CHAT_MODEL, chat_fallback_chain: config.chat_fallback_chain, @@ -837,6 +840,16 @@ export function getExpansionModel(): string { return requireConfig().expansion_model ?? DEFAULT_EXPANSION_MODEL; } +/** + * #4107: the model generateOcrText() routes to — `embedding_image_ocr_model` + * when set, else the expansion model. A direct "provider:model" string like + * embedding_multimodal_model (never models.tier-resolved), so `gbrain config + * set embedding_image_ocr_model` points OCR exactly where the user aimed it. + */ +export function getImageOcrModel(): string { + return requireConfig().embedding_image_ocr_model ?? getExpansionModel(); +} + export function getChatModel(): string { return requireConfig().chat_model ?? DEFAULT_CHAT_MODEL; } @@ -955,7 +968,14 @@ export function diagnoseEmbedding(modelOverride?: string): EmbeddingDiagnosis { } const required = recipe.auth_env?.required ?? []; - const missing = required.filter(k => !_config!.env[k]); + // #4385: a configured OPENAI_BASE_URL points native-openai embedding at a + // keyless local OpenAI-compatible server, so the override satisfies the + // key requirement — mirrors instantiateEmbedding's placeholder path. + const keylessBaseUrl = + recipe.implementation === 'native-openai' && !!resolveNativeBaseUrl('openai', _config); + const missing = required.filter( + k => !_config!.env[k] && !(keylessBaseUrl && k === 'OPENAI_API_KEY'), + ); if (missing.length > 0) { return { ok: false, @@ -1601,12 +1621,15 @@ async function resolveEmbeddingProvider(modelStr: string): Promise<{ model: any; function instantiateEmbedding(recipe: Recipe, modelId: string, cfg: AIGatewayConfig): any { switch (recipe.implementation) { case 'native-openai': { - const apiKey = cfg.env.OPENAI_API_KEY; + const baseURL = resolveNativeBaseUrl('openai', cfg); + // #4385: a base-URL override targets a local OpenAI-compatible server + // (LM Studio, vLLM) that ignores auth — the SDK only requires a + // non-empty key, so use the same placeholder as defaultResolveAuth. + const apiKey = cfg.env.OPENAI_API_KEY ?? (baseURL ? 'unauthenticated' : undefined); if (!apiKey) throw new AIConfigError( `OpenAI embedding requires OPENAI_API_KEY.`, recipe.setup_hint, ); - const baseURL = resolveNativeBaseUrl('openai', cfg); const client = createOpenAI({ apiKey, ...(baseURL ? { baseURL } : {}) }); // AI SDK v6: use .textEmbeddingModel() for embeddings return (client as any).textEmbeddingModel @@ -1826,7 +1849,17 @@ export async function embed(texts: string[], opts?: EmbedOpts): Promise 0 ? envCapRaw : undefined; + const maxBatchTokens = embedding?.max_batch_tokens ?? envCap; const charsPerToken = embedding?.chars_per_token ?? DEFAULT_CHARS_PER_TOKEN; // Pre-split is gated on max_batch_tokens. Recipes without it (e.g. OpenAI) @@ -2871,7 +2904,8 @@ export async function expand(query: string): Promise { /** * Cherry-1: opt-in OCR pass for ingested images. Uses the configured - * expansion model (default: DEFAULT_EXPANSION_MODEL) with a prompt explicitly + * `embedding_image_ocr_model` when set (#4107), else the expansion model + * (default: DEFAULT_EXPANSION_MODEL), with a prompt explicitly * instructing the model to NOT interpret instructions embedded in the * image (mitigation for OCR-as-prompt-injection). * @@ -2883,8 +2917,15 @@ export async function expand(query: string): Promise { * keeping the gateway focused on the LLM call. */ export async function generateOcrText(imageBytes: Buffer, mime: string): Promise { - if (!isAvailable('expansion')) return ''; - const { model, recipe, modelId } = await resolveExpansionProvider(getExpansionModel()); + // Unconfigured gateway stays a silent '' no-op (the pre-#4107 isAvailable + // gate's behavior), never a requireConfig() throw. + if (!_config) return ''; + const ocrModel = getImageOcrModel(); + // Fail-closed on a misconfigured OCR model (provider without an expansion + // touchpoint, or unkeyed): '' rather than silently OCRing with the + // expansion model. + if (!isAvailable('expansion', ocrModel)) return ''; + const { model, recipe, modelId } = await resolveExpansionProvider(ocrModel); const base64 = imageBytes.toString('base64'); const systemPrompt = [ 'Extract any visible text from this image VERBATIM.', @@ -3274,6 +3315,13 @@ export interface ChatOpts { tools?: ChatToolDef[]; maxTokens?: number; abortSignal?: AbortSignal; + /** + * Per-call provider options keyed by recipe id, deep-merged LAST — after + * the derived cache markers and configured `provider_chat_options` — so a + * call site can pin provider behavior it depends on (e.g. the triage judge + * disabling DeepSeek thinking) without config silently overriding it. + */ + providerOptions?: Record>; /** * Ask for the stable prefix (system prompt + last tool def) to be cached. * Silently ignored on providers whose recipe declares no prompt caching. @@ -3733,7 +3781,7 @@ export async function chat(opts: ChatOpts): Promise { const tools = toAISDKTools(opts.tools); - const providerOptions: Record = {}; + let providerOptions: Record = {}; if (useCache) { // Call-level `providerOptions.anthropic.cacheControl` is NOT a no-op: // @ai-sdk/anthropic 3.0.47+ passes it through as a top-level @@ -3772,6 +3820,8 @@ export async function chat(opts: ChatOpts): Promise { if (promptCacheKey) providerOptions.openai = { promptCacheKey }; } applyConfiguredChatProviderOptions(providerOptions, cfg, recipe.id, modelId); + // Call-scoped options merge last so they win over configured siblings. + providerOptions = deepMergeRecords(providerOptions, opts.providerOptions); // Derive ONE canonical cache-control value AFTER config merging and reuse // it for every breakpoint (system block, last tool def, call-level). If diff --git a/src/core/ai/provider-env.ts b/src/core/ai/provider-env.ts index a72d5f44..8a75c02a 100644 --- a/src/core/ai/provider-env.ts +++ b/src/core/ai/provider-env.ts @@ -39,6 +39,12 @@ export function mergedProviderEnv( if (cfg?.openrouter_api_key) fromConfig.OPENROUTER_API_KEY = cfg.openrouter_api_key; if (cfg?.voyage_api_key) fromConfig.VOYAGE_API_KEY = cfg.voyage_api_key; if (cfg?.dashscope_api_key) fromConfig.DASHSCOPE_API_KEY = cfg.dashscope_api_key; + // Same seam for LiteLLM + Together, closed alongside litellm's chat + // touchpoint (v0.42.61.0 made litellm a full chat provider, so the + // config-plane gap started biting daemon/launchd/MCP contexts the same + // way voyage's #2662 did). + if (cfg?.litellm_api_key) fromConfig.LITELLM_API_KEY = cfg.litellm_api_key; + if (cfg?.together_api_key) fromConfig.TOGETHER_API_KEY = cfg.together_api_key; if (cfg?.google_api_key) fromConfig.GOOGLE_GENERATIVE_AI_API_KEY = cfg.google_api_key; // #4031: the Azure key was the only member of the group below left unfolded, // so a config.json-only setup failed every embed from keyless shells diff --git a/src/core/ai/recipes/ollama.ts b/src/core/ai/recipes/ollama.ts index 83c342e9..62717a85 100644 --- a/src/core/ai/recipes/ollama.ts +++ b/src/core/ai/recipes/ollama.ts @@ -18,7 +18,15 @@ export const ollama: Recipe = { 'nomic-embed-text', 'mxbai-embed-large', 'all-minilm', + // Real Ollama library tags (verified 2026-08-08): the family is + // published as `qwen3-embedding` with size tags, and Arctic Embed + // 2.0 as `snowflake-arctic-embed2`. The earlier `qwen3-embed-8b` / + // HF-style `snowflake-arctic-embed-l-v2` spellings stay listed so + // brains initialized with them keep validating, but they never + // matched a pullable Ollama tag. + 'qwen3-embedding:8b', 'qwen3-embed-8b', + 'snowflake-arctic-embed2', 'snowflake-arctic-embed-l-v2', 'bge-m3', ], @@ -33,7 +41,9 @@ export const ollama: Recipe = { 'nomic-embed-text': 768, 'mxbai-embed-large': 1024, 'all-minilm': 384, + 'qwen3-embedding:8b': 4096, 'qwen3-embed-8b': 4096, + 'snowflake-arctic-embed2': 1024, 'snowflake-arctic-embed-l-v2': 1024, 'bge-m3': 1024, }, diff --git a/src/core/ai/types.ts b/src/core/ai/types.ts index a8cc58ca..1558b4d6 100644 --- a/src/core/ai/types.ts +++ b/src/core/ai/types.ts @@ -497,6 +497,13 @@ export interface AIGatewayConfig { * Allows brains using OpenAI for text to use Voyage for image embeddings. */ embedding_multimodal_model?: string; + /** + * Separate model for image OCR (e.g. "openai:gpt-4o-mini"). When set, + * generateOcrText() routes to this model instead of expansion_model. + * A direct "provider:model" string like embedding_multimodal_model — + * deliberately never models.tier-resolved (#4107). + */ + embedding_image_ocr_model?: string; /** Current expansion model as "provider:modelId". */ expansion_model?: string; /** Default chat model for `gateway.chat()` callers (subagent default). */ diff --git a/src/core/budget/budget-tracker.ts b/src/core/budget/budget-tracker.ts index b020d36c..0e2a8056 100644 --- a/src/core/budget/budget-tracker.ts +++ b/src/core/budget/budget-tracker.ts @@ -359,6 +359,15 @@ function costForUsage( export class BudgetTracker { private cumulativeUsd = 0; + /** + * #4365 — sum of projections reserved but not yet record()ed. Concurrent + * callers (e.g. skillopt's validation gate, concurrency 4) all pass + * admission against cumulativeUsd alone, breaching the cap by up to + * (N-1)×per-call cost. Admission checks cumulative + outstanding instead. + */ + private outstandingUsd = 0; + /** FIFO of unsettled projections keyed `${modelId}|${kind}` (gateway pairs reserve→record 1:1). */ + private readonly outstandingByKey = new Map(); private callsRecorded = 0; private readonly startedAt: number; private readonly auditPath: string; @@ -473,7 +482,7 @@ export class BudgetTracker { } if (this.opts.maxCostUsd !== undefined) { - const after = this.cumulativeUsd + projected; + const after = this.cumulativeUsd + this.outstandingUsd + projected; if (after > this.opts.maxCostUsd) { appendAuditLine(this.auditPath, { schema_version: 1, @@ -485,15 +494,23 @@ export class BudgetTracker { sub_label: estimate.label, projected_cost_usd: projected, cumulative_cost_usd: this.cumulativeUsd, + outstanding_usd: this.outstandingUsd, max_cost_usd: this.opts.maxCostUsd, }); this.fireExhausted(); throw new BudgetExhausted( `${this.opts.label}: projected cost $${after.toFixed(4)} exceeds --max-cost $${this.opts.maxCostUsd.toFixed(2)} ` + - `(cumulative $${this.cumulativeUsd.toFixed(4)} + this call $${projected.toFixed(4)})`, + `(cumulative $${this.cumulativeUsd.toFixed(4)} + outstanding $${this.outstandingUsd.toFixed(4)} + this call $${projected.toFixed(4)})`, { reason: 'cost', spent: this.cumulativeUsd, cap: this.opts.maxCostUsd, modelId: estimate.modelId }, ); } + // Admission passed — hold the projection until record() settles it so + // parallel reserve() calls can't all admit against the same cumulative. + const key = `${estimate.modelId}|${estimate.kind}`; + const queue = this.outstandingByKey.get(key) ?? []; + queue.push(projected); + this.outstandingByKey.set(key, queue); + this.outstandingUsd += projected; } appendAuditLine(this.auditPath, { @@ -549,6 +566,7 @@ export class BudgetTracker { return; } + this.settleReservation(actual.modelId, kind); this.cumulativeUsd += cost; appendAuditLine(this.auditPath, { schema_version: 1, @@ -587,6 +605,34 @@ export class BudgetTracker { }; } + /** + * Release the oldest unsettled reservation for this call's model+kind. + * Exact key first; on miss, the oldest same-kind entry — gateway.chat + * reserves with the pre-resolution model string (alias/bare/slash form) + * but records `${recipe.id}:${modelId}`, and a missed pop would leak + * phantom outstanding budget for the tracker's lifetime. Records with no + * reservation at all (expand/OCR spend sites) pop nothing. + */ + private settleReservation(modelId: string, kind: BudgetKind): void { + let key = `${modelId}|${kind}`; + let queue = this.outstandingByKey.get(key); + if (!queue || queue.length === 0) { + const suffix = `|${kind}`; + queue = undefined; + for (const [k, q] of this.outstandingByKey) { + if (k.endsWith(suffix) && q.length > 0) { + key = k; + queue = q; + break; + } + } + } + if (!queue || queue.length === 0) return; + const amount = queue.shift()!; + if (queue.length === 0) this.outstandingByKey.delete(key); + this.outstandingUsd = Math.max(0, this.outstandingUsd - amount); + } + /** Internal helper: throw BudgetExhausted(reason:'runtime') when the wall-clock cap fires. */ private assertRuntime(modelId: string): void { if (this.opts.maxRuntimeMs === undefined) return; diff --git a/src/core/capture-content.ts b/src/core/capture-content.ts index 954c7950..de9d0a69 100644 --- a/src/core/capture-content.ts +++ b/src/core/capture-content.ts @@ -59,9 +59,12 @@ export function defaultSlug(content: string, now: Date = new Date(), type?: stri * Returns the 0-indexed byte offset of the first NUL, or -1 if clean. * Caller decides the error shape (message vs JSON envelope). * - * Known limit: a PNG-without-NUL-in-first-8KB slips through. v0.39 - * magic-byte allowlist (per CV10-B + TODOS.md) closes this hole. The - * 8KB ceiling bounds the scan cost to ~microseconds even on huge files. + * The 8KB ceiling bounds the scan cost to ~microseconds even on huge files. + * + * This scan alone is NOT sufficient — a container with no NUL in its head (an + * ASCII-armored PDF being the common case) passes it. That hole is closed by + * `detectBinarySignature`, which runs first; keep both, since the NUL scan + * still catches binary formats that carry no signature in this list. */ export function detectBinaryNullByte(buf: Buffer): number { const limit = Math.min(buf.length, 8 * 1024); @@ -71,6 +74,81 @@ export function detectBinaryNullByte(buf: Buffer): number { return -1; } +/** + * Magic-byte signatures for container formats that must never be stored as a + * page body. Each entry matches `bytes` at a fixed `offset`. + * + * Entries are deliberately restricted to signatures that either contain a + * non-printable byte or are long/distinctive enough that a real markdown file + * opening with them is implausible. Weak two-letter ASCII magics (`MZ`, `BM`) + * and `ID3` are intentionally OMITTED: a legitimate text file can plausibly + * start with those, and the formats carrying them hold NUL bytes early anyway, + * so `detectBinaryNullByte` already covers them without the false-positive risk + * of refusing a valid capture. + */ +const BINARY_SIGNATURES: ReadonlyArray<{ offset: number; bytes: readonly number[]; label: string }> = [ + { offset: 0, bytes: [0x25, 0x50, 0x44, 0x46, 0x2d], label: 'PDF' }, // %PDF- + { offset: 0, bytes: [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a], label: 'PNG' }, + { offset: 0, bytes: [0xff, 0xd8, 0xff], label: 'JPEG' }, + { offset: 0, bytes: [0x47, 0x49, 0x46, 0x38, 0x37, 0x61], label: 'GIF' }, // GIF87a + { offset: 0, bytes: [0x47, 0x49, 0x46, 0x38, 0x39, 0x61], label: 'GIF' }, // GIF89a + { offset: 0, bytes: [0x50, 0x4b, 0x03, 0x04], label: 'ZIP / OOXML (docx, xlsx, pptx)' }, + { offset: 0, bytes: [0x50, 0x4b, 0x05, 0x06], label: 'ZIP (empty archive)' }, + { offset: 0, bytes: [0x50, 0x4b, 0x07, 0x08], label: 'ZIP (spanned archive)' }, + { offset: 0, bytes: [0x1f, 0x8b], label: 'gzip' }, + { offset: 0, bytes: [0x37, 0x7a, 0xbc, 0xaf, 0x27, 0x1c], label: '7-Zip' }, + { offset: 0, bytes: [0x52, 0x61, 0x72, 0x21, 0x1a, 0x07], label: 'RAR' }, + { offset: 0, bytes: [0x7f, 0x45, 0x4c, 0x46], label: 'ELF executable' }, + { offset: 0, bytes: [0xcf, 0xfa, 0xed, 0xfe], label: 'Mach-O' }, + { offset: 0, bytes: [0xce, 0xfa, 0xed, 0xfe], label: 'Mach-O' }, + { offset: 0, bytes: [0xfe, 0xed, 0xfa, 0xcf], label: 'Mach-O' }, + { offset: 0, bytes: [0xfe, 0xed, 0xfa, 0xce], label: 'Mach-O' }, + { offset: 0, bytes: [0xca, 0xfe, 0xba, 0xbe], label: 'Mach-O universal / Java class' }, + { offset: 0, bytes: [0x53, 0x51, 0x4c, 0x69, 0x74, 0x65, 0x20, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x20, 0x33], label: 'SQLite database' }, + { offset: 0, bytes: [0x4f, 0x67, 0x67, 0x53], label: 'Ogg' }, + { offset: 0, bytes: [0x66, 0x4c, 0x61, 0x43], label: 'FLAC' }, + { offset: 0, bytes: [0x1a, 0x45, 0xdf, 0xa3], label: 'Matroska / WebM' }, + { offset: 0, bytes: [0x49, 0x49, 0x2a, 0x00], label: 'TIFF' }, + { offset: 0, bytes: [0x4d, 0x4d, 0x00, 0x2a], label: 'TIFF' }, + { offset: 0, bytes: [0x77, 0x4f, 0x46, 0x46], label: 'WOFF font' }, + { offset: 0, bytes: [0x77, 0x4f, 0x46, 0x32], label: 'WOFF2 font' }, + { offset: 4, bytes: [0x66, 0x74, 0x79, 0x70], label: 'MP4 / MOV / HEIC' }, // ....ftyp + { offset: 8, bytes: [0x57, 0x45, 0x42, 0x50], label: 'WebP' }, // RIFF....WEBP + { offset: 8, bytes: [0x57, 0x41, 0x56, 0x45], label: 'WAV' }, // RIFF....WAVE + { offset: 8, bytes: [0x41, 0x56, 0x49, 0x20], label: 'AVI' }, // RIFF....AVI_ +]; + +/** + * Magic-byte binary guard (#4022) — closes the hole the CV10 NUL scan + * documented but never closed ("Known limit: a PNG-without-NUL-in-first-8KB + * slips through... magic-byte allowlist closes this hole"). + * + * Why the NUL scan is insufficient: a container whose leading bytes happen to + * contain no 0x00 — a small ASCII-armored PDF is the common case — passes the + * NUL scan, gets UTF-8-decoded into U+FFFD replacement characters, and is + * stored as the page body. `capture` then reports success while the document's + * real text is lost, because in a PDF that text lives inside FlateDecode + * streams. The stored page is unsearchable mojibake with a `%PDF-1.4` title. + * + * Returns a format label for the matched signature, or null when nothing + * matches. Cheap: a handful of byte comparisons against the file head. + */ +export function detectBinarySignature(buf: Buffer): string | null { + for (const sig of BINARY_SIGNATURES) { + const end = sig.offset + sig.bytes.length; + if (buf.length < end) continue; + let matched = true; + for (let i = 0; i < sig.bytes.length; i++) { + if (buf[sig.offset + i] !== sig.bytes[i]) { + matched = false; + break; + } + } + if (matched) return sig.label; + } + return null; +} + /** * v0.39.3.0 CV9 — normalize content for content_hash so identical text * produces identical hashes regardless of leading/trailing whitespace, diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts index 3f081397..b487cccb 100644 --- a/src/core/cli-flag-registry.generated.ts +++ b/src/core/cli-flag-registry.generated.ts @@ -17,7 +17,7 @@ export const CLI_FLAG_REGISTRY: Record = { 'advisor': ['--apply', '--brain', '--fast', '--force', '--from-pages', '--help', '--http', '--json', '--no-embedding', '--skills-dir', '--source', '--surface', '--token-ttl', '--verbose', '--workspace'], 'agent': ['--all', '--allow-old-serve', '--brain', '--detach', '--fanout-manifest', '--federated', '--federated-read', '--flag', '--flags', '--follow', '--harness', '--help', '--http', '--json', '--max-turns', '--mcp-only', '--model', '--no-federated', '--no-follow', '--note', '--path', '--port', '--preset', '--reissue', '--repo', '--restore-only', '--scopes', '--show-token', '--since', '--source', '--source-guard', '--subagent-def', '--surface', '--timeout-ms', '--token-ttl', '--tools', '--url', '--word', '--yes'], 'anomalies': ['--brain', '--fast', '--force', '--from-pages', '--help', '--http', '--json', '--lookback-days', '--mcp-only', '--no-embedding', '--sigma', '--since', '--source', '--surface', '--timeout', '--token-ttl'], - 'apply-migrations': ['--ab', '--all', '--auto-update', '--brain', '--break-lock', '--build-index', '--by-mention', '--compile', '--days', '--dry-run', '--exclusive', '--fast', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--from-meetings', '--from-pages', '--help', '--history', '--host-dir', '--http', '--json', '--lang', '--list', '--locks', '--markdown', '--max-age', '--migrate-only', '--migration', '--mode', '--multimodal', '--no-autopilot-install', '--no-embedding', '--no-extract', '--non-interactive', '--phase', '--priority', '--refresh-unqualified', '--remediate', '--rollback', '--skip-verify', '--source', '--stale', '--surface', '--token-ttl', '--undo-wave', '--use-captured-snapshot', '--with-calibration', '--yes'], + 'apply-migrations': ['--ab', '--all', '--auto-update', '--brain', '--break-lock', '--build-index', '--by-mention', '--compile', '--days', '--dry-run', '--exclusive', '--fast', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--from-meetings', '--from-pages', '--help', '--history', '--host-dir', '--http', '--json', '--lang', '--list', '--locks', '--markdown', '--max-age', '--migrate-only', '--migration', '--mode', '--multimodal', '--no-autopilot-install', '--no-embedding', '--no-extract', '--non-interactive', '--phase', '--priority', '--refresh-unqualified', '--remediate', '--require-db', '--rollback', '--skip-verify', '--source', '--stale', '--surface', '--token-ttl', '--undo-wave', '--use-captured-snapshot', '--with-calibration', '--yes'], 'auth': ['--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--days', '--enable-dcr', '--enable-dcr-insecure', '--fast', '--federated-read', '--force', '--from-pages', '--grant-types', '--help', '--http', '--id', '--json', '--no-embedding', '--redirect-uri', '--scopes', '--source', '--stale', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--usage', '--yes'], 'autopilot': ['--all', '--auto-fix', '--batch', '--brain', '--break-lock', '--by-type', '--check', '--dim', '--dimensions', '--dir', '--drain', '--embedding-dimensions', '--embedding-model', '--explain', '--fast', '--ff-only', '--fix', '--force', '--force-break-lock', '--force-retry', '--from-pages', '--help', '--http', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--json', '--markdown', '--max-age', '--max-rss', '--max-usd', '--migrate-only', '--model', '--multimodal', '--no', '--no-embed', '--no-embedding', '--no-federated', '--no-inject', '--no-mutate', '--no-worker', '--non-interactive', '--now', '--once', '--output', '--path', '--phase', '--refresh-cache', '--remediate', '--remediation-plan', '--repo', '--save', '--source', '--stale', '--status', '--surface', '--swap-only', '--take', '--target', '--target-score', '--timeout', '--to', '--token-ttl', '--uninstall', '--unsafe-bypass-dream-guard', '--user', '--version', '--yes'], 'backfill': ['--batch-size', '--brain', '--concurrency', '--dry-run', '--fresh', '--help', '--json', '--keep-index', '--list', '--max-errors', '--max-rows', '--resume', '--source'], @@ -28,7 +28,7 @@ export const CLI_FLAG_REGISTRY: Record = { 'brainstorm': ['--all', '--brain', '--chunker-debug', '--code', '--compile', '--fast', '--file', '--fix', '--force', '--force-rechunk', '--force-resume', '--from-pages', '--full', '--help', '--http', '--json', '--judge-model', '--lang', '--limit', '--list-runs', '--markdown', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--model', '--no-embed', '--no-embedding', '--no-save', '--path', '--resume', '--retry-failed', '--retry-judge', '--save', '--source', '--stale', '--strict-budget', '--surface', '--timeout', '--token-ttl', '--yes'], 'cache': ['--brain', '--fast', '--force', '--from-pages', '--help', '--http', '--json', '--no-embedding', '--source', '--surface', '--token-ttl', '--yes'], 'calibration': ['--ab', '--all', '--allow-empty', '--apply', '--asof', '--auto', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--by-mention', '--content', '--date', '--days', '--dry-run', '--entities', '--explain', '--federated', '--file', '--follow', '--full', '--help', '--holder', '--http', '--image', '--json', '--key-prefix', '--kind', '--lang', '--limit', '--markdown', '--max-usd', '--mode', '--multimodal', '--near-symbol', '--no-federated', '--offset', '--page', '--path', '--phase', '--progress-interval', '--progress-json', '--quiet', '--recency', '--regenerate', '--repo', '--restore-only', '--salience', '--save', '--scrub-gstack', '--session', '--session-id', '--since', '--slug', '--slugs', '--source', '--source-guard', '--stale', '--stats', '--stdin', '--surface', '--symbol-kind', '--thin', '--trusted-extraction', '--types', '--undo-wave', '--url', '--walk-depth', '--with-calibration', '--with-db', '--yes'], - 'call': ['--aliases', '--all', '--all-sources', '--allow-docker', '--anchor', '--apply', '--apply-rewrites', '--as-context', '--auto-fix', '--background', '--brain', '--budget', '--by-mention', '--catch-up', '--check', '--concurrency', '--confirm-destructive', '--content', '--cost-estimate', '--count', '--days', '--depth', '--dim', '--dir', '--direction', '--enable-dcr', '--enable-dcr-insecure', '--explain', '--fast', '--federated', '--file', '--fix', '--follow', '--force', '--from', '--from-meetings', '--grant-types', '--grep', '--hard-deadline', '--help', '--http', '--image', '--include-expired', '--include-frontmatter', '--infer-dates', '--install', '--interval', '--json', '--key', '--kind', '--lang', '--limit', '--link-source', '--link-type', '--llm', '--migrate-only', '--missing-path', '--multimodal', '--ner', '--no-embed', '--no-expand', '--no-federated', '--no-hard-deadline', '--no-retry-connect', '--no-save', '--older-than', '--once', '--page', '--param', '--params', '--password', '--path', '--pglite', '--port', '--prefer-postgres', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--public-url', '--qrels', '--queue', '--quiet', '--reenrich-after', '--refresh-cache', '--remediate', '--remediation-plan', '--repo', '--reset', '--restore-only', '--save', '--scopes', '--session', '--sigma', '--since', '--slug', '--slug-prefix', '--source', '--source-guard', '--source-id', '--stale', '--status', '--stdin', '--strategy', '--suites', '--supabase', '--supersessions', '--surface', '--symbol-kind', '--synthesize', '--tag', '--take', '--target', '--timeout', '--to', '--today', '--token', '--token-ttl', '--tools-json', '--type', '--undo', '--uninstall', '--url', '--version', '--watch', '--with-calibration', '--workers', '--yes'], + 'call': ['--aliases', '--all', '--all-sources', '--allow-docker', '--anchor', '--apply', '--apply-rewrites', '--as-context', '--auto-fix', '--background', '--brain', '--budget', '--by-mention', '--catch-up', '--check', '--concurrency', '--confirm-destructive', '--content', '--cost-estimate', '--count', '--days', '--depth', '--dim', '--dir', '--direction', '--enable-dcr', '--enable-dcr-insecure', '--explain', '--fast', '--federated', '--file', '--fix', '--follow', '--force', '--from', '--from-meetings', '--grant-types', '--grep', '--hard-deadline', '--help', '--http', '--image', '--include-expired', '--include-frontmatter', '--infer-dates', '--install', '--interval', '--json', '--key', '--kind', '--lang', '--limit', '--link-source', '--link-type', '--llm', '--migrate-only', '--missing-path', '--multimodal', '--ner', '--no-embed', '--no-expand', '--no-federated', '--no-hard-deadline', '--no-migrate', '--no-retry-connect', '--no-save', '--older-than', '--once', '--page', '--param', '--params', '--password', '--path', '--pglite', '--port', '--prefer-postgres', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--public-url', '--qrels', '--queue', '--quiet', '--reenrich-after', '--refresh-cache', '--remediate', '--remediation-plan', '--repo', '--reset', '--restore-only', '--save', '--scopes', '--session', '--sigma', '--since', '--slug', '--slug-prefix', '--source', '--source-guard', '--source-id', '--stale', '--status', '--stdin', '--strategy', '--suites', '--supabase', '--supersessions', '--surface', '--symbol-kind', '--synthesize', '--tag', '--take', '--target', '--timeout', '--to', '--today', '--token', '--token-ttl', '--tools-json', '--type', '--undo', '--uninstall', '--url', '--version', '--watch', '--with-calibration', '--workers', '--yes'], 'capture': ['--all', '--allow-empty', '--apply', '--asof', '--auto', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--by-mention', '--content', '--date', '--days', '--depth', '--entities', '--fast', '--federated', '--file', '--follow', '--force', '--from-pages', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--mode', '--multimodal', '--near-symbol', '--no-embedding', '--no-federated', '--offset', '--page', '--path', '--progress-interval', '--progress-json', '--quiet', '--recency', '--repo', '--restore-only', '--salience', '--save', '--scopes', '--session', '--session-id', '--since', '--slug', '--slugs', '--source', '--source-guard', '--stats', '--stdin', '--surface', '--timeout', '--token-ttl', '--trusted-extraction', '--type', '--types', '--url', '--walk-depth', '--what', '--where', '--who', '--with-db', '--yes'], 'check-backlinks': ['--background', '--brain', '--brain-wide-max-cost-usd', '--check', '--dir', '--dry-run', '--explain', '--follow', '--help', '--include-frontmatter', '--json', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--source', '--stale', '--timeout', '--type'], 'check-resolvable': ['--brain', '--dry-run', '--fix', '--help', '--json', '--skills-dir', '--source', '--strict', '--verbose'], @@ -39,12 +39,12 @@ export const CLI_FLAG_REGISTRY: Record = { 'code-def': ['--all', '--all-sources', '--brain', '--chunker-debug', '--help', '--json', '--lang', '--limit', '--no-json', '--pretty', '--source', '--yes'], 'code-refs': ['--all', '--all-sources', '--brain', '--chunker-debug', '--help', '--json', '--lang', '--limit', '--no-json', '--source', '--yes'], 'compile-context': ['--brain', '--budget', '--check', '--federated', '--help', '--include', '--json', '--no-federated', '--out', '--path', '--repo', '--restore-only', '--source', '--source-guard', '--stdout', '--target'], - 'config': ['--all', '--brain', '--column', '--coverage-override', '--detail', '--dry-run', '--embedding-dimensions', '--embedding-model', '--fast', '--federated-read', '--follow', '--force', '--from-pages', '--help', '--http', '--json', '--markdown', '--model', '--multimodal', '--no-embedding', '--no-federated', '--pattern', '--pglite', '--recency', '--reset', '--source', '--surface', '--to', '--token-ttl', '--url', '--yes'], + 'config': ['--all', '--brain', '--column', '--coverage-override', '--detail', '--dry-run', '--embedding-dimensions', '--embedding-model', '--fast', '--federated-read', '--follow', '--force', '--from-pages', '--help', '--http', '--json', '--markdown', '--model', '--multimodal', '--no-embedding', '--no-federated', '--pattern', '--pglite', '--raw', '--recency', '--reset', '--source', '--surface', '--to', '--token-ttl', '--url', '--yes'], 'connect': ['--agent', '--auto', '--bearer-token-env-var', '--bind', '--brain', '--client-id', '--client-secret', '--delete-brain', '--env', '--force', '--grant-types', '--header', '--help', '--http', '--install', '--issuer-url', '--json', '--mcp-only', '--mcp-url', '--name', '--oauth', '--oauth-client-id', '--oauth-client-secret', '--public-url', '--pure', '--register', '--remove', '--scope', '--scopes', '--show-token', '--source', '--status', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--url', '--version', '--workspace', '--yes'], 'connectors': ['--all', '--background', '--brain', '--brain-wide-max-cost-usd', '--check', '--cookie', '--dry-run', '--embed', '--explain', '--follow', '--force', '--full', '--help', '--install', '--json', '--limit', '--no-browser', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--source', '--stale', '--timeout', '--token', '--try-oauth', '--window-days'], 'conversation-parser': ['--brain', '--help', '--json', '--source'], 'db-repair': ['--ab', '--all', '--allow-docker', '--apply', '--apply-rewrites', '--auto-update', '--brain', '--break-lock', '--build-index', '--by-mention', '--compile', '--days', '--db-url', '--dry-run', '--exclusive', '--explain', '--fast', '--filter', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--from-pages', '--help', '--history', '--http', '--json', '--lang', '--locks', '--markdown', '--max-age', '--multimodal', '--name', '--near-symbol', '--no-embedding', '--no-extract', '--path', '--phase', '--prefer-postgres', '--priority', '--quiet', '--refresh-unqualified', '--remediate', '--restart', '--restore-only', '--rollback', '--skip-verify', '--source', '--stale', '--supabase', '--surface', '--symbol-kind', '--thin', '--token-ttl', '--undo-last-rewrite', '--undo-wave', '--url', '--use-captured-snapshot', '--version', '--with-calibration', '--yes'], - 'doctor': ['--ab', '--abbrev-ref', '--abi', '--abort', '--all', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply', '--apply-rewrites', '--audit-rejects', '--auto', '--auto-fix', '--auto-update', '--background', '--batch', '--brain', '--brain-wide-max-cost-usd', '--branch', '--break-lock', '--build-index', '--by-mention', '--by-type', '--cached', '--check', '--column', '--compile', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--date', '--days', '--delete-brain', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--env', '--exclude-standard', '--exclusive', '--explain', '--fast', '--federated-read', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--force-schema', '--force-sunset-target', '--format', '--fresh', '--from', '--from-meetings', '--from-pages', '--full', '--gbrain-bin', '--get', '--git-dir', '--git-path', '--grant-types', '--harness', '--health-interval', '--help', '--history', '--home', '--http', '--id', '--ignore-env-override', '--ignore-missing-key', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--index-audit', '--init', '--input', '--install', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--link-source', '--link-type', '--local', '--locks', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-jobs', '--max-rss', '--max-usd', '--mcp-even-if-plugin', '--mcp-only', '--migrate-only', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--near-symbol', '--nice', '--no', '--no-capture', '--no-cron', '--no-embed', '--no-embedding', '--no-extract', '--no-federated', '--no-hooks', '--no-mutate', '--no-verify', '--oauth-client-secret', '--older-than', '--once', '--others', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--prefer-postgres', '--preset', '--priority', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--pure', '--push-only', '--query', '--queue', '--quiet', '--rebase', '--rebuild', '--rebuild-rollup', '--recency', '--refresh', '--refresh-unqualified', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--repo', '--reranker', '--reset', '--resolve', '--restore-only', '--resume', '--retarget', '--review-lower', '--rollback', '--scope', '--scopes', '--session', '--set', '--short', '--show-current', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slugs', '--source', '--source-id', '--stale', '--stats', '--status', '--strategy', '--strict', '--supabase', '--surface', '--symbol-kind', '--target', '--target-score', '--thin', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--type', '--undo-wave', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--use-captured-snapshot', '--user-hooks', '--verbose', '--verify', '--version', '--window', '--with-calibration', '--workers', '--yes'], + 'doctor': ['--ab', '--abbrev-ref', '--abi', '--abort', '--all', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply', '--apply-rewrites', '--audit-rejects', '--auto', '--auto-fix', '--auto-update', '--background', '--batch', '--brain', '--brain-wide-max-cost-usd', '--branch', '--break-lock', '--build-index', '--by-mention', '--by-type', '--cached', '--check', '--column', '--compile', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--date', '--days', '--delete-brain', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--env', '--exclude-standard', '--exclusive', '--explain', '--fast', '--federated-read', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--force-schema', '--force-sunset-target', '--format', '--fresh', '--from', '--from-meetings', '--from-pages', '--full', '--gbrain-bin', '--get', '--git-dir', '--git-path', '--grant-types', '--harness', '--health-interval', '--help', '--history', '--home', '--http', '--id', '--ignore-env-override', '--ignore-missing-key', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--index-audit', '--init', '--input', '--install', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--link-source', '--link-type', '--local', '--locks', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-jobs', '--max-rss', '--max-usd', '--mcp-even-if-plugin', '--mcp-only', '--migrate-only', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--near-symbol', '--nice', '--no', '--no-capture', '--no-cron', '--no-embed', '--no-embedding', '--no-extract', '--no-federated', '--no-hooks', '--no-migrate', '--no-mutate', '--no-verify', '--oauth-client-secret', '--older-than', '--once', '--others', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--prefer-postgres', '--preset', '--priority', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--pure', '--push-only', '--query', '--queue', '--quiet', '--rebase', '--rebuild', '--rebuild-rollup', '--recency', '--refresh', '--refresh-unqualified', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--repo', '--reranker', '--reset', '--resolve', '--restore-only', '--resume', '--retarget', '--review-lower', '--rollback', '--scope', '--scopes', '--session', '--set', '--short', '--show-current', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slugs', '--source', '--source-id', '--stale', '--stats', '--status', '--strategy', '--strict', '--supabase', '--surface', '--symbol-kind', '--target', '--target-score', '--thin', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--type', '--undo-wave', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--use-captured-snapshot', '--user-hooks', '--verbose', '--verify', '--version', '--window', '--with-calibration', '--workers', '--yes'], 'dream': ['--against', '--aliases', '--all', '--allow-regression', '--asof', '--audit-rejects', '--background', '--batch', '--brain', '--brain-wide-max-cost-usd', '--break-lock', '--budget-usd', '--budget-usd-answer', '--budget-usd-retrieval', '--by-mention', '--by-type', '--by-type-floor', '--cancel-unmatched', '--check', '--code', '--committed-baseline', '--compare', '--compile', '--concurrent', '--cycles', '--date', '--detail', '--dim', '--dimensions', '--dir', '--drain', '--drain-implied', '--dry-run', '--embedding-dimensions', '--embedding-model', '--embeddings', '--expansion', '--explain', '--fast', '--federated', '--fix', '--fixtures', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--format', '--from', '--from-db', '--from-pages', '--gold', '--harness', '--help', '--http', '--include-holdout', '--include-null-signature', '--input', '--install', '--json', '--judge-model', '--justification', '--keyword-only', '--lang', '--limit', '--llm', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-tokens', '--max-usd', '--mcp-only', '--min-recall', '--mode', '--model', '--models', '--modes', '--multimodal', '--name', '--name-only', '--no', '--no-embed', '--no-embedding', '--no-extract', '--no-federated', '--no-llm', '--no-mutate', '--no-trajectory', '--once', '--out', '--output', '--output-dir', '--parallel', '--parity-baseline', '--path', '--pattern', '--pending', '--pglite', '--phase', '--priority', '--progress-interval', '--progress-json', '--pull', '--qrels', '--quiet', '--rebuild', '--receipt-dir', '--recency', '--reconcile-queue', '--remediate', '--repo', '--reranking', '--reset', '--resolve', '--restore-only', '--resume-from', '--retrieval-only', '--rubric-version', '--sample', '--seed', '--short', '--show-toplevel', '--since', '--skip-replay', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slug-prefix', '--source', '--source-guard', '--source-id', '--stale', '--suite', '--suites', '--supabase', '--supersessions', '--surface', '--task', '--thin', '--threshold', '--timeout', '--to', '--token-ttl', '--top-k', '--unsafe-bypass-dream-guard', '--update-baseline', '--verify', '--version', '--window', '--yes'], 'edges-backfill': ['--all', '--all-sources', '--brain', '--concurrency', '--federated', '--help', '--json', '--max-age', '--max-chunks', '--max-cost-usd', '--no-federated', '--older-than', '--path', '--repo', '--restore-only', '--source', '--source-guard', '--timeout', '--workers'], 'embed': ['--all', '--background', '--batch-size', '--brain', '--brain-wide-max-cost-usd', '--break-lock', '--catch-up', '--check', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--fast', '--fix', '--follow', '--force', '--force-break-lock', '--from-pages', '--help', '--http', '--include-null-signature', '--json', '--max-age', '--max-cost-usd', '--model', '--multimodal', '--name', '--no', '--no-embed', '--no-embedding', '--pace', '--pace-max-concurrency', '--parallel', '--path', '--pglite', '--prefix', '--priority', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--reset', '--serial', '--slugs', '--source', '--stale', '--status', '--supabase', '--surface', '--timeout', '--to', '--token-ttl', '--version'], @@ -78,7 +78,7 @@ export const CLI_FLAG_REGISTRY: Record = { 'orphans': ['--background', '--brain', '--brain-wide-max-cost-usd', '--check', '--count', '--explain', '--follow', '--help', '--include-pseudo', '--json', '--mode', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--source', '--stale', '--timeout'], 'pages': ['--brain', '--dry-run', '--help', '--json', '--older-than', '--source'], 'pglite-repair': ['--brain', '--break-lock', '--dry-rnu', '--dry-run', '--fast', '--force', '--from-pages', '--help', '--http', '--json', '--no-embedding', '--path', '--quiet', '--source', '--surface', '--token-ttl', '--yes'], - 'post-upgrade': ['--all', '--apply-clean-hunks', '--brain', '--check', '--code', '--compile', '--concurrency', '--cost-estimate', '--detail', '--dim', '--embedding-dimensions', '--embedding-model', '--fast', '--ff-only', '--flag', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--from-pages', '--help', '--host-dir', '--http', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--model', '--multimodal', '--name-only', '--no', '--no-autopilot-install', '--no-embed', '--no-embedding', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--path', '--pglite', '--quiet', '--recency', '--repo', '--reset', '--since', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--supabase', '--surface', '--swap-only', '--target', '--to', '--token-ttl', '--uninstall', '--user', '--verbose', '--verify', '--version', '--workers', '--yes'], + 'post-upgrade': ['--all', '--apply-clean-hunks', '--brain', '--check', '--code', '--compile', '--concurrency', '--cost-estimate', '--detail', '--dim', '--embedding-dimensions', '--embedding-model', '--fast', '--ff-only', '--flag', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--from-pages', '--help', '--host-dir', '--http', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--model', '--multimodal', '--name-only', '--no', '--no-autopilot-install', '--no-embed', '--no-embedding', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--path', '--pglite', '--quiet', '--recency', '--repo', '--require-db', '--reset', '--since', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--supabase', '--surface', '--swap-only', '--target', '--timeout', '--to', '--token-ttl', '--uninstall', '--user', '--verbose', '--verify', '--version', '--workers', '--yes'], 'protocol': ['--all', '--allow-empty', '--apply', '--asof', '--auto', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--by-mention', '--content', '--date', '--days', '--entities', '--fast', '--federated', '--file', '--follow', '--force', '--from-pages', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--max-usd', '--mode', '--multimodal', '--near-symbol', '--no-embedding', '--offset', '--page', '--path', '--progress-interval', '--progress-json', '--quiet', '--recency', '--salience', '--save', '--session', '--session-id', '--since', '--slug', '--slugs', '--source', '--stats', '--stdin', '--surface', '--synthesize', '--target', '--timeout', '--token', '--token-ttl', '--trusted-extraction', '--types', '--url', '--walk-depth', '--with-db', '--yes'], 'providers': ['--brain', '--dim', '--embedding-dimensions', '--embedding-model', '--embeddings', '--fast', '--force', '--from-pages', '--help', '--http', '--json', '--model', '--multimodal', '--no', '--no-embed', '--no-embedding', '--reranking', '--reset', '--source', '--surface', '--to', '--token-ttl', '--touchpoint', '--version', '--yes'], 'publish': ['--accent', '--bg', '--border', '--brain', '--card-bg', '--code-bg', '--error', '--fg', '--help', '--json', '--link', '--muted', '--out', '--password', '--source', '--title'], @@ -111,10 +111,10 @@ export const CLI_FLAG_REGISTRY: Record = { 'storage': ['--brain', '--federated', '--fix', '--help', '--json', '--no-federated', '--path', '--repo', '--restore-only', '--source', '--source-guard', '--to'], 'sweep': ['--all', '--background', '--batch-limit', '--brain', '--brain-wide-max-cost-usd', '--budget-ms', '--check', '--delete-brain', '--explain', '--federated', '--follow', '--help', '--home', '--json', '--name', '--no-delegate', '--no-federated', '--once', '--parallel', '--path', '--prefix', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--repo', '--restore-only', '--source', '--source-guard', '--stale', '--stats', '--timeout'], 'sync': ['--abbrev-ref', '--abi', '--abort', '--all', '--all-sources', '--allow-empty', '--apply', '--apply-rewrites', '--asof', '--auto', '--background', '--batch-size', '--brain', '--brain-wide-max-cost-usd', '--branch', '--break-lock', '--by-mention', '--cached', '--catch-up', '--check', '--clone-dir', '--code', '--column', '--compile', '--concurrency', '--confirm-destructive', '--content-audit', '--count', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--explain', '--fast', '--federated', '--ff-only', '--file', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--from-pages', '--full', '--full-history', '--git-path', '--hard-deadline', '--help', '--home', '--http', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--index-audit', '--infer-dates', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lang', '--link-source', '--link-type', '--lock', '--locks', '--log-noop', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-only', '--missing-path', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--nice', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-federated', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-recurse-submodules', '--no-renames', '--no-schema-pack', '--no-verify', '--object-format', '--older-than', '--once', '--orphan', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--prefer-postgres', '--prefix', '--priority', '--probe-pglite', '--progress-interval', '--progress-json', '--query', '--queue', '--quiet', '--rebase', '--rebuild', '--rebuild-rollup', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--repo', '--reset', '--respect-gitignore', '--restore-only', '--resume', '--retry-failed', '--run-id', '--save', '--scope', '--serial', '--short', '--show-toplevel', '--since', '--since-created', '--skills-dir', '--skip-failed', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--src-subpath', '--stale', '--stats', '--status', '--stdin', '--strategy', '--supabase', '--surface', '--symbol-kind', '--target', '--target-score', '--timeout', '--to', '--token-env', '--token-ttl', '--top-k', '--type', '--url', '--verbose', '--verify', '--watch', '--window', '--workers', '--working-tree', '--yes'], - 'takes': ['--accept', '--all', '--batch-size', '--brain', '--bucket-size', '--by', '--claim', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expired', '--fast', '--federated', '--file', '--force', '--from-pages', '--help', '--holder', '--http', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--no-embed', '--no-embedding', '--no-federated', '--outcome', '--path', '--pglite', '--quality', '--reject', '--repo', '--restore-only', '--row', '--semantic', '--serial', '--since', '--slugs', '--sort', '--source', '--source-guard', '--source-id', '--stale', '--status', '--supabase', '--surface', '--to', '--token-ttl', '--unit', '--until', '--value', '--weight', '--who', '--yes'], + 'takes': ['--accept', '--all', '--batch-size', '--brain', '--bucket-size', '--by', '--claim', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expired', '--fast', '--federated', '--file', '--force', '--from-pages', '--help', '--holder', '--http', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--model', '--multimodal', '--no', '--no-embed', '--no-embedding', '--no-federated', '--outcome', '--path', '--pglite', '--quality', '--reject', '--repo', '--restore-only', '--row', '--semantic', '--serial', '--since', '--slugs', '--sort', '--source', '--source-guard', '--source-id', '--stale', '--status', '--supabase', '--surface', '--to', '--token-ttl', '--unit', '--until', '--value', '--version', '--weight', '--who', '--yes'], 'think': ['--all', '--anchor', '--asof', '--bind', '--bound-slug-prefixes', '--brain', '--by-mention', '--calibration-holder', '--compile', '--db-url', '--enable-dcr', '--enable-dcr-insecure', '--explain', '--fast', '--federated', '--federated-read', '--force', '--from-pages', '--help', '--http', '--json', '--lang', '--log-full-params', '--markdown', '--max-usd', '--mcp-only', '--model', '--multimodal', '--name', '--near-symbol', '--no-embed', '--no-embedding', '--no-federated', '--no-hard-deadline', '--once', '--parallel', '--path', '--port', '--prefix', '--print-admin-token', '--priority', '--public-url', '--remediate', '--repo', '--restore-only', '--rounds', '--save', '--serial', '--since', '--source', '--source-guard', '--stale', '--stdio-idle-timeout', '--suppress', '--suppress-bootstrap-token', '--surface', '--symbol-kind', '--take', '--thin', '--timeout', '--token-ttl', '--until', '--url', '--with-calibration', '--yes'], 'transcripts': ['--all', '--all-discovery', '--background', '--brain', '--brain-wide-max-cost-usd', '--by-mention', '--check', '--code', '--compile', '--days', '--dry-run', '--embed', '--explain', '--facts', '--fast', '--federated', '--follow', '--force', '--format', '--from-pages', '--full', '--help', '--http', '--include-self', '--json', '--limit', '--markdown', '--max-bytes', '--max-cost-usd', '--no-embedding', '--no-federated', '--path', '--print', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--repo', '--restore-only', '--since', '--slug', '--source', '--source-guard', '--source-id', '--stale', '--surface', '--timeout', '--token-ttl'], - 'upgrade': ['--all', '--apply-clean-hunks', '--brain', '--check', '--code', '--compile', '--concurrency', '--cost-estimate', '--detail', '--dim', '--embedding-dimensions', '--embedding-model', '--fast', '--ff-only', '--flag', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--from-pages', '--help', '--host-dir', '--http', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--model', '--multimodal', '--name-only', '--no', '--no-autopilot-install', '--no-embed', '--no-embedding', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--path', '--pglite', '--quiet', '--recency', '--repo', '--reset', '--since', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--supabase', '--surface', '--swap-only', '--target', '--to', '--token-ttl', '--uninstall', '--user', '--verbose', '--verify', '--version', '--workers', '--yes'], + 'upgrade': ['--all', '--apply-clean-hunks', '--brain', '--check', '--code', '--compile', '--concurrency', '--cost-estimate', '--detail', '--dim', '--embedding-dimensions', '--embedding-model', '--fast', '--ff-only', '--flag', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--from-pages', '--help', '--host-dir', '--http', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--model', '--multimodal', '--name-only', '--no', '--no-autopilot-install', '--no-embed', '--no-embedding', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--path', '--pglite', '--quiet', '--recency', '--repo', '--require-db', '--reset', '--since', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--supabase', '--surface', '--swap-only', '--target', '--timeout', '--to', '--token-ttl', '--uninstall', '--user', '--verbose', '--verify', '--version', '--workers', '--yes'], 'watch': ['--brain', '--fast', '--federated', '--force', '--from-pages', '--help', '--http', '--json', '--max-pages', '--min-confidence', '--no-embedding', '--no-federated', '--path', '--repo', '--restore-only', '--source', '--source-guard', '--stats', '--surface', '--token-ttl', '--window-turns'], 'whoknows': ['--all', '--allow-empty', '--apply', '--asof', '--auto', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--by-mention', '--content', '--date', '--days', '--detail', '--entities', '--explain', '--fast', '--federated', '--file', '--follow', '--force', '--from-pages', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--mode', '--multimodal', '--near-symbol', '--no-embedding', '--offset', '--page', '--path', '--progress-interval', '--progress-json', '--quiet', '--recency', '--salience', '--save', '--session', '--session-id', '--since', '--slug', '--slugs', '--source', '--stats', '--stdin', '--surface', '--timeout', '--token-ttl', '--trusted-extraction', '--types', '--url', '--walk-depth', '--with-db', '--yes'], 'ze-switch': ['--background', '--brain', '--brain-wide-max-cost-usd', '--check', '--confirm-reembed', '--dim', '--dry-run', '--explain', '--follow', '--force', '--force-sunset-target', '--help', '--ignore-env-override', '--ignore-missing-key', '--json', '--markdown', '--non-interactive', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--reranker', '--reset', '--resume', '--source', '--stale', '--timeout', '--to', '--undo', '--yes'], diff --git a/src/core/code-graph-readiness.ts b/src/core/code-graph-readiness.ts index c85567f2..d9108fed 100644 --- a/src/core/code-graph-readiness.ts +++ b/src/core/code-graph-readiness.ts @@ -85,8 +85,13 @@ function effectiveSourceId(scope: ReadinessScope): string | undefined { return scope.allSources ? undefined : scope.sourceId; } -/** EXISTS probe: does any code chunk exist in scope? Matches the def/refs result query. */ -async function codeChunksExist(engine: BrainEngine, sourceId: string | undefined): Promise { +/** + * EXISTS probe: does any code chunk exist in scope? Matches the def/refs result + * query. Exported for the graph-four federated re-route (#4011, + * ops/context.ts `routeCodeIntelScope`) so routing and readiness share ONE + * "has code" predicate and can never disagree. + */ +export async function codeChunksExist(engine: BrainEngine, sourceId: string | undefined): Promise { const params: unknown[] = []; let scopeClause = ''; if (sourceId) { diff --git a/src/core/config-db-merge.ts b/src/core/config-db-merge.ts index 2776de59..798515f0 100644 --- a/src/core/config-db-merge.ts +++ b/src/core/config-db-merge.ts @@ -40,6 +40,8 @@ export const DB_MERGED_PROVIDER_KEY_FIELDS = [ 'openrouter_api_key', 'voyage_api_key', 'dashscope_api_key', + 'litellm_api_key', + 'together_api_key', 'google_api_key', 'azure_openai_api_key', ] as const; diff --git a/src/core/config.ts b/src/core/config.ts index a0f76fe1..f599ae70 100644 --- a/src/core/config.ts +++ b/src/core/config.ts @@ -4,6 +4,7 @@ import { homedir } from 'os'; import type { EngineConfig, EmbeddingColumnConfig } from './types.ts'; import { applyDbPlaneReadSideMerge, type DbPlaneEngineReader } from './config-db-merge.ts'; import { loadConfigSnapshot } from './config-snapshot.ts'; +import { loadGbrainEnvFile } from './gbrain-env-file.ts'; /** * Where is the active DB URL coming from? Pure introspection, no connection @@ -79,6 +80,21 @@ export interface GBrainConfig { * voyage_api_key above. */ dashscope_api_key?: string; + /** + * LiteLLM proxy API key. File-plane slot folded into the gateway env as + * LITELLM_API_KEY (optional in the litellm recipe — proxies may run + * unauthenticated locally). Closed alongside litellm's chat touchpoint + * (v0.42.61.0): once litellm became a full chat provider, daemon/launchd/ + * MCP contexts hit the same config-plane gap voyage did (#2662). Same + * fold pattern (and same DB-plane caveat) as voyage_api_key above. + */ + litellm_api_key?: string; + /** + * Together AI API key. File-plane slot folded into the gateway env as + * TOGETHER_API_KEY (required by the together recipe). Same fold pattern + * (and same DB-plane caveat) as voyage_api_key above. + */ + together_api_key?: string; /** * Google Gemini API key (#3500). File-plane slot folded into the gateway * env as GOOGLE_GENERATIVE_AI_API_KEY (the name the google recipe reads). @@ -654,6 +670,13 @@ export function envShadowDetected(dir: string = process.cwd()): boolean { } export function loadConfig(): GBrainConfig | null { + // #3893 (reimplemented from @y2688): fill process.env from the + // operator-owned ~/.gbrain/.env BEFORE the env-over-file merge below, so + // secrets can live outside config.json. Shell-exported env always wins + // (the loader never overrides an existing var), and cwd .env files stay + // untrusted (#427 guard above). + loadGbrainEnvFile(getConfigDir); + let fileConfig: GBrainConfig | null = null; try { const raw = readFileSync(getConfigPath(), 'utf-8'); @@ -1127,6 +1150,8 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [ 'openrouter_api_key', 'voyage_api_key', 'dashscope_api_key', + 'litellm_api_key', + 'together_api_key', 'google_api_key', 'azure_openai_api_key', 'azure_openai_endpoint', @@ -1329,9 +1354,10 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [ // Misc 'artifacts_sync_mode', 'cross_project_learnings', - // Link resolution (issue #972) + // Link resolution (issue #972; cross_source is issue #2589) 'link_resolution', 'link_resolution.global_basename', + 'link_resolution.cross_source', // Spend controls (v0.42.42.0, issue #2139). Previously `--force`-only — the // operator had to discover these by reading source. Registered so `config // set` accepts them directly. See docs/operations/spend-controls.md. diff --git a/src/core/cycle.ts b/src/core/cycle.ts index 5e37ce51..bb15d340 100644 --- a/src/core/cycle.ts +++ b/src/core/cycle.ts @@ -2097,9 +2097,10 @@ export async function runCycle( }; let lockStolenAbort = false; // Raced variant for the 5 long phases (synthesize / extract_atoms / patterns - // / synthesize_concepts / consolidate): their opts can't carry a signal yet - // (W6), so a steal must be able to stop the WAIT even though the phase's - // in-flight work runs to its own bounded timeout. Steal-free cycles behave + // / synthesize_concepts / consolidate): even where their opts now carry the + // signal (#4077 synthesize/patterns, consolidate), a steal must be able to + // stop the WAIT while the phase unwinds cooperatively; extract_atoms and + // synthesize_concepts still can't carry one (W6). Steal-free cycles behave // byte-identically to timePhase. const racedTimePhase = (fn: () => Promise) => raceStolen(timePhase(fn)); @@ -2245,6 +2246,10 @@ export async function runCycle( // (explicit --source wins, else derived from the checkout dir). sourceId: cycleSourceId, once: opts.onceForPhase === 'synthesize', + // #4077: combined external-abort + lock-steal signal, so a + // cancelled cycle stops judge calls, inline children, and + // derived-state writes instead of running out the grace period. + signal: cycleSignal, // #4168 sibling: clamp child-subagent timeouts to the remaining // job budget (same collision shape as propose_takes, cross-process // timeout domain — clamped via the patterns.ts childBudget template). @@ -2466,6 +2471,8 @@ export async function runCycle( // source owns the page, which is what doctor reports as // multi_source_drift. sourceId: cycleSourceId, + // #4077: same cooperative-cancellation threading as synthesize. + signal: cycleSignal, })); result.duration_ms = duration_ms; phaseResults.push(result); diff --git a/src/core/cycle/extract-atoms.ts b/src/core/cycle/extract-atoms.ts index b236bd49..e0ebe232 100644 --- a/src/core/cycle/extract-atoms.ts +++ b/src/core/cycle/extract-atoms.ts @@ -63,9 +63,9 @@ import { writeReceipt } from '../extract/receipt-writer.ts'; import { upsertExtractRollup } from '../extract/rollup-writer.ts'; import { createHash } from 'crypto'; import { slugifySegment } from '../sync.ts'; +import { resolveTierDefault } from '../model-config.ts'; const DEFAULT_BUDGET_USD = 0.3; -const DEFAULT_EXTRACT_ATOMS_MODEL = 'anthropic:claude-haiku-4-5'; // #4529 + #4540: per-item extractor caps, overridable via // cycle.extract_atoms.* config keys (max_input_chars — with the #4529 // legacy alias max_source_chars — plus max_output_tokens / pacing_ms). @@ -616,7 +616,9 @@ export async function runPhaseExtractAtoms( const failures: Array<{ source: string; error: string }> = []; let estimatedSpendUsd = 0; let budgetExhausted = false; - let extractModel = DEFAULT_EXTRACT_ATOMS_MODEL; + // #3813: key-aware tier default, not a hardcoded Anthropic model — an + // OPENAI_API_KEY-only install must not route to an unservable provider. + let extractModel = resolveTierDefault('utility'); let budgetCap = DEFAULT_BUDGET_USD; // #4529/#4540: the per-item input/output caps were hardcoded (slice(0, 50_000) + // maxTokens: 4096). Operators on small-context or thinking models need to @@ -666,8 +668,8 @@ export async function runPhaseExtractAtoms( if (Number.isFinite(n) && n > 0) pacingMs = Math.min(60_000, Math.floor(n)); } } catch { - // Keep safe defaults on any config-read failure: Haiku model, $0.30 cap, - // default max_source_chars. + // Keep safe defaults on any config-read failure: key-aware utility-tier + // model, $0.30 cap, default max_source_chars. } // A cost cap is only meaningful for a model the tracker can price. // BudgetTracker.reserve() hard-fails with BudgetExhausted(reason:'no_pricing') diff --git a/src/core/cycle/grade-takes.ts b/src/core/cycle/grade-takes.ts index 192ac98f..9387ecd9 100644 --- a/src/core/cycle/grade-takes.ts +++ b/src/core/cycle/grade-takes.ts @@ -410,12 +410,15 @@ export async function defaultEvidenceRetriever( /** * Production judge — calls gateway.chat with the GRADE_TAKE_PROMPT. + * chatFn is injectable so tests can drive the parse path without the gateway + * (mock.module is banned outside *.serial.test.ts); only cycle.ts and tests + * import this module, and both use the default. */ export async function defaultJudge(input: { take: Take; evidence: string; modelHint?: string; -}): Promise { +}, chatFn: typeof gatewayChat = gatewayChat): Promise { const prompt = GRADE_TAKE_PROMPT .replace('{CLAIM}', input.take.claim) .replace('{KIND}', input.take.kind) @@ -424,21 +427,19 @@ export async function defaultJudge(input: { .replace('{WEIGHT}', String(input.take.weight)) .replace('{EVIDENCE_BLOCK}', input.evidence); - const result = await gatewayChat({ + const result = await chatFn({ messages: [{ role: 'user', content: prompt }], ...(input.modelHint ? { model: input.modelHint } : {}), maxTokens: 600, }); const parsed = parseJudgeOutput(result.text); if (!parsed) { - // Failed parse — treat as unresolvable at low confidence so the row - // still lands in the cache (operator sees the LLM's parse failure - // surfaced via warnings) rather than disappearing silently. - return { - verdict: 'unresolvable', - confidence: 0.0, - reasoning: 'judge_output_parse_failed', - }; + // Throw, don't mint a verdict: a synthetic 'unresolvable' row would be + // cached under the deterministic evidence signature and skipped forever, + // indistinguishable from a genuine evidence-based verdict (#3910). The + // per-take catch turns this into a warning and retries next cycle — the + // same policy the loop already applies to thrown judge errors. + throw new Error(`judge output parse failed: unparseable judge response (${result.text.length} chars)`); } return parsed; } diff --git a/src/core/cycle/inline-drain.ts b/src/core/cycle/inline-drain.ts index 2ce192c1..4e885060 100644 --- a/src/core/cycle/inline-drain.ts +++ b/src/core/cycle/inline-drain.ts @@ -42,6 +42,7 @@ import { makeSubagentHandler } from '../minions/handlers/subagent.ts'; import { RateLeaseUnavailableError, leaseFullBackoffMs } from '../minions/rate-leases.ts'; import { reconnectAfterConnectionError } from '../minions/reconnect.ts'; import { isRetryableConnError } from '../retry-matcher.ts'; +import { anySignal, throwIfAborted } from '../abort-check.ts'; import { CYCLE_DEADLINE_RESERVE_MS } from './base-phase.ts'; /** @@ -124,17 +125,22 @@ export async function runSubagentsInline( * loop's LAST claimed child may still overrun the parent by up to its * own clamped timeout. */ deadlineAtMs: number | null = null, + /** #4077: cooperative cancellation from the enclosing cycle/minion job. + * Checked before every claim and combined into ctx.signal so an in-flight + * handler stops too; the current child is cancelled (truthful 'cancelled', + * not dead or a burned delayed retry) before the drain unwinds. */ + signal: AbortSignal | null = null, ): Promise { const n = Math.max(1, Math.floor(concurrency)); if (n === 1) { // Serial fast path: identical semantics to the pre-#4194 drain. - await drainLoop(engine, queue, queueName, yieldDuringPhase, handler, lockMs, 0, null, deadlineAtMs); + await drainLoop(engine, queue, queueName, yieldDuringPhase, handler, lockMs, 0, null, deadlineAtMs, signal); return; } const poolAbort = new AbortController(); const settled = await Promise.allSettled( Array.from({ length: n }, (_, loopIdx) => - drainLoop(engine, queue, queueName, yieldDuringPhase, handler, lockMs, loopIdx, poolAbort, deadlineAtMs)), + drainLoop(engine, queue, queueName, yieldDuringPhase, handler, lockMs, loopIdx, poolAbort, deadlineAtMs, signal)), ); // allSettled (not all): a rejecting loop must not strand siblings' // in-flight children mid-record. The first non-retryable rejection is @@ -153,6 +159,7 @@ async function drainLoop( loopIdx: number, poolAbort: AbortController | null, deadlineAtMs: number | null = null, + signal: AbortSignal | null = null, ): Promise { // #3555 interaction: the drain's queue ops used to be bare awaits, so a // transient pooler reap mid-drain threw out of the loop and stranded the @@ -179,6 +186,9 @@ async function drainLoop( // Shared-abort check: a sibling loop hit a non-retryable failure. Stop // claiming new children; the sibling's rejection carries the cause. if (poolAbort?.signal.aborted) return; + // #4077: external cancellation unwinds the drain — unclaimed children + // stay 'waiting' for the phase finally's reconcilePrivateQueue. + throwIfAborted(signal, '[dream] inline drain'); // #4168 adversarial: stop claiming when the parent budget cannot fit // another child. Already-running work is unaffected; unclaimed // children stay 'waiting' for the caller's cancel-and-defer pass. @@ -256,7 +266,10 @@ async function drainLoop( name: job.name, data: job.data, attempts_made: job.attempts_made, - signal: abort.signal, + // #4077: fold the phase's cancellation into the per-job signal so an + // in-flight handler (mid-LLM-call) stops without waiting for its own + // timeout; `abort` stays the loop-local source for timedOut below. + signal: anySignal(abort.signal, signal), deadlineAtMs: job.timeout_at != null ? job.timeout_at.getTime() : null, shutdownSignal: shutdown.signal, updateProgress: async (progress: unknown) => { @@ -388,6 +401,14 @@ async function drainLoop( ); }; try { + // #4077: external cancellation outranks outcome recording — a child + // stopped by the phase's abort must read 'cancelled', never dead or a + // burned delayed retry. Cancel is best-effort; the phase finally's + // reconcilePrivateQueue is the backstop. + if (signal?.aborted) { + try { await queue.cancelJob(job.id); } catch { /* reconcile backstop */ } + throwIfAborted(signal, '[dream] inline drain'); + } try { await record(); } catch (recordErr) { diff --git a/src/core/cycle/patterns.ts b/src/core/cycle/patterns.ts index 50773be2..3e312548 100644 --- a/src/core/cycle/patterns.ts +++ b/src/core/cycle/patterns.ts @@ -41,10 +41,16 @@ import type { Page, PageType } from '../types.ts'; import { loadAllowedSlugPrefixes, loadOutputRoot, runSubagentsInline } from './synthesize.ts'; import { probeChatModel } from '../ai/gateway.ts'; import { normalizeModelId } from '../model-id.ts'; +import { throwIfAborted } from '../abort-check.ts'; export interface PatternsPhaseOpts { brainDir: string; dryRun: boolean; + /** #4077: cooperative cancellation from the enclosing cycle/minion job. A + * cancelled cycle must stop the inline child and every derived-state + * write instead of running out the force-evict grace. Mirrors + * synthesize.ts's `signal`. */ + signal?: AbortSignal; yieldDuringPhase?: () => Promise; /** * issue #2860 — `gbrain dream --phase patterns --once`. Bypasses the @@ -126,6 +132,7 @@ export async function runPhasePatterns( const start = Date.now(); let ownedPrivateQueue: { queue: MinionQueue; name: string } | null = null; try { + throwIfAborted(opts.signal, '[dream] patterns'); const config = await loadPatternsConfig(engine); if (!config.enabled) { @@ -250,12 +257,18 @@ export async function runPhasePatterns( } throw e; } + // #4077: cancelled between submit and drain — unwind now; the finally's + // reconcilePrivateQueue cancels the just-submitted child. + throwIfAborted(opts.signal, '[dream] patterns subagent'); // Drain this phase's private child queue inline so the parent observes // the terminal state instead of polling waitForCompletion until // subagentWaitTimeoutMs expires. Runs on BOTH engines — on Postgres the // parent job otherwise deadlocks a fully-occupied worker (#2050). - await runSubagentsInline(engine, queue, childQueueName, renewPrivateQueueLease); + await runSubagentsInline( + engine, queue, childQueueName, renewPrivateQueueLease, + undefined, undefined, 1, null, opts.signal ?? null, + ); let outcome: MinionJobStatus | 'timeout'; try { @@ -263,7 +276,11 @@ export async function runPhasePatterns( timeoutMs: budgets.waitTimeoutMs, pollMs: 5 * 1000, renew: renewPrivateQueueLease, + signal: opts.signal, }); + // #4077: on abort the wait returns its last snapshot instead of + // throwing — unwind before treating it as an outcome. + throwIfAborted(opts.signal, '[dream] patterns completion wait'); outcome = final.status; } catch (e) { if (e instanceof TimeoutError) { @@ -291,10 +308,13 @@ export async function runPhasePatterns( // SubagentHandlerData.source_id), so getPage/getTags read the same row the // child wrote, and the reverse-write treats it as the native source. const cycleSourceId = opts.sourceId ?? 'default'; + // #4077: no post-abort derived-state writes (collection is a read, but + // the reverse-write below dual-writes files). + throwIfAborted(opts.signal, '[dream] patterns output'); const writtenRefs = await collectChildPutPageSlugs(engine, [job.id], cycleSourceId); // Reverse-write to fs. - const reverseWriteCount = await reverseWriteRefs(engine, opts.brainDir, writtenRefs, cycleSourceId); + const reverseWriteCount = await reverseWriteRefs(engine, opts.brainDir, writtenRefs, cycleSourceId, opts.signal); const details = { reflections_considered: reflections.length, @@ -557,15 +577,20 @@ async function reverseWriteRefs( brainDir: string, refs: Array<{ slug: string; source_id: string }>, nativeSourceId = 'default', + signal?: AbortSignal, ): Promise { let count = 0; for (const { slug, source_id } of refs) { + throwIfAborted(signal, '[dream] patterns reverse-write'); // v0.32.8 F6: guard against malformed source_id (would let join() break // out of brainDir). validateSourceId throws on `..`, `/`, etc. validateSourceId(source_id); const page = await engine.getPage(slug, { sourceId: source_id }); if (!page) continue; const tags = await engine.getTags(slug, { sourceId: source_id }); + // #4077: re-check after the row reads — an abort that lands during + // getPage/getTags must not reach this ref's file write. + throwIfAborted(signal, '[dream] patterns reverse-write'); try { const md = renderPageToMarkdown(page, tags); // v0.32.8 F6: foreign-source pages land under brainDir/.sources//.md diff --git a/src/core/cycle/synthesize.ts b/src/core/cycle/synthesize.ts index d69ac915..18e45e86 100644 --- a/src/core/cycle/synthesize.ts +++ b/src/core/cycle/synthesize.ts @@ -59,6 +59,7 @@ import { waitForCompletionRenewing, TimeoutError } from '../minions/wait-for-com import type { MinionJobInput, SubagentHandlerData } from '../minions/types.ts'; import { runSubagentsInline, runDrainRenewalTick, percentile, INLINE_LOCK_MS } from './inline-drain.ts'; import { buildManifestContext, buildLinkManifest, type ManifestContext } from './link-manifest.ts'; +import { throwIfAborted } from '../abort-check.ts'; // Re-exports: the drain was peeled to inline-drain.ts (dream-wave C7), the // allow-list loader to filing-rules.ts (#2397); patterns.ts and the @@ -289,6 +290,10 @@ export function rewriteChunkedSlug(slug: string, hash6: string, idx: number): st export interface SynthesizePhaseOpts { brainDir: string; dryRun: boolean; + /** #4077: cooperative cancellation from the enclosing cycle/minion job. A + * cancelled cycle must stop judge calls, inline children, and every + * derived-state write instead of running out the force-evict grace. */ + signal?: AbortSignal; /** Generic in-cycle keepalive for cycle-lock TTL renewal during long waits. */ yieldDuringPhase?: () => Promise; /** @@ -356,6 +361,7 @@ export async function runPhaseSynthesize( opts.brainDir = resolve(opts.brainDir); } try { + throwIfAborted(opts.signal, '[dream] synthesize'); const config = await loadSynthConfig(engine); // #4168 sibling: clamp the child-subagent budgets to the REAL remaining @@ -433,6 +439,16 @@ export async function runPhaseSynthesize( return ok('no transcripts to process', { transcripts_processed: 0, pages_written: 0 }); } + // Best-effort housekeeping (#4069): expiry is enforced on reads + // regardless, so a sweep failure must not block synthesis when the + // database is otherwise usable. + try { + const swept = await engine.sweepDreamVerdicts(); + if (swept > 0) process.stderr.write(`[dream] swept ${swept} expired verdict cache row(s)\n`); + } catch (e) { + process.stderr.write(`[dream] warning: verdict cache sweep failed: ${e instanceof Error ? e.message : String(e)}\n`); + } + // Scored triage (#4152): cached in dream_verdicts, judged on miss by the // utility-tier model through a bounded pool with a wall-clock miss budget. // Provider-aware judge client routes through gateway.chat, so any @@ -446,6 +462,7 @@ export async function runPhaseSynthesize( threshold: config.triage.threshold, concurrency: config.triage.concurrency, maxMs: config.triage.maxMs, + signal: opts.signal, }, opts.yieldDuringPhase); const verdicts = pass.reports; @@ -600,6 +617,9 @@ export async function runPhaseSynthesize( // quota is admission-space; both stop further submits this run). const budgetExhaustedDeferrals: string[] = []; for (const t of worthProcessing) { + // #4077: never submit new children after cancellation; the finally's + // reconcilePrivateQueue cancels anything already submitted. + throwIfAborted(opts.signal, '[dream] synthesize fan-out'); if (quotaHit) { skipReports.push({ filePath: t.filePath, reason: 'admission_quota: submission stopped this run' }); continue; @@ -874,6 +894,7 @@ export async function runPhaseSynthesize( await runSubagentsInline( engine, queue, childQueueName, renewPrivateQueueLease, undefined, undefined, effectiveConcurrency, opts.deadlineAtMs ?? null, + opts.signal ?? null, ); // Captured HERE: everything after this line (waiters, collection, // provenance, reverse-writes, backfill) is post-drain phase work and must @@ -912,7 +933,12 @@ export async function runPhaseSynthesize( timeoutMs: Math.min(config.subagentWaitTimeoutMs, remainingParentMs), pollMs: 5 * 1000, renew: renewPrivateQueueLease, + signal: opts.signal, }); + // #4077: on abort the wait returns its last snapshot instead of + // throwing — unwind before recording a non-terminal status as an + // outcome (finally cancels the still-live children). + throwIfAborted(opts.signal, '[dream] synthesize completion wait'); // Turn telemetry: surfaces max_turns cap pressure in details.synthesis // so the 30→16 default can be re-litigated on data. #4216 adds the // execution-path markers so operators see oneshot vs fallback mix. @@ -955,10 +981,10 @@ export async function runPhaseSynthesize( // of every child-written page BEFORE reverse-rendering, so generated pages // are queryable (`frontmatter->>'dream_generated'`) and a later put_page // write-through (which re-renders from the DB row) can't erase the stamp. - await stampDreamProvenance(engine, writtenRefs, summaryDate); + await stampDreamProvenance(engine, writtenRefs, summaryDate, opts.signal); // Dual-write: reverse-render each DB row → markdown file. - const reverseWriteCount = await reverseWriteRefs(engine, opts.brainDir, writtenRefs, cycleSourceId); + const reverseWriteCount = await reverseWriteRefs(engine, opts.brainDir, writtenRefs, cycleSourceId, opts.signal); // Summary index page (deterministic; orchestrator-written via direct // engine.putPage so no allow-list path needed). @@ -966,9 +992,13 @@ export async function runPhaseSynthesize( // Back-compat: writeSummaryPage takes string[] for display; map refs back to slugs. const writtenSlugs = writtenRefs.map(r => r.slug); if (SUMMARY_SLUG_RE.test(summarySlug)) { - await writeSummaryPage(engine, opts.brainDir, summarySlug, summaryDate, writtenSlugs, childOutcomes, cycleSourceId); + await writeSummaryPage(engine, opts.brainDir, summarySlug, summaryDate, writtenSlugs, childOutcomes, cycleSourceId, opts.signal); } + // #4077: nothing below runs for a cancelled cycle — no phase-end embed + // spend, no cooldown stamp (the next run must retry these transcripts). + throwIfAborted(opts.signal, '[dream] synthesize completion'); + // CDX-8: deferred-embed closure. Oneshot children write chunks with // `embedding IS NULL`; the global `embed` phase only runs on SOME // invocation shapes (autopilot per-source cycles run NON_GLOBAL_PHASES, @@ -1511,9 +1541,10 @@ async function checkCooldown( // ── Significance judge (gateway-routed; provider-agnostic) ────────────── // -// The JudgeClient interface is unchanged for test-seam stability — existing -// tests that pass a mock client to judgeSignificance keep working byte- -// identically. Only the construction path moved from `new Anthropic()` to +// The JudgeClient interface keeps the legacy create(params) call shape for +// test-seam stability — existing mocks keep working (the options bag is +// optional, #4077 cooperative cancellation). Only the construction path +// moved from `new Anthropic()` to // `gateway.chat()` so any provider with a registered recipe (Anthropic, // DeepSeek, OpenRouter, Voyage, Ollama, llama-server, etc.) is reachable // via `gbrain config set models.dream.synthesize_verdict :`. @@ -1525,7 +1556,10 @@ async function checkCooldown( // for AIConfigError surfacing mid-run. export interface JudgeClient { - create: (params: Anthropic.MessageCreateParamsNonStreaming) => Promise; + create: ( + params: Anthropic.MessageCreateParamsNonStreaming, + options?: { signal?: AbortSignal }, + ) => Promise; } /** @@ -1563,7 +1597,7 @@ export function makeJudgeClient(verdictModel: string): JudgeClient | null { if (v.parsed.providerId === 'anthropic' && !hasAnthropicKey()) return null; return { - create: async (params): Promise => { + create: async (params, options): Promise => { // Map Anthropic.MessageCreateParamsNonStreaming → gateway.ChatOpts. // `judgeSignificance` always sends string content + string system, // and the adapter only TEXT-flattens the array-of-blocks shape — @@ -1590,6 +1624,16 @@ export function makeJudgeClient(verdictModel: string): JudgeClient | null { system, messages, maxTokens: params.max_tokens, + // DeepSeek v4 thinks by default and bills reasoning as OUTPUT tokens + // against max_tokens (recipe thinking_by_default, #4172). The judge + // wants only the small JSON verdict, so pin thinking off per-call — + // the openai-compatible adapter spreads providerOptions[recipe.id] + // into the wire body, where `thinking` is DeepSeek's documented knob. + ...(v.parsed.providerId === 'deepseek' + ? { providerOptions: { deepseek: { thinking: { type: 'disabled' } } } } + : {}), + // #4077: a cancelled cycle tears down the in-flight judge call too. + abortSignal: options?.signal, }); // Map gateway.ChatResult → Anthropic.Message shape. judgeSignificance @@ -1719,7 +1763,7 @@ export async function judgeSignificance( client: JudgeClient, t: DiscoveredTranscript, verdictModel = 'claude-haiku-4-5-20251001', - opts: { maxChars?: number; maxTokens?: number } = {}, + opts: { maxChars?: number; maxTokens?: number; signal?: AbortSignal } = {}, ): Promise { const maxChars = Math.max(1000, opts.maxChars ?? DEFAULT_TRIAGE_MAX_CHARS); const { text: trimmed, sampledPct } = buildTriageSample(t.content, maxChars); @@ -1763,7 +1807,7 @@ two reasons. Quote verbatim; never paraphrase inside "quote".`; max_tokens: opts.maxTokens ?? DEFAULT_TRIAGE_MAX_TOKENS, system: sys, messages: [{ role: 'user', content: `Transcript ${t.basename}:\n\n${trimmed}` }], - }); + }, { signal: opts.signal }); // stop_reason === 'max_tokens' means the response was cut off; 'refusal' // means the model refused or a content filter blocked it. Even if a @@ -1941,6 +1985,9 @@ export interface TriagePassCfg { concurrency: number; /** Wall-clock budget (ms) for cache-MISS judging; 0 = unlimited. Hits are always free. */ maxMs: number; + /** #4077: cooperative cancellation — no new judge pulls, no post-abort + * dream_verdicts writes; the abort unwinds the pass (phase fails). */ + signal?: AbortSignal; /** Retriage: ignore the cache entirely. */ force?: boolean; /** Retriage --since: cached rows judged before this instant are stale (re-judged). */ @@ -2088,12 +2135,16 @@ export async function runTriagePass( }; return; } + // #4077: never START a judge call after cancellation; the in-flight call + // below rides the same signal via the gateway's abortSignal. + throwIfAborted(cfg.signal, '[dream] significance judge'); try { let triage: TriageResult; try { triage = await judgeSignificance(judge, t, cfg.model, { maxChars: cfg.maxChars, maxTokens: cfg.maxTokens, + signal: cfg.signal, }); } finally { // Spend accounting (outside-voice CX3): the paid call happened whether @@ -2125,6 +2176,9 @@ export async function runTriagePass( }; return; } + // #4077: a cancelled cycle must not bank new dream_verdicts rows for + // work it is abandoning — the next run re-judges from a clean slate. + throwIfAborted(cfg.signal, '[dream] significance judge'); await engine.putDreamVerdict(t.filePath, t.contentHash, { worth_processing: triage.worth_processing, reasons: triage.reasons, @@ -2560,10 +2614,14 @@ async function stampDreamProvenance( engine: BrainEngine, refs: Array<{ slug: string; source_id: string; raw_source?: string }>, cycleDate: string, + signal?: AbortSignal, ): Promise { if (refs.length === 0) return; const { executeRawJsonb } = await import('../sql-query.ts'); for (const { slug, source_id, raw_source } of refs) { + // #4077: per-row abort check — the per-row try below is only for stamp + // failures and must not swallow the cancellation unwind. + throwIfAborted(signal, '[dream] synthesize provenance'); try { await executeRawJsonb( engine, @@ -2594,14 +2652,19 @@ async function reverseWriteRefs( brainDir: string, refs: Array<{ slug: string; source_id: string }>, nativeSourceId = 'default', + signal?: AbortSignal, ): Promise { let count = 0; for (const { slug, source_id } of refs) { + throwIfAborted(signal, '[dream] synthesize reverse-write'); // v0.32.8 F6: validate source_id is filesystem-safe before any join(). validateSourceId(source_id); const page = await engine.getPage(slug, { sourceId: source_id }); if (!page) continue; const tags = await engine.getTags(slug, { sourceId: source_id }); + // #4077: re-check after the row reads — an abort that lands during + // getPage/getTags must not reach this ref's file write. + throwIfAborted(signal, '[dream] synthesize reverse-write'); try { const md = renderPageToMarkdown(page, tags); // v0.32.8 F6: foreign-source pages land at brainDir/.sources//.md @@ -2656,7 +2719,9 @@ async function writeSummaryPage( writtenSlugs: string[], childOutcomes: Array<{ jobId: number; status: string }>, sourceId = 'default', + signal?: AbortSignal, ): Promise { + throwIfAborted(signal, '[dream] synthesize summary'); const completed = childOutcomes.filter(c => c.status === 'completed').length; const failed = childOutcomes.length - completed; diff --git a/src/core/engine-errors.ts b/src/core/engine-errors.ts new file mode 100644 index 00000000..6da900bc --- /dev/null +++ b/src/core/engine-errors.ts @@ -0,0 +1,32 @@ +/** + * Typed engine errors shared by both engine implementations. Lives outside + * engine.ts (the interface module) for the same circular-import reason as + * engine-constants.ts. + * + * #4109: the graph mutations (addLink / addTimelineEntry) resolve their page + * endpoints inside the mutation statement, so a miss must identify WHICH + * endpoint failed. The operations layer reclassifies these misses into the + * caller-facing error envelope (permission_denied vs page_not_found) by + * `instanceof` — never by message-prefix matching, which silently stops + * firing when a message is reworded. The message is built HERE so both + * engines stay in lockstep parity by construction. + */ + +/** Which page reference a mutation failed to resolve. `page` = single-slug ops. */ +export type PageMissEndpoint = 'from' | 'to' | 'page'; + +export class PageMissingError extends Error { + constructor( + public readonly operation: 'addLink' | 'addTimelineEntry', + public readonly endpoint: PageMissEndpoint, + public readonly slug: string, + public readonly sourceId: string, + ) { + super( + operation === 'addTimelineEntry' + ? `addTimelineEntry failed: page "${slug}" (source=${sourceId}) not found` + : `addLink failed: ${endpoint} page "${slug}" (source=${sourceId}) not found`, + ); + this.name = 'PageMissingError'; + } +} diff --git a/src/core/engine.ts b/src/core/engine.ts index b099f318..c74aeae4 100644 --- a/src/core/engine.ts +++ b/src/core/engine.ts @@ -463,6 +463,14 @@ export interface DreamVerdict { triage_version: number | null; } +/** + * Lifetime of a cached dream verdict (#4069). `triage_version`/`model` already + * invalidate rows semantically; this is the TEMPORAL bound — rows for deleted + * or re-hashed transcripts age out, long-lived transcripts re-judge at this + * cadence. Mirrored by the '30 days' defaults in migration v138 + schema.sql. + */ +export const DREAM_VERDICT_TTL_SECONDS = 30 * 86400; + /** Input shape for putDreamVerdict — judged_at defaults to now() server-side. */ export interface DreamVerdictInput { worth_processing: boolean; @@ -582,6 +590,15 @@ export interface FactListOpts { * are returned. Remote (untrusted) callers must supply ['world']. */ visibility?: FactVisibility[]; + /** + * Case-insensitive substring filter on fact text, applied IN SQL (before + * limit). A client-side post-limit grep silently returns nothing for + * high-cardinality entities — the match may sit outside the newest-N + * window (found by the 2026-08-06 memory eval on an entity with hundreds + * of facts). LIKE wildcards in the needle are escaped; plain substring + * semantics only. + */ + grep?: string; /** * When true, `listFactsSince`'s `since` comparison and ORDER BY use * COALESCE(valid_from, created_at) — event time — instead of creation @@ -1474,11 +1491,12 @@ export interface BrainEngine { opts?: RelationalFanoutOpts, ): Promise; /** - * For a list of slugs, return how many inbound links each has. + * For a list of page ids, return how many inbound links each has. * Used by hybrid search backlink boost. Single SQL query, not N+1. - * Slugs with zero inbound links are present in the map with value 0. + * Keyed by page id — NOT slug — so namesake slugs across sources never + * share or sum counts (#4380). Ids with zero links map to 0. */ - getBacklinkCounts(slugs: string[]): Promise>; + getBacklinkCounts(pageIds: number[]): Promise>; /** * v0.40.4 — for a list of page_ids, return adjacency aggregates * restricted to the subgraph induced by them. Returns ALL pages with @@ -1824,6 +1842,11 @@ export interface BrainEngine { // page-scoped — transcripts being judged aren't pages yet. getDreamVerdict(filePath: string, contentHash: string): Promise; putDreamVerdict(filePath: string, contentHash: string, verdict: DreamVerdictInput): Promise; + /** + * Delete expired dream verdicts; returns rows removed. Best-effort + * housekeeping — reads already treat expired rows as misses (#4069). + */ + sweepDreamVerdicts(): Promise; // ============================================================ // v0.32.6 Contradiction probe — batched takes fetch + cache + trends diff --git a/src/core/entities/resolve.ts b/src/core/entities/resolve.ts index 288b458f..2e219e88 100644 --- a/src/core/entities/resolve.ts +++ b/src/core/entities/resolve.ts @@ -152,7 +152,13 @@ function isBareName(raw: string): boolean { return true; } -const PREFIX_EXPANSION_DIRS = ['people', 'companies'] as const; +// hosts/projects joined people/companies after the 2026-08-06 memory eval: a +// bare infra token ("hive") fell through to slugify and recall returned +// nothing while the canonical hosts/ page + its facts sat one prefix +// away. `infra/` is deliberately NOT here — it is a mixed namespace of +// analysis/runbook documents (`infra/hive-dependency-audit-…`), and any such +// doc would trip the ambiguity gate and re-break bare-token resolution. +const PREFIX_EXPANSION_DIRS = ['people', 'companies', 'hosts', 'projects'] as const; /** * v0.40.2.0 — resolution-source-tagged variant for trajectory routing. diff --git a/src/core/eval-contradictions/runner.ts b/src/core/eval-contradictions/runner.ts index 14fd9028..5be212f7 100644 --- a/src/core/eval-contradictions/runner.ts +++ b/src/core/eval-contradictions/runner.ts @@ -34,6 +34,7 @@ import { CostTracker, estimateUpperBoundCost } from './cost-tracker.ts'; import { buildSourceTierBreakdown, classifySlugTier } from './cross-source.ts'; import { shouldSkipForDateMismatch } from './date-filter.ts'; import { withBudgetTracker } from '../ai/gateway.ts'; +import { resolveTierDefault } from '../model-config.ts'; import { BudgetTracker, BudgetExhausted } from '../budget/budget-tracker.ts'; import { judgeContradiction, type JudgeInput, type JudgeOutput } from './judge.ts'; import { JudgeErrorCollector } from './judge-errors.ts'; @@ -54,7 +55,6 @@ import { } from './types.ts'; const DEFAULT_TOP_K = 5; -const DEFAULT_JUDGE_MODEL = 'anthropic:claude-haiku-4-5'; const DEFAULT_MAX_PAIR_CHARS = 1500; /** Caller-supplied judge function signature; defaults to judgeContradiction. */ @@ -270,7 +270,10 @@ export async function runContradictionProbe(opts: RunnerOpts): Promise { const startedAt = Date.now(); - const judgeModel = opts.judgeModel ?? DEFAULT_JUDGE_MODEL; + // #3813: key-aware tier default, not a hardcoded Anthropic model — an + // OPENAI_API_KEY-only install must not route the judge to an unservable + // provider. + const judgeModel = opts.judgeModel ?? resolveTierDefault('utility'); const topK = Math.max(1, opts.topK ?? DEFAULT_TOP_K); const sampling = opts.sampling ?? 'deterministic'; const budgetUsd = opts.budgetUsd ?? 5.0; diff --git a/src/core/facts/backstop.ts b/src/core/facts/backstop.ts index 26e6fa2d..af05f9c2 100644 --- a/src/core/facts/backstop.ts +++ b/src/core/facts/backstop.ts @@ -38,6 +38,7 @@ */ import type { BrainEngine, FactInsertStatus, NewFact } from '../engine.ts'; +import type { ResolutionSource } from '../entities/resolve.ts'; import { isFactsBackstopEligible } from './eligibility.ts'; import type { PageType } from '../types.ts'; @@ -479,7 +480,8 @@ async function runPipeline( * * Pipeline: * 1. extract (extractFactsFromTurn — sanitize + LLM + parser) - * 2. resolve (resolveEntitySlug — canonicalize free-form entity refs) + * 2. resolve (resolveEntitySlugWithSource — canonicalize free-form entity + * refs, provenance-tagged for the #4108 stub guard) * 3. dedup (findCandidateDuplicates + cosineSimilarity @ 0.95) * 4. write (writeFactsToFence → markdown atomic write + engine.insertFacts) * @@ -521,7 +523,7 @@ async function runPipelineBodyInner( abortSignal?: AbortSignal, ): Promise<{ inserted: number; duplicate: number; superseded: number; fact_ids: number[]; entity_slugs: string[]; skipped_reason?: import('./extract.ts').ExtractFailureReason }> { const { extractFactsFromTurnWithOutcome, FactsExtractionError } = await import('./extract.ts'); - const { resolveEntitySlug } = await import('../entities/resolve.ts'); + const { resolveEntitySlugWithSource } = await import('../entities/resolve.ts'); const { cosineSimilarity } = await import('./classify.ts'); const { writeFactsToFence, lookupSourceLocalPath } = await import('./fence-write.ts'); @@ -586,6 +588,8 @@ async function runPipelineBodyInner( type SurvivedFact = { f: typeof facts[number]; resolvedSlug: string | null; + // #4108: resolution provenance threaded to the fence writer's stub guard. + resolutionSource: ResolutionSource | null; }; const survived: SurvivedFact[] = []; @@ -595,9 +599,11 @@ async function runPipelineBodyInner( // D4: notability filter applied post-extraction, pre-insert. if (filter === 'high-only' && f.notability !== 'high') continue; - const resolvedSlug = f.entity_slug - ? await resolveEntitySlug(ctx.engine, ctx.sourceId, f.entity_slug) + const resolved = f.entity_slug + ? await resolveEntitySlugWithSource(ctx.engine, ctx.sourceId, f.entity_slug) : null; + const resolvedSlug = resolved?.slug ?? null; + const resolutionSource = resolved?.source ?? null; // Dedup against DB candidates (correct per Codex Q7: fence rows // have no embeddings; FS lock + sync invariant means DB == fence @@ -628,7 +634,7 @@ async function runPipelineBodyInner( continue; } - survived.push({ f, resolvedSlug }); + survived.push({ f, resolvedSlug, resolutionSource }); } if (survived.length === 0) { @@ -734,9 +740,18 @@ async function runPipelineBodyInner( sessionId: f.source_session ?? null, })); + // #4108 fail-closed on mixed provenance: one fallback-minted ref in the + // group means the slug's existence is unproven — block the whole group. + // (byEntity members always resolved non-null, so null here is defensive.) + const groupResolutionSource: ResolutionSource = group.some( + (s) => s.resolutionSource === 'fallback_slugify' || s.resolutionSource == null, + ) + ? 'fallback_slugify' + : group[0].resolutionSource!; + const result = await writeFactsToFence( ctx.engine, - { sourceId: ctx.sourceId, localPath, slug }, + { sourceId: ctx.sourceId, localPath, slug, resolutionSource: groupResolutionSource }, inputFacts, ); @@ -750,12 +765,15 @@ async function runPipelineBodyInner( } if (result.stubGuardBlocked || result.targetUnresolvable) { // v0.34.5: writeFactsToFence refused to spawn a phantom - // unprefixed entity page (e.g. `jared.md` at brain root). - // #4204: or the shared page-target resolver found the source - // tree unusable (deleted dir / hostile source_path row). + // unprefixed entity page (e.g. `jared.md` at brain root) — + // or, #4108, a page for a fallback-resolved slug no live page + // backs. #4204: or the shared page-target resolver found the + // source tree unusable (deleted dir / hostile source_path row). // Route these facts to the legacy DB-only path so they // aren't dropped — the slug stays attached but no markdown - // file is created. + // file is created. This also keeps blocked slugs out of + // fencedSlugs, so fallback-minted slugs never reach the + // entity_slugs checkpoint/link manifests downstream. for (const { f } of group) { const newFact: NewFact = { fact: f.fact, @@ -771,7 +789,7 @@ async function runPipelineBodyInner( valid_from: f.valid_from ?? ctx.validFrom, context: ctx.sourceSlug ?? null, }; - const legacyResult = await ctx.engine.insertFact(newFact, { source_id: ctx.sourceId }); // gbrain-allow-direct-insert: stub-guard / unresolvable-target fallback (no fenceable page or usable tree) + const legacyResult = await ctx.engine.insertFact(newFact, { source_id: ctx.sourceId }); // gbrain-allow-direct-insert: stub-guard / unresolvable-target fallback for unprefixed or fallback-resolved entity slugs (no fenceable page or usable tree) fact_ids.push(legacyResult.id); if (legacyResult.status === 'inserted') inserted += 1; else if ((legacyResult.status as FactInsertStatus) === 'duplicate') duplicate += 1; diff --git a/src/core/facts/fence-write.ts b/src/core/facts/fence-write.ts index 496365b8..5cdefd2e 100644 --- a/src/core/facts/fence-write.ts +++ b/src/core/facts/fence-write.ts @@ -39,6 +39,7 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync, renameSync, appendF import { dirname, isAbsolute, relative } from 'node:path'; import type { BrainEngine, NewFact, FactVisibility } from '../engine.ts'; +import type { ResolutionSource } from '../entities/resolve.ts'; import { inferTypeFromPack } from '../markdown.ts'; import { loadActivePackBestEffort } from '../schema-pack/best-effort.ts'; import { withPageLock } from '../page-lock.ts'; @@ -57,6 +58,15 @@ export interface FenceTarget { localPath: string | null; /** Entity slug — also becomes source_markdown_slug + the file basename. */ slug: string; + /** + * #4108: how `slug` was resolved. REQUIRED (not optional) so no caller can + * silently skip provenance: 'fallback_slugify' and null (resolver returned + * nothing / caller has no resolution step) are blocked from stub-creating a + * page — a fallback-minted slug names an entity nothing verified exists. + * 'exact_page' / 'alias_exact' / 'fuzzy_match' all verified a live page, so + * stub-create (DB↔file drift repair) stays allowed for them. + */ + resolutionSource: ResolutionSource | null; } /** Input fact prepared by runPipelineWithBody (post-dedup). */ @@ -91,12 +101,15 @@ export interface FenceWriteResult { fenceWriteFailed?: true; /** * True when the stub-creation guard refused to spawn a phantom entity - * page for an unprefixed bare slug (e.g. `jared` with no `people/` - * directory). Rows were NOT inserted; the caller is expected to route - * the facts to the legacy DB-only path so they aren't silently dropped. + * page — either for an unprefixed bare slug (e.g. `jared` with no + * `people/` directory), or (#4108) for a slug whose resolutionSource is + * 'fallback_slugify'/null, i.e. a slug the resolver invented rather than + * verified. Rows were NOT inserted; the caller is expected to route the + * facts to the legacy DB-only path so they aren't silently dropped. * - * This is the v0.34.5 fix for the entity-resolution bug where `"Jared"` - * fell through resolution and produced a top-level `jared.md` stub. + * The unprefixed arm is the v0.34.5 fix for the entity-resolution bug + * where `"Jared"` fell through resolution and produced a top-level + * `jared.md` stub. */ stubGuardBlocked?: true; /** @@ -304,32 +317,55 @@ export async function writeFactsToFence( if (existsSync(filePath)) { body = readFileSync(filePath, 'utf-8'); } else { - // Stub-creation guard. Phantom entity pages at the brain root were - // being spawned when resolveEntitySlug fell through to a bare - // slugify because pg_trgm scored too low on short bare names. The - // resolver now has a prefix-expansion step that catches most of - // those, but this guard is the second wall: refuse to stub-create - // a page whose slug has no directory prefix (people/, companies/, - // deals/, topics/, etc.). The caller routes these facts to the - // legacy DB-only path so they aren't silently dropped — the fact - // still gets recorded, it just doesn't spawn a phantom entity - // page on disk. + // Stub-creation guard, two arms: // - // Sunset target: v0.36. Once `stub_guard_24h` (the gbrain doctor - // surface backed by the audit log written here) reads <5 hits/week - // for 3 consecutive weeks on production brains, the prefix-expansion - // in resolveEntitySlug is sufficient and this guard can be removed. - // The audit log under `~/.gbrain/audit/stub-guard-YYYY-Www.jsonl` - // is the operator visibility surface for that retirement decision. - if (!target.slug.includes('/')) { + // 1. Unprefixed slug (v0.34.5). Phantom entity pages at the brain + // root were being spawned when resolveEntitySlug fell through to + // a bare slugify because pg_trgm scored too low on short bare + // names. The resolver now has a prefix-expansion step that + // catches most of those, but this arm is the second wall: refuse + // to stub-create a page whose slug has no directory prefix + // (people/, companies/, deals/, topics/, etc.). + // + // 2. Fallback/absent resolution provenance (#4108). A PREFIXED + // fallback_slugify result (e.g. "companies/zeta-widgets" for an + // entity no page backs) sailed past arm 1 and materialized as a + // canonical stub page; after sync it resolved as exact_page, + // closing a fallback→stub→exact-match feedback loop. Blocklist + // shape on purpose: only 'fallback_slugify' and null are blocked, + // so future ResolutionSource members that verify a live page + // (like v0.46.15's 'alias_exact') fence without touching this. + // + // Either way the caller routes these facts to the legacy DB-only + // path so they aren't silently dropped — the fact still gets + // recorded (entity_slug retained), it just doesn't spawn a phantom + // entity page on disk. + // + // Sunset target: v0.36, for arm 1 ONLY (the 'unprefixed' reason in + // the audit log). Once `stub_guard_24h` (the gbrain doctor surface + // backed by the audit log written here) reads <5 unprefixed + // hits/week for 3 consecutive weeks on production brains, the + // prefix-expansion in resolveEntitySlug is sufficient and arm 1 can + // be removed. Arm 2 does NOT sunset: it is the only wall between + // resolver-invented slugs and canonical page creation, and no + // resolver improvement can retire it (the fallback floor is by + // design). The audit log under + // `~/.gbrain/audit/stub-guard-YYYY-Www.jsonl` is the operator + // visibility surface, with per-arm `reason` fields. + const fallbackResolved = + target.resolutionSource === 'fallback_slugify' || target.resolutionSource == null; + if (!target.slug.includes('/') || fallbackResolved) { logStubGuardEvent({ slug: target.slug, source_id: target.sourceId, fact_count: facts.length, + reason: !target.slug.includes('/') ? 'unprefixed' : 'fallback_resolution', }); // eslint-disable-next-line no-console console.warn( - `[facts] refusing to stub-create unprefixed entity page slug=${target.slug} — routing to legacy DB-only path. Provide a directory prefix (people/, companies/, etc.) to opt into fence writes.`, + !target.slug.includes('/') + ? `[facts] refusing to stub-create unprefixed entity page slug=${target.slug} — routing to legacy DB-only path. Provide a directory prefix (people/, companies/, etc.) to opt into fence writes.` + : `[facts] refusing to stub-create entity page slug=${target.slug} from a fallback-resolved reference (no live page verified) — routing to legacy DB-only path.`, ); return { inserted: 0, ids: [], stubGuardBlocked: true }; } diff --git a/src/core/facts/stub-guard-audit.ts b/src/core/facts/stub-guard-audit.ts index 12ede17b..632a8aa5 100644 --- a/src/core/facts/stub-guard-audit.ts +++ b/src/core/facts/stub-guard-audit.ts @@ -3,11 +3,15 @@ * * Writes one line per stub-guard fire to * `${GBRAIN_AUDIT_DIR:-~/.gbrain/audit}/stub-guard-YYYY-Www.jsonl` - * when `writeFactsToFence` refuses to spawn an unprefixed entity page. The - * audit log is the operator visibility surface for the v0.34.5+ stub guard - * sunset criterion: when this reads <5 hits/week for 3 consecutive weeks - * on production brains, the guard can be removed in v0.36 (the prefix - * expansion in resolveEntitySlug is sufficient). + * when `writeFactsToFence` refuses to spawn an unprefixed entity page + * (reason 'unprefixed') or a page for a fallback-resolved slug (#4108, + * reason 'fallback_resolution'). The audit log is the operator visibility + * surface for the v0.34.5+ stub guard sunset criterion, WHICH APPLIES TO + * THE 'unprefixed' REASON ONLY: when unprefixed reads <5 hits/week for 3 + * consecutive weeks on production brains, that arm can be removed in v0.36 + * (the prefix expansion in resolveEntitySlug is sufficient). The + * 'fallback_resolution' arm never sunsets — it is the only wall between + * resolver-invented slugs and canonical page creation. * * Best-effort: write failures go to stderr and never block the legacy DB-only * fallback path. A disk-full attacker could silently disable the trail. @@ -42,6 +46,11 @@ export interface StubGuardEvent { source_id: string; /** How many facts were in the rejected batch (informational). */ fact_count: number; + /** + * Which guard arm fired (#4108). Optional: pre-#4108 lines have no reason + * and are counted as 'unprefixed' (the only arm that existed then). + */ + reason?: 'unprefixed' | 'fallback_resolution'; } /** diff --git a/src/core/facts/write-single.ts b/src/core/facts/write-single.ts index 58ef5199..339998db 100644 --- a/src/core/facts/write-single.ts +++ b/src/core/facts/write-single.ts @@ -33,7 +33,7 @@ export interface SingleFactInput { /** Free-text attribution, stored verbatim as the fact's `source`. */ provenance: string; kind?: NewFact['kind']; - /** Free-form entity ref; canonicalized via resolveEntitySlug. */ + /** Free-form entity ref; canonicalized via resolveEntitySlugWithSource. */ entity?: string | null; /** Facts-layer default 'private'; the remember VERB passes 'world' [F2]. */ visibility?: 'private' | 'world'; @@ -56,7 +56,7 @@ export async function writeSingleFact( sourceId: string, input: SingleFactInput, ): Promise { - const { resolveEntitySlug } = await import('../entities/resolve.ts'); + const { resolveEntitySlugWithSource } = await import('../entities/resolve.ts'); const { cosineSimilarity } = await import('./classify.ts'); const { writeFactsToFence, lookupSourceLocalPath } = await import('./fence-write.ts'); const { isAvailable, embedOne } = await import('../ai/gateway.ts'); @@ -66,9 +66,13 @@ export async function writeSingleFact( const visibility = input.visibility ?? 'private'; const validUntil = input.validUntil ?? null; - const resolvedSlug = input.entity - ? ((await resolveEntitySlug(engine, sourceId, input.entity)) ?? input.entity) + const resolved = input.entity + ? await resolveEntitySlugWithSource(engine, sourceId, input.entity) : null; + const resolvedSlug = input.entity ? (resolved?.slug ?? input.entity) : null; + // #4108: provenance for the fence writer's stub guard. Null when the + // resolver returned nothing (fail-closed — no live page was verified). + const resolutionSource = resolved?.source ?? null; // Embedding (NOT an LLM call): powers dedup + downstream recall. Fail-soft — // a missing/failing provider degrades dedup, never the write. @@ -139,7 +143,7 @@ export async function writeSingleFact( if (fenceable) { const result = await writeFactsToFence( engine, - { sourceId, localPath, slug: resolvedSlug }, + { sourceId, localPath, slug: resolvedSlug, resolutionSource }, [ { fact: factText, diff --git a/src/core/gbrain-env-file.ts b/src/core/gbrain-env-file.ts new file mode 100644 index 00000000..b879f80b --- /dev/null +++ b/src/core/gbrain-env-file.ts @@ -0,0 +1,57 @@ +/** + * ~/.gbrain/.env secrets loader (#3893, reimplemented from @y2688's + * community PR). + * + * Bun only auto-loads `.env` from the process cwd, which for a globally + * installed CLI is arbitrary — and cwd .env files are UNTRUSTED input (the + * #427 DATABASE_URL-hijack guard in config.ts exists because of them). The + * gbrain home directory is operator-owned, so `~/.gbrain/.env` is a + * deliberate place to keep API keys OUT of config.json. loadConfig() calls + * this before its env-over-file merge; a variable the shell already + * exported is NEVER overridden, so real env keeps absolute precedence. + */ +import { existsSync, readFileSync } from 'fs'; +import { join } from 'path'; + +// KEY=VALUE with a POSIX-shaped name. `export KEY=...` is deliberately not +// accepted: this is an env FILE, not a shell script (same stance as Bun's +// own .env loader). +const ASSIGNMENT = /^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/; + +/** + * Parse `/.env` and fill process.env with its assignments. + * + * `resolveDir` is a thunk (not a precomputed string) so an invalid + * GBRAIN_HOME — configDir() throws on relative or `..` paths — stays inside + * this function's catch instead of turning loadConfig into a throw site. + */ +export function loadGbrainEnvFile(resolveDir: () => string): void { + try { + const envPath = join(resolveDir(), '.env'); + if (!existsSync(envPath)) return; + const raw = readFileSync(envPath, 'utf-8'); + for (const rawLine of raw.split('\n')) { + const line = rawLine.trim(); + if (!line || line.startsWith('#')) continue; + const m = line.match(ASSIGNMENT); + if (!m) continue; + const key = m[1]!; + let value = (m[2] ?? '').trim(); + const quoted = + (value.startsWith('"') && value.endsWith('"') && value.length >= 2) || + (value.startsWith("'") && value.endsWith("'") && value.length >= 2); + if (quoted) { + value = value.slice(1, -1); + } else { + // Unquoted values may carry a trailing inline comment. + const hash = value.indexOf(' #'); + if (hash !== -1) value = value.slice(0, hash).trim(); + } + // Shell-exported env always wins; empty values never land. + if (value && !(key in process.env)) process.env[key] = value; + } + } catch { + // The file is optional — missing, unreadable, or an invalid home dir + // must not break config loading. + } +} diff --git a/src/core/import-file.ts b/src/core/import-file.ts index 41aaeab1..2df510d1 100644 --- a/src/core/import-file.ts +++ b/src/core/import-file.ts @@ -577,8 +577,11 @@ export async function importFromContent( logContentSanityAssessment(slug, sourceId ?? 'default', sanityResult, { disposition: 'soft_block', }); - process.stderr.write( - `[gbrain] content-sanity flag (oversized): ${slug} (${sanityResult.bytes} bytes) — page lands, embedding skipped, agent warned\n`, + // #3893 (reimplemented from @y2688): console.warn, not bare stderr — + // soft_block silently drops embedding, and console-level warns are + // what operator log hooks and collectors can observe. + console.warn( + `[gbrain] content-sanity flag (oversized): ${slug} (${sanityResult.bytes} bytes) — page lands, embedding skipped, agent warned`, ); } else { // markup_heavy: page ingests NORMALLY (keeps chunks, embeds). The @@ -1858,10 +1861,11 @@ async function readExifSafe(buf: Buffer): Promise> { } /** - * Cherry-1 OCR: optional gpt-4o-mini pass extracting visible text from an + * Cherry-1 OCR: optional vision-model pass extracting visible text from an * image. Returns '' when: * - the embedding_image_ocr config flag is off (default) - * - the configured expansion model is unavailable (no API key) + * - the configured OCR model (embedding_image_ocr_model, else the expansion + * model — #4107) is unavailable (no API key / no expansion touchpoint) * - the OCR call itself fails (logged once per session) * - the per-run OCR budget is exhausted (#3973 — see _ocrRunBudget below) * @@ -1974,10 +1978,14 @@ async function maybeOcrGated( await bump('ocr_attempted'); try { - const { isAvailable, generateOcrText } = await import('./ai/gateway.ts'); - if (!isAvailable('expansion')) { + const { isAvailable, generateOcrText, getImageOcrModel } = await import('./ai/gateway.ts'); + // getImageOcrModel throws on an unconfigured gateway; count that as + // no-key (the pre-#4107 isAvailable gate returned false there). + let ocrModel: string | null = null; + try { ocrModel = getImageOcrModel(); } catch { /* unconfigured gateway */ } + if (!ocrModel || !isAvailable('expansion', ocrModel)) { if (!_ocrWarnedThisSession) { - console.warn('[gbrain] OCR opt-in is true but expansion model is unavailable; skipping OCR for this session'); + console.warn(`[gbrain] OCR opt-in is true but the OCR model (${ocrModel ?? 'gateway unconfigured'}) is unavailable; skipping OCR for this session`); _ocrWarnedThisSession = true; } await bump('ocr_failed_no_key'); diff --git a/src/core/link-extraction.ts b/src/core/link-extraction.ts index 98d205aa..9e0a94e5 100644 --- a/src/core/link-extraction.ts +++ b/src/core/link-extraction.ts @@ -1679,3 +1679,40 @@ export async function isGlobalBasenameEnabled(engine: BrainEngine): Promise { + const envVal = process.env.GBRAIN_LINK_RESOLUTION_CROSS_SOURCE; + if (envVal != null) { + const normalized = envVal.trim().toLowerCase(); + return ['1', 'true', 'yes', 'on'].includes(normalized); + } + const val = await engine.getConfig('link_resolution.cross_source'); + if (val == null) return false; + const normalized = val.trim().toLowerCase(); + return ['1', 'true', 'yes', 'on'].includes(normalized); +} diff --git a/src/core/migrate.ts b/src/core/migrate.ts index e20611c3..40ebafd8 100644 --- a/src/core/migrate.ts +++ b/src/core/migrate.ts @@ -6259,6 +6259,36 @@ export const MIGRATIONS: Migration[] = [ process.stderr.write(` v142: takes.embedding resized to vector(${embeddingDim}); existing take vectors cleared\n`); }, }, + { + // Train port: renumbered 138 -> 142 -> 143 (wave-k pass 1 appended + // v138-v141 on the branch, then master consumed v142 for the + // takes-embedding resize above; LATEST_VERSION is Math.max so only the + // duplicate id needed fixing). Guarded DDL below is idempotent, so a + // brain that ran the branch's v142 spelling records v143 as a no-op. + version: 143, + name: 'dream_verdicts_ttl', + // #4069 (reimplemented): 30-day TTL on the significance-verdict cache. + // `triage_version`/`model` (v129) already invalidate rows semantically, + // but nothing ever DELETED rows — verdicts for deleted or re-hashed + // transcripts lived forever. Reads treat expired rows as misses (so + // long-lived transcripts re-judge at a 30-day cadence, refreshing the + // TTL) and runPhaseSynthesize sweeps expired rows best-effort. Backfill + // derives expiry from judged_at so pre-TTL rows keep their original age + // instead of gaining a fresh 30 days. The interval literal mirrors + // DREAM_VERDICT_TTL_SECONDS (engine.ts) and the schema.sql default. + idempotent: true, + sql: ` + ALTER TABLE dream_verdicts ADD COLUMN IF NOT EXISTS expires_at TIMESTAMPTZ; + UPDATE dream_verdicts + SET expires_at = judged_at + interval '30 days' + WHERE expires_at IS NULL; + ALTER TABLE dream_verdicts + ALTER COLUMN expires_at SET DEFAULT (now() + interval '30 days'), + ALTER COLUMN expires_at SET NOT NULL; + CREATE INDEX IF NOT EXISTS dream_verdicts_expires_idx + ON dream_verdicts (expires_at); + `, + }, ]; export const LATEST_VERSION = MIGRATIONS.length > 0 diff --git a/src/core/model-config.ts b/src/core/model-config.ts index 0d913dc3..9bbfff82 100644 --- a/src/core/model-config.ts +++ b/src/core/model-config.ts @@ -64,7 +64,13 @@ export const DEFAULT_ALIASES: Record = { opus: 'anthropic:claude-opus-4-7', sonnet: 'anthropic:claude-sonnet-4-6', haiku: 'anthropic:claude-haiku-4-5-20251001', - gemini: 'google:gemini-3-pro', + // `gemini` repointed (#2507): `gemini-3-pro` only ever existed as a preview + // id (`gemini-3-pro-preview`) and was shut down — it was never chat-listed + // in the google recipe nor priced. 2.5-flash is the recipe's chat models[0]; + // there is NO GA pro-class Gemini chat target today, so the alias + // deliberately sits a capability class below the opus convention until + // Google ships a GA pro. Guarded by test/default-alias-liveness.test.ts. + gemini: 'google:gemini-2.5-flash', // `gpt` resolves DYNAMICALLY in resolveAlias (account-discovered OpenAI // flagship, recipe-ranked static floor) — this entry keeps the alias // enumerable but the value here is only the documentation floor; a pinned diff --git a/src/core/ops/code-intel.ts b/src/core/ops/code-intel.ts index 8d1ed69a..29f2c034 100644 --- a/src/core/ops/code-intel.ts +++ b/src/core/ops/code-intel.ts @@ -9,7 +9,7 @@ */ import type { Operation } from './contract.ts'; -import { resolveCodeIntelScope } from './context.ts'; +import { routeCodeIntelScope } from './context.ts'; import { CODE_CALLERS_DESCRIPTION, CODE_CALLEES_DESCRIPTION, @@ -45,9 +45,10 @@ const code_callers: Operation = { const symbol = p.symbol as string; const limit = (p.limit as number) ?? 100; const sourceIdParam = typeof p.source_id === 'string' ? p.source_id : undefined; - // Single trust+grant resolver: remote callers can't span sources outside - // their grant, and `__all__` collapses to their grant (not the whole brain). - const { allSources, sourceId } = resolveCodeIntelScope(ctx, sourceIdParam, p.all_sources === true); + // Single trust+grant resolver + federated code-source re-route (see + // routeCodeIntelScope): remote callers can't span sources outside their + // grant, and `__all__` collapses to their grant (not the whole brain). + const { allSources, sourceId } = await routeCodeIntelScope(ctx, sourceIdParam, p.all_sources === true); const edges = await ctx.engine.getCallersOf(symbol, { limit, allSources, @@ -83,8 +84,8 @@ const code_callees: Operation = { const symbol = p.symbol as string; const limit = (p.limit as number) ?? 100; const sourceIdParam = typeof p.source_id === 'string' ? p.source_id : undefined; - // Single trust+grant resolver (see code_callers). - const { allSources, sourceId } = resolveCodeIntelScope(ctx, sourceIdParam, p.all_sources === true); + // Single trust+grant resolver + federated re-route (see code_callers). + const { allSources, sourceId } = await routeCodeIntelScope(ctx, sourceIdParam, p.all_sources === true); const edges = await ctx.engine.getCalleesOf(symbol, { limit, allSources, @@ -175,7 +176,7 @@ const code_blast: Operation = { // source outside its grant (pre-fix this scoped by bare ctx.sourceId only). // Falls back to ctx.sourceId (a required string) for the trusted-local case, // exactly preserving pre-fix local behavior. - const { sourceId: scopedSourceId } = resolveCodeIntelScope(ctx, typeof p.source_id === 'string' ? p.source_id : undefined); + const { sourceId: scopedSourceId } = await routeCodeIntelScope(ctx, typeof p.source_id === 'string' ? p.source_id : undefined); const sourceId = scopedSourceId ?? ctx.sourceId; return getCachedOrCompute( ctx.engine, @@ -211,7 +212,7 @@ const code_flow: Operation = { const max_nodes = Math.min((p.max_nodes as number) ?? 200, 200); const exact = (p.exact as boolean) ?? false; // Single trust+grant resolver (see code_blast). - const { sourceId: scopedSourceId } = resolveCodeIntelScope(ctx, typeof p.source_id === 'string' ? p.source_id : undefined); + const { sourceId: scopedSourceId } = await routeCodeIntelScope(ctx, typeof p.source_id === 'string' ? p.source_id : undefined); const sourceId = scopedSourceId ?? ctx.sourceId; return getCachedOrCompute( ctx.engine, diff --git a/src/core/ops/context.ts b/src/core/ops/context.ts index 4bf009a8..d77954ad 100644 --- a/src/core/ops/context.ts +++ b/src/core/ops/context.ts @@ -599,6 +599,81 @@ export function federatedSearchScope( return scope; } +/** + * #4109 — preflight a page endpoint for a same-source graph mutation + * (add_link / add_timeline_entry). + * + * These ops intentionally write only to `ctx.sourceId`, while page reads may + * span the caller's federated visibility scope. When the requested slug + * exists only in another READABLE source, report that source boundary + * explicitly (`permission_denied`) instead of the misleading "not found" the + * engine's exact-source resolution emits — which surfaced over MCP as + * `internal_error` and made intentional source isolation look like data + * loss. Sources outside the caller's read grant remain indistinguishable + * from absence: the diagnostic lookup uses `federatedSearchScope`, the SAME + * visibility ladder as `get_page`, so this preflight can never become a + * cross-source existence oracle. + */ +export async function requireWritablePage( + ctx: OperationContext, + slug: string, + operation: string, + endpoint: 'from' | 'to' | 'page', +): Promise { + const writeSource = ctx.sourceId || 'default'; + // Graph rows may reference soft-deleted pages — includeDeleted preserves + // that engine mutation contract for the exact write source. The federated + // diagnostic lookup below intentionally stays active-page-only so a + // soft-deleted foreign page is never disclosed. + const writable = await ctx.engine.getPage(slug, { + sourceId: writeSource, + includeDeleted: true, + }); + if (writable) return; + + const visibleScope = federatedSearchScope(ctx); + const spansAnotherSource = + (visibleScope.sourceIds?.some((sourceId) => sourceId !== writeSource) ?? false) || + (visibleScope.sourceId !== undefined && visibleScope.sourceId !== writeSource); + if (spansAnotherSource) { + const visible = await ctx.engine.getPage(slug, visibleScope); + if (visible && visible.source_id !== writeSource) { + throw new OperationError( + 'permission_denied', + `${operation}${endpoint === 'page' ? '' : ` ${endpoint}`} page "${slug}" is readable from source "${visible.source_id}" but this client writes to source "${writeSource}".`, + 'Graph mutations are same-source by design. Use a client whose write source owns the page, or import the page into your write source first.', + ); + } + } + + throw new OperationError( + 'page_not_found', + `${operation}${endpoint === 'page' ? '' : ` ${endpoint}`} page "${slug}" was not found in writable source "${writeSource}".`, + ); +} + +/** + * #4109 — reclassify a typed engine miss (PageMissingError) raised by the + * mutation itself, after `requireWritablePage` already passed: the page was + * hard-deleted between preflight and mutation. Re-running the preflight + * regenerates the same permission_denied / page_not_found envelope; if the + * page reappeared between those reads (restore race), fall through to a + * deterministic miss instead of leaking the raw engine error as + * internal_error. + */ +export async function reclassifyMutationTimePageMiss( + ctx: OperationContext, + slug: string, + operation: string, + endpoint: 'from' | 'to' | 'page', +): Promise { + await requireWritablePage(ctx, slug, operation, endpoint); + throw new OperationError( + 'page_not_found', + `${operation}${endpoint === 'page' ? '' : ` ${endpoint}`} page "${slug}" was unavailable in writable source "${ctx.sourceId || 'default'}" during the mutation.`, + ); +} + /** * Code-intel adapter for `resolveRequestedScope`. Graph traversal * (code_callers/code_callees/code_blast/code_flow) is single-source by design — @@ -639,6 +714,53 @@ export function resolveCodeIntelScope( ); } +/** + * Federated re-route for the graph four (code_callers / code_callees / + * code_blast / code_flow) — the #3242 sibling. An UNQUALIFIED graph query from + * a no-grant caller collapses to the scalar seed source (usually 'default'), + * which on vault+code brains holds no code — so the graph ops report + * `not_built` while code_def / code_refs (which widen across + * `ctx.localFederatedSourceIds`) answer fine. Graph traversal must stay + * single-source (engine API + cache key take ONE sourceId), so instead of + * widening we RE-ROUTE: when the collapsed source has no code chunks and + * exactly one source in the caller's federated read set does, traverse that + * one — the multi-source cousin of the CLI's `sole_non_default` tier (#1434). + * + * Fail-closed, in order: never fires when the caller passed `source_id` or + * `all_sources` (explicit wins), when the scope is already brain-wide, when a + * grant is present (`ctx.auth.allowedSources` governs — same guard as + * `federatedSearchScope`), when there is no federated read set (a granted + * token never widens), when the collapsed source itself has code, or when + * zero or 2+ federated sources have code (ambiguous → original scope stands + * and readiness reports honestly). Probe errors also keep the original scope. + */ +export async function routeCodeIntelScope( + ctx: OperationContext, + sourceIdParam: string | undefined, + allSourcesParam = false, +): Promise<{ allSources: boolean; sourceId?: string }> { + const scope = resolveCodeIntelScope(ctx, sourceIdParam, allSourcesParam); + if ( + sourceIdParam !== undefined || allSourcesParam || + scope.allSources || scope.sourceId === undefined || + ctx.auth?.allowedSources !== undefined || + !ctx.localFederatedSourceIds || ctx.localFederatedSourceIds.length < 2 + ) { + return scope; + } + try { + const { codeChunksExist } = await import('../code-graph-readiness.ts'); + if (await codeChunksExist(ctx.engine, scope.sourceId)) return scope; + const withCode: string[] = []; + for (const id of ctx.localFederatedSourceIds) { + if (id === scope.sourceId) continue; + if (await codeChunksExist(ctx.engine, id)) withCode.push(id); + } + if (withCode.length === 1) return { allSources: false, sourceId: withCode[0] }; + } catch { /* probe failure → original scope stands */ } + return scope; +} + /** * T4/D5 — resolve a per-call search-mode override. Honored ONLY for trusted/ * local callers (ctx.remote === false) so a remote OAuth client can't escalate diff --git a/src/core/ops/contract.ts b/src/core/ops/contract.ts index e4b63627..6d9575dd 100644 --- a/src/core/ops/contract.ts +++ b/src/core/ops/contract.ts @@ -431,7 +431,8 @@ export interface OperationContext { * `config.federated = true` source, so an unqualified read/search spans * federated sources as docs/guides/multi-source-brains.md promises. * - * Consumed exclusively by `federatedSearchScope`. Fail-closed remains: + * Consumed exclusively by `federatedSearchScope` and the graph-four + * re-route `routeCodeIntelScope` (#4011). Fail-closed remains: * a grant (`ctx.auth.allowedSources`) or a per-call `source_id` always * wins, and a context without this field never widens. */ diff --git a/src/core/ops/facts.ts b/src/core/ops/facts.ts index 70f800da..4c8678a9 100644 --- a/src/core/ops/facts.ts +++ b/src/core/ops/facts.ts @@ -180,7 +180,7 @@ const recall: Operation = { include_expired: { type: 'boolean', description: 'When true, include expired_at IS NOT NULL rows. Default false.' }, supersessions: { type: 'boolean', description: 'When true, return only the supersession audit log (facts with superseded_by set), newest first by COALESCE(expired_at, valid_until).' }, limit: { type: 'number', description: 'Per-arm cap: max fact rows AND max search results. Default 50, cap 100.' }, - grep: { type: 'string', description: 'Substring filter on fact text (case-insensitive). Applied client-side after recall.' }, + grep: { type: 'string', description: 'Substring filter on fact text (case-insensitive). Applied in SQL before the limit, so matches on high-cardinality entities are found even outside the newest-N window.' }, include_pending: { type: 'boolean', description: 'v0.32: when true, response includes pending_consolidation_count (facts not yet promoted to takes by the dream-cycle consolidate phase). One round trip; backward-compatible (field omitted when false).' }, }, scope: 'read', @@ -268,6 +268,7 @@ const recall: Operation = { activeOnly: !includeExpired, limit, visibility, + grep: grep ?? undefined, excludeAuditRows: true, }); })), @@ -280,6 +281,7 @@ const recall: Operation = { activeOnly: !includeExpired, limit, visibility, + grep: grep ?? undefined, excludeAuditRows: true, }), )), @@ -295,6 +297,7 @@ const recall: Operation = { activeOnly: !includeExpired, limit, visibility, + grep: grep ?? undefined, excludeAuditRows: true, }), )), @@ -310,6 +313,7 @@ const recall: Operation = { activeOnly: !includeExpired, limit, visibility, + grep: grep ?? undefined, excludeAuditRows: true, }), )), @@ -325,7 +329,11 @@ const recall: Operation = { // filter is belt-and-braces defense in depth, not the primary guard. rows = rows.filter((r) => !(AUDIT_ROW_SOURCES as readonly string[]).includes(r.source)); - if (grep) rows = rows.filter(r => r.fact.toLowerCase().includes(grep)); + // Engines apply grep in SQL (pre-limit). This client-side pass stays only + // as the filter for the supersessions branch, which bypasses FactListOpts. + if (grep && p.supersessions === true) { + rows = rows.filter(r => r.fact.toLowerCase().includes(grep)); + } // v0.32: optional pending-consolidation count piggy-backed on the recall // response. Single round trip on thin-client; omitted when not requested diff --git a/src/core/ops/links.ts b/src/core/ops/links.ts index 8289d4e5..71a121ef 100644 --- a/src/core/ops/links.ts +++ b/src/core/ops/links.ts @@ -8,7 +8,14 @@ */ import type { Operation } from './contract.ts'; -import { enforceClientSlugFence, linkReadScopeOpts, sourceScopeOpts } from './context.ts'; +import { + enforceClientSlugFence, + linkReadScopeOpts, + reclassifyMutationTimePageMiss, + requireWritablePage, + sourceScopeOpts, +} from './context.ts'; +import { PageMissingError } from '../engine-errors.ts'; // #4224: flag-gated cross-source identity union for the link read ops. import { unionLinksAcrossIdentity } from '../entity-identity.ts'; import { findPrivateOnlySlugs, resolveExcludePrivatePages } from '../search/private-visibility.ts'; @@ -91,12 +98,24 @@ const add_link: Operation = { const linkOpts = ctx.sourceId ? { fromSourceId: ctx.sourceId, toSourceId: ctx.sourceId, originSourceId: ctx.sourceId } : undefined; - await ctx.engine.addLink( // gbrain-allow-direct-insert: add_link MCP op is the explicit canonical surface for manual link creation; auto-link reconciliation runs separately via auto_link post-hook - p.from as string, p.to as string, - (p.context as string) || '', (p.link_type as string) || '', - linkSource, undefined, undefined, - linkOpts, - ); + // #4109: per-endpoint source-boundary diagnostics before the mutation. + await requireWritablePage(ctx, p.from as string, 'add_link', 'from'); + await requireWritablePage(ctx, p.to as string, 'add_link', 'to'); + try { + await ctx.engine.addLink( // gbrain-allow-direct-insert: add_link MCP op is the explicit canonical surface for manual link creation; auto-link reconciliation runs separately via auto_link post-hook + p.from as string, p.to as string, + (p.context as string) || '', (p.link_type as string) || '', + linkSource, undefined, undefined, + linkOpts, + ); + } catch (error) { + // An endpoint hard-deleted between preflight and mutation: reclassify + // the typed engine miss instead of surfacing it as internal_error. + if (error instanceof PageMissingError) { + return reclassifyMutationTimePageMiss(ctx, error.slug, 'add_link', error.endpoint); + } + throw error; + } return { status: 'ok' }; }, cliHints: { name: 'link', aliases: ['link-add'], positional: ['from', 'to'] }, diff --git a/src/core/ops/pages.ts b/src/core/ops/pages.ts index 83a1b689..c94c97ff 100644 --- a/src/core/ops/pages.ts +++ b/src/core/ops/pages.ts @@ -12,7 +12,7 @@ import { clampSearchLimit } from '../engine.ts'; import type { Page, PageType } from '../types.ts'; import { importFromContent } from '../import-file.ts'; import { serializePageToMarkdown } from '../markdown.ts'; -import { writePageThrough, type WriteThroughResult } from '../write-through.ts'; +import { writePageThrough, deletePageThrough, resolvePageWriteTarget, type WriteThroughResult } from '../write-through.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'; @@ -1112,6 +1112,18 @@ const delete_page: Operation = { const sourceOpts = requestedSource ? { sourceId: requestedSource } : ctx.sourceId ? { sourceId: ctx.sourceId } : {}; + // #4022 trust gating: sandbox subagents (viaSubagent without + // allowedSlugPrefixes) stay DB-only, matching put_page's write-through gate. + const isSandboxSubagent = ctx.viaSubagent === true + && !(Array.isArray(ctx.allowedSlugPrefixes) && ctx.allowedSlugPrefixes.length > 0); + // #4022: resolve the artifact target BEFORE softDeletePage stamps + // deleted_at — resolvePageWriteTarget reads the recorded source_path from + // active rows only, so a post-stamp resolution would fall back to the + // slug-derived twin and miss the real artifact. + const wtSourceId = sourceOpts.sourceId ?? 'default'; + const target = isSandboxSubagent + ? undefined + : await resolvePageWriteTarget(ctx.engine, slug, wtSourceId); // v0.26.5: rewired from hard-delete to soft-delete. The hard-delete primitive // (engine.deletePage) is now reserved for purgeDeletedPages and explicit // tests. softDeletePage returns null when the slug is unknown OR already @@ -1126,9 +1138,18 @@ const delete_page: Operation = { } return { status: 'already_soft_deleted', slug, ...(sourceOpts.sourceId ? { source_id: sourceOpts.sourceId } : {}), deleted_at: existing.deleted_at }; } + // #4022: remove the on-disk artifact too. Pre-fix this was DB-only, so the + // deleted page's `.md` survived, any timer-based commit (snapshot cron, + // hardened post-commit push) pushed it back into git, and the next + // `gbrain sync` resurrected the page. Best-effort like put_page's + // write-through: a skip/error never fails the delete (the DB row is the + // durable sink and the stale file reconciles on the next sync). + const writeThrough = isSandboxSubagent + ? { removed: false, skipped: 'subagent_sandbox' as const } + : await deletePageThrough(ctx.engine, slug, { sourceId: wtSourceId, logger: ctx.logger, target }); // Echo the targeted source so a multi-source caller can verify WHICH row // the delete landed on (#4329's false-confidence failure mode). - return { status: 'soft_deleted', slug, ...(sourceOpts.sourceId ? { source_id: sourceOpts.sourceId } : {}), recoverable_until: 'now + 72h via restore_page' }; + return { status: 'soft_deleted', slug, ...(sourceOpts.sourceId ? { source_id: sourceOpts.sourceId } : {}), recoverable_until: 'now + 72h via restore_page', write_through: writeThrough }; }, cliHints: { name: 'delete', positional: ['slug'] }, }; @@ -1162,7 +1183,18 @@ const restore_page: Operation = { } return { status: 'already_active', slug, ...(sourceOpts.sourceId ? { source_id: sourceOpts.sourceId } : {}) }; } - return { status: 'restored', slug, ...(sourceOpts.sourceId ? { source_id: sourceOpts.sourceId } : {}) }; + // #4022: re-render the artifact — delete_page now removes it, so without + // this a restored page has a DB row and no file, and `sync --full`'s + // delete-reconcile treats the missing artifact as a user deletion, + // silently re-deleting the page that was just restored. Keeps the two + // sinks symmetric across the delete/restore pair; sandbox subagents stay + // DB-only, matching put_page's trust gate. + const isSandboxSubagent = ctx.viaSubagent === true + && !(Array.isArray(ctx.allowedSlugPrefixes) && ctx.allowedSlugPrefixes.length > 0); + const writeThrough = isSandboxSubagent + ? { written: false, skipped: 'subagent_sandbox' as const } + : await writePageThrough(ctx.engine, slug, { sourceId: sourceOpts.sourceId, logger: ctx.logger }); + return { status: 'restored', slug, ...(sourceOpts.sourceId ? { source_id: sourceOpts.sourceId } : {}), write_through: writeThrough }; }, cliHints: { name: 'restore', positional: ['slug'] }, }; diff --git a/src/core/ops/schema-packs.ts b/src/core/ops/schema-packs.ts index 802e0941..58a6f0a8 100644 --- a/src/core/ops/schema-packs.ts +++ b/src/core/ops/schema-packs.ts @@ -110,7 +110,7 @@ const schema_lint: Operation = { scope: 'read', handler: async (ctx, p) => { const { runAllLintRules } = await import('../schema-pack/lint-rules.ts'); - const { loadActivePack } = await import('../schema-pack/load-active.ts'); + const { loadActivePack, resolveLoadedPack } = await import('../schema-pack/load-active.ts'); const { loadConfig, gbrainPath } = await import('../config.ts'); const { existsSync } = await import('node:fs'); const { join } = await import('node:path'); @@ -128,7 +128,9 @@ const schema_lint: Operation = { } if (!path) return { error: 'pack_not_found', pack: packName }; const { loadPackFromFile: loader } = await import('../schema-pack/loader.ts'); - manifest = loader(path); + // #4373: lint the MERGED manifest so extends-inherited page types + // count as declared — parity with the active-pack branch below. + manifest = (await resolveLoadedPack(loader(path))).manifest; } else { const resolved = await loadActivePack({ cfg, remote: ctx.remote ?? true, sourceId: ctx.sourceId }); manifest = resolved.manifest; diff --git a/src/core/ops/timeline.ts b/src/core/ops/timeline.ts index d998469d..2284bb13 100644 --- a/src/core/ops/timeline.ts +++ b/src/core/ops/timeline.ts @@ -7,7 +7,14 @@ */ import type { Operation } from './contract.ts'; -import { enforceSubagentSlugFence, enforceClientSlugFence, sourceScopeOpts } from './context.ts'; +import { + enforceSubagentSlugFence, + enforceClientSlugFence, + reclassifyMutationTimePageMiss, + requireWritablePage, + sourceScopeOpts, +} from './context.ts'; +import { PageMissingError } from '../engine-errors.ts'; import { slugHiddenFromCaller } from '../search/private-visibility.ts'; import { writeTimelineEntryThrough } from '../timeline-write-through.ts'; @@ -54,6 +61,10 @@ const add_timeline_entry: Operation = { } // v0.31.8 (D7): thread ctx.sourceId. const sourceOpts = ctx.sourceId ? { sourceId: ctx.sourceId } : {}; + // #4109: source-boundary diagnostics before the write-through/insert — + // a page readable only from another granted source must come back as + // permission_denied, not the engine's exact-source "not found". + await requireWritablePage(ctx, p.slug as string, 'add_timeline_entry', 'page'); // #1856: on an FS/git-canonical brain (a disk target resolves for this // page), route the entry through the page/facts write-through seam so the // canonical markdown gains the bullet too — a DB-only insert stranded the @@ -100,12 +111,22 @@ const add_timeline_entry: Operation = { // raw input tuple would recreate the duplicate class on the error path // (raw row now + re-extracted canonical row later). const canonical = writeThrough?.entry; - const inserted = await ctx.engine.addTimelineEntry(p.slug as string, { // gbrain-allow-direct-insert: add_timeline_entry MCP op is the explicit canonical surface for manual timeline entries on DB-only brains; FS-canonical brains route through writeTimelineEntryThrough above - date: canonical?.date ?? date, - source: canonical ? canonical.source : entryInput.source, - summary: canonical ? canonical.summary : entryInput.summary, - detail: entryInput.detail, - }, sourceOpts); + let inserted: boolean; + try { + inserted = await ctx.engine.addTimelineEntry(p.slug as string, { // gbrain-allow-direct-insert: add_timeline_entry MCP op is the explicit canonical surface for manual timeline entries on DB-only brains; FS-canonical brains route through writeTimelineEntryThrough above + date: canonical?.date ?? date, + source: canonical ? canonical.source : entryInput.source, + summary: canonical ? canonical.summary : entryInput.summary, + detail: entryInput.detail, + }, sourceOpts); + } catch (error) { + // Page hard-deleted between preflight and insert: reclassify the typed + // engine miss instead of surfacing it as internal_error. + if (error instanceof PageMissingError) { + return reclassifyMutationTimePageMiss(ctx, error.slug, 'add_timeline_entry', error.endpoint); + } + throw error; + } const writeThroughReport = { written: false, skipped: isSandboxSubagent ? 'subagent_sandbox' : (writeThrough?.skipped ?? 'db_only'), diff --git a/src/core/page-summary.ts b/src/core/page-summary.ts index e9e68aa3..d861d257 100644 --- a/src/core/page-summary.ts +++ b/src/core/page-summary.ts @@ -33,6 +33,7 @@ import { chat, type ChatOpts, type ChatResult } from './ai/gateway.ts'; import { logSynopsisFailure, type SynopsisFailureKind } from './audit-synopsis.ts'; import { sanitizeSynopsis } from './embedding-context.ts'; +import { resolveTierDefault } from './model-config.ts'; /** * Default cap on synopsis output tokens. ~200 tokens gives 50-100 token @@ -46,7 +47,12 @@ import { sanitizeSynopsis } from './embedding-context.ts'; */ export const SYNOPSIS_MAX_TOKENS = 200; -/** Default model when caller doesn't override. Resolves through the gateway. */ +/** + * Stable synopsis-model anchor for corpus_generation hashing (title-mode + * pages and the inline import path) — NOT the live chat default. Changing + * this string invalidates prior embeddings via the D27 P1-5 contract; the + * live default is the key-aware utility tier (#3813). + */ export const DEFAULT_SYNOPSIS_MODEL = 'anthropic:claude-haiku-4-5-20251001'; /** @@ -158,7 +164,9 @@ export async function generatePerChunkSynopsis( const maxTokens = args.maxTokens ?? SYNOPSIS_MAX_TOKENS; const chatOpts: ChatOpts = { - model: args.model ?? DEFAULT_SYNOPSIS_MODEL, + // #3813: key-aware tier default, not the hardcoded hash anchor above — + // an OPENAI_API_KEY-only install must not route to Anthropic. + model: args.model ?? resolveTierDefault('utility'), system: SYSTEM_PROMPT, messages: [{ role: 'user', content: userPrompt }], maxTokens, diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts index 14c5e647..7202c293 100644 --- a/src/core/pglite-engine.ts +++ b/src/core/pglite-engine.ts @@ -35,7 +35,7 @@ import type { NewFact, FactListOpts, FactsHealth, SourceRow, } from './engine.ts'; -import { MAX_SEARCH_LIMIT, clampSearchLimit } from './engine.ts'; +import { DREAM_VERDICT_TTL_SECONDS, MAX_SEARCH_LIMIT, clampSearchLimit } from './engine.ts'; // Engine-path imports stay static unless a call site carries an explicit // engine-dynamic-import-ok justification. The gateway is the only current // exception because its local try/catch preserves a soft fallback. @@ -58,6 +58,7 @@ import { hnswEfSearchFor, hnswIndexExpected, HNSW_EF_SEARCH_MAX } from './vector import { PGLITE_SCHEMA_SQL, getPGLiteSchema } from './pglite-schema.ts'; import { DEFAULT_EMBEDDING_MODEL, DEFAULT_EMBEDDING_DIMENSIONS } from './ai/defaults.ts'; import { DELETE_BATCH_SIZE } from './engine-constants.ts'; +import { PageMissingError } from './engine-errors.ts'; import { SOURCE_CONFIG_OBJECT_SQL } from './source-config-sql.ts'; import { MARKDOWN_CHUNKER_VERSION } from './chunkers/recursive.ts'; import { acquireLock, releaseLock, type LockHandle } from './pglite-lock.ts'; @@ -898,6 +899,28 @@ export class PGLiteEngine implements BrainEngine { // finally's releaseLock + dispose. await drainBackgroundWorkBeforeDisconnect(); if (db) { + // #3893 (reimplemented from @y2688): best-effort WAL flush BEFORE + // close(). A clean close() checkpoints on its own, but the #4143 + // class below means close can time out or wedge and be abandoned — + // an explicit pre-close CHECKPOINT makes the data files current so + // an abandoned close loses no committed rows. PGLite-only by design + // (no postgres-engine parity twin): a server Postgres owns its own + // checkpointer and survives this process dying. Bounded by the same + // close timeout and never throwing — a slow or failed CHECKPOINT + // must not block teardown. Runs after the drain so it is the only + // statement in flight when it executes. + let checkpointTimer: ReturnType | undefined; + try { + await Promise.race([ + db.query('CHECKPOINT').catch(() => undefined), + new Promise((resolve) => { + checkpointTimer = setTimeout(resolve, pgliteCloseTimeoutMs()); + }), + ]); + } finally { + if (checkpointTimer) clearTimeout(checkpointTimer); + } + // Deliberately NOT wrapped in preservingProcessExitCode: close's // status write (0) is long-standing baseline behavior that test-runner // processes depend on (wrapping it flipped bun test's own exit code — @@ -3663,33 +3686,38 @@ export class PGLiteEngine implements BrainEngine { const toSrc = opts?.toSourceId ?? 'default'; const originSrc = opts?.originSourceId ?? 'default'; - // Source-qualified pre-check gives a clean missing-page error before the - // INSERT SELECT path can silently return zero rows. - const exists = await this.db.query( - `SELECT 1 FROM pages WHERE slug = $1 AND source_id = $2 - INTERSECT - SELECT 1 FROM pages WHERE slug = $3 AND source_id = $4`, - [from, fromSrc, to, toSrc] - ); - if (exists.rows.length === 0) { - throw new Error(`addLink failed: page "${from}" (source=${fromSrc}) or "${to}" (source=${toSrc}) not found`); - } const src = linkSource ?? 'markdown'; - // Mirror addLinksBatch's VALUES + composite JOIN shape. The old cross- - // product over pages f/t fanned out across sources containing the slugs. - await this.db.query( - `INSERT INTO links (from_page_id, to_page_id, link_type, context, link_source, origin_page_id, origin_field) - SELECT f.id, t.id, v.link_type, v.context, v.link_source, o.id, v.origin_field - FROM (VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)) - AS v(from_slug, to_slug, link_type, context, link_source, origin_slug, origin_field, from_source_id, to_source_id, origin_source_id) - JOIN pages f ON f.slug = v.from_slug AND f.source_id = v.from_source_id - JOIN pages t ON t.slug = v.to_slug AND t.source_id = v.to_source_id - LEFT JOIN pages o ON o.slug = v.origin_slug AND o.source_id = v.origin_source_id - ON CONFLICT (from_page_id, to_page_id, link_type, link_source, origin_page_id) DO UPDATE SET - context = EXCLUDED.context, - origin_field = EXCLUDED.origin_field`, - [from, to, linkType || '', sanitizeForJsonb(context || ''), src, originSlug ?? null, originField ?? null, fromSrc, toSrc, originSrc] + // #4109: mirrors PostgresEngine — resolve both required endpoints and + // upsert from one statement snapshot, reporting the missing endpoint + // individually. Lookups stay source-qualified per endpoint (not the old + // cross-product over pages f/t that fanned out across sources containing + // the slugs). No FOR KEY SHARE here: PGLite is single-writer in-process, + // so no concurrent session can delete between lookup and insert. + const result = await this.db.query<{ from_exists: boolean; to_exists: boolean }>( + `WITH endpoint_state AS ( + SELECT + (SELECT id FROM pages WHERE slug = $1 AND source_id = $2) AS from_id, + (SELECT id FROM pages WHERE slug = $3 AND source_id = $4) AS to_id, + (SELECT id FROM pages WHERE slug = $5 AND source_id = $6) AS origin_id + ), upserted AS ( + INSERT INTO links (from_page_id, to_page_id, link_type, context, link_source, origin_page_id, origin_field) + SELECT s.from_id, s.to_id, $7, $8, $9, s.origin_id, $10 + FROM endpoint_state s + WHERE s.from_id IS NOT NULL AND s.to_id IS NOT NULL + ON CONFLICT (from_page_id, to_page_id, link_type, link_source, origin_page_id) DO UPDATE SET + context = EXCLUDED.context, + origin_field = EXCLUDED.origin_field + RETURNING 1 + ) + SELECT + endpoint_state.from_id IS NOT NULL AS from_exists, + endpoint_state.to_id IS NOT NULL AS to_exists + FROM endpoint_state`, + [from, fromSrc, to, toSrc, originSlug ?? null, originSrc, linkType || '', sanitizeForJsonb(context || ''), src, originField ?? null] ); + const row = result.rows[0]; + if (!row?.from_exists) throw new PageMissingError('addLink', 'from', from, fromSrc); + if (!row.to_exists) throw new PageMissingError('addLink', 'to', to, toSrc); } async addLinksBatch(links: LinkBatchInput[], opts?: BatchOpts): Promise { @@ -4354,28 +4382,29 @@ export class PGLiteEngine implements BrainEngine { })); } - async getBacklinkCounts(slugs: string[]): Promise> { - const result = new Map(); - if (slugs.length === 0) return result; - // Initialize all slugs to 0 so callers get a consistent map. - for (const s of slugs) result.set(s, 0); + async getBacklinkCounts(pageIds: number[]): Promise> { + const result = new Map(); + if (pageIds.length === 0) return result; + // Initialize all ids to 0 so callers get a consistent map. + for (const id of pageIds) result.set(id, 0); // v0.41.18.0 D12: filter mentions OUT of backlink-count for search // ranking — parity with postgres-engine.ts. See that file's comment // for the full rationale. `IS DISTINCT FROM` is NULL-safe so legacy // rows with NULL link_source still count toward backlinks. + // #4380: keyed by p.id, not slug — parity with postgres-engine.ts. // PGLite needs explicit cast for array binding (does not auto-serialize JS arrays). const { rows } = await this.db.query( - `SELECT p.slug AS slug, COUNT(l.id)::int AS cnt + `SELECT p.id AS page_id, COUNT(l.id)::int AS cnt FROM pages p LEFT JOIN links l ON l.to_page_id = p.id AND l.link_source IS DISTINCT FROM 'mentions' - WHERE p.slug = ANY($1::text[]) - GROUP BY p.slug`, - [slugs] + WHERE p.id = ANY($1::int[]) + GROUP BY p.id`, + [pageIds] ); - for (const r of rows as { slug: string; cnt: number }[]) { - result.set(r.slug, Number(r.cnt)); + for (const r of rows as { page_id: number; cnt: number }[]) { + result.set(Number(r.page_id), Number(r.cnt)); } return result; } @@ -4638,33 +4667,37 @@ export class PGLiteEngine implements BrainEngine { opts?: { skipExistenceCheck?: boolean; sourceId?: string }, ): Promise { const sourceId = opts?.sourceId ?? 'default'; - if (!opts?.skipExistenceCheck) { - const { rows } = await this.db.query( - 'SELECT 1 FROM pages WHERE slug = $1 AND source_id = $2', - [slug, sourceId] - ); - if (rows.length === 0) { - throw new Error(`addTimelineEntry failed: page "${slug}" (source=${sourceId}) not found`); - } - } - // ON CONFLICT DO NOTHING via the (page_id, date, md5(summary), source) - // unique index (#3737: md5-keyed so long summaries fit the btree row cap). - // #3827: RETURNING 1 makes the outcome observable (true = inserted, - // false = deduplicated or JOIN-dropped under skipExistenceCheck), - // mirroring the Postgres engine. Source-qualify the page-id lookup so - // multi-source brains don't fan timeline rows out across every source - // containing the slug. + // #4109: mirrors PostgresEngine — page resolution and insertion share one + // statement snapshot so the miss is typed (PageMissingError) rather than + // inferred from a zero-row insert. ON CONFLICT DO NOTHING via the + // (page_id, date, md5(summary), source) unique index (#3737: md5-keyed so + // long summaries fit the btree row cap). + // #3827: the `inserted` flag makes the outcome observable (true = + // inserted, false = deduplicated, or page missing under + // skipExistenceCheck), mirroring the Postgres engine. Source-qualify the + // page-id lookup so multi-source brains don't fan timeline rows out + // across every source containing the slug. // Free-text body fields are NUL + lone-surrogate sanitized (#2011), matching // the batch path and the Postgres engine; identity fields (slug, date) raw. - const { rows: inserted } = await this.db.query( - `INSERT INTO timeline_entries (page_id, date, source, summary, detail) - SELECT id, $2::date, $3, $4, $5 - FROM pages WHERE slug = $1 AND source_id = $6 - ON CONFLICT (page_id, date, md5(summary), source) DO NOTHING - RETURNING 1`, + const result = await this.db.query<{ page_exists: boolean; inserted: boolean }>( + `WITH page_state AS ( + SELECT id FROM pages WHERE slug = $1 AND source_id = $6 + ), inserted AS ( + INSERT INTO timeline_entries (page_id, date, source, summary, detail) + SELECT id, $2::date, $3, $4, $5 + FROM page_state + ON CONFLICT (page_id, date, md5(summary), source) DO NOTHING + RETURNING 1 + ) + SELECT + EXISTS(SELECT 1 FROM page_state) AS page_exists, + EXISTS(SELECT 1 FROM inserted) AS inserted`, [slug, entry.date, sanitizeForJsonb(entry.source || ''), sanitizeForJsonb(entry.summary), sanitizeForJsonb(entry.detail || ''), sourceId] ); - return inserted.length > 0; + if (!result.rows[0]?.page_exists && !opts?.skipExistenceCheck) { + throw new PageMissingError('addTimelineEntry', 'page', slug, sourceId); + } + return result.rows[0]?.inserted === true; } async addTimelineEntriesBatch(entries: TimelineBatchInput[], opts?: BatchOpts): Promise { @@ -5145,7 +5178,8 @@ export class PGLiteEngine implements BrainEngine { `SELECT worth_processing, reasons, judged_at, score, content_type, segments, entities, model, triage_version FROM dream_verdicts - WHERE file_path = $1 AND content_hash = $2`, + WHERE file_path = $1 AND content_hash = $2 + AND expires_at > now()`, [filePath, contentHash] ); if (result.rows.length === 0) return null; @@ -5166,10 +5200,14 @@ export class PGLiteEngine implements BrainEngine { async putDreamVerdict(filePath: string, contentHash: string, verdict: DreamVerdictInput): Promise { // $N::jsonb + JSON.stringify is legal ONLY on PGLite (its db.query parses // text→jsonb natively); the postgres.js twin must use sql.json(). + // Expiry is computed server-side (now() + TTL) so it lives on the same + // clock as the `expires_at > now()` read predicate and judged_at. await this.db.query( `INSERT INTO dream_verdicts (file_path, content_hash, worth_processing, reasons, - score, content_type, segments, entities, model, triage_version) - VALUES ($1, $2, $3, $4::jsonb, $5, $6, $7::jsonb, $8::jsonb, $9, $10) + score, content_type, segments, entities, model, triage_version, + expires_at) + VALUES ($1, $2, $3, $4::jsonb, $5, $6, $7::jsonb, $8::jsonb, $9, $10, + now() + make_interval(secs => $11)) ON CONFLICT (file_path, content_hash) DO UPDATE SET worth_processing = EXCLUDED.worth_processing, reasons = EXCLUDED.reasons, @@ -5179,13 +5217,22 @@ export class PGLiteEngine implements BrainEngine { entities = EXCLUDED.entities, model = EXCLUDED.model, triage_version = EXCLUDED.triage_version, - judged_at = now()`, + judged_at = now(), + expires_at = EXCLUDED.expires_at`, [filePath, contentHash, verdict.worth_processing, JSON.stringify(verdict.reasons), verdict.score, verdict.content_type, JSON.stringify(verdict.segments), - JSON.stringify(verdict.entities), verdict.model, verdict.triage_version] + JSON.stringify(verdict.entities), verdict.model, verdict.triage_version, + DREAM_VERDICT_TTL_SECONDS] ); } + async sweepDreamVerdicts(): Promise { + const result = await this.db.query( + `DELETE FROM dream_verdicts WHERE expires_at <= now()` + ); + return result.affectedRows ?? 0; + } + // ============================================================ // v0.31: Hot memory — facts table operations // ============================================================ diff --git a/src/core/pglite-engine/facts.ts b/src/core/pglite-engine/facts.ts index a57954b9..3f040698 100644 --- a/src/core/pglite-engine/facts.ts +++ b/src/core/pglite-engine/facts.ts @@ -11,6 +11,7 @@ import type { import { MAX_SEARCH_LIMIT, clampSearchLimit } from '../engine.ts'; import { AUDIT_ROW_SOURCES } from '../facts/audit-sources.ts'; import { resolveSupersededByRow, isInt4RowRef, type SupersedeTarget } from '../facts/supersede-resolve.ts'; +import { escapeLikePattern } from '../cjk.ts'; /** Narrow slice of PGLiteEngine the facts operations use. */ export interface PgliteFactsDeps { @@ -415,10 +416,13 @@ export async function listSupersessions( } export async function countUnconsolidatedFacts(deps: PgliteFactsDeps, source_id: string): Promise { + // Audit checkpoint rows never set consolidated_at, so without the source + // exclusion each one counts as forever-pending consolidation backlog. const r = await deps.db.query<{ count: number }>( `SELECT COUNT(*)::int AS count FROM facts - WHERE source_id = $1 AND consolidated_at IS NULL AND expired_at IS NULL`, - [source_id], + WHERE source_id = $1 AND consolidated_at IS NULL AND expired_at IS NULL + AND NOT (source = ANY($2::text[]))`, + [source_id, [...AUDIT_ROW_SOURCES]], ); return Number(r.rows[0]?.count ?? 0); } @@ -640,6 +644,13 @@ async function _listFacts( whereParts.push(`visibility = ANY($visibility)`); params.visibility = opts.visibility; } + if (opts.grep && opts.grep.trim()) { + // SQL-side substring filter (before limit) — a client-side post-limit + // grep silently misses matches outside the newest-N window on + // high-cardinality entities. Parity with the postgres engine. + whereParts.push(`fact ILIKE $grepPat ESCAPE '\\'`); + params.grepPat = '%' + escapeLikePattern(opts.grep.trim()) + '%'; + } for (const c of opts.whereClauses ?? []) whereParts.push(c); Object.assign(params, opts.whereParams ?? {}); diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts index 2b24650a..07ec30c5 100644 --- a/src/core/postgres-engine.ts +++ b/src/core/postgres-engine.ts @@ -37,7 +37,7 @@ import { logBatchRetry as auditLogBatchRetry, logBatchExhausted as auditLogBatch import type { DomainBankSampleOpts, CorpusSampleOpts, DomainBankRow, } from './types.ts'; -import { MAX_SEARCH_LIMIT, clampSearchLimit } from './engine.ts'; +import { DREAM_VERDICT_TTL_SECONDS, MAX_SEARCH_LIMIT, clampSearchLimit } from './engine.ts'; import { executeRawJsonb, type SqlValue } from './sql-query.ts'; import { sanitizeForJsonb, sanitizeText, buildLinkRows, buildTimelineRows } from './batch-rows.ts'; import { runMigrations } from './migrate.ts'; @@ -89,6 +89,7 @@ import { privatePagesFilterFragment } from './search/private-visibility.ts'; import { unverifiedExtractionFragment } from './extraction-review.ts'; import { DEFAULT_EMBEDDING_MODEL, DEFAULT_EMBEDDING_DIMENSIONS } from './ai/defaults.ts'; import { DELETE_BATCH_SIZE } from './engine-constants.ts'; +import { PageMissingError } from './engine-errors.ts'; import { SOURCE_CONFIG_OBJECT_SQL } from './source-config-sql.ts'; import { shouldExcludeFromOrphanReporting, loadOrphanPolicyOverrides } from './orphan-policy.ts'; import { LINK_EXTRACTOR_VERSION_TS } from './link-extraction.ts'; @@ -2926,36 +2927,41 @@ export class PostgresEngine implements BrainEngine { const toSrc = opts?.toSourceId ?? 'default'; const originSrc = opts?.originSourceId ?? 'default'; - // Pre-check existence so we can throw a clear error (ON CONFLICT DO UPDATE - // returns 0 rows when source SELECT is empty, indistinguishable from missing - // page). Source-qualified — pre-v0.18 the bare slug check matched ANY source, - // letting addLink succeed even when the intended source row was missing. - const exists = await sql` - SELECT 1 FROM pages WHERE slug = ${from} AND source_id = ${fromSrc} - INTERSECT - SELECT 1 FROM pages WHERE slug = ${to} AND source_id = ${toSrc} - `; - if (exists.length === 0) { - throw new Error(`addLink failed: page "${from}" (source=${fromSrc}) or "${to}" (source=${toSrc}) not found`); - } // Default link_source to 'markdown' for back-compat with pre-v0.13 callers. - // Mirror addLinksBatch's VALUES + JOIN-on-(slug, source_id) shape. The old - // `FROM pages f, pages t` cross-product fanned out across every source - // containing either slug, so a multi-source brain silently created edges - // pointing at the wrong pages. const src = linkSource ?? 'markdown'; - await sql` - INSERT INTO links (from_page_id, to_page_id, link_type, context, link_source, origin_page_id, origin_field) - SELECT f.id, t.id, v.link_type, v.context, v.link_source, o.id, v.origin_field - FROM (VALUES (${from}, ${to}, ${linkType || ''}, ${sanitizeForJsonb(context || '')}, ${src}, ${originSlug ?? null}, ${originField ?? null}, ${fromSrc}, ${toSrc}, ${originSrc})) - AS v(from_slug, to_slug, link_type, context, link_source, origin_slug, origin_field, from_source_id, to_source_id, origin_source_id) - JOIN pages f ON f.slug = v.from_slug AND f.source_id = v.from_source_id - JOIN pages t ON t.slug = v.to_slug AND t.source_id = v.to_source_id - LEFT JOIN pages o ON o.slug = v.origin_slug AND o.source_id = v.origin_source_id - ON CONFLICT (from_page_id, to_page_id, link_type, link_source, origin_page_id) DO UPDATE SET - context = EXCLUDED.context, - origin_field = EXCLUDED.origin_field + // #4109: resolve both required endpoints and upsert from ONE statement + // snapshot — a separate pre-check raced concurrent hard deletes (a delete + // winning between check and insert made a zero-row upsert look like + // success). The lookups stay source-qualified per endpoint (JOIN-on- + // (slug, source_id), not the pre-v0.18 cross-product that fanned out + // across sources containing either slug). FOR KEY SHARE makes a + // concurrent hard delete linearize around the mutation: a delete that + // wins first is observed as a missing endpoint; a mutation that wins + // first holds the referenced rows through the insert instead of leaking + // a raw FK violation. + const [result] = await sql` + WITH endpoint_state AS ( + SELECT + (SELECT id FROM pages WHERE slug = ${from} AND source_id = ${fromSrc} FOR KEY SHARE) AS from_id, + (SELECT id FROM pages WHERE slug = ${to} AND source_id = ${toSrc} FOR KEY SHARE) AS to_id, + (SELECT id FROM pages WHERE slug = ${originSlug ?? null} AND source_id = ${originSrc} FOR KEY SHARE) AS origin_id + ), upserted AS ( + INSERT INTO links (from_page_id, to_page_id, link_type, context, link_source, origin_page_id, origin_field) + SELECT s.from_id, s.to_id, ${linkType || ''}, ${sanitizeForJsonb(context || '')}, ${src}, s.origin_id, ${originField ?? null} + FROM endpoint_state s + WHERE s.from_id IS NOT NULL AND s.to_id IS NOT NULL + ON CONFLICT (from_page_id, to_page_id, link_type, link_source, origin_page_id) DO UPDATE SET + context = EXCLUDED.context, + origin_field = EXCLUDED.origin_field + RETURNING 1 + ) + SELECT + endpoint_state.from_id IS NOT NULL AS from_exists, + endpoint_state.to_id IS NOT NULL AS to_exists + FROM endpoint_state `; + if (!result?.from_exists) throw new PageMissingError('addLink', 'from', from, fromSrc); + if (!result.to_exists) throw new PageMissingError('addLink', 'to', to, toSrc); } async addLinksBatch(links: LinkBatchInput[], opts?: BatchOpts): Promise { @@ -3634,10 +3640,10 @@ export class PostgresEngine implements BrainEngine { })); } - async getBacklinkCounts(slugs: string[]): Promise> { - const result = new Map(); - if (slugs.length === 0) return result; - for (const s of slugs) result.set(s, 0); + async getBacklinkCounts(pageIds: number[]): Promise> { + const result = new Map(); + if (pageIds.length === 0) return result; + for (const id of pageIds) result.set(id, 0); // v0.41.18.0 D12: filter mentions OUT of backlink-count for search // ranking. `link_source='mentions'` rows are auto-linked body-text @@ -3647,17 +3653,19 @@ export class PostgresEngine implements BrainEngine { // --by-mention run, boosting popular-mention pages over intentional- // backlink pages. `IS DISTINCT FROM` is NULL-safe so legacy rows with // NULL link_source still count (NULL != 'mentions' → row included). + // #4380: keyed by p.id, not slug — grouping by bare slug summed every + // namesake's backlinks across sources, boosting zero-backlink pages. const sql = this.sql; const rows = await sql` - SELECT p.slug as slug, COUNT(l.id)::int as cnt + SELECT p.id as page_id, COUNT(l.id)::int as cnt FROM pages p LEFT JOIN links l ON l.to_page_id = p.id AND l.link_source IS DISTINCT FROM 'mentions' - WHERE p.slug = ANY(${slugs}::text[]) - GROUP BY p.slug + WHERE p.id = ANY(${pageIds}::int[]) + GROUP BY p.id `; - for (const r of rows as unknown as { slug: string; cnt: number }[]) { - result.set(r.slug, Number(r.cnt)); + for (const r of rows as unknown as { page_id: number; cnt: number }[]) { + result.set(Number(r.page_id), Number(r.cnt)); } return result; } @@ -3928,31 +3936,38 @@ export class PostgresEngine implements BrainEngine { ): Promise { const sql = this.sql; const sourceId = opts?.sourceId ?? 'default'; - if (!opts?.skipExistenceCheck) { - const exists = await sql`SELECT 1 FROM pages WHERE slug = ${slug} AND source_id = ${sourceId}`; - if (exists.length === 0) { - throw new Error(`addTimelineEntry failed: page "${slug}" (source=${sourceId}) not found`); - } - } - // ON CONFLICT DO NOTHING via the (page_id, date, md5(summary), source) - // unique index (#3737: md5-keyed so long summaries fit the btree row cap). - // #3827: RETURNING 1 makes the outcome observable — 0 rows means either - // page missing OR duplicate; with the existence check above (default) the - // false return unambiguously means "deduplicated", and under - // skipExistenceCheck the caller asserts the page exists. Source-qualify - // the page-id lookup so multi-source brains don't fan timeline rows out - // across every source containing the slug. + // #4109: page resolution and insertion share ONE statement snapshot, so a + // concurrent hard delete linearizes before the lookup (missing) or after + // the insert (success) instead of surfacing a raw FK violation; FOR KEY + // SHARE holds the referenced row through the insert. ON CONFLICT DO + // NOTHING via the (page_id, date, md5(summary), source) unique index + // (#3737: md5-keyed so long summaries fit the btree row cap). + // #3827: the `inserted` flag makes the outcome observable — with the + // page_exists throw below (default) a false return unambiguously means + // "deduplicated", and under skipExistenceCheck the caller asserts the + // page exists. Source-qualify the page-id lookup so multi-source brains + // don't fan timeline rows out across every source containing the slug. // Free-text body fields are NUL + lone-surrogate sanitized (#2011) so a // surrogate from sliced/imported content can't reach the (later) ::jsonb // batch path or corrupt the row; identity fields (slug, date) are left raw. - const inserted = await sql` - INSERT INTO timeline_entries (page_id, date, source, summary, detail) - SELECT id, ${entry.date}::date, ${sanitizeForJsonb(entry.source || '')}, ${sanitizeForJsonb(entry.summary)}, ${sanitizeForJsonb(entry.detail || '')} - FROM pages WHERE slug = ${slug} AND source_id = ${sourceId} - ON CONFLICT (page_id, date, md5(summary), source) DO NOTHING - RETURNING 1 + const [result] = await sql` + WITH page_state AS ( + SELECT id FROM pages WHERE slug = ${slug} AND source_id = ${sourceId} FOR KEY SHARE + ), inserted AS ( + INSERT INTO timeline_entries (page_id, date, source, summary, detail) + SELECT id, ${entry.date}::date, ${sanitizeForJsonb(entry.source || '')}, ${sanitizeForJsonb(entry.summary)}, ${sanitizeForJsonb(entry.detail || '')} + FROM page_state + ON CONFLICT (page_id, date, md5(summary), source) DO NOTHING + RETURNING 1 + ) + SELECT + EXISTS(SELECT 1 FROM page_state) AS page_exists, + EXISTS(SELECT 1 FROM inserted) AS inserted `; - return inserted.length > 0; + if (!result?.page_exists && !opts?.skipExistenceCheck) { + throw new PageMissingError('addTimelineEntry', 'page', slug, sourceId); + } + return result?.inserted === true; } async addTimelineEntriesBatch(entries: TimelineBatchInput[], opts?: BatchOpts): Promise { @@ -4402,6 +4417,7 @@ export class PostgresEngine implements BrainEngine { score, content_type, segments, entities, model, triage_version FROM dream_verdicts WHERE file_path = ${filePath} AND content_hash = ${contentHash} + AND expires_at > now() `; if (rows.length === 0) return null; const r = rows[0]; @@ -4420,12 +4436,16 @@ export class PostgresEngine implements BrainEngine { async putDreamVerdict(filePath: string, contentHash: string, verdict: DreamVerdictInput): Promise { const sql = this.sql; + // Expiry is computed server-side (now() + TTL) so it lives on the same + // clock as the `expires_at > now()` read predicate and judged_at. await sql` INSERT INTO dream_verdicts (file_path, content_hash, worth_processing, reasons, - score, content_type, segments, entities, model, triage_version) + score, content_type, segments, entities, model, triage_version, + expires_at) VALUES (${filePath}, ${contentHash}, ${verdict.worth_processing}, ${sql.json(verdict.reasons as Parameters[0])}, ${verdict.score}, ${verdict.content_type}, ${sql.json(verdict.segments as unknown as Parameters[0])}, - ${sql.json(verdict.entities as Parameters[0])}, ${verdict.model}, ${verdict.triage_version}) + ${sql.json(verdict.entities as Parameters[0])}, ${verdict.model}, ${verdict.triage_version}, + now() + make_interval(secs => ${DREAM_VERDICT_TTL_SECONDS})) ON CONFLICT (file_path, content_hash) DO UPDATE SET worth_processing = EXCLUDED.worth_processing, reasons = EXCLUDED.reasons, @@ -4435,10 +4455,17 @@ export class PostgresEngine implements BrainEngine { entities = EXCLUDED.entities, model = EXCLUDED.model, triage_version = EXCLUDED.triage_version, - judged_at = now() + judged_at = now(), + expires_at = EXCLUDED.expires_at `; } + async sweepDreamVerdicts(): Promise { + const sql = this.sql; + const result = await sql`DELETE FROM dream_verdicts WHERE expires_at <= now()`; + return result.count ?? 0; + } + // ============================================================ // v0.31: Hot memory — facts table operations // ============================================================ diff --git a/src/core/postgres-engine/facts.ts b/src/core/postgres-engine/facts.ts index 8e412208..88e6a854 100644 --- a/src/core/postgres-engine/facts.ts +++ b/src/core/postgres-engine/facts.ts @@ -16,6 +16,16 @@ import { MAX_SEARCH_LIMIT, clampSearchLimit } from '../engine.ts'; import { tryParseEmbedding } from '../utils.ts'; import { AUDIT_ROW_SOURCES } from '../facts/audit-sources.ts'; import { resolveSupersededByRow, isInt4RowRef, type SupersedeTarget } from '../facts/supersede-resolve.ts'; +import { escapeLikePattern } from '../cjk.ts'; + +/** + * SQL-side substring filter (before limit) — a client-side post-limit grep + * silently misses matches outside the newest-N window on high-cardinality + * entities. Parity with the pglite engine's `_listFacts`. + */ +function grepPattern(opts: FactListOpts | undefined): string | null { + return (opts?.grep && opts.grep.trim()) ? '%' + escapeLikePattern(opts.grep.trim()) + '%' : null; +} /** Narrow slice of PostgresEngine the facts operations use. */ export interface PgFactsDeps { @@ -314,6 +324,7 @@ export async function listFactsByEntity( const kinds = (opts?.kinds && opts.kinds.length > 0) ? opts.kinds : null; const visibility = (opts?.visibility && opts.visibility.length > 0) ? opts.visibility : null; const excludeAuditRows = opts?.excludeAuditRows === true; + const grepPat = grepPattern(opts); const rows = await sql` SELECT * FROM facts WHERE source_id = ${source_id} @@ -323,6 +334,7 @@ export async function listFactsByEntity( ${kinds ? sql`AND kind = ANY(${kinds}::text[])` : sql``} ${visibility ? sql`AND visibility = ANY(${visibility}::text[])` : sql``} ${excludeAuditRows ? sql`AND source != ALL(${AUDIT_ROW_SOURCES}::text[])` : sql``} + ${grepPat ? sql`AND fact ILIKE ${grepPat} ESCAPE '\\'` : sql``} ORDER BY valid_from DESC, id DESC LIMIT ${limit} OFFSET ${offset} `; @@ -345,6 +357,7 @@ export async function listFactsSince( const entitySlug = opts?.entitySlug ?? null; const eventTime = opts?.eventTime === true; const excludeAuditRows = opts?.excludeAuditRows === true; + const grepPat = grepPattern(opts); const rows = await sql` SELECT * FROM facts WHERE source_id = ${source_id} @@ -355,6 +368,7 @@ export async function listFactsSince( ${kinds ? sql`AND kind = ANY(${kinds}::text[])` : sql``} ${visibility ? sql`AND visibility = ANY(${visibility}::text[])` : sql``} ${excludeAuditRows ? sql`AND source != ALL(${AUDIT_ROW_SOURCES}::text[])` : sql``} + ${grepPat ? sql`AND fact ILIKE ${grepPat} ESCAPE '\\'` : sql``} ORDER BY ${eventTime ? sql`COALESCE(valid_from, created_at)` : sql`created_at`} DESC, id DESC LIMIT ${limit} OFFSET ${offset} `; @@ -375,6 +389,7 @@ export async function listFactsBySession( const kinds = (opts?.kinds && opts.kinds.length > 0) ? opts.kinds : null; const visibility = (opts?.visibility && opts.visibility.length > 0) ? opts.visibility : null; const excludeAuditRows = opts?.excludeAuditRows === true; + const grepPat = grepPattern(opts); const rows = await sql` SELECT * FROM facts WHERE source_id = ${source_id} @@ -384,6 +399,7 @@ export async function listFactsBySession( ${kinds ? sql`AND kind = ANY(${kinds}::text[])` : sql``} ${visibility ? sql`AND visibility = ANY(${visibility}::text[])` : sql``} ${excludeAuditRows ? sql`AND source != ALL(${AUDIT_ROW_SOURCES}::text[])` : sql``} + ${grepPat ? sql`AND fact ILIKE ${grepPat} ESCAPE '\\'` : sql``} ORDER BY created_at DESC, id DESC LIMIT ${limit} OFFSET ${offset} `; @@ -419,11 +435,14 @@ export async function listSupersessions( export async function countUnconsolidatedFacts(deps: PgFactsDeps, source_id: string): Promise { const sql = deps.sql; + // Audit checkpoint rows never set consolidated_at, so without the source + // exclusion each one counts as forever-pending consolidation backlog. const rows = await sql<{ count: number }[]>` SELECT COUNT(*)::int AS count FROM facts WHERE source_id = ${source_id} AND consolidated_at IS NULL AND expired_at IS NULL + AND source != ALL(${AUDIT_ROW_SOURCES}::text[]) `; return Number(rows[0]?.count ?? 0); } diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.ts index 5c731557..08c3c700 100644 --- a/src/core/schema-embedded.generated.ts +++ b/src/core/schema-embedded.generated.ts @@ -1175,8 +1175,12 @@ CREATE TABLE IF NOT EXISTS dream_verdicts ( entities JSONB, model TEXT, triage_version INT, + -- #4069 (migration v138): 30-day verdict TTL. Reads treat expired rows as + -- misses; the synthesize phase sweeps them best-effort. + expires_at TIMESTAMPTZ NOT NULL DEFAULT (now() + interval '30 days'), PRIMARY KEY (file_path, content_hash) ); +CREATE INDEX IF NOT EXISTS dream_verdicts_expires_idx ON dream_verdicts (expires_at); -- ============================================================ -- Cycle coordination lock — v0.17 runCycle primitive diff --git a/src/core/schema-pack/index.ts b/src/core/schema-pack/index.ts index dc405508..c791393b 100644 --- a/src/core/schema-pack/index.ts +++ b/src/core/schema-pack/index.ts @@ -99,6 +99,7 @@ export { export { loadActivePack, loadResolvedPackByName, + resolveLoadedPack, resolveActivePackNameOnly, __setPackLocatorForTests, _resetPackLocatorForTests, diff --git a/src/core/schema-pack/load-active.ts b/src/core/schema-pack/load-active.ts index d8809c66..61c41498 100644 --- a/src/core/schema-pack/load-active.ts +++ b/src/core/schema-pack/load-active.ts @@ -153,6 +153,18 @@ export async function loadActivePack(input: LoadActivePackInput): Promise` resolves by name via loadResolvedPackByName, #4501). + */ +export async function resolveLoadedPack(manifest: SchemaPackManifest): Promise { // Thread the locator so resolvePack can snapshot file paths + mtimes // for the stat-TTL gate on subsequent calls (codex C6 + D11 + D13). return await resolvePack(manifest, loadPackManifestByName, { diff --git a/src/core/search/hybrid.ts b/src/core/search/hybrid.ts index d7077d41..a40d410f 100644 --- a/src/core/search/hybrid.ts +++ b/src/core/search/hybrid.ts @@ -230,7 +230,9 @@ const DEBUG = process.env.GBRAIN_SEARCH_DEBUG === '1'; /** * Apply backlink boost to a result list in place. Mutates each result's score * by (1 + BACKLINK_BOOST_COEF * log(1 + count)). Pure data transform; no DB call. - * Caller fetches counts via engine.getBacklinkCounts. + * Caller fetches counts via engine.getBacklinkCounts. Counts are keyed by + * page_id, not slug, so namesake slugs across sources never share a boost + * (#4380). * * v0.35.6.0 — floor-ratio gate. When `floorThreshold` is provided, results * with `r.score < floorThreshold` are SKIPPED (no boost applied). NaN scores @@ -246,13 +248,13 @@ const DEBUG = process.env.GBRAIN_SEARCH_DEBUG === '1'; */ export function applyBacklinkBoost( results: SearchResult[], - counts: Map, + counts: Map, floorThreshold?: number, ): void { for (const r of results) { if (!Number.isFinite(r.score)) continue; if (floorThreshold !== undefined && r.score < floorThreshold) continue; - const count = counts.get(r.slug) ?? 0; + const count = counts.get(r.page_id) ?? 0; if (count > 0) { const factor = 1.0 + BACKLINK_BOOST_COEF * Math.log(1 + count); r.score *= factor; @@ -551,8 +553,8 @@ export async function runPostFusionStages( // Backlink stage (existing behavior, preserved). if (opts.applyBacklinks) { try { - const slugs = Array.from(new Set(results.map(r => r.slug))); - const counts = await engine.getBacklinkCounts(slugs); + const pageIds = Array.from(new Set(results.map(r => r.page_id))); + const counts = await engine.getBacklinkCounts(pageIds); applyBacklinkBoost(results, counts, floorThreshold); } catch { // Non-fatal; preserves the existing pre-v0.29.1 contract. diff --git a/src/core/sweep.ts b/src/core/sweep.ts index 6f641b1c..902f0428 100644 --- a/src/core/sweep.ts +++ b/src/core/sweep.ts @@ -393,9 +393,20 @@ async function runLinksTimelinePass( } } const { allSlugs, slugToSources } = await lookupRefsForSlugs(engine, [...needed]); + // #3478: the 'default' fallback is a federation feature — a sweep over an + // isolated source must not push cross-source edges. Single-row fetchSource + // (not loadAllSources) keeps the sweep's bounded-cost discipline; a missing + // sources row fails closed to isolated. + const { fetchSource, isSourceFederated } = await import('./sources-load.ts'); + const sourceRow = await fetchSource(engine, sourceId); + const allowCrossSource = sourceRow !== null && isSourceFederated(sourceRow.config); for (const { slug, candidates } of pageCandidates) { for (const c of candidates) { - const resolved = resolveCandidateSources(c, slug, sourceId, allSlugs, slugToSources); + // #2589: a cross_source drop here means the target exists only in + // other sources and cross-source links are off — the sweep skips it + // exactly like the extract paths do (extract.ts counts these; the + // sweep has no drop ledger). + const resolved = resolveCandidateSources(c, slug, sourceId, allSlugs, slugToSources, allowCrossSource); if (!resolved.ok) continue; linkBatch.push({ from_slug: resolved.fromSlug, diff --git a/src/core/think/cite-render.ts b/src/core/think/cite-render.ts index 25168973..11451055 100644 --- a/src/core/think/cite-render.ts +++ b/src/core/think/cite-render.ts @@ -101,10 +101,19 @@ export function normalizeStructuredCitations( return { citations, warnings }; } +/** Machine-stable closure key: `slug` for page citations, `slug#row` for take citations. */ +function citationKey(c: ParsedCitation): string { + return c.row_num === null ? c.page_slug : `${c.page_slug}#${c.row_num}`; +} + /** * Combine the structured citations + body fallback into a single resolved * list. Strategy: - * - If structured has any valid entries, use them as the source of truth. + * - If structured has any valid entries, use them as the source of truth, + * but still parse the inline markers and warn on any delta between the + * two sets (#4376: a drifted/fabricated visible marker otherwise + * surfaces with zero warnings). Warn-only — per the trust contract + * above, a mismatch never fails the synthesis. * - Otherwise fall back to the inline-marker scan and emit a warning so * callers know the synthesis was rendered without explicit structured * citations. @@ -115,7 +124,21 @@ export function resolveCitations( ): { citations: ParsedCitation[]; warnings: string[]; usedFallback: boolean } { const structured = normalizeStructuredCitations(structuredRaw); if (structured.citations.length > 0) { - return { citations: structured.citations, warnings: structured.warnings, usedFallback: false }; + const warnings = [...structured.warnings]; + const inline = parseInlineCitations(answerBody); + const inlineKeys = new Set(inline.map(citationKey)); + const structuredKeys = new Set(structured.citations.map(citationKey)); + for (const c of inline) { + if (!structuredKeys.has(citationKey(c))) { + warnings.push(`CITATIONS_INLINE_NOT_IN_STRUCTURED:${citationKey(c)}`); + } + } + for (const c of structured.citations) { + if (!inlineKeys.has(citationKey(c))) { + warnings.push(`CITATIONS_STRUCTURED_NOT_INLINE:${citationKey(c)}`); + } + } + return { citations: structured.citations, warnings, usedFallback: false }; } const fallback = parseInlineCitations(answerBody); const warnings = [...structured.warnings, 'CITATIONS_REGEX_FALLBACK']; diff --git a/src/core/think/index.ts b/src/core/think/index.ts index 9f0f53d7..113a31ce 100644 --- a/src/core/think/index.ts +++ b/src/core/think/index.ts @@ -150,12 +150,13 @@ export interface ThinkResponse { * non-empty gather). `ok` is the only value that marks a real answer. */ export type ThinkSynthesisStatus = - | 'ok' // parsed JSON with a non-empty answer - | 'empty_answer' // parsed JSON, answer empty - | 'not_json' // unparseable output: malformed JSON, refusals, the graceful sentinel - | 'no_llm' // no key configured — gather-only stub - | 'model_unusable' // configured model failed the probe (unknown provider/model) - | 'llm_error'; // client.create() threw (429 / timeout / 5xx / network) + | 'ok' // parsed JSON with a non-empty answer + | 'empty_answer' // parsed JSON, answer empty + | 'not_json' // unparseable output: malformed JSON, refusals, the graceful sentinel + | 'output_truncated' // unparseable because stop_reason=max_tokens cut the envelope (#4375) + | 'no_llm' // no key configured — gather-only stub + | 'model_unusable' // configured model failed the probe (unknown provider/model) + | 'llm_error'; // client.create() threw (429 / timeout / 5xx / network) export interface ThinkResult { question: string; @@ -229,12 +230,18 @@ const THINKING_DEFAULT_MAX_OUTPUT_TOKENS = 16000; // 4000 default. const OPENAI_REASONING_MODEL_RE = /^openai[:/](?:gpt-5|o[0-9]+)(?:[.-]|$)/i; const OPENAI_CHAT_SNAPSHOT_RE = /-chat(?:-|$)/i; // gpt-5-chat-latest, gpt-5.2-chat-latest +// #4375: the default deep tier (anthropic:claude-opus-4-7) routinely needs +// more than 4000 tokens for the synthesis JSON envelope; at 4000 the envelope +// truncates mid-stream. Anthropic-scoped only (same spelling variants as +// THINKING_BY_DEFAULT_MODEL_RE), so provider hard caps (DeepSeek 8192, +// gpt-4o) are unaffected; providers bill actual tokens, not the cap. +const ANTHROPIC_CLAUDE_4X_MODEL_RE = /(?:^|[:/])(?:anthropic[:/])?claude-(?:opus|sonnet|haiku)-4-\d/i; export function maxOutputTokensFor(modelStr: string): number { const openaiReasoning = OPENAI_REASONING_MODEL_RE.test(modelStr) && !OPENAI_CHAT_SNAPSHOT_RE.test(modelStr); // Shared name-based predicate (#4087: one source of truth in gateway.ts — // provider-prefixed + bare Claude 5 spellings, never 3.5-era models). - if (isThinkingByDefaultModel(modelStr) || openaiReasoning) { + if (isThinkingByDefaultModel(modelStr) || openaiReasoning || ANTHROPIC_CLAUDE_4X_MODEL_RE.test(modelStr)) { return THINKING_DEFAULT_MAX_OUTPUT_TOKENS; } // Recipe-declared thinking-by-default (gbrain#4172, e.g. DeepSeek v4): @@ -817,11 +824,20 @@ export async function runThink( const text = block && 'text' in block ? block.text : ''; const parsed = tryParseJSON(text); if (!parsed || typeof parsed !== 'object') { - warnings.push('LLM_OUTPUT_NOT_JSON'); + // #4375: a max_tokens stop means the envelope was CUT, not malformed — + // label it honestly so operators raise the budget instead of chasing + // model-output bugs. The adapter maps gateway 'length' to 'max_tokens'. + const stop = (created as { stop_reason?: string }).stop_reason; + if (stop === 'max_tokens') { + warnings.push('LLM_OUTPUT_TRUNCATED'); + synthesisStatus = 'output_truncated'; + } else { + warnings.push('LLM_OUTPUT_NOT_JSON'); + // Refusals + the graceful sentinel land here too — coarse on purpose + // (no dedicated status; the raw text stays in `answer` for consumers). + synthesisStatus = 'not_json'; + } synthesisOk = false; // #1698: malformed output (and the non-JSON graceful sentinel) - // Refusals + the graceful sentinel land here too — coarse on purpose - // (no dedicated status; for PROSE the raw text stays in `answer`). - synthesisStatus = 'not_json'; // #4509: a malformed JSON envelope (max-token truncation is the // common cause) previously shipped VERBATIM as the user-facing // answer. Salvage the answer/citations/gaps fields tolerantly; when @@ -855,6 +871,18 @@ export async function runThink( for (const w of resolved.warnings) warnings.push(w); } + // #4376: close resolved citations against the gathered evidence — a cited + // slug absent from every gather stream is unverifiable provenance. Warn-only; + // the never-fail synthesis contract (cite-render.ts) stays intact. + const gatheredSlugs = new Set([ + ...gather.pages.map(p => p.slug), + ...gather.takes.map(t => t.page_slug), + ...gather.graphSlugs, + ]); + for (const slug of new Set(resolved.citations.map(c => c.page_slug))) { + if (!gatheredSlugs.has(slug)) warnings.push(`CITATION_NOT_IN_GATHER:${slug}`); + } + // Round-loop scaffolding (rounds > 1 currently re-runs without gap-driven retrieval). // The loop is in place so the v0.29 gap-fill heuristic doesn't change the call site. for (let r = 1; r < rounds; r++) { diff --git a/src/core/transcripts/ingest.ts b/src/core/transcripts/ingest.ts index 5ed33642..8cb9f0bb 100644 --- a/src/core/transcripts/ingest.ts +++ b/src/core/transcripts/ingest.ts @@ -18,7 +18,8 @@ * file continues. * - RUN-LEVEL (fail-closed integrity): importFromContent duplicate-lookup * or read-back failures and putRawData misses rethrow and abort the run. - * Heuristic seam: import errors matching /too large/ stay per-session. + * Heuristic seam: import errors matching /too large|invalid byte + * sequence/ stay per-session. * * Watermark: the RESULT carries `cleanScan` (no errors anywhere, no limit * truncation) + `maxSessionTs`; the COMMAND advances the `--since last` @@ -144,7 +145,9 @@ function lastMessageTs(messages: Array<{ timestamp: string }>): string { const RUN_ABORT_MARKER = 'transcripts-ingest run abort'; function isPerSessionImportError(err: unknown): boolean { - return err instanceof Error && /too large/i.test(err.message); + // 'invalid byte sequence' is Postgres rejecting the DATA (e.g. a U+0000 a + // sanitizer missed, #4392) — one bad session, never a DB-down signal. + return err instanceof Error && /too large|invalid byte sequence/i.test(err.message); } export async function runTranscriptsIngest( diff --git a/src/core/transcripts/render.ts b/src/core/transcripts/render.ts index b2eaefe9..feed32e1 100644 --- a/src/core/transcripts/render.ts +++ b/src/core/transcripts/render.ts @@ -33,6 +33,7 @@ import { join } from 'node:path'; import { DEFAULT_BYTES_BLOCK } from '../content-sanity.ts'; import { redactFindings } from '../secret-scan.ts'; import { loadPatterns } from '../skillpack/harvest-lint.ts'; +import { sanitizeForJsonb } from '../batch-rows.ts'; import { ensureWellFormed, truncateUtf8 } from '../text-safe.ts'; import { BUILTIN_PATTERNS } from '../conversation-parser/builtins.ts'; import type { ParsedSession, TranscriptMessage } from './types.ts'; @@ -122,7 +123,10 @@ export function redactSession( let imperativesFlagged = 0; const clean = (text: string): string => { - let out = ensureWellFormed(text); + // sanitizeForJsonb (NUL-strip + well-form): transcripts capture raw tool + // output that legitimately carries U+0000, which Postgres text/jsonb + // reject at the write boundary (#4392). + let out = sanitizeForJsonb(text); const r = redactFindings(out); redactionCount += r.redactions.length; out = r.text; diff --git a/src/core/types.ts b/src/core/types.ts index 44644f93..26e4ca93 100644 --- a/src/core/types.ts +++ b/src/core/types.ts @@ -491,10 +491,10 @@ export interface SalienceResult { * * Why a dedicated engine method instead of composing `listPages` + * `getBacklinkCounts` in memory: - * - `getBacklinkCounts` groups by bare `slug`, so the same slug in two - * sources collapses/contaminates the count. This query counts inbound - * links per page row (`to_page_id = p.id`), which is source-correct by - * construction. + * - `getBacklinkCounts` is page-id-keyed (source-correct since #4380), + * but composing it with `listPages` in memory still costs a second + * round-trip. This query counts inbound links per page row + * (`to_page_id = p.id`) inside the one source-scoped query. * - `listPages` returns full `Page` rows (bodies). 500 stub bodies per * type per source is not a memory guarantee. This projection carries * only `body_len`, never the body. diff --git a/src/core/verbs.ts b/src/core/verbs.ts index 65ab7d1c..ca300e7f 100644 --- a/src/core/verbs.ts +++ b/src/core/verbs.ts @@ -216,6 +216,7 @@ const entity: Operation = { // messages) ride `detail` only; the message carries the code. const SYNTHESIS_FAILURE_CODES: Record = { not_json: 'LLM_OUTPUT_NOT_JSON', + output_truncated: 'LLM_OUTPUT_TRUNCATED', empty_answer: 'SYNTHESIS_EMPTY_ANSWER', llm_error: 'LLM_CALL_FAILED', model_unusable: 'MODEL_NOT_USABLE', @@ -432,7 +433,7 @@ const STATUS_ENUM = ['inserted', 'duplicate', 'superseded']; // fallback or a typed `unavailable` error) and stay enum-listed so any // v1 server emitting them validates. const SYNTHESIS_STATUS_ENUM = [ - 'ok', 'empty_answer', 'not_json', 'no_llm', 'model_unusable', 'llm_error', 'extractive_fallback', + 'ok', 'empty_answer', 'not_json', 'output_truncated', 'no_llm', 'model_unusable', 'llm_error', 'extractive_fallback', ]; export const RESPONSE_SCHEMAS: Record> = { diff --git a/src/core/verbs/entity-card.ts b/src/core/verbs/entity-card.ts index 94656fd7..4e8142dd 100644 --- a/src/core/verbs/entity-card.ts +++ b/src/core/verbs/entity-card.ts @@ -237,7 +237,7 @@ async function assembleCard( // [ship P1.2] Incoming edges + backlink_count are SOURCE-SAFE on BOTH sides. // engine.getBacklinks(slug,{sourceId}) only scopes the TARGET page's source, // so a foreign-source page linking to a same-named entity would leak its - // slug; engine.getBacklinkCounts has no source param at all. We instead run + // slug; engine.getBacklinkCounts counts inbound from ALL sources. We run // a both-sides-scoped query here (f.source_id = t.source_id = this source), // mentions excluded (matching the backlink-count convention). Outgoing edges // (getLinks) are the entity's OWN declared links — from-side scoped — so they diff --git a/src/core/write-through.ts b/src/core/write-through.ts index 7a86eaef..13f4c5fb 100644 --- a/src/core/write-through.ts +++ b/src/core/write-through.ts @@ -196,9 +196,48 @@ export async function isWriteThroughDisabled(engine: BrainEngine): Promise { let filePath: string; let writeRoot: string; + let scanRoot: string; const srcRows = await engine.executeRaw<{ local_path: string | null }>( `SELECT local_path FROM sources WHERE id = $1`, [sourceId], @@ -269,6 +309,7 @@ export async function resolvePageWriteTarget( ? resolveSourceLocalFilePath(sourceLocalPath, recordedPath) ?? join(sourceLocalPath, `${slug}.md`) : join(sourceLocalPath, recordedPathFromFileUri(recordedUri, sourceLocalPath) ?? `${slug}.md`); // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- result passes isWriteTargetContained before any write (#4204/#4289 guard) writeRoot = sourceLocalPath; + scanRoot = sourceLocalPath; } else { const repoPath = await engine.getConfig('sync.repo_path'); if (!repoPath) { @@ -290,6 +331,9 @@ export async function resolvePageWriteTarget( const knownPath = recordedPath ?? recordedPathFromFileUri(recordedUri, pageRoot); filePath = knownPath ? join(pageRoot, knownPath) : resolvePageFilePath(repoPath, slug, sourceId); writeRoot = repoPath; + // pageRoot, not repoPath: a later `sources add --path ` scan + // walks pageRoot, so the bind must speak that scan's convention. + scanRoot = pageRoot; } // Defense-in-depth (#1647-slug / codex #6): confirm the computed file path @@ -301,7 +345,7 @@ export async function resolvePageWriteTarget( return { ok: false, skipped: 'path_escapes_source_root' }; } - return { ok: true, filePath, writeRoot }; + return { ok: true, filePath, writeRoot, sourcePathToBind: scannerSourcePath(scanRoot, filePath) }; } /** @@ -329,7 +373,7 @@ export async function writePageThrough( if (!target.ok) { return { written: false, skipped: target.skipped }; } - const { filePath, writeRoot } = target; + const { filePath, writeRoot, sourcePathToBind } = target; const writtenPage = await engine.getPage(slug, { sourceId }); if (!writtenPage) { @@ -388,6 +432,26 @@ export async function writePageThrough( 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}`); + } + // #2426: on a durability-hardened repo (user ran `gbrain sources harden`), // commit the artifact so it reaches git — pre-fix, write-through content // stayed uncommitted forever: never pushed, `last_sync_at` frozen, and @@ -418,3 +482,73 @@ export async function writePageThrough( return { written: false, error: msg }; } } + +export interface DeleteThroughResult { + /** True when an artifact existed and was unlinked. */ + removed: boolean; + /** The path that was removed (or would have been). */ + path?: string; + /** + * Non-error reasons nothing was removed. Shares the target-resolution skip + * vocabulary (kept in lockstep via the Extract), plus: + * - disabled_by_config: the operator opted the brain out of the disk sink. + * - file_not_present: the page had no artifact on disk (DB-only page, or + * already removed by hand) — a clean no-op, not a failure. + */ + skipped?: 'disabled_by_config' | 'file_not_present' | Extract['skipped']; + /** Set when the unlink itself threw (EACCES, EPERM, read-only mount). */ + error?: string; +} + +/** + * Remove the on-disk markdown artifact for `slug` — the delete-side counterpart + * to `writePageThrough` (#4022). + * + * Why this exists: `put_page`/capture write BOTH sinks (DB row + `.md` file), + * but `delete_page` used to touch only the DB. The orphaned file then outlived + * the page, and on any repo whose brain is committed on a timer (a `snapshot` + * cron, `sources harden`'s post-commit push) the deleted page's artifact gets + * committed back into git *after* deletion — so the page reappears on the next + * `gbrain sync`, silently resurrecting content the user deleted. + * + * Deliberately mirrors `writePageThrough`'s contract: never throws, reports via + * `skipped`/`error`, and resolves its target through the shared + * `resolvePageWriteTarget` so the two planes cannot disagree about which file + * backs a page. The DB row remains the durable sink — a failure here leaves a + * stale file that the next `gbrain sync` reconciles, never a lost row. + * + * `opts.target`: resolvePageWriteTarget reads the recorded `source_path` from + * ACTIVE rows only, so the delete_page op resolves the target BEFORE + * `softDeletePage` stamps `deleted_at` and passes it here. Resolving after the + * stamp would miss the recorded path, fall back to the slug-derived twin, and + * report a clean `file_not_present` no-op while the REAL artifact stayed on + * disk — the very silent-no-op class this helper exists to close. + */ +export async function deletePageThrough( + engine: BrainEngine, + slug: string, + opts: { sourceId?: string; logger?: WriteThroughLogger; target?: PageWriteTarget } = {}, +): Promise { + const sourceId = opts.sourceId ?? 'default'; + try { + // `sync.write_through=false` means the operator opted this brain out of + // the disk sink entirely — never unlink files gbrain does not own. + if (await isWriteThroughDisabled(engine)) { + return { removed: false, skipped: 'disabled_by_config' }; + } + const target = opts.target ?? await resolvePageWriteTarget(engine, slug, sourceId); + if (!target.ok) return { removed: false, skipped: target.skipped }; + const { filePath } = target; + + if (!existsSync(filePath)) { + return { removed: false, path: filePath, skipped: 'file_not_present' }; + } + + unlinkSync(filePath); + return { removed: true, path: filePath }; + } catch (e) { + const msg = e instanceof Error ? e.message : String(e); + opts.logger?.warn(`[write-through] delete failed for ${slug}: ${msg}`); + return { removed: false, error: msg }; + } +} diff --git a/src/schema.sql b/src/schema.sql index 1040be49..c1f5d753 100644 --- a/src/schema.sql +++ b/src/schema.sql @@ -1171,8 +1171,12 @@ CREATE TABLE IF NOT EXISTS dream_verdicts ( entities JSONB, model TEXT, triage_version INT, + -- #4069 (migration v138): 30-day verdict TTL. Reads treat expired rows as + -- misses; the synthesize phase sweeps them best-effort. + expires_at TIMESTAMPTZ NOT NULL DEFAULT (now() + interval '30 days'), PRIMARY KEY (file_path, content_hash) ); +CREATE INDEX IF NOT EXISTS dream_verdicts_expires_idx ON dream_verdicts (expires_at); -- ============================================================ -- Cycle coordination lock — v0.17 runCycle primitive diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.md index c4a884bb..05386043 100644 --- a/templates/bootstrap/template-repo/README.md +++ b/templates/bootstrap/template-repo/README.md @@ -1,6 +1,6 @@ # gbrain agent workspace — template - + 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/ai/build-gateway-config.test.ts b/test/ai/build-gateway-config.test.ts index a09b4217..285438d1 100644 --- a/test/ai/build-gateway-config.test.ts +++ b/test/ai/build-gateway-config.test.ts @@ -161,6 +161,46 @@ describe('buildGatewayConfig config-plane API-key folding', () => { }); }); + // Same seam for LiteLLM + Together, closed alongside litellm's chat + // touchpoint (v0.42.61.0): once litellm became a full chat provider, + // daemon/launchd/MCP contexts hit the same config-plane gap voyage did + // (#2662). The fold lives in mergedProviderEnv (src/core/ai/provider-env.ts). + test('litellm_api_key folds into gateway env as LITELLM_API_KEY', async () => { + await withEnv({ LITELLM_API_KEY: undefined }, async () => { + const cfg = buildGatewayConfig({ + litellm_api_key: 'sk-llm-config-plane', + } as unknown as GBrainConfig); + expect(cfg.env.LITELLM_API_KEY).toBe('sk-llm-config-plane'); + }); + }); + + test('a real LITELLM_API_KEY process.env value wins over the config-plane fallback', async () => { + await withEnv({ LITELLM_API_KEY: 'sk-llm-env-plane' }, async () => { + const cfg = buildGatewayConfig({ + litellm_api_key: 'sk-llm-config-plane', + } as unknown as GBrainConfig); + expect(cfg.env.LITELLM_API_KEY).toBe('sk-llm-env-plane'); + }); + }); + + test('together_api_key folds into gateway env as TOGETHER_API_KEY', async () => { + await withEnv({ TOGETHER_API_KEY: undefined }, async () => { + const cfg = buildGatewayConfig({ + together_api_key: 'sk-tg-config-plane', + } as unknown as GBrainConfig); + expect(cfg.env.TOGETHER_API_KEY).toBe('sk-tg-config-plane'); + }); + }); + + test('a real TOGETHER_API_KEY process.env value wins over the config-plane fallback', async () => { + await withEnv({ TOGETHER_API_KEY: 'sk-tg-env-plane' }, async () => { + const cfg = buildGatewayConfig({ + together_api_key: 'sk-tg-config-plane', + } as unknown as GBrainConfig); + expect(cfg.env.TOGETHER_API_KEY).toBe('sk-tg-env-plane'); + }); + }); + // #3500: the google recipe reads GOOGLE_GENERATIVE_AI_API_KEY; before this // fold the ONLY configuration route was exporting that exact env name. test('google_api_key folds into gateway env as GOOGLE_GENERATIVE_AI_API_KEY', async () => { @@ -272,6 +312,22 @@ describe('buildGatewayConfig env empty-string clobber guard (#1249)', () => { }); }); +describe('buildGatewayConfig OCR-model threading (#4107)', () => { + // The config key was declared/env-merged/DB-merged in config.ts but never + // picked into AIGatewayConfig, so generateOcrText() could not see it. + test('embedding_image_ocr_model reaches the gateway config', () => { + const cfg = buildGatewayConfig({ + embedding_image_ocr_model: 'deepseek:deepseek-v4-pro', + } as unknown as GBrainConfig); + expect(cfg.embedding_image_ocr_model).toBe('deepseek:deepseek-v4-pro'); + }); + + test('absent embedding_image_ocr_model stays undefined (expansion fallback signal preserved)', () => { + const cfg = buildGatewayConfig(baseConfig); + expect(cfg.embedding_image_ocr_model).toBeUndefined(); + }); +}); + /** * Side-effect guard (v0.37.x): importing buildGatewayConfig from src/cli.ts * must NOT trigger the CLI's top-level main() and dump help to stdout. The diff --git a/test/ai/embed-env-batch-cap.test.ts b/test/ai/embed-env-batch-cap.test.ts new file mode 100644 index 00000000..123f5328 --- /dev/null +++ b/test/ai/embed-env-batch-cap.test.ts @@ -0,0 +1,132 @@ +/** + * GBRAIN_EMBED_MAX_BATCH_TOKENS — operator-declared batch cap for + * no_batch_cap recipes (ollama, llama-server, litellm). Reimplemented from + * PR #3622 (drdeebtech). + * + * Why: local inference servers (ollama with `-np 1`) process one request + * at a time and keep computing client-aborted requests. Without a batch + * cap, embed() sends a page's ENTIRE chunk set as one request; a request + * that outlives the embed timeout is retried forever by the stale-page + * loop while the server grinds abandoned work — a self-sustaining + * congestion collapse (observed 2026-07-29/30: 6,900+ timeouts, ~4 cores + * pinned). The recipes deliberately declare `no_batch_cap: true` because + * real capacity depends on the operator's hardware — so the cap is an + * operator env knob, mirroring GBRAIN_EMBED_CONCURRENCY. + * + * The knob is read from the gateway's configure-time env snapshot + * (`cfg.env`, Codex C3 — the gateway never reads process.env at call + * time); production folds the whole process env into that snapshot via + * buildGatewayConfig/mergedProviderEnv, so `export + * GBRAIN_EMBED_MAX_BATCH_TOKENS=2048` reaches it. Tests therefore pass the + * knob through configureGateway({env}) — hermetic, no process.env writes. + * + * Coverage: + * - env cap set + no_batch_cap recipe → pre-split into bounded batches + * - env cap absent → existing single-call fast path (regression guard) + * - invalid env values (0, negative, garbage, empty) → fast path unchanged + * - recipe-declared max_batch_tokens still wins over the env knob + */ + +import { afterAll, afterEach, beforeEach, describe, expect, mock, test } from 'bun:test'; +import { + configureGateway, + resetGateway, + embed, + __setEmbedTransportForTests, +} from '../../src/core/ai/gateway.ts'; + +// Same rationale as test/ai/adaptive-embed-batch.test.ts: without a final +// reset, this file's last gateway config leaks into whichever test file the +// shard runs next. +afterAll(() => resetGateway()); + +function fakeEmbeddings(values: string[], dims: number): { embeddings: number[][] } { + return { + embeddings: values.map((_, i) => + Array.from({ length: dims }, (_, j) => (j === 0 ? i : 0.1)), + ), + }; +} + +const ENV_KEY = 'GBRAIN_EMBED_MAX_BATCH_TOKENS'; + +function configureOllama(env: Record = {}): void { + configureGateway({ + embedding_model: 'ollama:nomic-embed-text', + embedding_dimensions: 768, + env, + }); +} + +describe('GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes', () => { + beforeEach(() => resetGateway()); + afterEach(() => __setEmbedTransportForTests(null)); + + test('env cap set → ollama batches are pre-split and each stays within the token budget', async () => { + configureOllama({ [ENV_KEY]: '1000' }); + + const stub = mock(async ({ values }: { values: string[] }) => fakeEmbeddings(values, 768)); + __setEmbedTransportForTests(stub as any); + + // 10 texts × 2000 chars = 500 tokens each at the default 4 chars/token. + // Budget 1000 tokens → at most 2 texts per batch (fewer once the default + // safety factor tightens it) → several transport calls, never 1. + const texts = Array.from({ length: 10 }, (_, i) => `${i}`.repeat(2000)); + const result = await embed(texts); + + expect(result).toHaveLength(10); + expect(stub.mock.calls.length).toBeGreaterThan(1); + for (const [arg] of stub.mock.calls) { + const batch = (arg as { values: string[] }).values; + const batchChars = batch.reduce((s, t) => s + t.length, 0); + // 1000 tokens × 4 chars/token = 4000 chars absolute ceiling per batch + // (the safety factor only ever tightens below this). + expect(batchChars).toBeLessThanOrEqual(4000); + } + }); + + test('env cap absent → single transport call (existing fast-path preserved)', async () => { + configureOllama({}); + + const stub = mock(async ({ values }: { values: string[] }) => fakeEmbeddings(values, 768)); + __setEmbedTransportForTests(stub as any); + + const texts = Array.from({ length: 10 }, (_, i) => `${i}`.repeat(2000)); + const result = await embed(texts); + + expect(stub).toHaveBeenCalledTimes(1); + expect(result).toHaveLength(10); + }); + + test.each(['0', '-5', 'abc', ''])('invalid env value %j → fast path unchanged', async (bad) => { + configureOllama({ [ENV_KEY]: bad }); + + const stub = mock(async ({ values }: { values: string[] }) => fakeEmbeddings(values, 768)); + __setEmbedTransportForTests(stub as any); + + const result = await embed(['a'.repeat(8000), 'b'.repeat(8000)]); + expect(stub).toHaveBeenCalledTimes(1); + expect(result).toHaveLength(2); + }); + + test('recipe-declared max_batch_tokens wins over a larger env value', async () => { + // Voyage declares max_batch_tokens=120000 with safety_factor 0.5 → + // 60K-token effective budget. A huge env value must NOT loosen it. + configureGateway({ + embedding_model: 'voyage:voyage-3-large', + embedding_dimensions: 1024, + env: { VOYAGE_API_KEY: 'sk-fake', [ENV_KEY]: '99000000' }, + }); + + const stub = mock(async ({ values }: { values: string[] }) => fakeEmbeddings(values, 1024)); + __setEmbedTransportForTests(stub as any); + + // 20 texts × 8000 chars (= MAX_CHARS, so no truncation) = 8000 tokens + // each at voyage's 1 char/token density → 160K tokens total against a + // 60K effective budget → must split into >1 call. If the env value + // (99M) leaked past the recipe cap, everything would fit in 1 call. + const texts = Array.from({ length: 20 }, (_, i) => `${i % 10}`.repeat(8000)); + await embed(texts); + expect(stub.mock.calls.length).toBeGreaterThan(1); + }); +}); diff --git a/test/ai/embed-keyless-base-url.test.ts b/test/ai/embed-keyless-base-url.test.ts new file mode 100644 index 00000000..8316d6f2 --- /dev/null +++ b/test/ai/embed-keyless-base-url.test.ts @@ -0,0 +1,88 @@ +/** + * #4385 — keyless local OpenAI-compatible embedding via OPENAI_BASE_URL. + * + * A configured OPENAI_BASE_URL points the native-openai embedding path at a + * local OpenAI-compatible server (LM Studio, vLLM) that needs no real key — + * the SDK only requires a non-empty string. Pins: + * - embed() with OPENAI_BASE_URL set and no OPENAI_API_KEY does not throw + * AIConfigError (the base-URL override satisfies the key requirement). + * - diagnoseEmbedding() reports ok under the same config, so the + * sync/embed/import credential preflight passes too. + * - With neither key nor base URL, both paths still fail closed. + */ + +import { describe, test, expect, afterEach } from 'bun:test'; +import { + configureGateway, + resetGateway, + embed, + diagnoseEmbedding, + __setEmbedTransportForTests, +} from '../../src/core/ai/gateway.ts'; +import { AIConfigError } from '../../src/core/ai/errors.ts'; + +// The issue's exact configuration: LM Studio serving a qwen3 embedding model. +const LOCAL_BASE_URL = 'http://127.0.0.1:1234/v1'; +const MODEL = 'openai:text-embedding-qwen3-embedding-0.6b'; +const DIMS = 1024; + +function configureWith(env: Record): void { + configureGateway({ + embedding_model: MODEL, + embedding_dimensions: DIMS, + env, + }); +} + +function fakeEmbeddings(count: number, dims: number) { + return { + embeddings: Array.from({ length: count }, () => + Array.from({ length: dims }, () => 0.1), + ), + }; +} + +afterEach(() => { + __setEmbedTransportForTests(null); + resetGateway(); +}); + +describe('keyless embedding via OPENAI_BASE_URL (#4385)', () => { + test('embed() succeeds with OPENAI_BASE_URL set and no OPENAI_API_KEY', async () => { + configureWith({ OPENAI_BASE_URL: LOCAL_BASE_URL }); + __setEmbedTransportForTests((async (args: any) => + fakeEmbeddings(args.values.length, DIMS)) as any); + const vectors = await embed(['hello']); + expect(vectors).toHaveLength(1); + expect(vectors[0]).toBeInstanceOf(Float32Array); + expect(vectors[0].length).toBe(DIMS); + }); + + test('embed() still fails closed with neither key nor base URL', async () => { + configureWith({}); + __setEmbedTransportForTests((async (args: any) => + fakeEmbeddings(args.values.length, DIMS)) as any); + await expect(embed(['hello'])).rejects.toThrow(AIConfigError); + await expect(embed(['hello'])).rejects.toThrow(/OPENAI_API_KEY/); + }); + + // No transport stub here: diagnoseEmbedding's test-transport fast path + // would short-circuit to ok and mask the credential logic under test. + test('diagnoseEmbedding: base-URL override satisfies the key requirement', () => { + configureWith({ OPENAI_BASE_URL: LOCAL_BASE_URL }); + const d = diagnoseEmbedding(); + expect(d.ok).toBe(true); + }); + + test('diagnoseEmbedding: neither key nor base URL → missing_env', () => { + configureWith({}); + const d = diagnoseEmbedding(); + expect(d.ok).toBe(false); + if (!d.ok) { + expect(d).toMatchObject({ + reason: 'missing_env', + missingEnvVars: ['OPENAI_API_KEY'], + }); + } + }); +}); diff --git a/test/ai/gateway-chat.test.ts b/test/ai/gateway-chat.test.ts index d229f66d..8643b7e9 100644 --- a/test/ai/gateway-chat.test.ts +++ b/test/ai/gateway-chat.test.ts @@ -386,6 +386,41 @@ describe('chat touchpoint — provider_chat_options passthrough', () => { expect(providerOptions).toBeUndefined(); }); + test('call-scoped providerOptions merge last without dropping configured siblings', async () => { + const providerOptions = await captureProviderOptions({ + chat_model: 'deepseek:deepseek-v4-flash', + provider_chat_options: { + deepseek: { temperature: 0.2 }, + }, + env: { DEEPSEEK_API_KEY: 'fake' }, + }, { + providerOptions: { deepseek: { thinking: { type: 'disabled' } } }, + }); + + expect(providerOptions).toEqual({ + deepseek: { temperature: 0.2, thinking: { type: 'disabled' } }, + }); + }); + + test('call-scoped providerOptions win over configured options on key conflict', async () => { + // The call site pins behavior it depends on (e.g. the triage judge + // disabling DeepSeek thinking); config-level provider_chat_options must + // not silently override it. + const providerOptions = await captureProviderOptions({ + chat_model: 'deepseek:deepseek-v4-flash', + provider_chat_options: { + deepseek: { thinking: { type: 'enabled' } }, + }, + env: { DEEPSEEK_API_KEY: 'fake' }, + }, { + providerOptions: { deepseek: { thinking: { type: 'disabled' } } }, + }); + + expect(providerOptions).toEqual({ + deepseek: { thinking: { type: 'disabled' } }, + }); + }); + test('anthropic cacheControl survives provider_chat_options merging', async () => { // gbrain#2490: this call-level cacheControl is real (not a no-op) — // @ai-sdk/anthropic serializes it as the Anthropic API's documented diff --git a/test/ai/ocr-model-routing.test.ts b/test/ai/ocr-model-routing.test.ts new file mode 100644 index 00000000..32023624 --- /dev/null +++ b/test/ai/ocr-model-routing.test.ts @@ -0,0 +1,159 @@ +/** + * #4107 — `embedding_image_ocr_model` routing. + * + * The config key was declared, env-merged, DB-merged, and allowlisted + * (src/core/config.ts), but generateOcrText() unconditionally resolved the + * EXPANSION model, so the configured OCR model never received a single + * request. Pins: + * - getImageOcrModel() accessor: configured value wins; expansion fallback + * when unset; getExpansionModel() unaffected either way + * - wire routing: generateOcrText() posts body.model = the OCR model while + * expand() still posts the expansion model (the two route independently) + * - fail-closed: an OCR model on a provider without an expansion touchpoint + * yields '' with ZERO network calls (never silently OCRs with the + * expansion model) + * - key independence: OCR works when the OCR model's provider is keyed even + * if the expansion model's provider is not + * + * Hermetic: globalThis.fetch stubbed (gateway.test.ts Voyage-shim precedent), + * restored in afterEach; provider env passes explicitly via configureGateway + * (the provider-keys preload strips ambient keys). DeepSeek is used because + * it is openai-compatible with an expansion touchpoint, so assertTouchpoint + * passes and the wire body is a plain JSON chat completion; model ids are + * the recipe's current (non-retired) v4 names. + */ +import { describe, test, expect, beforeEach, afterEach } from 'bun:test'; +import { + configureGateway, + resetGateway, + generateOcrText, + expand, + getExpansionModel, +} from '../../src/core/ai/gateway.ts'; + +// Looked up dynamically so this file still RUNS (and fails at the assertion +// level, not import time) against pre-#4107 builds missing the export. +async function callGetImageOcrModel(): Promise { + const mod = (await import('../../src/core/ai/gateway.ts')) as { + getImageOcrModel?: () => string; + }; + if (typeof mod.getImageOcrModel !== 'function') { + throw new Error('getImageOcrModel is not exported from the gateway'); + } + return mod.getImageOcrModel(); +} + +const EXPANSION_MODEL = 'deepseek:deepseek-v4-flash'; +const OCR_MODEL = 'deepseek:deepseek-v4-pro'; + +const realFetch = globalThis.fetch; + +beforeEach(() => resetGateway()); +afterEach(() => { + globalThis.fetch = realFetch; + resetGateway(); +}); + +/** Stub the wire, capturing every JSON request body, answering `content`. */ +function stubChatCompletions( + captured: Array>, + content: string, +): void { + globalThis.fetch = (async (url: string | URL | Request, init?: RequestInit) => { + const urlStr = typeof url === 'string' ? url : url instanceof URL ? url.href : url.url; + // The SDK downloads the data: image URL through fetch too — serve it with + // the real fetch so `captured` holds only chat-completion POST bodies. + if (urlStr.startsWith('data:')) return realFetch(url as never, init as never); + const body = JSON.parse(String(init?.body ?? '{}')) as Record; + captured.push(body); + return new Response( + JSON.stringify({ + id: 'chatcmpl-test', + object: 'chat.completion', + created: 0, + model: String(body.model ?? ''), + choices: [ + { index: 0, message: { role: 'assistant', content }, finish_reason: 'stop' }, + ], + usage: { prompt_tokens: 10, completion_tokens: 5, total_tokens: 15 }, + }), + { status: 200, headers: { 'content-type': 'application/json' } }, + ); + }) as unknown as typeof fetch; +} + +describe('getImageOcrModel accessor (#4107)', () => { + test('configured embedding_image_ocr_model wins; expansion model unchanged', async () => { + configureGateway({ + expansion_model: EXPANSION_MODEL, + embedding_image_ocr_model: OCR_MODEL, + env: { DEEPSEEK_API_KEY: 'sk-test-ocr' }, + }); + expect(await callGetImageOcrModel()).toBe(OCR_MODEL); + expect(getExpansionModel()).toBe(EXPANSION_MODEL); + }); + + test('falls back to the expansion model when unset', async () => { + configureGateway({ + expansion_model: EXPANSION_MODEL, + env: { DEEPSEEK_API_KEY: 'sk-test-ocr' }, + }); + expect(await callGetImageOcrModel()).toBe(EXPANSION_MODEL); + }); +}); + +describe('generateOcrText wire routing (#4107)', () => { + test('OCR posts the OCR model; expand() still posts the expansion model', async () => { + const captured: Array> = []; + stubChatCompletions(captured, 'HELLO'); + configureGateway({ + expansion_model: EXPANSION_MODEL, + embedding_image_ocr_model: OCR_MODEL, + env: { DEEPSEEK_API_KEY: 'sk-test-ocr' }, + }); + + const text = await generateOcrText(Buffer.from('x'), 'image/png'); + expect(text).toBe('HELLO'); + expect(captured.length).toBe(1); + expect(captured[0].model).toBe('deepseek-v4-pro'); + + // expand() is best-effort: a non-JSON answer degrades to [query], but the + // request it sent still proves which model the expansion path resolved. + await expand('probe query'); + expect(captured.length).toBe(2); + expect(captured[1].model).toBe('deepseek-v4-flash'); + }); + + test('fail-closed: OCR model on a provider without an expansion touchpoint yields "" and no wire call', async () => { + const captured: Array> = []; + stubChatCompletions(captured, 'HELLO'); + configureGateway({ + expansion_model: EXPANSION_MODEL, + // voyage has no expansion touchpoint — isAvailable must gate on the + // OCR model, never silently OCR with the expansion model instead. + embedding_image_ocr_model: 'voyage:voyage-3-large', + env: { DEEPSEEK_API_KEY: 'sk-test-ocr', VOYAGE_API_KEY: 'pa-test' }, + }); + + const text = await generateOcrText(Buffer.from('x'), 'image/png'); + expect(text).toBe(''); + expect(captured.length).toBe(0); + }); + + test('key independence: OCR works when only the OCR model\'s provider is keyed', async () => { + const captured: Array> = []; + stubChatCompletions(captured, 'OCR TEXT'); + configureGateway({ + // Expansion pinned to an unkeyed provider: pre-#4107 the gate checked + // THIS model's availability and silently disabled OCR. + expansion_model: 'anthropic:claude-haiku-4-5-20251001', + embedding_image_ocr_model: OCR_MODEL, + env: { DEEPSEEK_API_KEY: 'sk-test-ocr' }, + }); + + const text = await generateOcrText(Buffer.from('x'), 'image/png'); + expect(text).toBe('OCR TEXT'); + expect(captured.length).toBe(1); + expect(captured[0].model).toBe('deepseek-v4-pro'); + }); +}); diff --git a/test/ai/ollama-library-tag-dims.test.ts b/test/ai/ollama-library-tag-dims.test.ts new file mode 100644 index 00000000..398a6385 --- /dev/null +++ b/test/ai/ollama-library-tag-dims.test.ts @@ -0,0 +1,97 @@ +/** + * Ollama library-tag dims — coverage for the pullable-tag catalog refresh. + * + * The ollama recipe gained the REAL Ollama library spellings + * (`qwen3-embedding:8b`, `snowflake-arctic-embed2`) alongside the legacy + * never-pullable spellings (`qwen3-embed-8b`, `snowflake-arctic-embed-l-v2`). + * `qwen3-embedding:8b` is the first colon-bearing model tag in any recipe's + * models list, which makes it the first tag to exercise + * `embeddingDimsForModel()`'s strip-the-leading-`provider:`-prefix logic with + * a colon INSIDE the model id. + * + * Contract pinned here: + * - Qualified form (`ollama:qwen3-embedding:8b`) strips only the FIRST + * colon, so the tag survives and resolves to its declared 4096. This is + * the form every live caller passes (init verbose path, `gbrain + * embedding-migrate --to ...` — which rejects non-qualified input). + * - Bare colon-bearing form (`qwen3-embedding:8b`) has its `qwen3-embedding` + * head eaten by the prefix strip and falls back to default_dims (768). + * That is the documented strip-first-colon contract, NOT the tag's native + * width — colon-bearing library tags MUST be passed provider-qualified. + * If this pin ever fails because the strip became provider-aware, update + * it to 4096 and delete the caveat. + */ + +import { describe, expect, test } from 'bun:test'; +import { getRecipe } from '../../src/core/ai/recipes/index.ts'; +import { embeddingDimsForModel } from '../../src/core/ai/model-resolver.ts'; +import { resolveMigrationTarget } from '../../src/core/embedding-migration.ts'; + +describe('ollama library-tag dims — new pullable tags', () => { + const ollama = getRecipe('ollama')!; + + test('snowflake-arctic-embed2 resolves to 1024 (bare and qualified)', () => { + expect(embeddingDimsForModel(ollama, 'snowflake-arctic-embed2')).toBe(1024); + expect(embeddingDimsForModel(ollama, 'ollama:snowflake-arctic-embed2')).toBe(1024); + }); + + test('qualified ollama:qwen3-embedding:8b resolves to 4096 (colon tag survives the provider strip)', () => { + expect(embeddingDimsForModel(ollama, 'ollama:qwen3-embedding:8b')).toBe(4096); + }); + + test('CAVEAT: bare qwen3-embedding:8b falls back to default_dims — colon tags require the qualified form', () => { + // The strip-first-colon contract treats `qwen3-embedding` as a provider + // prefix and looks up `8b`, which is unlisted → default_dims (768). + // Live callers never hit this: init's verbose path passes the full + // `ollama:...` string and resolveMigrationTarget() requires it. + expect(embeddingDimsForModel(ollama, 'qwen3-embedding:8b')).toBe(768); + }); + + test('legacy spellings keep validating at their declared dims', () => { + expect(embeddingDimsForModel(ollama, 'qwen3-embed-8b')).toBe(4096); + expect(embeddingDimsForModel(ollama, 'snowflake-arctic-embed-l-v2')).toBe(1024); + }); + + test('both new tags are listed in the embedding touchpoint models', () => { + const models = getRecipe('ollama')!.touchpoints.embedding!.models; + expect(models).toContain('qwen3-embedding:8b'); + expect(models).toContain('snowflake-arctic-embed2'); + }); + + test('SWEEP: every listed model with a declared dim resolves through the qualified form', () => { + // Future colon-bearing tags stay safe: the qualified form (what init and + // migration actually pass) must always reach the declared model_dims row. + const tp = ollama.touchpoints.embedding!; + for (const [model, dims] of Object.entries(tp.model_dims ?? {})) { + expect( + embeddingDimsForModel(ollama, `ollama:${model}`), + `ollama:${model} must resolve to its declared ${dims}`, + ).toBe(dims); + } + }); +}); + +describe('embedding-migrate --to accepts the new tags at their native widths', () => { + test('resolveMigrationTarget(ollama:qwen3-embedding:8b) → 4096', () => { + expect(resolveMigrationTarget('ollama:qwen3-embedding:8b')).toEqual({ + toModel: 'ollama:qwen3-embedding:8b', + toDims: 4096, + }); + }); + + test('resolveMigrationTarget(ollama:snowflake-arctic-embed2) → 1024', () => { + expect(resolveMigrationTarget('ollama:snowflake-arctic-embed2')).toEqual({ + toModel: 'ollama:snowflake-arctic-embed2', + toDims: 1024, + }); + }); + + test('bare colon tag fails loud, not silently at 768 [PIN]', () => { + // 'qwen3-embedding:8b' PASSES the includes(':') qualification guard (it + // contains a colon), so the fail-loud contract this file's header relies + // on actually comes from resolveRecipe throwing on the unknown provider + // 'qwen3-embedding'. Pin that: if recipe resolution ever became lenient, + // a bare colon tag would silently plan a 768-wide migration. + expect(() => resolveMigrationTarget('qwen3-embedding:8b')).toThrow(); + }); +}); diff --git a/test/apply-migrations-list-db-state.serial.test.ts b/test/apply-migrations-list-db-state.serial.test.ts new file mode 100644 index 00000000..1762eaa3 --- /dev/null +++ b/test/apply-migrations-list-db-state.serial.test.ts @@ -0,0 +1,71 @@ +/** + * #4364 integration: `apply-migrations --list --require-db` against an + * unreachable Postgres must say so on stdout and exit nonzero. Pre-fix, the + * pre-flight probe's catch swallowed the connection error, so an unreachable + * DB printed the identical all-pending plan at exit 0 as a clean one — + * indistinguishable to operators and CI gates. + * + * Serial because it spawns a subprocess and writes a tmpdir. Skippable via + * `GBRAIN_SKIP_SUBPROCESS_TESTS=1` for fast-loop budget control. + */ +import { describe, test, expect } from 'bun:test'; +import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'fs'; +import { join } from 'path'; +import { tmpdir } from 'os'; + +const REPO = new URL('..', import.meta.url).pathname.replace(/\/$/, ''); +const SKIP = process.env.GBRAIN_SKIP_SUBPROCESS_TESTS === '1'; + +async function runCli( + args: string[], + env: Record, + timeoutMs: number, +): Promise<{ exitCode: number; stdout: string; stderr: string }> { + const proc = Bun.spawn(['bun', 'run', `${REPO}/src/cli.ts`, ...args], { + cwd: REPO, + env: { ...process.env, ...env }, + stdout: 'pipe', + stderr: 'pipe', + }); + const killer = setTimeout(() => { + try { proc.kill('SIGKILL'); } catch { /* already dead */ } + }, timeoutMs); + try { + const [stdout, stderr, exitCode] = await Promise.all([ + new Response(proc.stdout).text(), + new Response(proc.stderr).text(), + proc.exited, + ]); + return { exitCode, stdout, stderr }; + } finally { + clearTimeout(killer); + } +} + +describe('apply-migrations --list with unreachable postgres (#4364)', () => { + test.skipIf(SKIP)('--list --require-db reports UNREACHABLE and exits nonzero', async () => { + const home = mkdtempSync(join(tmpdir(), 'gbrain-list-dbstate-')); + try { + mkdirSync(join(home, '.gbrain'), { recursive: true }); + // Loopback port 1: binding it needs root, so nothing listens there and + // connect fails fast with ECONNREFUSED — no traffic leaves the box. + writeFileSync( + join(home, '.gbrain', 'config.json'), + JSON.stringify({ + engine: 'postgres', + database_url: 'postgresql://gbrain:gbrain@127.0.0.1:1/gbrain', + }) + '\n', + ); + const env = { HOME: home, GBRAIN_HOME: home }; + + const res = await runCli(['apply-migrations', '--list', '--require-db'], env, 90_000); + expect(res.stdout).toContain('UNREACHABLE'); + expect(res.exitCode).not.toBe(0); + // The plan table still renders — the DB-state line is additive, so the + // filesystem-side migration plan stays visible for triage. + expect(res.stdout).toMatch(/pending/); + } finally { + try { rmSync(home, { recursive: true, force: true }); } catch { /* best effort */ } + } + }, 180_000); +}); diff --git a/test/apply-migrations-list-db-state.test.ts b/test/apply-migrations-list-db-state.test.ts new file mode 100644 index 00000000..254b2cdc --- /dev/null +++ b/test/apply-migrations-list-db-state.test.ts @@ -0,0 +1,39 @@ +/** + * #4364 unit scope: `apply-migrations --list`/`--dry-run` must surface the + * pre-flight DB probe outcome instead of swallowing connection errors — an + * unreachable database used to print the identical all-pending plan (exit 0) + * as a clean one. Covers the probe-summary formatter and the --require-db + * flag parse; the end-to-end unreachable-DB spawn is in + * test/apply-migrations-list-db-state.serial.test.ts. + */ + +import { describe, test, expect } from 'bun:test'; +import { __testing } from '../src/commands/apply-migrations.ts'; + +const { parseArgs, formatDbProbeLine } = __testing; + +describe('formatDbProbeLine (#4364)', () => { + test('connected → schema/latest summary line', () => { + expect(formatDbProbeLine({ status: 'connected', schemaVer: 7, latest: 9 })) + .toBe('Database: connected, schema v7 (latest 9)'); + }); + + test('unreachable → loud UNREACHABLE line carrying the reason', () => { + const line = formatDbProbeLine({ status: 'unreachable', reason: 'connect ECONNREFUSED' }); + expect(line).toContain('UNREACHABLE'); + expect(line).toContain('connect ECONNREFUSED'); + }); + + test('skipped → not-probed line carrying the reason', () => { + const line = formatDbProbeLine({ status: 'skipped', reason: 'pglite manages schema in-process' }); + expect(line).toContain('not probed'); + expect(line).toContain('pglite'); + }); +}); + +describe('--require-db flag (#4364)', () => { + test('defaults to false; --require-db flips it', () => { + expect(parseArgs([]).requireDb).toBe(false); + expect(parseArgs(['--require-db']).requireDb).toBe(true); + }); +}); diff --git a/test/apply-migrations.test.ts b/test/apply-migrations.test.ts index f5f229f3..e0fb2b87 100644 --- a/test/apply-migrations.test.ts +++ b/test/apply-migrations.test.ts @@ -206,12 +206,15 @@ describe('force-retry escape hatch', () => { // date" paths must exit 0 so shell scripts gating on the exit code work. // Pre-fix, these `return` statements left the CLI dispatcher's implicit // non-zero exit code in place when callers checked $?. +// #4364 amendment: list/dry-run exit via listExit, which is 0 EXCEPT under +// the opt-in --require-db flag when the DB probe failed (then 1). describe('runApplyMigrations exit codes (v0.36.1.x #1062)', () => { - test('source contains process.exit(0) on list/dry-run/up-to-date branches', async () => { + test('source contains process.exit(listExit) on list/dry-run and exit(0) up-to-date', async () => { const { readFileSync } = await import('fs'); const src = readFileSync('src/commands/apply-migrations.ts', 'utf8'); - expect(src).toMatch(/cli\.list\s*\)\s*\{\s*printList\(plan,\s*installed\);\s*process\.exit\(0\);/); - expect(src).toMatch(/cli\.dryRun\s*\)\s*\{\s*printDryRun\(plan,\s*installed\);\s*process\.exit\(0\);/); + expect(src).toMatch(/const listExit = cli\.requireDb && dbProbe\.status === 'unreachable' \? 1 : 0;/); + expect(src).toMatch(/cli\.list\s*\)\s*\{\s*printList\(plan,\s*installed,\s*dbProbe\);\s*process\.exit\(listExit\);/); + expect(src).toMatch(/cli\.dryRun\s*\)\s*\{\s*printDryRun\(plan,\s*installed,\s*dbProbe\);\s*process\.exit\(listExit\);/); expect(src).toMatch(/All migrations up to date[\s\S]{0,80}process\.exit\(0\)/); }); }); diff --git a/test/backlink-count-mention-filter.test.ts b/test/backlink-count-mention-filter.test.ts index 554cba48..042c662f 100644 --- a/test/backlink-count-mention-filter.test.ts +++ b/test/backlink-count-mention-filter.test.ts @@ -41,10 +41,11 @@ beforeEach(async () => { await engine.executeRaw('DELETE FROM pages'); }); -async function seedTarget(slug: string): Promise { - await engine.putPage(slug, { +async function seedTarget(slug: string): Promise { + const page = await engine.putPage(slug, { type: 'person', title: 'Target', compiled_truth: 'body', timeline: '', frontmatter: {}, }); + return page.id; } async function seedSource(slug: string, idx: number): Promise { @@ -56,7 +57,7 @@ async function seedSource(slug: string, idx: number): Promise { describe('getBacklinkCounts — D12 mention filter', () => { test('10 markdown-source links + 0 mention-source → backlink count = 10', async () => { const target = 'people/alice'; - await seedTarget(target); + const targetId = await seedTarget(target); const links = []; for (let i = 0; i < 10; i++) { const src = `writing/post-${i}`; @@ -70,13 +71,13 @@ describe('getBacklinkCounts — D12 mention filter', () => { }); } await engine.addLinksBatch(links); - const counts = await engine.getBacklinkCounts([target]); - expect(counts.get(target)).toBe(10); + const counts = await engine.getBacklinkCounts([targetId]); + expect(counts.get(targetId)).toBe(10); }); test('0 markdown + 50 mention-source links → backlink count = 0', async () => { const target = 'people/bob'; - await seedTarget(target); + const targetId = await seedTarget(target); const links = []; for (let i = 0; i < 50; i++) { const src = `writing/mention-${i}`; @@ -90,13 +91,13 @@ describe('getBacklinkCounts — D12 mention filter', () => { }); } await engine.addLinksBatch(links); - const counts = await engine.getBacklinkCounts([target]); - expect(counts.get(target)).toBe(0); + const counts = await engine.getBacklinkCounts([targetId]); + expect(counts.get(targetId)).toBe(0); }); test('10 markdown + 50 mention-source → backlink count = 10', async () => { const target = 'people/carol'; - await seedTarget(target); + const targetId = await seedTarget(target); const links = []; for (let i = 0; i < 10; i++) { const src = `writing/intent-${i}`; @@ -113,8 +114,8 @@ describe('getBacklinkCounts — D12 mention filter', () => { }); } await engine.addLinksBatch(links); - const counts = await engine.getBacklinkCounts([target]); - expect(counts.get(target)).toBe(10); + const counts = await engine.getBacklinkCounts([targetId]); + expect(counts.get(targetId)).toBe(10); }); test('NULL link_source legacy rows still count toward backlinks (IS DISTINCT FROM semantics)', async () => { @@ -123,14 +124,11 @@ describe('getBacklinkCounts — D12 mention filter', () => { // filter would silently drop these. `IS DISTINCT FROM` treats NULL // as a distinct value so NULL-source rows count. const target = 'people/legacy'; - await seedTarget(target); + const targetId = await seedTarget(target); await seedSource('writing/legacy-1', 0); await seedSource('writing/legacy-2', 1); // Insert via raw SQL because addLinksBatch requires a link_source value // — legacy rows pre-v0.13 had NULL. - const targetId = (await engine.executeRaw<{ id: number }>( - `SELECT id FROM pages WHERE slug = $1`, [target], - ))[0]!.id; const src1Id = (await engine.executeRaw<{ id: number }>( `SELECT id FROM pages WHERE slug = $1`, ['writing/legacy-1'], ))[0]!.id; @@ -142,21 +140,18 @@ describe('getBacklinkCounts — D12 mention filter', () => { VALUES ($1, $2, $3, NULL), ($4, $2, $3, NULL)`, [src1Id, targetId, 'mentions', src2Id], ); - const counts = await engine.getBacklinkCounts([target]); - expect(counts.get(target)).toBe(2); + const counts = await engine.getBacklinkCounts([targetId]); + expect(counts.get(targetId)).toBe(2); }); test('mixed link_source (markdown, frontmatter, manual, NULL) all count; only mentions filtered', async () => { const target = 'companies/acme'; - await seedTarget(target); + const targetId = await seedTarget(target); await seedSource('w/md', 1); await seedSource('w/fm', 2); await seedSource('w/manual', 3); await seedSource('w/auto', 4); // Insert via raw SQL since addLinksBatch doesn't accept all link_source variants in one call. - const targetId = (await engine.executeRaw<{ id: number }>( - `SELECT id FROM pages WHERE slug = $1`, [target], - ))[0]!.id; const ids = await engine.executeRaw<{ slug: string; id: number }>( `SELECT slug, id FROM pages WHERE slug IN ($1, $2, $3, $4)`, ['w/md', 'w/fm', 'w/manual', 'w/auto'], @@ -170,13 +165,50 @@ describe('getBacklinkCounts — D12 mention filter', () => { ($4, $5, 'mentions', 'mentions')`, [m.get('w/md'), m.get('w/fm'), m.get('w/manual'), m.get('w/auto'), targetId], ); - const counts = await engine.getBacklinkCounts([target]); + const counts = await engine.getBacklinkCounts([targetId]); // markdown + frontmatter + manual = 3; mentions filtered out. - expect(counts.get(target)).toBe(3); + expect(counts.get(targetId)).toBe(3); }); - test('uninitialized slug returns 0 (consistent map shape)', async () => { - const counts = await engine.getBacklinkCounts(['does/not/exist']); - expect(counts.get('does/not/exist')).toBe(0); + test('unknown page id returns 0 (consistent map shape)', async () => { + const counts = await engine.getBacklinkCounts([999_999]); + expect(counts.get(999_999)).toBe(0); + }); +}); + +describe('getBacklinkCounts — #4380 page-id keying (multi-source namesakes)', () => { + test('same slug in two sources: counts are per page, never summed across namesakes', async () => { + // #4380: the old query grouped by bare slug with no source filter, so + // every page sharing a slug got the SUM of all namesakes' backlinks + // and hybrid search boosted zero-backlink pages. Keying by page id is + // source-correct by construction. + const slug = 'tools/claude'; + await engine.executeRaw( + `INSERT INTO sources (id, name) VALUES ('other-src', 'Other') ON CONFLICT (id) DO NOTHING`, + ); + const pageA = await engine.putPage(slug, { + type: 'concept', title: 'Claude (source A)', compiled_truth: 'body', timeline: '', frontmatter: {}, + }); + const pageB = await engine.putPage(slug, { + type: 'concept', title: 'Claude (source B)', compiled_truth: 'body', timeline: '', frontmatter: {}, + }, { sourceId: 'other-src' }); + expect(pageA.id).not.toBe(pageB.id); + + // Three non-mentions links target ONLY source A's page. Insert by + // explicit page id — slug-based addLink cannot address one namesake. + for (let i = 0; i < 3; i++) { + const src = await engine.putPage(`writing/ref-${i}`, { + type: 'note', title: `Ref ${i}`, compiled_truth: 'body', timeline: '', frontmatter: {}, + }); + await engine.executeRaw( + `INSERT INTO links (from_page_id, to_page_id, link_type, link_source) + VALUES ($1, $2, 'mentions', 'markdown')`, + [src.id, pageA.id], + ); + } + + const counts = await engine.getBacklinkCounts([pageA.id, pageB.id]); + expect(counts.get(pageA.id)).toBe(3); + expect(counts.get(pageB.id)).toBe(0); }); }); diff --git a/test/benchmark-graph-quality.ts b/test/benchmark-graph-quality.ts index 46b37862..947fda10 100644 --- a/test/benchmark-graph-quality.ts +++ b/test/benchmark-graph-quality.ts @@ -576,10 +576,15 @@ async function measureAggregate( for (const q of AGGREGATE_QUERIES) { const candidates = seeds.filter(s => s.slug.startsWith(`${q.kind}/`)).map(s => s.slug); - // C: structured backlink counts. - const counts = await engine.getBacklinkCounts(candidates); + // C: structured backlink counts (page-id-keyed since #4380; single + // default-source benchmark brain, so slug→id is unambiguous). + const idRows = await engine.executeRaw<{ id: number; slug: string }>( + `SELECT id, slug FROM pages WHERE slug = ANY($1::text[])`, [candidates], + ); + const idBySlug = new Map(idRows.map(r => [r.slug, r.id])); + const counts = await engine.getBacklinkCounts(idRows.map(r => r.id)); const cTop = candidates - .map(s => ({ slug: s, n: counts.get(s) ?? 0 })) + .map(s => ({ slug: s, n: counts.get(idBySlug.get(s) ?? -1) ?? 0 })) .sort((a, b) => b.n - a.n) .slice(0, q.topN) .map(x => x.slug); @@ -751,11 +756,11 @@ async function measureRanking( .sort((a, b) => b.score - a.score) .filter(r => { if (seenWithout.has(r.slug)) return false; seenWithout.add(r.slug); return true; }); - const allSlugs = sortedWithout.map(r => r.slug); - const counts = await engine.getBacklinkCounts(allSlugs); + const allIds = sortedWithout.map(r => r.page_id); + const counts = await engine.getBacklinkCounts(allIds); const boosted = sortedWithout.map(r => ({ ...r, - score: r.score * (1 + 0.05 * Math.log(1 + (counts.get(r.slug) ?? 0))), + score: r.score * (1 + 0.05 * Math.log(1 + (counts.get(r.page_id) ?? 0))), })); // boosted is already deduped (sortedWithout was). Just re-sort by new score. const sortedWith = [...boosted].sort((a, b) => b.score - a.score); diff --git a/test/capture-runcapture.test.ts b/test/capture-runcapture.test.ts index 9beadce6..b5d3d2e7 100644 --- a/test/capture-runcapture.test.ts +++ b/test/capture-runcapture.test.ts @@ -23,7 +23,7 @@ import { describe, test, expect } from 'bun:test'; import { __testing as captureTesting } from '../src/commands/capture.ts'; import { computeContentHash } from '../src/core/ingestion/types.ts'; -const { detectBinaryNullByte, normalizeForHash, maybeRewriteSourceFkError } = captureTesting; +const { detectBinaryNullByte, detectBinarySignature, normalizeForHash, maybeRewriteSourceFkError } = captureTesting; describe('CV10 — binary file guard (detectBinaryNullByte)', () => { test('returns -1 on plain ASCII', () => { @@ -82,6 +82,72 @@ describe('CV10 — binary file guard (detectBinaryNullByte)', () => { }); }); +describe('magic-byte binary guard (detectBinarySignature)', () => { + // The regression that motivated this guard: a small ASCII-armored PDF with + // ZERO NUL bytes anywhere. It passed the CV10 NUL scan, was UTF-8-decoded to + // U+FFFD mojibake, and got stored as a page body titled '%PDF-1.4' — with the + // document's real text (inside FlateDecode streams) silently lost, while + // `capture` reported success. + test('rejects a NUL-free PDF that the NUL scan cannot catch', () => { + const pdf = Buffer.from('%PDF-1.4\n1 0 obj\n<>\nendobj\n'); + expect(pdf.includes(0)).toBe(false); // the exact hole: no NUL to find + expect(detectBinaryNullByte(pdf)).toBe(-1); // ...so the old guard passes it + expect(detectBinarySignature(pdf)).toBe('PDF'); // ...and the new one stops it + }); + + test('detects common container formats', () => { + const cases: Array<[Buffer, string]> = [ + [Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), 'PNG'], + [Buffer.from([0xff, 0xd8, 0xff, 0xe0]), 'JPEG'], + [Buffer.from('GIF89a'), 'GIF'], + [Buffer.from([0x50, 0x4b, 0x03, 0x04]), 'ZIP / OOXML (docx, xlsx, pptx)'], + [Buffer.from([0x1f, 0x8b, 0x08]), 'gzip'], + [Buffer.from([0x7f, 0x45, 0x4c, 0x46]), 'ELF executable'], + [Buffer.from('SQLite format 3\0'), 'SQLite database'], + [Buffer.from('OggS'), 'Ogg'], + [Buffer.from([0x1a, 0x45, 0xdf, 0xa3]), 'Matroska / WebM'], + ]; + for (const [buf, label] of cases) { + expect(detectBinarySignature(buf)).toBe(label); + } + }); + + test('matches signatures at non-zero offsets', () => { + // MP4: 4-byte box size, then 'ftyp' at offset 4. + const mp4 = Buffer.concat([Buffer.from([0x00, 0x00, 0x00, 0x18]), Buffer.from('ftypisom')]); + expect(detectBinarySignature(mp4)).toBe('MP4 / MOV / HEIC'); + // RIFF containers are disambiguated by the tag at offset 8. + const webp = Buffer.concat([Buffer.from('RIFF'), Buffer.from([0, 0, 0, 0]), Buffer.from('WEBP')]); + expect(detectBinarySignature(webp)).toBe('WebP'); + const wav = Buffer.concat([Buffer.from('RIFF'), Buffer.from([0, 0, 0, 0]), Buffer.from('WAVE')]); + expect(detectBinarySignature(wav)).toBe('WAV'); + }); + + test('passes real text through, including the shapes that look risky', () => { + const texts = [ + 'hello world', + '# A markdown heading\n\nBody text.', + '測試 brain content', // multi-byte CJK + 'thinking 🧠🔥 hot', // emoji + '# BOM-prefixed markdown', // UTF-8 BOM + '---\ntitle: T\ntype: note\n---\n\n# Body', // frontmatter + 'MZ is a two-letter prefix in a sentence.', // deliberately-omitted weak magic + 'BM is another one.', // deliberately-omitted weak magic + 'ID3 tags are metadata containers.', // deliberately-omitted weak magic + '%!PS-Adobe-3.0 is PostScript, which is text.', + ]; + for (const t of texts) { + expect(detectBinarySignature(Buffer.from(t))).toBeNull(); + } + }); + + test('handles buffers shorter than a signature without throwing', () => { + expect(detectBinarySignature(Buffer.alloc(0))).toBeNull(); + expect(detectBinarySignature(Buffer.from('%PD'))).toBeNull(); // truncated PDF magic + expect(detectBinarySignature(Buffer.from([0x89]))).toBeNull(); + }); +}); + describe('CV9 — normalizeForHash (trim + LF + NFKC)', () => { test('strips leading/trailing whitespace', () => { expect(normalizeForHash(' hello ')).toBe('hello'); diff --git a/test/cite-render-closure.test.ts b/test/cite-render-closure.test.ts new file mode 100644 index 00000000..807e72e2 --- /dev/null +++ b/test/cite-render-closure.test.ts @@ -0,0 +1,157 @@ +import { describe, test, expect, beforeAll, afterAll } from 'bun:test'; +import { PGLiteEngine } from '../src/core/pglite-engine.ts'; +import { runThink, type ThinkLLMClient } from '../src/core/think/index.ts'; +import { resolveCitations } from '../src/core/think/cite-render.ts'; + +// #4376 — think accepted mismatched inline and structured citations as +// successful: once ANY structured citation existed, resolveCitations never +// parsed the inline markers, so a visible fabricated/near-match citation in +// the answer body surfaced with zero warnings, and nothing closed the +// resolved citations against the gathered evidence set. These tests pin the +// closure warnings (warning layer only — the never-fail trust contract in +// cite-render.ts stays intact: structured citations remain the source of +// truth and synthesis is not failed over a mismatch). + +function stubClientFromResponse(payload: unknown): ThinkLLMClient { + return { + create: async () => ({ + id: 'msg_closure', + type: 'message', + role: 'assistant', + model: 'stub', + stop_reason: 'end_turn', + stop_sequence: null, + usage: { input_tokens: 10, output_tokens: 10, cache_creation_input_tokens: 0, cache_read_input_tokens: 0, server_tool_use: null, service_tier: null }, + content: [{ type: 'text', text: JSON.stringify(payload) }], + }), + }; +} + +describe('resolveCitations — inline/structured closure warnings', () => { + test('inline marker differing from the structured citation warns both ways', () => { + // The issue's exact repro shape: visible [records/example-a], structured + // records/example-b. Red at HEAD: warnings === []. + const r = resolveCitations( + [{ page_slug: 'records/example-b', row_num: null }], + 'The answer cites [records/example-a] visibly.', + ); + expect(r.usedFallback).toBe(false); + // Structured stays the source of truth — no repair, no fallback swap. + expect(r.citations).toHaveLength(1); + expect(r.citations[0].page_slug).toBe('records/example-b'); + expect(r.warnings).toContain('CITATIONS_INLINE_NOT_IN_STRUCTURED:records/example-a'); + expect(r.warnings).toContain('CITATIONS_STRUCTURED_NOT_INLINE:records/example-b'); + }); + + test('near-match slugs (the reported UUID drift) are warned, not repaired', () => { + const r = resolveCitations( + [{ page_slug: 'experiences/0000-bbbb', row_num: null }], + 'One visible near-match [experiences/0000-aaaa].', + ); + expect(r.citations.map(c => c.page_slug)).toEqual(['experiences/0000-bbbb']); + expect(r.warnings).toContain('CITATIONS_INLINE_NOT_IN_STRUCTURED:experiences/0000-aaaa'); + expect(r.warnings).toContain('CITATIONS_STRUCTURED_NOT_INLINE:experiences/0000-bbbb'); + }); + + test('matching inline and structured sets emit no mismatch warnings', () => { + const r = resolveCitations( + [ + { page_slug: 'people/alice-example', row_num: 2 }, + { page_slug: 'records/example-a', row_num: null }, + ], + 'Alice [people/alice-example#2] and the record [records/example-a].', + ); + expect(r.warnings.filter(w => w.startsWith('CITATIONS_INLINE_NOT_IN_STRUCTURED'))).toEqual([]); + expect(r.warnings.filter(w => w.startsWith('CITATIONS_STRUCTURED_NOT_INLINE'))).toEqual([]); + }); + + test('row_num is part of the closure key (slug#row)', () => { + const r = resolveCitations( + [{ page_slug: 'people/alice-example', row_num: 3 }], + 'Take cite [people/alice-example#2].', + ); + expect(r.warnings).toContain('CITATIONS_INLINE_NOT_IN_STRUCTURED:people/alice-example#2'); + expect(r.warnings).toContain('CITATIONS_STRUCTURED_NOT_INLINE:people/alice-example#3'); + }); + + test('inline-only extra beyond a matching structured set warns one way only', () => { + const r = resolveCitations( + [{ page_slug: 'records/example-a', row_num: null }], + 'Cited [records/example-a] plus a fabricated [records/example-c].', + ); + expect(r.warnings).toContain('CITATIONS_INLINE_NOT_IN_STRUCTURED:records/example-c'); + expect(r.warnings.filter(w => w.startsWith('CITATIONS_STRUCTURED_NOT_INLINE'))).toEqual([]); + }); + + test('structured-only citations with no visible markers warn one way only', () => { + const r = resolveCitations( + [{ page_slug: 'records/example-a', row_num: null }], + 'Prose with no visible markers at all.', + ); + expect(r.warnings).toContain('CITATIONS_STRUCTURED_NOT_INLINE:records/example-a'); + expect(r.warnings.filter(w => w.startsWith('CITATIONS_INLINE_NOT_IN_STRUCTURED'))).toEqual([]); + }); + + test('the structured-empty regex fallback path is unchanged', () => { + const r = resolveCitations([], 'Body text [people/alice-example#2]'); + expect(r.usedFallback).toBe(true); + expect(r.citations).toHaveLength(1); + expect(r.warnings).toContain('CITATIONS_REGEX_FALLBACK'); + expect(r.warnings.filter(w => w.startsWith('CITATIONS_INLINE_NOT_IN_STRUCTURED'))).toEqual([]); + expect(r.warnings.filter(w => w.startsWith('CITATIONS_STRUCTURED_NOT_INLINE'))).toEqual([]); + }); +}); + +describe('runThink — resolved citations close against the gather set', () => { + let engine: PGLiteEngine; + + beforeAll(async () => { + engine = new PGLiteEngine(); + await engine.connect({}); + await engine.initSchema(); + const alice = await engine.putPage('people/alice-example', { + title: 'Alice', type: 'person', compiled_truth: 'Alice founded Acme.', + }); + await engine.addTakesBatch([ + { page_id: alice.id, row_num: 1, claim: 'CEO of Acme', kind: 'fact', holder: 'world', weight: 1.0 }, + { page_id: alice.id, row_num: 2, claim: 'Strong technical founder', kind: 'take', holder: 'garry', weight: 0.85 }, + ]); + }); + + afterAll(async () => { + await engine.disconnect(); + }); + + test('a structured citation outside the gathered evidence warns CITATION_NOT_IN_GATHER', async () => { + const result = await runThink(engine, { + question: 'technical founder', + withTrajectory: false, + client: stubClientFromResponse({ + answer: 'The answer cites [records/example-a] visibly.', + citations: [{ page_slug: 'records/example-b', row_num: null }], + gaps: [], + }), + }); + // Warning layer only — the synthesis itself still succeeds. + expect(result.synthesis_status).toBe('ok'); + expect(result.warnings).toContain('CITATIONS_INLINE_NOT_IN_STRUCTURED:records/example-a'); + expect(result.warnings).toContain('CITATIONS_STRUCTURED_NOT_INLINE:records/example-b'); + expect(result.warnings).toContain('CITATION_NOT_IN_GATHER:records/example-b'); + }); + + test('citations covered by the gathered evidence emit no closure warnings', async () => { + const result = await runThink(engine, { + question: 'technical founder', + withTrajectory: false, + client: stubClientFromResponse({ + answer: 'Strong founder [people/alice-example#2].', + citations: [{ page_slug: 'people/alice-example', row_num: 2 }], + gaps: [], + }), + }); + expect(result.synthesis_status).toBe('ok'); + expect(result.warnings.filter(w => w.startsWith('CITATIONS_INLINE_NOT_IN_STRUCTURED'))).toEqual([]); + expect(result.warnings.filter(w => w.startsWith('CITATIONS_STRUCTURED_NOT_INLINE'))).toEqual([]); + expect(result.warnings.filter(w => w.startsWith('CITATION_NOT_IN_GATHER'))).toEqual([]); + }); +}); diff --git a/test/config-gbrain-env-file.test.ts b/test/config-gbrain-env-file.test.ts new file mode 100644 index 00000000..64e70761 --- /dev/null +++ b/test/config-gbrain-env-file.test.ts @@ -0,0 +1,122 @@ +/** + * ~/.gbrain/.env secrets loader (#3893, reimplemented from @y2688's PR). + * + * Bun only auto-loads `.env` from the process cwd, which for a globally + * installed CLI is arbitrary — and cwd .env files are UNTRUSTED input (the + * #427 DATABASE_URL-hijack guard in config.ts exists because of them). The + * gbrain home is operator-owned, so `~/.gbrain/.env` is the deliberate spot + * for API keys that must stay OUT of config.json. loadConfig() fills + * process.env from it; a variable the shell already exported always wins. + */ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'fs'; +import { tmpdir } from 'os'; +import { join } from 'path'; +import { describe, expect, test } from 'bun:test'; +import { loadConfig, saveConfig } from '../src/core/config.ts'; +import { withEnv } from './helpers/with-env.ts'; + +/** + * Fresh isolated GBRAIN_HOME with a minimal PGLite config.json (so + * loadConfig() returns a config object) and the given ~/.gbrain/.env body. + * The `env` overrides ride through withEnv so every key the loader might + * set is restored after the callback — including keys the loader itself + * writes into process.env. + */ +async function withEnvFile( + envFileBody: string | null, + env: Record, + fn: () => Promise | T, +): Promise { + const home = mkdtempSync(join(tmpdir(), 'gbrain-env-file-')); + try { + return await withEnv({ GBRAIN_HOME: home, ...env }, async () => { + saveConfig({ engine: 'pglite', database_path: join(home, 'brain.pglite') }); + if (envFileBody !== null) { + mkdirSync(join(home, '.gbrain'), { recursive: true }); + writeFileSync(join(home, '.gbrain', '.env'), envFileBody, 'utf-8'); + } + return await fn(); + }); + } finally { + rmSync(home, { recursive: true, force: true }); + } +} + +describe('loadConfig — ~/.gbrain/.env secrets file (#3893)', () => { + test('a key in ~/.gbrain/.env reaches process.env and the merged config', async () => { + await withEnvFile( + 'OPENAI_API_KEY=sk-envfile-123\n', + { OPENAI_API_KEY: undefined }, + () => { + const cfg = loadConfig(); + expect(process.env.OPENAI_API_KEY).toBe('sk-envfile-123'); + expect(cfg?.openai_api_key).toBe('sk-envfile-123'); + }, + ); + }); + + test('a shell-exported variable wins over the .env file value', async () => { + await withEnvFile( + 'OPENAI_API_KEY=sk-envfile-loser\n', + { OPENAI_API_KEY: 'sk-shell-winner' }, + () => { + const cfg = loadConfig(); + expect(process.env.OPENAI_API_KEY).toBe('sk-shell-winner'); + expect(cfg?.openai_api_key).toBe('sk-shell-winner'); + }, + ); + }); + + test('quoted values are unwrapped; unquoted values drop trailing inline comments', async () => { + await withEnvFile( + [ + 'ANTHROPIC_API_KEY="sk-quoted-value"', + "OPENROUTER_API_KEY='sk-single-quoted'", + 'ZEROENTROPY_API_KEY=sk-inline # trailing comment', + '', + ].join('\n'), + { + ANTHROPIC_API_KEY: undefined, + OPENROUTER_API_KEY: undefined, + ZEROENTROPY_API_KEY: undefined, + }, + () => { + loadConfig(); + expect(process.env.ANTHROPIC_API_KEY).toBe('sk-quoted-value'); + expect(process.env.OPENROUTER_API_KEY).toBe('sk-single-quoted'); + expect(process.env.ZEROENTROPY_API_KEY).toBe('sk-inline'); + }, + ); + }); + + test('comments, blank lines, malformed lines, and empty values never land', async () => { + await withEnvFile( + [ + '# a full-line comment', + '', + '=no-key-name', + 'not a assignment line', + 'GBRAIN_TEST_ENV_FILE_EMPTY=', + 'GBRAIN_TEST_ENV_FILE_OK=yes', + '', + ].join('\n'), + { + GBRAIN_TEST_ENV_FILE_EMPTY: undefined, + GBRAIN_TEST_ENV_FILE_OK: undefined, + }, + () => { + // Must not throw on the junk lines. + expect(loadConfig()).not.toBeNull(); + expect(process.env.GBRAIN_TEST_ENV_FILE_EMPTY).toBeUndefined(); + expect(process.env.GBRAIN_TEST_ENV_FILE_OK).toBe('yes'); + }, + ); + }); + + test('a missing ~/.gbrain/.env is not an error', async () => { + await withEnvFile(null, {}, () => { + const cfg = loadConfig(); + expect(cfg?.engine).toBe('pglite'); + }); + }); +}); diff --git a/test/config-get-plane.test.ts b/test/config-get-plane.test.ts index 70fe0d24..eb55ce54 100644 --- a/test/config-get-plane.test.ts +++ b/test/config-get-plane.test.ts @@ -31,10 +31,13 @@ function writeFileConfig(cfg: Record): void { } /** Run `config get ` with GBRAIN_HOME pinned to the tmp brain and the - * chat-model env overlay cleared, capturing output + exit code. */ + * chat-model + anthropic-key env overlays cleared (loadConfig folds + * ANTHROPIC_API_KEY into anthropic_api_key, which the #3943 pins read), + * capturing output + exit code. `extraArgs` lands flags around the key. */ async function runGet( dbValues: Record, key: string, + extraArgs: { before?: string[]; after?: string[] } = {}, ): Promise<{ logs: string[]; errs: string[]; exit: number | null }> { const logs: string[] = []; const errs: string[] = []; @@ -47,8 +50,8 @@ async function runGet( }) as never); try { await withEnv( - { GBRAIN_HOME: home, GBRAIN_CHAT_MODEL: undefined }, - () => runConfig(stubEngine(dbValues), ['get', key]), + { GBRAIN_HOME: home, GBRAIN_CHAT_MODEL: undefined, ANTHROPIC_API_KEY: undefined }, + () => runConfig(stubEngine(dbValues), ['get', ...(extraArgs.before ?? []), key, ...(extraArgs.after ?? [])]), ); } catch (e) { if (!(e as Error).message.startsWith('EXIT:')) throw e; @@ -91,3 +94,53 @@ describe('#2120 — config get resolves file plane with DB fallback', () => { expect(errs.join('\n')).toContain('Config key not found: chat_model'); }); }); + +describe('#3943 — config get redacts sensitive values by default (--raw opts out)', () => { + test('file-plane sensitive key prints *** and the secret appears nowhere', async () => { + writeFileConfig({ engine: 'pglite', anthropic_api_key: 'sk-ant-test3943-file-secret' }); + const { logs, errs, exit } = await runGet({}, 'anthropic_api_key'); + expect(exit).toBeNull(); + expect(logs).toContain('***'); + expect(logs.join('\n')).not.toContain('sk-ant-test3943-file-secret'); + expect(errs.join('\n')).not.toContain('sk-ant-test3943-file-secret'); + }); + + test('DB-plane sensitive key prints ***', async () => { + writeFileConfig({ engine: 'pglite' }); + const { logs, exit } = await runGet({ github_token: 'ghp-test3943-db-secret' }, 'github_token'); + expect(exit).toBeNull(); + expect(logs).toContain('***'); + expect(logs.join('\n')).not.toContain('ghp-test3943-db-secret'); + }); + + // Pin: redactConfigValue routes DSNs through redactPgUrl, which drops the + // whole userinfo (both scheme spellings) — host/db stay legible for scripts. + test('database_url prints the userinfo-redacted URL', async () => { + writeFileConfig({ engine: 'pglite', database_url: 'postgresql://user:pw3943@host/db' }); + const { logs, exit } = await runGet({}, 'database_url'); + expect(exit).toBeNull(); + expect(logs).toContain('postgresql://***@host/db'); + expect(logs.join('\n')).not.toContain('pw3943'); + }); + + test('--raw before the key still resolves the key and prints the verbatim secret', async () => { + writeFileConfig({ engine: 'pglite', anthropic_api_key: 'sk-ant-test3943-raw-optout' }); + const { logs, exit } = await runGet({}, 'anthropic_api_key', { before: ['--raw'] }); + expect(exit).toBeNull(); + expect(logs).toContain('sk-ant-test3943-raw-optout'); + }); + + test('--raw after the key prints the verbatim secret', async () => { + writeFileConfig({ engine: 'pglite', anthropic_api_key: 'sk-ant-test3943-raw-optout' }); + const { logs, exit } = await runGet({}, 'anthropic_api_key', { after: ['--raw'] }); + expect(exit).toBeNull(); + expect(logs).toContain('sk-ant-test3943-raw-optout'); + }); + + test('non-sensitive key still prints its raw value (scripting regression guard)', async () => { + writeFileConfig({ engine: 'pglite', chat_model: 'anthropic:claude-sonnet-4-6' }); + const { logs, exit } = await runGet({}, 'chat_model'); + expect(exit).toBeNull(); + expect(logs).toContain('anthropic:claude-sonnet-4-6'); + }); +}); diff --git a/test/core/budget/budget-tracker.test.ts b/test/core/budget/budget-tracker.test.ts index 5cfd1ba6..6ce9ff53 100644 --- a/test/core/budget/budget-tracker.test.ts +++ b/test/core/budget/budget-tracker.test.ts @@ -453,6 +453,70 @@ describe('BudgetTracker.record', () => { }); }); +describe('BudgetTracker outstanding reservations (#4365)', () => { + // Haiku 4.5: $1/M input + $5/M output → 10K in + 10K out projects $0.06. + const estimate = { + modelId: 'claude-haiku-4-5-20251001', + estimatedInputTokens: 10_000, + maxOutputTokens: 10_000, + kind: 'chat' as const, + }; + + test('concurrent reservations count against the cap', () => { + const t = new BudgetTracker({ maxCostUsd: 1.0, label: 'test', auditPath }); + // Bank $0.90 of real spend (900K input tokens at $1/M). + t.record({ modelId: 'claude-haiku-4-5-20251001', inputTokens: 900_000, outputTokens: 0, kind: 'chat' }); + // One $0.06 projection fits ($0.96 ≤ $1.00)… + expect(() => t.reserve(estimate)).not.toThrow(); + // …but a second concurrent one must NOT: $0.90 + $0.06 outstanding + // + $0.06 projected = $1.02 > $1.00. Pre-fix, admission ignored the + // in-flight reservation and every parallel call passed at $0.96. + let caught: unknown = null; + try { + t.reserve(estimate); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(BudgetExhausted); + expect((caught as BudgetExhausted).reason).toBe('cost'); + expect((caught as Error).message).toContain('outstanding'); + const denied = readAudit().find((e) => e.event === 'reserve_denied'); + expect(denied).toBeDefined(); + expect(denied!.outstanding_usd as number).toBeCloseTo(0.06, 9); + }); + + test('record() settles the reservation: reserve→record→reserve at the same margin succeeds', () => { + const t = new BudgetTracker({ maxCostUsd: 1.0, label: 'test', auditPath }); + t.record({ modelId: 'claude-haiku-4-5-20251001', inputTokens: 900_000, outputTokens: 0, kind: 'chat' }); + t.reserve(estimate); + // Actual usage far under the projection: cumulative $0.901. + t.record({ modelId: 'claude-haiku-4-5-20251001', inputTokens: 1000, outputTokens: 0, kind: 'chat' }); + // Outstanding released — the same $0.06 projection fits again + // ($0.901 + $0.06 = $0.961 ≤ $1.00). + expect(() => t.reserve(estimate)).not.toThrow(); + }); + + test('record() under the post-resolution model id still settles (same-kind fallback)', () => { + // gateway.chat reserves with the pre-resolution string (alias/bare/slash + // form) but records `${recipe.id}:${modelId}` — a missed pop would leak + // phantom outstanding budget forever. + const t = new BudgetTracker({ maxCostUsd: 1.0, label: 'test', auditPath }); + t.record({ modelId: 'claude-haiku-4-5-20251001', inputTokens: 900_000, outputTokens: 0, kind: 'chat' }); + t.reserve({ ...estimate, modelId: 'anthropic/claude-haiku-4-5-20251001' }); + t.record({ modelId: 'anthropic:claude-haiku-4-5-20251001', inputTokens: 1000, outputTokens: 0, kind: 'chat' }); + expect(() => t.reserve(estimate)).not.toThrow(); + }); + + test('unreserved records (expand/OCR) never drive outstanding negative', () => { + const t = new BudgetTracker({ maxCostUsd: 1.0, label: 'test', auditPath }); + // Two records with no prior reserve — the pop must be a no-op both times. + t.record({ modelId: 'claude-haiku-4-5-20251001', inputTokens: 1000, outputTokens: 0, kind: 'chat' }); + t.record({ modelId: 'claude-haiku-4-5-20251001', inputTokens: 1000, outputTokens: 0, kind: 'chat' }); + // Admission math is unaffected: $0.002 spent + $0.06 projected fits. + expect(() => t.reserve(estimate)).not.toThrow(); + }); +}); + describe('BudgetTracker.onExhausted', () => { test('fires once, synchronously, before throw propagates', () => { const t = new BudgetTracker({ maxCostUsd: 0.001, label: 'test', auditPath }); diff --git a/test/cycle-abort.test.ts b/test/cycle-abort.test.ts index 12b751aa..cb50c199 100644 --- a/test/cycle-abort.test.ts +++ b/test/cycle-abort.test.ts @@ -205,3 +205,44 @@ describe('#1972 — complete cooperative-abort coverage', () => { expect(read('../src/commands/lint.ts')).toContain('if (isAborted(opts.signal)) break;'); }); }); + +describe('#4077 — synthesize/patterns cooperative-abort threading', () => { + test('cycle.ts forwards cycleSignal into the synthesize and patterns phase opts', async () => { + const fs = await import('fs'); + const src = fs.readFileSync(new URL('../src/core/cycle.ts', import.meta.url), 'utf8'); + const body = src.slice(src.indexOf('export async function runCycle')); + // Bounded to each call's own opts literal — an unanchored [\s\S]*? regex + // would false-pass on consolidate's `signal: cycleSignal` further down. + const callOf = (fnName: string): string => { + const start = body.indexOf(`${fnName}(engine, {`); + expect(start).toBeGreaterThan(-1); + return body.slice(start, body.indexOf('}))', start)); + }; + // W0 posture: phases receive the COMBINED cycleSignal (external abort + + // lock steal), same as consolidate — not the raw opts.signal. + expect(callOf('runPhaseSynthesize')).toContain('signal: cycleSignal,'); + expect(callOf('runPhasePatterns')).toContain('signal: cycleSignal,'); + }); + + test('synthesize threads its signal through judge, inline drain, and completion wait', async () => { + const fs = await import('fs'); + const src = fs.readFileSync(new URL('../src/core/cycle/synthesize.ts', import.meta.url), 'utf8'); + expect(src).toContain('signal?: AbortSignal'); + // Triage pass carries the signal into every judge call (gateway abortSignal). + expect(src).toMatch(/judgeSignificance\(judge, t, cfg\.model, \{[\s\S]*?signal: cfg\.signal,[\s\S]*?\}\)/); + expect(src).toMatch(/runSubagentsInline\([\s\S]{0,240}?opts\.signal/); + expect(src).toMatch(/waitForCompletionRenewing\(queue, jobId, \{[\s\S]*?signal: opts\.signal,/); + // Write boundaries downstream of the drain are signal-guarded. + expect(src).toContain('stampDreamProvenance(engine, writtenRefs, summaryDate, opts.signal)'); + expect(src).toContain('reverseWriteRefs(engine, opts.brainDir, writtenRefs, cycleSourceId, opts.signal)'); + }); + + test('patterns sibling threads the same signal through inline drain, wait, and reverse-write', async () => { + const fs = await import('fs'); + const src = fs.readFileSync(new URL('../src/core/cycle/patterns.ts', import.meta.url), 'utf8'); + expect(src).toContain('signal?: AbortSignal'); + expect(src).toMatch(/runSubagentsInline\([\s\S]{0,240}?opts\.signal/); + expect(src).toMatch(/waitForCompletionRenewing\(queue, job\.id, \{[\s\S]*?signal: opts\.signal,/); + expect(src).toContain('reverseWriteRefs(engine, opts.brainDir, writtenRefs, cycleSourceId, opts.signal)'); + }); +}); diff --git a/test/cycle-patterns-source-scope.test.ts b/test/cycle-patterns-source-scope.test.ts index 2b7cfb5d..1ff1a309 100644 --- a/test/cycle-patterns-source-scope.test.ts +++ b/test/cycle-patterns-source-scope.test.ts @@ -111,4 +111,44 @@ describe('#1586: the patterns phase scopes its writes to the cycle source', () = rmSync(foreignDir, { recursive: true, force: true }); } }); + + test('#4077: abort during reverse-write stops the current and all remaining file writes', async () => { + const abortDir = mkdtempSync(join(tmpdir(), 'gbrain-patterns-abort-')); + const controller = new AbortController(); + const refs = [ + { slug: 'wiki/personal/patterns/abort-first', source_id: SOURCE_ID }, + { slug: 'wiki/personal/patterns/abort-second', source_id: SOURCE_ID }, + ]; + // Fake engine: the abort fires DURING the first ref's row reads, so the + // post-read signal check — not just the loop-top one — must stop the + // first file write too. + const fakeEngine = { + getPage: async (slug: string) => ({ + slug, + type: 'note', + title: slug, + compiled_truth: slug, + frontmatter: {}, + timeline: '', + }), + getTags: async () => { + controller.abort(new Error('patterns-reverse-write-cancelled')); + return []; + }, + }; + + try { + await expect(reverseWriteRefs( + fakeEngine as any, + abortDir, + refs, + SOURCE_ID, + controller.signal, + )).rejects.toThrow('patterns-reverse-write-cancelled'); + expect(existsSync(join(abortDir, `${refs[0]!.slug}.md`))).toBe(false); + expect(existsSync(join(abortDir, `${refs[1]!.slug}.md`))).toBe(false); + } finally { + rmSync(abortDir, { recursive: true, force: true }); + } + }); }); diff --git a/test/cycle/extract-atoms-progress.test.ts b/test/cycle/extract-atoms-progress.test.ts index 62a9a5b1..2a2f6e8a 100644 --- a/test/cycle/extract-atoms-progress.test.ts +++ b/test/cycle/extract-atoms-progress.test.ts @@ -10,6 +10,8 @@ import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:tes import { PGLiteEngine } from '../../src/core/pglite-engine.ts'; import { runPhaseExtractAtoms } from '../../src/core/cycle/extract-atoms.ts'; import { resetPgliteState } from '../helpers/reset-pglite.ts'; +import { withEnv } from '../helpers/with-env.ts'; +import { resolveTierDefault } from '../../src/core/model-config.ts'; import type { ProgressReporter } from '../../src/core/progress.ts'; import type { ChatResult, ChatOpts } from '../../src/core/ai/gateway.ts'; @@ -117,7 +119,7 @@ describe('extract_atoms progress wiring (T4)', () => { expect(ticks[0].note).toMatch(/atoms.*skipped/); }); - test('passes an explicit Haiku model to chat calls', async () => { + test('passes an explicit tier-default model to chat calls', async () => { const seenModels: Array = []; const validAtomJson = JSON.stringify([ { title: 'A', atom_type: 'insight', body: 'body a' }, @@ -133,7 +135,38 @@ describe('extract_atoms progress wiring (T4)', () => { return stubChat(validAtomJson)(o); }, }); - expect(seenModels).toEqual(['anthropic:claude-haiku-4-5']); + // Hermetic-keyless unit lane → the key-aware default degrades to the + // static utility-tier floor. + expect(seenModels).toEqual([resolveTierDefault('utility')]); + }); + + test('unconfigured model follows the key-aware utility-tier default (#3813)', async () => { + // With only OPENAI_API_KEY present, the phase must not route to a + // hardcoded Anthropic model the install cannot serve — the default has + // to come from resolveTierDefault, like facts/classify.ts. + await withEnv({ ANTHROPIC_API_KEY: undefined, OPENAI_API_KEY: 'sk-test-openai' }, async () => { + const expected = resolveTierDefault('utility'); + // Guard against a tautological pass: the key-aware default for an + // OpenAI-only env must actually be an OpenAI model. + expect(expected.startsWith('openai:')).toBe(true); + const seenModels: Array = []; + const validAtomJson = JSON.stringify([ + { title: 'A', atom_type: 'insight', body: 'body a' }, + ]); + const result = await runPhaseExtractAtoms(engine, { + sourceId: 'default', + _transcripts: [ + { filePath: '/tmp/t1.txt', content: 'transcript 1 body', contentHash: 'h1'.repeat(8) }, + ], + _pages: [], + _chat: async (o: ChatOpts) => { + seenModels.push(o.model); + return stubChat(validAtomJson)(o); + }, + }); + expect(seenModels).toEqual([expected]); + expect(result.details.model).toBe(expected); + }); }); test('DB config can override the extract_atoms budget and model', async () => { diff --git a/test/cycle/synthesize-gateway-adapter.test.ts b/test/cycle/synthesize-gateway-adapter.test.ts index 54ad1b92..26e33935 100644 --- a/test/cycle/synthesize-gateway-adapter.test.ts +++ b/test/cycle/synthesize-gateway-adapter.test.ts @@ -104,6 +104,38 @@ describe('makeJudgeClient — construction-time provider probe', () => { }); describe('JudgeClient.create — gateway routing + shape adapter', () => { + test('A2b (#4077): forwards a caller AbortSignal to gateway.chat', async () => { + await withEnv({ ANTHROPIC_API_KEY: 'sk-test-A2b' }, async () => { + const judge = makeJudgeClient('claude-haiku-4-5-20251001'); + expect(judge).not.toBeNull(); + const abort = new AbortController(); + let receivedSignal: AbortSignal | undefined; + __setChatTransportForTests(async (opts): Promise => { + receivedSignal = opts.abortSignal; + return { + text: WORTH_PROCESSING_JSON, + blocks: [], + stopReason: 'end', + usage: { input_tokens: 10, output_tokens: 20, cache_read_tokens: 0, cache_creation_tokens: 0 }, + model: 'test:stub', + providerId: 'test', + }; + }); + + await judge!.create({ + model: 'claude-haiku-4-5-20251001', + max_tokens: 200, + system: 'judge system prompt', + messages: [{ role: 'user', content: 'judge this' }], + }, { signal: abort.signal }); + + // The exact caller signal must reach the transport — a cancelled cycle + // has to be able to tear down an in-flight judge call, not just skip + // the next one. + expect(receivedSignal).toBe(abort.signal); + }); + }); + test('A3: routes through gateway.chat (verified via __setChatTransportForTests stub)', async () => { await withEnv({ ANTHROPIC_API_KEY: 'sk-test-A3' }, async () => { const judge = makeJudgeClient('claude-haiku-4-5-20251001'); @@ -112,10 +144,12 @@ describe('JudgeClient.create — gateway routing + shape adapter', () => { let transportCalled = false; let receivedSystem: string | undefined; let receivedModel: string | undefined; + let receivedProviderOptions: Record> | undefined; __setChatTransportForTests(async (opts): Promise => { transportCalled = true; receivedSystem = opts.system; receivedModel = opts.model; + receivedProviderOptions = opts.providerOptions; return { text: WORTH_PROCESSING_JSON, blocks: [], @@ -137,12 +171,50 @@ describe('JudgeClient.create — gateway routing + shape adapter', () => { expect(receivedSystem).toBe('judge system prompt'); // Gateway model gets the anthropic: prefix normalized expect(receivedModel).toBe('anthropic:claude-haiku-4-5-20251001'); + // The thinking-disable pin is DeepSeek-only; other providers must not + // receive call-scoped provider options from the judge. + expect(receivedProviderOptions).toBeUndefined(); // Anthropic.Message shape returned expect(result.content?.[0]?.type).toBe('text'); expect((result.content?.[0] as { type: string; text: string }).text).toBe(WORTH_PROCESSING_JSON); }); }); + test('A3b: DeepSeek verdict judge disables thinking for its own call only', async () => { + // DeepSeek v4 models think by default and bill reasoning as OUTPUT tokens + // against max_tokens (recipe thinking_by_default, gbrain#4172). The triage + // judge wants the plain JSON verdict, so it pins thinking off per-call via + // ChatOpts.providerOptions instead of burning budget on reasoning. + // No DEEPSEEK_API_KEY needed: non-anthropic construction skips the key + // probe (A9) and the transport is stubbed. + const judge = makeJudgeClient('deepseek:deepseek-v4-flash'); + expect(judge).not.toBeNull(); + + let receivedProviderOptions: Record> | undefined; + __setChatTransportForTests(async (opts): Promise => { + receivedProviderOptions = opts.providerOptions; + return { + text: WORTH_PROCESSING_JSON, + blocks: [], + stopReason: 'end', + usage: { input_tokens: 10, output_tokens: 20, cache_read_tokens: 0, cache_creation_tokens: 0 }, + model: 'deepseek:deepseek-v4-flash', + providerId: 'deepseek', + }; + }); + + await judge!.create({ + model: 'deepseek:deepseek-v4-flash', + max_tokens: 1024, + system: 'judge system prompt', + messages: [{ role: 'user', content: 'judge this' }], + }); + + expect(receivedProviderOptions).toEqual({ + deepseek: { thinking: { type: 'disabled' } }, + }); + }); + test('A4: ChatResult.text → Anthropic.Message.content[0].text mapping', async () => { await withEnv({ ANTHROPIC_API_KEY: 'sk-test-A4' }, async () => { const judge = makeJudgeClient('claude-haiku-4-5-20251001'); diff --git a/test/default-alias-liveness.test.ts b/test/default-alias-liveness.test.ts new file mode 100644 index 00000000..8a432a0a --- /dev/null +++ b/test/default-alias-liveness.test.ts @@ -0,0 +1,74 @@ +/** + * Dead-alias guard — DEFAULT_ALIASES / TIER_DEFAULTS must point at LIVE, + * recipe-listed, priced chat models. + * + * The sibling of test/default-model-panels.test.ts and + * test/cross-modal-default-slots.test.ts (#3510), closing the last unguarded + * hardcoded-default surface (#2507): `gemini` pointed at `google:gemini-3-pro` + * — only ever a preview id (`gemini-3-pro-preview`), shut down, never + * chat-listed nor priced — for months because nothing pinned alias targets to + * a recipe list. The guard only works if recipes list LIVE models — do not + * re-add a retired model to a recipe to quiet this test. + * + * Alias values feed the subagent queue (classifyCapabilities requires a + * provider-qualified, tool-capable model), so this also pins parseability + * and supports_tools. The `gpt` alias resolves DYNAMICALLY at runtime + * (account discovery); its static DEFAULT_ALIASES entry is the documented + * floor and must satisfy the same liveness bar. + */ +import { describe, expect, test } from 'bun:test'; + +import { DEFAULT_ALIASES, TIER_DEFAULTS } from '../src/core/model-config.ts'; +import { getRecipe } from '../src/core/ai/recipes/index.ts'; +import { resolveRecipe } from '../src/core/ai/model-resolver.ts'; +import { splitProviderModelId } from '../src/core/model-id.ts'; +import { canonicalLookup } from '../src/core/model-pricing.ts'; + +const ALL_DEFAULTS: Array<[string, string]> = [ + ...Object.entries(DEFAULT_ALIASES).map(([k, v]) => [`alias:${k}`, v] as [string, string]), + ...Object.entries(TIER_DEFAULTS).map(([k, v]) => [`tier:${k}`, v] as [string, string]), +]; + +describe('DEFAULT_ALIASES + TIER_DEFAULTS ↔ recipe consistency (dead-alias guard)', () => { + test('every default carries an explicit provider prefix and a known recipe', () => { + for (const [name, target] of ALL_DEFAULTS) { + const { provider, model } = splitProviderModelId(target); + expect(provider, `${name} → "${target}" must be provider-qualified`).not.toBeNull(); + expect(model.length, `${name} → "${target}" has an empty model tail`).toBeGreaterThan(0); + expect(getRecipe(provider!), `${name} → unknown recipe "${provider}"`).toBeDefined(); + } + }); + + test('every default target is LISTED in its recipe chat touchpoint (after recipe aliases)', () => { + for (const [name, target] of ALL_DEFAULTS) { + // resolveRecipe applies recipe-level aliases (e.g. anthropic's + // undated → dated rewrites) before the listing check, matching what + // the gateway does at call time. + const { parsed, recipe } = resolveRecipe(target); + const chatModels = recipe.touchpoints.chat?.models ?? []; + expect( + chatModels, + `${name} → "${target}" not listed for ${recipe.id} chat — the alias resolves to a dead model`, + ).toContain(parsed.modelId); + } + }); + + test('every default target supports tool calling (subagent queue requirement)', () => { + for (const [name, target] of ALL_DEFAULTS) { + const { recipe } = resolveRecipe(target); + expect( + recipe.touchpoints.chat?.supports_tools, + `${name} → "${target}": ${recipe.id} chat lacks supports_tools`, + ).toBe(true); + } + }); + + test('every default target has a canonical pricing entry', () => { + for (const [name, target] of ALL_DEFAULTS) { + expect( + canonicalLookup(target), + `${name} → "${target}" missing from CANONICAL_PRICING`, + ).toBeDefined(); + } + }); +}); diff --git a/test/doctor-abandoned-threads-month-precision.test.ts b/test/doctor-abandoned-threads-month-precision.test.ts new file mode 100644 index 00000000..d851714c --- /dev/null +++ b/test/doctor-abandoned-threads-month-precision.test.ts @@ -0,0 +1,68 @@ +/** + * #4041 regression: doctor's abandoned_threads check must not warn on legal + * month-precision since_date values. The fence spec allows 'YYYY-MM' cells + * (stored verbatim as TEXT), but a bare since_date::date cast throws + * "invalid input syntax for type date" on them, turning the check's real + * signal into a spurious driver-error warn. Real-engine test on purpose — + * the hermetic mock suite (test/doctor-calibration-checks.test.ts) stubs + * executeRaw and can never catch SQL-level defects. + */ +import { describe, test, expect, beforeAll, afterAll } from 'bun:test'; +import { PGLiteEngine } from '../src/core/pglite-engine.ts'; +import { checkAbandonedThreads } from '../src/commands/doctor.ts'; + +let engine: PGLiteEngine; + +// Relative dates keep the test deterministic forever: 24 months back is +// always past the check's 12-month threshold. Day pinned to the 1st (UTC) +// so month arithmetic can never roll over. +const now = new Date(); +const past = new Date(Date.UTC(now.getUTCFullYear() - 2, now.getUTCMonth(), 1)); +const monthPrecisionSince = past.toISOString().slice(0, 7); // 'YYYY-MM' +const dayPrecisionSince = past.toISOString().slice(0, 10); // 'YYYY-MM-01' + +beforeAll(async () => { + engine = new PGLiteEngine(); + await engine.connect({}); + await engine.initSchema(); + const page = await engine.putPage('people/alice-example', { + title: 'Alice Example', + type: 'person' as const, + compiled_truth: '## Takes\n\nAlice is a strong founder.\n', + }); + await engine.addTakesBatch([ + { + page_id: page.id, + row_num: 1, + claim: 'Will win her market', + kind: 'take', + holder: 'holder-a', + weight: 0.85, + since_date: monthPrecisionSince, + }, + // Mixed formats in one table: the day-precision row must keep counting. + { + page_id: page.id, + row_num: 2, + claim: 'Strong technical team', + kind: 'take', + holder: 'holder-a', + weight: 0.9, + since_date: dayPrecisionSince, + }, + ]); +}); + +afterAll(async () => { + await engine.disconnect(); +}); + +describe('checkAbandonedThreads month-precision since_date (#4041)', () => { + test('counts month-precision takes instead of warning on the cast', async () => { + const check = await checkAbandonedThreads(engine); + // count > 0 is still 'ok' by design; 'warn' here means the query threw. + expect(check.status).toBe('ok'); + expect(check.message).toContain('2 high-conviction take(s)'); + expect(check.message).toContain('gbrain calibration'); + }); +}); diff --git a/test/doctor-no-migrate.serial.test.ts b/test/doctor-no-migrate.serial.test.ts new file mode 100644 index 00000000..408e030c --- /dev/null +++ b/test/doctor-no-migrate.serial.test.ts @@ -0,0 +1,116 @@ +/** + * #4364: `gbrain doctor --no-migrate` must be observational. Pre-fix, the + * doctor branch called connectEngine() WITHOUT probeOnly, whose auto-migrate + * block ran pending schema migrations — so doctor pointed at a clean DB + * migrated it 1→latest before the health report, destroying the very + * pre-migration state it was asked to report on. + * + * Spawns `doctor --no-migrate --json` against an UNINITIALIZED PGLite brain, + * then opens the datadir in-process and asserts the gbrain schema was NOT + * created. Red pre-fix: the flag was ignored and connectEngine's + * tryRunPendingMigrations built the full schema. + * + * Serial because it spawns a subprocess and writes a tmpdir. Skippable via + * `GBRAIN_SKIP_SUBPROCESS_TESTS=1` for fast-loop budget control. + */ +import { describe, test, expect } from 'bun:test'; +import { PGlite } from '@electric-sql/pglite'; +import { vector } from '@electric-sql/pglite/vector'; +import { pg_trgm } from '@electric-sql/pglite/contrib/pg_trgm'; +import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'fs'; +import { join } from 'path'; +import { tmpdir } from 'os'; + +const REPO = new URL('..', import.meta.url).pathname.replace(/\/$/, ''); +const SKIP = process.env.GBRAIN_SKIP_SUBPROCESS_TESTS === '1'; + +async function runCli( + args: string[], + env: Record, + timeoutMs: number, +): Promise<{ exitCode: number; stdout: string; stderr: string }> { + const proc = Bun.spawn(['bun', 'run', `${REPO}/src/cli.ts`, ...args], { + cwd: REPO, + env: { ...process.env, ...env }, + stdout: 'pipe', + stderr: 'pipe', + }); + const killer = setTimeout(() => { + try { proc.kill('SIGKILL'); } catch { /* already dead */ } + }, timeoutMs); + try { + const [stdout, stderr, exitCode] = await Promise.all([ + new Response(proc.stdout).text(), + new Response(proc.stderr).text(), + proc.exited, + ]); + return { exitCode, stdout, stderr }; + } finally { + clearTimeout(killer); + } +} + +function makeHome(prefix: string): { home: string; dataDir: string; env: Record } { + const home = mkdtempSync(join(tmpdir(), prefix)); + const dataDir = join(home, '.gbrain', 'brain.pglite'); + mkdirSync(join(home, '.gbrain'), { recursive: true }); + writeFileSync( + join(home, '.gbrain', 'config.json'), + JSON.stringify({ + engine: 'pglite', + database_path: dataDir, + embedding_dimensions: 1536, + }) + '\n', + ); + return { home, dataDir, env: { HOME: home, GBRAIN_HOME: home } }; +} + +/** + * Open the datadir directly: connectEngine's connect() creates raw pgdata + * either way, but the gbrain schema (pages et al) only appears if migrations + * ran. `null` from to_regclass = schema never created. + */ +async function pagesRegclass(dataDir: string): Promise { + const db = await PGlite.create({ dataDir, extensions: { vector, pg_trgm } }); + try { + const res = await db.query<{ pages: string | null }>( + "SELECT to_regclass('public.pages')::text AS pages", + ); + return res.rows[0]?.pages ?? null; + } finally { + await db.close(); + } +} + +describe('doctor --no-migrate keeps a clean DB unmigrated (#4364)', () => { + test.skipIf(SKIP)('schema is NOT created by doctor when --no-migrate is passed', async () => { + const { home, dataDir, env } = makeHome('gbrain-doctor-nomigrate-'); + try { + // Deliberately NO `init --migrate-only` first: the point is observing + // what doctor does to a never-initialized brain. + const doctor = await runCli(['doctor', '--no-migrate', '--json'], env, 180_000); + // Red pre-fix in two layers: the flag didn't exist (pre-dispatch + // validator rejected it before connecting — asserted here so the + // schema check below can't pass vacuously), and without it doctor's + // connectEngine() auto-migrated the clean DB. + expect(doctor.stderr).not.toContain('unknown flag'); + // Doctor may exit nonzero here (an uninitialized brain is unhealthy); + // the contract under test is purely "no mutation", not the verdict. + expect(await pagesRegclass(dataDir)).toBeNull(); + } finally { + try { rmSync(home, { recursive: true, force: true }); } catch { /* best effort */ } + } + }, 300_000); + + test.skipIf(SKIP)('contrast: plain doctor still auto-migrates (detection harness is live)', async () => { + const { home, dataDir, env } = makeHome('gbrain-doctor-migrate-'); + try { + await runCli(['doctor', '--json'], env, 180_000); + // Guards the test above against a vacuous pass: proves this harness + // observes the schema whenever doctor's connectEngine() migrates. + expect(await pagesRegclass(dataDir)).toBe('pages'); + } finally { + try { rmSync(home, { recursive: true, force: true }); } catch { /* best effort */ } + } + }, 300_000); +}); diff --git a/test/dream-verdict-cache-ttl.test.ts b/test/dream-verdict-cache-ttl.test.ts new file mode 100644 index 00000000..9f018d47 --- /dev/null +++ b/test/dream-verdict-cache-ttl.test.ts @@ -0,0 +1,157 @@ +/** + * dream_verdicts TTL (#4069 reimplemented): every cached triage verdict gets + * a 30-day expiry — reads treat expired rows as misses, re-judging refreshes + * the expiry, and sweepDreamVerdicts garbage-collects expired rows. + * + * `triage_version`/`model` already invalidate rows SEMANTICALLY; the TTL is + * the TEMPORAL bound: rows for deleted or re-hashed transcripts age out, and + * long-lived transcripts re-judge at a 30-day cadence. + * + * PGLite-backed. The Postgres engine carries the identical predicates + * (engine-parity iron rule); its triage path runs in + * test/e2e/dream-triage-postgres.test.ts. + * + * Run: bun test test/dream-verdict-cache-ttl.test.ts + */ + +import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test'; +import { DREAM_VERDICT_TTL_SECONDS, type DreamVerdictInput } from '../src/core/engine.ts'; +import { MIGRATIONS, LATEST_VERSION, runMigrations } from '../src/core/migrate.ts'; +import { PGLiteEngine } from '../src/core/pglite-engine.ts'; +import { TRIAGE_VERSION } from '../src/core/cycle/synthesize.ts'; + +let engine: PGLiteEngine; + +beforeAll(async () => { + engine = new PGLiteEngine(); + await engine.connect({ engine: 'pglite' } as never); + await engine.initSchema(); +}, 60_000); + +afterAll(async () => { + await engine.disconnect(); +}); + +beforeEach(async () => { + await engine.executeRaw('DELETE FROM dream_verdicts'); +}); + +/** Triage-v1-shaped verdict input (post-#4152 putDreamVerdict contract). */ +function verdictInput(overrides: Partial = {}): DreamVerdictInput { + return { + worth_processing: true, + reasons: ['substantive strategy discussion'], + score: 0.8, + content_type: 'strategy', + segments: [], + entities: [], + model: 'anthropic:claude-haiku-4-5-20251001', + triage_version: TRIAGE_VERSION, + ...overrides, + }; +} + +describe('dream_verdicts TTL', () => { + test('migration v143 adds a 30-day expiry column and index', async () => { + // Train port: v138 in the source branch, renumbered to 142 on the + // wave-k train (pass 1 had already appended v138-v141), then to 143 on + // the master retarget (master consumed v142 for the takes-embedding + // resize). + const migration = MIGRATIONS.find(item => item.name === 'dream_verdicts_ttl'); + expect(migration?.version).toBe(143); + expect(migration?.idempotent).toBe(true); + expect(LATEST_VERSION).toBeGreaterThanOrEqual(143); + + const columns = await engine.executeRaw<{ + is_nullable: string; + column_default: string | null; + }>(`SELECT is_nullable, column_default + FROM information_schema.columns + WHERE table_name = 'dream_verdicts' AND column_name = 'expires_at'`); + expect(columns).toHaveLength(1); + expect(columns[0].is_nullable).toBe('NO'); + expect(columns[0].column_default).toContain('30 days'); + + const indexes = await engine.executeRaw<{ indexname: string }>( + `SELECT indexname FROM pg_indexes + WHERE tablename = 'dream_verdicts' + AND indexname = 'dream_verdicts_expires_idx'`, + ); + expect(indexes).toHaveLength(1); + }); + + test('put assigns the default TTL and get returns a fresh verdict', async () => { + await engine.putDreamVerdict('/tmp/fresh.md', 'fresh-hash', verdictInput()); + + const hit = await engine.getDreamVerdict('/tmp/fresh.md', 'fresh-hash'); + expect(hit?.worth_processing).toBe(true); + expect(hit?.score).toBe(0.8); + + // Compare against the DATABASE clock — expiry is written and enforced + // server-side, so client-clock skew must not enter the assertion. + const rows = await engine.executeRaw<{ ttl_seconds: number }>( + `SELECT EXTRACT(EPOCH FROM (expires_at - now()))::float8 AS ttl_seconds + FROM dream_verdicts WHERE content_hash = 'fresh-hash'`, + ); + expect(rows[0].ttl_seconds).toBeGreaterThan(DREAM_VERDICT_TTL_SECONDS - 60); + expect(rows[0].ttl_seconds).toBeLessThanOrEqual(DREAM_VERDICT_TTL_SECONDS); + }); + + test('re-judging via upsert refreshes a nearly-expired row', async () => { + await engine.putDreamVerdict('/tmp/rejudged.md', 'rejudged-hash', verdictInput()); + await engine.executeRaw( + `UPDATE dream_verdicts SET expires_at = now() + interval '1 minute' + WHERE content_hash = 'rejudged-hash'`, + ); + + await engine.putDreamVerdict('/tmp/rejudged.md', 'rejudged-hash', verdictInput({ score: 0.9 })); + + const rows = await engine.executeRaw<{ ttl_seconds: number }>( + `SELECT EXTRACT(EPOCH FROM (expires_at - now()))::float8 AS ttl_seconds + FROM dream_verdicts WHERE content_hash = 'rejudged-hash'`, + ); + expect(rows[0].ttl_seconds).toBeGreaterThan(DREAM_VERDICT_TTL_SECONDS - 60); + expect((await engine.getDreamVerdict('/tmp/rejudged.md', 'rejudged-hash'))?.score).toBe(0.9); + }); + + test('expired rows miss on read and sweep deletes only expired rows', async () => { + await engine.putDreamVerdict('/tmp/expired.md', 'expired-hash', verdictInput({ + worth_processing: false, + score: 0.1, + reasons: ['legacy poison'], + })); + await engine.putDreamVerdict('/tmp/fresh.md', 'fresh-hash', verdictInput()); + await engine.executeRaw( + `UPDATE dream_verdicts SET expires_at = now() - interval '1 second' + WHERE content_hash = 'expired-hash'`, + ); + + expect(await engine.getDreamVerdict('/tmp/expired.md', 'expired-hash')).toBeNull(); + expect(await engine.getDreamVerdict('/tmp/fresh.md', 'fresh-hash')).not.toBeNull(); + expect(await engine.sweepDreamVerdicts()).toBe(1); + + const rows = await engine.executeRaw<{ content_hash: string }>( + 'SELECT content_hash FROM dream_verdicts ORDER BY content_hash', + ); + expect(rows.map(row => row.content_hash)).toEqual(['fresh-hash']); + }); + + test('upgrade backfill derives expiry from judged_at and is idempotent', async () => { + // Simulate a pre-v138 brain: no expires_at column, one boolean-era row + // judged 45 days ago. The backfill must preserve the row's original age + // (judged_at + 30 days = already expired) instead of granting legacy + // rows a fresh 30-day lifetime. + await engine.executeRaw('ALTER TABLE dream_verdicts DROP COLUMN expires_at'); + await engine.executeRaw(` + INSERT INTO dream_verdicts (file_path, content_hash, worth_processing, reasons, judged_at) + VALUES ('/tmp/legacy.md', 'legacy-hash', false, '[]'::jsonb, now() - interval '45 days') + `); + await engine.setConfig('version', '137'); + + const first = await runMigrations(engine); + expect(first.applied).toBeGreaterThanOrEqual(1); + expect(await engine.getDreamVerdict('/tmp/legacy.md', 'legacy-hash')).toBeNull(); + expect(await engine.sweepDreamVerdicts()).toBe(1); + expect((await runMigrations(engine)).applied).toBe(0); + }, 30_000); +}); diff --git a/test/e2e/code-intel-mcp-ops-pglite.test.ts b/test/e2e/code-intel-mcp-ops-pglite.test.ts index 9928be80..a6825efa 100644 --- a/test/e2e/code-intel-mcp-ops-pglite.test.ts +++ b/test/e2e/code-intel-mcp-ops-pglite.test.ts @@ -153,6 +153,33 @@ describe('v0.34 W3 — code_callers source scoping', () => { }); }); +describe('#4011 — graph ops re-route to the code-bearing federated source', () => { + test('unqualified code_callers on a code-less seed source finds callers in the sole code-bearing federated source', async () => { + // Vault+code brain: the caller's scalar scope ('default') holds no code; + // the graph lives entirely in 'code-src'. Pre-#4011 the traversal stayed + // on 'default' and readiness honestly reported not_built — masking a + // fully built graph that code_def / code_refs could already see. + await registerSource(engine, 'default'); + await registerSource(engine, 'code-src'); + const defPage = await insertCodePage(engine, 'code-src', 'src/foo.ts'); + const callerPage = await insertCodePage(engine, 'code-src', 'src/caller.ts'); + await insertChunk(engine, defPage, 0, 'parseMarkdown', 'function'); + const callerChunk = await insertChunk(engine, callerPage, 0, 'callerInCode', 'function'); + await insertUnresolvedEdge(engine, callerChunk, 'callerInCode', 'parseMarkdown', 'code-src'); + const ctx = { + ...makeCtx(engine, 'default'), + remote: true, + localFederatedSourceIds: ['default', 'code-src'], + }; + const result = (await operationsByName.code_callers!.handler(ctx, { symbol: 'parseMarkdown' })) as { + count: number; status: string; callers: Array<{ from_symbol_qualified: string }>; + }; + expect(result.status).not.toBe('not_built'); + expect(result.count).toBe(1); + expect(result.callers[0]!.from_symbol_qualified).toBe('callerInCode'); + }); +}); + describe('v0.34 W3 — code_def finds definition sites', () => { test('returns a definition for a seeded function symbol', async () => { await seedDefSite(engine); diff --git a/test/e2e/dream-synthesize-pglite.test.ts b/test/e2e/dream-synthesize-pglite.test.ts index 263a46fd..ebfee840 100644 --- a/test/e2e/dream-synthesize-pglite.test.ts +++ b/test/e2e/dream-synthesize-pglite.test.ts @@ -851,6 +851,109 @@ describe('E2E synthesize — PGLite inline subagent drain (takeover of #2699)', }, 30_000); }); +// ── #4077 cooperative abort — a cancelled cycle stops writing ───────── + +describe('E2E synthesize — cooperative abort (#4077)', () => { + test('abort during the triage judge fails the phase before cache, job, or page writes', async () => { + const rig = await setupRig(); + const abort = new AbortController(); + try { + await rig.engine.setConfig('dream.synthesize.enabled', 'true'); + await rig.engine.setConfig('dream.synthesize.session_corpus_dir', rig.corpusDir); + // deepseek: makeJudgeClient needs no local key (A9) — auth is the + // gateway's problem, and the transport below is stubbed anyway. + await rig.engine.setConfig('models.dream.synthesize_verdict', 'deepseek:deepseek-chat'); + const filePath = join(rig.corpusDir, '2026-08-13-abort-during-judge.txt'); + const body = 'a durable conversation about cancellation safety\n'.repeat(100); + writeFileSync(filePath, body); + + // Judge call slow enough that the abort (10ms) fires while it is + // in flight; the phase must unwind before caching the verdict. + __setChatTransportForTests(async () => { + await new Promise(resolve => setTimeout(resolve, 50)); + return { + text: JSON.stringify({ score: 0.9, content_type: 'strategy', segments: [], entities: [], reasons: ['durable cancellation contract'] }), + blocks: [], + stopReason: 'end' as const, + usage: { input_tokens: 10, output_tokens: 20, cache_read_tokens: 0, cache_creation_tokens: 0 }, + model: 'deepseek:deepseek-chat', + providerId: 'deepseek', + }; + }); + + setTimeout(() => abort.abort(new Error('test-cancel')), 10); + const result = await runPhaseSynthesize(rig.engine, { + brainDir: rig.brainDir, + dryRun: false, + signal: abort.signal, + }); + + expect(result.status).toBe('fail'); + expect(JSON.stringify(result.error)).toContain('test-cancel'); + const { createHash } = await import('node:crypto'); + const hash = createHash('sha256').update(body, 'utf8').digest('hex'); + expect(await rig.engine.getDreamVerdict(filePath, hash)).toBeNull(); + const jobs = await rig.engine.executeRaw<{ count: string }>( + `SELECT COUNT(*)::text AS count FROM minion_jobs`, + ); + const pages = await rig.engine.executeRaw<{ count: string }>( + `SELECT COUNT(*)::text AS count FROM pages`, + ); + expect(jobs[0]?.count).toBe('0'); + expect(pages[0]?.count).toBe('0'); + } finally { + resetGateway(); + await rig.cleanup(); + } + }, 30_000); + + test('caller abort cancels an active inline child well inside the 30s force-evict grace', async () => { + const rig = await setupRig(); + try { + const { MinionQueue } = await import('../../src/core/minions/queue.ts'); + const queue = new MinionQueue(rig.engine); + const queueName = `dream-inline-test-abort-${Date.now()}`; + const child = await queue.add( + 'subagent', + { prompt: 'test', model: 'anthropic:claude-sonnet-4-6', max_turns: 1 }, + { queue: queueName, max_attempts: 1 }, + { allowProtectedSubmit: true }, + ); + const controller = new AbortController(); + const started = Date.now(); + setTimeout(() => controller.abort(new Error('test-cancel-inline')), 10); + + // Handler only ends when ctx.signal fires — like the real subagent + // handler mid-LLM-call. The external abort must reach ctx.signal AND + // leave the child truthfully 'cancelled', not dead/delayed. + await expect(synthTesting.runSubagentsInline( + rig.engine, + queue, + queueName, + undefined, + async (ctx) => { + await new Promise((_, reject) => { + ctx.signal.addEventListener('abort', () => reject(new Error('provider aborted')), { once: true }); + }); + }, + undefined, + undefined, + null, + controller.signal, + )).rejects.toThrow('test-cancel-inline'); + + expect(Date.now() - started).toBeLessThan(30_000); + expect((await queue.getJob(child.id))?.status).toBe('cancelled'); + const pages = await rig.engine.executeRaw<{ count: string }>( + `SELECT COUNT(*)::text AS count FROM pages`, + ); + expect(pages[0]?.count).toBe('0'); + } finally { + await rig.cleanup(); + } + }, 30_000); +}); + // ── #4216 oneshot mode — full-phase E2E ───────────────────── describe('E2E synthesize — oneshot mode (#4216, DEFAULT)', () => { diff --git a/test/e2e/graph-quality.test.ts b/test/e2e/graph-quality.test.ts index 12a1736d..d8b2e095 100644 --- a/test/e2e/graph-quality.test.ts +++ b/test/e2e/graph-quality.test.ts @@ -351,17 +351,17 @@ Mention of [Alice](people/alice). test('search backlink boost: well-connected pages rank higher', async () => { // Create 3 pages all matching a search term, but with different inbound link counts. - await engine.putPage('topic/popular', { + const popular = await engine.putPage('topic/popular', { type: 'concept', title: 'Popular Topic', compiled_truth: 'This is the popular topic about widgets.', timeline: '', }); - await engine.putPage('topic/medium', { + const medium = await engine.putPage('topic/medium', { type: 'concept', title: 'Medium Topic', compiled_truth: 'This is a medium topic about widgets.', timeline: '', }); - await engine.putPage('topic/obscure', { + const obscure = await engine.putPage('topic/obscure', { type: 'concept', title: 'Obscure Topic', compiled_truth: 'This is an obscure topic about widgets.', timeline: '', @@ -376,9 +376,9 @@ Mention of [Alice](people/alice). await engine.addLink('ref/popular-0', 'topic/medium', '', 'mentions'); // Verify backlink counts. - const counts = await engine.getBacklinkCounts(['topic/popular', 'topic/medium', 'topic/obscure']); - expect(counts.get('topic/popular')).toBe(5); - expect(counts.get('topic/medium')).toBe(1); - expect(counts.get('topic/obscure')).toBe(0); + const counts = await engine.getBacklinkCounts([popular.id, medium.id, obscure.id]); + expect(counts.get(popular.id)).toBe(5); + expect(counts.get(medium.id)).toBe(1); + expect(counts.get(obscure.id)).toBe(0); }); }); diff --git a/test/e2e/source-boundary-mutation-postgres.test.ts b/test/e2e/source-boundary-mutation-postgres.test.ts new file mode 100644 index 00000000..937191cc --- /dev/null +++ b/test/e2e/source-boundary-mutation-postgres.test.ts @@ -0,0 +1,117 @@ +/** + * #4109 — real-Postgres regression coverage for source-boundary mutation + * deletion races. + * + * A hard delete that already owns the parent-row lock must linearize before + * addLink / addTimelineEntry: the FOR KEY SHARE endpoint resolution waits for + * the deleting transaction, then reports the missing endpoint through the + * typed engine contract (PageMissingError message shape) — never a raw + * SQLSTATE 23503 FK violation and never a zero-row upsert reported as + * success. PGLite is single-writer in-process, so this class only exists on + * real Postgres. + * + * DATABASE_URL-gated: self-skips without a real Postgres (same placement + * pattern as test/e2e/dream-triage-postgres.test.ts — picked up by the + * existing Postgres-service CI job). + */ + +import { describe, test, expect, beforeAll, afterAll } from 'bun:test'; +import postgres, { type Sql } from 'postgres'; +import { hasDatabase, setupDB, teardownDB, getEngine } from './helpers.ts'; + +const describePg = hasDatabase() ? describe : describe.skip; + +function deferred() { + let resolve!: () => void; + const promise = new Promise((done) => { + resolve = done; + }); + return { promise, resolve }; +} + +describePg('#4109 source-boundary mutation deletion races — Postgres', () => { + let deleter: Sql; + + beforeAll(async () => { + await setupDB(); + // Dedicated single-connection session so the racing DELETE holds its + // transaction open independently of the engine's pool. + deleter = postgres(process.env.DATABASE_URL!, { max: 1, prepare: false }); + }, 90_000); + + afterAll(async () => { + await deleter.end({ timeout: 5 }); + await teardownDB(); + }, 30_000); + + async function seedPage(slug: string): Promise { + await getEngine().putPage(slug, { + type: 'concept', + title: slug, + compiled_truth: 'deletion-race fixture', + }); + } + + test('addLink waits for a winning hard delete, then identifies the missing to endpoint', async () => { + const from = 'topics/race-link-from'; + const to = 'topics/race-link-to'; + await seedPage(from); + await seedPage(to); + + const deleteLocked = deferred(); + const releaseDelete = deferred(); + const deletion = deleter.begin(async (tx) => { + await tx`DELETE FROM pages WHERE slug = ${to} AND source_id = 'default'`; + deleteLocked.resolve(); + await releaseDelete.promise; + }); + await deleteLocked.promise; + + let settled = false; + const mutation = getEngine().addLink(from, to).finally(() => { + settled = true; + }); + // The FOR KEY SHARE endpoint lookup must block on the open delete. + await Bun.sleep(50); + expect(settled).toBeFalse(); + + releaseDelete.resolve(); + await deletion; + await expect(mutation).rejects.toThrow( + `addLink failed: to page "${to}" (source=default) not found`, + ); + }, 15_000); + + test('addTimelineEntry waits for a winning hard delete, then identifies the missing page', async () => { + const slug = 'topics/race-timeline'; + await seedPage(slug); + + const deleteLocked = deferred(); + const releaseDelete = deferred(); + const deletion = deleter.begin(async (tx) => { + await tx`DELETE FROM pages WHERE slug = ${slug} AND source_id = 'default'`; + deleteLocked.resolve(); + await releaseDelete.promise; + }); + await deleteLocked.promise; + + let settled = false; + const mutation = getEngine() + .addTimelineEntry(slug, { + date: '2026-08-14', + source: 'test', + summary: 'deletion-race fixture', + }) + .finally(() => { + settled = true; + }); + await Bun.sleep(50); + expect(settled).toBeFalse(); + + releaseDelete.resolve(); + await deletion; + await expect(mutation).rejects.toThrow( + `addTimelineEntry failed: page "${slug}" (source=default) not found`, + ); + }, 15_000); +}); diff --git a/test/embed-quarantine.serial.test.ts b/test/embed-quarantine.serial.test.ts new file mode 100644 index 00000000..8efd51dc --- /dev/null +++ b/test/embed-quarantine.serial.test.ts @@ -0,0 +1,169 @@ +/** + * Embed failure quarantine (--stale path). Reimplemented from PR #3622 + * (drdeebtech). + * + * Why: a page whose embed makes no progress is only logged; its chunks stay + * NULL, so every autopilot cycle re-sends the exact same doomed request + * forever. Against a serial local embedding server (ollama `-np 1`) that + * keeps computing client-aborted requests, this self-sustains into a + * congestion collapse (observed 2026-07-29/30: 6,900+ timeouts, pages + * retried 29×, ~4 CPU cores pinned for days). The quarantine gives the loop + * a give-up point: after N consecutive ZERO-progress attempts in one + * process, the page is skipped until the process restarts (or the operator + * sets frontmatter.embed_skip permanently). + * + * Coverage: + * - page failing GBRAIN_EMBED_QUARANTINE_AFTER (default 3) consecutive + * runs is skipped on the next run + * - a success resets the counter (transient blips never quarantine) + * - a PARTIAL failure (#3037 per-chunk isolation left some chunks NULL but + * others embedded) counts as progress, never toward quarantine — the + * next pass sends a smaller request, not the identical doomed one + * - the threshold is operator-tunable via env + * + * Serial: uses mock.module (leaks across files sharing a bun process). + */ +import { describe, test, expect, mock, beforeEach, afterEach } from 'bun:test'; +import type { BrainEngine } from '../src/core/engine.ts'; + +let totalPoisonCalls = 0; +let embedShouldFail = true; + +mock.module('../src/core/embedding.ts', () => ({ + embedBatch: async (texts: string[]) => { + if (texts.some(t => t.includes('POISON'))) { + totalPoisonCalls++; + // Deterministic-failure shaped: not 429/gateway/net-transient (#3374 + // retries timeouts in-run now), so the backoff loop throws immediately + // and the call count stays the attempt count. + if (embedShouldFail) throw new Error('[embed(ollama:nomic-embed-text)] 401 Unauthorized'); + } + return texts.map(() => new Float32Array(1536)); + }, + currentEmbeddingSignature: () => 'test:model:1536', +})); + +// Import AFTER mocking. +const { runEmbedCore, _resetEmbedQuarantineForTest } = await import('../src/commands/embed.ts'); + +// Preflight seam (same as test/embed-partial-failure-3037.serial.test.ts): +// make diagnoseEmbedding's fast-path pass without real env vars. +const { __setEmbedTransportForTests } = await import('../src/core/ai/gateway.ts'); +__setEmbedTransportForTests(async () => ({ embeddings: [], usage: { tokens: 0 } } as any)); + +function mockEngine(overrides: Partial> = {}): BrainEngine { + const calls: { method: string; args: any[] }[] = []; + const track = (method: string) => (...args: any[]) => { + calls.push({ method, args }); + if (overrides[method]) return overrides[method](...args); + return Promise.resolve(null); + }; + return new Proxy({} as any, { + get(_, prop: string) { + if (prop === '_calls') return calls; + if (overrides[prop]) return overrides[prop]; + return track(prop); + }, + }); +} + +// ONE chunk on purpose: a single-text batch never fans out (#3037 isolation +// needs >1 text), so each attempted run costs exactly one embedBatch call — +// the call count IS the attempt count. +const POISON_ROWS = [ + { page_id: 1, chunk_index: 0, source_id: 'default', slug: 'poison', chunk_text: 'POISON chunk one', chunk_source: 'compiled_truth' as const, model: null, token_count: 4 }, +]; + +function poisonEngine(): BrainEngine { + return mockEngine({ + countStaleChunks: async () => POISON_ROWS.length, + listStaleChunks: async () => POISON_ROWS, + getChunks: async () => POISON_ROWS.map(r => ({ + chunk_index: r.chunk_index, chunk_text: r.chunk_text, + chunk_source: r.chunk_source, token_count: r.token_count, + })), + upsertChunks: async () => {}, + setPageEmbeddingSignature: async () => {}, + }); +} + +beforeEach(() => { + totalPoisonCalls = 0; + embedShouldFail = true; + process.env.GBRAIN_EMBED_CONCURRENCY = '1'; + _resetEmbedQuarantineForTest?.(); +}); + +afterEach(() => { + delete process.env.GBRAIN_EMBED_QUARANTINE_AFTER; + delete process.env.GBRAIN_EMBED_CONCURRENCY; +}); + +describe('embed --stale failure quarantine', () => { + test('page failing 3 consecutive runs is quarantined on the 4th', async () => { + const engine = poisonEngine(); + + for (let run = 1; run <= 3; run++) { + await runEmbedCore(engine, { stale: true }); + expect(totalPoisonCalls).toBe(run); // one attempt per run, no more + } + + await runEmbedCore(engine, { stale: true }); + // Quarantined: run 4 must NOT send the doomed page to the provider. + expect(totalPoisonCalls).toBe(3); + }); + + test('a success resets the failure counter', async () => { + const engine = poisonEngine(); + + await runEmbedCore(engine, { stale: true }); // fail #1 + await runEmbedCore(engine, { stale: true }); // fail #2 + embedShouldFail = false; + await runEmbedCore(engine, { stale: true }); // success → counter resets + embedShouldFail = true; + await runEmbedCore(engine, { stale: true }); // fail #1 (fresh count) + // Without reset the page would already be quarantined here (3 cumulative + // failures) and this run would add no call. With reset it must attempt. + expect(totalPoisonCalls).toBe(4); + + await runEmbedCore(engine, { stale: true }); // fail #2 + await runEmbedCore(engine, { stale: true }); // fail #3 → quarantine + await runEmbedCore(engine, { stale: true }); // skipped + expect(totalPoisonCalls).toBe(6); + }); + + test('partial failure (#3037 fan-out embedded some chunks) never quarantines', async () => { + // Two chunks: the whole-page batch fails, isolation retries per chunk, + // POISON fails and the sibling succeeds → progress every run. Each run + // costs 2 POISON-bearing calls (the batch + the single-chunk retry). + const rows = [ + { page_id: 1, chunk_index: 0, source_id: 'default', slug: 'partial-poison', chunk_text: 'POISON chunk', chunk_source: 'compiled_truth' as const, model: null, token_count: 4 }, + { page_id: 1, chunk_index: 1, source_id: 'default', slug: 'partial-poison', chunk_text: 'healthy chunk', chunk_source: 'compiled_truth' as const, model: null, token_count: 4 }, + ]; + const engine = mockEngine({ + countStaleChunks: async () => rows.length, + listStaleChunks: async () => rows, + getChunks: async () => rows.map(r => ({ + chunk_index: r.chunk_index, chunk_text: r.chunk_text, + chunk_source: r.chunk_source, token_count: r.token_count, + })), + upsertChunks: async () => {}, + }); + + for (let run = 1; run <= 5; run++) { + const result = await runEmbedCore(engine, { stale: true }); + // Still attempted on runs 4 and 5 — well past the default threshold. + expect(totalPoisonCalls).toBe(run * 2); + expect(result.embedded).toBe(1); // the healthy sibling landed + } + }); + + test('threshold is tunable via GBRAIN_EMBED_QUARANTINE_AFTER', async () => { + process.env.GBRAIN_EMBED_QUARANTINE_AFTER = '1'; + const engine = poisonEngine(); + + await runEmbedCore(engine, { stale: true }); // fail #1 → quarantine immediately + await runEmbedCore(engine, { stale: true }); // skipped + expect(totalPoisonCalls).toBe(1); + }); +}); diff --git a/test/entity-resolve-prefix-dirs.test.ts b/test/entity-resolve-prefix-dirs.test.ts new file mode 100644 index 00000000..56c4d46b --- /dev/null +++ b/test/entity-resolve-prefix-dirs.test.ts @@ -0,0 +1,75 @@ +/** + * Entity resolution — prefix expansion over the hosts/ and projects/ + * directories. + * + * A bare infra token ("hive") with a canonical `hosts/` page used + * to fall through to slugify because PREFIX_EXPANSION_DIRS only listed + * people/ and companies/ — recall then queried an invented slug and + * returned nothing while the page and its facts sat one prefix away + * (2026-08-06 memory eval; reimplemented from community PR #3851 by + * miroslavb). + * + * `infra/` stays deliberately excluded — see the PREFIX_EXPANSION_DIRS + * comment in src/core/entities/resolve.ts — and that exclusion is pinned + * here so it can't be "fixed" back in. + * + * Fixture names use placeholder-pattern slugs per CLAUDE.md privacy rule. + * PGLite-only; no DATABASE_URL, no API keys. + */ + +import { describe, it, expect, beforeAll, afterAll } from 'bun:test'; +import { resolveEntitySlug } from '../src/core/entities/resolve.ts'; +import { PGLiteEngine } from '../src/core/pglite-engine.ts'; + +let engine: PGLiteEngine; + +beforeAll(async () => { + engine = new PGLiteEngine(); + await engine.connect({ database_url: '' }); + await engine.initSchema(); + + const pages = [ + // Bare child: exact `hosts/` page, no suffixed siblings. + { slug: 'hosts/hive', title: 'hive', type: 'note' }, + // Suffixed child: only `projects/-…` exists. + { slug: 'projects/apollo-lander', title: 'Apollo Lander', type: 'note' }, + // Cross-directory collision for the ambiguity gate. + { slug: 'people/kiwi-example', title: 'Kiwi Example', type: 'person' }, + { slug: 'hosts/kiwi', title: 'kiwi', type: 'note' }, + // infra/ is a mixed namespace of analysis/runbook docs — must NOT be + // prefix-expanded. + { slug: 'infra/vault-runbook', title: 'Vault Runbook', type: 'note' }, + ]; + for (const p of pages) { + await engine.putPage(p.slug, { + type: p.type, + title: p.title, + compiled_truth: `# ${p.title}`, + frontmatter: { type: p.type, title: p.title, slug: p.slug }, + }, { sourceId: 'default' }); + } +}); + +afterAll(async () => { + await engine.disconnect(); +}); + +describe('resolveEntitySlug — hosts/ and projects/ prefix expansion', () => { + it('bare token resolves to its exact hosts/ page', async () => { + expect(await resolveEntitySlug(engine, 'default', 'hive')).toBe('hosts/hive'); + }); + + it('bare token resolves to its suffixed projects/-… page', async () => { + expect(await resolveEntitySlug(engine, 'default', 'apollo')).toBe('projects/apollo-lander'); + }); + + it('cross-directory collision trips the ambiguity gate (slugify fallback)', async () => { + // people/kiwi-example and hosts/kiwi both match — expansion must + // refuse to pick one and fall through to the deterministic slugify. + expect(await resolveEntitySlug(engine, 'default', 'kiwi')).toBe('kiwi'); + }); + + it('infra/ pages are not prefix-expanded', async () => { + expect(await resolveEntitySlug(engine, 'default', 'vault')).toBe('vault'); + }); +}); diff --git a/test/eval-contradictions-runner.test.ts b/test/eval-contradictions-runner.test.ts index 07d6d34a..6a051731 100644 --- a/test/eval-contradictions-runner.test.ts +++ b/test/eval-contradictions-runner.test.ts @@ -10,6 +10,8 @@ import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test'; import { PGLiteEngine } from '../src/core/pglite-engine.ts'; import { resetPgliteState } from './helpers/reset-pglite.ts'; +import { withEnv } from './helpers/with-env.ts'; +import { resolveTierDefault } from '../src/core/model-config.ts'; import { PreFlightBudgetError, runContradictionProbe, @@ -113,6 +115,25 @@ describe('runContradictionProbe', () => { expect(out.report.total_contradictions_flagged).toBe(0); }); + test('default judge model follows the key-aware utility tier (#3813)', async () => { + // With only OPENAI_API_KEY present, the judge default must not be a + // hardcoded Anthropic model the install cannot serve. + await withEnv({ ANTHROPIC_API_KEY: undefined, OPENAI_API_KEY: 'sk-test-openai' }, async () => { + const expected = resolveTierDefault('utility'); + // Guard against a tautological pass: the key-aware default for an + // OpenAI-only env must actually be an OpenAI model. + expect(expected.startsWith('openai:')).toBe(true); + const out = await runContradictionProbe({ + engine, + queries: [], + judgeFn: stubJudge({}), + searchFn: async () => [], + budgetUsd: 5, + }); + expect(out.report.judge_model).toBe(expected); + }); + }); + test('cross-slug pair detection with stubbed search + judge', async () => { const idA = await seedPage('companies/acme', 'Acme'); const idB = await seedPage('openclaw/chat/x', 'Chat'); diff --git a/test/extract-cross-source-links-db.serial.test.ts b/test/extract-cross-source-links-db.serial.test.ts new file mode 100644 index 00000000..588a2d1f --- /dev/null +++ b/test/extract-cross-source-links-db.serial.test.ts @@ -0,0 +1,198 @@ +/** + * #2589 — cross-source wikilink edges, END-TO-END through the DB extract + * paths (the sibling test/extract-cross-source-links.test.ts covers only the + * pure resolveCandidateSources helper + the config ladder). Pinned here: + * + * - `extract links --source db`, flag OFF (default): a wikilink whose + * target exists only in another source writes NO edge, and the drop is + * OBSERVABLE (skipped-cross-source summary line) — never silent. + * - Flag ON via the env escape hatch: the edge IS written and to_page_id + * lands on the other source's page (the real (source_id, slug) join). + * - Flag ON, target in multiple foreign sources: the persisted edge points + * at the lexicographically smallest source (deterministic end-to-end). + * - `extract --stale --json`, flag OFF: the extract_stale_done event + * carries `skipped_cross_source` (the new JSON field). + * - extractStaleFromDB, flag ON via DB config: edge written, and the + * return shape's `skippedCrossSource` is 0. + * - `link_resolution.cross_source` is registered in KNOWN_CONFIG_KEYS + * (so `gbrain config set` accepts it without --force). + * + * Hermetic PGLite — no DATABASE_URL, no API keys. Harness conventions from + * test/extract-source-aware.test.ts. Serial file: mutates process.env. + */ + +import { describe, test, expect, beforeAll, afterAll, beforeEach, afterEach } from 'bun:test'; +import { PGLiteEngine } from '../src/core/pglite-engine.ts'; +import { runExtract, extractStaleFromDB } from '../src/commands/extract.ts'; +import { KNOWN_CONFIG_KEYS } from '../src/core/config.ts'; + +let engine: PGLiteEngine; + +const ENV_KEY = 'GBRAIN_LINK_RESOLUTION_CROSS_SOURCE'; +const savedEnv = process.env[ENV_KEY]; + +beforeAll(async () => { + engine = new PGLiteEngine(); + await engine.connect({}); + await engine.initSchema(); +}, 60_000); + +afterAll(async () => { + if (savedEnv === undefined) delete process.env[ENV_KEY]; + else process.env[ENV_KEY] = savedEnv; + if (engine) await engine.disconnect(); +}, 60_000); + +async function truncateAll(): Promise { + for (const t of ['content_chunks', 'links', 'timeline_entries', 'tags', 'raw_data', 'page_versions', 'ingest_log', 'pages']) { + await (engine as any).db.exec(`DELETE FROM ${t}`); + } + await (engine as any).db.exec(`DELETE FROM sources WHERE id <> 'default'`); + await (engine as any).db.exec(`DELETE FROM config WHERE key = 'link_resolution.cross_source'`); +} + +beforeEach(async () => { + await truncateAll(); + delete process.env[ENV_KEY]; +}, 60_000); // PGLite full-migration-chain init needs breathing room (house pattern, see extract-db.test.ts) +afterEach(() => { + delete process.env[ENV_KEY]; +}); + +/** Seed the literal #2589 shape: a comms page wikilinks a person page that + * lives ONLY in vault source(s) — never 'comms', never 'default'. */ +async function seedCrossSource(targetSources: string[] = ['vault-a']): Promise { + const ids = ['comms', ...targetSources]; + await engine.executeRaw( + `INSERT INTO sources (id, name) SELECT unnest($1::text[]), unnest($1::text[]) + ON CONFLICT (id) DO NOTHING`, [ids], + ); + for (const src of targetSources) { + await engine.executeRaw( + `INSERT INTO pages (slug, source_id, type, title, compiled_truth, timeline) + VALUES ('people/alice-example', $1, 'person', 'Alice', 'A person page.', '')`, [src], + ); + } + await engine.executeRaw( + `INSERT INTO pages (slug, source_id, type, title, compiled_truth, timeline) + VALUES ('comms/msg-1', 'comms', 'note', 'Msg 1', 'Talked to [[people/alice-example]] today.', '')`, + ); +} + +/** All persisted edges with BOTH endpoints' source ids resolved. */ +async function edgeEndpoints(): Promise> { + return engine.executeRaw<{ from_slug: string; from_sid: string; to_slug: string; to_sid: string }>( + `SELECT pf.slug AS from_slug, pf.source_id AS from_sid, + pt.slug AS to_slug, pt.source_id AS to_sid + FROM links l + JOIN pages pf ON l.from_page_id = pf.id + JOIN pages pt ON l.to_page_id = pt.id + ORDER BY pf.slug, pt.slug`, + ); +} + +function captureConsole(): { lines: string[]; restore: () => void } { + const lines: string[] = []; + const orig = console.log; + console.log = (...args: unknown[]) => { lines.push(args.map(String).join(' ')); }; + return { lines, restore: () => { console.log = orig; } }; +} + +function captureStdout(): { chunks: string[]; restore: () => void } { + const chunks: string[] = []; + const orig = process.stdout.write.bind(process.stdout); + process.stdout.write = ((chunk: string | Uint8Array): boolean => { + chunks.push(typeof chunk === 'string' ? chunk : Buffer.from(chunk).toString('utf-8')); + return true; + }) as any; + return { chunks, restore: () => { process.stdout.write = orig; } }; +} + +describe('#2589 extract links --source db — cross-source edges end-to-end', () => { + test('flag OFF (default): no edge written, drop surfaced in the summary (not silent)', async () => { + await seedCrossSource(['vault-a']); + const cap = captureConsole(); + try { + await runExtract(engine, ['links', '--source', 'db']); + } finally { + cap.restore(); + } + expect(await edgeEndpoints()).toEqual([]); + // The observable-drop contract: the human summary names the skip count. + const summary = cap.lines.join('\n'); + expect(summary).toContain('Skipped 1 cross-source candidate'); + expect(summary).toContain('link_resolution.cross_source'); + }); + + test('flag ON (env): edge written with to_page_id in the OTHER source', async () => { + await seedCrossSource(['vault-a']); + process.env[ENV_KEY] = '1'; + const cap = captureConsole(); + try { + await runExtract(engine, ['links', '--source', 'db']); + } finally { + cap.restore(); + } + expect(await edgeEndpoints()).toEqual([ + { from_slug: 'comms/msg-1', from_sid: 'comms', to_slug: 'people/alice-example', to_sid: 'vault-a' }, + ]); + // No skip line when nothing was skipped. + expect(cap.lines.join('\n')).not.toContain('cross-source candidate'); + }); + + test('flag ON, target in vault-b AND vault-a: persisted edge is deterministic (lexicographic min)', async () => { + // vault-b listed first so enumeration order can't accidentally pass. + await seedCrossSource(['vault-b', 'vault-a']); + process.env[ENV_KEY] = '1'; + const cap = captureConsole(); + try { + await runExtract(engine, ['links', '--source', 'db']); + } finally { + cap.restore(); + } + const edges = await edgeEndpoints(); + expect(edges.length).toBe(1); + expect(edges[0].to_sid).toBe('vault-a'); + }); +}); + +describe('#2589 extract --stale — skipped_cross_source observability + config plane', () => { + test('flag OFF: extract_stale_done JSON event carries skipped_cross_source, no edge written', async () => { + await seedCrossSource(['vault-a']); + const out = captureStdout(); + try { + await runExtract(engine, ['--stale', '--json']); + } finally { + out.restore(); + } + const events = out.chunks.join('').split('\n').filter(l => l.trim().startsWith('{')).map(l => JSON.parse(l)); + const done = events.find(e => e.action === 'extract_stale_done'); + expect(done).toBeDefined(); + expect(done.skipped_cross_source).toBe(1); + expect(done.links_created).toBe(0); + expect(await edgeEndpoints()).toEqual([]); + }); + + test('flag ON via DB config: extractStaleFromDB writes the edge; return shape counts 0 skips', async () => { + await seedCrossSource(['vault-a']); + await engine.setConfig('link_resolution.cross_source', 'true'); + const cap = captureConsole(); + let r: Awaited>; + try { + r = await extractStaleFromDB(engine, { + dryRun: false, jsonMode: false, includeFrontmatter: false, catchUp: false, + }); + } finally { + cap.restore(); + } + expect(r.skippedCrossSource).toBe(0); + expect(r.linksCreated).toBeGreaterThanOrEqual(1); + expect(await edgeEndpoints()).toEqual([ + { from_slug: 'comms/msg-1', from_sid: 'comms', to_slug: 'people/alice-example', to_sid: 'vault-a' }, + ]); + }); + + test('link_resolution.cross_source is a KNOWN config key (config set accepts it)', () => { + expect(KNOWN_CONFIG_KEYS).toContain('link_resolution.cross_source'); + }); +}); diff --git a/test/extract-cross-source-links.test.ts b/test/extract-cross-source-links.test.ts new file mode 100644 index 00000000..4446f34d --- /dev/null +++ b/test/extract-cross-source-links.test.ts @@ -0,0 +1,171 @@ +/** + * #2589 — cross-source wikilink edges: no more silent zero-edge drops. + * + * `resolveCandidateSources` historically returned `null` for a target that + * exists ONLY in other sources (neither the origin page's source nor + * 'default') — the same `null` as a missing endpoint, so multi-source graphs + * went sparse with dead_links stuck at 0 and nothing in the summary. A + * maintainer repro on current master (hermetic PGLite driving real + * `gbrain extract links --source db`) re-severitied the issue p3 → P1. + * + * Post-fix contract, pinned here: + * - cross-source-only targets return the distinguishable + * { ok: false, reason: 'cross_source' } when the flag is off (callers + * COUNT the drop — #2589's reasoned-failure shape); + * - with `{ crossSource: true }` the edge resolves with a DETERMINISTIC + * to_source_id (lexicographically smallest matching source) so repeated + * extracts and both engines converge under the (source_id, slug) key; + * - same-source and 'default' resolution are byte-for-byte unchanged for a + * FEDERATED origin (train port: #3478 landed first and gates the ambient + * 'default' fallback on `allowCrossSource`; the explicit #2589 opt-in + * supersedes that gate, and isolated-origin drops are counted too); + * - `isCrossSourceLinksEnabled` follows the #972 ladder: env override > + * DB config > default false. + */ + +import { describe, test, expect } from 'bun:test'; +import { resolveCandidateSources } from '../src/commands/extract.ts'; +import { isCrossSourceLinksEnabled } from '../src/core/link-extraction.ts'; +import type { LinkCandidate } from '../src/core/link-extraction.ts'; +import type { BrainEngine } from '../src/core/engine.ts'; +import { withEnv } from './helpers/with-env.ts'; + +function cand(targetSlug: string, fromSlug?: string): LinkCandidate { + return { + targetSlug, + fromSlug, + linkType: 'mentions', + context: 'ctx', + linkSource: 'markdown', + } as LinkCandidate; +} + +function maps(entries: Record) { + const allSlugs = new Set(Object.keys(entries)); + const slugToSources = new Map(Object.entries(entries)); + return { allSlugs, slugToSources }; +} + +describe('#2589 resolveCandidateSources — cross-source targets', () => { + test('same-source target unchanged (regression pin)', () => { + const { allSlugs, slugToSources } = maps({ + 'people/alice-example': ['vault-a'], + 'comms/msg-1': ['vault-a'], + }); + const r = resolveCandidateSources(cand('people/alice-example'), 'comms/msg-1', 'vault-a', allSlugs, slugToSources, true); + expect(r).toEqual({ ok: true, fromSlug: 'comms/msg-1', fromSourceId: 'vault-a', toSourceId: 'vault-a' }); + }); + + test("'default'-source fallback unchanged (regression pin)", () => { + const { allSlugs, slugToSources } = maps({ + 'people/alice-example': ['default'], + 'comms/msg-1': ['comms'], + }); + const r = resolveCandidateSources(cand('people/alice-example'), 'comms/msg-1', 'comms', allSlugs, slugToSources, true); + expect(r).toEqual({ ok: true, fromSlug: 'comms/msg-1', fromSourceId: 'comms', toSourceId: 'default' }); + }); + + test("missing endpoint returns reason 'missing_target' (distinct from a cross-source drop)", () => { + const { allSlugs, slugToSources } = maps({ 'comms/msg-1': ['comms'] }); + const r = resolveCandidateSources(cand('people/ghost'), 'comms/msg-1', 'comms', allSlugs, slugToSources, true); + expect(r).toEqual({ ok: false, reason: 'missing_target' }); + }); + + test("flag OFF: cross-source-only target returns reason 'cross_source', not a missing-target drop — the literal #2589 repro", () => { + // The issue's shape: a comms page wikilinks a person whose page lives + // only in a vault source. Pre-fix this returned null (silent drop). + const { allSlugs, slugToSources } = maps({ + 'people/alice-example': ['vault-a'], + 'comms/msg-1': ['comms'], + }); + const r = resolveCandidateSources(cand('people/alice-example'), 'comms/msg-1', 'comms', allSlugs, slugToSources, true); + expect(r).toEqual({ ok: false, reason: 'cross_source' }); + const rExplicitOff = resolveCandidateSources( + cand('people/alice-example'), 'comms/msg-1', 'comms', allSlugs, slugToSources, true, { crossSource: false }, + ); + expect(rExplicitOff).toEqual({ ok: false, reason: 'cross_source' }); + }); + + test('flag ON: cross-source edge resolves with the target source', () => { + const { allSlugs, slugToSources } = maps({ + 'people/alice-example': ['vault-a'], + 'comms/msg-1': ['comms'], + }); + const r = resolveCandidateSources( + cand('people/alice-example'), 'comms/msg-1', 'comms', allSlugs, slugToSources, true, { crossSource: true }, + ); + expect(r).toEqual({ ok: true, fromSlug: 'comms/msg-1', fromSourceId: 'comms', toSourceId: 'vault-a' }); + }); + + test('flag ON: multi-source target picks deterministically (lexicographic min)', () => { + // Order in the map deliberately reversed vs lexicographic to prove the + // pick sorts rather than trusting enumeration order — repeated extracts + // and both engines must converge on the same (source_id, slug) edge. + const { allSlugs, slugToSources } = maps({ + 'people/alice-example': ['vault-b', 'vault-a'], + 'comms/msg-1': ['comms'], + }); + const r = resolveCandidateSources( + cand('people/alice-example'), 'comms/msg-1', 'comms', allSlugs, slugToSources, true, { crossSource: true }, + ); + expect(r).toEqual({ ok: true, fromSlug: 'comms/msg-1', fromSourceId: 'comms', toSourceId: 'vault-a' }); + }); + + test('flag ON: same-source still wins over cross-source (no pick when unnecessary)', () => { + const { allSlugs, slugToSources } = maps({ + 'people/alice-example': ['vault-a', 'comms'], + 'comms/msg-1': ['comms'], + }); + const r = resolveCandidateSources( + cand('people/alice-example'), 'comms/msg-1', 'comms', allSlugs, slugToSources, true, { crossSource: true }, + ); + expect(r).toEqual({ ok: true, fromSlug: 'comms/msg-1', fromSourceId: 'comms', toSourceId: 'comms' }); + }); + + test('isolated origin (#3478 gate): flag OFF counts the drop, flag ON resolves', () => { + // Composition pin for the wave-k train merge: an ISOLATED (non-federated) + // origin never grows ambient cross-source edges — including the 'default' + // fallback — but the drop is COUNTED, and the explicit #2589 opt-in + // supersedes the gate (it exists to stop default-on silent regrowth). + const { allSlugs, slugToSources } = maps({ + 'people/alice-example': ['default'], + 'comms/msg-1': ['comms'], + }); + const off = resolveCandidateSources( + cand('people/alice-example'), 'comms/msg-1', 'comms', allSlugs, slugToSources, false, + ); + expect(off).toEqual({ ok: false, reason: 'cross_source' }); + const on = resolveCandidateSources( + cand('people/alice-example'), 'comms/msg-1', 'comms', allSlugs, slugToSources, false, { crossSource: true }, + ); + expect(on).toEqual({ ok: true, fromSlug: 'comms/msg-1', fromSourceId: 'comms', toSourceId: 'default' }); + }); +}); + +describe('#2589 isCrossSourceLinksEnabled — #972 resolution ladder', () => { + function engineWith(dbVal: string | null): BrainEngine { + return { getConfig: async () => dbVal } as unknown as BrainEngine; + } + + test('default false (no env, no config)', async () => { + await withEnv({ GBRAIN_LINK_RESOLUTION_CROSS_SOURCE: undefined }, async () => { + expect(await isCrossSourceLinksEnabled(engineWith(null))).toBe(false); + }); + }); + + test('DB config enables', async () => { + await withEnv({ GBRAIN_LINK_RESOLUTION_CROSS_SOURCE: undefined }, async () => { + expect(await isCrossSourceLinksEnabled(engineWith('true'))).toBe(true); + expect(await isCrossSourceLinksEnabled(engineWith('off'))).toBe(false); + }); + }); + + test('env overrides DB config in BOTH directions (operator escape hatch)', async () => { + await withEnv({ GBRAIN_LINK_RESOLUTION_CROSS_SOURCE: '1' }, async () => { + expect(await isCrossSourceLinksEnabled(engineWith(null))).toBe(true); + }); + await withEnv({ GBRAIN_LINK_RESOLUTION_CROSS_SOURCE: '0' }, async () => { + expect(await isCrossSourceLinksEnabled(engineWith('true'))).toBe(false); + }); + }); +}); diff --git a/test/extract-cross-source-resolution-observability.test.ts b/test/extract-cross-source-resolution-observability.test.ts index c8a10fb9..c40b5eff 100644 --- a/test/extract-cross-source-resolution-observability.test.ts +++ b/test/extract-cross-source-resolution-observability.test.ts @@ -26,7 +26,7 @@ describe('resolveCandidateSources — reason attribution (#2589)', () => { ['origin-page', ['source-a']], ['target-page', ['source-a']], ]); - const r = resolveCandidateSources(candidate('target-page'), 'origin-page', 'source-a', allSlugs, slugToSources); + const r = resolveCandidateSources(candidate('target-page'), 'origin-page', 'source-a', allSlugs, slugToSources, true); expect(r.ok).toBe(true); if (r.ok) { expect(r.fromSourceId).toBe('source-a'); @@ -40,7 +40,7 @@ describe('resolveCandidateSources — reason attribution (#2589)', () => { ['origin-page', ['source-a']], ['target-page', ['default']], ]); - const r = resolveCandidateSources(candidate('target-page'), 'origin-page', 'source-a', allSlugs, slugToSources); + const r = resolveCandidateSources(candidate('target-page'), 'origin-page', 'source-a', allSlugs, slugToSources, true); expect(r.ok).toBe(true); if (r.ok) expect(r.toSourceId).toBe('default'); }); @@ -48,7 +48,7 @@ describe('resolveCandidateSources — reason attribution (#2589)', () => { test('reason=missing_target when the target slug is not in allSlugs at all', () => { const allSlugs = new Set(['origin-page']); const slugToSources = new Map([['origin-page', ['source-a']]]); - const r = resolveCandidateSources(candidate('nonexistent-page'), 'origin-page', 'source-a', allSlugs, slugToSources); + const r = resolveCandidateSources(candidate('nonexistent-page'), 'origin-page', 'source-a', allSlugs, slugToSources, true); expect(r.ok).toBe(false); if (!r.ok) expect(r.reason).toBe('missing_target'); }); @@ -56,7 +56,7 @@ describe('resolveCandidateSources — reason attribution (#2589)', () => { test('reason=missing_from when the origin slug is not in allSlugs', () => { const allSlugs = new Set(['target-page']); const slugToSources = new Map([['target-page', ['source-a']]]); - const r = resolveCandidateSources(candidate('target-page'), 'origin-page', 'source-a', allSlugs, slugToSources); + const r = resolveCandidateSources(candidate('target-page'), 'origin-page', 'source-a', allSlugs, slugToSources, true); expect(r.ok).toBe(false); if (!r.ok) expect(r.reason).toBe('missing_from'); }); @@ -76,6 +76,7 @@ describe('resolveCandidateSources — reason attribution (#2589)', () => { 'comms-imessage', allSlugs, slugToSources, + true, ); expect(r.ok).toBe(false); if (!r.ok) expect(r.reason).toBe('cross_source'); @@ -87,7 +88,7 @@ describe('resolveCandidateSources — reason attribution (#2589)', () => { ['origin-page', ['source-a']], ['target-page', ['source-b']], ]); - const r = resolveCandidateSources(candidate('target-page'), 'origin-page', 'source-a', allSlugs, slugToSources); + const r = resolveCandidateSources(candidate('target-page'), 'origin-page', 'source-a', allSlugs, slugToSources, true); expect(r).not.toHaveProperty('toSourceId'); expect(r).not.toHaveProperty('fromSourceId'); }); diff --git a/test/extract-source-aware.test.ts b/test/extract-source-aware.test.ts index ee79fb03..99ce4ad0 100644 --- a/test/extract-source-aware.test.ts +++ b/test/extract-source-aware.test.ts @@ -122,4 +122,34 @@ describe('extract --source-id flag (#1204)', () => { ); expect(Number(linkRows[0]?.n ?? 0)).toBe(0); }); + + test('#3478: isolated source never falls back to a default-source target', async () => { + // $N::text::jsonb (never bare ::jsonb on a stringified param) per the + // JSONB invariant in CLAUDE.md. + await engine.executeRaw( + `INSERT INTO sources (id, name, config) VALUES ($1, $1, $2::text::jsonb)`, + ['isolated', JSON.stringify({ federated: false })], + ); + await engine.executeRaw( + `INSERT INTO pages (slug, source_id, type, title, compiled_truth, timeline) + VALUES + ('people/shared-target', 'default', 'person', 'Shared', 'Lives in default.', ''), + ('notes/isolated-note', 'isolated', 'note', 'Note', 'See [[people/shared-target]].', '')`, + ); + const origLog = console.log; + console.log = () => {}; + try { + await runExtract(engine, ['links', '--source', 'db', '--source-id', 'isolated', '--json']); + } finally { + console.log = origLog; + } + // The target exists only in 'default'; the non-federated source must not + // gain a cross-source edge from the fallback. + const linkRows = await engine.executeRaw<{ n: string }>( + `SELECT COUNT(*)::text AS n FROM links l + JOIN pages p ON l.from_page_id = p.id + WHERE p.source_id = 'isolated'`, + ); + expect(Number(linkRows[0]?.n ?? 0)).toBe(0); + }); }); diff --git a/test/extract-stale.test.ts b/test/extract-stale.test.ts index a5678786..e2c03813 100644 --- a/test/extract-stale.test.ts +++ b/test/extract-stale.test.ts @@ -148,6 +148,61 @@ describe('gbrain extract --stale', () => { expect(await engine.countStalePagesForExtraction()).toBe(2); }); + test('#3478: isolated source does not create a cross-source fallback link', async () => { + // $N::text::jsonb (never bare ::jsonb on a stringified param) per the + // JSONB invariant in CLAUDE.md. + await engine.executeRaw( + `INSERT INTO sources (id, name, config) VALUES ($1, $1, $2::text::jsonb) + ON CONFLICT (id) DO UPDATE SET config = EXCLUDED.config`, + ['isolated-kb', JSON.stringify({ federated: false })], + ); + try { + await engine.putPage('people/alice', personPage('Alice')); + await engine.putPage( + 'companies/private', + companyPage('Private', '[Alice](people/alice) advises Private.'), + { sourceId: 'isolated-kb' }, + ); + + await runExtract(engine, ['--stale', '--source-id', 'isolated-kb']); + + // The target exists only in 'default'; a non-federated source must NOT + // fall back across the source boundary (edge would leak isolated pages + // into cross-source graph reads). + const links = await engine.getLinks('companies/private', { sourceId: 'isolated-kb' }); + expect(links.some(l => l.to_slug === 'people/alice')).toBe(false); + } finally { + // truncateAll clears pages but not sources — remove the fixture row so + // later tests in this file see the pristine sources table. + await engine.executeRaw(`DELETE FROM sources WHERE id = 'isolated-kb'`); + } + }); + + test('#3478: federated source preserves the cross-source default fallback', async () => { + await engine.executeRaw( + `INSERT INTO sources (id, name, config) VALUES ($1, $1, $2::text::jsonb) + ON CONFLICT (id) DO UPDATE SET config = EXCLUDED.config`, + ['shared-kb', JSON.stringify({ federated: true })], + ); + try { + await engine.putPage('people/alice', personPage('Alice')); + await engine.putPage( + 'companies/shared', + companyPage('Shared', '[Alice](people/alice) advises Shared.'), + { sourceId: 'shared-kb' }, + ); + + await runExtract(engine, ['--stale', '--source-id', 'shared-kb']); + + // The target exists only in default, so a created edge proves the + // federated fallback stayed enabled. + const links = await engine.getLinks('companies/shared', { sourceId: 'shared-kb' }); + expect(links.some(l => l.to_slug === 'people/alice')).toBe(true); + } finally { + await engine.executeRaw(`DELETE FROM sources WHERE id = 'shared-kb'`); + } + }); + test('CRITICAL (CDX-1): page edited after stamp is re-extracted', async () => { await engine.putPage('people/alice', personPage('Alice')); await engine.putPage('companies/acme', companyPage('Acme', 'No links yet.')); diff --git a/test/facts-classify.test.ts b/test/facts-classify.test.ts index dd244f66..ce889b43 100644 --- a/test/facts-classify.test.ts +++ b/test/facts-classify.test.ts @@ -9,13 +9,35 @@ * - 4-strategy parse fallback for malformed JSON */ -import { describe, test, expect } from 'bun:test'; +import { describe, test, expect, beforeAll, afterAll } from 'bun:test'; import { cosineSimilarity, classifyAgainstCandidates, } from '../src/core/facts/classify.ts'; +import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts'; +import { LEGACY_EMBEDDING_CONFIG } from './helpers/legacy-embedding-config.ts'; import type { FactRow } from '../src/core/engine.ts'; +/** + * Two tests below pin the NO-CHAT-PROVIDER branch (classifier unavailable → + * cosine fallback). They used to just assume it: legacy-embedding-preload + * snapshots `env: { ...process.env }` into the gateway, so any provider key + * that reaches the snapshot makes `isAvailable('chat')` true and the tests + * take the LLM classifier path — real billable calls from a unit test. + * provider-keys-preload now strips ambient keys before the snapshot, but + * that is an environmental guarantee; pin the precondition in-file with an + * explicitly empty gateway env (the override mechanism the legacy preload + * documents). resetGateway() restores the baseline for later files in the + * shard (#3554 makes it re-apply the legacy config, not unconfigure). + */ +beforeAll(() => { + configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: {} }); +}); + +afterAll(() => { + resetGateway(); +}); + function makeFact(overrides: Partial & { id: number }): FactRow { return { source_id: 'default', entity_slug: 'people/alice-example', fact: 'x', kind: 'fact', @@ -94,8 +116,8 @@ describe('classifyAgainstCandidates', () => { { fact: 'new', kind: 'fact', embedding: a }, candidates, ); - // Without API key in test env, isAvailable('chat') is false → straight to - // cosine fallback. cos ≈ 0.93 ≥ 0.92 → duplicate. + // Gateway configured with env:{} above → isAvailable('chat') is false → + // straight to cosine fallback. cos ≈ 0.93 ≥ 0.92 → duplicate. expect(result.decision).toBe('duplicate'); expect((result as { reason: string }).reason).toBe('cosine_fallback'); }); @@ -106,8 +128,9 @@ describe('classifyAgainstCandidates', () => { { fact: 'new', kind: 'fact', embedding: null }, candidates, ); - // Without API key in test env, isAvailable('chat') is false → cosine fallback path. - // newFact has no embedding so cosine fallback can't compute → independent. + // Gateway configured with env:{} above → isAvailable('chat') is false → + // cosine fallback path. newFact has no embedding so cosine fallback can't + // compute → independent. expect(result.decision).toBe('independent'); expect((result as { reason: string }).reason).toBe('cosine_fallback'); }); diff --git a/test/facts-fallback-stub-guard.test.ts b/test/facts-fallback-stub-guard.test.ts new file mode 100644 index 00000000..6b5853a7 --- /dev/null +++ b/test/facts-fallback-stub-guard.test.ts @@ -0,0 +1,185 @@ +/** + * #4108 — fallback-resolved entity refs must not materialize canonical stub + * pages. + * + * End-to-end zero-LLM matrix through writeSingleFact (the pipeline's + * post-extraction stages: resolve → dedup → fence-first write) against a real + * PGLiteEngine with sources.local_path set, so the fence path is reachable: + * + * 1. nonexistent PREFIXED entity → fallback_slugify → DB-only, no stub page + * 2. nonexistent BARE entity → fallback_slugify → DB-only, no root stub + * 3. existing page, exact slug → exact_page → fence written + * 4. existing page, fuzzy title → fuzzy_match → fence written + * 5. existing page, curated alias → alias_exact → fence written + * + * Cases 1-2 pin the issue's expected behavior: the fact is RETAINED + * (entity_slug intact, legacy DB insert) but never mints a canonical page for + * a slug the resolver invented. Cases 3-5 pin that every provenance that + * verified a live page still fences. + */ + +import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test'; +import { mkdtempSync, rmSync, existsSync, readFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +import { PGLiteEngine } from '../src/core/pglite-engine.ts'; +import { writeSingleFact } from '../src/core/facts/write-single.ts'; + +let engine: PGLiteEngine; +let brainDir: string; + +beforeAll(async () => { + engine = new PGLiteEngine(); + await engine.connect({}); + await engine.initSchema(); + + // Live pages for the resolvable arms of the matrix (no on-disk files — + // the fence write stub-creates them, exercising DB→file drift repair). + await engine.putPage('companies/acme-example', { + type: 'company', + title: 'Acme Example', + compiled_truth: '# Acme Example', + frontmatter: {}, + }, { sourceId: 'default' }); + await engine.putPage('people/felicia-example', { + type: 'person', + title: 'Felicia Example', + compiled_truth: '# Felicia Example', + frontmatter: {}, + }, { sourceId: 'default' }); + await engine.putPage('people/star-example', { + type: 'person', + title: 'Star Example', + compiled_truth: '# Star Example', + frontmatter: {}, + }, { sourceId: 'default' }); + await engine.setPageAliases('people/star-example', 'default', ['starshine']); +}); + +afterAll(async () => { + await engine.disconnect(); +}); + +beforeEach(async () => { + // Fresh tree per test so file-existence assertions are hermetic. + brainDir = mkdtempSync(join(tmpdir(), 'facts-fallback-stub-guard-')); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + await (engine as any).db.query('DELETE FROM facts'); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + await (engine as any).db.query( + `UPDATE sources SET local_path = $1 WHERE id = 'default'`, + [brainDir], + ); +}); + +afterAll(() => { + try { + if (brainDir) rmSync(brainDir, { recursive: true, force: true }); + } catch { + /* best-effort */ + } +}); + +async function factRow(id: number): Promise<{ entity_slug: string | null; source_markdown_slug: string | null }> { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const rows = await (engine as any).db.query( + 'SELECT entity_slug, source_markdown_slug FROM facts WHERE id = $1', + [id], + ); + return rows.rows[0]; +} + +describe('writeSingleFact × resolution provenance (#4108 matrix)', () => { + test('1. nonexistent prefixed entity: fact retained DB-only, no canonical stub page', async () => { + const r = await writeSingleFact(engine, 'default', { + fact: 'Ships invisible widgets', + provenance: 'test:matrix', + entity: 'companies/zeta-widgets-nonexistent', + }); + + expect(r.status).toBe('inserted'); + expect(r.entity_slug).toBe('companies/zeta-widgets-nonexistent'); + + // The pre-#4108 bug: this exact write minted + // companies/zeta-widgets-nonexistent.md as a canonical stub page that a + // later sync imported, turning the invented slug into an exact_page hit. + expect(existsSync(join(brainDir, 'companies/zeta-widgets-nonexistent.md'))).toBe(false); + + const row = await factRow(r.id); + expect(row.entity_slug).toBe('companies/zeta-widgets-nonexistent'); + // DB-only insert — no fence file backs the row. + expect(row.source_markdown_slug).toBeNull(); + }); + + test('2. nonexistent bare entity: fact retained DB-only, no root stub', async () => { + const r = await writeSingleFact(engine, 'default', { + fact: 'Mentioned once in passing', + provenance: 'test:matrix', + entity: 'zetaperson', + }); + + expect(r.status).toBe('inserted'); + expect(r.entity_slug).toBe('zetaperson'); + expect(existsSync(join(brainDir, 'zetaperson.md'))).toBe(false); + + const row = await factRow(r.id); + expect(row.source_markdown_slug).toBeNull(); + }); + + test('3. exact existing page: fence written', async () => { + const r = await writeSingleFact(engine, 'default', { + fact: 'Raised a seed round in 2017', + provenance: 'test:matrix', + entity: 'companies/acme-example', + }); + + expect(r.status).toBe('inserted'); + expect(r.entity_slug).toBe('companies/acme-example'); + + const filePath = join(brainDir, 'companies/acme-example.md'); + expect(existsSync(filePath)).toBe(true); + const body = readFileSync(filePath, 'utf-8'); + expect(body).toContain('## Facts'); + expect(body).toContain('Raised a seed round in 2017'); + + const row = await factRow(r.id); + expect(row.source_markdown_slug).toBe('companies/acme-example'); + }); + + test('4. fuzzy-resolvable display name: fence written onto the existing page', async () => { + const r = await writeSingleFact(engine, 'default', { + fact: 'Joined the platform team', + provenance: 'test:matrix', + entity: 'Felicia Example', + }); + + expect(r.status).toBe('inserted'); + expect(r.entity_slug).toBe('people/felicia-example'); + + const filePath = join(brainDir, 'people/felicia-example.md'); + expect(existsSync(filePath)).toBe(true); + expect(readFileSync(filePath, 'utf-8')).toContain('Joined the platform team'); + + const row = await factRow(r.id); + expect(row.source_markdown_slug).toBe('people/felicia-example'); + }); + + test('5. curated alias: alias_exact provenance fences (not blocked by the fallback guard)', async () => { + const r = await writeSingleFact(engine, 'default', { + fact: 'Prefers the starshine handle', + provenance: 'test:matrix', + entity: 'starshine', + }); + + expect(r.status).toBe('inserted'); + expect(r.entity_slug).toBe('people/star-example'); + + const filePath = join(brainDir, 'people/star-example.md'); + expect(existsSync(filePath)).toBe(true); + expect(readFileSync(filePath, 'utf-8')).toContain('Prefers the starshine handle'); + + const row = await factRow(r.id); + expect(row.source_markdown_slug).toBe('people/star-example'); + }); +}); diff --git a/test/facts-recall-audit-rows.test.ts b/test/facts-recall-audit-rows.test.ts index 24a17c4f..c2d310d1 100644 --- a/test/facts-recall-audit-rows.test.ts +++ b/test/facts-recall-audit-rows.test.ts @@ -34,7 +34,7 @@ import { PGLiteEngine } from '../src/core/pglite-engine.ts'; import { dispatchToolCall } from '../src/mcp/dispatch.ts'; import { runRecall } from '../src/commands/recall.ts'; import { withEnv, emptyHome } from './helpers/with-env.ts'; -import { TERMINAL_AUDIT_SOURCE, NON_EXTRACTABLE_AUDIT_SOURCE, LEGACY_TERMINAL_AUDIT_SOURCE } from '../src/core/facts/audit-sources.ts'; +import { TERMINAL_AUDIT_SOURCE, NON_EXTRACTABLE_AUDIT_SOURCE, LEGACY_TERMINAL_AUDIT_SOURCE, AUDIT_ROW_SOURCES } from '../src/core/facts/audit-sources.ts'; let engine: PGLiteEngine; @@ -268,3 +268,43 @@ describe('post-review fix: legacy (pre-v2) terminal audit rows are also excluded expect(facts.some(f => f.fact === 'the user prefers oat milk in their coffee')).toBe(true); }); }); + +// #4394: countUnconsolidatedFacts feeds `gbrain recall --pending` and the +// recall op's pending_consolidation_count. Audit checkpoint rows are written +// without consolidated_at (extract-conversation-facts never consolidates its +// own progress markers), so a bare `consolidated_at IS NULL AND expired_at +// IS NULL` predicate counts every checkpoint ever written as forever-pending +// backlog — one per ingested page, inflating the figure on any brain that has +// run extract-conversation-facts. The count must key its exclusion on +// `source` (the writer), like the recall fetch predicates above. +describe('countUnconsolidatedFacts excludes audit checkpoint rows', () => { + let engine3: PGLiteEngine; + + beforeAll(async () => { + engine3 = new PGLiteEngine(); + await engine3.connect({}); + await engine3.initSchema(); + + await engine3.insertFact( + { fact: 'the user prefers oat milk in their coffee', kind: 'preference', entity_slug: 'coffee-prefs', source: 'test' }, + { source_id: 'default' }, + ); + // One checkpoint row per audit source (current terminal, non-extractable, + // legacy terminal) — all with consolidated_at NULL, as production writes + // them. + for (const auditSource of AUDIT_ROW_SOURCES) { + await engine3.insertFact( + { fact: 'EXTRACTION_COMPLETE', kind: 'fact', entity_slug: null, source: auditSource, source_session: `audit-${auditSource}`, notability: 'low' }, + { source_id: 'default' }, + ); + } + }); + + afterAll(async () => { + await engine3.disconnect(); + }); + + test('pending count is the one real fact, not real + audit checkpoints', async () => { + expect(await engine3.countUnconsolidatedFacts('default')).toBe(1); + }); +}); diff --git a/test/facts-recall-grep-sql.test.ts b/test/facts-recall-grep-sql.test.ts new file mode 100644 index 00000000..0742272e --- /dev/null +++ b/test/facts-recall-grep-sql.test.ts @@ -0,0 +1,133 @@ +/** + * recall (MCP op) — `grep` must filter in SQL, BEFORE the limit. + * + * A client-side post-limit grep silently returns nothing on a + * high-cardinality entity: the matching fact sits outside the newest-N + * window the engine fetched, so `recall --entity X --grep needle` comes + * back empty while the fact exists — indistinguishable from "not in + * memory" (found by the 2026-08-06 memory eval on an entity with hundreds + * of facts; reimplemented from community PR #3851 by miroslavb). + * + * Seed order matters: the needle fact goes in FIRST (older created_at / + * lowest id), then `limit`-plus newer non-matching facts go in AFTER. + * With ORDER BY ... DESC, id DESC the needle falls OUTSIDE the fetch + * window — a post-limit filter finds nothing, so these tests only pass + * when the engines apply grep in the WHERE clause. (Seeding the needle + * last would let a client-side grep pass too — non-discriminative.) + * + * The supersessions arm bypasses FactListOpts, so its client-side grep + * is pinned separately below. + * + * PGLite-only; no DATABASE_URL, no API keys. + */ + +import { describe, test, expect, beforeAll, afterAll } from 'bun:test'; +import { PGLiteEngine } from '../src/core/pglite-engine.ts'; +import { dispatchToolCall } from '../src/mcp/dispatch.ts'; + +let engine: PGLiteEngine; + +const ENTITY = 'people/alice-example'; +const SESSION = 'grep-session-a'; +const NEEDLE_FACT = 'alice prefers oat milk in coffee'; +// More filler rows than the limit used below, so the needle fact is +// guaranteed to sit outside the newest-N window on every arm's sort key. +const FILLER_COUNT = 10; +const LIMIT = 5; + +async function recall(params: Record) { + const result = await dispatchToolCall(engine, 'recall', params, { + remote: false, + sourceId: 'default', + }); + expect(result.isError).toBeFalsy(); + return JSON.parse(result.content[0].text) as { + facts: Array<{ fact: string; entity_slug: string | null }>; + }; +} + +beforeAll(async () => { + engine = new PGLiteEngine(); + await engine.connect({}); + await engine.initSchema(); + + await engine.insertFact( + { fact: NEEDLE_FACT, kind: 'preference', entity_slug: ENTITY, source: 'test', source_session: SESSION }, + { source_id: 'default' }, + ); + // A literal-wildcard row for the escaping test: '100%' must be matched + // as text, not as a LIKE pattern. + await engine.insertFact( + { fact: 'alice keeps battery at 100% before travel', kind: 'fact', entity_slug: ENTITY, source: 'test', source_session: SESSION }, + { source_id: 'default' }, + ); + for (let i = 0; i < FILLER_COUNT; i++) { + await engine.insertFact( + { fact: `alice filler fact number ${i}`, kind: 'fact', entity_slug: ENTITY, source: 'test', source_session: SESSION }, + { source_id: 'default' }, + ); + } +}); + +afterAll(async () => { + await engine.disconnect(); +}); + +describe('recall grep filters in SQL before the limit', () => { + test('entity arm: needle outside the newest-N window is still found', async () => { + const payload = await recall({ entity: ENTITY, grep: 'oat milk', limit: LIMIT }); + expect(payload.facts.some(f => f.fact === NEEDLE_FACT)).toBe(true); + expect(payload.facts.every(f => f.fact.includes('oat milk'))).toBe(true); + }); + + test('session arm: needle outside the newest-N window is still found', async () => { + const payload = await recall({ session_id: SESSION, grep: 'oat milk', limit: LIMIT }); + expect(payload.facts.some(f => f.fact === NEEDLE_FACT)).toBe(true); + }); + + test('since arm: needle outside the newest-N window is still found', async () => { + const payload = await recall({ since: '1 hour ago', grep: 'oat milk', limit: LIMIT }); + expect(payload.facts.some(f => f.fact === NEEDLE_FACT)).toBe(true); + }); + + test('no-filter arm: needle outside the newest-N window is still found', async () => { + const payload = await recall({ grep: 'oat milk', limit: LIMIT }); + expect(payload.facts.some(f => f.fact === NEEDLE_FACT)).toBe(true); + }); + + test('grep is case-insensitive', async () => { + const payload = await recall({ entity: ENTITY, grep: 'OAT MILK', limit: LIMIT }); + expect(payload.facts.some(f => f.fact === NEEDLE_FACT)).toBe(true); + }); + + test('LIKE wildcards in the needle are literal, not patterns', async () => { + // Unescaped, '100%' becomes the pattern %100%% and would also match + // every 'filler fact number 100'-style row containing '100'. Escaped, + // it matches only the literal-percent row. + const payload = await recall({ entity: ENTITY, grep: '100%', limit: LIMIT }); + expect(payload.facts.length).toBe(1); + expect(payload.facts[0].fact).toBe('alice keeps battery at 100% before travel'); + }); + + test('non-matching grep returns empty, not the unfiltered window', async () => { + const payload = await recall({ entity: ENTITY, grep: 'no-such-needle-anywhere', limit: LIMIT }); + expect(payload.facts.length).toBe(0); + }); +}); + +describe('supersessions arm keeps its client-side grep', () => { + test('grep filters the supersession audit log', async () => { + const old = await engine.insertFact( + { fact: 'bob-example lives in kirkland', kind: 'fact', entity_slug: 'people/bob-example', source: 'test' }, + { source_id: 'default' }, + ); + await engine.insertFact( + { fact: 'bob-example lives in bellevue', kind: 'fact', entity_slug: 'people/bob-example', source: 'test' }, + { source_id: 'default', supersedeId: old.id }, + ); + const hit = await recall({ supersessions: true, grep: 'kirkland' }); + expect(hit.facts.some(f => f.fact === 'bob-example lives in kirkland')).toBe(true); + const miss = await recall({ supersessions: true, grep: 'no-such-needle-anywhere' }); + expect(miss.facts.length).toBe(0); + }); +}); diff --git a/test/fence-write.test.ts b/test/fence-write.test.ts index 866164f6..c25baac4 100644 --- a/test/fence-write.test.ts +++ b/test/fence-write.test.ts @@ -23,6 +23,7 @@ import { PGLiteEngine } from '../src/core/pglite-engine.ts'; import { writeFactsToFence, lookupSourceLocalPath } from '../src/core/facts/fence-write.ts'; import type { FenceInputFact } from '../src/core/facts/fence-write.ts'; import { forgetFactInFence } from '../src/core/facts/forget.ts'; +import { readRecentStubGuardEvents } from '../src/core/facts/stub-guard-audit.ts'; import { writeSingleFact } from '../src/core/facts/write-single.ts'; import { _resetWriteThroughCacheForTest } from '../src/core/write-through.ts'; import { resetGateway } from '../src/core/ai/gateway.ts'; @@ -103,7 +104,7 @@ describe('writeFactsToFence — happy path', () => { test('stub-creates entity page when none exists, writes fence, stamps DB', async () => { const result = await writeFactsToFence( engine, - { sourceId: 'default', localPath: brainDir, slug: 'people/alice' }, + { sourceId: 'default', localPath: brainDir, slug: 'people/alice', resolutionSource: 'exact_page' }, [baseInput()], ); @@ -144,7 +145,7 @@ describe('writeFactsToFence — happy path', () => { test('types a stub from the prefix table, not a hardcoded 4-entry list', async () => { const result = await writeFactsToFence( engine, - { sourceId: 'default', localPath: brainDir, slug: 'projects/apollo' }, + { sourceId: 'default', localPath: brainDir, slug: 'projects/apollo', resolutionSource: 'exact_page' }, [baseInput({ fact: 'Apollo shipped in 2017' })], ); @@ -167,7 +168,7 @@ describe('writeFactsToFence — happy path', () => { const result = await writeFactsToFence( engine, - { sourceId: 'default', localPath: brainDir, slug: 'people/bob' }, + { sourceId: 'default', localPath: brainDir, slug: 'people/bob', resolutionSource: 'exact_page' }, [baseInput({ fact: 'Founded Widgets Inc.' })], ); @@ -183,7 +184,7 @@ describe('writeFactsToFence — happy path', () => { test('multi-fact batch appends consecutive row_nums', async () => { const result = await writeFactsToFence( engine, - { sourceId: 'default', localPath: brainDir, slug: 'people/carol' }, + { sourceId: 'default', localPath: brainDir, slug: 'people/carol', resolutionSource: 'exact_page' }, [ baseInput({ fact: 'Claim 1' }), baseInput({ fact: 'Claim 2' }), @@ -206,14 +207,14 @@ describe('writeFactsToFence — happy path', () => { // First write seeds the fence with rows 1 and 2. await writeFactsToFence( engine, - { sourceId: 'default', localPath: brainDir, slug: 'people/dan' }, + { sourceId: 'default', localPath: brainDir, slug: 'people/dan', resolutionSource: 'exact_page' }, [baseInput({ fact: 'First' }), baseInput({ fact: 'Second' })], ); // Second write should pick up at row_num=3. const result = await writeFactsToFence( engine, - { sourceId: 'default', localPath: brainDir, slug: 'people/dan' }, + { sourceId: 'default', localPath: brainDir, slug: 'people/dan', resolutionSource: 'exact_page' }, [baseInput({ fact: 'Third' })], ); @@ -228,7 +229,7 @@ describe('writeFactsToFence — happy path', () => { test('stub-creates nested directories (companies/x → mkdir companies)', async () => { const result = await writeFactsToFence( engine, - { sourceId: 'default', localPath: brainDir, slug: 'companies/acme' }, + { sourceId: 'default', localPath: brainDir, slug: 'companies/acme', resolutionSource: 'exact_page' }, [baseInput({ fact: 'Founded 2017' })], ); @@ -245,7 +246,7 @@ describe('writeFactsToFence — happy path', () => { const result = await writeFactsToFence( engine, - { sourceId: 'default', localPath: brainDir, slug: 'people/durable' }, + { sourceId: 'default', localPath: brainDir, slug: 'people/durable', resolutionSource: 'exact_page' }, [baseInput({ fact: 'Durable fence fact' })], ); @@ -261,7 +262,7 @@ describe('writeFactsToFence — legacy fallback', () => { test('null localPath returns legacyFallback:true with no inserts', async () => { const result = await writeFactsToFence( engine, - { sourceId: 'default', localPath: null, slug: 'people/whoever' }, + { sourceId: 'default', localPath: null, slug: 'people/whoever', resolutionSource: 'exact_page' }, [baseInput()], ); @@ -277,7 +278,7 @@ describe('writeFactsToFence — legacy fallback', () => { const slug = 'people/should-not-exist'; const result = await writeFactsToFence( engine, - { sourceId: 'default', localPath: brainDir, slug }, + { sourceId: 'default', localPath: brainDir, slug, resolutionSource: 'exact_page' }, [], ); expect(result).toEqual({ inserted: 0, ids: [] }); @@ -291,7 +292,7 @@ describe('writeFactsToFence — atomic recovery', () => { test('after a successful write, no .tmp file is left behind', async () => { await writeFactsToFence( engine, - { sourceId: 'default', localPath: brainDir, slug: 'people/erin' }, + { sourceId: 'default', localPath: brainDir, slug: 'people/erin', resolutionSource: 'exact_page' }, [baseInput()], ); @@ -301,10 +302,13 @@ describe('writeFactsToFence — atomic recovery', () => { }); describe('writeFactsToFence — stub guard (v0.34.5)', () => { - test('refuses to stub-create an unprefixed entity page (bare slug)', async () => { + test('refuses to stub-create an unprefixed entity page (bare slug), even with exact_page provenance', async () => { + // #4108: the guard is a UNION — the unprefixed-slug arm keeps blocking + // regardless of resolution provenance, it wasn't replaced by the + // provenance arm. const result = await writeFactsToFence( engine, - { sourceId: 'default', localPath: brainDir, slug: 'alice' }, + { sourceId: 'default', localPath: brainDir, slug: 'alice', resolutionSource: 'exact_page' }, [baseInput()], ); @@ -322,10 +326,11 @@ describe('writeFactsToFence — stub guard (v0.34.5)', () => { test('prefixed slugs (people/, companies/, etc.) bypass the guard', async () => { // Sanity: re-prove the happy path right next to the guard test so a // future refactor that breaks the guard's slug.includes('/') check - // can't silently pass by only running the guard case. + // can't silently pass by only running the guard case. #4108: passes + // 'exact_page' — resolved-to-existing entities still fence. const result = await writeFactsToFence( engine, - { sourceId: 'default', localPath: brainDir, slug: 'people/zelda' }, + { sourceId: 'default', localPath: brainDir, slug: 'people/zelda', resolutionSource: 'exact_page' }, [baseInput({ fact: 'Founded Hyrule Labs in 2024' })], ); @@ -339,7 +344,7 @@ describe('writeFactsToFence — stub guard (v0.34.5)', () => { // guard only fires when there's actual work the caller wants to do. const result = await writeFactsToFence( engine, - { sourceId: 'default', localPath: brainDir, slug: 'alice' }, + { sourceId: 'default', localPath: brainDir, slug: 'alice', resolutionSource: 'fallback_slugify' }, [], ); @@ -366,7 +371,7 @@ describe('writeFactsToFence — v0.46 (#3014) supersession-warning seam', () => try { result = await writeFactsToFence( engine, - { sourceId: 'default', localPath: brainDir, slug: 'people/alice' }, + { sourceId: 'default', localPath: brainDir, slug: 'people/alice', resolutionSource: 'exact_page' }, [baseInput({ fact: 'Points at a row that is not there', context: 'superseded by #99' })], ); } finally { @@ -381,6 +386,92 @@ describe('writeFactsToFence — v0.46 (#3014) supersession-warning seam', () => }); }); +describe('writeFactsToFence — fallback-resolution stub guard (#4108)', () => { + test('prefixed slug with fallback_slugify provenance is blocked: no page, no DB rows', async () => { + const auditDir = mkdtempSync(join(tmpdir(), 'stub-guard-audit-4108-')); + try { + await withEnv({ GBRAIN_AUDIT_DIR: auditDir }, async () => { + const result = await writeFactsToFence( + engine, + { sourceId: 'default', localPath: brainDir, slug: 'companies/zeta-nonexistent', resolutionSource: 'fallback_slugify' }, + [baseInput()], + ); + + expect(result.inserted).toBe(0); + expect(result.ids).toHaveLength(0); + expect(result.stubGuardBlocked).toBe(true); + + // No canonical stub page materialized for the invented slug. + expect(existsSync(join(brainDir, 'companies/zeta-nonexistent.md'))).toBe(false); + expect(existsSync(join(brainDir, 'companies/zeta-nonexistent.md.tmp'))).toBe(false); + + // No DB rows either — the CALLER routes to the legacy DB-only path. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const rows = await (engine as any).db.query('SELECT COUNT(*) AS n FROM facts'); + expect(Number(rows.rows[0].n)).toBe(0); + + // The audit event carries the new reason so stub_guard_24h can count + // fallback blocks separately from unprefixed ones. + const events = readRecentStubGuardEvents({ sinceMs: 60_000 }); + expect(events).toHaveLength(1); + expect(events[0]).toMatchObject({ + slug: 'companies/zeta-nonexistent', + reason: 'fallback_resolution', + }); + }); + } finally { + rmSync(auditDir, { recursive: true, force: true }); + } + }); + + test('null provenance is blocked too (fail-closed when the caller has no resolution step)', async () => { + const result = await writeFactsToFence( + engine, + { sourceId: 'default', localPath: brainDir, slug: 'companies/zeta-nullprov', resolutionSource: null }, + [baseInput()], + ); + + expect(result.stubGuardBlocked).toBe(true); + expect(existsSync(join(brainDir, 'companies/zeta-nullprov.md'))).toBe(false); + }); + + test('fallback provenance still APPENDS when the page file already exists on disk (DB/file drift edge)', async () => { + // The guard lives on the stub-CREATE branch only: a file that exists on + // disk but hasn't reached the pages index yet keeps accepting appends. + const slug = 'companies/zeta-ondisk'; + mkdirSync(join(brainDir, 'companies'), { recursive: true }); + writeFileSync( + join(brainDir, `${slug}.md`), + `---\ntype: company\ntitle: Zeta Ondisk\nslug: ${slug}\n---\n\n# Zeta Ondisk\n`, + 'utf-8', + ); + + const result = await writeFactsToFence( + engine, + { sourceId: 'default', localPath: brainDir, slug, resolutionSource: 'fallback_slugify' }, + [baseInput({ fact: 'Still accepts drift appends' })], + ); + + expect(result.inserted).toBe(1); + expect(result.stubGuardBlocked).toBeUndefined(); + expect(readFileSync(join(brainDir, `${slug}.md`), 'utf-8')).toContain('Still accepts drift appends'); + }); + + test('alias_exact provenance passes the guard (curated alias hits may stub-create)', async () => { + // #4108 blocklist shape: only fallback_slugify/null are blocked, so the + // v0.46.15 alias_exact member fences like exact_page/fuzzy_match. + const result = await writeFactsToFence( + engine, + { sourceId: 'default', localPath: brainDir, slug: 'people/star-example', resolutionSource: 'alias_exact' }, + [baseInput()], + ); + + expect(result.inserted).toBe(1); + expect(result.stubGuardBlocked).toBeUndefined(); + expect(existsSync(join(brainDir, 'people/star-example.md'))).toBe(true); + }); +}); + describe('lookupSourceLocalPath', () => { test('returns the configured local_path for an existing source', async () => { const got = await lookupSourceLocalPath(engine, 'default'); @@ -414,7 +505,7 @@ describe('writeFactsToFence — row_num survives a fence-less rewrite', () => { const first = await writeFactsToFence( engine, - { sourceId: 'default', localPath: brainDir, slug }, + { sourceId: 'default', localPath: brainDir, slug, resolutionSource: 'exact_page' }, [baseInput({ fact: 'First fact' }), baseInput({ fact: 'Second fact' })], ); expect(first.inserted).toBe(2); @@ -432,7 +523,7 @@ describe('writeFactsToFence — row_num survives a fence-less rewrite', () => { // existing rows on idx_facts_fence_key. const second = await writeFactsToFence( engine, - { sourceId: 'default', localPath: brainDir, slug }, + { sourceId: 'default', localPath: brainDir, slug, resolutionSource: 'exact_page' }, [baseInput({ fact: 'Third fact' })], ); expect(second.inserted).toBe(1); @@ -463,7 +554,7 @@ describe('writeFactsToFence — row_num survives a fence-less rewrite', () => { const result = await writeFactsToFence( brokenEngine, - { sourceId: 'default', localPath: brainDir, slug: 'people/dave' }, + { sourceId: 'default', localPath: brainDir, slug: 'people/dave', resolutionSource: 'exact_page' }, [baseInput({ fact: 'Written despite the failed hint' })], ); expect(result.inserted).toBe(1); @@ -478,7 +569,7 @@ describe('writeFactsToFence — sync.write_through opt-out', () => { const result = await writeFactsToFence( engine, - { sourceId: 'default', localPath: brainDir, slug: 'people/alice-example' }, + { sourceId: 'default', localPath: brainDir, slug: 'people/alice-example', resolutionSource: 'exact_page' }, [baseInput()], ); @@ -502,7 +593,7 @@ describe('writeFactsToFence — sync.write_through opt-out', () => { const result = await writeFactsToFence( engine, - { sourceId: 'default', localPath: brainDir, slug: 'people/db-only' }, + { sourceId: 'default', localPath: brainDir, slug: 'people/db-only', resolutionSource: 'exact_page' }, [baseInput()], ); @@ -552,7 +643,7 @@ describe('writeFactsToFence — durability latch recovery', () => { writeFileSync(indexLock, ''); const first = await writeFactsToFence( engine, - { sourceId: 'default', localPath: brainDir, slug: 'people/latch' }, + { sourceId: 'default', localPath: brainDir, slug: 'people/latch', resolutionSource: 'exact_page' }, [baseInput({ fact: 'First latch fact' })], ); expect(first.inserted).toBe(1); @@ -562,7 +653,7 @@ describe('writeFactsToFence — durability latch recovery', () => { const second = await writeFactsToFence( engine, - { sourceId: 'default', localPath: brainDir, slug: 'people/latch' }, + { sourceId: 'default', localPath: brainDir, slug: 'people/latch', resolutionSource: 'exact_page' }, [baseInput({ fact: 'Second latch fact' })], ); expect(second.inserted).toBe(1); @@ -605,7 +696,7 @@ describe('writeFactsToFence — durability latch recovery', () => { const a = writeFactsToFence( gatedEngine, - { sourceId: 'default', localPath: brainDir, slug: 'people/race' }, + { sourceId: 'default', localPath: brainDir, slug: 'people/race', resolutionSource: 'exact_page' }, [baseInput({ fact: 'Writer A fact' })], ); // Wait until A's rename landed (post-rename, pre-commit). @@ -617,7 +708,7 @@ describe('writeFactsToFence — durability latch recovery', () => { const b = writeFactsToFence( engine, - { sourceId: 'default', localPath: brainDir, slug: 'people/race' }, + { sourceId: 'default', localPath: brainDir, slug: 'people/race', resolutionSource: 'exact_page' }, [baseInput({ fact: 'Writer B fact' })], ); // Give B a beat to start (pre-fix, its snapshot fired here, before @@ -656,7 +747,7 @@ describe('writeFactsToFence — path matches writePageThrough (#4204)', () => { const result = await writeFactsToFence( engine, - { sourceId: 'proj', localPath: projDir, slug: 'people/alice' }, + { sourceId: 'proj', localPath: projDir, slug: 'people/alice', resolutionSource: 'exact_page' }, [baseInput()], ); @@ -698,7 +789,7 @@ describe('writeFactsToFence — path matches writePageThrough (#4204)', () => { const result = await writeFactsToFence( engine, - { sourceId: 'default', localPath: brainDir, slug: 'people/alice-smith' }, + { sourceId: 'default', localPath: brainDir, slug: 'people/alice-smith', resolutionSource: 'exact_page' }, [baseInput()], ); @@ -735,7 +826,7 @@ describe('writeFactsToFence — path matches writePageThrough (#4204)', () => { const result = await writeFactsToFence( engine, - { sourceId: 'default', localPath: goneDir, slug: 'people/erin' }, + { sourceId: 'default', localPath: goneDir, slug: 'people/erin', resolutionSource: 'exact_page' }, [baseInput()], ); diff --git a/test/files.test.ts b/test/files.test.ts index f6bf96a4..4da6906e 100644 --- a/test/files.test.ts +++ b/test/files.test.ts @@ -1,9 +1,9 @@ import { describe, test, expect, beforeAll, afterAll, spyOn } from 'bun:test'; -import { writeFileSync, mkdirSync, rmSync, symlinkSync, mkdtempSync } from 'fs'; +import { writeFileSync, readFileSync, mkdirSync, rmSync, symlinkSync, mkdtempSync } from 'fs'; import { join, basename } from 'path'; import { createHash } from 'crypto'; import { tmpdir } from 'os'; -import { collectFiles, formatFileSizeKb, getMimeType } from '../src/commands/files.ts'; +import { collectFiles, formatFileSizeKb, getMimeType, noStorageBackendMessage } from '../src/commands/files.ts'; import { operationsByName } from '../src/core/operations.ts'; import * as db from '../src/core/db.ts'; @@ -449,3 +449,49 @@ describe('files verify git lane (per-source root resolution)', () => { } }); }); + +describe('storage precondition — the silent-no-op class (#4022)', () => { + test('refusal message names the subcommand and why it refuses', () => { + const msg = noStorageBackendMessage('upload'); + expect(msg).toContain('gbrain files upload'); + // The two facts a user needs: nothing was stored, and metadata-only is why. + expect(msg).toContain('refusing to continue'); + expect(msg).toMatch(/metadata only|no blob column/); + expect(noStorageBackendMessage('redirect')).toContain('gbrain files redirect'); + }); + + /** + * The guard rung: a bug is a sample, not the population. `upload`, `sync`, + * and `redirect` each tested storage permissively (`if (config?.storage)`) + * and continued when the answer was "no" — inserting rows, printing + * "uploaded", and in `redirect` unlinking local originals whose bytes had + * never left the machine. This scan fails if anyone reintroduces the + * permissive form, so the whole class stays dead rather than just the three + * instances. + */ + test('[GUARD] no storage-dependent path uses the permissive `if (config?.storage)` form', () => { + const src = readFileSync(join(import.meta.dir, '..', 'src', 'commands', 'files.ts'), 'utf8'); + // Strip comments so prose describing the old bug doesn't trip the scan. + const code = src + .split('\n') + .filter((l) => { + const t = l.trim(); + return !t.startsWith('*') && !t.startsWith('//') && !t.startsWith('/*'); + }) + .join('\n'); + + expect(code).not.toMatch(/if\s*\(\s*config\?\.storage\s*\)/); + // And the storage-dependent commands must route through the shared guard. + for (const op of ['upload', 'sync', 'mirror', 'redirect']) { + expect(code).toContain(`requireStorageBackend('${op}')`); + } + }); + + test('[GUARD] verify never hardcodes its mismatch/missing counts', () => { + const src = readFileSync(join(import.meta.dir, '..', 'src', 'commands', 'files.ts'), 'utf8'); + // The original printed `${verified} files verified, 0 mismatches, 0 missing` + // with both counts literal, so phantom rows reported as verified. + expect(src).not.toMatch(/files verified, 0 mismatches, 0 missing/); + expect(src).toContain('${verified} files verified, ${mismatches} mismatches, ${missing} missing'); + }); +}); diff --git a/test/fixtures/preload-guard/operator-env-probe.test.ts b/test/fixtures/preload-guard/operator-env-probe.test.ts new file mode 100644 index 00000000..74bb1189 --- /dev/null +++ b/test/fixtures/preload-guard/operator-env-probe.test.ts @@ -0,0 +1,29 @@ +/** + * Probe fixture for test/operator-env-preload.test.ts. + * + * The parent test spawns `bun test` on this file with a controlled ambient + * environment and asserts on what SURVIVED the preload stack, read back from + * the JSON report written here. The probed names arrive via + * GBRAIN_TEST_OPERATOR_ENV_PROBE_NAMES (comma-separated) so the parent stays + * the single source of truth — this probe never dumps the whole environment, + * whose values on a dev shell can be secrets. + * + * When the report-path var is absent (normal suite discovery running this + * file directly), it passes as a no-op, like guard-probe.test.ts. + */ +import { test, expect } from 'bun:test'; +import { writeFileSync } from 'fs'; + +test('probe: report surviving ambient env after preloads', () => { + const out = process.env.GBRAIN_TEST_OPERATOR_ENV_PROBE_OUT; + if (!out) { + expect(true).toBe(true); + return; + } + const names = (process.env.GBRAIN_TEST_OPERATOR_ENV_PROBE_NAMES ?? '') + .split(',') + .filter(Boolean); + const seen: Record = {}; + for (const name of names) seen[name] = process.env[name] ?? null; + writeFileSync(out, JSON.stringify(seen)); +}); diff --git a/test/grade-takes.test.ts b/test/grade-takes.test.ts index c6343cca..6f977617 100644 --- a/test/grade-takes.test.ts +++ b/test/grade-takes.test.ts @@ -14,6 +14,7 @@ * - cache hit path: skip already-graded (take, prompt, judge, evidence_sig) * - takes that are too recent are skipped * - judge throw on a single take logs warning + phase continues + * - parse failure rejects instead of minting a cached 'unresolvable' (#3910) * - parseJudgeOutput unit tests * - takeIsOldEnough unit tests */ @@ -21,6 +22,7 @@ import { describe, test, expect } from 'bun:test'; import { runPhaseGradeTakes, + defaultJudge, parseJudgeOutput, evidenceSignature, takeIsOldEnough, @@ -422,6 +424,61 @@ describe('runPhaseGradeTakes — phase integration', () => { }); }); +// ─── #3910: judge parse failure must not mint a durable verdict ───── + +/** Hermetic gateway stand-in: returns fixed text through defaultJudge's chatFn seam. */ +function stubChatFn(text: string): NonNullable[1]> { + return async () => ({ + text, + blocks: [], + stopReason: 'end', + usage: { input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_creation_tokens: 0 }, + model: 'test:stub-judge', + providerId: 'stub', + }); +} + +describe('defaultJudge parse failure (#3910)', () => { + test('unparseable judge output rejects instead of resolving to a synthetic unresolvable verdict', async () => { + const take = buildTake({ id: 7, sinceDate: '2023-01-01' }); + await expect( + defaultJudge({ take, evidence: 'evidence body' }, stubChatFn('sorry, cannot answer in JSON')), + ).rejects.toThrow(/parse/); + }); + + test('control: valid verdict JSON resolves to the parsed verdict', async () => { + const take = buildTake({ id: 8, sinceDate: '2023-01-01' }); + const verdict = await defaultJudge( + { take, evidence: 'evidence body' }, + stubChatFn('{"verdict":"correct","confidence":0.88,"reasoning":"evidence supports it"}'), + ); + expect(verdict).toEqual({ verdict: 'correct', confidence: 0.88, reasoning: 'evidence supports it' }); + }); + + test('phase: parse failure warns naming the take, writes NO cache row, and the take stays retryable', async () => { + const takes = [buildTake({ id: 42, sinceDate: '2023-01-01' })]; + const { engine, captured, resolves } = buildMockEngine({ takes }); + const garbageChat = stubChatFn('sorry, cannot answer in JSON'); + const judge: JudgeFn = (input) => defaultJudge(input, garbageChat); + + const result = await runPhaseGradeTakes(buildCtx(engine), { judge }); + + expect(result.status).toBe('warn'); // per-take warnings, but no halt + const details = result.details as Record; + expect(details.verdicts_written).toBe(0); + // Pre-fix: one INSERT landed a {verdict:'unresolvable', confidence:0} row + // keyed on the deterministic placeholder evidence signature, so every + // later cycle cache-hit it and the take was silently frozen forever. + const inserts = captured.filter(c => c.sql.includes('INSERT INTO take_grade_cache')); + expect(inserts).toHaveLength(0); + const warnings = details.warnings as string[]; + expect(warnings).toHaveLength(1); + expect(warnings[0]).toContain('42'); + expect(warnings[0]).toContain('parse'); + expect(resolves).toHaveLength(0); + }); +}); + // ─── judge model follows the gateway chat model ───────────────────── describe('judge model follows the gateway chat model (label = actual)', () => { diff --git a/test/helpers/operator-env-preload.ts b/test/helpers/operator-env-preload.ts new file mode 100644 index 00000000..975f17b5 --- /dev/null +++ b/test/helpers/operator-env-preload.ts @@ -0,0 +1,75 @@ +/** + * Pre-test setup: drop the operator's ambient agent/workspace context so the + * unit suite's result depends on the code under test, not on whoever's shell + * started it. + * + * scripts/run-e2e.sh already performs this scrub for the E2E lane (its + * "Hermetic env scrub" block); the unit lane never got the same treatment. + * Measured on one operator machine (#4023), ambient operator context alone + * produced failures with no defect in the product: a stray GBRAIN_SOURCE + * short-circuits source resolution at tier `env` before the tier under test + * (8 failures across source-resolver-with-tier / source-resolver-silent- + * fallback, 1 in extract-fs-source-id), and GBRAIN_CYCLE_FRESHNESS_WARN_HOURS + * moves the very threshold doctor-cycle-freshness asserts. Provider + * *_API_KEYs — the other ambient-failure class #4023 measured — are handled + * by provider-keys-preload.ts; this preload deliberately leaves them alone. + * + * A preload rather than a runner-script scrub so a direct + * `bun test test/foo.test.ts` — how anyone iterates on a single file — is + * covered too. For the wrapper lanes the scrub is idempotent: run-e2e.sh + * already unsets these prefixes and re-exports its own keeps at its own + * subprocess boundary. This runs once, before any test file loads, so it only + * removes ambient shell state — vars a test sets itself are never touched. + * + * CONDUCTOR_* / MCP_* / OPENCLAW_* are operator/agent workspace context with + * no test-infrastructure tenants: stripped wholesale. GBRAIN_* is shared + * between operator config overrides (must be stripped) and this repo's own + * test machinery exported into `bun test` processes by the runners and CI + * workflows (must survive), so it is stripped through the keep-lists below. + * A blanket GBRAIN_* delete would break that machinery — e.g. the e2e lane's + * GBRAIN_DATABASE_URL target or the snapshot fast path. + * + * Escape hatch: GBRAIN_TEST_KEEP_AMBIENT_ENV=1 disables the scrub entirely + * (it lives under GBRAIN_TEST_, so it survives its own scrub). Debugging: + * GBRAIN_DEBUG_PRELOAD=1 logs the removed NAMES — never values, which may be + * secrets. + */ + +/** Operator/agent workspace prefixes with no test-machinery tenants. */ +const STRIP_PREFIX = /^(CONDUCTOR_|MCP_|OPENCLAW_)/; + +const KEEP_EXACT = new Set([ + 'GBRAIN_HOME', // per-run HOME isolation — gbrain-home-preload and run-e2e.sh both respect a pre-set value + 'GBRAIN_DATABASE_URL', // e2e DB target; database-url-guard-preload (registered first) already vetoed un-opted runs + 'GBRAIN_MODEL_DISCOVERY', // operator override provider-keys-preload deliberately respects + 'GBRAIN_PGLITE_SNAPSHOT', // schema-snapshot fast path exported by every unit runner (scripts/lib/test-env.sh) + 'GBRAIN_COMPILED_BIN', // heavy-lane compile-once binary (agent-harness.ts ensureCompiledGbrain) + 'GBRAIN_AUDIT_DIR', // audit-dir-preload honors a wrapper pre-set (inspect audit output after a run) + 'GBRAIN_SYNC_FAILURES_DIR', // same wrapper pre-set contract in sync-failures-preload + 'GBRAIN_DEBUG_PRELOAD', // the preload stack's own logging hatch +]); + +// GBRAIN_TEST_*: test-control opt-ins (ALLOW_DATABASE_URL, KEEP_PROVIDER_KEYS, +// shard/memory knobs) must survive their own scrub or every escape hatch is a +// dead end. GBRAIN_CI_*: ci-local.sh port plumbing. GBRAIN_E2E_*: db-guard's +// name-floor opt-in (its error message tells operators to set it) + e2e +// runner knobs. GBRAIN_REAL_*: heavy-lane real-agent door-suite opt-ins read +// in-process by test/e2e/install-real-*.serial.test.ts. +const KEEP_PREFIX = /^GBRAIN_(TEST_|CI_|E2E_|REAL_)/; + +if (process.env.GBRAIN_TEST_KEEP_AMBIENT_ENV !== '1') { + const removed: string[] = []; + for (const name of Object.keys(process.env)) { + const strip = + STRIP_PREFIX.test(name) || + (name.startsWith('GBRAIN_') && !KEEP_EXACT.has(name) && !KEEP_PREFIX.test(name)); + if (!strip) continue; + delete process.env[name]; + removed.push(name); + } + if (process.env.GBRAIN_DEBUG_PRELOAD === '1' && removed.length > 0) { + console.error( + `[operator-env-preload] cleared ${removed.length}: ${removed.sort().join(', ')}`, + ); + } +} diff --git a/test/import-file-content-sanity.test.ts b/test/import-file-content-sanity.test.ts index 809c883b..df9f45e7 100644 --- a/test/import-file-content-sanity.test.ts +++ b/test/import-file-content-sanity.test.ts @@ -1,4 +1,4 @@ -import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test'; +import { describe, test, expect, beforeAll, afterAll, beforeEach, spyOn } from 'bun:test'; import { PGLiteEngine } from '../src/core/pglite-engine.ts'; import { resetPgliteState } from './helpers/reset-pglite.ts'; import { withEnv } from './helpers/with-env.ts'; @@ -252,6 +252,26 @@ describe('importFromContent — soft-block (D9 transition + embed_skip)', () => expect(chunks.length).toBe(0); }); }); + + test('soft-block notice fires through console.warn, not bare stderr (#3893)', async () => { + await withIsolatedHome(async () => { + // #3893 (reimplemented from @y2688): a bare process.stderr.write is + // invisible to console-level operator hooks and log collectors — the + // oversized soft_block silently drops embedding, so its notice must + // go through console.warn. + const warnSpy = spyOn(console, 'warn'); + try { + const content = FRONTMATTER + 'a'.repeat(600_000); + await importFromContent(engine, 'test/warn-visibility', content, { noEmbed: true }); + const messages = warnSpy.mock.calls.map(args => args.map(String).join(' ')); + expect(messages.some(m => + m.includes('content-sanity flag (oversized)') && m.includes('test/warn-visibility'), + )).toBe(true); + } finally { + warnSpy.mockRestore(); + } + }); + }); }); describe('importFromContent — gate markers excluded from content_hash (no re-sync churn, #1699)', () => { diff --git a/test/init-force-engine-preservation.test.ts b/test/init-force-engine-preservation.test.ts new file mode 100644 index 00000000..119a9602 --- /dev/null +++ b/test/init-force-engine-preservation.test.ts @@ -0,0 +1,146 @@ +/** + * #3753 (reimplemented with credit to @harshsahrawat-commits) — a `--force` + * re-init with NO explicit engine flag must preserve a configured postgres + * engine. Pre-fix, the PGLite default branch swallowed the postgres config: + * running the deferred-setup hint's own command shape on a postgres brain + * rewrote config.json to engine=pglite, orphaning the postgres data behind a + * config that no longer pointed at it. Explicit flags (--pglite / --url) + * still switch engines, by saying so. + * + * Subprocess-driven (runInit calls process.exit on several paths) with a + * hermetic per-test GBRAIN_HOME, same pattern as test/init-mcp-only.test.ts. + * The preserved-postgres fixture URL points at a closed loopback port + * (nothing listens on 127.0.0.1:9), so the postgres connect fails fast AFTER + * the routing decision under test — the assertions are on config.json, which + * initPostgres only rewrites after a successful connect. + */ + +import { describe, test as testRaw, expect } from 'bun:test'; +import { mkdtempSync, mkdirSync, rmSync, existsSync, readFileSync, writeFileSync } from 'fs'; +import { tmpdir } from 'os'; +import { join } from 'path'; + +// PGLite cold start + initSchema in the subprocess runs ~5–20s on loaded +// machines; the 5s bun default (bunfig timeout is ignored by bun) is too tight. +function test(name: string, fn: () => void | Promise): void { + testRaw(name, fn, 120_000); +} + +const REPO_ROOT = join(import.meta.dir, '..'); + +// Closed loopback port: connection refused immediately, deterministically, +// with no network dependence. +const PRESERVED_URL = 'postgresql://gbrain:gbrain@127.0.0.1:9/gbrain_preserved'; + +async function runCli( + args: string[], + opts: { gbrainHome: string; cwd: string }, +): Promise<{ stdout: string; stderr: string; exitCode: number }> { + const { spawn } = await import('child_process'); + return new Promise((resolve) => { + const child = spawn('bun', ['run', join(REPO_ROOT, 'src', 'cli.ts'), ...args], { + env: { + // Minimal env: ambient DATABASE_URL/GBRAIN_DATABASE_URL or provider + // keys would change init's routing and detection tiers. + PATH: process.env.PATH, + HOME: process.env.HOME, + GBRAIN_HOME: opts.gbrainHome, + }, + stdio: ['ignore', 'pipe', 'pipe'], + cwd: opts.cwd, + }); + let stdout = ''; + let stderr = ''; + child.stdout?.on('data', (b) => { stdout += b.toString(); }); + child.stderr?.on('data', (b) => { stderr += b.toString(); }); + child.on('close', (code) => resolve({ stdout, stderr, exitCode: code ?? -1 })); + }); +} + +/** Fresh GBRAIN_HOME seeded with a postgres config, plus an empty cwd (so + * init's .md smart-detection scans nothing). GBRAIN_HOME is a PARENT dir: + * configDir() appends '.gbrain' itself. */ +function makePostgresHome(): { home: string; cwd: string; cleanup: () => void } { + const home = mkdtempSync(join(tmpdir(), 'gbrain-init-preserve-home-')); + const cwd = mkdtempSync(join(tmpdir(), 'gbrain-init-preserve-cwd-')); + mkdirSync(join(home, '.gbrain')); + writeFileSync( + join(home, '.gbrain', 'config.json'), + JSON.stringify({ engine: 'postgres', database_url: PRESERVED_URL }, null, 2), + ); + return { + home, + cwd, + cleanup: () => { + rmSync(home, { recursive: true, force: true }); + rmSync(cwd, { recursive: true, force: true }); + }, + }; +} + +function readConfig(home: string): Record { + return JSON.parse(readFileSync(join(home, '.gbrain', 'config.json'), 'utf-8')); +} + +describe('#3753 — --force re-init preserves a configured postgres engine', () => { + test('no engine flag: postgres config survives (not rewritten to pglite)', async () => { + const { home, cwd, cleanup } = makePostgresHome(); + try { + const r = await runCli(['init', '--force', '--no-embedding'], { gbrainHome: home, cwd }); + const cfg = readConfig(home); + // THE bug: pre-fix this came back 'pglite' — the default branch + // rewrote the config and orphaned the postgres data. + expect(cfg.engine).toBe('postgres'); + expect(cfg.database_url).toBe(PRESERVED_URL); + // No shadow PGLite brain materialized in GBRAIN_HOME either. + expect(existsSync(join(home, '.gbrain', 'brain.pglite'))).toBe(false); + expect(r.stderr).toMatch(/postgres engine preserved/); + } finally { + cleanup(); + } + }); + + test('--non-interactive without --url or env URL: preserved postgres URL is used instead of failing', async () => { + const { home, cwd, cleanup } = makePostgresHome(); + try { + const r = await runCli(['init', '--force', '--non-interactive', '--no-embedding'], { gbrainHome: home, cwd }); + expect(r.stderr).toMatch(/postgres engine preserved/); + expect(r.stderr).not.toMatch(/--non-interactive requires --url/); + const cfg = readConfig(home); + expect(cfg.engine).toBe('postgres'); + expect(cfg.database_url).toBe(PRESERVED_URL); + } finally { + cleanup(); + } + }); + + test('explicit --pglite still switches engines', async () => { + const { home, cwd, cleanup } = makePostgresHome(); + try { + const r = await runCli(['init', '--force', '--pglite', '--no-embedding'], { gbrainHome: home, cwd }); + expect(r.exitCode).toBe(0); + expect(r.stderr).not.toMatch(/postgres engine preserved/); + const cfg = readConfig(home); + expect(cfg.engine).toBe('pglite'); + } finally { + cleanup(); + } + }); + + test('explicit --url wins: no preservation, manual URL is dialed', async () => { + const { home, cwd, cleanup } = makePostgresHome(); + try { + const manual = 'postgresql://gbrain:gbrain@127.0.0.1:9/gbrain_other'; + const r = await runCli(['init', '--force', '--no-embedding', '--url', manual], { gbrainHome: home, cwd }); + expect(r.stderr).not.toMatch(/postgres engine preserved/); + // Connect to the closed port fails before any config write: the + // original config must be untouched (not clobbered by the manual URL, + // and never flipped to pglite). + const cfg = readConfig(home); + expect(cfg.engine).toBe('postgres'); + expect(cfg.database_url).toBe(PRESERVED_URL); + } finally { + cleanup(); + } + }); +}); diff --git a/test/operator-env-preload.test.ts b/test/operator-env-preload.test.ts new file mode 100644 index 00000000..4dd1fcb2 --- /dev/null +++ b/test/operator-env-preload.test.ts @@ -0,0 +1,165 @@ +/** + * #4023 operator-context hermeticity: a bare `bun test` must not inherit the + * operator's ambient agent/workspace context. A stray GBRAIN_SOURCE + * short-circuits source resolution at tier `env` before the tier under test; + * a GBRAIN_CYCLE_FRESHNESS_WARN_HOURS moves the very threshold + * doctor-cycle-freshness asserts; CONDUCTOR_/MCP_/OPENCLAW_ workspace vars + * are one `gbrain init`-shaped test away from the same class. run-e2e.sh + * already scrubs these for the E2E lane; test/helpers/operator-env-preload.ts + * is the unit-lane equivalent, and the repo's own test machinery (the + * GBRAIN_TEST_ / GBRAIN_CI_ / GBRAIN_E2E_ / GBRAIN_REAL_ prefixes + the exact + * keeps) must survive it. + * + * Each case spawns a real `bun test` child on a probe fixture with a + * controlled environment (the database-url-guard-preload.test.ts pattern), so + * what's asserted is the actual preload behavior, not a re-implementation of + * it. The probe reports the surviving values as JSON; all asserting happens + * here. + */ +import { describe, test, expect } from 'bun:test'; +import { mkdtempSync, readFileSync, rmSync } from 'fs'; +import { tmpdir } from 'os'; +import { join, resolve } from 'path'; + +const REPO_ROOT = resolve(import.meta.dir, '..'); +const PROBE = 'test/fixtures/preload-guard/operator-env-probe.test.ts'; + +/** + * Base child env: inherit, then strip every var these cases assert on plus + * the guard/scrub opt-ins, so a dev shell's own exports can't contaminate + * either direction of an assertion. + */ +function baseEnv(probed: string[]): Record { + const drop = new Set([ + ...probed, + 'DATABASE_URL', + 'GBRAIN_DATABASE_URL', + 'GBRAIN_TEST_ALLOW_DATABASE_URL', + 'GBRAIN_TEST_KEEP_AMBIENT_ENV', + 'GBRAIN_DEBUG_PRELOAD', + ]); + const env: Record = {}; + for (const [k, v] of Object.entries(process.env)) { + if (v === undefined || drop.has(k)) continue; + env[k] = v; + } + return env; +} + +function runProbe( + ambient: Record, + probed: string[], +): { exitCode: number; stderr: string; report: Record } { + const dir = mkdtempSync(join(tmpdir(), 'gb-operator-env-probe-')); + const out = join(dir, 'report.json'); + try { + const proc = Bun.spawnSync(['bun', 'test', '--timeout=15000', PROBE], { + cwd: REPO_ROOT, + env: { + ...baseEnv(probed), + ...ambient, + GBRAIN_TEST_OPERATOR_ENV_PROBE_OUT: out, + GBRAIN_TEST_OPERATOR_ENV_PROBE_NAMES: probed.join(','), + }, + stdout: 'pipe', + stderr: 'pipe', + // A hung child would otherwise block the sync call past bun's own + // per-test timeout (which cannot preempt a native sync call). + timeout: 20_000, + killSignal: 'SIGKILL', + }); + let report: Record = {}; + try { + report = JSON.parse(readFileSync(out, 'utf8')); + } catch { + // Leave {} — the exitCode assertion will surface the child failure. + } + return { exitCode: proc.exitCode ?? -1, stderr: proc.stderr.toString(), report }; + } finally { + rmSync(dir, { recursive: true, force: true }); + } +} + +describe('operator-env-preload (#4023)', () => { + test('strips ambient operator context: CONDUCTOR_/MCP_/OPENCLAW_ wholesale, GBRAIN_ config overrides', () => { + const probed = [ + 'CONDUCTOR_WORKSPACE_NAME', + 'MCP_SCOPE', + 'OPENCLAW_WORKSPACE', + 'GBRAIN_SOURCE', + 'GBRAIN_CYCLE_FRESHNESS_WARN_HOURS', + 'GBRAIN_BRAIN_ID', + ]; + const r = runProbe( + { + CONDUCTOR_WORKSPACE_NAME: 'ambient-leak', + MCP_SCOPE: 'ambient-leak', + OPENCLAW_WORKSPACE: 'ambient-leak', + GBRAIN_SOURCE: 'default', + GBRAIN_CYCLE_FRESHNESS_WARN_HOURS: '10', + GBRAIN_BRAIN_ID: 'ambient-leak', + }, + probed, + ); + expect(r.exitCode).toBe(0); + for (const name of probed) expect({ [name]: r.report[name] }).toEqual({ [name]: null }); + }, 30_000); + + test('keeps the test machinery the runners and CI workflows export', () => { + const probed = [ + 'GBRAIN_MODEL_DISCOVERY', + 'GBRAIN_PGLITE_SNAPSHOT', + 'GBRAIN_COMPILED_BIN', + 'GBRAIN_TEST_SENTINEL', + 'GBRAIN_CI_PG_PORT', + 'GBRAIN_E2E_ALLOW_DB', + 'GBRAIN_REAL_HERMES_E2E', + ]; + const ambient: Record = { + // '1' (not 'off') so a strip is distinguishable from provider-keys- + // preload's own default of 'off' when the var is absent. + GBRAIN_MODEL_DISCOVERY: '1', + GBRAIN_PGLITE_SNAPSHOT: 'probe-snapshot.tar', + GBRAIN_COMPILED_BIN: '/probe/bin/gbrain', + GBRAIN_TEST_SENTINEL: 'kept', + GBRAIN_CI_PG_PORT: '5434', + GBRAIN_E2E_ALLOW_DB: 'gbrain_probe_db', + GBRAIN_REAL_HERMES_E2E: '0', + }; + const r = runProbe(ambient, probed); + expect(r.exitCode).toBe(0); + for (const name of probed) expect({ [name]: r.report[name] }).toEqual({ [name]: ambient[name] }); + }, 30_000); + + test('keeps GBRAIN_DATABASE_URL in the opted-in e2e lane', () => { + // The e2e wrappers export GBRAIN_DATABASE_URL as the lane's target; a + // blanket GBRAIN_* delete here would sever it AFTER the guard preload + // approved the run. + const url = 'postgresql://localhost:5434/gbrain_probe'; + const r = runProbe( + { GBRAIN_DATABASE_URL: url, GBRAIN_TEST_ALLOW_DATABASE_URL: '1' }, + ['GBRAIN_DATABASE_URL'], + ); + expect(r.exitCode).toBe(0); + expect(r.report.GBRAIN_DATABASE_URL).toBe(url); + }, 30_000); + + test('GBRAIN_TEST_KEEP_AMBIENT_ENV=1 disables the scrub', () => { + const r = runProbe( + { GBRAIN_SOURCE: 'default', GBRAIN_TEST_KEEP_AMBIENT_ENV: '1' }, + ['GBRAIN_SOURCE'], + ); + expect(r.exitCode).toBe(0); + expect(r.report.GBRAIN_SOURCE).toBe('default'); + }, 30_000); + + test('GBRAIN_DEBUG_PRELOAD=1 logs removed names, never values', () => { + const r = runProbe( + { GBRAIN_SOURCE: 'hunter2-not-for-logs', GBRAIN_DEBUG_PRELOAD: '1' }, + ['GBRAIN_SOURCE'], + ); + expect(r.exitCode).toBe(0); + expect(r.stderr).toContain('GBRAIN_SOURCE'); + expect(r.stderr).not.toContain('hunter2-not-for-logs'); + }, 30_000); +}); diff --git a/test/pglite-disconnect-checkpoint.test.ts b/test/pglite-disconnect-checkpoint.test.ts new file mode 100644 index 00000000..941e2694 --- /dev/null +++ b/test/pglite-disconnect-checkpoint.test.ts @@ -0,0 +1,59 @@ +/** + * PGLite disconnect issues a best-effort CHECKPOINT before close() (#3893, + * reimplemented from @y2688's PR). + * + * PGLite is in-process WASM: when close() times out or wedges (the #4143 + * class) the handle is abandoned and dies with the process, losing any WAL + * not yet flushed into the data files. A pre-close CHECKPOINT makes the + * data files current so an abandoned close loses no committed rows. This is + * deliberately PGLite-only (no postgres-engine parity twin): a server + * Postgres owns its own checkpointer and survives this process dying. + */ +import { afterAll, beforeAll, describe, expect, test } from 'bun:test'; +import { PGLiteEngine } from '../src/core/pglite-engine.ts'; + +type RawHandle = { + query(sql: string, ...rest: unknown[]): Promise; + close(): Promise; +}; + +let engine: PGLiteEngine; + +beforeAll(async () => { + engine = new PGLiteEngine(); + await engine.connect({}); +}); + +afterAll(async () => { + // The test below already disconnects; a second disconnect is a no-op + // (db and lock are both null). Kept for the R4 no-leak contract. + await engine.disconnect(); +}); + +describe('PGLiteEngine.disconnect — pre-close WAL checkpoint (#3893)', () => { + test('CHECKPOINT runs on the live handle, and before close()', async () => { + const raw = (engine as unknown as { _db: RawHandle })._db; + expect(raw).toBeTruthy(); + + const events: string[] = []; + const origQuery = raw.query.bind(raw); + raw.query = ((sql: string, ...rest: unknown[]) => { + events.push(`query:${sql}`); + return origQuery(sql, ...rest); + }) as RawHandle['query']; + const origClose = raw.close.bind(raw); + raw.close = (() => { + events.push('close'); + return origClose(); + }) as RawHandle['close']; + + await engine.disconnect(); + + const checkpointIdx = events.findIndex(e => e === 'query:CHECKPOINT'); + const closeIdx = events.indexOf('close'); + expect(closeIdx).toBeGreaterThanOrEqual(0); + // Red pre-#3893: no CHECKPOINT was ever issued (checkpointIdx === -1). + expect(checkpointIdx).toBeGreaterThanOrEqual(0); + expect(closeIdx).toBeGreaterThan(checkpointIdx); + }, 30_000); +}); diff --git a/test/pglite-engine.test.ts b/test/pglite-engine.test.ts index 120e658d..66551412 100644 --- a/test/pglite-engine.test.ts +++ b/test/pglite-engine.test.ts @@ -1323,19 +1323,22 @@ describe('PGLiteEngine: Timeline dedup constraint (v6 migration)', () => { }); describe('PGLiteEngine: getBacklinkCounts', () => { + let aliceId: number; + let acmeId: number; + beforeEach(async () => { await truncateAll(); - await engine.putPage('people/alice', { ...testPage, type: 'person', title: 'Alice' }); + aliceId = (await engine.putPage('people/alice', { ...testPage, type: 'person', title: 'Alice' })).id; await engine.putPage('people/bob', { ...testPage, type: 'person', title: 'Bob' }); - await engine.putPage('companies/acme', { ...testPage, type: 'company', title: 'Acme' }); + acmeId = (await engine.putPage('companies/acme', { ...testPage, type: 'company', title: 'Acme' })).id; }); - test('returns Map for given slugs', async () => { + test('returns Map for given page ids', async () => { await engine.addLink('people/alice', 'companies/acme', '', 'works_at'); await engine.addLink('people/bob', 'companies/acme', '', 'invested_in'); - const counts = await engine.getBacklinkCounts(['companies/acme', 'people/alice']); - expect(counts.get('companies/acme')).toBe(2); - expect(counts.get('people/alice')).toBe(0); + const counts = await engine.getBacklinkCounts([acmeId, aliceId]); + expect(counts.get(acmeId)).toBe(2); + expect(counts.get(aliceId)).toBe(0); }); test('empty input -> empty Map', async () => { @@ -1343,9 +1346,9 @@ describe('PGLiteEngine: getBacklinkCounts', () => { expect(counts.size).toBe(0); }); - test('slugs with zero links: present in Map with 0', async () => { - const counts = await engine.getBacklinkCounts(['people/alice']); - expect(counts.get('people/alice')).toBe(0); + test('page ids with zero links: present in Map with 0', async () => { + const counts = await engine.getBacklinkCounts([aliceId]); + expect(counts.get(aliceId)).toBe(0); }); }); diff --git a/test/schema-bootstrap-coverage.test.ts b/test/schema-bootstrap-coverage.test.ts index 7ae41f20..6ad0b051 100644 --- a/test/schema-bootstrap-coverage.test.ts +++ b/test/schema-bootstrap-coverage.test.ts @@ -939,6 +939,14 @@ const COLUMN_EXEMPTIONS = new Set([ // statement shape, doctor's extract_health falls back to a 0-column // query). Column-only, no bootstrap probe needed. 'extract_rollup_7d.expected_limit_count', + // #4069 (migration v143) — verdict TTL column. Same precedent as the + // triage-v1 columns above: dream_verdicts is migration-created on PGLite + // (v30, absent from PGLITE_SCHEMA_SQL), so no schema-blob forward + // reference can exist, and dream_verdicts_expires_idx is created INSIDE + // the same v143 migration. The migration chain always runs before any + // reader, so getDreamVerdict's expiry predicate sees the column on old + // brains too. + 'dream_verdicts.expires_at', ]); test('every ALTER TABLE ADD COLUMN in MIGRATIONS is covered by applyForwardReferenceBootstrap (column-only class)', async () => { diff --git a/test/schema-lint-extends.test.ts b/test/schema-lint-extends.test.ts new file mode 100644 index 00000000..3ab5469a --- /dev/null +++ b/test/schema-lint-extends.test.ts @@ -0,0 +1,175 @@ +// #4373 — `gbrain schema lint ` and the MCP schema_lint op's +// named-pack branch must lint the MERGED manifest: page types inherited +// through `extends` count as declared, matching validate/use/active (which +// all consume loadActivePack → resolvePack → mergeInheritedManifest). +// Red pre-fix: both named-pack branches fed the raw unmerged manifest to +// runAllLintRules, so inherited types fired the false errors +// link_types_undeclared_page_type / frontmatter_links_undeclared_page_type. + +import { afterEach, beforeEach, describe, expect, it } from 'bun:test'; +import { spawnSync } from 'node:child_process'; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { operationsByName } from '../src/core/operations.ts'; +import type { OperationContext } from '../src/core/operations.ts'; +import { _resetPackCacheForTests } from '../src/core/schema-pack/registry.ts'; +import { withEnv } from './helpers/with-env.ts'; + +const REPO_ROOT = join(import.meta.dir, '..'); + +const PARENT_YAML = `api_version: gbrain-schema-pack-v1 +name: lint-parent +version: 1.0.0 +description: "" +gbrain_min_version: 0.38.0 +extends: null +borrow_from: [] +page_types: + - name: experience + primitive: temporal + path_prefixes: + - experiences/ + aliases: [] + extractable: false + expert_routing: false +link_types: [] +frontmatter_links: [] +takes_kinds: + - fact + - take + - bet + - hunch +enrichable_types: [] +filing_rules: [] +`; + +// Child declares NO page_types of its own; both references resolve only +// through the parent's 'experience' type. +const CHILD_YAML = `api_version: gbrain-schema-pack-v1 +name: lint-child +version: 1.0.0 +description: "" +gbrain_min_version: 0.38.0 +extends: lint-parent +borrow_from: [] +page_types: [] +link_types: + - name: had_experience + inference: + page_type: experience +frontmatter_links: + - page_type: experience + fields: [related] + link_type: had_experience +takes_kinds: + - fact + - take + - bet + - hunch +enrichable_types: [] +filing_rules: [] +`; + +// Control fixture: 'ghost' is declared NOWHERE in the chain, so the +// undeclared error must still fire on the merged manifest (fail-closed). +const CHILD_BAD_YAML = `api_version: gbrain-schema-pack-v1 +name: lint-child-bad +version: 1.0.0 +description: "" +gbrain_min_version: 0.38.0 +extends: lint-parent +borrow_from: [] +page_types: [] +link_types: + - name: haunted_by + inference: + page_type: ghost +frontmatter_links: [] +takes_kinds: + - fact + - take + - bet + - hunch +enrichable_types: [] +filing_rules: [] +`; + +let tmpHome: string; + +function seedPack(name: string, yaml: string): void { + const dir = join(tmpHome, '.gbrain', 'schema-packs', name); + mkdirSync(dir, { recursive: true }); + writeFileSync(join(dir, 'pack.yaml'), yaml, 'utf-8'); +} + +beforeEach(() => { + _resetPackCacheForTests(); + tmpHome = mkdtempSync(join(tmpdir(), 'gbrain-lint-extends-')); + seedPack('lint-parent', PARENT_YAML); + seedPack('lint-child', CHILD_YAML); +}); + +afterEach(() => { + _resetPackCacheForTests(); + try { rmSync(tmpHome, { recursive: true, force: true }); } catch { /* swallow */ } +}); + +function ctxOf(): OperationContext { + // schema_lint's named-pack branch never touches the engine (file-plane + // rules only), so a stub context keeps this hermetic and PGLite-free. + return { + engine: null, + config: {}, + logger: { info: () => {}, warn: () => {}, error: () => {} }, + dryRun: false, + remote: true, + } as unknown as OperationContext; +} + +type LintReport = { ok: boolean; errors: Array<{ rule: string }> }; + +describe('schema_lint op — named pack with extends (#4373)', () => { + it('treats extends-inherited page types as declared', async () => { + await withEnv({ GBRAIN_HOME: tmpHome }, async () => { + const result = await operationsByName.schema_lint!.handler(ctxOf(), { pack: 'lint-child' }) as LintReport; + const rules = (result.errors ?? []).map((e) => e.rule); + expect(rules).not.toContain('link_types_undeclared_page_type'); + expect(rules).not.toContain('frontmatter_links_undeclared_page_type'); + expect(result.ok).toBe(true); + }); + }); + + it('still fires undeclared errors for types missing from the whole chain', async () => { + await withEnv({ GBRAIN_HOME: tmpHome }, async () => { + seedPack('lint-child-bad', CHILD_BAD_YAML); + const result = await operationsByName.schema_lint!.handler(ctxOf(), { pack: 'lint-child-bad' }) as LintReport; + const rules = (result.errors ?? []).map((e) => e.rule); + expect(rules).toContain('link_types_undeclared_page_type'); + expect(result.ok).toBe(false); + }); + }); +}); + +describe('gbrain schema lint CLI — extends (#4373)', () => { + it('lints the merged manifest: exit 0, no inherited-type errors', () => { + // bun's spawnSync does NOT inherit process.env mutations, so pass env + // explicitly (same isolation pattern as test/schema-cli.test.ts). + const env = { + ...process.env, + GBRAIN_DATABASE_URL: '', + DATABASE_URL: '', + GBRAIN_HOME: tmpHome, + }; + const result = spawnSync('bun', ['run', 'src/cli.ts', 'schema', 'lint', 'lint-child', '--json'], { + cwd: REPO_ROOT, + encoding: 'utf-8', + env, + }); + const report = JSON.parse(result.stdout || '{}') as LintReport; + const rules = (report.errors ?? []).map((e) => e.rule); + expect(rules).not.toContain('link_types_undeclared_page_type'); + expect(rules).not.toContain('frontmatter_links_undeclared_page_type'); + expect(result.status).toBe(0); + }); +}); diff --git a/test/search.test.ts b/test/search.test.ts index 0dd7433d..da3fd613 100644 --- a/test/search.test.ts +++ b/test/search.test.ts @@ -212,41 +212,54 @@ describe('applyBacklinkBoost (v0.10.1)', () => { }); test('positive backlinks boost score by formula (1 + 0.05 * log(1 + count))', () => { - const results: SearchResult[] = [makeResult({ slug: 'popular', score: 1.0 })]; - applyBacklinkBoost(results, new Map([['popular', 10]])); + const results: SearchResult[] = [makeResult({ slug: 'popular', page_id: 1, score: 1.0 })]; + applyBacklinkBoost(results, new Map([[1, 10]])); // 1.0 * (1 + 0.05 * log(11)) ≈ 1.0 * 1.1199 const expected = 1.0 * (1 + 0.05 * Math.log(11)); expect(results[0].score).toBeCloseTo(expected, 4); }); test('higher count = larger boost (log scaling)', () => { - const a: SearchResult[] = [makeResult({ slug: 'a', score: 1.0 })]; - const b: SearchResult[] = [makeResult({ slug: 'b', score: 1.0 })]; - applyBacklinkBoost(a, new Map([['a', 1]])); - applyBacklinkBoost(b, new Map([['b', 100]])); + const a: SearchResult[] = [makeResult({ slug: 'a', page_id: 1, score: 1.0 })]; + const b: SearchResult[] = [makeResult({ slug: 'b', page_id: 2, score: 1.0 })]; + applyBacklinkBoost(a, new Map([[1, 1]])); + applyBacklinkBoost(b, new Map([[2, 100]])); expect(b[0].score).toBeGreaterThan(a[0].score); }); test('mutates results in place (no return value)', () => { - const results: SearchResult[] = [makeResult({ slug: 'x', score: 1.0 })]; - const ret = applyBacklinkBoost(results, new Map([['x', 5]])); + const results: SearchResult[] = [makeResult({ slug: 'x', page_id: 1, score: 1.0 })]; + const ret = applyBacklinkBoost(results, new Map([[1, 5]])); expect(ret).toBeUndefined(); expect(results[0].score).toBeGreaterThan(1.0); }); - test('slug not in counts map: no boost', () => { - const results: SearchResult[] = [makeResult({ slug: 'unknown', score: 0.5 })]; - applyBacklinkBoost(results, new Map([['other', 100]])); + test('page_id not in counts map: no boost', () => { + const results: SearchResult[] = [makeResult({ slug: 'unknown', page_id: 1, score: 0.5 })]; + applyBacklinkBoost(results, new Map([[999, 100]])); expect(results[0].score).toBe(0.5); }); + test('#4380: counts keyed by page_id — namesake slugs across sources do not share boosts', () => { + // Two sources each hold a page with the SAME slug; only page 11 has + // backlinks. The slug-keyed map used pre-#4380 stamped the summed + // factor onto BOTH results; page_id keying keeps them independent. + const linked = makeResult({ slug: 'tools/claude', page_id: 11, score: 1.0, source_id: 'a' }); + const unlinked = makeResult({ slug: 'tools/claude', page_id: 22, score: 1.0, source_id: 'b' }); + applyBacklinkBoost([linked, unlinked], new Map([[11, 4]])); + expect(linked.score).toBeGreaterThan(1.0); + expect(linked.backlink_boost).toBeGreaterThan(1.0); + expect(unlinked.score).toBe(1.0); + expect(unlinked.backlink_boost).toBeUndefined(); + }); + test('multiple results with mixed counts: each scored independently', () => { const results: SearchResult[] = [ - makeResult({ slug: 'a', score: 1.0 }), - makeResult({ slug: 'b', score: 1.0 }), - makeResult({ slug: 'c', score: 1.0 }), + makeResult({ slug: 'a', page_id: 1, score: 1.0 }), + makeResult({ slug: 'b', page_id: 2, score: 1.0 }), + makeResult({ slug: 'c', page_id: 3, score: 1.0 }), ]; - applyBacklinkBoost(results, new Map([['a', 0], ['b', 5], ['c', 50]])); + applyBacklinkBoost(results, new Map([[1, 0], [2, 5], [3, 50]])); expect(results[0].score).toBe(1.0); expect(results[1].score).toBeGreaterThan(1.0); expect(results[2].score).toBeGreaterThan(results[1].score); @@ -335,10 +348,10 @@ describe('computeFloorThreshold', () => { describe('applyBacklinkBoost — floor gate', () => { test('floorThreshold undefined preserves prior behavior bit-for-bit', () => { const results: SearchResult[] = [ - makeResult({ slug: 'top', score: 1.0 }), - makeResult({ slug: 'weak', score: 0.3 }), + makeResult({ slug: 'top', page_id: 1, score: 1.0 }), + makeResult({ slug: 'weak', page_id: 2, score: 0.3 }), ]; - applyBacklinkBoost(results, new Map([['top', 10], ['weak', 10]])); + applyBacklinkBoost(results, new Map([[1, 10], [2, 10]])); const factor = 1 + 0.05 * Math.log(11); expect(results[0].score).toBeCloseTo(1.0 * factor, 6); expect(results[1].score).toBeCloseTo(0.3 * factor, 6); @@ -346,10 +359,10 @@ describe('applyBacklinkBoost — floor gate', () => { test('weak result below threshold gets no boost', () => { const results: SearchResult[] = [ - makeResult({ slug: 'top', score: 1.0 }), - makeResult({ slug: 'weak', score: 0.3 }), + makeResult({ slug: 'top', page_id: 1, score: 1.0 }), + makeResult({ slug: 'weak', page_id: 2, score: 0.3 }), ]; - applyBacklinkBoost(results, new Map([['top', 10], ['weak', 10]]), 0.85); + applyBacklinkBoost(results, new Map([[1, 10], [2, 10]]), 0.85); const factor = 1 + 0.05 * Math.log(11); expect(results[0].score).toBeCloseTo(1.0 * factor, 6); expect(results[1].score).toBe(0.3); // gated out @@ -357,20 +370,20 @@ describe('applyBacklinkBoost — floor gate', () => { test('borderline result at exactly threshold is eligible', () => { const results: SearchResult[] = [ - makeResult({ slug: 'top', score: 1.0 }), - makeResult({ slug: 'edge', score: 0.85 }), + makeResult({ slug: 'top', page_id: 1, score: 1.0 }), + makeResult({ slug: 'edge', page_id: 2, score: 0.85 }), ]; - applyBacklinkBoost(results, new Map([['top', 10], ['edge', 10]]), 0.85); + applyBacklinkBoost(results, new Map([[1, 10], [2, 10]]), 0.85); const factor = 1 + 0.05 * Math.log(11); expect(results[1].score).toBeCloseTo(0.85 * factor, 6); }); test('regression scenario: 1000-backlink weak result cannot leapfrog strong primary', () => { const withGate: SearchResult[] = [ - makeResult({ slug: 'strong-primary', score: 1.0 }), - makeResult({ slug: 'weak-with-signal', score: 0.5 }), + makeResult({ slug: 'strong-primary', page_id: 1, score: 1.0 }), + makeResult({ slug: 'weak-with-signal', page_id: 2, score: 0.5 }), ]; - applyBacklinkBoost(withGate, new Map([['weak-with-signal', 1000]]), 0.85); + applyBacklinkBoost(withGate, new Map([[2, 1000]]), 0.85); withGate.sort((a, b) => b.score - a.score); expect(withGate[0].slug).toBe('strong-primary'); expect(withGate[1].slug).toBe('weak-with-signal'); @@ -382,10 +395,10 @@ describe('applyBacklinkBoost — floor gate', () => { // otherwise let NaN rows BYPASS the gate and receive boosts. NaN scores // are skipped entirely. const results: SearchResult[] = [ - makeResult({ slug: 'top', score: 1.0 }), - makeResult({ slug: 'nan', score: NaN }), + makeResult({ slug: 'top', page_id: 1, score: 1.0 }), + makeResult({ slug: 'nan', page_id: 2, score: NaN }), ]; - applyBacklinkBoost(results, new Map([['top', 10], ['nan', 10]]), 0.85); + applyBacklinkBoost(results, new Map([[1, 10], [2, 10]]), 0.85); expect(results[1].score).toBeNaN(); // unchanged }); @@ -470,7 +483,7 @@ describe('applyRecencyBoost — floor gate (T6 IRON RULE)', () => { describe('runPostFusionStages — single-baseline composition (D6/T2)', () => { // Build a minimal engine stub that returns predictable boost inputs. function makeStubEngine(opts: { - backlinks?: Map; + backlinks?: Map; salience?: Map; dates?: Map; }): { getBacklinkCounts: any; getSalienceScores: any; getEffectiveDates: any } { @@ -487,13 +500,13 @@ describe('runPostFusionStages — single-baseline composition (D6/T2)', () => { // gates both stages — a result eligible for backlink is also eligible // for salience (and vice versa), regardless of stage order. const engine = makeStubEngine({ - backlinks: new Map([['top', 100], ['weak', 100]]), + backlinks: new Map([[1, 100], [2, 100]]), salience: new Map([['default::top', 10], ['default::weak', 10]]), }); const resultsA: SearchResult[] = [ - makeResult({ slug: 'top', score: 1.0, source_id: undefined }), - makeResult({ slug: 'weak', score: 0.3, source_id: undefined }), + makeResult({ slug: 'top', page_id: 1, score: 1.0, source_id: undefined }), + makeResult({ slug: 'weak', page_id: 2, score: 0.3, source_id: undefined }), ]; const optsA: PostFusionOpts = { applyBacklinks: true, @@ -505,8 +518,8 @@ describe('runPostFusionStages — single-baseline composition (D6/T2)', () => { // Run again with only salience enabled — same threshold should apply. const resultsB: SearchResult[] = [ - makeResult({ slug: 'top', score: 1.0, source_id: undefined }), - makeResult({ slug: 'weak', score: 0.3, source_id: undefined }), + makeResult({ slug: 'top', page_id: 1, score: 1.0, source_id: undefined }), + makeResult({ slug: 'weak', page_id: 2, score: 0.3, source_id: undefined }), ]; const optsB: PostFusionOpts = { applyBacklinks: false, @@ -525,11 +538,11 @@ describe('runPostFusionStages — single-baseline composition (D6/T2)', () => { test('floorRatio undefined: bit-for-bit prior behavior (no gate, weak gets boosted)', async () => { const engine = makeStubEngine({ - backlinks: new Map([['weak', 1000]]), + backlinks: new Map([[2, 1000]]), }); const results: SearchResult[] = [ - makeResult({ slug: 'top', score: 1.0, source_id: undefined }), - makeResult({ slug: 'weak', score: 0.3, source_id: undefined }), + makeResult({ slug: 'top', page_id: 1, score: 1.0, source_id: undefined }), + makeResult({ slug: 'weak', page_id: 2, score: 0.3, source_id: undefined }), ]; const opts: PostFusionOpts = { applyBacklinks: true, diff --git a/test/search/attribution-stamping.test.ts b/test/search/attribution-stamping.test.ts index b28dc82e..1ecae048 100644 --- a/test/search/attribution-stamping.test.ts +++ b/test/search/attribution-stamping.test.ts @@ -47,7 +47,7 @@ function r(slug: string, score: number, page_id = 1): SearchResult { describe('applyBacklinkBoost — attribution', () => { test('count > 0 → backlink_boost stamped with the actual factor', () => { const results = [r('a/b', 1.0, 1)]; - const counts = new Map([['a/b', 10]]); + const counts = new Map([[1, 10]]); applyBacklinkBoost(results, counts); expect(results[0].backlink_boost).toBeGreaterThan(1.0); expect(results[0].backlink_boost).toBeLessThan(2.0); @@ -57,14 +57,14 @@ describe('applyBacklinkBoost — attribution', () => { test('count = 0 → no stamp', () => { const results = [r('a/b', 1.0, 1)]; - applyBacklinkBoost(results, new Map([['a/b', 0]])); + applyBacklinkBoost(results, new Map([[1, 0]])); expect(results[0].backlink_boost).toBeUndefined(); expect(results[0].score).toBe(1.0); }); test('below floor → no stamp', () => { const results = [r('weak', 0.1, 1)]; - applyBacklinkBoost(results, new Map([['weak', 10]]), 0.5); + applyBacklinkBoost(results, new Map([[1, 10]]), 0.5); expect(results[0].backlink_boost).toBeUndefined(); expect(results[0].score).toBe(0.1); }); @@ -157,7 +157,7 @@ describe('runPostFusionStages — base_score stamp', () => { test('base_score captures pre-boost score even when boosts run', async () => { const results = [r('a/b', 10.0, 1)]; const fakeEngine = { - getBacklinkCounts: async () => new Map([['a/b', 5]]), + getBacklinkCounts: async () => new Map([[1, 5]]), } as any; await runPostFusionStages(fakeEngine, results, { applyBacklinks: true, diff --git a/test/serve-http-metrics.test.ts b/test/serve-http-metrics.test.ts new file mode 100644 index 00000000..e34529b6 --- /dev/null +++ b/test/serve-http-metrics.test.ts @@ -0,0 +1,160 @@ +/** + * /metrics surface for `gbrain serve --http` (#3893, reimplemented from + * @y2688's PR). + * + * Two properties the original community PR got wrong are pinned here: + * + * 1. The tracking middleware must be registered BEFORE every route — + * Express only applies `app.use` middleware to routes registered after + * it, and the PR mounted the tracker after most routes, so they were + * never counted (structural test below). + * 2. GET /metrics must sit behind requireAdmin — request/error/latency + * series profile a personal brain's usage, so the exposition is not a + * public surface (the PR served it unauthenticated). + * + * The helpers are exercised against a bare Express app wired in the SAME + * order as serve-http.ts (precedent: the mountOAuthCorsGate tests in + * test/serve-http-cors.test.ts). + */ +import { describe, expect, test } from 'bun:test'; +import express from 'express'; +import type { Server } from 'http'; +import { readFileSync } from 'node:fs'; +import { + createMetricsCounters, + metricsTrackingMiddleware, + recordCompletedRequest, + renderPrometheusMetrics, + type MetricsCounters, +} from '../src/commands/serve-http-metrics.ts'; + +describe('recordCompletedRequest', () => { + test('classifies status >= 400 as errors and records latency samples', () => { + const c = createMetricsCounters(1_000); + recordCompletedRequest(c, 200, 12); + recordCompletedRequest(c, 404, 5); + recordCompletedRequest(c, 500, 30); + expect(c.errors).toBe(2); + expect(c.latencySamples).toEqual([12, 5, 30]); + }); + + test('caps the latency buffer, keeping the newest samples (memory bound)', () => { + const c = createMetricsCounters(); + for (let i = 0; i <= 10_000; i++) recordCompletedRequest(c, 200, i); + expect(c.latencySamples.length).toBe(5_000); + expect(c.latencySamples[c.latencySamples.length - 1]).toBe(10_000); + expect(c.latencySamples[0]).toBe(5_001); + }); +}); + +describe('renderPrometheusMetrics', () => { + test('renders counters, ratio, percentiles, and uptime in exposition format', () => { + const c = createMetricsCounters(0); + c.requests = 10; + c.errors = 2; + c.latencySamples = Array.from({ length: 100 }, (_, i) => i + 1); // 1..100 + const text = renderPrometheusMetrics(c, 5_000); + expect(text).toContain('# TYPE gbrain_requests_total counter'); + expect(text).toContain('gbrain_requests_total 10'); + expect(text).toContain('gbrain_errors_total 2'); + expect(text).toContain('gbrain_error_ratio 0.2000'); + expect(text).toContain('gbrain_latency_ms_p50 51'); + expect(text).toContain('gbrain_latency_ms_p99 100'); + expect(text).toContain('gbrain_uptime_seconds 5.0'); + }); + + test('zero-state renders without dividing by zero', () => { + const c = createMetricsCounters(0); + const text = renderPrometheusMetrics(c, 0); + expect(text).toContain('gbrain_requests_total 0'); + expect(text).toContain('gbrain_error_ratio 0'); + expect(text).toContain('gbrain_latency_ms_p50 0'); + expect(text).toContain('gbrain_latency_ms_p99 0'); + }); +}); + +describe('metricsTrackingMiddleware — Express wiring (serve-http.ts order)', () => { + function buildApp(counters: MetricsCounters, opts: { authed: boolean }): express.Express { + const app = express(); + // Mirrors serve-http.ts: tracker first, then routes. + app.use(metricsTrackingMiddleware(counters)); + const adminGate = (_req: express.Request, res: express.Response, next: express.NextFunction) => { + if (opts.authed) { next(); return; } + res.status(401).json({ error: 'Admin authentication required' }); + }; + app.get('/metrics', adminGate, (_req, res) => { + res.set('Content-Type', 'text/plain; version=0.0.4'); + res.send(renderPrometheusMetrics(counters)); + }); + app.get('/ok', (_req, res) => res.json({ ok: true })); + app.get('/boom', (_req, res) => res.status(500).json({ boom: true })); + return app; + } + + async function withServer( + app: express.Express, + fn: (base: string) => Promise, + ): Promise { + const server: Server = app.listen(0); + await new Promise(resolve => server.once('listening', () => resolve())); + const addr = server.address(); + const port = typeof addr === 'object' && addr ? addr.port : 0; + try { + return await fn(`http://127.0.0.1:${port}`); + } finally { + await new Promise(resolve => server.close(() => resolve())); + } + } + + test('counts requests on routes registered after it; 5xx lands as an error', async () => { + const counters = createMetricsCounters(); + await withServer(buildApp(counters, { authed: true }), async base => { + await fetch(`${base}/ok`); + await fetch(`${base}/boom`); + expect(counters.requests).toBe(2); + expect(counters.errors).toBe(1); + expect(counters.latencySamples.length).toBe(2); + }); + }); + + test('/metrics scrapes are excluded from the counters they report', async () => { + const counters = createMetricsCounters(); + await withServer(buildApp(counters, { authed: true }), async base => { + const res = await fetch(`${base}/metrics`); + expect(res.status).toBe(200); + expect(await res.text()).toContain('gbrain_requests_total 0'); + expect(counters.requests).toBe(0); + }); + }); + + test('an unauthenticated scrape gets 401, not the exposition', async () => { + const counters = createMetricsCounters(); + await withServer(buildApp(counters, { authed: false }), async base => { + const res = await fetch(`${base}/metrics`); + expect(res.status).toBe(401); + expect(await res.text()).not.toContain('gbrain_requests_total'); + }); + }); +}); + +describe('serve-http.ts wiring (structural — the two defects of the original PR)', () => { + // test-reads-source-ok: mount ORDER (middleware before first route) and the requireAdmin + // gate are wiring properties of the real serve-http.ts; the behavioral tests above run a + // rebuilt harness app, so only a source scan pins the real module without booting it. + const src = readFileSync(new URL('../src/commands/serve-http.ts', import.meta.url), 'utf-8'); + + test('tracking middleware is mounted before the first route registration', () => { + const mw = src.indexOf('metricsTrackingMiddleware('); + const firstTokenRoute = src.indexOf("app.post('/token'"); + const authRouterMount = src.indexOf('app.use(authRouter)'); + expect(mw).toBeGreaterThan(-1); + expect(firstTokenRoute).toBeGreaterThan(-1); + expect(authRouterMount).toBeGreaterThan(-1); + expect(mw).toBeLessThan(firstTokenRoute); + expect(mw).toBeLessThan(authRouterMount); + }); + + test('GET /metrics is gated behind requireAdmin', () => { + expect(src).toMatch(/app\.get\(\s*'\/metrics',\s*requireAdmin/); + }); +}); diff --git a/test/source-boundary-mutation-errors.test.ts b/test/source-boundary-mutation-errors.test.ts new file mode 100644 index 00000000..eb098c20 --- /dev/null +++ b/test/source-boundary-mutation-errors.test.ts @@ -0,0 +1,358 @@ +/** + * #4109 — same-source graph mutation diagnostics at the source boundary. + * + * `get_page` reads may span the caller's federated grant, but `add_link` / + * `add_timeline_entry` intentionally write only to the caller's scalar write + * source. Pre-fix, targeting a page the caller can READ from another granted + * source hit the engine's exact-source existence check, whose generic Error + * surfaced over MCP as `internal_error` — intentional source isolation looked + * like data loss. + * + * Pinned behavior: + * - a visible foreign endpoint → `permission_denied` naming the readable + * source and the client's write source (per endpoint: from / to / page); + * - a page outside the read grant → `page_not_found` that never names the + * foreign source (same anti-enumeration posture as get_page); + * - a soft-deleted foreign page is indistinguishable from absence; + * - soft-deleted pages IN the write source keep the existing engine + * mutation contract (graph rows may reference them); + * - same-source mutations are unchanged; + * - the engines report the missing endpoint individually (from vs to) in + * lockstep parity, so dispatch can classify mutation-time misses. + * + * Runs end to end through `dispatchToolCall` (the path both MCP transports + * share) against a real PGLiteEngine, per mcp-dispatch-optional-params.test.ts. + */ + +import { describe, test, expect, beforeAll, afterAll } from 'bun:test'; +import { PGLiteEngine } from '../src/core/pglite-engine.ts'; +import type { BrainEngine } from '../src/core/engine.ts'; +import { PageMissingError } from '../src/core/engine-errors.ts'; +import { dispatchToolCall } from '../src/mcp/dispatch.ts'; +import { runSources } from '../src/commands/sources.ts'; +import type { AuthInfo } from '../src/core/operations.ts'; + +let engine: PGLiteEngine; + +// Source ids chosen so the foreign one ('privsrc') shares no substring with +// the 'internal_error' envelope code — the no-disclosure assertions below +// check the raw payload text. +const WRITE_SRC = 'shared'; +const FOREIGN_SRC = 'privsrc'; + +const FROM_SLUG = 'topics/sbme-from'; +const TO_SHARED = 'topics/sbme-to-shared'; +const TO_FOREIGN = 'topics/sbme-to-foreign'; +const TL_FOREIGN = 'topics/sbme-tl-foreign'; +const DELETED_FOREIGN = 'topics/sbme-deleted-foreign'; +const SD_FROM = 'topics/sbme-sd-from'; +const SD_TO = 'topics/sbme-sd-to'; + +function auth(allowedSources: string[]): AuthInfo { + return { token: 'test-token', clientId: 'test-client', scopes: [], allowedSources }; +} + +// Grant spans both sources (can READ the foreign page) vs write source only. +const GRANTED = { remote: true, sourceId: WRITE_SRC, auth: auth([WRITE_SRC, FOREIGN_SRC]) }; +const UNGRANTED = { remote: true, sourceId: WRITE_SRC, auth: auth([WRITE_SRC]) }; + +function payload(result: { content: Array<{ type: string; text: string }> }) { + return JSON.parse(result.content[0]!.text); +} + +async function seed(slug: string, sourceId: string): Promise { + await engine.putPage(slug, { + type: 'concept', + title: slug, + compiled_truth: 'source-boundary fixture', + }, { sourceId }); +} + +async function countLinks(from: string, to: string): Promise { + const rows = await engine.executeRaw<{ count: number }>( + `SELECT COUNT(*)::int AS count + FROM links l + JOIN pages f ON f.id = l.from_page_id + JOIN pages t ON t.id = l.to_page_id + WHERE f.slug = $1 AND t.slug = $2`, + [from, to], + ); + return rows[0].count; +} + +beforeAll(async () => { + engine = new PGLiteEngine(); + await engine.connect({}); + await engine.initSchema(); + await runSources(engine, ['add', WRITE_SRC, '--no-federated']); + await runSources(engine, ['add', FOREIGN_SRC, '--no-federated']); + await seed(FROM_SLUG, WRITE_SRC); + await seed(TO_SHARED, WRITE_SRC); + await seed(TO_FOREIGN, FOREIGN_SRC); + await seed(TL_FOREIGN, FOREIGN_SRC); + await seed(DELETED_FOREIGN, FOREIGN_SRC); + await engine.softDeletePage(DELETED_FOREIGN, { sourceId: FOREIGN_SRC }); + await seed(SD_FROM, WRITE_SRC); + await seed(SD_TO, WRITE_SRC); + await engine.softDeletePage(SD_FROM, { sourceId: WRITE_SRC }); + await engine.softDeletePage(SD_TO, { sourceId: WRITE_SRC }); +}, 120_000); // full PGLite schema init can exceed the default hook timeout under suite load + +afterAll(async () => { + await engine.disconnect(); +}, 30_000); + +describe('add_link source-boundary diagnostics (#4109)', () => { + test('a visible foreign `to` endpoint is permission_denied naming the boundary', async () => { + const result = await dispatchToolCall(engine, 'add_link', { + from: FROM_SLUG, + to: TO_FOREIGN, + link_type: 'documents', + }, GRANTED); + + expect(result.isError).toBe(true); + expect(payload(result)).toMatchObject({ + error: 'permission_denied', + message: `add_link to page "${TO_FOREIGN}" is readable from source "${FOREIGN_SRC}" but this client writes to source "${WRITE_SRC}".`, + }); + expect(await countLinks(FROM_SLUG, TO_FOREIGN)).toBe(0); + }); + + test('a visible foreign `from` endpoint is identified as `from`', async () => { + const result = await dispatchToolCall(engine, 'add_link', { + from: TO_FOREIGN, + to: TO_SHARED, + link_type: 'documents', + }, GRANTED); + + expect(result.isError).toBe(true); + expect(payload(result).error).toBe('permission_denied'); + expect(payload(result).message).toContain(`add_link from page "${TO_FOREIGN}"`); + expect(await countLinks(TO_FOREIGN, TO_SHARED)).toBe(0); + }); + + test('a foreign page outside the read grant stays page_not_found without disclosure', async () => { + const result = await dispatchToolCall(engine, 'add_link', { + from: FROM_SLUG, + to: TO_FOREIGN, + link_type: 'documents', + }, UNGRANTED); + + expect(result.isError).toBe(true); + expect(payload(result)).toMatchObject({ + error: 'page_not_found', + message: `add_link to page "${TO_FOREIGN}" was not found in writable source "${WRITE_SRC}".`, + }); + expect(result.content[0]!.text).not.toContain(FOREIGN_SRC); + }); + + test('a soft-deleted foreign page is indistinguishable from absence', async () => { + const result = await dispatchToolCall(engine, 'add_link', { + from: FROM_SLUG, + to: DELETED_FOREIGN, + link_type: 'documents', + }, GRANTED); + + expect(result.isError).toBe(true); + expect(payload(result)).toMatchObject({ error: 'page_not_found' }); + expect(result.content[0]!.text).not.toContain(FOREIGN_SRC); + }); + + test('soft-deleted pages in the write source preserve the engine mutation contract', async () => { + const result = await dispatchToolCall(engine, 'add_link', { + from: SD_FROM, + to: SD_TO, + link_type: 'documents', + }, GRANTED); + + expect(result.isError).toBeUndefined(); + expect(await countLinks(SD_FROM, SD_TO)).toBe(1); + }); + + test('same-source add_link still reaches the engine', async () => { + const result = await dispatchToolCall(engine, 'add_link', { + from: FROM_SLUG, + to: TO_SHARED, + link_type: 'documents', + }, GRANTED); + + expect(result.isError).toBeUndefined(); + expect(await countLinks(FROM_SLUG, TO_SHARED)).toBe(1); + }); +}); + +describe('add_timeline_entry source-boundary diagnostics (#4109)', () => { + const ENTRY = { date: '2026-08-14', summary: 'Reviewed next steps.' }; + + test('a visible foreign page is permission_denied naming the boundary', async () => { + const result = await dispatchToolCall(engine, 'add_timeline_entry', { + slug: TL_FOREIGN, + ...ENTRY, + }, GRANTED); + + expect(result.isError).toBe(true); + expect(payload(result)).toMatchObject({ + error: 'permission_denied', + message: `add_timeline_entry page "${TL_FOREIGN}" is readable from source "${FOREIGN_SRC}" but this client writes to source "${WRITE_SRC}".`, + }); + const entries = await engine.getTimeline(TL_FOREIGN, { sourceId: FOREIGN_SRC }); + expect(entries.length).toBe(0); + }); + + test('a foreign page outside the read grant stays page_not_found without disclosure', async () => { + const result = await dispatchToolCall(engine, 'add_timeline_entry', { + slug: TL_FOREIGN, + ...ENTRY, + }, UNGRANTED); + + expect(result.isError).toBe(true); + expect(payload(result)).toMatchObject({ + error: 'page_not_found', + message: `add_timeline_entry page "${TL_FOREIGN}" was not found in writable source "${WRITE_SRC}".`, + }); + expect(result.content[0]!.text).not.toContain(FOREIGN_SRC); + }); + + test('same-source add_timeline_entry still reaches the engine', async () => { + const result = await dispatchToolCall(engine, 'add_timeline_entry', { + slug: FROM_SLUG, + ...ENTRY, + }, GRANTED); + + expect(result.isError).toBeUndefined(); + expect(payload(result)).toMatchObject({ status: 'ok' }); + const entries = await engine.getTimeline(FROM_SLUG, { sourceId: WRITE_SRC }); + expect(entries.length).toBe(1); + }); +}); + +describe('engine per-endpoint miss messages (lockstep parity contract)', () => { + test('addLink identifies a missing `to` endpoint', async () => { + await expect( + engine.addLink(FROM_SLUG, 'topics/sbme-missing', '', 'documents', 'manual', undefined, undefined, + { fromSourceId: WRITE_SRC, toSourceId: WRITE_SRC, originSourceId: WRITE_SRC }), + ).rejects.toThrow( + `addLink failed: to page "topics/sbme-missing" (source=${WRITE_SRC}) not found`, + ); + }); + + test('addLink identifies a missing `from` endpoint', async () => { + await expect( + engine.addLink('topics/sbme-missing', TO_SHARED, '', 'documents', 'manual', undefined, undefined, + { fromSourceId: WRITE_SRC, toSourceId: WRITE_SRC, originSourceId: WRITE_SRC }), + ).rejects.toThrow( + `addLink failed: from page "topics/sbme-missing" (source=${WRITE_SRC}) not found`, + ); + }); + + test('the miss is typed, not a message-prefix contract', async () => { + // The ops layer reclassifies by instanceof; a reworded message must not + // silently disable the reclassification (the #4109 string-matching trap). + try { + await engine.addTimelineEntry('topics/sbme-missing', { + date: '2026-08-14', + summary: 'never lands', + }, { sourceId: WRITE_SRC }); + throw new Error('should have thrown'); + } catch (e) { + expect(e).toBeInstanceOf(PageMissingError); + expect((e as PageMissingError).endpoint).toBe('page'); + expect((e as PageMissingError).slug).toBe('topics/sbme-missing'); + expect((e as PageMissingError).sourceId).toBe(WRITE_SRC); + } + }); +}); + +describe('mutation-time deletion race reclassification (#4109)', () => { + // A hard delete can land between the ops-layer preflight and the engine + // mutation. The engine's typed miss must be reclassified into the same + // caller-facing envelope — deterministically faked here since a real race + // needs a second writer (covered against real Postgres by + // test/e2e/source-boundary-mutation-postgres.test.ts). + type StoredPage = { slug: string; source_id: string }; + + function fakeEngine(pages: StoredPage[], raceDeleteSlug: string) { + return { + async getPage(slug: string, opts: { sourceId?: string; sourceIds?: string[] } = {}) { + const sources = opts.sourceIds ?? (opts.sourceId ? [opts.sourceId] : []); + const page = pages.find( + (candidate) => candidate.slug === slug && sources.includes(candidate.source_id), + ); + return page ? ({ ...page } as never) : null; + }, + async addLink(from: string, to: string) { + const endpoint = raceDeleteSlug === from ? 'from' : 'to'; + pages.splice(pages.findIndex((page) => page.slug === raceDeleteSlug), 1); + throw new PageMissingError('addLink', endpoint, raceDeleteSlug, WRITE_SRC); + }, + async addTimelineEntry(slug: string) { + pages.splice(pages.findIndex((page) => page.slug === raceDeleteSlug), 1); + throw new PageMissingError('addTimelineEntry', 'page', slug, WRITE_SRC); + }, + // DB-only brain: no source local_path / repo_path, so the timeline + // write-through takes its handled:false path and the op falls through + // to the insert. + async executeRaw() { + return []; + }, + async getConfig() { + return null; + }, + } as unknown as BrainEngine; + } + + test('add_link reclassifies an endpoint hard-deleted after preflight', async () => { + const eng = fakeEngine( + [{ slug: 'topics/race-from', source_id: WRITE_SRC }, { slug: 'topics/race-to', source_id: WRITE_SRC }], + 'topics/race-to', + ); + const result = await dispatchToolCall(eng, 'add_link', { + from: 'topics/race-from', + to: 'topics/race-to', + }, UNGRANTED); + + expect(result.isError).toBe(true); + expect(payload(result)).toMatchObject({ + error: 'page_not_found', + message: `add_link to page "topics/race-to" was not found in writable source "${WRITE_SRC}".`, + }); + }); + + test('add_timeline_entry reclassifies a page hard-deleted after preflight', async () => { + const eng = fakeEngine([{ slug: 'topics/race-tl', source_id: WRITE_SRC }], 'topics/race-tl'); + const result = await dispatchToolCall(eng, 'add_timeline_entry', { + slug: 'topics/race-tl', + date: '2026-08-14', + summary: 'raced away', + }, UNGRANTED); + + expect(result.isError).toBe(true); + expect(payload(result)).toMatchObject({ + error: 'page_not_found', + message: `add_timeline_entry page "topics/race-tl" was not found in writable source "${WRITE_SRC}".`, + }); + }); + + test('a page restored between reclassification reads still misses deterministically', async () => { + // The engine miss fired, but by the time the reclassifier re-reads, the + // page is back (delete + restore race): never internal_error. + const eng = { + async getPage(slug: string) { + return { slug, source_id: WRITE_SRC } as never; + }, + async addLink() { + throw new PageMissingError('addLink', 'to', 'topics/race-restored', WRITE_SRC); + }, + } as unknown as BrainEngine; + const result = await dispatchToolCall(eng, 'add_link', { + from: 'topics/race-from', + to: 'topics/race-restored', + }, UNGRANTED); + + expect(result.isError).toBe(true); + expect(payload(result)).toMatchObject({ + error: 'page_not_found', + message: `add_link to page "topics/race-restored" was unavailable in writable source "${WRITE_SRC}" during the mutation.`, + }); + }); +}); diff --git a/test/source-id-tx-regression.test.ts b/test/source-id-tx-regression.test.ts index ed890e74..5e8d5396 100644 --- a/test/source-id-tx-regression.test.ts +++ b/test/source-id-tx-regression.test.ts @@ -218,21 +218,38 @@ describe('addLink rewrites the cross-product into a source-qualified JOIN', () = expect(rows[0].to_src).toBe('default'); }); - test('addLink fails fast when the source-qualified endpoint doesn\'t exist', async () => { + test('addLink identifies the missing source-qualified endpoint', async () => { // Pre-fix: cross-product would silently fall back to the wrong source - // pair and succeed. Post-fix: missing-source-row → no JOIN match → no row - // inserted → INTERSECT pre-check throws. - let err: Error | null = null; + // pair and succeed. Post-fix: missing-source-row → endpoint unresolved → + // typed per-endpoint miss (#4109) so operation dispatch can classify + // mutation-time races without parsing the old ambiguous "A or B" message. + let fromErr: Error | null = null; try { await engine.addLink( - FROM_SLUG, TO_SLUG, 'phantom edge', 'documents', 'markdown', undefined, undefined, - { fromSourceId: 'nonexistent-src', toSourceId: 'nonexistent-src' }, + FROM_SLUG, TO_SLUG, 'phantom from edge', 'documents', 'markdown', undefined, undefined, + { fromSourceId: 'nonexistent-src', toSourceId: 'default' }, ); } catch (e) { - err = e as Error; + fromErr = e as Error; } - expect(err).not.toBeNull(); - expect(err!.message).toMatch(/not found/); + expect(fromErr).not.toBeNull(); + expect(fromErr!.message).toBe( + `addLink failed: from page "${FROM_SLUG}" (source=nonexistent-src) not found`, + ); + + let toErr: Error | null = null; + try { + await engine.addLink( + FROM_SLUG, TO_SLUG, 'phantom to edge', 'documents', 'markdown', undefined, undefined, + { fromSourceId: 'default', toSourceId: 'nonexistent-src' }, + ); + } catch (e) { + toErr = e as Error; + } + expect(toErr).not.toBeNull(); + expect(toErr!.message).toBe( + `addLink failed: to page "${TO_SLUG}" (source=nonexistent-src) not found`, + ); }); }); diff --git a/test/source-scope-resolver.test.ts b/test/source-scope-resolver.test.ts index 9ee33d21..7eb3b30c 100644 --- a/test/source-scope-resolver.test.ts +++ b/test/source-scope-resolver.test.ts @@ -16,6 +16,9 @@ import { OperationError, type OperationContext, } from '../src/core/operations.ts'; +// #4011: lives in ops/context.ts only — operations.ts is a peel-target shell +// whose re-export surface is frozen (module-size ratchet). +import { routeCodeIntelScope } from '../src/core/ops/context.ts'; function ctxOf(overrides: Partial = {}): OperationContext { return { @@ -136,3 +139,74 @@ describe('resolveCodeIntelScope — single-source code traversal', () => { expect(() => resolveCodeIntelScope(ctx, '__all__')).toThrow(OperationError); }); }); + +describe('routeCodeIntelScope — federated code-source re-route (#3242 sibling)', () => { + /** Engine stub whose codeChunksExist probe answers true for the given sources. */ + function engineWithCodeIn(...sourcesWithCode: string[]) { + return { + executeRaw: async (_sql: string, params: unknown[] = []) => { + const sourceId = params[params.length - 1] as string | undefined; + return [{ e: sourceId !== undefined && sourcesWithCode.includes(sourceId) }]; + }, + } as any; + } + + test('unqualified query on a code-less seed source re-routes to the sole code-bearing federated source', async () => { + const ctx = ctxOf({ + remote: true, + sourceId: 'default', + engine: engineWithCodeIn('code-src'), + localFederatedSourceIds: ['default', 'code-src'], + }); + expect(await routeCodeIntelScope(ctx, undefined)).toEqual({ allSources: false, sourceId: 'code-src' }); + }); + + test('does NOT re-route when the collapsed source itself has code', async () => { + const ctx = ctxOf({ + remote: true, + sourceId: 'default', + engine: engineWithCodeIn('default', 'code-src'), + localFederatedSourceIds: ['default', 'code-src'], + }); + expect(await routeCodeIntelScope(ctx, undefined)).toEqual({ allSources: false, sourceId: 'default' }); + }); + + test('explicit source_id always wins — never re-routed even to a code-bearing source', async () => { + const ctx = ctxOf({ + remote: true, + sourceId: 'default', + engine: engineWithCodeIn('code-src'), + localFederatedSourceIds: ['default', 'code-src'], + }); + expect(await routeCodeIntelScope(ctx, 'default')).toEqual({ allSources: false, sourceId: 'default' }); + }); + + test('ambiguous (2+ federated sources with code) keeps the original scope', async () => { + const ctx = ctxOf({ + remote: true, + sourceId: 'default', + engine: engineWithCodeIn('code-a', 'code-b'), + localFederatedSourceIds: ['default', 'code-a', 'code-b'], + }); + expect(await routeCodeIntelScope(ctx, undefined)).toEqual({ allSources: false, sourceId: 'default' }); + }); + + test('no federated read set (granted token) never widens', async () => { + const ctx = ctxOf({ + remote: true, + sourceId: 'default', + engine: engineWithCodeIn('code-src'), + }); + expect(await routeCodeIntelScope(ctx, undefined)).toEqual({ allSources: false, sourceId: 'default' }); + }); + + test('probe failure fails closed to the original scope', async () => { + const ctx = ctxOf({ + remote: true, + sourceId: 'default', + engine: { executeRaw: async () => { throw new Error('db down'); } } as any, + localFederatedSourceIds: ['default', 'code-src'], + }); + expect(await routeCodeIntelScope(ctx, undefined)).toEqual({ allSources: false, sourceId: 'default' }); + }); +}); diff --git a/test/sync-break-lock-source.test.ts b/test/sync-break-lock-source.test.ts new file mode 100644 index 00000000..95712778 --- /dev/null +++ b/test/sync-break-lock-source.test.ts @@ -0,0 +1,114 @@ +/** + * #4412 — `gbrain sync --break-lock` / `--force-break-lock` must resolve the + * target source through the SAME tiers as the sync path (flag → GBRAIN_SOURCE + * env → dotfile → local_path → ...), not a bare `--source argv ?? 'default'` + * fallback. + * + * Pre-fix, a crashed env/dotfile-resolved sync (e.g. the serve-delegated sync + * holding gbrain-sync:workspace in sync-delegation-under-serve Pin 3/4) told + * the operator to re-run `gbrain sync --break-lock`; the break-lock branch + * then "successfully" broke the absent gbrain-sync:default while the real + * lock stayed dead-held through the 60s takeover grace, so the follow-up + * sync still refused with exit 1. + * + * Test isolation: canonical PGLite block (R3 + R4); env via withEnv (R1); + * no subprocesses. + */ +import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test'; +import { hostname } from 'os'; +import { PGLiteEngine } from '../src/core/pglite-engine.ts'; +import { resetPgliteState } from './helpers/reset-pglite.ts'; +import { withEnv } from './helpers/with-env.ts'; +import { runSync } from '../src/commands/sync.ts'; + +let engine: PGLiteEngine; + +beforeAll(async () => { + engine = new PGLiteEngine(); + await engine.connect({}); + await engine.initSchema(); +}); + +afterAll(async () => { + await engine.disconnect(); +}); + +beforeEach(async () => { + await resetPgliteState(engine); + // Also clear gbrain_cycle_locks since resetPgliteState focuses on user data + // and the lock table is per-test state we want fresh. + await engine.executeRaw('DELETE FROM gbrain_cycle_locks', []); +}); + +// Insert a gbrain-sync: lock row held by a dead pid, acquired NOW — +// inside the 60s takeover grace, the exact state a SIGKILLed sync leaves. +async function insertDeadHeldLock(sourceId: string): Promise { + await engine.executeRaw( + `INSERT INTO gbrain_cycle_locks (id, holder_pid, holder_host, acquired_at, ttl_expires_at, last_refreshed_at) + VALUES ($1, $2, $3, NOW(), NOW() + INTERVAL '30 minutes', NOW())`, + [`gbrain-sync:${sourceId}`, 999999, hostname()], + ); +} + +async function lockExists(sourceId: string): Promise { + const rows = await engine.executeRaw<{ id: string }>( + `SELECT id FROM gbrain_cycle_locks WHERE id = $1`, + [`gbrain-sync:${sourceId}`], + ); + return rows.length > 0; +} + +/** Run runSync(args) with process.exit + console.log captured. */ +async function runSyncCaptured(args: string[]): Promise<{ exitCode: number | undefined; out: string }> { + const logs: string[] = []; + const origLog = console.log; + const origExit = process.exit; + let exitCode: number | undefined; + console.log = (...a: unknown[]) => { logs.push(a.map(String).join(' ')); }; + (process.exit as unknown as (code?: number) => void) = ((code?: number) => { + exitCode = code ?? 0; + throw new Error('__exit__'); + }) as never; + try { + await runSync(engine, args); + } catch (e) { + if ((e as Error).message !== '__exit__') throw e; + } finally { + process.exit = origExit; + console.log = origLog; + } + return { exitCode, out: logs.join('\n') }; +} + +describe("#4412 — break-lock resolves source through sync's own tiers", () => { + test("GBRAIN_SOURCE-resolved: --force-break-lock breaks the env source's lock, not gbrain-sync:default", async () => { + await engine.executeRaw(`INSERT INTO sources (id, name) VALUES ('workspace', 'workspace')`); + await insertDeadHeldLock('workspace'); + + const { exitCode } = await withEnv({ GBRAIN_SOURCE: 'workspace' }, () => + runSyncCaptured(['--force-break-lock', '--yes']), + ); + + expect(exitCode).toBe(0); + // Pre-fix red: the branch targeted gbrain-sync:default (absent), printed + // the wedge hint, exited 0 — and the workspace row survived dead-held. + expect(await lockExists('workspace')).toBe(false); + }); + + test('explicit --source still wins over env and needs no registered source row', async () => { + await engine.executeRaw(`INSERT INTO sources (id, name) VALUES ('workspace', 'workspace')`); + await insertDeadHeldLock('workspace'); + // 'other' is deliberately NOT in sources: breaking a deleted source's + // leftover lock via explicit --source must keep working (no existence + // assertion on the flag path). + await insertDeadHeldLock('other'); + + const { exitCode } = await withEnv({ GBRAIN_SOURCE: 'workspace' }, () => + runSyncCaptured(['--force-break-lock', '--source', 'other', '--yes']), + ); + + expect(exitCode).toBe(0); + expect(await lockExists('other')).toBe(false); + expect(await lockExists('workspace')).toBe(true); + }); +}); diff --git a/test/think-max-output-tokens.test.ts b/test/think-max-output-tokens.test.ts index 36e66426..7ac9a11d 100644 --- a/test/think-max-output-tokens.test.ts +++ b/test/think-max-output-tokens.test.ts @@ -1,13 +1,17 @@ /** * Pins `maxOutputTokensFor` — the per-model output-token budget `runThink` * passes to `client.create`. Thinking-by-default Claude 5 models - * (`anthropic:claude-*-5`) and OpenAI reasoning models (gpt-5 family, - * o-series) spend a large share of the budget on internal reasoning before - * emitting an answer, so the 4000 default left `think` with empty/truncated - * text. They get 16000; everything else stays 4000. + * (`anthropic:claude-*-5`), OpenAI reasoning models (gpt-5 family, + * o-series), and the Anthropic Claude 4.x deep-tier family (gbrain#4375 — + * the default `deep` alias is anthropic:claude-opus-4-7, whose JSON envelope + * truncated at 4000) get 16000; everything else stays 4000. + * + * Also pins the gbrain#4375 truncation labeling: a max_tokens-cut envelope + * is 'output_truncated' / LLM_OUTPUT_TRUNCATED, never the generic not_json. */ -import { describe, test, expect } from 'bun:test'; -import { maxOutputTokensFor } from '../src/core/think/index.ts'; +import { afterAll, beforeAll, describe, test, expect } from 'bun:test'; +import { maxOutputTokensFor, runThink, type ThinkLLMClient } from '../src/core/think/index.ts'; +import { PGLiteEngine } from '../src/core/pglite-engine.ts'; describe('maxOutputTokensFor — thinking-default headroom', () => { test('Claude 5 family gets 16000', () => { @@ -29,11 +33,24 @@ describe('maxOutputTokensFor — thinking-default headroom', () => { expect(maxOutputTokensFor('openai/gpt-5.2')).toBe(16000); // slash form }); - test('non-Claude-5 and non-reasoning models keep 4000', () => { - expect(maxOutputTokensFor('anthropic:claude-opus-4-8')).toBe(4000); - expect(maxOutputTokensFor('anthropic:claude-haiku-4-5')).toBe(4000); - expect(maxOutputTokensFor('anthropic:claude-sonnet-4-6')).toBe(4000); + test('gbrain#4375 — Anthropic Claude 4.x family gets 16000 (deep-tier truncation headroom)', () => { + // The default deep tier (model-config.ts) is anthropic:claude-opus-4-7: + // at 4000 the synthesis JSON envelope truncated mid-stream and was + // mislabeled not_json. Anthropic-scoped only, so provider hard caps + // (DeepSeek 8192, gpt-4o) are unaffected. + expect(maxOutputTokensFor('anthropic:claude-opus-4-7')).toBe(16000); + expect(maxOutputTokensFor('anthropic:claude-opus-4-8')).toBe(16000); + expect(maxOutputTokensFor('anthropic:claude-haiku-4-5')).toBe(16000); + expect(maxOutputTokensFor('anthropic:claude-sonnet-4-6')).toBe(16000); + expect(maxOutputTokensFor('anthropic/claude-opus-4-7')).toBe(16000); // slash form + expect(maxOutputTokensFor('claude-opus-4-7')).toBe(16000); // bare spelling + expect(maxOutputTokensFor('openrouter:anthropic/claude-opus-4-7')).toBe(16000); + }); + + test('non-headroom models keep 4000', () => { + // 3.x-era Claude spellings never match the 4.x family regex. expect(maxOutputTokensFor('anthropic:claude-3-haiku')).toBe(4000); + expect(maxOutputTokensFor('anthropic:claude-3-5-sonnet')).toBe(4000); expect(maxOutputTokensFor('openai:gpt-4o')).toBe(4000); expect(maxOutputTokensFor('openai:gpt-4o-mini')).toBe(4000); expect(maxOutputTokensFor('openai:gpt-4.1')).toBe(4000); @@ -71,3 +88,67 @@ describe('maxOutputTokensFor — thinking-default headroom', () => { expect(maxOutputTokensFor('voyage:voyage-4')).toBe(4000); // chat-less recipe }); }); + +describe('runThink — max_tokens truncation labeling (gbrain#4375)', () => { + let engine: PGLiteEngine; + + beforeAll(async () => { + engine = new PGLiteEngine(); + await engine.connect({}); + await engine.initSchema(); + await engine.putPage('notes/quokka-payments', { + title: 'Quokka Payments', + type: 'note', + compiled_truth: 'The quokka payments migration finished in March with zero downtime.', + }); + }); + + afterAll(async () => { + await engine.disconnect(); + }); + + // Same stub-message shape as auto-think-phase.test.ts so contextual typing + // against the Anthropic Message union holds without casts. + function clientOf(text: string, stopReason: 'end_turn' | 'max_tokens'): ThinkLLMClient { + return { + create: async () => ({ + id: 'msg_stub', + type: 'message', + role: 'assistant', + model: 'anthropic:claude-opus-4-7', + stop_reason: stopReason, + stop_sequence: null, + usage: { input_tokens: 900, output_tokens: 4000, cache_creation_input_tokens: 0, cache_read_input_tokens: 0, server_tool_use: null, service_tier: null }, + content: [{ type: 'text', text }], + }), + }; + } + + test('stop_reason max_tokens + unparseable envelope → output_truncated, not the generic not_json', async () => { + const result = await runThink(engine, { + question: 'quokka payments migration status', + // A max_tokens cut ends the JSON envelope mid-string — unparseable. + client: clientOf('{"answer":"The quokka payments migration finished in Mar', 'max_tokens'), + withTrajectory: false, + }); + expect(result.warnings).toContain('LLM_OUTPUT_TRUNCATED'); + expect(result.synthesis_status).toBe('output_truncated'); + expect(result.warnings).not.toContain('LLM_OUTPUT_NOT_JSON'); + expect(result.synthesisOk).toBe(false); + // Extractive-fallback contract holds for truncation like any other + // compose failure: a non-empty gather still yields digest material. + expect(result.pagesGathered).toBeGreaterThanOrEqual(1); + expect(result.extractive).toBeDefined(); + }); + + test('non-JSON output WITHOUT truncation keeps the generic not_json labeling', async () => { + const result = await runThink(engine, { + question: 'quokka payments migration status', + client: clientOf('I cannot help with that request.', 'end_turn'), + withTrajectory: false, + }); + expect(result.synthesis_status).toBe('not_json'); + expect(result.warnings).toContain('LLM_OUTPUT_NOT_JSON'); + expect(result.warnings).not.toContain('LLM_OUTPUT_TRUNCATED'); + }); +}); diff --git a/test/timeline-write-through.test.ts b/test/timeline-write-through.test.ts index 38e3afaf..273eea4a 100644 --- a/test/timeline-write-through.test.ts +++ b/test/timeline-write-through.test.ts @@ -324,7 +324,7 @@ describe('wave-C review: splice-under-lock, never whole-file regeneration', () = // deletes the fence-owned fact rows. const fence = await writeFactsToFence( engine, - { sourceId: 'default', localPath: brainDir, slug }, + { sourceId: 'default', localPath: brainDir, slug, resolutionSource: 'exact_page' }, [fenceFact('Founded Widget-Co in 2017')], ); expect(fence.inserted).toBe(1); @@ -360,7 +360,7 @@ describe('wave-C review: splice-under-lock, never whole-file regeneration', () = const filePath = await seedPage(slug, body); await writeFactsToFence( engine, - { sourceId: 'default', localPath: brainDir, slug }, + { sourceId: 'default', localPath: brainDir, slug, resolutionSource: 'exact_page' }, [fenceFact('Fence row that must stay last')], ); @@ -390,7 +390,7 @@ describe('wave-C review: splice-under-lock, never whole-file regeneration', () = const [fenceRes, opRes] = await Promise.all([ writeFactsToFence( engine, - { sourceId: 'default', localPath: brainDir, slug }, + { sourceId: 'default', localPath: brainDir, slug, resolutionSource: 'exact_page' }, [fenceFact('Concurrent fence fact')], ), addTimelineEntryOp.handler(makeCtx(), { diff --git a/test/transcripts-nul.test.ts b/test/transcripts-nul.test.ts new file mode 100644 index 00000000..9b8345c8 --- /dev/null +++ b/test/transcripts-nul.test.ts @@ -0,0 +1,171 @@ +/** + * gbrain#4392 — an escaped \u0000 in transcript content must never abort the + * whole ingest run. Agent transcripts capture raw tool output (grep on a + * binary, truncated buffers), so NUL is legitimate input; Postgres text/jsonb + * simply cannot store U+0000 and rejects the write with + * 'invalid byte sequence for encoding "UTF8": 0x00'. Two guarantees pinned: + * 1. the redact/render boundary strips U+0000 from every persisted string, + * so a NUL-bearing session imports (with the NUL gone) instead of dying + * at the database boundary; + * 2. an encoding-shaped import error that still reaches the write is a + * per-SESSION error (counted, run continues) — never a run abort that + * starves every file queued behind the bad one. + */ +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test'; +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { PGLiteEngine } from '../src/core/pglite-engine.ts'; +import { resetPgliteState } from './helpers/reset-pglite.ts'; +import { runTranscriptsIngest } from '../src/core/transcripts/ingest.ts'; +import { buildTranscriptSlug } from '../src/core/transcripts/types.ts'; + +const NUL = String.fromCharCode(0); + +let engine: PGLiteEngine; +let tmp: string; + +beforeAll(async () => { + engine = new PGLiteEngine(); + await engine.connect({}); + await engine.initSchema(); +}); + +afterAll(async () => { + await engine.disconnect(); +}); + +beforeEach(async () => { + await resetPgliteState(engine); + tmp = mkdtempSync(join(tmpdir(), 'gb-nul-')); +}); + +afterEach(() => { + rmSync(tmp, { recursive: true, force: true }); +}); + +const NO_PATTERNS = { userPatternsPath: '/nonexistent-patterns.txt' }; + +/** Minimal codex-rollout JSONL: session_meta + one user turn + one reply. */ +function writeCodexSession( + name: string, + sessionId: string, + startIso: string, + userText: string, + cwd = '/tmp', +): string { + const lines = [ + JSON.stringify({ + timestamp: startIso, + type: 'session_meta', + payload: { id: name, session_id: sessionId, timestamp: startIso, cwd }, + }), + JSON.stringify({ + timestamp: startIso, + type: 'event_msg', + payload: { type: 'user_message', message: userText }, + }), + JSON.stringify({ + timestamp: startIso, + type: 'response_item', + payload: { + type: 'message', + role: 'assistant', + id: 'ri-1', + content: [{ type: 'output_text', text: 'acknowledged, noted the tool spew' }], + }, + }), + ]; + const p = join(tmp, `${name}.jsonl`); + writeFileSync(p, lines.join('\n') + '\n'); + return p; +} + +describe('transcripts ingest with U+0000 in content (#4392)', () => { + test('a NUL-bearing session imports with the NUL stripped and never aborts the run', async () => { + const badStart = '2026-08-10T08:00:00.000Z'; + const cleanStart = '2026-08-11T09:00:00.000Z'; + // JSON.stringify renders the NUL as the escaped \u0000 — exactly the + // 6-ASCII-char shape codex rollouts carry (raw 0x00 never hits the file). + // NUL rides BOTH persisted surfaces: message content (pages/chunks text + // columns) and session metadata (raw_data ::jsonb, which rejects the + // NUL escape with 'unsupported Unicode escape sequence'). + const bad = writeCodexSession( + 'bad-rollout', + 'nul-session-1', + badStart, + `before${NUL}after grep binary spew`, + `/tmp/work${NUL}dir`, + ); + const clean = writeCodexSession('clean-rollout', 'clean-session-1', cleanStart, 'a perfectly normal question'); + + // Red at base: throws 'transcripts-ingest run abort: putRawData failed + // for conversations/sessions/…: unsupported Unicode escape sequence'. + const r = await runTranscriptsIngest(engine, { + paths: [bad, clean], + format: 'codex', + sourceId: 'default', + ...NO_PATTERNS, + }); + + expect(r.sessionsImported).toBe(2); + expect(r.sessionsErrored).toBe(0); + expect(r.erroredFiles).toBe(0); + + const badSlug = buildTranscriptSlug('codex', badStart, { sessionId: 'nul-session-1' }); + const badPage = await engine.getPage(badSlug, { sourceId: 'default' }); + expect(badPage).not.toBeNull(); + expect(badPage!.compiled_truth).toContain('beforeafter grep binary spew'); + expect(badPage!.compiled_truth.includes(NUL)).toBe(false); + + const rawRows = await engine.getRawData(badSlug, 'transcript:codex', { sourceId: 'default' }); + expect(rawRows.length).toBe(1); + expect((rawRows[0].data as { cwd?: string }).cwd).toBe('/tmp/workdir'); + + const cleanSlug = buildTranscriptSlug('codex', cleanStart, { sessionId: 'clean-session-1' }); + expect(await engine.getPage(cleanSlug, { sourceId: 'default' })).not.toBeNull(); + }); + + test('an encoding-shaped write error is a per-session error, not a run abort', async () => { + const poison = writeCodexSession('poison-rollout', 'poison-session-1', '2026-08-10T08:00:00.000Z', 'first queued session'); + const healthy = writeCodexSession('healthy-rollout', 'healthy-session-1', '2026-08-11T09:00:00.000Z', 'second queued session'); + + // Simulate a NUL that slips past the strip on some other persisted + // surface: the FIRST page-write transaction (the poison session, files + // run in order) throws the exact Postgres encoding error; everything + // else delegates to the real engine. + let failedOnce = false; + const failingEngine = new Proxy(engine, { + get(t, k) { + if (k === 'transaction' && !failedOnce) { + return () => { + failedOnce = true; + throw new Error('invalid byte sequence for encoding "UTF8": 0x00'); + }; + } + const v = (t as unknown as Record)[k]; + return typeof v === 'function' && k !== 'constructor' + ? (v as (...a: unknown[]) => unknown).bind(t) + : v; + }, + }); + + // Red at base: the error escalates to RUN_ABORT_MARKER and this throws. + const r = await runTranscriptsIngest(failingEngine, { + paths: [poison, healthy], + format: 'codex', + sourceId: 'default', + ...NO_PATTERNS, + }); + + expect(r.sessionsErrored).toBe(1); + expect(r.files[0].sessions[0].error).toContain('invalid byte sequence'); + expect(r.cleanScan).toBe(false); + // The queue continued: the healthy session behind the poison one landed. + expect(r.sessionsImported).toBe(1); + const healthySlug = buildTranscriptSlug('codex', '2026-08-11T09:00:00.000Z', { + sessionId: 'healthy-session-1', + }); + expect(await engine.getPage(healthySlug, { sourceId: 'default' })).not.toBeNull(); + }); +}); diff --git a/test/upgrade.serial.test.ts b/test/upgrade.serial.test.ts index cea00413..eaf49b66 100644 --- a/test/upgrade.serial.test.ts +++ b/test/upgrade.serial.test.ts @@ -1,8 +1,11 @@ import { describe, test, expect } from 'bun:test'; -import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'fs'; +import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'fs'; import { dirname, join } from 'path'; import { tmpdir } from 'os'; +import * as upgradeModule from '../src/commands/upgrade.ts'; import { resolveBunGlobalRoot } from '../src/commands/upgrade.ts'; +import { formatMarker } from '../src/core/self-upgrade.ts'; +import { VERSION } from '../src/version.ts'; // We can't easily mock process.execPath in bun, so we test the upgrade // command's --help output and the detection logic via subprocess @@ -215,3 +218,142 @@ describe('post-upgrade behavior (post v0.12.0 merge)', () => { expect(stdout).toContain('Usage: gbrain post-upgrade'); }); }); + +describe('assessUpgradeOutcome (#4366)', () => { + test('mismatch when still running an older version than the target', () => { + expect(upgradeModule.assessUpgradeOutcome('0.46.25.0', '0.46.21.0')).toBe('mismatch'); + }); + + test('ok when the observed version reaches or passes the target', () => { + expect(upgradeModule.assessUpgradeOutcome('0.46.25.0', '0.46.25.0')).toBe('ok'); + expect(upgradeModule.assessUpgradeOutcome('0.46.25.0', '0.47.0.0')).toBe('ok'); + }); + + test('ok when no target is known (legacy callers keep current behavior)', () => { + expect(upgradeModule.assessUpgradeOutcome(undefined, '0.40.0.0')).toBe('ok'); + }); + + test('unverified when the observed version is missing or unparseable', () => { + expect(upgradeModule.assessUpgradeOutcome('0.46.25.0', '')).toBe('unverified'); + expect(upgradeModule.assessUpgradeOutcome('0.46.25.0', 'not-a-version')).toBe('unverified'); + }); + + test('accepts a v-prefixed target tag', () => { + expect(upgradeModule.assessUpgradeOutcome('v0.46.25.0', '0.46.21.0')).toBe('mismatch'); + }); +}); + +describe('runUpgrade target verification (#4366)', () => { + const TARGET = '99.99.99.0'; + const OLD = '0.40.0.0'; + const repoRoot = new URL('..', import.meta.url).pathname; + + /** + * Build a hermetic fake install under a temp HOME and run runUpgrade in a + * subprocess (Bun snapshots environ at birth, so PATH shims cannot be + * injected in-process): + * - a PATH-first `clawhub` shim exiting 0 without changing anything — + * the same successful-no-op shape as `bun update` on an exact-tag Git + * pin (the issue's install); + * - a PATH-first `gbrain` shim that keeps reporting `observedVersion`; + * - a pre-seeded upgrade-available marker so cache retention is observable. + */ + async function runUpgradeAgainstFakeInstall(opts: { + observedVersion: string; + targetVersion?: string; + }): Promise<{ home: string; exitCode: number; stderr: string }> { + const home = mkdtempSync(join(tmpdir(), 'gbrain-upgrade-target-')); + const bin = join(home, 'bin'); + mkdirSync(bin); + writeFileSync(join(bin, 'clawhub'), '#!/bin/sh\nexit 0\n'); + writeFileSync(join(bin, 'gbrain'), `#!/bin/sh\necho "gbrain ${opts.observedVersion}"\n`); + chmodSync(join(bin, 'clawhub'), 0o755); + chmodSync(join(bin, 'gbrain'), 0o755); + + mkdirSync(join(home, '.gbrain'), { recursive: true }); + writeFileSync( + join(home, '.gbrain', 'last-update-check'), + formatMarker({ kind: 'upgrade_available', current: OLD, latest: TARGET }) + '\n', + ); + + // The driver lives OUTSIDE the repo so detectInstallMethod() cannot see a + // node_modules/.git ancestor and falls through to the clawhub shim. + const driverPath = join(home, 'driver.ts'); + writeFileSync( + driverPath, + `import { runUpgrade } from '${repoRoot}src/commands/upgrade.ts';\n` + + `const t = process.env.TEST_TARGET_VERSION;\n` + + `await runUpgrade(['--swap-only'], t ? { targetVersion: t } : {});\n`, + ); + + const env: Record = { + ...process.env, + HOME: home, + GBRAIN_HOME: home, + PATH: `${bin}:${process.env.PATH}`, + }; + delete env.TEST_TARGET_VERSION; + if (opts.targetVersion) env.TEST_TARGET_VERSION = opts.targetVersion; + + const proc = Bun.spawn(['bun', 'run', driverPath], { + cwd: repoRoot, + env, + stdout: 'pipe', + stderr: 'pipe', + }); + const stderr = await new Response(proc.stderr).text(); + const exitCode = await proc.exited; + return { home, exitCode, stderr }; + } + + test('mismatch exits nonzero, keeps the pending-upgrade cache, and records verify-target', async () => { + const { home, exitCode, stderr } = await runUpgradeAgainstFakeInstall({ + observedVersion: OLD, + targetVersion: TARGET, + }); + try { + expect(exitCode).toBe(1); + // The upgrade-available marker must survive so future nags still fire. + expect(existsSync(join(home, '.gbrain', 'last-update-check'))).toBe(true); + // No false JUST_UPGRADED breadcrumb for an upgrade that never happened. + expect(existsSync(join(home, '.gbrain', 'just-upgraded-from'))).toBe(false); + // The operator gets the exact-tag reinstall remediation. + expect(stderr).toContain(`github:garrytan/gbrain#v${TARGET}`); + + const errPath = join(home, '.gbrain', 'upgrade-errors.jsonl'); + const records = existsSync(errPath) + ? readFileSync(errPath, 'utf-8').trim().split('\n').map((l) => JSON.parse(l)) + : []; + expect(records.some((r) => r.phase === 'verify-target')).toBe(true); + } finally { + rmSync(home, { recursive: true, force: true }); + } + }); + + test('reaching the target keeps the success path: cache cleared, breadcrumb written, exit 0', async () => { + const { home, exitCode } = await runUpgradeAgainstFakeInstall({ + observedVersion: TARGET, + targetVersion: TARGET, + }); + try { + expect(exitCode).toBe(0); + expect(existsSync(join(home, '.gbrain', 'last-update-check'))).toBe(false); + expect(readFileSync(join(home, '.gbrain', 'just-upgraded-from'), 'utf-8').trim()).toBe(VERSION); + } finally { + rmSync(home, { recursive: true, force: true }); + } + }); + + test('no target (legacy caller) preserves prior behavior even when the version is stale', async () => { + const { home, exitCode } = await runUpgradeAgainstFakeInstall({ + observedVersion: OLD, + }); + try { + expect(exitCode).toBe(0); + expect(existsSync(join(home, '.gbrain', 'last-update-check'))).toBe(false); + expect(existsSync(join(home, '.gbrain', 'just-upgraded-from'))).toBe(true); + } finally { + rmSync(home, { recursive: true, force: true }); + } + }); +}); diff --git a/test/write-through.test.ts b/test/write-through.test.ts index 28071d01..ee84d8be 100644 --- a/test/write-through.test.ts +++ b/test/write-through.test.ts @@ -14,9 +14,13 @@ import * as os from 'node:os'; import { PGLiteEngine } from '../src/core/pglite-engine.ts'; import { resetPgliteState } from './helpers/reset-pglite.ts'; import { resetGateway } from '../src/core/ai/gateway.ts'; -import { writePageThrough, isWriteThroughDisabled, _resetWriteThroughCacheForTest } from '../src/core/write-through.ts'; +import { + writePageThrough, deletePageThrough, resolvePageWriteTarget, + isWriteThroughDisabled, _resetWriteThroughCacheForTest, +} from '../src/core/write-through.ts'; import { importFromContent } from '../src/core/import-file.ts'; import { serializePageToMarkdown, resolvePageFilePath } from '../src/core/markdown.ts'; +import { operations, type OperationContext } from '../src/core/operations.ts'; let engine: PGLiteEngine; let tmpRoot: string; @@ -147,7 +151,7 @@ describe('writePageThrough', () => { expect(walkFiles(brainDir).sort()).toEqual([path.join(brainDir, authored)]); }); - test('[REGRESSION twin] null source_path still falls back to the slug-derived path', async () => { + test('[REGRESSION twin] null source_path falls back to the slug path and binds it immediately (#4247)', async () => { await engine.setConfig('sync.repo_path', brainDir); const slug = 'inbox/2026-01-01-abc123'; // Born via put/capture: no file of record, so source_path stays NULL. @@ -160,6 +164,14 @@ describe('writePageThrough', () => { expect(res.written).toBe(true); expect(res.path).toBe(resolvePageFilePath(brainDir, slug, 'default')); + // #4247: the just-materialized file IS the file of record — mtime-watermark + // incremental sync never rescans an untouched file, so without an immediate + // bind the row stays source_path=NULL forever. + const rows = await engine.executeRaw<{ source_path: string | null }>( + `SELECT source_path FROM pages WHERE source_id = 'default' AND slug = $1`, + [slug], + ); + expect(rows[0]?.source_path).toBe(`${slug}.md`); }); test('[REGRESSION twin] falls back to a contained file:// source_uri when source_path is null (capture --file of a vault file)', async () => { @@ -183,6 +195,12 @@ describe('writePageThrough', () => { expect(res.written).toBe(true); expect(res.path).toBe(path.join(brainDir, authored)); + // #4247: the contained file:// target is the file of record — bind it. + const rows = await engine.executeRaw<{ source_path: string | null }>( + `SELECT source_path FROM pages WHERE source_id = 'default' AND slug = $1`, + [slug], + ); + expect(rows[0]?.source_path).toBe(authored); // NB: no `existsSync(slug path)` assertion here — this slug differs from the // authored name only by CASE, so a case-insensitive FS (macOS/Windows) folds // the two and existsSync would report a twin that isn't there. walkFiles @@ -427,6 +445,58 @@ describe('writePageThrough', () => { expect(fs.existsSync(path.join(sourceRoot, sourcePath))).toBe(false); }); + test('[#4247] put-born page in a subdirectory-scoped local_path binds a Git-root-relative source_path', async () => { + const gitRoot = path.join(tmpRoot, 'monorepo'); + fs.mkdirSync(path.join(gitRoot, '.git'), { recursive: true }); + const sourceRoot = path.join(gitRoot, 'public', 'changelog'); + fs.mkdirSync(sourceRoot, { recursive: true }); + await engine.executeRaw( + `INSERT INTO sources (id, name, local_path, config) VALUES ('changelog', 'Changelog', $1, '{}'::jsonb)`, + [sourceRoot], + ); + const slug = 'posts/2026-08-24'; + // Born via put: no file of record, so the slug-derived path is minted + // under the source's own tree. + await importFromContent(engine, slug, `---\ntitle: Release\ntype: note\n---\n\n# Body\n`, { + noEmbed: true, + sourceId: 'changelog', + }); + + const res = await writePageThrough(engine, slug, { sourceId: 'changelog' }); + + expect(res.written).toBe(true); + expect(res.path).toBe(path.join(sourceRoot, 'posts', '2026-08-24.md')); + // Scoped syncs record source_path GIT-ROOT-relative (#774), and + // delete-reconcile keys on that exact form — a local_path-relative bind + // here would desync reconcile and sweep the page while its file exists. + const rows = await engine.executeRaw<{ source_path: string | null }>( + `SELECT source_path FROM pages WHERE source_id = 'changelog' AND slug = $1`, + [slug], + ); + expect(rows[0]?.source_path).toBe(`public/changelog/${slug}.md`); + }); + + test('[#4247] an existing scanner-recorded source_path is never rewritten by write-through', async () => { + await engine.setConfig('sync.repo_path', brainDir); + const slug = 'library/people/steve-jobs'; + const authored = 'Library/People/Steve Jobs.md'; + await importFromContent(engine, slug, `---\ntitle: Steve Jobs\ntype: person\n---\n\n# Body\n`, { + noEmbed: true, + sourceId: 'default', + sourcePath: authored, + }); + fs.mkdirSync(path.join(brainDir, 'Library', 'People'), { recursive: true }); + + const res = await writePageThrough(engine, slug, { sourceId: 'default' }); + + expect(res.written).toBe(true); + const rows = await engine.executeRaw<{ source_path: string | null }>( + `SELECT source_path FROM pages WHERE source_id = 'default' AND slug = $1`, + [slug], + ); + expect(rows[0]?.source_path).toBe(authored); + }); + test('[REGRESSION #2831] differently-cased entry occupying the target → skipped case_insensitive_collision, existing file untouched', async () => { await engine.setConfig('sync.repo_path', brainDir); const slug = 'wiki/ideas/note'; @@ -485,3 +555,171 @@ describe('writePageThrough', () => { expect(files.some((f) => f.includes('.tmp.'))).toBe(false); }); }); + +describe('deletePageThrough (#4022)', () => { + // The leak this closes: delete_page was DB-only, so the artifact outlived the + // page. On any brain committed on a timer (snapshot cron, hardened + // post-commit push) the orphan got committed AFTER deletion and the next + // `gbrain sync` resurrected the page. + test('removes the artifact written by writePageThrough (path parity)', async () => { + await engine.setConfig('sync.repo_path', brainDir); + const slug = 'concepts/delete-me'; + await seedPage(slug); + + const written = await writePageThrough(engine, slug, { sourceId: 'default' }); + expect(written.written).toBe(true); + expect(fs.existsSync(written.path!)).toBe(true); + + const removed = await deletePageThrough(engine, slug, { sourceId: 'default' }); + expect(removed.removed).toBe(true); + // Path parity is the whole point of the shared resolver: a delete that + // computed the path differently would miss the file (leaving the orphan) + // or unlink the wrong one. + expect(removed.path).toBe(written.path); + expect(fs.existsSync(written.path!)).toBe(false); + }); + + test('missing artifact is a clean no-op, not an error', async () => { + await engine.setConfig('sync.repo_path', brainDir); + const slug = 'concepts/db-only-page'; + await seedPage(slug); + + const res = await deletePageThrough(engine, slug, { sourceId: 'default' }); + expect(res.removed).toBe(false); + expect(res.skipped).toBe('file_not_present'); + expect(res.error).toBeUndefined(); + }); + + test('no repo configured → skipped, never throws', async () => { + // sync.repo_path deliberately unset (DB-only brain by design). + const slug = 'concepts/no-repo'; + await seedPage(slug); + + const res = await deletePageThrough(engine, slug, { sourceId: 'default' }); + expect(res.removed).toBe(false); + expect(res.skipped).toBe('no_repo_configured'); + }); + + test('sync.write_through=false → skipped disabled_by_config, file untouched', async () => { + await engine.setConfig('sync.repo_path', brainDir); + const slug = 'concepts/opted-out'; + await seedPage(slug); + const written = await writePageThrough(engine, slug, { sourceId: 'default' }); + expect(written.written).toBe(true); + + // The operator opted the brain out of the disk sink — the delete plane + // must not start unlinking files gbrain no longer owns. + await engine.setConfig('sync.write_through', 'false'); + _resetWriteThroughCacheForTest(); + + const res = await deletePageThrough(engine, slug, { sourceId: 'default' }); + expect(res).toEqual({ removed: false, skipped: 'disabled_by_config' }); + expect(fs.existsSync(written.path!)).toBe(true); + }); + + test('a pre-stamp target keeps the recorded source_path reachable after soft-delete', async () => { + await engine.setConfig('sync.repo_path', brainDir); + const slug = 'library/people/ada-lovelace'; + const authored = 'Library/People/Ada Lovelace.md'; + await importFromContent(engine, slug, `---\ntitle: Ada Lovelace\ntype: person\n---\n\n# Body\n`, { + noEmbed: true, + sourceId: 'default', + sourcePath: authored, + }); + const written = await writePageThrough(engine, slug, { sourceId: 'default' }); + expect(written.path).toBe(path.join(brainDir, authored)); + + // resolvePageWriteTarget reads source_path from ACTIVE rows only, so the + // delete plane resolves the target BEFORE softDeletePage stamps + // deleted_at; a post-stamp resolution would fall back to the slug-derived + // twin, report a clean file_not_present no-op, and leave the REAL + // artifact on disk for the next timer-based commit to resurrect. + const target = await resolvePageWriteTarget(engine, slug, 'default'); + await engine.softDeletePage(slug, { sourceId: 'default' }); + + const removed = await deletePageThrough(engine, slug, { sourceId: 'default', target }); + expect(removed.removed).toBe(true); + expect(removed.path).toBe(path.join(brainDir, authored)); + expect(fs.existsSync(path.join(brainDir, authored))).toBe(false); + }); +}); + +describe('delete_page / restore_page write-through symmetry (#4022)', () => { + const delete_page = operations.find((o) => o.name === 'delete_page')!; + const restore_page = operations.find((o) => o.name === 'restore_page')!; + + function ctxOf(overrides: Partial = {}): OperationContext { + return { + engine: engine as any, + config: { engine: 'pglite' } as any, + logger: { info() {}, warn() {}, error() {} }, + dryRun: false, + remote: false, + sourceId: 'default', + ...overrides, + } as OperationContext; + } + + test('[REGRESSION resurrect] delete_page removes the recorded source_path artifact', async () => { + await engine.setConfig('sync.repo_path', brainDir); + const slug = 'library/people/grace-hopper'; + const authored = 'Library/People/Grace Hopper.md'; + await importFromContent(engine, slug, `---\ntitle: Grace Hopper\ntype: person\n---\n\n# Body\n`, { + noEmbed: true, + sourceId: 'default', + sourcePath: authored, + }); + const written = await writePageThrough(engine, slug, { sourceId: 'default' }); + expect(written.path).toBe(path.join(brainDir, authored)); + + const res = await delete_page.handler(ctxOf(), { slug }) as Record; + + expect(res.status).toBe('soft_deleted'); + // Pre-fix the delete was DB-only: the authored `.md` survived, the next + // timer-based commit pushed it back into git, and `gbrain sync` + // re-imported it — resurrecting the page the user deleted. + expect(fs.existsSync(path.join(brainDir, authored))).toBe(false); + expect(res.write_through?.removed).toBe(true); + expect(res.write_through?.path).toBe(path.join(brainDir, authored)); + }); + + test('restore_page re-renders the artifact (sync --full must not re-delete the restored page)', async () => { + await engine.setConfig('sync.repo_path', brainDir); + const slug = 'concepts/round-trip'; + await seedPage(slug); + const written = await writePageThrough(engine, slug, { sourceId: 'default' }); + expect(fs.existsSync(written.path!)).toBe(true); + + const del = await delete_page.handler(ctxOf(), { slug }) as Record; + expect(del.write_through?.removed).toBe(true); + expect(fs.existsSync(written.path!)).toBe(false); + + const res = await restore_page.handler(ctxOf(), { slug }) as Record; + + expect(res.status).toBe('restored'); + // Without the re-render a restored page has a DB row and no artifact, and + // `sync --full` delete-reconcile treats the missing file as a user + // deletion — silently re-deleting the page the user just restored. + expect(res.write_through?.written).toBe(true); + expect(fs.existsSync(written.path!)).toBe(true); + }); + + test('sandbox subagents stay DB-only on both planes (matches put_page trust gate)', async () => { + await engine.setConfig('sync.repo_path', brainDir); + const slug = 'concepts/sandboxed'; + await seedPage(slug); + const written = await writePageThrough(engine, slug, { sourceId: 'default' }); + expect(fs.existsSync(written.path!)).toBe(true); + + const sandboxCtx = ctxOf({ viaSubagent: true }); + const del = await delete_page.handler(sandboxCtx, { slug }) as Record; + expect(del.status).toBe('soft_deleted'); + expect(del.write_through?.skipped).toBe('subagent_sandbox'); + // The DB row is soft-deleted but the sandboxed caller never touches disk. + expect(fs.existsSync(written.path!)).toBe(true); + + const rest = await restore_page.handler(sandboxCtx, { slug }) as Record; + expect(rest.status).toBe('restored'); + expect(rest.write_through?.skipped).toBe('subagent_sandbox'); + }); +});