v0.46.35.0 fix: wave-k maintainer train — 31 red-proven fixes (5 fix-wave-j salvages, 11 verified issues, 15 credited reimplementations) (#4650)

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 <noreply@anthropic.com>
Co-authored-by: DarkNightForge <DarkNightForge@users.noreply.github.com>
Co-authored-by: DarkNightForge <eashanbabber@gmail.com>
Co-authored-by: Dr Deeb <drdeebtech@users.noreply.github.com>
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 <leihao_zhou@qingsongchou.com>
Co-authored-by: miroslavb <31091373+miroslavb@users.noreply.github.com>
Co-authored-by: y2688 <172344182+y2688@users.noreply.github.com>
This commit is contained in:
Garry Tan
2026-08-27 13:09:55 -07:00
committed by GitHub
parent 534a27a982
commit 3464179ce9
166 changed files with 7795 additions and 634 deletions

View File

@@ -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",

View File

@@ -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",

View File

@@ -1,4 +1,4 @@
<!-- gbrain-runbook-stamp: 0.46.34.0 -->
<!-- gbrain-runbook-stamp: 0.46.35.0 -->
<!-- This stamp must equal the VERSION file at every release; CI enforces it
(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it to
the installed binary and warns on skew. -->

View File

@@ -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,

View File

@@ -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.

View File

@@ -1 +1 @@
0.46.34.0
0.46.35.0

View File

@@ -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"]

View File

@@ -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

File diff suppressed because one or more lines are too long

View File

@@ -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 <token>
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

View File

@@ -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": {

View File

@@ -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",

View File

@@ -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",

View File

@@ -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",

View File

@@ -1,4 +1,4 @@
<!-- gbrain-plugin-tree-stamp: 0.46.34.0 -->
<!-- gbrain-plugin-tree-stamp: 0.46.35.0 -->
# gbrain-coding (generated persona variant — do not hand-edit)
Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant.

View File

@@ -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",

View File

@@ -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",

View File

@@ -1,4 +1,4 @@
<!-- gbrain-plugin-tree-stamp: 0.46.34.0 -->
<!-- gbrain-plugin-tree-stamp: 0.46.35.0 -->
# gbrain-daily (generated persona variant — do not hand-edit)
Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant.

View File

@@ -1,4 +1,4 @@
<!-- gbrain-plugin-tree-stamp: 0.46.34.0 -->
<!-- gbrain-plugin-tree-stamp: 0.46.35.0 -->
# gbrain plugin skill tree (generated — do not hand-edit)
This tree is the curated skill set for the gbrain Codex and Claude Code

View File

@@ -101,6 +101,8 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
"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<string, string[]> = {
"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",

View File

@@ -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)
Can't render this file because it contains an unexpected character in line 6 and column 173.

View File

@@ -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
Can't render this file because it contains an unexpected character in line 38 and column 63.

View File

@@ -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.

View File

@@ -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",

View File

@@ -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<BrainEngin
// host brain's merge.
MERGED_CONFIG_BY_ENGINE.set(engine, merged);
// Stash gate flags on process.env for downstream readers (import-file.ts
// dispatches on GBRAIN_EMBEDDING_MULTIMODAL, OCR consumer reads
// GBRAIN_EMBEDDING_IMAGE_OCR_*). The gateway itself doesn't read these
// flags; this preserves the contract without changing the gateway shape.
// dispatches on GBRAIN_EMBEDDING_MULTIMODAL, gates OCR on GBRAIN_EMBEDDING_IMAGE_OCR).
// The OCR *model* reaches the gateway via the re-configure below (#4107); its
// env stash stays so subprocesses re-fold it through loadConfig's env merge.
if (merged.embedding_multimodal !== undefined) {
process.env.GBRAIN_EMBEDDING_MULTIMODAL = String(merged.embedding_multimodal);
}

View File

@@ -44,6 +44,8 @@ interface ApplyMigrationsArgs {
forceAll?: boolean;
/** v0.30.1 (D6 / X3): bypass verify-hook drift detection on a single run. */
skipVerify?: boolean;
/** #4364: exit 1 when the DB pre-flight probe fails instead of proceeding filesystem-only. */
requireDb: boolean;
help: boolean;
}
@@ -72,6 +74,7 @@ function parseArgs(args: string[]): ApplyMigrationsArgs {
forceSchema: has('--force-schema'),
forceAll: has('--force-all') || has('--force'),
skipVerify: has('--skip-verify'),
requireDb: has('--require-db'),
help: has('--help') || has('-h'),
};
}
@@ -102,6 +105,9 @@ Usage:
non-idempotent migrations (D6 escape hatch).
Flags:
--require-db Exit 1 when the database is unreachable
instead of continuing with the
filesystem-only migration plan.
--mode <always|pain_triggered|off> Set minion_mode without prompting.
--host-dir <path> 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<void> {
// --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<void> {
// 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<void> {
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<void> {
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,
};

View File

@@ -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 <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,
};

View File

@@ -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'

View File

@@ -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<string, number>();
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.

View File

@@ -319,13 +319,19 @@ export async function checkLinkResolutionOpportunity(
export async function checkAbandonedThreads(engine: BrainEngine): Promise<Check> {
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) {

View File

@@ -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<string, number>();
/** 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++;

View File

@@ -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<void> {
}
// 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

View File

@@ -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;

View File

@@ -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<string>,
slugToSources: Map<string, string[]>,
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<string>();
const slugToSources = new Map<string, string[]>();
@@ -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.`);

View File

@@ -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 <slug>` 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 <dir> [--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);

View File

@@ -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 <connection_string> or GBRAIN_DATABASE_URL env var');
process.exit(1);
}
} else if (preservedPostgresUrl) {
databaseUrl = preservedPostgresUrl;
} else {
databaseUrl = await supabaseWizard();
}

View File

@@ -238,6 +238,7 @@ async function classifyBatch(paragraphs: string[]): Promise<Array<'high' | 'medi
if (paragraphs.length === 0) return [];
const { chat } = await import('../core/ai/gateway.ts');
const { resolveTierDefault } = await import('../core/model-config.ts');
const system = [
'Classify each paragraph into HIGH, MEDIUM, or LOW notability for personal-knowledge memory:',
@@ -256,7 +257,8 @@ async function classifyBatch(paragraphs: string[]): Promise<Array<'high' | 'medi
try {
const result = await chat({
model: 'anthropic:claude-haiku-4-5-20251001',
// #3813: key-aware tier default, not a hardcoded Anthropic model.
model: resolveTierDefault('utility'),
system,
messages: [{ role: 'user', content: userMsg }],
maxTokens: 200,

View File

@@ -33,6 +33,7 @@ import {
removePrefixFromType,
removeTypeFromPack,
resolveActivePackNameOnly,
resolveLoadedPack,
loadPackFromFile,
parseSchemaPackManifest,
runStatsCore,

View File

@@ -99,5 +99,9 @@ export async function runSelfUpgrade(args: string[]): Promise<void> {
}
// 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,
});
}

View File

@@ -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');
}

View File

@@ -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
// ---------------------------------------------------------------------------

View File

@@ -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:<src>; 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,

View File

@@ -708,8 +708,18 @@ async function cmdExtract(engine: BrainEngine, rest: string[]): Promise<void> {
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);

View File

@@ -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);

View File

@@ -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,

View File

@@ -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<Float32A
const expected = effectiveDims;
const embedding = recipe.touchpoints?.embedding;
const maxBatchTokens = embedding?.max_batch_tokens;
// GBRAIN_EMBED_MAX_BATCH_TOKENS (#3622): operator-declared cap for recipes
// that ship without one (ollama/llama-server/litellm declare no_batch_cap
// because real capacity depends on the operator's local server). Without
// any cap, a page's entire chunk set goes out as ONE request — on a serial
// local server that can outlive the embed timeout and starve the queue.
// Recipe-declared caps always win; invalid values are ignored. Read from
// the configure-time env snapshot (Codex C3), never process.env at call
// time — buildGatewayConfig folds the operator's process env into it.
const envCapRaw = parseInt(cfg.env?.GBRAIN_EMBED_MAX_BATCH_TOKENS ?? '', 10);
const envCap = Number.isFinite(envCapRaw) && envCapRaw > 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<string[]> {
/**
* 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<string[]> {
* keeping the gateway focused on the LLM call.
*/
export async function generateOcrText(imageBytes: Buffer, mime: string): Promise<string> {
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<string, Record<string, unknown>>;
/**
* 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<ChatResult> {
const tools = toAISDKTools(opts.tools);
const providerOptions: Record<string, any> = {};
let providerOptions: Record<string, any> = {};
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<ChatResult> {
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

View File

@@ -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

View File

@@ -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,
},

View File

@@ -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). */

View File

@@ -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<string, number[]>();
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;

View File

@@ -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,

View File

@@ -17,7 +17,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'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<string, readonly string[]> = {
'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<string, readonly string[]> = {
'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<string, readonly string[]> = {
'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<string, readonly string[]> = {
'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'],

View File

@@ -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<boolean> {
/**
* 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<boolean> {
const params: unknown[] = [];
let scopeClause = '';
if (sourceId) {

View File

@@ -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;

View File

@@ -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.

View File

@@ -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 = <T,>(fn: () => Promise<T>) => 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);

View File

@@ -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')

View File

@@ -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<JudgeVerdict> {
}, chatFn: typeof gatewayChat = gatewayChat): Promise<JudgeVerdict> {
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;
}

View File

@@ -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<void> {
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<void> {
// #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) {

View File

@@ -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<void>;
/**
* 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<number> {
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/<id>/<slug>.md

View File

@@ -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<void>;
/**
@@ -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 <provider>:<model>`.
@@ -1525,7 +1556,10 @@ async function checkCooldown(
// for AIConfigError surfacing mid-run.
export interface JudgeClient {
create: (params: Anthropic.MessageCreateParamsNonStreaming) => Promise<Anthropic.Message>;
create: (
params: Anthropic.MessageCreateParamsNonStreaming,
options?: { signal?: AbortSignal },
) => Promise<Anthropic.Message>;
}
/**
@@ -1563,7 +1597,7 @@ export function makeJudgeClient(verdictModel: string): JudgeClient | null {
if (v.parsed.providerId === 'anthropic' && !hasAnthropicKey()) return null;
return {
create: async (params): Promise<Anthropic.Message> => {
create: async (params, options): Promise<Anthropic.Message> => {
// 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<TriageResult> {
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<void> {
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<number> {
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/<id>/<slug>.md
@@ -2656,7 +2719,9 @@ async function writeSummaryPage(
writtenSlugs: string[],
childOutcomes: Array<{ jobId: number; status: string }>,
sourceId = 'default',
signal?: AbortSignal,
): Promise<void> {
throwIfAborted(signal, '[dream] synthesize summary');
const completed = childOutcomes.filter(c => c.status === 'completed').length;
const failed = childOutcomes.length - completed;

32
src/core/engine-errors.ts Normal file
View File

@@ -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';
}
}

View File

@@ -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<RelationalFanoutRow[]>;
/**
* 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<Map<string, number>>;
getBacklinkCounts(pageIds: number[]): Promise<Map<number, number>>;
/**
* 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<DreamVerdict | null>;
putDreamVerdict(filePath: string, contentHash: string, verdict: DreamVerdictInput): Promise<void>;
/**
* Delete expired dream verdicts; returns rows removed. Best-effort
* housekeeping — reads already treat expired rows as misses (#4069).
*/
sweepDreamVerdicts(): Promise<number>;
// ============================================================
// v0.32.6 Contradiction probe — batched takes fetch + cache + trends

View File

@@ -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/<token> 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.

View File

@@ -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<RunnerRes
async function _runContradictionProbeInner(opts: RunnerOpts): Promise<RunnerResult> {
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;

View File

@@ -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;

View File

@@ -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 };
}

View File

@@ -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';
}
/**

View File

@@ -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<SingleFactResult> {
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,

View File

@@ -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 `<dir>/.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.
}
}

View File

@@ -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<Record<string, unknown>> {
}
/**
* 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');

View File

@@ -1679,3 +1679,40 @@ export async function isGlobalBasenameEnabled(engine: BrainEngine): Promise<bool
const normalized = val.trim().toLowerCase();
return ['1', 'true', 'yes', 'on'].includes(normalized);
}
/**
* Read the `link_resolution.cross_source` config flag. Defaults to FALSE
* (opt-in only; the historical same-source-or-'default' edge gate is
* preserved for existing brains).
*
* When TRUE: a wikilink whose target slug exists ONLY in other sources
* (neither the origin page's source nor 'default') still produces an edge,
* with `to_source_id` picked deterministically (lexicographically smallest
* matching source). When FALSE, those candidates are dropped — but counted
* and surfaced in the extract summary, never silent (issue #2589: the drop
* was previously indistinguishable from an unresolved link).
*
* SCOPE: the DB extract paths only (`extract links --source db`,
* `extract --stale`) — they resolve against the full multi-source slug map.
* The FS-walk paths (dir-driven, incl. the autopilot cycle's extract phase)
* build their slug set from the walked files of ONE source, so cross-source
* targets aren't resolvable there; FS-walk parity is a filed follow-up.
*
* Resolution order (highest → lowest):
* 1. Env var `GBRAIN_LINK_RESOLUTION_CROSS_SOURCE=1` (operator override)
* 2. DB plane via `engine.getConfig('link_resolution.cross_source')`
* 3. Default false
*
* Closes https://github.com/garrytan/gbrain/issues/2589.
*/
export async function isCrossSourceLinksEnabled(engine: BrainEngine): Promise<boolean> {
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);
}

View File

@@ -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

View File

@@ -64,7 +64,13 @@ export const DEFAULT_ALIASES: Record<string, string> = {
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

View File

@@ -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,

View File

@@ -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<void> {
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<never> {
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

View File

@@ -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.
*/

View File

@@ -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

View File

@@ -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'] },

View File

@@ -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'] },
};

View File

@@ -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;

View File

@@ -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'),

View File

@@ -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,

View File

@@ -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<typeof setTimeout> | undefined;
try {
await Promise.race([
db.query('CHECKPOINT').catch(() => undefined),
new Promise<void>((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<number> {
@@ -4354,28 +4382,29 @@ export class PGLiteEngine implements BrainEngine {
}));
}
async getBacklinkCounts(slugs: string[]): Promise<Map<string, number>> {
const result = new Map<string, number>();
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<Map<number, number>> {
const result = new Map<number, number>();
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<boolean> {
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<number> {
@@ -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<void> {
// $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<number> {
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
// ============================================================

View File

@@ -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<number> {
// 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 ?? {});

View File

@@ -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<number> {
@@ -3634,10 +3640,10 @@ export class PostgresEngine implements BrainEngine {
}));
}
async getBacklinkCounts(slugs: string[]): Promise<Map<string, number>> {
const result = new Map<string, number>();
if (slugs.length === 0) return result;
for (const s of slugs) result.set(s, 0);
async getBacklinkCounts(pageIds: number[]): Promise<Map<number, number>> {
const result = new Map<number, number>();
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<boolean> {
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<number> {
@@ -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<void> {
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<typeof sql.json>[0])},
${verdict.score}, ${verdict.content_type}, ${sql.json(verdict.segments as unknown as Parameters<typeof sql.json>[0])},
${sql.json(verdict.entities as Parameters<typeof sql.json>[0])}, ${verdict.model}, ${verdict.triage_version})
${sql.json(verdict.entities as Parameters<typeof sql.json>[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<number> {
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
// ============================================================

View File

@@ -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<FactRowSqlShape[]>`
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<FactRowSqlShape[]>`
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<FactRowSqlShape[]>`
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<number> {
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);
}

View File

@@ -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

View File

@@ -99,6 +99,7 @@ export {
export {
loadActivePack,
loadResolvedPackByName,
resolveLoadedPack,
resolveActivePackNameOnly,
__setPackLocatorForTests,
_resetPackLocatorForTests,

View File

@@ -153,6 +153,18 @@ export async function loadActivePack(input: LoadActivePackInput): Promise<Resolv
const cached = tryCachedPack(resolution.pack_name);
if (cached) return cached;
const manifest = await loadPackManifestByName(resolution.pack_name);
return await resolveLoadedPack(manifest);
}
/**
* Resolve an already-loaded manifest's extends/borrow chain through the
* same locator `loadActivePack` uses (bundled assets + ~/.gbrain/schema-packs
* + the test seam). Named-pack consumers that already hold a loaded manifest
* (the MCP schema_lint op's own file lookup) call this so they lint the
* MERGED manifest, matching validate/use/active (#4373; CLI `schema lint
* <name>` resolves by name via loadResolvedPackByName, #4501).
*/
export async function resolveLoadedPack(manifest: SchemaPackManifest): Promise<ResolvedPack> {
// 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, {

View File

@@ -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<string, number>,
counts: Map<number, number>,
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.

View File

@@ -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,

View File

@@ -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'];

View File

@@ -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<string>([
...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++) {

View File

@@ -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(

View File

@@ -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;

View File

@@ -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.

View File

@@ -216,6 +216,7 @@ const entity: Operation = {
// messages) ride `detail` only; the message carries the code.
const SYNTHESIS_FAILURE_CODES: Record<string, string> = {
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<VerbName, Record<string, unknown>> = {

View File

@@ -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

View File

@@ -196,9 +196,48 @@ export async function isWriteThroughDisabled(engine: BrainEngine): Promise<boole
/** Resolved disk target for a page's canonical markdown artifact. */
export type PageWriteTarget =
| { ok: true; filePath: string; writeRoot: string }
| {
ok: true;
filePath: string;
writeRoot: string;
/**
* `filePath` expressed in the file scanner's `pages.source_path`
* convention (#774: git-root-relative when the scan root sits inside a
* git repo, scan-root-relative otherwise; forward slashes). What
* writePageThrough binds onto a source_path=NULL row after the file
* materializes (#4247).
*/
sourcePathToBind: string;
}
| { ok: false; skipped: 'no_repo_configured' | 'repo_not_found' | 'source_repo_belongs_to_other_source' | 'path_escapes_source_root' };
/**
* Scanner-convention `pages.source_path` for a file under `scanRoot` (the
* root a sync of this source walks). Mirrors sync's #774 rule — a scan root
* INSIDE a git repo records GIT-ROOT-relative paths (scoped sync), a git-root
* or non-git root records root-relative — and must stay the exact inverse of
* `resolveSourceLocalFilePath` (markdown.ts): delete-reconcile keys on this
* form, so a local_path-relative bind for a subdirectory-scoped source would
* read as stale and sweep the page while its file is still on disk.
*/
function scannerSourcePath(scanRoot: string, filePath: string): string {
// nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- scanRoot is the operator-written sources.local_path / sync.repo_path config root; canonicalizing it here mints no fs read/write path
const absRoot = resolve(scanRoot);
let cursor = absRoot;
while (true) {
// nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- cursor only walks UP (dirname) from the operator-config root joined with the literal '.git' segment; existsSync boolean probe, no content ever read or served
if (existsSync(join(cursor, '.git'))) {
// nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- filePath was proven inside writeRoot by isWriteTargetContained before the sole call site (resolvePageWriteTarget); output is an in-memory source_path string, not an fs operand
return relative(cursor, resolve(filePath)).replaceAll('\\', '/');
}
const parent = dirname(cursor);
if (parent === cursor) break;
cursor = parent;
}
// nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- same: containment-checked filePath relative to the operator-config root, string minting only
return relative(absRoot, resolve(filePath)).replaceAll('\\', '/');
}
/**
* Compute the ONE file a (source, slug) pair lives in on disk.
*
@@ -242,6 +281,7 @@ export async function resolvePageWriteTarget(
): Promise<PageWriteTarget> {
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 <pageRoot>` 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<PageWriteTarget, { ok: false }>['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<DeleteThroughResult> {
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 };
}
}

Some files were not shown because too many files have changed in this diff Show More