Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

GBRA-156: warm socket production wave (narrowed identity, loud refusals, cancellation, round-trip cap error, sweep gating, read-only search transactions, deferred bookkeeping, supersedes index)

garrytanf88dbb80f5ce
diff --git a/docs/guides/cli-socket.md b/docs/guides/cli-socket.md
index 3d098af8e1..980d56bb98 100644
--- a/docs/guides/cli-socket.md
+++ b/docs/guides/cli-socket.md
@@ -61,18 +61,15 @@ watch, cursor and rollup forms of `recall`, and a page large enough that
## When it is not used
-The CLI falls back to its normal path, silently, when:
+The CLI falls back to its normal path when (silently, except for an identity
+refusal, which always prints a notice):
- no serve has the socket open, or the serve died and left a stale socket;
- the serve does not accept the request within about a second (a wedged serve
never stalls the CLI);
-- the answer takes longer than 30 seconds, or than the call's `--timeout` when
- that is shorter, the serve's own read deadline passes, or the serve dies in
- the middle of the request: the CLI then runs the call itself, once, with its
- usual timeout and exit codes (it can only be a read, so running it again is
- safe). A warm read that runs past 30 seconds therefore runs a second time
- cold, so a slow LLM-backed query (`query`, `recall --question`) can cost
- twice; pass a shorter `--timeout` or set `GBRAIN_CLI_SOCKET=0` for those;
+- the serve dies in the middle of the request: the CLI then runs the call
+ itself, once, with its usual timeout and exit codes (it can only be a read,
+ so running it again is safe);
- the serve answers with a frame the CLI cannot fully read or render (nothing
is printed from it);
- the serve was started for a different brain or environment. The CLI sends
@@ -90,8 +87,14 @@ The CLI falls back to its normal path, silently, when:
(`READ_BEHAVIOR_ENV` in `src/core/cli-socket/identity.ts`: models,
embeddings, search tuning, visibility, timeouts, schema pack, AI call log,
contributor capture and the like), which provider API keys are set (never
- their values), and the values of the provider routing settings (base URLs,
- endpoints, deployments, API versions, org, project and group ids).
+ their values, for every provider), and the values of the provider routing
+ settings (base URLs, endpoints, deployments, API versions, org, project and
+ group ids) of every provider either side can call. A provider neither side
+ can call (one of its required variables is unset in the environment and the
+ config file, and none of its keys is set) cannot reach an answer, so its
+ routing settings may differ: an Azure API version exported in a shell that
+ has no Azure endpoint no longer refuses the call. The identity decides which
+ answer a call may reuse, never who may connect (see Security).
Connection sizing and driver settings (`GBRAIN_POOL_SIZE`,
`GBRAIN_DIRECT_POOL_SIZE`, `GBRAIN_PREPARE`, ...), the database URL
variables and `GBRAIN_SOURCE` (which every request carries and the serve
@@ -102,9 +105,28 @@ The CLI falls back to its normal path, silently, when:
path until the serve restarts with the same settings. The refusal names the
part that differed, never its value: `refused (identity_mismatch): database
port`, `env GBRAIN_MODEL`, `provider key VOYAGE_API_KEY`, `config
- contents`, and the serve logs each distinct one once;
+ contents`, and the serve logs each distinct one once. Every refused call
+ also prints a `socket_identity_mismatch` notice naming the part (an
+ `[AGENT]` block on a non-TTY stdout, stderr under `--json` or on a TTY),
+ and the serve counts refusals by part for `gbrain doctor --only
+ cli_socket_refusals`, which warns while any happened in the last 24 hours;
- the CLI targets a mount brain (`--brain <mount>` and the other mount tiers).
+A warm call that takes longer than 30 seconds, or than its `--timeout` when
+that is shorter, does not start over on the cold path. The serve cancels the
+request's remaining work (its open read transactions are cancelled and their
+connections discarded, and its later statements are refused) and the CLI
+prints a retryable `timeout` error and exits 124: the envelope on stdout under
+`--json`, the human line on stderr, and without `--json` an `[AGENT]` block on
+stdout as well, so a caller that discards stderr still sees why. The CLI does
+the same when the serve never answers in time. A client that disconnects
+before its answer (killed by its own `timeout`) cancels the request the same
+way, and the serve logs it.
+
+While warm CLI calls flow, the serve's idle maintenance sweep does not start:
+a socket request counts as activity, as MCP stdin data does. The serve logs
+`idle sweep: started` and `idle sweep: finished in <n> ms` around each sweep.
+
`GBRAIN_DEBUG=1` prints one `[cli-socket] cold path: <reason>` line on stderr
whenever a call falls back, including when no socket exists (`no socket at
<path>`, with how to start one), and one `[cli-socket] warm: <command>
@@ -130,8 +152,12 @@ socket entirely, for comparisons and benchmarks.
socket and says why, and the CLI never connects.
- One serve per `GBRAIN_HOME` holds the socket; requests and responses are
size-bounded and each connection carries exactly one request. At most 8
- requests run at once; a request that timed out keeps its slot until its work
- actually finishes, so slow requests cannot pile up.
+ requests run at once; a request that timed out keeps its slot until its
+ cancelled work actually finishes, so slow requests cannot pile up.
+- The identity comparison is not an access check: who may connect is decided
+ only by the file permissions and the peer uid above, and narrowing which
+ provider settings must match never lets a call use a credential or a
+ provider its own environment does not configure.
- Postgres brains only. A PGLite brain's CLI calls already reach its running
serve through the persistence socket.
diff --git a/scripts/bench/production-soak/socket-probe.ts b/scripts/bench/production-soak/socket-probe.ts
new file mode 100644
index 0000000000..91e22ad406
--- /dev/null
+++ b/scripts/bench/production-soak/socket-probe.ts
@@ -0,0 +1,176 @@
+#!/usr/bin/env bun
+/**
+ * Warm CLI socket probe on a loaded production-soak brain (GBRA-156): the soak topology at --rtt-ms, the loopback mock
+ * provider, one `gbrain serve --cli-socket` (GBRAIN_SQL_TRACE on) and --n warm `gbrain search --json --timings` CLI
+ * calls. Per call it records the CLI's wall time, the serve's op time (timings_ms.op), the CLI overhead around it,
+ * and the serve's database round trips for the call: the total, and the sequential ones (the longest chain of round
+ * trips each starting after the previous one answered, i.e. the network floor the call cannot overlap).
+ *
+ * Background work the serve runs on its own (the persistence effects drain, the on-commit notifier) is not the call's:
+ * its statements, and every statement in a transaction that holds one, are counted as bg_trips, apart from the
+ * call's trips. Before measuring, the probe waits until the serve's trace has shown no persistence_effects statement for
+ * --settle-quiet-s (at most --settle-max-s), so a drain left over from the load does not ride along.
+ *
+ * --sweep N forces the serve's idle maintenance sweep beside searches N times: the serve ticks every
+ * --sweep-interval-ms (GBRAIN_SWEEP_IDLE_INTERVAL_MS), --touch pages with facts fences are marked updated before each
+ * cycle so the facts reconcile has work, and the probe starts --burst searches the moment the serve logs
+ * `idle sweep: started`, recording whether each search ran while the sweep was in flight.
+ *
+ * bun scripts/bench/production-soak/socket-probe.ts --fixture ~/soak/fixture --work ~/soak/work --out ~/socket-probe \
+ * [--rtt-ms 58] [--n 30] [--warmup 3] [--embed-ms 200] [--rerank-ms 300] [--sweep 0] [--sweep-interval-ms 15000] [--burst 3] [--touch 40]
+ */
+import { appendFileSync, existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs';
+import { join, resolve } from 'node:path';
+import postgres from '#postgres';
+import { startMockProviders } from '../retrieval-scale/mock-providers.ts';
+import { spawnChild } from '../sync-freshness-lib.ts';
+import { childEnv, now, REPO, sleep, startTopology, writeConfig } from './lib.ts';
+
+const argv = process.argv.slice(2);
+const flag = (name: string, fallback = '') => { const i = argv.indexOf('--' + name); return i >= 0 ? argv[i + 1]! : fallback; };
+const FIXTURE = resolve(flag('fixture')), WORK = resolve(flag('work')), OUT = resolve(flag('out'));
+const RTT = Number(flag('rtt-ms', '58')), N = Number(flag('n', '30')), WARMUP = Number(flag('warmup', '3'));
+const EMBED = Number(flag('embed-ms', '200')), RERANK = Number(flag('rerank-ms', '300'));
+const SETTLE_QUIET_S = Number(flag('settle-quiet-s', '15')), SETTLE_MAX_S = Number(flag('settle-max-s', '1800'));
+const SWEEPS = Number(flag('sweep', '0')), SWEEP_MS = Number(flag('sweep-interval-ms', '15000')), BURST = Number(flag('burst', '3')), TOUCH = Number(flag('touch', '40'));
+const manifest = JSON.parse(readFileSync(join(FIXTURE, 'manifest.json'), 'utf8'));
+const ready = JSON.parse(readFileSync(join(WORK, 'ready.json'), 'utf8'));
+const HOME = join(WORK, 'home');
+const CLI = join(REPO, 'src', 'cli.ts');
+
+interface Trip { t: number; ms: number; label: string; conn: number; kind: string; sql: string; bg?: boolean }
+const BACKGROUND = /persistence_|sync_notifier/;
+const DRAIN = /persistence_effects/;
+
+/** The longest chain of round trips in which each one starts after the previous one answered. */
+function sequential(trips: Trip[]): number {
+ const sorted = [...trips].sort((a, b) => (a.t + a.ms) - (b.t + b.ms));
+ const depth: number[] = [];
+ let best = 0;
+ for (let i = 0; i < sorted.length; i++) {
+ let d = 1;
+ for (let j = 0; j < i; j++) if (sorted[j]!.t + sorted[j]!.ms <= sorted[i]!.t) d = Math.max(d, depth[j]! + 1);
+ depth.push(d);
+ best = Math.max(best, d);
+ }
+ return best;
+}
+
+function readTrips(file: string): Trip[] {
+ if (!existsSync(file)) return [];
+ const trips = readFileSync(file, 'utf8').split('\n').filter(Boolean).map(l => JSON.parse(l) as Trip).filter(r => r.kind !== 'connect' && r.kind !== 'tls_untraced');
+ const open = new Map<number, Trip[]>();
+ for (const r of [...trips].sort((a, b) => a.t - b.t)) {
+ r.bg = BACKGROUND.test(r.sql);
+ const sql = r.sql.trim().toLowerCase();
+ if (sql.startsWith('begin')) { open.set(r.conn, [r]); continue; }
+ const tx = open.get(r.conn);
+ if (!tx) continue;
+ tx.push(r);
+ if (sql === 'commit' || sql === 'rollback') {
+ open.delete(r.conn);
+ if (tx.some(x => x.bg)) for (const x of tx) x.bg = true;
+ }
+ }
+ return trips;
+}
+
+async function queries(directUrl: string): Promise<string[]> {
+ const sql = postgres(directUrl, { max: 1, onnotice: () => {} });
+ const rows = await sql.unsafe("SELECT p.title, left(c.chunk_text, 600) AS text FROM pages p JOIN content_chunks c ON c.page_id = p.id AND c.chunk_index = 0 WHERE p.deleted_at IS NULL AND p.frontmatter->>'visibility' IS NULL AND p.type <> 'chat' ORDER BY md5(p.id::text) LIMIT 200") as Array<{ title: string; text: string }>;
+ await sql.end();
+ return rows.map((r, i) => {
+ const words = r.text.replace(/[^a-z\s]/gi, ' ').split(/\s+/).filter(w => w.length > 3);
+ const k = 2 + (i % 3), at = (i * 7919) % Math.max(1, words.length - k);
+ const name = i % 3 === 0 ? r.title.split(/\s+/).slice(0, 2).join(' ') : '';
+ return [name, ...words.slice(at, at + k)].filter(Boolean).join(' ') || r.title;
+ });
+}
+
+rmSync(OUT, { recursive: true, force: true });
+mkdirSync(OUT, { recursive: true });
+const topo = await startTopology(WORK, undefined, undefined, true);
+await topo.setRtt(0);
+const direct = topo.direct(ready.db);
+const qs = await queries(direct);
+await topo.setRtt(RTT);
+const mock = startMockProviders({ manifest: { seed: manifest.options.seed, chunks: manifest.pages * 4, pages: manifest.pages, dims: 1536 }, embedMs: EMBED, rerankMs: RERANK });
+writeConfig(HOME, topo.txn(ready.db), mock.url);
+const serveTrace = join(OUT, 'trace-serve.jsonl');
+const base = childEnv(HOME, mock.url, { GBRAIN_DIRECT_DATABASE_URL: topo.session(ready.db) });
+const serveEnv = { ...base, GBRAIN_SQL_TRACE: serveTrace, GBRAIN_SQL_TRACE_LABEL: 'serve', GBRAIN_SWEEP: SWEEPS > 0 ? '1' : '0', GBRAIN_SWEEP_IDLE_INTERVAL_MS: String(SWEEP_MS) };
+let serveLog = '';
+const serve = spawnChild([process.execPath, CLI, 'serve', '--cli-socket'], { cwd: HOME, env: serveEnv, logFile: join(OUT, 'serve.log'), stdin: true });
+serve.onLine(l => { if (l.stream === 'err') serveLog += l.text + '\n'; });
+for (let i = 0; i < 720 && !/cli-socket: listening/.test(serveLog); i++) await sleep(250);
+if (!/cli-socket: listening/.test(serveLog)) throw new Error('serve did not open the CLI socket:\n' + serveLog.slice(-2000));
+
+const settleStart = now();
+let lastBg = now();
+for (;;) {
+ const bg = readTrips(serveTrace).filter(r => DRAIN.test(r.sql));
+ if (bg.length) lastBg = Math.max(lastBg, ...bg.slice(-50).map(r => r.t + r.ms));
+ if (now() - lastBg >= SETTLE_QUIET_S * 1000 || now() - settleStart >= SETTLE_MAX_S * 1000) break;
+ await sleep(1000);
+}
+const settledAfterS = Math.round((now() - settleStart) / 1000);
+console.log('settle', settledAfterS, 's', now() - lastBg >= SETTLE_QUIET_S * 1000 ? 'quiet' : 'still busy at --settle-max-s');
+
+const sweepStarts = () => (serveLog.match(/idle sweep: started/g) ?? []).length;
+const sweepEnds = () => (serveLog.match(/idle sweep: finished/g) ?? []).length;
+
+async function call(i: number, label: string): Promise<void> {
+ const query = qs[i % qs.length]!;
+ const cliTrace = join(OUT, 'trace-cli-' + i + '.jsonl');
+ const inSweep = sweepStarts() > sweepEnds();
+ const t0 = now();
+ const p = Bun.spawn([process.execPath, CLI, 'search', query, '--json', '--timings'], { cwd: HOME, env: { ...base, GBRAIN_SQL_TRACE: cliTrace }, stdout: 'pipe', stderr: 'pipe' });
+ const [stdout, stderr, code] = await Promise.all([new Response(p.stdout).text(), new Response(p.stderr).text(), p.exited]);
+ const t1 = now();
+ await sleep(1200);
+ let op: number | null = null;
+ let timings: Record<string, unknown> | null = null;
+ try { timings = JSON.parse(stdout).timings_ms ?? null; op = typeof timings?.op === 'number' ? timings.op : null; } catch { /* non-JSON output */ }
+ const window = readTrips(serveTrace).filter(r => r.label === 'serve' && r.t >= t0 && r.t + r.ms <= t1 + 5);
+ const trips = window.filter(r => !r.bg);
+ const record = { i, label, t0, t1, query_words: query.split(' ').length, ms: Math.round(t1 - t0), op_ms: op, cli_overhead_ms: op === null ? null : Math.round(t1 - t0 - op),
+ code, warm: readTrips(cliTrace).length === 0, in_sweep_at_start: inSweep, in_sweep_at_end: sweepStarts() > sweepEnds(),
+ trips: trips.length, bg_trips: window.length - trips.length, sequential: sequential(trips), conns: new Set(trips.map(r => r.conn)).size, stages: timings?.stages, parts: timings?.parts_ms, stderr_tail: code === 0 ? undefined : stderr.slice(-300) };
+ appendFileSync(join(OUT, 'calls.jsonl'), JSON.stringify(record) + '\n');
+}
+
+for (let i = 0; i < WARMUP; i++) await call(i, 'warmup');
+for (let i = 0; i < N; i++) await call(WARMUP + i, 'baseline');
+if (SWEEPS > 0) {
+ const sql = postgres(direct, { max: 1, onnotice: () => {} });
+ for (let cycle = 0; cycle < SWEEPS; cycle++) {
+ await sql.unsafe(`UPDATE pages SET updated_at = now() WHERE id IN (SELECT id FROM pages WHERE source_id = 'default' AND deleted_at IS NULL AND compiled_truth LIKE '%gbrain:facts:begin%' ORDER BY random() LIMIT ${TOUCH})`);
+ const before = sweepStarts();
+ for (let w = 0; w < 4 * SWEEP_MS / 250 && sweepStarts() === before; w++) await sleep(250);
+ if (sweepStarts() === before) { appendFileSync(join(OUT, 'calls.jsonl'), JSON.stringify({ label: 'sweep', cycle, error: 'no sweep started' }) + '\n'); continue; }
+ await Promise.all(Array.from({ length: BURST }, (_, k) => call(10_000 + cycle * BURST + k, 'during_sweep')));
+ for (let w = 0; w < 240 && sweepStarts() > sweepEnds(); w++) await sleep(250);
+ }
+ await sql.end();
+}
+serve.kill();
+mock.stop();
+const rows = readFileSync(join(OUT, 'calls.jsonl'), 'utf8').trim().split('\n').map(l => JSON.parse(l));
+const p50 = (xs: Array<number | null>) => { const s = xs.filter((x): x is number => typeof x === 'number').sort((a, b) => a - b); return s.length ? s[Math.floor((s.length - 1) / 2)] : null; };
+const max = (xs: Array<number | null>) => Math.max(...xs.filter((x): x is number => typeof x === 'number'));
+const sweeps = [...serveLog.matchAll(/idle sweep: finished in (\d+) ms/g)].map(m => Number(m[1]));
+for (const label of ['baseline', 'during_sweep']) {
+ const r = rows.filter(x => x.label === label);
+ if (!r.length) continue;
+ console.log(label, 'n', r.length, 'warm', r.filter(x => x.warm).length, 'wall p50', p50(r.map(x => x.ms)), 'max', max(r.map(x => x.ms)), 'op p50', p50(r.map(x => x.op_ms)),
+ 'cli overhead p50', p50(r.map(x => x.cli_overhead_ms)), 'trips p50', p50(r.map(x => x.trips)), 'bg trips p50', p50(r.map(x => x.bg_trips)), 'sequential p50', p50(r.map(x => x.sequential)), 'conns p50', p50(r.map(x => x.conns)),
+ 'errors', r.filter(x => x.code !== 0).length);
+}
+const stageKeys = new Set<string>();
+for (const r of rows.filter(x => x.label === 'baseline')) for (const k of Object.keys(r.stages ?? {})) stageKeys.add(k);
+for (const k of [...stageKeys].sort()) console.log(' stage', k.padEnd(14), 'p50', p50(rows.filter(x => x.label === 'baseline').map(x => x.stages?.[k] ?? null)));
+const partKeys = new Set<string>();
+for (const r of rows.filter(x => x.label === 'baseline')) for (const [s, ps] of Object.entries(r.parts ?? {})) for (const k of Object.keys(ps as object)) partKeys.add(s + '.' + k);
+for (const k of [...partKeys].sort()) { const [s, n] = k.split('.'); console.log(' part', k.padEnd(24), 'p50', p50(rows.filter(x => x.label === 'baseline').map(x => x.parts?.[s!]?.[n!] ?? null))); }
+if (sweeps.length) console.log('sweeps', sweeps.length, 'duration ms', sweeps.join(','));
+process.exit(0);
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index df7b646170..471408431f 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -16,12 +16,12 @@ src/commands/sync.ts 550 ratchet refactor wave 1 split target (W4 sync); ceiling
src/core/cycle.ts 3337 ratchet +2 GBRA-130 C-2 (#6946): the sync phase reads an owned clone's pull block and reports it as pull_blocked (logic in url-clone.ts urlClonePullBlock/urlClonePullBlockSummary); +6 GBRA-130 A-1: the extract phase warns on failed or breaker-stopped stale drain pages (logic in cycle/connector-extract.ts staleDrainFailures); +1 W1 belief ledger: the extract phase runs the sampled belief drift reconcile (logic in belief/coverage-report.ts); +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); 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; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224); +3 retrieval feedback retention in the purge phase (logic in feedback/store.ts pruneRetrievalFeedback); 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); +15 GBRA-49 temporal typed edges: edge_contradictions phase registration + dispatch block + extract-phase relationship sweep call (logic in cycle/edge-contradictions.ts, link-relationships.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; +1 fix wave 9 lane P (#5151): extract_facts phase passes drain so the facts watermark drain runs (logic in facts/reconcile-watermark.ts); +10 #6188: fence_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in cycle/fence-repair.ts); +19 fix wave 12 #6242: source cycles with brain-wide phases also take the shared gbrain-cycle lease (acquireDbCycleLock lease set, needsMaintenanceLease, skipBrainWidePhases, all-skipped deriveStatus case; lease logic in cycle/lock-set.ts); +16 #6377: content_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK), the REPAIR_LANE_PHASES dispatch helper shared with fence_repair (logic in cycle/content-repair.ts); +10 C4 pinned questions: standing_questions phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in questions/phase.ts); +11 #6696 (A5, A4): runCycle becomes the background-origin wrapper over runCycleUnscoped and adds the capacity notices (logic in persistence/admission-origin.ts, capacity-snapshot.ts) plus the CycleReport.notices interface field; +2 #6297: CycleOpts.directPhases (operator-named phases skip the patterns cadence); +5 #6865: unindexed_files phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its line in the REPAIR_LANE_PHASES dispatch helper (logic in cycle/unindexed-files.ts); +2 fix wave 20 #6954: the extract phase warns on extract_write_lost and its stale drain retries the pages left due; +5 #7241: CycleOpts.onPhaseStart and its best-effort call in timePhase, so the autopilot-cycle job writes its current phase to minion_jobs.progress
src/core/cycle/synthesize.ts 3240 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); lowered to 3200 by wave 9 lane W #5145: completion-key helpers (findLegacyCompletion, findSynthV2Completion, loadSuccessfulSynthesisKeys) peeled to synthesize-completion.ts with the new pre-triage partition; +13 P2 extraction.date_grounding: transcript observation date line instead of a run-date "Today's date" (config field + prompt arg); +1 fix wave 11 #6160: oneshot_task_prefixes on the child job data; +18 fix wave 12 #6069: unreliable-verdict backoff in runTriagePass (report code, pass backoff count, triage details entry; marker logic in triage-backoff.ts); +1 fix wave 12 #6242: SYNTH_PHASE_FAIL keeps an OperationError's suggestion and code (OperationError import); +3 wave 17 #6616: slug discovery and postprocessing share the canonical committed child outputs (loadCommittedSynthesisOutputs in synthesize-postprocess.ts; one call-site line, one parameter, one lookup line); lowered to 3224 by wave 17 #6642: the summary provenance section moved to summaryProvenanceLines in dream-provenance.ts; +6 GBRA-130 B-6 (#6860): surrogate-safe triage cuts (truncateUtf8) and the per-transcript verdict-cache write call site (logic in triage-backoff.ts VerdictCacheWrites); +2 GBRA-161 PR 4 (#7065): the synthesize phase activates each synthesized transcript's outputs as its generation (activateSynthesisGenerations import and call site; logic in cycle/synthesize-generations.ts); +8 GBRA-161 PR 5 (S-2): the dream summary publishes as a single-item dream_summary generation bound to its pre-run revision (publishSinglePage with a generation_fenced skip)
src/core/cycle/extract-atoms.ts 1658 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) is peeled into extract-atoms-parse.ts (-193, fix wave 10 lane B); +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); +17 #5031: same-page case-insensitive atom adoption fallback (one page-atom scan per source page per run); +12 P2 atomsPrompt helper: extraction.date_grounding source observation date + rule in the atoms prompt; +4 GBRA-75: octet_length-bounded body-length predicate (minCompiledTruthChars) for discovery and the backlog count; GBRA-130 A-42 (#6804): dot-led atom stems and the legacy-slug adoption guard
-src/core/engine.ts 2856 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +1 GBRA-49: LinkReadScope temporal opts on the link read contract; +4 #5984: upsertChunks sealChunkerVersion and createVersion preimage contract docs (round-trip diet); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2683 measured); +10 P7 relationalChainHop member + ChainHopOpts/ChainHopEdge imports (SQL in search/read-enrichment.ts); +14 contributor audit wave P0: listFactsKeyset member (delta facts keyset read contract) + FactRow.created_at_iso; +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 3 P2 speaker attribution: FactAttribution type + FactRow/NewFact.attributed_to fields + findCandidateDuplicates attributedTo option contract; +4 #5984 lane apply diet: setPageAliases inline option and upsertChunks pageId contract docs; +10 #6278: executeRaw timeoutMs contract (transaction-local statement_timeout for bounded preparation reads); +2 GBRA-69: replaceDerivedLinksBatch member; master v0.60.136.0 merge into #5575 memory trust (both sides kept); +6 GBRA-67: readPageSnapshotsBatch interface member (BrainEngine signatures cannot move); +1 GBRA-75 wave 10: optional findDuplicatePages member (batched findDuplicatePage, contract in engine-sql/pages.ts); +4 FactListOpts/TrajectoryOpts.excludePrivate fact-provenance visibility contract (interface fields cannot move); +18 GBRA-76: TransactionOptions (abort signal) interface and the transaction/transactionDirect signatures (abort logic in postgres-engine/transaction-abort.ts); +2 W14 P3.11 (#4381): LinkBatchInput.resolution_type on top of W13; +1 C2: findCandidateDuplicates arm:'keyword' contract doc (facts.candidate_fusion); re-summed at the master 6ccf30c3e merge (2708 integration + 2707 master - 2707 base); +5 Cat 40 Hard fix wave F2 (#6271): countKeywordPages/searchKeywordPages BrainEngine signatures (SQL in engine-sql/keyword-pages.ts); +6 W15 P1.2 (#6454): countStaleFrontmatterKeyPages/listStaleFrontmatterKeyPages/stripStaleFrontmatterKeys contract (SQL in engine-sql/pages.ts); +2 large pages Wave A sub-a: getChunkPage signature (get_chunks paging; SQL in engine-sql/chunks.ts); +5 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows signatures + type import (SQL in engine-sql/chunks.ts); +2 Cat 40 next wave part 1: non-ranking link types on the relationalFanout/relationalChainHop/getBacklinkCounts/getAdjacencyBoosts contract docs (policy in link-ranking-policy.ts; re-summed at the 0.60.242.0 merge: master 2794 + 2); +26 Wave B PR 1: segmented page storage members (allocateBodyOccurrenceIds..sweepSegments) + page-body type import (SQL in engine-sql/page-body.ts); merge v0.60.248.0: Wave B PR 1 and master growth compose at 2822; +1 LHF wave 2 item 1: executeRaw opts gain jitOff/prepare (the JIT-off typed-search type check; logic in ops/search-type-filter.ts); +9 PR2 fix lane X: BrainEngine.keywordBoundedRead, one unscoped read under the keyword statement bound for the segmented-region read (interface member and its doc cannot move): 2823 + 9; +9 GBRA-177: TakesListOpts.oldestFirst/sinceOnOrBefore/ungradedFirst for the grade_takes window (interface fields cannot move; SQL in engine-sql/takes.ts): 2832 + 9; +6 GBRA-156: TransactionOptions.pipelineFirst (the declaration goes out with BEGIN behind a transaction-mode pooler; predicate in persistence/protocol.ts); interface fields cannot move; +1 GBRA-161 PR 2: deprecation notes on insertFacts({ deleteForPageFirst }), deleteFactsForPage and expireFact (interface docs cannot move); +7 GBRA-156: TransactionOptions.pipelineEarly (search read bodies go out behind BEGIN; predicate in postgres-engine/search-settings.ts); interface fields cannot move
+src/core/engine.ts 2858 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +1 GBRA-49: LinkReadScope temporal opts on the link read contract; +4 #5984: upsertChunks sealChunkerVersion and createVersion preimage contract docs (round-trip diet); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2683 measured); +10 P7 relationalChainHop member + ChainHopOpts/ChainHopEdge imports (SQL in search/read-enrichment.ts); +14 contributor audit wave P0: listFactsKeyset member (delta facts keyset read contract) + FactRow.created_at_iso; +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 3 P2 speaker attribution: FactAttribution type + FactRow/NewFact.attributed_to fields + findCandidateDuplicates attributedTo option contract; +4 #5984 lane apply diet: setPageAliases inline option and upsertChunks pageId contract docs; +10 #6278: executeRaw timeoutMs contract (transaction-local statement_timeout for bounded preparation reads); +2 GBRA-69: replaceDerivedLinksBatch member; master v0.60.136.0 merge into #5575 memory trust (both sides kept); +6 GBRA-67: readPageSnapshotsBatch interface member (BrainEngine signatures cannot move); +1 GBRA-75 wave 10: optional findDuplicatePages member (batched findDuplicatePage, contract in engine-sql/pages.ts); +4 FactListOpts/TrajectoryOpts.excludePrivate fact-provenance visibility contract (interface fields cannot move); +18 GBRA-76: TransactionOptions (abort signal) interface and the transaction/transactionDirect signatures (abort logic in postgres-engine/transaction-abort.ts); +2 W14 P3.11 (#4381): LinkBatchInput.resolution_type on top of W13; +1 C2: findCandidateDuplicates arm:'keyword' contract doc (facts.candidate_fusion); re-summed at the master 6ccf30c3e merge (2708 integration + 2707 master - 2707 base); +5 Cat 40 Hard fix wave F2 (#6271): countKeywordPages/searchKeywordPages BrainEngine signatures (SQL in engine-sql/keyword-pages.ts); +6 W15 P1.2 (#6454): countStaleFrontmatterKeyPages/listStaleFrontmatterKeyPages/stripStaleFrontmatterKeys contract (SQL in engine-sql/pages.ts); +2 large pages Wave A sub-a: getChunkPage signature (get_chunks paging; SQL in engine-sql/chunks.ts); +5 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows signatures + type import (SQL in engine-sql/chunks.ts); +2 Cat 40 next wave part 1: non-ranking link types on the relationalFanout/relationalChainHop/getBacklinkCounts/getAdjacencyBoosts contract docs (policy in link-ranking-policy.ts; re-summed at the 0.60.242.0 merge: master 2794 + 2); +26 Wave B PR 1: segmented page storage members (allocateBodyOccurrenceIds..sweepSegments) + page-body type import (SQL in engine-sql/page-body.ts); merge v0.60.248.0: Wave B PR 1 and master growth compose at 2822; +1 LHF wave 2 item 1: executeRaw opts gain jitOff/prepare (the JIT-off typed-search type check; logic in ops/search-type-filter.ts); +9 PR2 fix lane X: BrainEngine.keywordBoundedRead, one unscoped read under the keyword statement bound for the segmented-region read (interface member and its doc cannot move): 2823 + 9; +9 GBRA-177: TakesListOpts.oldestFirst/sinceOnOrBefore/ungradedFirst for the grade_takes window (interface fields cannot move; SQL in engine-sql/takes.ts): 2832 + 9; +6 GBRA-156: TransactionOptions.pipelineFirst (the declaration goes out with BEGIN behind a transaction-mode pooler; predicate in persistence/protocol.ts); interface fields cannot move; +1 GBRA-161 PR 2: deprecation notes on insertFacts({ deleteForPageFirst }), deleteFactsForPage and expireFact (interface docs cannot move); +7 GBRA-156: TransactionOptions.pipelineEarly (search read bodies go out behind BEGIN; predicate in postgres-engine/search-settings.ts); interface fields cannot move; +2 GBRA-156: TransactionOptions.readOnly (search read transactions open BEGIN READ ONLY; 2858 measured)
src/core/import-file.ts 2075 ratchet +2 W1 belief ledger: the legacy import is an unmanaged projection point (logic in belief/projection-point.ts); +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts); +1 F1c: direct imports run in maintenanceTransaction (write attribution; helper in persistence/attribution.ts); lowered to 2178: #5988 content screen and content-sanity config peeled to core/import-screen.ts; +1 #6007: the prepared apply returns its page id and seal (PreparedImportApplied); +1 #5333: trusted imports drop a stale oversized embed_skip/content_flag the gate no longer sets, and an embed_skip transition defeats both unchanged fast paths; wave 10 collector: lane E (#5333) and the other lanes compose at 2183; grown #6188 (+17): fence options interface, result fields and the Tier 1 step call (logic in fence-repair/import-step.ts); +2 #5984 single-write fast path: the coordinated existingSnapshot option (interface field) composes with the lane apply diet at 2202; +1 GBRA-69: a coordinated apply defers its chunker seal to the caller (sealImportedPage in page-state/projections.ts); lowered to 2023: #5001 the edge-mapping loop moved to code-chunks.ts mapCodeEdges (shared with the prepared apply); W14 P3.13 (#5001) lowered 2049→2023 by moving the edge loop to mapCodeEdges; +2 W13 PR1 on top (2025 measured); +2 #6529: the unchanged-image skip path records source_path (refreshSourcePath, as #4588 does for Markdown); +4 large pages A6/T33: code files keep CODE_FILE_MAX_BYTES, a page over PAGE_INLINE_MAX_BYTES commits with NULL vectors for the metered stale sweep; +1 #6722: an embed_skip page is chunked and never embedded (noEmbed folds the marker); merge v0.60.240.0: large pages and master growth compose at 2032; +24 Wave B lane 1d: the segmented storage step (stage before publication, flip in the apply, seal and post-commit projection; logic in persistence/segmented-apply.ts and page-body/ingest.ts) and the streamed-import dispatch over the single-string ceiling (logic in page-body/streamed-import.ts); merge v0.60.248.0: Wave B PR 1 and master growth compose at 2056; +4 Wave B review: a rename re-preparation reuses the staged segmented body (reuseSegments option) and the remote fence merge reads an unread body as fence-free (fenceBody in page-body/page-shape.ts); +2 Wave B gem A: a coordinated demotion versions the segmented page before demoting it (createVersion order); lanes compose at 2062; +2 Wave B lane 2q: ImportResult.searchable (interface field; the value comes from SegmentedImport.afterCommit);+2: pre-publication withdrawal validation; +9 #7172: kept chunk rows move to their new index and a bounded managed publication defers its chunk replacement (logic in page-state/chunk-moves.ts and page-state/projections.ts continueDeferredProjection); merge v0.60.332.0: #7172 and master growth compose at 2075
src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullable
src/core/operations.ts 244 ratchet +1 #7168: graphRankOperations import (ops/graph-rank.ts; spread shares the orphans line); peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts); +2 retrieval feedback: feedbackOperations import and spread (ops/feedback.ts); +1 #6007: pageBatchOperations import (spread shares the pages line); +1 P5: wanted_pages area row; lowered GBRA-75 W11 cold start: OP_AREAS + finalize step moved to operation-load.ts (shared with the CLI per-op loader); +1 C4 pinned questions: questionsOperations import and spread (ops/questions.ts; its areas live in operation-load.ts OP_AREAS); +1 Wave B append: pageAppendOperations import (spread shares the pages line); +1 Wave B upload sessions: pageUploadOperations import (spread shares the pages line); +1 #7191: search-exact import
src/core/pglite-engine.ts 3087 ratchet +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +5 GBRA-67: readPageSnapshotsBatch delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages delegate (SQL in engine-sql/pages.ts); +2 GBRA-76: transaction/transactionDirect take TransactionOptions and refuse an already-aborted signal before BEGIN; +2 #4772 (W14 PR3): entityTypes HealthDeps delegate + import (policy in schema-pack/entity-types.ts, SQL in engine-sql/health.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3023 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates (SQL in engine-sql/pages.ts); +6 large pages Wave A sub-a: getChunkPage delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their imports; +7 LHF wave 2 item 5: request config snapshot delegate lines in getConfig/getAllConfig/setConfig/unsetConfig (logic in config-snapshot.ts); +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move); integrated at the Wave B PR 2 master merge (v0.60.264.0): master 3072 + 3; +5 PR2 fix lane X: keywordBoundedRead runs the read on the engine itself (engine methods cannot move): 3075 + 5; +2 GBRA-130 B-6 (#6860): putDreamVerdict passes its payload through wellFormedJson (engine methods cannot move); +1 GBRA-130 A-1: held option on the stale-page list/count signatures (SQL in engine-sql/pages.ts); +1 GBRA-130 integration: the A-1 (links_extract_failure) and B-6 (wellFormedJson putDreamVerdict) engine hunks composed at the lane merge; +2 #6948: putPage runs assertOriginUnclaimed in its page transaction and restorePage runs assertRevivalUnclaimed (logic in persistence/origin-guard.ts; engine methods cannot move): 3080 + 2; GBRA-130 composed with #6948 at the master 0e0cd27b merge: re-summed to the merged line count (3085); +2 #7159: the frontmatter where clause in searchKeyword and its import (SQL in search/frontmatter-where.ts; engine methods cannot move)
-src/core/postgres-engine.ts 3137 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +1 #5984 single-write fast path composes with the lane apply diet at 2944; +2 #5984 shared parameter types: the instance pool passes shared_types and initSchema clears them after migrations (helpers in db.ts); +2 #6276: the remote alias-resolving readPageSnapshot runs with JIT off (withScopedReadTransaction jitOff); +5 #6278: executeRaw timeoutMs delegate (statement in postgres-engine/bounded-statement.ts); +23 #6278 PR 1.5: cancelSettleMs() and the settle timer in runUnsafe that discards a reserved connection whose cancel a transaction-mode pooler never completed; +3 #6317 lane 2: getPoolDiagnostics().pool from the vendored driver (postgres-engine/pool-stats.ts) and the prepare mark; +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +1 GBRA-69 extract batching: replaceDerivedLinksBatch delegate (batch logic in derived-links.ts); +9 GBRA-75: getBacklinkCounts and getHealth statements run JIT-off through the private jitOffRead transaction helper (engine methods cannot move); +3 GBRA-75 wave 7: searchKeyword and searchVector start the once-per-engine background search statistics guard (logic in search/projection-statistics.ts); +7 GBRA-67: readPageSnapshotsBatch scoped-read delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages scoped-read delegate (SQL in engine-sql/pages.ts); +7 #6383: poolIncidents hooks on the instance/module/connection-manager pools (counter and lines in pool-gauge.ts, budget in db.ts) and stuckDiscards/buildFailures in getPoolDiagnostics; +3 GBRA-76: transaction/transactionDirect take TransactionOptions; transactionOn attaches the begin handle to withTransactionAbort (logic in postgres-engine/transaction-abort.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +1 #5227: schema.sql replay under withSchemaLockTimeout (wave 14 PR1); +1 driver desync tripwire: desyncDiscards in getPoolDiagnostics (counter and line in pool-gauge.ts); +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages scoped-read delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3027 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates, reads scoped (SQL in engine-sql/pages.ts); +12 wave 16 G5.1 (#6495): keywordStatementTimeout memo field, its connect/disconnect resets and the keywordStatementTimeoutSetting accessor, plus one awaited setting per keyword/chunk/CJK transaction (resolver in postgres-engine/keyword-statement-timeout.ts); wave 16 G5.1 gate fix: keywordStatementTimeoutSetting resolves the knob once per connection on the first keyword statement from the saved connect config (connect issues no statement for it; 3042 measured); +7 large pages Wave A sub-a: getChunkPage scoped-read delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their imports; +3 wave 18b lane 2 (#6495): keywordTimeouts negative-cache field and the searchKeyword runner wrap (logic in postgres-engine/keyword-timeout-cache.ts); integrated at wave 18b: master 3082 + 3; +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move); integrated at the Wave B PR 2 master merge (v0.60.264.0): master 3085 + 3; +3 PR2 fix lane E (E1): getChunks/getChunkPage/getChunkWindows run the manifest privilege probe in their scoped transaction (chunkManifestReads in search/safe-chunks.ts); integrated at the lane E merge onto b75a69a6d: 3088 + 3; +6 PR2 fix lane X: searchVector, explainVectorSearch, the hasMore witness and runVectorAttempt pick the chunk-manifest statement form inside each bounded attempt transaction, so its statement_timeout bounds the probe (form memo vectorStatementForms in search/vector-statement.ts; engine methods cannot move): 3091 + 6; +5 PR2 fix lane X: keywordBoundedRead runs the read in withScopedReadTransaction under the keyword statement timeout setting (engine methods cannot move): 3097 + 5; +2 GBRA-130 B-6 (#6860): putDreamVerdict passes its payload through wellFormedJson (engine methods cannot move); +1 GBRA-130 A-1: held option on the stale-page list/count signatures (SQL in engine-sql/pages.ts); +1 GBRA-130 integration: the A-1 (links_extract_failure) and B-6 (wellFormedJson putDreamVerdict) engine hunks composed at the lane merge; +2 #6948: putPage runs assertOriginUnclaimed in its page transaction and restorePage runs assertRevivalUnclaimed (logic in persistence/origin-guard.ts; engine methods cannot move): 3102 + 2; GBRA-130 composed with #6948 at the master 0e0cd27b merge: re-summed to the merged line count (3107); +3 #7159: the frontmatter where clause in the two keyword typesClause sites and its import (SQL in search/frontmatter-where.ts; engine methods cannot move); GBRA-156 retrieval wave (#7201) composed with #7194 at the merge: re-summed (3114 measured); +2 warm CLI socket (#7218): connectedDatabaseUrl getter (the URL the engine connected with, bound into the socket identity), composed over the GBRA-156 retrieval wave (3116 measured); +1 GBRA-133 PR 2b: transactionOn hands the outermost transaction its commit checks (page-state/transactions.ts withCommitChecks), composed with the warm CLI socket at the merge (3117 measured); +18 GBRA-156: the private readTransaction helper behind withScopedReadTransaction and jitOffRead answers a top-level read before its COMMIT settles (engine methods cannot move; 3135 measured); +1 GBRA-156: transactionOn and runUnsafe hold a per-search connection slot (import of search/connection-budget.ts; 3136 measured); +2 GBRA-156: transactionOn passes TransactionOptions.pipelineFirst to the pool begin as { first } (driver gate in vendor/postgres index.js begin); an engine method cannot move; composed with the warm CLI socket and GBRA-133 PR 2b at the master v0.60.344.0 merge (3119 measured); GBRA-151 #7183/#7187/#7188 re-summed at the v0.60.402.0 merge (3135 measured); +2 #7183 (GBRA-151) at the v0.60.412.0 merge: read-write-transactions import and transactionOn wraps its connection in readWriteTransactions (logic in postgres-engine/read-write-transactions.ts; engine methods cannot move): 3135 + 2
+src/core/postgres-engine.ts 3143 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +1 #5984 single-write fast path composes with the lane apply diet at 2944; +2 #5984 shared parameter types: the instance pool passes shared_types and initSchema clears them after migrations (helpers in db.ts); +2 #6276: the remote alias-resolving readPageSnapshot runs with JIT off (withScopedReadTransaction jitOff); +5 #6278: executeRaw timeoutMs delegate (statement in postgres-engine/bounded-statement.ts); +23 #6278 PR 1.5: cancelSettleMs() and the settle timer in runUnsafe that discards a reserved connection whose cancel a transaction-mode pooler never completed; +3 #6317 lane 2: getPoolDiagnostics().pool from the vendored driver (postgres-engine/pool-stats.ts) and the prepare mark; +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +1 GBRA-69 extract batching: replaceDerivedLinksBatch delegate (batch logic in derived-links.ts); +9 GBRA-75: getBacklinkCounts and getHealth statements run JIT-off through the private jitOffRead transaction helper (engine methods cannot move); +3 GBRA-75 wave 7: searchKeyword and searchVector start the once-per-engine background search statistics guard (logic in search/projection-statistics.ts); +7 GBRA-67: readPageSnapshotsBatch scoped-read delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages scoped-read delegate (SQL in engine-sql/pages.ts); +7 #6383: poolIncidents hooks on the instance/module/connection-manager pools (counter and lines in pool-gauge.ts, budget in db.ts) and stuckDiscards/buildFailures in getPoolDiagnostics; +3 GBRA-76: transaction/transactionDirect take TransactionOptions; transactionOn attaches the begin handle to withTransactionAbort (logic in postgres-engine/transaction-abort.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +1 #5227: schema.sql replay under withSchemaLockTimeout (wave 14 PR1); +1 driver desync tripwire: desyncDiscards in getPoolDiagnostics (counter and line in pool-gauge.ts); +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages scoped-read delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3027 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates, reads scoped (SQL in engine-sql/pages.ts); +12 wave 16 G5.1 (#6495): keywordStatementTimeout memo field, its connect/disconnect resets and the keywordStatementTimeoutSetting accessor, plus one awaited setting per keyword/chunk/CJK transaction (resolver in postgres-engine/keyword-statement-timeout.ts); wave 16 G5.1 gate fix: keywordStatementTimeoutSetting resolves the knob once per connection on the first keyword statement from the saved connect config (connect issues no statement for it; 3042 measured); +7 large pages Wave A sub-a: getChunkPage scoped-read delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their imports; +3 wave 18b lane 2 (#6495): keywordTimeouts negative-cache field and the searchKeyword runner wrap (logic in postgres-engine/keyword-timeout-cache.ts); integrated at wave 18b: master 3082 + 3; +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move); integrated at the Wave B PR 2 master merge (v0.60.264.0): master 3085 + 3; +3 PR2 fix lane E (E1): getChunks/getChunkPage/getChunkWindows run the manifest privilege probe in their scoped transaction (chunkManifestReads in search/safe-chunks.ts); integrated at the lane E merge onto b75a69a6d: 3088 + 3; +6 PR2 fix lane X: searchVector, explainVectorSearch, the hasMore witness and runVectorAttempt pick the chunk-manifest statement form inside each bounded attempt transaction, so its statement_timeout bounds the probe (form memo vectorStatementForms in search/vector-statement.ts; engine methods cannot move): 3091 + 6; +5 PR2 fix lane X: keywordBoundedRead runs the read in withScopedReadTransaction under the keyword statement timeout setting (engine methods cannot move): 3097 + 5; +2 GBRA-130 B-6 (#6860): putDreamVerdict passes its payload through wellFormedJson (engine methods cannot move); +1 GBRA-130 A-1: held option on the stale-page list/count signatures (SQL in engine-sql/pages.ts); +1 GBRA-130 integration: the A-1 (links_extract_failure) and B-6 (wellFormedJson putDreamVerdict) engine hunks composed at the lane merge; +2 #6948: putPage runs assertOriginUnclaimed in its page transaction and restorePage runs assertRevivalUnclaimed (logic in persistence/origin-guard.ts; engine methods cannot move): 3102 + 2; GBRA-130 composed with #6948 at the master 0e0cd27b merge: re-summed to the merged line count (3107); +3 #7159: the frontmatter where clause in the two keyword typesClause sites and its import (SQL in search/frontmatter-where.ts; engine methods cannot move); GBRA-156 retrieval wave (#7201) composed with #7194 at the merge: re-summed (3114 measured); +2 warm CLI socket (#7218): connectedDatabaseUrl getter (the URL the engine connected with, bound into the socket identity), composed over the GBRA-156 retrieval wave (3116 measured); +1 GBRA-133 PR 2b: transactionOn hands the outermost transaction its commit checks (page-state/transactions.ts withCommitChecks), composed with the warm CLI socket at the merge (3117 measured); +18 GBRA-156: the private readTransaction helper behind withScopedReadTransaction and jitOffRead answers a top-level read before its COMMIT settles (engine methods cannot move; 3135 measured); +1 GBRA-156: transactionOn and runUnsafe hold a per-search connection slot (import of search/connection-budget.ts; 3136 measured); +2 GBRA-156: transactionOn passes TransactionOptions.pipelineFirst to the pool begin as { first } (driver gate in vendor/postgres index.js begin); an engine method cannot move; composed with the warm CLI socket and GBRA-133 PR 2b at the master v0.60.344.0 merge (3119 measured); GBRA-151 #7183/#7187/#7188 re-summed at the v0.60.402.0 merge (3135 measured); +2 #7183 (GBRA-151) at the v0.60.412.0 merge: read-write-transactions import and transactionOn wraps its connection in readWriteTransactions (logic in postgres-engine/read-write-transactions.ts; engine methods cannot move): 3135 + 2; +6 GBRA-156: transactionOn opens readOnly transactions as BEGIN READ ONLY and a top-level read inherits its request signal, runUnsafe refuses an aborted request (logic in request-signal.ts; engine methods cannot move): 3137 + 6
src/core/search/hybrid.ts 1562 ratchet +5 GBRA-81 item 5 per-stage search timings: HybridSearchOpts._timings (interface field) and the timer bindings and import in hybridSearch/hybridSearchCached (collector logic in search/stage-timings.ts); +2 W5 page-unit ranking cut: HybridSearchOpts.pageRankCut (logic in search/page-rank-cut.ts); +9 W3 confidence-gated reranking: HybridSearchOpts.rerankGate and the gate/lookup threading through rerankAndPin and sizeReturnPool (logic in search/hybrid/rerank-gate.ts, crag.ts gradePreRerank); re-summed at the W3 merge onto master v0.60.168.0 (1641 measured); +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key; +5 green master wave (embedding opt-out): HybridSearchOpts._embeddingOptedOut (interface field) read once per request and threaded to the cache-lookup embed and the keyword-only gate; +24 P2 explain RRF attribution stamp in rrfFusionWeighted, backlink_count stamp, explain_target stage observations, explain/explainTarget opts; +14 fix wave 13 P4.8 #6400: lazyQueryEmbedDeadline (the query-embed deadline starts when the embed starts) and the _queryEmbedDeadline getter; +1 query facts arm: HybridSearchOpts.onQueryEmbedding (interface field; its one-line call is paid inside the ceiling) after the vector arms, so the facts arm reuses the query embedding without a second model call; re-summed at the master a08578ca5 merge (1591 master lines + 3 integration lines: the onQueryEmbedding hook); lowered to 1562: LHF wave 2 item 3 peeled cosineReScore into search/cosine-rescore.ts
src/core/types.ts 2347 ratchet +4 Wave B PR 1 (1c): Page.body_storage/body_bytes (interface fields; guard logic in page-body/page-shape.ts); +8 W3 confidence-gated reranking: HybridSearchMeta.rerank_gate (RerankGateMeta in search/hybrid/rerank-gate.ts); re-summed at the W3 merge onto master v0.60.168.0 (2279 measured); +7 fix wave 11 W6.2/W6.3 (#5989, #6132): SearchOpts.hnswIterativeScan and cjkKeyword, the keyword_candidates_incomplete stage and HybridSearchMeta.keyword_candidates (logic in engine-sql/cjk-search.ts); +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +6 retrieval feedback: SearchResult feedback_boost/content_hash/relational_path_edges stamps and RelationalFanoutRow.path_edges (interface fields); +2 RelationalFanoutOpts.wide (interface field); 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); +1 green master wave: embedding_disabled degraded reason (closed vocabulary); +2 #5951: Chunk.source_id (get_chunks names each row's source); 1 P2 SearchResult explain fields (rrf attribution, blend_norm_rrf, score_details, backlink_count) + RrfAttribution (interface fields); +11 #5575 (L1b): PageReadScope minTrust/suppressFlagged, SearchResult trust_tier/origin/unconfirmed, TimelineOpts eligibility (interface fields cannot move); +8 #4772 (W14 PR3): BrainHealth.entity_types_status field (interface fields cannot move); +1 C4: question page type row; +6 entity anchoring: optional SearchResult.entity_anchored row stamp (logic in search/entity-anchor.ts); +4 query facts arm: optional SearchResult.fact_row and superseded_claim row fields (logic in search/facts-arm.ts); +2 query facts arm: SearchResult result_type/fact_id/page_slug/follow_up (fact rows are never page-shaped); +9 Cat 40 Hard fix wave (#6271): SearchResult matched_alias/evidence_omitted/provenance, SearchOpts.rankQuery, keyword_count_unavailable stage and rerank_failed reasons; +12 fix wave 15 P2.1 (#6500): PageFilters.slugAfter (single-source slug keyset, interface field + doc) and the updated_desc tiebreaker comment (the keyset walk lives in facts/conversation-enumeration.ts); +2 wave 16 G5.1 (#6495): EngineConfig.keyword_statement_timeout_ms (interface field + doc); +2 GBRA-92: EngineConfig.pglite_shared_buffers (interface field + doc); +11 large pages (Wave A): Chunk/ChunkInput projected_byte_start/end interface fields (span logic in chunkers/recursive.ts, page-window/document.ts); +4 wave 18b lane 2 (#6495): SearchOpts.keywordTimeoutCache, the skipped_after_timeout degraded reason and the useCache doc line; integrated at wave 18b: master 2319 + 4; +2 LHF wave 2 item 3: retrieval meta cosine_rescore field (js_fallback disclosure; logic in search/cosine-rescore.ts); +14 GBRA-154 ranking wave (#4612 #7153 #7156 #7162 #7164): SearchResult collapsed/redirect_to/image_page/rank_prior/rank_score/fused_score stamps and HybridSearchMeta.collapse (interface fields; logic in search/collapse.ts, rank-priors.ts, score-contract.ts); GBRA-151 retrieval P0 x operability wave merge: both sides grew the file, re-summed (2343 measured); GBRA-156 retrieval wave (#7201) composed with #7194 at the merge: re-summed (2345 measured); GBRA-151 #7147 follow-up re-summed at the v0.60.338.0 merge (2347 measured)
src/core/minions/queue.ts 2544 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keys; +18 Lane D: deferJob (a deferral returns a job to delayed with no attempt counted and no stacktrace growth); the ceiling had 17 lines of slack; +5 agent operator follow-up Item 5 merged over master: claim-time spend fence token and legacy_default stamp (logic in minions/spend-authorization.ts); +5 GBRA-130 A-30: claim excludeWatchdogSuspects option (signature, doc and the mark parameter), the releaseWatchdogClaim delegate, and the co-runner stall call site in handleStalled (logic in minions/watchdog-attribution.ts); +5 GBRA-158 #7239/#7240: failJob result parameter (the #7216 hunk), jsonbSafeJson import and its call in add (sanitizer in text-safe.ts); +2 #7242 lane reservation: claim excludeNames option (doc line and the bound array; policy in minions/lanes.ts); +1 #7241 submitter label import (job-insight.ts) + 1 queue-families type import; #7252 x #7249 merge: both sides grew the file, re-summed (2544 measured)
diff --git a/src/cli/cli-socket-client.ts b/src/cli/cli-socket-client.ts
index 2dea8dfbc9..391cdcd13b 100644
--- a/src/cli/cli-socket-client.ts
+++ b/src/cli/cli-socket-client.ts
@@ -5,7 +5,8 @@
* answers, the CLI prints that answer with the cold path's own renderer and
* exit codes. A missing, unsafe, stale, busy, refusing or dying socket returns
* false and the cold path runs as if the socket did not exist (a note goes to
- * stderr only with GBRAIN_DEBUG=1). GBRAIN_CLI_SOCKET=0 skips the socket.
+ * stderr only with GBRAIN_DEBUG=1, except an identity refusal, which always
+ * prints a degraded notice). GBRAIN_CLI_SOCKET=0 skips the socket.
*/
import net from 'node:net';
import { format } from 'node:util';
@@ -19,8 +20,9 @@ import { cliSocketIdentity } from '../core/cli-socket/identity.ts';
import { peerCredSupport, peerUid, type PeerCredSupport } from '../core/cli-socket/peer-cred.ts';
import {
CONNECT_TIMEOUT_MS, DEFAULT_READ_WALLCLOCK_MS, FrameReader, HANDSHAKE_TIMEOUT_MS, isHandshakeFrame, isResultFrame, MAX_RESPONSE_BYTES,
- MAX_ROUND_TRIP_MS, reviveOperationError, type CliSocketOp, type CliSocketRequest, type OutputChunk, type ResultFrame,
+ MAX_ROUND_TRIP_MS, reviveOperationError, warmRoundTripTimeout, type CliSocketOp, type CliSocketRequest, type OutputChunk, type ResultFrame,
} from '../core/cli-socket/protocol.ts';
+import type { OperationError } from '../core/ops/contract.ts';
export const CLI_SOCKET_COMMANDS: readonly string[] = ['search', 'query', 'get', 'recall'];
const SOCKET_OPS: Record<string, CliSocketOp> = { search: 'search', query: 'query', get_page: 'get_page' };
@@ -29,6 +31,39 @@ function debug(reason: string): void {
if (process.env.GBRAIN_DEBUG === '1') process.stderr.write(`[cli-socket] cold path: ${reason}\n`);
}
+/**
+ * A refusal by identity is never silent (GBRA-156): every call from an environment that differs from the serve's
+ * takes the slower cold path until that part matches, so the CLI prints a degraded notice naming the part (never its
+ * value) whether or not GBRAIN_DEBUG is set. The serve counts the refusal for doctor `cli_socket_refusals`.
+ */
+export async function noteCliSocketRefusal(reason: string): Promise<void> {
+ const refused = /^refused \(identity_mismatch\)(?:: (.+))?$/.exec(reason);
+ if (!refused) return;
+ const part = refused[1] ?? 'its identity';
+ const { writeCliNotices } = await import('../core/interop-notices.ts');
+ writeCliNotices([{ code: 'socket_identity_mismatch', kind: 'degraded',
+ why: `The running serve's warm CLI socket refused this call because ${part} differs from the serve's (the value is never shown), so it ran on the slower cold path. Every call from this environment does until that part matches the serve's.`,
+ fix: { argv: ['gbrain', 'doctor', '--only', 'cli_socket_refusals', '--json'], consent: [], actor: 'agent', requires_exclusive: false, docs: 'docs/guides/cli-socket.md',
+ why: 'Read-only: names each identity part the serve refused and how often; run the caller with the serve\'s value, or restart the serve with the caller\'s.' } }]);
+}
+
+const isRoundTripTimeout = (fields: Record<string, unknown>) => fields.code === 'timeout' && fields.reason === 'cli_socket_round_trip_cap';
+
+/**
+ * GBRA-156: a warm call that reached its round-trip cap prints a retryable `timeout` error and exits 124 instead of
+ * starting over on the cold path. The envelope goes to stdout under --json and the human line to stderr, as every CLI
+ * error does; without --json an [AGENT] block also goes to stdout, so a caller that discards stderr still sees why.
+ */
+export async function writeWarmTimeout(error: OperationError, command: string): Promise<true> {
+ const { writeCliError } = await import('./cli-error.ts');
+ const { setCliExitVerdict, jsonRequested } = await import('../core/cli-force-exit.ts');
+ const { agentBlock } = await import('../core/agent-markers.ts');
+ const exit = writeCliError(error, command);
+ if (!jsonRequested(process.argv.slice(2))) process.stdout.write(agentBlock({ why: `[timeout] ${error.message}`, next: 'wait: retry the same command' }));
+ setCliExitVerdict(exit);
+ return true;
+}
+
function debugWarm(command: string, path: string): void {
if (process.env.GBRAIN_DEBUG === '1') process.stderr.write(`[cli-socket] warm: ${command} answered by the serve socket at ${path}\n`);
}
@@ -166,6 +201,7 @@ export async function renderOp(command: string, op: OperationMeta, params: Recor
const { applyCliOpNotices, captureOpNotice } = await import('./op-notices.ts');
const { setCliExitVerdict, writeStdoutFinal } = await import('../core/cli-force-exit.ts');
await noteSource(frame);
+ if (frame.kind === 'error' && isRoundTripTimeout(frame.error)) { await replay(frame); return writeWarmTimeout(reviveOperationError(frame.error), command); }
if (frame.kind === 'error') {
const { writeCliError } = await import('./cli-error.ts');
const rendered = await buffered(() => writeCliError(reviveOperationError(frame.error), command));
@@ -236,11 +272,17 @@ export async function maybeServeFromCliSocket(command: string, args: string[]):
if (!recall.isRecallVerbForm(flags)) return false;
if (!recall.isOneShotRecall(flags)) recall.validateAndNormalizeFlags(flags);
const outcome = await exchangeCliSocket(path, { ...base, kind: 'recall', args }, resultTimeoutMs);
- if ('reason' in outcome) { debug(outcome.reason); return false; }
+ if ('reason' in outcome) {
+ await noteCliSocketRefusal(outcome.reason);
+ if (outcome.reason === 'round_trip_timeout') return writeWarmTimeout(warmRoundTripTimeout(command, resultTimeoutMs, 'cli'), command);
+ debug(outcome.reason);
+ return false;
+ }
if (outcome.frame.kind === 'fallback') { debug(outcome.frame.reason); return false; }
const frame = outcome.frame;
debugWarm(command, path);
await noteSource(frame);
+ if (frame.kind === 'error' && isRoundTripTimeout(frame.error)) { await replay(frame); return writeWarmTimeout(reviveOperationError(frame.error), command); }
if (frame.kind === 'error' && !recall.isOneShotRecall(flags)) { await replay(frame); throw reviveOperationError(frame.error); }
const { writeCliNotices } = await import('../core/interop-notices.ts');
const rendered = await buffered(async () => {
@@ -257,7 +299,12 @@ export async function maybeServeFromCliSocket(command: string, args: string[]):
const prepared = await opRequest(command, args);
if (typeof prepared === 'string') { debug(prepared); return false; }
const outcome = await exchangeCliSocket(path, { ...base, kind: 'op', op: SOCKET_OPS[prepared.op.name]!, params: prepared.params }, resultTimeoutMs);
- if ('reason' in outcome) { debug(outcome.reason); return false; }
+ if ('reason' in outcome) {
+ await noteCliSocketRefusal(outcome.reason);
+ if (outcome.reason === 'round_trip_timeout') return writeWarmTimeout(warmRoundTripTimeout(command, resultTimeoutMs, 'cli'), command);
+ debug(outcome.reason);
+ return false;
+ }
if (outcome.frame.kind === 'fallback') { debug(outcome.frame.reason); return false; }
debugWarm(command, path);
return renderOp(command, prepared.op, prepared.params, outcome.frame);
diff --git a/src/commands/doctor/checks/cli-socket-refusals.ts b/src/commands/doctor/checks/cli-socket-refusals.ts
new file mode 100644
index 0000000000..c123edbb9a
--- /dev/null
+++ b/src/commands/doctor/checks/cli-socket-refusals.ts
@@ -0,0 +1,36 @@
+/**
+ * cli_socket_refusals (GBRA-156): warns while the warm CLI socket refused CLI calls in the last 24 hours. A refused
+ * call is answered by the CLI's own cold path, several times slower, and a caller whose environment differs from the
+ * serve's (a cron, another agent harness) is refused on every call. The serve counts refusals by the identity part
+ * that differed, never its value (core/cli-socket/refusals.ts). Read-only; reads one file in the run directory.
+ */
+import type { Check } from '../../doctor.ts';
+import type { DoctorContext, DoctorEntry } from '../context.ts';
+import { configDir } from '../../../core/config.ts';
+import { cliSocketDir } from '../../../core/cli-socket/fs-guard.ts';
+import { readRefusals } from '../../../core/cli-socket/refusals.ts';
+
+const WINDOW_MS = 24 * 60 * 60 * 1000;
+const DOCS = 'docs/guides/cli-socket.md';
+
+async function runCliSocketRefusals(_ctx: DoctorContext): Promise<Check[]> {
+ const checks: Check[] = [];
+ const record = readRefusals(cliSocketDir(configDir()));
+ const since = Date.now() - WINDOW_MS;
+ const recent = Object.entries(record?.parts ?? {}).filter(([, part]) => Date.parse(part.last_at) >= since).sort((a, b) => b[1].count - a[1].count);
+ if (recent.length === 0) {
+ checks.push({ name: 'cli_socket_refusals', status: 'ok', details: { refusals: 0, docs: DOCS }, message: 'The warm CLI socket refused no CLI call in the last 24 hours.' });
+ return checks;
+ }
+ const total = recent.reduce((n, [, part]) => n + part.count, 0);
+ checks.push({ name: 'cli_socket_refusals', status: 'warn',
+ details: { refusals: total, serve_pid: record!.pid, serve_started_at: record!.started_at, parts: Object.fromEntries(recent), docs: DOCS },
+ message: `The warm CLI socket refused ${total} CLI call(s) since ${recent.map(([, p]) => p.first_at).sort()[0]}, so each ran on the slower cold path: `
+ + recent.map(([name, part]) => `${name} differs from the serve's (${part.count}, last ${part.last_at})`).join('; ')
+ + '. Run the caller with the same value as the serve (or restart the serve with the caller\'s), then the calls are answered warm. Values are never recorded.',
+ fix: { argv: ['gbrain', 'doctor', '--only', 'cli_socket_refusals', '--json'], consent: [], actor: 'agent', requires_exclusive: false, docs: DOCS,
+ why: 'Read-only: names each identity part that differed and how often; align that part between the caller and the serve.' } });
+ return checks;
+}
+
+export const cliSocketRefusalsEntry: DoctorEntry = { name: 'cli_socket_refusals', emits: ['cli_socket_refusals'], run: runCliSocketRefusals };
diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.ts
index 59de739198..cb6198e38c 100644
--- a/src/commands/doctor/registry.ts
+++ b/src/commands/doctor/registry.ts
@@ -95,6 +95,7 @@ import { grantNewOpsEntry } from './checks/grant-new-ops.ts';
import { linksExtractionLagEntry, syncFreshnessEntry, searchModeEntry } from './checks/sync-search.ts';
import { persistenceConsumersEntry, serveBuildDriftEntry } from './checks/persistence-consumers.ts';
import { runtimeBuildSkewEntry } from './checks/runtime-build-skew.ts';
+import { cliSocketRefusalsEntry } from './checks/cli-socket-refusals.ts';
import { gitConvergenceEntry } from './checks/git-convergence.ts';
import { gitWriterEntry } from './checks/git-writer.ts';
import { retrievalFeedbackEntry } from './checks/retrieval-feedback.ts';
@@ -267,6 +268,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [
coreMemoryEntry,
persistenceConsumersEntry,
runtimeBuildSkewEntry,
+ cliSocketRefusalsEntry,
atomHeldFailedEntry,
extractionInputTruncatedEntry,
ghostPagesEntry,
diff --git a/src/commands/serve.ts b/src/commands/serve.ts
index 5698f51441..19b05451fb 100644
--- a/src/commands/serve.ts
+++ b/src/commands/serve.ts
@@ -14,6 +14,7 @@ import { startFactsDrainScheduler, type FactsDrainScheduler, type FactsDrainSche
import { startMovementWatch, type MovementWatch } from '../core/persistence/sync-movement.ts';
import { startServeHeadWatcher } from '../core/serve-head-watcher.ts';
import { onForwardProgress } from '../core/forward-progress.ts';
+import { foregroundWindow } from '../core/foreground-activity.ts';
import { graduationHandoffRequested, writeServeGraduationEnvelope } from '../core/persistence/graduation-serve-guard.ts';
import {
installLoopStallWatchdog,
@@ -69,6 +70,18 @@ const PARENT_WATCHDOG_INTERVAL_MS = 5_000;
// sweep fires after 10–20 min of true inactivity — the armIdle re-arm
// semantics expressed through the injectable deps.setInterval seam.
const IDLE_SWEEP_INTERVAL_MS = 10 * 60_000;
+/** GBRA-156: GBRAIN_SWEEP_IDLE_INTERVAL_MS shortens the cadence for benchmarks that force a sweep beside searches (scripts/bench/production-soak/socket-probe.ts); at least 1 s. */
+function idleSweepIntervalMs(): number {
+ const n = Number(process.env.GBRAIN_SWEEP_IDLE_INTERVAL_MS);
+ return Number.isFinite(n) && n >= 1_000 ? Math.floor(n) : IDLE_SWEEP_INTERVAL_MS;
+}
+
+/** GBRA-156: each idle sweep names its start and its duration on stderr, so slow requests can be lined up with it. */
+async function loggedIdleSweep(log: (line: string) => void, run: () => Promise<unknown>): Promise<void> {
+ const startedAt = Date.now();
+ log('[gbrain serve] idle sweep: started');
+ try { await run(); } finally { log(`[gbrain serve] idle sweep: finished in ${Date.now() - startedAt} ms`); }
+}
// Small per-run budget for idle sweeps: the serve must snap back to
// serving tool calls the moment the client wakes up.
@@ -864,6 +877,7 @@ function installStdioLifecycle(
});
let stdinSawData = false;
let sweepInFlight = false;
+ const sawForeground = foregroundWindow();
let dataListenerAttached = false;
idleSweepTimer = deps.setInterval(() => {
if (shuttingDown) return;
@@ -879,17 +893,16 @@ function installStdioLifecycle(
dataListenerAttached = true;
return;
}
- if (stdinSawData) { stdinSawData = false; return; } // active — re-arm
- if (sweepInFlight) return; // never overlap sweeps
- // Degraded mode (db-availability 4c): background sweeps must not burn
+ if (sawForeground() || stdinSawData) { stdinSawData = false; return; } // active (stdin, or a warm CLI socket request: GBRA-156) — re-arm
+ // Never overlap sweeps. Degraded mode (db-availability 4c): background sweeps must not burn
// the min-interval reconnect budget — tool calls own recovery.
- if (isEngineDegradedForServe(engine)) return;
+ if (sweepInFlight || isEngineDegradedForServe(engine)) return;
sweepInFlight = true;
Promise.resolve()
- .then(() => runIdleSweep(engine))
+ .then(() => loggedIdleSweep(deps.log, () => runIdleSweep(engine)))
.catch(() => { /* idle sweep is best-effort; never kill serve */ })
.finally(() => { sweepInFlight = false; });
- }, IDLE_SWEEP_INTERVAL_MS);
+ }, idleSweepIntervalMs());
(idleSweepTimer as { unref?: () => void } | null)?.unref?.();
}
diff --git a/src/core/background-work.ts b/src/core/background-work.ts
index 468d16aa29..640c3e59b9 100644
--- a/src/core/background-work.ts
+++ b/src/core/background-work.ts
@@ -52,8 +52,41 @@
* risks a cycle. The warn below is a local once-per-process Set, not
* utils.warnOncePerProcess, for exactly that reason.
*/
+import { AsyncLocalStorage } from 'node:async_hooks';
export type BackgroundWorkDrainMode = 'exit' | 'disconnect';
+/**
+ * GBRA-156: search-time writes (the page_retrievals bump, the eval_candidates
+ * insert, the semantic-cache store) start after the response inside a request
+ * that owns a deferral scope (the warm CLI socket), instead of mid-request,
+ * where they competed with the response stage for the search's connections.
+ * Outside a scope (a cold CLI, which drains them before exit), they start at
+ * once, as before. node:async_hooks is a builtin, so this module stays a leaf.
+ */
+interface Deferral { released: boolean; queue: Array<() => void> }
+const responseDeferral = new AsyncLocalStorage<Deferral | null>();
+
+/** Start `start` after the enclosing request's response, or now when no request defers (or its response already went). */
+export function deferUntilResponse(start: () => void): void {
+ const scope = responseDeferral.getStore();
+ if (scope && !scope.released) scope.queue.push(start); else start();
+}
+
+/** Runs `fn` with a deferral scope; `release` starts every write it deferred and returns how many. */
+export async function withResponseDeferral<T>(fn: () => Promise<T>): Promise<{ value: T; release: () => number }> {
+ const scope: Deferral = { released: false, queue: [] };
+ const value = await responseDeferral.run(scope, fn);
+ return {
+ value,
+ release: () => responseDeferral.run(null, () => {
+ scope.released = true;
+ const started = scope.queue.splice(0);
+ for (const start of started) { try { start(); } catch { /* a deferred sink never throws into the caller */ } }
+ return started.length;
+ }),
+ };
+}
+
/**
* Shared teardown budgets (#4284). This module is the natural home: it is the
* zero-import leaf that every teardown participant (both engines,
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index d242d15751..d40df2876c 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1248,8 +1248,8 @@ export function behaviorChangesNotice(chain: ChainDisclosure | null, opts: { rem
export async function withTrustClaimAsk(engine: BrainEngine, notice: Notice | null): Promise<Notice | null> {
if (!notice || (notice.fix?.argv && notice.fix.argv.join(' ') !== DOCTOR_ARGV.join(' '))) return notice;
try {
- const { claimSourcesFix, readUnclaimedLegacySources, CLAIM_USER_MESSAGE } = await import('./trust/claim.ts');
- if ((await readUnclaimedLegacySources(engine)).unclaimed.length === 0) return notice;
+ const { claimSourcesFix, hasUnclaimedLegacySources, CLAIM_USER_MESSAGE } = await import('./trust/claim.ts');
+ if (!(await hasUnclaimedLegacySources(engine))) return notice;
return { ...notice, fix: claimSourcesFix(), user_message: CLAIM_USER_MESSAGE };
} catch {
return notice;
diff --git a/src/core/cli-socket/execute.ts b/src/core/cli-socket/execute.ts
index 3581a933d7..c05ffab5c5 100644
--- a/src/core/cli-socket/execute.ts
+++ b/src/core/cli-socket/execute.ts
@@ -20,7 +20,9 @@ import { localFederatedSourceIds, resolveSourceWithTier, SourceTargetError } fro
import { OperationTimeoutError, withTimeout } from '../timeout.ts';
import { bigintToStringReplacer } from '../utils.ts';
import { OutputCapture, withOutputCapture } from './output-capture.ts';
-import { DEFAULT_READ_WALLCLOCK_MS, MAX_ROUND_TRIP_MS, serializeOperationError, type CliSocketRequest, type ResultFrame } from './protocol.ts';
+import { withRequestSignal } from '../request-signal.ts';
+import { withResponseDeferral } from '../background-work.ts';
+import { DEFAULT_READ_WALLCLOCK_MS, MAX_ROUND_TRIP_MS, serializeOperationError, warmRoundTripTimeout, type CliSocketRequest, type ResultFrame } from './protocol.ts';
/** File config merged with the DB plane, read fresh for every request (inside its config snapshot), as a cold CLI reads it at connect. */
export async function mergedRequestConfig(engine: BrainEngine): Promise<GBrainConfig> {
@@ -90,11 +92,19 @@ function track<T>(work: Work, promise: Promise<T>): Promise<T> {
return promise;
}
-async function runOp(engine: BrainEngine, request: Extract<CliSocketRequest, { kind: 'op' }>, capture: OutputCapture, work: Work): Promise<ResultFrame> {
+/** The round trip reached its cap: cancel the request's remaining work (request-signal.ts) and answer a retryable timeout. */
+function roundTripTimeout(request: CliSocketRequest, ms: number, cancel: AbortController, capture: OutputCapture): ResultFrame {
+ cancel.abort(new Error('round_trip_cap'));
+ return { v: 1, kind: 'error', error: serializeOperationError(warmRoundTripTimeout(request.command, ms, 'serve')), output: capture.chunks };
+}
+
+const wallclock = (request: CliSocketRequest) => Math.min(MAX_ROUND_TRIP_MS, request.cli.timeout_ms ?? DEFAULT_READ_WALLCLOCK_MS);
+
+async function runOp(engine: BrainEngine, request: Extract<CliSocketRequest, { kind: 'op' }>, capture: OutputCapture, work: Work, cancel: AbortController): Promise<ResultFrame> {
const op = operationsByName[request.op];
if (!op || op.scope !== 'read' || op.mutating) return { v: 1, kind: 'fallback', reason: 'not_a_read_op' };
const params = request.params;
- const wallclockMs = Math.min(MAX_ROUND_TRIP_MS, request.cli.timeout_ms ?? DEFAULT_READ_WALLCLOCK_MS);
+ const wallclockMs = wallclock(request);
let meta: Record<string, unknown> | null = null;
const notices: Notice[] = [];
const sinks = {
@@ -114,21 +124,23 @@ async function runOp(engine: BrainEngine, request: Extract<CliSocketRequest, { k
const result = JSON.parse(JSON.stringify(raw, bigintToStringReplacer) ?? 'null');
return { v: 1, kind: 'result', result, meta, notices: [...notices, ...retrieval, ...takeChatFallbackHopNotices()], output: capture.chunks };
} catch (error) {
- if (error instanceof OperationTimeoutError) return { v: 1, kind: 'fallback', reason: 'timeout' };
+ if (error instanceof OperationTimeoutError) return roundTripTimeout(request, wallclockMs, cancel, capture);
if (op.name === 'get_page' && (error as { code?: unknown })?.code === 'page_body_segmented') return { v: 1, kind: 'fallback', reason: 'segmented_page' };
return errorFrame(error, capture);
}
}
-async function runRecall(engine: BrainEngine, request: Extract<CliSocketRequest, { kind: 'recall' }>, capture: OutputCapture, work: Work): Promise<ResultFrame> {
+async function runRecall(engine: BrainEngine, request: Extract<CliSocketRequest, { kind: 'recall' }>, capture: OutputCapture, work: Work, cancel: AbortController): Promise<ResultFrame> {
const { recallVerbForCaller } = await import('../../commands/recall.ts');
+ const wallclockMs = wallclock(request);
try {
- const raw = await track(work, recallVerbForCaller(engine, request.args, { cwd: request.routing.cwd, env: request.routing.source_env ?? undefined }));
+ const raw = await withTimeout(track(work, recallVerbForCaller(engine, request.args, { cwd: request.routing.cwd, env: request.routing.source_env ?? undefined })), wallclockMs, `gbrain ${request.command}`);
if (raw === null) return { v: 1, kind: 'fallback', reason: 'not_a_recall_verb' };
const result = JSON.parse(JSON.stringify(raw, bigintToStringReplacer) ?? 'null');
// A cold recall prints the first chat-fallback hop at teardown (src/core/cli-force-exit.ts); the CLI does the same with these.
return { v: 1, kind: 'result', result, meta: null, notices: takeChatFallbackHopNotices(), output: capture.chunks };
} catch (error) {
+ if (error instanceof OperationTimeoutError) return roundTripTimeout(request, wallclockMs, cancel, capture);
return errorFrame(error, capture);
}
}
@@ -146,12 +158,17 @@ export interface ExecutedRequest {
settled: Promise<unknown>;
}
-export async function executeCliSocketRequest(engine: BrainEngine, request: CliSocketRequest): Promise<ExecutedRequest> {
+/** `signal`: the serve aborts it when the client disconnects before the answer; the request's work is then cancelled (request-signal.ts). */
+export async function executeCliSocketRequest(engine: BrainEngine, request: CliSocketRequest, signal?: AbortSignal): Promise<ExecutedRequest> {
const capture = new OutputCapture();
const work: Work = [];
- const answered = await withOutputCapture(capture, () => withRequestConfigSnapshot(engine, () => request.kind === 'op'
- ? runOp(engine, request, capture, work)
- : runRecall(engine, request, capture, work)));
+ const cancel = new AbortController();
+ if (signal) signal.aborted ? cancel.abort(signal.reason) : signal.addEventListener('abort', () => cancel.abort(signal.reason), { once: true });
+ const { value: answered, release } = await withResponseDeferral(() => withRequestSignal(cancel.signal, () => withOutputCapture(capture, () => withRequestConfigSnapshot(engine, () => request.kind === 'op'
+ ? runOp(engine, request, capture, work, cancel)
+ : runRecall(engine, request, capture, work, cancel)))));
+ // GBRA-156: the request's writes (background-work.ts deferUntilResponse) start once the serve has written this answer.
+ setImmediate(release);
const settled = Promise.allSettled(work);
if (answered.kind === 'fallback') return { frame: answered, settled };
if (capture.overflow) return { frame: { v: 1, kind: 'fallback', reason: 'output_too_large' }, settled };
diff --git a/src/core/cli-socket/identity.ts b/src/core/cli-socket/identity.ts
index b58788f9b6..e919bd1f21 100644
--- a/src/core/cli-socket/identity.ts
+++ b/src/core/cli-socket/identity.ts
@@ -12,6 +12,7 @@ import { createHash } from 'node:crypto';
import { readFileSync, realpathSync } from 'node:fs';
import type { GBrainConfig } from '../config.ts';
import { listRecipes } from '../ai/recipes/index.ts';
+import { mergedProviderEnv } from '../ai/provider-env.ts';
/**
* The GBRAIN_* variables that can change what a socket read (search, query,
@@ -71,19 +72,43 @@ function providerEnv(): string[] {
const sha256 = (text: string): string => createHash('sha256').update(text).digest('hex');
+/**
+ * Provider variables that cannot reach any answer from this side: every name belongs only to providers that cannot
+ * authenticate here, because one of their required variables is absent from the provider environment the gateway
+ * builds (`mergedProviderEnv`: this environment plus the config file's provider fields) and none of their credential
+ * variables is set. A provider with no required variable (local servers) and the compatibility endpoints never count.
+ * The serve compares such a name only when the other side can use its provider, so a variable of a provider neither
+ * side can call (an Azure API version on a brain with no Azure endpoint) no longer sends a CLI to its cold path.
+ */
+function inertProviderEnv(merged: Record<string, string>): Set<string> {
+ const inert = new Set<string>();
+ const live = new Set<string>(EXTRA_PROVIDER_ENV);
+ for (const recipe of listRecipes()) {
+ const required = recipe.auth_env?.required ?? [];
+ const names = [...required, ...(recipe.auth_env?.optional ?? [])];
+ const callable = required.length === 0 || required.every(name => merged[name] !== undefined)
+ || names.some(name => SECRET_PROVIDER_ENV.test(name) && merged[name] !== undefined);
+ for (const name of names) (callable ? live : inert).add(name);
+ }
+ for (const name of live) inert.delete(name);
+ return inert;
+}
+
/** The parts of the environment that change what a read answers or where its text goes, each value as a SHA-256 and credentials as names only. */
export interface BehaviorEnv {
- /** READ_BEHAVIOR_ENV names that are set, with the SHA-256 of each value; provider routing variables (base URLs, endpoints, deployments, ids) likewise. */
+ /** READ_BEHAVIOR_ENV names that are set, with the SHA-256 of each value; routing variables (base URLs, endpoints, deployments, ids) of providers this side can call likewise. */
values: Record<string, string>;
- /** The provider credentials that are set, by name (never the value). */
+ /** The provider credentials that are set, by name (never the value), for every provider. */
credentials: string[];
}
-export function behaviorEnv(env: Record<string, string | undefined>): BehaviorEnv {
+/** `fileConfig`: the config file's contents, whose provider fields (keys, the Azure endpoint and deployment) can make a provider callable. */
+export function behaviorEnv(env: Record<string, string | undefined>, fileConfig: GBrainConfig | null = null): BehaviorEnv {
const values: Record<string, string> = {};
for (const name of READ_BEHAVIOR_ENV) if (env[name] !== undefined) values[name] = sha256(env[name]!);
const set = providerEnv().filter(name => env[name] !== undefined && env[name] !== '');
- for (const name of set) if (!SECRET_PROVIDER_ENV.test(name)) values[name] = sha256(env[name]!);
+ const inert = inertProviderEnv(mergedProviderEnv(fileConfig, env));
+ for (const name of set) if (!SECRET_PROVIDER_ENV.test(name) && !inert.has(name)) values[name] = sha256(env[name]!);
return { values, credentials: set.filter(name => SECRET_PROVIDER_ENV.test(name)) };
}
@@ -118,8 +143,12 @@ function realpathOr(path: string): string {
try { return realpathSync(path); } catch { return `absent:${path}`; }
}
-function fileDigest(path: string): string {
- try { return sha256(readFileSync(path, 'utf8')); } catch { return 'absent'; }
+function readConfigFile(path: string): { digest: string; config: GBrainConfig | null } {
+ let text: string;
+ try { text = readFileSync(path, 'utf8'); } catch { return { digest: 'absent', config: null }; }
+ let config: GBrainConfig | null = null;
+ try { const parsed: unknown = JSON.parse(text); if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) config = parsed as GBrainConfig; } catch { /* the digest still compares it */ }
+ return { digest: sha256(text), config };
}
export interface CliSocketIdentityInput {
@@ -146,6 +175,7 @@ export interface CliSocketIdentity {
/** The brain id, the database target, the config home and file (realpath and content), the read-behavior env and the gbrain version. */
export function cliSocketIdentity(input: CliSocketIdentityInput): CliSocketIdentity {
+ const file = readConfigFile(input.configFile);
return {
version: input.version,
brain: input.brainId,
@@ -153,8 +183,8 @@ export function cliSocketIdentity(input: CliSocketIdentityInput): CliSocketIdent
database: input.config.database_url ? databaseTarget(input.config.database_url) : null,
config_dir: realpathOr(input.configDir),
config_file: realpathOr(input.configFile),
- config_sha256: fileDigest(input.configFile),
- env: behaviorEnv(input.env),
+ config_sha256: file.digest,
+ env: behaviorEnv(input.env, file.config),
};
}
diff --git a/src/core/cli-socket/protocol.ts b/src/core/cli-socket/protocol.ts
index 099cc10df8..a924757df7 100644
--- a/src/core/cli-socket/protocol.ts
+++ b/src/core/cli-socket/protocol.ts
@@ -5,7 +5,7 @@
* one result line. Both directions are size-bounded.
*/
import type { Notice } from '../agent-output.ts';
-import { OperationError } from '../ops/contract.ts';
+import { OperationError, opError } from '../ops/contract.ts';
import { isCliSocketIdentity, type CliSocketIdentity } from './identity.ts';
export const CLI_SOCKET_PROTOCOL = 1;
@@ -20,6 +20,18 @@ export const DEFAULT_READ_WALLCLOCK_MS = 180_000;
/** The longest a CLI waits on one whole exchange (or its --timeout, when shorter) before running the call itself. */
export const MAX_ROUND_TRIP_MS = 30_000;
+/**
+ * GBRA-156: a warm call that reached its round-trip cap answers with this retryable `timeout` error instead of
+ * running the call again on the cold path. The serve sends it after cancelling the request's remaining work; the CLI
+ * builds the same error when the serve never answered in time.
+ */
+export function warmRoundTripTimeout(command: string, ms: number, side: 'serve' | 'cli'): OperationError {
+ return opError('timeout', `gbrain ${command} did not finish within ${ms} ms on the warm CLI socket${side === 'serve' ? '; the serve cancelled it' : ' (the serve did not answer)'}.`,
+ 'Retry the same command. If it keeps timing out, check the serve log (gbrain serve) for a request still running, or add --timeout to bound the call.',
+ { reason: 'cli_socket_round_trip_cap', retryable: true, docs: 'docs/guides/cli-socket.md',
+ why: `The warm CLI socket caps one call at ${ms} ms so a caller never waits on a request without a bound; the call returned this error instead of starting over on the slower cold path.` });
+}
+
/** The read operations a serve answers over the socket. Everything else keeps the cold path. */
export const CLI_SOCKET_OPS = ['search', 'query', 'get_page'] as const;
export type CliSocketOp = typeof CLI_SOCKET_OPS[number];
diff --git a/src/core/cli-socket/refusals.ts b/src/core/cli-socket/refusals.ts
new file mode 100644
index 0000000000..06fbc9b689
--- /dev/null
+++ b/src/core/cli-socket/refusals.ts
@@ -0,0 +1,55 @@
+/**
+ * Refusal counts of the warm CLI socket, for doctor `cli_socket_refusals`. A refused CLI call takes its cold path,
+ * several times slower, so a caller whose environment drifted from the serve's pays that on every call. The serve
+ * counts each refusal by the identity part that differed (never its value) and keeps the counts in
+ * `<run dir>/cli-socket-refusals.json` (0600, written at most once per FLUSH_MS and when the serve closes); doctor
+ * reads that file. Best-effort: a write that fails is retried at the next refusal and never affects an answer.
+ */
+import { readFileSync, renameSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+
+export const REFUSALS_FILE = 'cli-socket-refusals.json';
+const FLUSH_MS = 5_000;
+
+export interface RefusalPart { count: number; first_at: string; last_at: string }
+export interface RefusalRecord { v: 1; pid: number; started_at: string; parts: Record<string, RefusalPart> }
+
+export interface RefusalCounter { record(part: string): void; flush(): void }
+
+export function refusalCounter(dir: string, now: () => Date = () => new Date()): RefusalCounter {
+ const state: RefusalRecord = { v: 1, pid: process.pid, started_at: now().toISOString(), parts: {} };
+ let dirty = false;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const flush = () => {
+ clearTimeout(timer);
+ timer = undefined;
+ if (!dirty) return;
+ const path = join(dir, REFUSALS_FILE);
+ try {
+ writeFileSync(`${path}.tmp`, JSON.stringify(state) + '\n', { mode: 0o600 });
+ renameSync(`${path}.tmp`, path);
+ dirty = false;
+ } catch { /* retried at the next refusal */ }
+ };
+ return {
+ record(part) {
+ const at = now().toISOString();
+ const entry = state.parts[part];
+ state.parts[part] = entry ? { ...entry, count: entry.count + 1, last_at: at } : { count: 1, first_at: at, last_at: at };
+ dirty = true;
+ if (!timer) { timer = setTimeout(flush, FLUSH_MS); timer.unref(); }
+ },
+ flush,
+ };
+}
+
+/** The newest serve's counts, or null when no serve recorded a refusal (or the file is unreadable). */
+export function readRefusals(dir: string): RefusalRecord | null {
+ try {
+ const value = JSON.parse(readFileSync(join(dir, REFUSALS_FILE), 'utf8')) as RefusalRecord;
+ if (value?.v !== 1 || typeof value.parts !== 'object' || value.parts === null) return null;
+ return value;
+ } catch {
+ return null;
+ }
+}
diff --git a/src/core/cli-socket/server.ts b/src/core/cli-socket/server.ts
index ca19b9d04b..a851c1a24c 100644
--- a/src/core/cli-socket/server.ts
+++ b/src/core/cli-socket/server.ts
@@ -17,6 +17,8 @@ import { executeCliSocketRequest, type ExecutedRequest } from './execute.ts';
import { CliSocketUnsafeError, cliSocketDir, cliSocketPath, ensurePrivateDir, privateSocketProblem, socketPathFits, verifyBoundSocket } from './fs-guard.ts';
import { cliSocketIdentity, cliSocketIdentityMismatch, type CliSocketIdentity } from './identity.ts';
import { installOutputCapture } from './output-capture.ts';
+import { refusalCounter } from './refusals.ts';
+import { beginForegroundRequest } from '../foreground-activity.ts';
import { peerCredSupport, peerUid, type PeerCredSupport } from './peer-cred.ts';
import { FrameReader, isCliSocketRequest, MAX_REQUEST_BYTES, MAX_RESPONSE_BYTES, MAX_ROUND_TRIP_MS, REQUEST_READ_TIMEOUT_MS,
type CliSocketRequest, type HandshakeFrame, type ResultFrame } from './protocol.ts';
@@ -35,7 +37,7 @@ export interface CliSocketServerOptions {
identity?: CliSocketIdentity;
uid?: () => number | undefined;
brainId?: () => string;
- execute?: (request: CliSocketRequest) => Promise<ExecutedRequest>;
+ execute?: (request: CliSocketRequest, signal: AbortSignal) => Promise<ExecutedRequest>;
/** After this long a request whose work has not settled is logged once (its slot is still held). */
stuckAfterMs?: number;
}
@@ -125,7 +127,7 @@ export async function startCliSocketServer(opts: CliSocketServerOptions): Promis
const identity = opts.identity ?? cliSocketIdentity({
config: { engine: 'postgres', database_url: databaseUrl }, brainId, configDir: home, configFile: configPath(), version: VERSION, env: process.env,
});
- const execute = opts.execute ?? ((request: CliSocketRequest) => executeCliSocketRequest(opts.engine, request));
+ const execute = opts.execute ?? ((request: CliSocketRequest, signal: AbortSignal) => executeCliSocketRequest(opts.engine, request, signal));
installOutputCapture();
const sockets = new Set<Socket>();
@@ -133,6 +135,7 @@ export async function startCliSocketServer(opts: CliSocketServerOptions): Promis
let closing = false;
const rejectedUids = new Set<number | null>();
const loggedMismatches = new Set<string>();
+ const refusals = refusalCounter(dir);
const server = net.createServer(socket => {
socket.on('error', () => {});
if (closing || sockets.size >= MAX_CONNECTIONS) { socket.destroy(); return; }
@@ -162,19 +165,30 @@ export async function startCliSocketServer(opts: CliSocketServerOptions): Promis
const mismatch = cliSocketIdentityMismatch(identity, request.identity);
if (mismatch) {
if (!loggedMismatches.has(mismatch)) { loggedMismatches.add(mismatch); log(`refused a CLI call: identity_mismatch (${mismatch} differs from this serve's); that CLI takes its cold path.`); }
+ refusals.record(mismatch);
socket.end(frame({ v: 1, accepted: false, reason: 'identity_mismatch', mismatch }));
return;
}
if (active >= MAX_ACTIVE_REQUESTS) { socket.end(frame({ v: 1, accepted: false, reason: 'busy' })); return; }
// Active until the request's own work settles, not until it answered: a timed-out handler still holds its slot.
active++;
+ const finishForeground = beginForegroundRequest();
const started = performance.now();
let settled: Promise<unknown> = Promise.resolve();
+ // GBRA-156: a client that goes away before its answer cancels the request's remaining work and frees its connections.
+ const cancel = new AbortController();
+ let answered = false;
+ socket.once('close', () => {
+ if (answered || cancel.signal.aborted) return;
+ cancel.abort(new Error('client_disconnected'));
+ log(`a ${request.command} request's client disconnected after ${Math.round(performance.now() - started)} ms; its remaining work is cancelled.`);
+ });
try {
socket.write(frame({ v: 1, accepted: true }));
let result: ResultFrame;
- try { ({ frame: result, settled } = await execute(request)); }
+ try { ({ frame: result, settled } = await execute(request, cancel.signal)); }
catch { result = { v: 1, kind: 'fallback', reason: 'serve_error' }; }
+ answered = true;
if (!socket.destroyed) socket.end(frame(result));
} finally {
let done = false;
@@ -182,7 +196,7 @@ export async function startCliSocketServer(opts: CliSocketServerOptions): Promis
if (!done) log(`a ${request.command} request is still running ${Math.round((performance.now() - started) / 1000)} s after it started; its slot stays held until it finishes (${active} of ${MAX_ACTIVE_REQUESTS} in use).`);
}, Math.max(0, (opts.stuckAfterMs ?? MAX_ROUND_TRIP_MS) - (performance.now() - started)));
stuck.unref();
- void settled.then(() => { done = true; clearTimeout(stuck); active--; }, () => { done = true; clearTimeout(stuck); active--; });
+ void settled.then(() => { done = true; clearTimeout(stuck); active--; finishForeground(); }, () => { done = true; clearTimeout(stuck); active--; finishForeground(); });
}
})();
});
@@ -203,6 +217,7 @@ export async function startCliSocketServer(opts: CliSocketServerOptions): Promis
const close = () => {
if (closing) return;
closing = true;
+ refusals.flush();
server.close();
for (const socket of sockets) socket.destroy();
try { if (lstatSync(path).ino === inode) unlinkSync(path); } catch { /* already gone */ }
diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.ts
index c28e07bf81..1d71429e20 100644
--- a/src/core/doctor-categories.ts
+++ b/src/core/doctor-categories.ts
@@ -344,6 +344,8 @@ export const OPS_CHECK_NAMES: ReadonlySet<string> = new Set([
'serve_build_drift',
// #7245: serve, the jobs supervisor, worker parents and job children on different builds (doctor/checks/runtime-build-skew.ts).
'runtime_build_skew',
+ // GBRA-156: the warm CLI socket refused CLI calls by identity part in the last 24 h (doctor/checks/cli-socket-refusals.ts).
+ 'cli_socket_refusals',
'stale_embedding_effects',
'vector_plan',
'keyword_plan',
diff --git a/src/core/engine.ts b/src/core/engine.ts
index 97aaff283a..17da329678 100644
--- a/src/core/engine.ts
+++ b/src/core/engine.ts
@@ -153,6 +153,8 @@ export interface TransactionOptions {
* set_config (`isPipelinableSearchRead`). Ignored by PGLite and inside a transaction.
*/
pipelineEarly?: (statement: string) => boolean;
+ /** GBRA-156: Postgres opens `BEGIN READ ONLY` (a write inside fails with 25006); search's reads pass it. Ignored by PGLite and when nested. */
+ readOnly?: boolean;
}
/** Input row for addLinksBatch. Optional fields default to '' (matches NOT NULL DDL). */
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index af977d23eb..47606b1881 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -819,6 +819,7 @@ export const NOTICE_CODES = {
first_run_decisions: { kind: 'ask', summary: 'init finished (or a stdio MCP session started on a brain with open decisions); the first-run decisions (search mode, writeback, harness wiring, skills) carry defaults the user may change. The one muteable ask.' },
first_run_decisions_muted: { kind: 'info', summary: 'First-run decisions are still open, but the user muted them; the fix shows them again (`gbrain notices unmute first_run_decisions`).' },
migrations_pending: { kind: 'safety', summary: 'Schema migrations are pending or failed to apply on this brain.' },
+ socket_identity_mismatch: { kind: 'degraded', summary: 'The running serve\'s warm CLI socket refused this CLI call because an identity part (named, never its value) differs from the serve\'s, so the call ran on the slower cold path; doctor `cli_socket_refusals` counts these.' },
sync_retry_failed_deprecated: { kind: 'coaching', summary: '`gbrain sync --retry-failed` is a deprecated alias for a plain sync, accepted for two releases: a plain sync retries a failure the previous run recorded by itself. Drop the flag.' },
sync_tail_degraded: { kind: 'degraded', summary: 'A managed sync ended synced, but its post-checkpoint tail (planner statistics, link extraction for the imported pages) failed, was cut off at its budget or did not start before the run\'s deadline; the step stays scheduled for the next sync, and the fix runs it now (`gbrain extract --stale --source-id <id>`, or doctor for the statistics).' },
no_resident: { kind: 'degraded', summary: 'gbrain sync trigger recorded the request (and queued a job or nudged the serve), but no resident (gbrain serve, gbrain jobs work or the autopilot daemon) watches the source, so the recorded request waits until one starts or a sync reaches it; the fix syncs the checkout HEAD now (`gbrain sync --source <id> --no-pull`). docs/guides/on-commit-sync.md#no-resident' },
diff --git a/src/core/eval-capture.ts b/src/core/eval-capture.ts
index 711d7b9238..ed7309c4ba 100644
--- a/src/core/eval-capture.ts
+++ b/src/core/eval-capture.ts
@@ -43,7 +43,7 @@ import type {
} from './types.ts';
import type { GBrainConfig } from './config.ts';
import { scrubPii } from './eval-capture-scrub.ts';
-import { registerBackgroundWorkDrainer } from './background-work.ts';
+import { deferUntilResponse, registerBackgroundWorkDrainer } from './background-work.ts';
// HybridSearchMeta is canonical in src/core/types.ts and exported via the
// public `gbrain/types` subpath. Surfaced from hybridSearch via the
@@ -164,9 +164,12 @@ export async function captureEvalCandidate(
// returned promise is back-compat for any awaiter. The async DB write
// (logEvalCandidate) is the same lock-pin / disconnect-race class as the other
// sinks — on PGLite an undrained capture racing db.close() can wedge.
- const p = doCaptureEvalCandidate(engine, ctx, opts);
- trackEvalCapture(p);
- return p;
+ // GBRA-156: inside a request that defers its writes (background-work.ts deferUntilResponse), the insert starts after the response.
+ return new Promise<void>(resolve => deferUntilResponse(() => {
+ const p = doCaptureEvalCandidate(engine, ctx, opts);
+ trackEvalCapture(p);
+ p.then(resolve, () => resolve());
+ }));
}
async function doCaptureEvalCandidate(
diff --git a/src/core/foreground-activity.ts b/src/core/foreground-activity.ts
new file mode 100644
index 0000000000..d8ae637e17
--- /dev/null
+++ b/src/core/foreground-activity.ts
@@ -0,0 +1,36 @@
+/**
+ * GBRA-156: foreground requests a serve answers outside its MCP stdin (the warm CLI socket). The serve's idle
+ * maintenance sweep treats a window with one as active, as it treats stdin data, so a sweep never starts while warm
+ * CLI searches are flowing and competing with them for the event loop and the pool.
+ */
+let inFlight = 0;
+let lastAt = 0;
+
+/** Marks one foreground request started; the returned function marks it finished (idempotent). */
+export function beginForegroundRequest(now: () => number = Date.now): () => void {
+ inFlight++;
+ lastAt = now();
+ let done = false;
+ return () => {
+ if (done) return;
+ done = true;
+ inFlight--;
+ lastAt = now();
+ };
+}
+
+/** A window check: each call says whether a foreground request is running now or ran since the previous call (or since the window opened). */
+export function foregroundWindow(now: () => number = Date.now): () => boolean {
+ let since = now();
+ return () => {
+ const active = inFlight > 0 || lastAt >= since;
+ since = now();
+ return active;
+ };
+}
+
+/** Test seam. */
+export function _resetForegroundActivityForTests(): void {
+ inFlight = 0;
+ lastAt = 0;
+}
diff --git a/src/core/last-retrieved.ts b/src/core/last-retrieved.ts
index b2e83f317e..936d0f1297 100644
--- a/src/core/last-retrieved.ts
+++ b/src/core/last-retrieved.ts
@@ -47,7 +47,7 @@
import type { BrainEngine } from './engine.ts';
import { isMissingSchemaObject } from './utils.ts';
-import { registerBackgroundWorkDrainer } from './background-work.ts';
+import { deferUntilResponse, registerBackgroundWorkDrainer } from './background-work.ts';
let _trackRetrievalCache: { ts: number; enabled: boolean } | null = null;
const TRACK_RETRIEVAL_CACHE_TTL_MS = 30_000;
@@ -197,6 +197,10 @@ export const BUMP_LAST_RETRIEVED_SQL = `INSERT INTO page_retrievals (page_id, la
*/
export function bumpLastRetrievedAt(engine: BrainEngine, pageIds: number[]): void {
if (pageIds.length === 0) return;
+ deferUntilResponse(() => startBump(engine, pageIds));
+}
+
+function startBump(engine: BrainEngine, pageIds: number[]): void {
// Fire-and-forget on purpose for callers (MCP, internal). The CLI
// path awaits the drain helper below before disconnecting, which
// is how #1247/#1269/#1290 are fixed without exposing the IIFE
diff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.ts
index 8ae4c78b96..d985f98aba 100644
--- a/src/core/pglite-schema.generated.ts
+++ b/src/core/pglite-schema.generated.ts
@@ -233,6 +233,7 @@ CREATE INDEX IF NOT EXISTS idx_links_origin ON links(origin_page_id);
CREATE OR REPLACE VIEW page_links AS
SELECT id, from_page_id, to_page_id FROM links;
+CREATE INDEX IF NOT EXISTS idx_links_supersedes_to ON links (to_page_id) WHERE link_type = 'supersedes';
CREATE TABLE IF NOT EXISTS wanted_links (
id BIGSERIAL PRIMARY KEY,
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index bead2df0d2..0953a4aca7 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -114,6 +114,7 @@ import * as db from './db.ts';
import { ConnectionManager, DEFAULT_DIRECT_POOL_SIZE } from './connection-manager.ts';
import { logConnectionEvent } from './connection-audit.ts';
import { drainBackgroundWorkBeforeDisconnect } from './background-work.ts';
+import { requestSignal, throwIfRequestAborted } from './request-signal.ts';
import { validateSlug, contentHash, isBlankBody, rowToPage, rowToStalePage, rowToChunk, rowToSearchResult, parseEmbedding, tryParseEmbedding, isUndefinedTableError, warnOncePerProcess } from './utils.ts';
import { resolveBoostMap, resolveHardExcludes } from './search/source-boost.ts';
import { buildSourceFactorCase, buildHardExcludeClause, buildVisibilityClause, buildBestPerPagePoolCte, buildOrFallbackWebsearchQuery, boundWebsearchQuery, collapseWebsearchDashRuns } from './search/sql-ranking.ts';
@@ -393,7 +394,7 @@ export class PostgresEngine implements BrainEngine {
}
/**
- * GBRA-156: a top-level read transaction answers when its read returns, without waiting for COMMIT's round trip.
+ * GBRA-156: a top-level read transaction opens `BEGIN READ ONLY` (a write inside it fails, never commits) and answers when its read returns, without waiting for COMMIT's round trip.
* The driver keeps the connection reserved, and the gauge counts it, until COMMIT settles; a failed COMMIT cannot
* change rows already read, so it is not the caller's error. `run` lets its statement errors propagate (every read here does).
*/
@@ -407,7 +408,7 @@ export class PostgresEngine implements BrainEngine {
answered = true;
resolve(result);
return result;
- }, { pipelineEarly: isPipelinableSearchRead }).catch(error => { if (!answered) reject(error); });
+ }, { pipelineEarly: isPipelinableSearchRead, readOnly: true }).catch(error => { if (!answered) reject(error); });
});
}
@@ -683,17 +684,21 @@ export class PostgresEngine implements BrainEngine {
}
private async transactionOn<T>(conn: ReturnType<typeof postgres>, fn: (engine: BrainEngine) => Promise<T>, opts?: TransactionOptions): Promise<T> {
+ // GBRA-156: a top-level read transaction inherits its request's signal (request-signal.ts), so a request nobody waits for gives its connection back.
+ const inherited = !opts?.signal && opts?.readOnly && !this._pageTransaction ? requestSignal() : undefined;
+ if (inherited) opts = { ...opts, signal: inherited };
if (opts?.signal?.aborted) throw transactionAborted(opts.signal);
- conn = readWriteTransactions(conn);
+ if (!opts?.readOnly) conn = readWriteTransactions(conn);
// try/finally, not .finally on the chained promise: begin() can throw
// SYNCHRONOUSLY (e.g. nested transaction on a tx clone whose conn has no
// .begin), which would skip a chained .finally and leak the counter.
if (!this._pageTransaction) this.checkoutGauge.acquire('tx');
try {
// GBRA-156: the pool's begin takes `first`; a nested transaction's begin (a savepoint) takes only the callback.
+ const mode = opts?.readOnly ? { mode: 'read only' } : {};
const begin = (run: (handle: unknown) => Promise<unknown>) => this._pageTransaction ? conn.begin(run)
- : opts?.pipelineEarly ? conn.begin({ early: opts.pipelineEarly }, run)
- : opts?.pipelineFirst ? conn.begin({ first: opts.pipelineFirst }, run) : conn.begin(run);
+ : opts?.pipelineEarly ? conn.begin({ ...mode, early: opts.pipelineEarly }, run)
+ : opts?.pipelineFirst ? conn.begin({ ...mode, first: opts.pipelineFirst }, run) : conn.begin(mode, run);
return await holdSearchConnection(() => withCommitChecks(checks => withTransactionAbort(opts?.signal, attach => withHeldPageKeys(this._pageTransaction ? this._heldPageKeys : null, held => begin(async (handle) => {
attach(handle as Discardable);
if (!this._pageTransaction) this.checkoutGauge.checkedOut();
@@ -2938,6 +2943,7 @@ export class PostgresEngine implements BrainEngine {
// try/finally (not .finally on the promise): runUnsafe throws
// SYNCHRONOUSLY on a pre-aborted signal, which would skip a chained
// .finally and leak the counter.
+ throwIfRequestAborted();
this.checkoutGauge.acquire('raw');
try {
if (opts?.jitOff && await needsJitOff(this.sql, this._pageTransaction)) return await runJitOffStatement<T>(this.sql, this._pageTransaction, sql, params, opts, (c, s, p, o) => this.runUnsafe(c, s, p, o), () => this.checkoutGauge.checkedOut());
diff --git a/src/core/request-signal.ts b/src/core/request-signal.ts
new file mode 100644
index 0000000000..6735c04f38
--- /dev/null
+++ b/src/core/request-signal.ts
@@ -0,0 +1,31 @@
+/**
+ * GBRA-156: the abort signal of the request a statement runs for. The warm CLI socket aborts it when its client
+ * disconnects before the answer or the request reaches its round-trip cap; the Postgres engine then refuses every
+ * later statement of that request and cancels its open read transactions (cancel, then discard the connection), so a
+ * request nobody waits for stops holding connections and its serve slot. Work started outside a request (sweeps,
+ * writes deferred past the response) runs with no signal.
+ */
+import { AsyncLocalStorage } from 'node:async_hooks';
+
+const store = new AsyncLocalStorage<AbortSignal | undefined>();
+
+export function withRequestSignal<T>(signal: AbortSignal, fn: () => T): T {
+ return store.run(signal, fn);
+}
+
+/** Runs `fn` outside any request's signal (work that must outlive the request). */
+export function withoutRequestSignal<T>(fn: () => T): T {
+ return store.run(undefined, fn);
+}
+
+export function requestSignal(): AbortSignal | undefined {
+ return store.getStore();
+}
+
+/** Throws the request's AbortError when its signal has fired. */
+export function throwIfRequestAborted(): void {
+ const signal = store.getStore();
+ if (!signal?.aborted) return;
+ const reason = signal.reason;
+ throw new DOMException(reason instanceof Error ? reason.message : 'request aborted', 'AbortError');
+}
diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.ts
index f4dbe77c17..01c7e8bcb9 100644
--- a/src/core/schema-embedded.generated.ts
+++ b/src/core/schema-embedded.generated.ts
@@ -578,6 +578,7 @@ CREATE INDEX IF NOT EXISTS idx_links_from ON links(from_page_id);
CREATE INDEX IF NOT EXISTS idx_links_to ON links(to_page_id);
CREATE INDEX IF NOT EXISTS idx_links_source ON links(link_source);
CREATE INDEX IF NOT EXISTS idx_links_origin ON links(origin_page_id);
+CREATE INDEX IF NOT EXISTS idx_links_supersedes_to ON links (to_page_id) WHERE link_type = 'supersedes';
-- Wanted pages (migration wanted_links): authored links whose target page does
-- not exist. A live target updated after checked_at makes the origin stale for
diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.ts
index 0446a17bcc..7455a19853 100644
--- a/src/core/schema-migrations/latest.generated.ts
+++ b/src/core/schema-migrations/latest.generated.ts
@@ -4,4 +4,4 @@
// The highest schema migration version (migrate.ts LATEST_VERSION), importable without
// loading the migrations themselves.
-export const LATEST_SCHEMA_VERSION = 267;
+export const LATEST_SCHEMA_VERSION = 268;
diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.ts
index 2df9303dd2..23a569bd12 100644
--- a/src/core/schema-migrations/registry.generated.ts
+++ b/src/core/schema-migrations/registry.generated.ts
@@ -268,6 +268,7 @@ import { v264 } from './v264-set-based-fact-insert-guards.ts';
import { v265 } from './v265-derived-generations.ts';
import { v266 } from './v266-derived-generation-activations.ts';
import { v267 } from './v267-pages-title-search-index.ts';
+import { v268 } from './v268-links-supersedes-index.ts';
// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the
// runner sorts by version before applying.
@@ -534,4 +535,5 @@ export const MIGRATIONS: Migration[] = [
v265,
v266,
v267,
+ v268,
];
diff --git a/src/core/schema-migrations/v268-links-supersedes-index.ts b/src/core/schema-migrations/v268-links-supersedes-index.ts
new file mode 100644
index 0000000000..8cc28ae60a
--- /dev/null
+++ b/src/core/schema-migrations/v268-links-supersedes-index.ts
@@ -0,0 +1,31 @@
+import type { Migration } from './types.ts';
+import { buildIndexOnline, migrationNotice } from './helpers.ts';
+
+// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md
+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.
+//
+// GBRA-156: search gates its supersession stage on an existence probe
+// (`links WHERE link_type = 'supersedes' LIMIT 1`, search/hybrid.ts). No links
+// index leads with link_type, so on a brain with no supersedes edges, the
+// common case, the probe read every links row to return nothing. This partial
+// index holds only supersedes edges, keyed by the stale page: the probe reads
+// an empty index, and the downrank lookup (`to_page_id = ANY(...)`) reads
+// only supersedes edges. Built online (CONCURRENTLY on Postgres); an
+// interrupted build leaves an INVALID index that the next initSchema drops and
+// rebuilds.
+export const LINKS_SUPERSEDES_INDEX = {
+ name: 'idx_links_supersedes_to',
+ table: 'links',
+ sql: "CREATE INDEX IF NOT EXISTS idx_links_supersedes_to ON links (to_page_id) WHERE link_type = 'supersedes'",
+};
+
+export const v268: Migration = {
+ version: 268,
+ name: 'links_supersedes_index',
+ idempotent: true,
+ transaction: false,
+ sql: '',
+ handler: async engine => {
+ await buildIndexOnline(engine, 268, LINKS_SUPERSEDES_INDEX, { notice: migrationNotice });
+ },
+};
diff --git a/src/core/search/connection-budget.ts b/src/core/search/connection-budget.ts
index 22d880fa7f..babd35e8bd 100644
--- a/src/core/search/connection-budget.ts
+++ b/src/core/search/connection-budget.ts
@@ -12,6 +12,7 @@
* scope, and on PGLite, nothing changes.
*/
import { AsyncLocalStorage } from 'node:async_hooks';
+import { throwIfRequestAborted } from '../request-signal.ts';
/** The most pooled connections one search or query op holds at once. */
export const SEARCH_CONNECTION_LIMIT = 4;
@@ -42,6 +43,7 @@ export async function holdSearchConnection<T>(fn: () => Promise<T>): Promise<T>
if (budget.free > 0) budget.free -= 1;
else await new Promise<void>(resolve => (urgency.getStore() ? budget.urgent : budget.waiters).push(resolve));
try {
+ throwIfRequestAborted();
return await budgets.run(null, fn);
} finally {
const next = budget.urgent.shift() ?? budget.waiters.shift();
diff --git a/src/core/search/hybrid.ts b/src/core/search/hybrid.ts
index 9e655d6c0b..d90c459458 100644
--- a/src/core/search/hybrid.ts
+++ b/src/core/search/hybrid.ts
@@ -24,7 +24,7 @@ export { resolveDateBoundary, resolveSearchDateBounds } from './date-bounds.ts';
import { hasReadPolicy, pageReadFilter } from './read-policy-sql.ts';
import { embedQuery } from '../embedding.ts';
import { loadEmbeddingQueryPrefix } from './query-prefix.ts';
-import { registerBackgroundWorkDrainer } from '../background-work.ts';
+import { deferUntilResponse, registerBackgroundWorkDrainer } from '../background-work.ts';
import { applyAliasHop, isExcludedIdentity, type IdentityTierOpts } from './alias-hop.ts';
export { applyAliasHop, isExcludedIdentity, type IdentityTierOpts };
import { dedupResults, segmentRegions } from './dedup.ts';
@@ -1341,7 +1341,7 @@ export async function hybridSearchCached(
// every 60s); the stamp still rides the stored meta so a hit is honest.
// Stale unreranked rows after a key appears expire within one TTL.
const isDegraded = (finalMeta.degraded ?? []).some(affectsRecall);
- trackCacheWrite(
+ deferUntilResponse(() => trackCacheWrite(
semanticCache.cache
.store(query, queryEmbedding, results, finalMeta, {
sourceId: cacheScopeKey(opts),
@@ -1349,7 +1349,7 @@ export async function hybridSearchCached(
...(isDegraded ? { ttlSeconds: DEGRADED_CACHE_TTL_SECONDS } : {}),
})
.catch(() => { /* swallow */ }),
- );
+ ));
}
return budgeted;
diff --git a/src/core/trust/claim.ts b/src/core/trust/claim.ts
index 23fcc831f3..6dd90064ec 100644
--- a/src/core/trust/claim.ts
+++ b/src/core/trust/claim.ts
@@ -183,26 +183,52 @@ export interface UnclaimedLegacySources {
* as pre-trust); a fresh or empty brain has none.
*/
export async function readUnclaimedLegacySources(engine: Pick<BrainEngine, 'executeRaw'>): Promise<UnclaimedLegacySources> {
- const legacy = await legacyUnknownBySource(engine);
+ const { candidates, pending } = await claimCandidates(engine);
+ const legacy = candidates.length ? await legacyUnknownBySource(engine, candidates) : new Map<string, number>();
+ return {
+ unclaimed: candidates.filter(id => (legacy.get(id) ?? 0) > 0).map(id => ({ id, legacy_unknown: legacy.get(id)! })),
+ pending,
+ };
+}
+
+/**
+ * The behavior-change notice's claim ask: does any unclaimed, live, non-connector source hold a legacy row at
+ * `unknown`? One existence probe per such source instead of a count of every source's rows, and no table scan at all
+ * when every source is claimed. Throws before the trust migration, as readUnclaimedLegacySources does.
+ */
+export async function hasUnclaimedLegacySources(engine: Pick<BrainEngine, 'executeRaw'>): Promise<boolean> {
+ const { candidates } = await claimCandidates(engine);
+ if (candidates.length === 0) return false;
+ const ceilings = await readLegacyCeilings(engine);
+ const rows = await engine.executeRaw<{ id: string }>(
+ `SELECT s.id FROM unnest($1::text[]) AS s(id) WHERE
+ EXISTS (SELECT 1 FROM pages p WHERE p.source_id = s.id AND p.trust_tier = 'unknown' AND p.deleted_at IS NULL AND ${legacyRowSql('pages', 'p', ceilings)})
+ OR EXISTS (SELECT 1 FROM facts f WHERE f.source_id = s.id AND f.trust_tier = 'unknown' AND ${legacyRowSql('facts', 'f', ceilings)})
+ OR EXISTS (SELECT 1 FROM takes t JOIN pages p ON p.id = t.page_id WHERE p.source_id = s.id AND t.trust_tier = 'unknown' AND ${legacyRowSql('takes', 't', ceilings)})
+ OR EXISTS (SELECT 1 FROM timeline_entries te JOIN pages p ON p.id = te.page_id WHERE p.source_id = s.id AND te.trust_tier = 'unknown' AND ${legacyRowSql('timeline_entries', 'te', ceilings)})
+ LIMIT 1`, [candidates]);
+ return rows.length > 0;
+}
+
+/** Live, non-connector sources: the unclaimed ones a claim could help, and the claimed ones whose lift has not finished. */
+async function claimCandidates(engine: Pick<BrainEngine, 'executeRaw'>): Promise<{ candidates: string[]; pending: string[] }> {
const rows = await engine.executeRaw<{ id: string; claimed: boolean; lifted: boolean }>(
`SELECT s.id, ${claimedSourceSql('s')} AS claimed, (s.config ? '${TRUST_CLAIM_LIFTED_AT_KEY}') AS lifted
FROM sources s WHERE NOT s.archived AND ${notConnectorSourceSql('s')} ORDER BY s.id`);
- return {
- unclaimed: rows.filter(r => !r.claimed && (legacy.get(r.id) ?? 0) > 0).map(r => ({ id: r.id, legacy_unknown: legacy.get(r.id)! })),
- pending: rows.filter(r => r.claimed && !r.lifted).map(r => r.id),
- };
+ return { candidates: rows.filter(r => !r.claimed).map(r => r.id), pending: rows.filter(r => r.claimed && !r.lifted).map(r => r.id) };
}
-/** Legacy rows (claim-state.ts) still at `unknown`, per source, across pages, facts, takes and timeline entries. */
-async function legacyUnknownBySource(engine: Pick<BrainEngine, 'executeRaw'>): Promise<Map<string, number>> {
+/** Legacy rows (claim-state.ts) still at `unknown`, per source, across pages, facts, takes and timeline entries; only `sourceIds` when given. */
+async function legacyUnknownBySource(engine: Pick<BrainEngine, 'executeRaw'>, sourceIds?: string[]): Promise<Map<string, number>> {
const ceilings = await readLegacyCeilings(engine);
+ const only = (column: string) => sourceIds ? ` AND ${column} = ANY($1::text[])` : '';
const rows = await engine.executeRaw<{ source_id: string; n: number | string }>(
`SELECT source_id, sum(n)::bigint AS n FROM (
- SELECT p.source_id, count(*) AS n FROM pages p WHERE p.trust_tier = 'unknown' AND p.deleted_at IS NULL AND ${legacyRowSql('pages', 'p', ceilings)} GROUP BY 1
- UNION ALL SELECT f.source_id, count(*) FROM facts f WHERE f.trust_tier = 'unknown' AND ${legacyRowSql('facts', 'f', ceilings)} GROUP BY 1
- UNION ALL SELECT p.source_id, count(*) FROM takes t JOIN pages p ON p.id = t.page_id WHERE t.trust_tier = 'unknown' AND ${legacyRowSql('takes', 't', ceilings)} GROUP BY 1
- UNION ALL SELECT p.source_id, count(*) FROM timeline_entries te JOIN pages p ON p.id = te.page_id WHERE te.trust_tier = 'unknown' AND ${legacyRowSql('timeline_entries', 'te', ceilings)} GROUP BY 1
- ) u GROUP BY source_id`);
+ SELECT p.source_id, count(*) AS n FROM pages p WHERE p.trust_tier = 'unknown' AND p.deleted_at IS NULL AND ${legacyRowSql('pages', 'p', ceilings)}${only('p.source_id')} GROUP BY 1
+ UNION ALL SELECT f.source_id, count(*) FROM facts f WHERE f.trust_tier = 'unknown' AND ${legacyRowSql('facts', 'f', ceilings)}${only('f.source_id')} GROUP BY 1
+ UNION ALL SELECT p.source_id, count(*) FROM takes t JOIN pages p ON p.id = t.page_id WHERE t.trust_tier = 'unknown' AND ${legacyRowSql('takes', 't', ceilings)}${only('p.source_id')} GROUP BY 1
+ UNION ALL SELECT p.source_id, count(*) FROM timeline_entries te JOIN pages p ON p.id = te.page_id WHERE te.trust_tier = 'unknown' AND ${legacyRowSql('timeline_entries', 'te', ceilings)}${only('p.source_id')} GROUP BY 1
+ ) u GROUP BY source_id`, sourceIds ? [sourceIds] : undefined);
return new Map(rows.map(r => [r.source_id, Number(r.n)]));
}
diff --git a/src/schema.sql b/src/schema.sql
index b11a386aa0..6559d0bd9d 100644
--- a/src/schema.sql
+++ b/src/schema.sql
@@ -574,6 +574,7 @@ CREATE INDEX IF NOT EXISTS idx_links_from ON links(from_page_id);
CREATE INDEX IF NOT EXISTS idx_links_to ON links(to_page_id);
CREATE INDEX IF NOT EXISTS idx_links_source ON links(link_source);
CREATE INDEX IF NOT EXISTS idx_links_origin ON links(origin_page_id);
+CREATE INDEX IF NOT EXISTS idx_links_supersedes_to ON links (to_page_id) WHERE link_type = 'supersedes';
-- Wanted pages (migration wanted_links): authored links whose target page does
-- not exist. A live target updated after checked_at makes the origin stale for
diff --git a/test/cli-socket.test.ts b/test/cli-socket.test.ts
index c066479da2..2109ad61fa 100644
--- a/test/cli-socket.test.ts
+++ b/test/cli-socket.test.ts
@@ -32,13 +32,16 @@ import {
} from '../src/core/cli-socket/fs-guard.ts';
import { peerCredSupport } from '../src/core/cli-socket/peer-cred.ts';
import { startCliSocketServer, type CliSocketBinding } from '../src/core/cli-socket/server.ts';
-import { cliSocketRoundTripMs, exchangeCliSocket, renderOp } from '../src/cli/cli-socket-client.ts';
+import { cliSocketRoundTripMs, exchangeCliSocket, noteCliSocketRefusal, renderOp } from '../src/cli/cli-socket-client.ts';
+import { readRefusals } from '../src/core/cli-socket/refusals.ts';
+import { cliSocketRefusalsEntry } from '../src/commands/doctor/checks/cli-socket-refusals.ts';
import { loadOperation } from '../src/core/operation-load.ts';
import { isResultFrame, reviveOperationError, serializeOperationError, type CliSocketRequest, type ResultFrame } from '../src/core/cli-socket/protocol.ts';
import { queueFirstFallbackHop, takeChatFallbackHopNotices, __resetChatFallbackHopNoticeForTests } from '../src/core/ai/fallback-hop-queue.ts';
import { installOutputCapture, OutputCapture, withOutputCapture } from '../src/core/cli-socket/output-capture.ts';
import { opError, OperationError } from '../src/core/ops/contract.ts';
import { loadConfigWithEngine, type GBrainConfig } from '../src/core/config.ts';
+import { withEnv } from './helpers/with-env.ts';
const uid = process.getuid!();
const engine = { kind: 'postgres', connectedDatabaseUrl: 'postgresql://[email protected]/brain' } as unknown as BrainEngine;
@@ -183,9 +186,10 @@ describe('identity', () => {
homeWithConfig('a');
const env = (extra: Record<string, string>) => identity({ env: { GBRAIN_HOME: '/home/alice-example', ...extra } });
expect(cliSocketIdentityMismatch(env({ OPENAI_BASE_URL: 'http://127.0.0.1:11434/v1' }), env({ OPENAI_BASE_URL: 'https://api.openai.com/v1' }))).toBe('env OPENAI_BASE_URL');
+ const callable = { OPENROUTER_API_KEY: 'k', OPENAI_API_KEY: 'k', MINIMAX_API_KEY: 'k', AZURE_OPENAI_ENDPOINT: 'https://azure.acme-example.test', AZURE_OPENAI_DEPLOYMENT: 'd' };
for (const name of ['OLLAMA_BASE_URL', 'LMSTUDIO_BASE_URL', 'LLAMA_SERVER_BASE_URL', 'LLAMA_SERVER_RERANKER_BASE_URL', 'LITELLM_BASE_URL', 'OPENROUTER_BASE_URL',
'ANTHROPIC_BASE_URL', 'AZURE_OPENAI_ENDPOINT', 'AZURE_OPENAI_DEPLOYMENT', 'AZURE_OPENAI_API_VERSION', 'OPENAI_ORG_ID', 'OPENAI_PROJECT', 'MINIMAX_GROUP_ID']) {
- expect(cliSocketIdentityMismatch(env({ [name]: 'value-one' }), env({ [name]: 'value-two' })), name).toBe(`env ${name}`);
+ expect(cliSocketIdentityMismatch(env({ ...callable, [name]: 'value-one' }), env({ ...callable, [name]: 'value-two' })), name).toBe(`env ${name}`);
}
for (const name of ['OPENAI_API_KEY', 'AZURE_OPENAI_API_KEY', 'LLAMA_SERVER_API_KEY', 'VOYAGE_API_KEY']) {
expect(cliSocketIdentityMismatch(env({ [name]: 'value-one' }), env({ [name]: 'value-two' })), name).toBeNull();
@@ -195,6 +199,36 @@ describe('identity', () => {
expect(JSON.stringify(env({ VOYAGE_API_KEY: 'value-one' }))).not.toContain('value-one');
});
+ test('a routing variable of a provider neither side can call may differ; one that either side can call, from its environment or its config file, may not', () => {
+ homeWithConfig('a');
+ const env = (extra: Record<string, string>) => identity({ env: { GBRAIN_HOME: '/home/alice-example', ...extra } });
+ expect(cliSocketIdentityMismatch(env({}), env({ AZURE_OPENAI_API_VERSION: '2024-10-21' }))).toBeNull();
+ expect(cliSocketIdentityMismatch(env({ AZURE_OPENAI_API_VERSION: 'a' }), env({ AZURE_OPENAI_API_VERSION: 'b' }))).toBeNull();
+ expect(cliSocketIdentityMismatch(env({ OPENAI_ORG_ID: 'org-a' }), env({}))).toBeNull();
+ expect(cliSocketIdentityMismatch(env({ OPENROUTER_REFERER: 'a', MINIMAX_GROUP_ID: 'g' }), env({}))).toBeNull();
+ const azure = { AZURE_OPENAI_ENDPOINT: 'https://azure.acme-example.test', AZURE_OPENAI_DEPLOYMENT: 'd' };
+ expect(cliSocketIdentityMismatch(env({ ...azure, AZURE_OPENAI_API_VERSION: 'a' }), env({ ...azure }))).toBe('env AZURE_OPENAI_API_VERSION');
+ expect(cliSocketIdentityMismatch(env({ ...azure, AZURE_OPENAI_API_VERSION: 'a' }), env({ AZURE_OPENAI_API_VERSION: 'a' }))).toBe('env AZURE_OPENAI_API_VERSION');
+ expect(cliSocketIdentityMismatch(env({ AZURE_OPENAI_API_VERSION: 'a' }), env({ ...azure, AZURE_OPENAI_API_VERSION: 'a' }))).toBe('env AZURE_OPENAI_API_VERSION');
+ expect(cliSocketIdentityMismatch(env({ AZURE_OPENAI_API_KEY: 'k', AZURE_OPENAI_API_VERSION: 'a' }), env({ AZURE_OPENAI_API_KEY: 'k' }))).toBe('env AZURE_OPENAI_API_VERSION');
+ expect(cliSocketIdentityMismatch(env({ OPENAI_API_KEY: 'k', OPENAI_ORG_ID: 'org-a' }), env({ OPENAI_API_KEY: 'k' }))).toBe('env OPENAI_ORG_ID');
+ expect(cliSocketIdentityMismatch(env({ OLLAMA_BASE_URL: 'http://127.0.0.1:11434' }), env({}))).toBe('env OLLAMA_BASE_URL');
+ homeWithConfig('a', JSON.stringify({ engine: 'postgres', azure_openai_endpoint: 'https://azure.acme-example.test', azure_openai_deployment: 'd' }));
+ expect(cliSocketIdentityMismatch(env({ AZURE_OPENAI_API_VERSION: 'a' }), env({}))).toBe('env AZURE_OPENAI_API_VERSION');
+ });
+
+ test('narrowing never lets a caller borrow a credential or a provider it did not configure (who may connect is the uid check below, never the identity)', () => {
+ homeWithConfig('a');
+ const env = (extra: Record<string, string>) => identity({ env: { GBRAIN_HOME: '/home/alice-example', ...extra } });
+ for (const name of ['OPENAI_API_KEY', 'AZURE_OPENAI_API_KEY', 'VOYAGE_API_KEY', 'ANTHROPIC_API_KEY', 'TYPESAFE_API_KEY', 'JEV_TYPESAFE_API_KEY']) {
+ expect(cliSocketIdentityMismatch(env({ [name]: 'k' }), env({})), name).toBe(`provider key ${name}`);
+ expect(cliSocketIdentityMismatch(env({}), env({ [name]: 'k' })), name).toBe(`provider key ${name}`);
+ }
+ const azure = { AZURE_OPENAI_ENDPOINT: 'https://azure.acme-example.test', AZURE_OPENAI_DEPLOYMENT: 'd', AZURE_OPENAI_USE_ENTRA: '1' };
+ expect(cliSocketIdentityMismatch(env(azure), env({}))).not.toBeNull();
+ expect(cliSocketIdentityMismatch(env({}), env(azure))).not.toBeNull();
+ });
+
test('every GBRAIN_* name in src is classified: read behavior (READ_BEHAVIOR_ENV) or listed here as unable to change a socket read', () => {
const names = new Set<string>();
for (const file of new Bun.Glob('src/**/*.ts').scanSync('.')) {
@@ -336,7 +370,66 @@ describe('serve listener', () => {
expect(started.lines.filter(line => line.includes('identity_mismatch')).length).toBe(2);
});
- test('rejects a peer whose kernel uid differs, and one whose uid cannot be read', async () => {
+ test('a refusal is counted by part (never its value) for doctor cli_socket_refusals, and the CLI prints a degraded notice whatever GBRAIN_DEBUG says', async () => {
+ const { binding, path } = await start();
+ const drifted = { ...serveIdentity(), env: { values: { AZURE_OPENAI_API_VERSION: 'f'.repeat(64) }, credentials: [] } };
+ for (let i = 0; i < 3; i++) expect(await exchangeCliSocket(path, request(drifted), 5_000)).toEqual({ reason: 'refused (identity_mismatch): env AZURE_OPENAI_API_VERSION' });
+ expect(await exchangeCliSocket(path, request({ ...serveIdentity(), version: '1.0.1' }), 5_000)).toHaveProperty('reason');
+ binding!.close();
+ bindings.length = 0;
+ const record = readRefusals(join(root, 'home', '.gbrain', 'run'))!;
+ expect(record.parts['env AZURE_OPENAI_API_VERSION']!.count).toBe(3);
+ expect(record.parts.version!.count).toBe(1);
+ expect(JSON.stringify(record)).not.toContain('f'.repeat(64));
+ await withEnv({ GBRAIN_HOME: join(root, 'home') }, async () => {
+ const [check] = await cliSocketRefusalsEntry.run({} as never) as unknown as Array<{ status: string; message: string; details: { refusals: number } }>;
+ expect(check!.status).toBe('warn');
+ expect(check!.details.refusals).toBe(4);
+ expect(check!.message).toContain('env AZURE_OPENAI_API_VERSION differs');
+ rmSync(join(root, 'home', '.gbrain', 'run', 'cli-socket-refusals.json'));
+ expect((await cliSocketRefusalsEntry.run({} as never) as Array<{ status: string }>)[0]!.status).toBe('ok');
+ });
+ const err: string[] = [];
+ const write = process.stderr.write.bind(process.stderr);
+ const writeOut = process.stdout.write.bind(process.stdout);
+ const capture = ((chunk: string | Uint8Array) => { err.push(String(chunk)); return true; }) as typeof process.stderr.write;
+ process.stderr.write = capture;
+ process.stdout.write = capture;
+ try {
+ await withEnv({ GBRAIN_DEBUG: undefined }, async () => {
+ await noteCliSocketRefusal('refused (identity_mismatch): env AZURE_OPENAI_API_VERSION');
+ await noteCliSocketRefusal('refused (busy)');
+ await noteCliSocketRefusal('connect_failed (ENOENT)');
+ });
+ } finally {
+ process.stderr.write = write;
+ process.stdout.write = writeOut;
+ }
+ const printed = err.join('');
+ expect(printed).toContain('socket_identity_mismatch');
+ expect(printed).toContain('env AZURE_OPENAI_API_VERSION differs');
+ expect(printed).toContain('gbrain doctor --only cli_socket_refusals --json');
+ expect(printed.match(/socket_identity_mismatch/g)!.length).toBe(1);
+ });
+
+ test('a client that goes away before its answer aborts the request\'s signal, and the serve logs it', async () => {
+ let seen: AbortSignal | undefined;
+ let release!: () => void;
+ const settled = new Promise<void>(resolve => { release = resolve; });
+ const { path, lines } = await start({ execute: async (_request, signal) => {
+ seen = signal;
+ await new Promise<void>(resolve => signal.addEventListener('abort', () => resolve(), { once: true }));
+ release();
+ return { frame: okFrame, settled };
+ } });
+ expect(await exchangeCliSocket(path, request(serveIdentity()), 300)).toEqual({ reason: 'round_trip_timeout' });
+ await settled;
+ expect(seen!.aborted).toBe(true);
+ expect(String((seen!.reason as Error).message)).toBe('client_disconnected');
+ expect(lines.join('\n')).toMatch(/a search request's client disconnected after \d+ ms; its remaining work is cancelled\./);
+ });
+
+ test('rejects a peer whose kernel uid differs, and one whose uid cannot be read, even when it presents the serve\'s exact identity', async () => {
let calls = 0;
// The first read is the start-up self-test on this process's own connection.
const { binding, path, lines } = await start({ peerCred: { ok: true, read: () => (calls++ === 0 ? uid : uid + 1) } });
diff --git a/test/e2e/cli-socket-postgres.test.ts b/test/e2e/cli-socket-postgres.test.ts
index e92dfce767..4548e295db 100644
--- a/test/e2e/cli-socket-postgres.test.ts
+++ b/test/e2e/cli-socket-postgres.test.ts
@@ -57,6 +57,12 @@ describe.skipIf(!DATABASE_URL)('warm CLI socket (postgres)', () => {
return { stdout, stderr, exitCode };
}
+ /** The [AGENT] block a refused non-JSON call prints on stdout before the cold path's output. */
+ function refusedNotice(part: string): string {
+ const why = `[socket_identity_mismatch] The running serve's warm CLI socket refused this call because ${part} differs from the serve's (the value is never shown), so it ran on the slower cold path. Every call from this environment does until that part matches the serve's.`;
+ return `[AGENT]\nwhy: ${why}\nactor: agent\nnext: run: gbrain doctor --only cli_socket_refusals --json --brain host\n[/AGENT]\n`;
+ }
+
function traceFile(): string { return join(home, `trace-${traceSeq++}.jsonl`); }
function tripLines(file: string): string[] {
if (!existsSync(file)) return [];
@@ -215,7 +221,7 @@ describe.skipIf(!DATABASE_URL)('warm CLI socket (postgres)', () => {
try {
const run = await cli(READS.search!, { GBRAIN_DEBUG: '1' });
expect(run.stderr).toContain('[cli-socket] cold path: refused (identity_mismatch): config contents');
- expect(run.stdout).toBe(cold.get('search')!.stdout);
+ expect(run.stdout).toBe(refusedNotice('config contents') + cold.get('search')!.stdout);
expect(run.exitCode).toBe(0);
} finally {
writeFileSync(configFile, original);
@@ -236,8 +242,36 @@ describe.skipIf(!DATABASE_URL)('warm CLI socket (postgres)', () => {
for (const [extra, part] of extras) {
const run = await cli(READS.search!, { GBRAIN_DEBUG: '1', ...extra });
expect(run.stderr).toContain(`[cli-socket] cold path: refused (identity_mismatch): ${part}`);
- expect(run.stdout).toBe(cold.get('search')!.stdout);
+ expect(run.stdout).toBe(refusedNotice(part) + cold.get('search')!.stdout);
}
+ // GBRA-156: without GBRAIN_DEBUG the refusal is still printed (an [AGENT] block on a non-TTY stdout; stderr under --json).
+ const quiet = await cli(READS.search!, { GBRAIN_CONTRIBUTOR_MODE: '1' });
+ expect(quiet.stdout).toBe(refusedNotice('env GBRAIN_CONTRIBUTOR_MODE') + cold.get('search')!.stdout);
+ const quietJson = await cli(READS['search --json']!, { GBRAIN_CONTRIBUTOR_MODE: '1' });
+ expect(quietJson.stdout).toBe(cold.get('search --json')!.stdout);
+ expect(quietJson.stderr).toContain('[socket_identity_mismatch]');
+ }, 90_000);
+
+ test('a variable of a provider neither side can call (an Azure API version, no Azure endpoint) no longer refuses: answered warm', async () => {
+ const trace = traceFile();
+ const run = await cli(READS.search!, { GBRAIN_DEBUG: '1', GBRAIN_SQL_TRACE: trace, AZURE_OPENAI_API_VERSION: '2024-10-21', OPENAI_ORG_ID: 'org-example' });
+ expect(run.stderr).not.toContain('[cli-socket] cold path');
+ expect(roundTrips(trace)).toBe(0);
+ expect({ stdout: run.stdout, exitCode: run.exitCode }).toEqual({ stdout: cold.get('search')!.stdout, exitCode: 0 });
+ }, 90_000);
+
+ test('a request that reaches its round-trip cap answers a retryable timeout error (not a cold rerun), and its slot is free again', async () => {
+ const identity = cliSocketIdentity({ config: { engine: 'postgres', database_url: databaseUrl }, brainId: 'host', configDir: join(home, '.gbrain'), configFile, version: VERSION, env });
+ const capped = await exchangeCliSocket(socketPath, { v: 1, identity, command: 'search', kind: 'op', op: 'search', params: { query: WORD },
+ routing: { cwd: process.cwd(), source_env: null }, cli: { quiet: false, timeout_ms: 1 } }, 30_000);
+ expect(capped).toMatchObject({ frame: { kind: 'error', error: { code: 'timeout', reason: 'cli_socket_round_trip_cap', retryable: true } } });
+ const run = await cli(['search', WORD, '--timeout=1ms']);
+ expect(run.exitCode).toBe(124);
+ expect(run.stdout).toContain('[AGENT]');
+ expect(run.stdout).toContain('[timeout] gbrain search did not finish within 1 ms on the warm CLI socket');
+ const after = await cli(READS.search!, { GBRAIN_DEBUG: '1' });
+ expect(after.stderr).not.toContain('[cli-socket] cold path');
+ expect(after.stdout).toBe(cold.get('search')!.stdout);
}, 90_000);
test('a CLI that differs only in connection sizing and driver-only URL parameters is answered warm', async () => {
diff --git a/test/e2e/search-read-pipeline-postgres.test.ts b/test/e2e/search-read-pipeline-postgres.test.ts
index 2aacd2795e..8d18a455cb 100644
--- a/test/e2e/search-read-pipeline-postgres.test.ts
+++ b/test/e2e/search-read-pipeline-postgres.test.ts
@@ -48,8 +48,10 @@ run('search read transactions pipeline their body behind BEGIN (direct pool)', (
});
await Bun.sleep(1200);
const records = readSqlTrace(trace).filter(r => (r as { label?: string }).label === 'search-read-direct' && r.kind !== 'connect').sort((a, b) => a.t - b.t);
- const measured = records.slice(records.findLastIndex(r => /^begin read write$/i.test(r.sql)));
+ // GBRA-156: a search read transaction opens read-only, so no write can commit inside it.
+ const measured = records.slice(records.findLastIndex(r => /^begin read only$/i.test(r.sql)));
const begin = measured[0]!;
+ expect(begin.sql).toMatch(/^begin read only$/i);
const settings = measured.find(r => /^SELECT set_config\('jit'/.test(r.sql))!;
const title = measured.find(r => /WITH top_pages AS/.test(r.sql))!;
expect(rows).toBeGreaterThan(0);
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
index 96e209d5a8..0b21cf8848 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
@@ -1193,6 +1193,7 @@
"idx_links_from": "CREATE INDEX idx_links_from ON public.links USING btree (from_page_id)",
"idx_links_origin": "CREATE INDEX idx_links_origin ON public.links USING btree (origin_page_id)",
"idx_links_source": "CREATE INDEX idx_links_source ON public.links USING btree (link_source)",
+ "idx_links_supersedes_to": "CREATE INDEX idx_links_supersedes_to ON public.links USING btree (to_page_id) WHERE (link_type = 'supersedes'::text)",
"idx_links_to": "CREATE INDEX idx_links_to ON public.links USING btree (to_page_id)",
"idx_mcp_log_agent_time": "CREATE INDEX idx_mcp_log_agent_time ON public.mcp_request_log USING btree (agent_name, created_at DESC)",
"idx_mcp_log_time_agent": "CREATE INDEX idx_mcp_log_time_agent ON public.mcp_request_log USING btree (created_at, token_name)",
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
index d25271865d..aec85815da 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
@@ -1193,6 +1193,7 @@
"idx_links_from": "CREATE INDEX idx_links_from ON public.links USING btree (from_page_id)",
"idx_links_origin": "CREATE INDEX idx_links_origin ON public.links USING btree (origin_page_id)",
"idx_links_source": "CREATE INDEX idx_links_source ON public.links USING btree (link_source)",
+ "idx_links_supersedes_to": "CREATE INDEX idx_links_supersedes_to ON public.links USING btree (to_page_id) WHERE (link_type = 'supersedes'::text)",
"idx_links_to": "CREATE INDEX idx_links_to ON public.links USING btree (to_page_id)",
"idx_mcp_log_agent_time": "CREATE INDEX idx_mcp_log_agent_time ON public.mcp_request_log USING btree (agent_name, created_at DESC)",
"idx_mcp_log_time_agent": "CREATE INDEX idx_mcp_log_time_agent ON public.mcp_request_log USING btree (created_at, token_name)",
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
index cb3ecd5e65..e0883f0bc1 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
@@ -1191,6 +1191,7 @@
"idx_links_from": "CREATE INDEX idx_links_from ON public.links USING btree (from_page_id)",
"idx_links_origin": "CREATE INDEX idx_links_origin ON public.links USING btree (origin_page_id)",
"idx_links_source": "CREATE INDEX idx_links_source ON public.links USING btree (link_source)",
+ "idx_links_supersedes_to": "CREATE INDEX idx_links_supersedes_to ON public.links USING btree (to_page_id) WHERE (link_type = 'supersedes'::text)",
"idx_links_to": "CREATE INDEX idx_links_to ON public.links USING btree (to_page_id)",
"idx_mcp_log_agent_time": "CREATE INDEX idx_mcp_log_agent_time ON public.mcp_request_log USING btree (agent_name, created_at DESC)",
"idx_mcp_log_time_agent": "CREATE INDEX idx_mcp_log_time_agent ON public.mcp_request_log USING btree (created_at, token_name)",
diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
index 35b0e24d33..bc74d5283f 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
@@ -894,6 +894,7 @@
"idx_links_from": "CREATE INDEX idx_links_from ON public.links USING btree (from_page_id)",
"idx_links_origin": "CREATE INDEX idx_links_origin ON public.links USING btree (origin_page_id)",
"idx_links_source": "CREATE INDEX idx_links_source ON public.links USING btree (link_source)",
+ "idx_links_supersedes_to": "CREATE INDEX idx_links_supersedes_to ON public.links USING btree (to_page_id) WHERE (link_type = 'supersedes'::text)",
"idx_links_to": "CREATE INDEX idx_links_to ON public.links USING btree (to_page_id)",
"idx_mcp_log_agent_time": "CREATE INDEX idx_mcp_log_agent_time ON public.mcp_request_log USING btree (agent_name, created_at DESC)",
"idx_mcp_log_time_agent": "CREATE INDEX idx_mcp_log_time_agent ON public.mcp_request_log USING btree (created_at, token_name)",
diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json
index 583a826803..f250bbb6dd 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json
@@ -894,6 +894,7 @@
"idx_links_from": "CREATE INDEX idx_links_from ON public.links USING btree (from_page_id)",
"idx_links_origin": "CREATE INDEX idx_links_origin ON public.links USING btree (origin_page_id)",
"idx_links_source": "CREATE INDEX idx_links_source ON public.links USING btree (link_source)",
+ "idx_links_supersedes_to": "CREATE INDEX idx_links_supersedes_to ON public.links USING btree (to_page_id) WHERE (link_type = 'supersedes'::text)",
"idx_links_to": "CREATE INDEX idx_links_to ON public.links USING btree (to_page_id)",
"idx_mcp_log_agent_time": "CREATE INDEX idx_mcp_log_agent_time ON public.mcp_request_log USING btree (agent_name, created_at DESC)",
"idx_mcp_log_time_agent": "CREATE INDEX idx_mcp_log_time_agent ON public.mcp_request_log USING btree (created_at, token_name)",
diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json
index 528833041b..64a06b07c3 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json
@@ -893,6 +893,7 @@
"idx_links_from": "CREATE INDEX idx_links_from ON public.links USING btree (from_page_id)",
"idx_links_origin": "CREATE INDEX idx_links_origin ON public.links USING btree (origin_page_id)",
"idx_links_source": "CREATE INDEX idx_links_source ON public.links USING btree (link_source)",
+ "idx_links_supersedes_to": "CREATE INDEX idx_links_supersedes_to ON public.links USING btree (to_page_id) WHERE (link_type = 'supersedes'::text)",
"idx_links_to": "CREATE INDEX idx_links_to ON public.links USING btree (to_page_id)",
"idx_mcp_log_agent_time": "CREATE INDEX idx_mcp_log_agent_time ON public.mcp_request_log USING btree (agent_name, created_at DESC)",
"idx_mcp_log_time_agent": "CREATE INDEX idx_mcp_log_time_agent ON public.mcp_request_log USING btree (created_at, token_name)",
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-default.json b/test/fixtures/goldens/catalog/postgres-engine-init-default.json
index 69f8598652..59def43b49 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-default.json
@@ -1196,6 +1196,7 @@
"idx_links_from": "CREATE INDEX idx_links_from ON public.links USING btree (from_page_id)",
"idx_links_origin": "CREATE INDEX idx_links_origin ON public.links USING btree (origin_page_id)",
"idx_links_source": "CREATE INDEX idx_links_source ON public.links USING btree (link_source)",
+ "idx_links_supersedes_to": "CREATE INDEX idx_links_supersedes_to ON public.links USING btree (to_page_id) WHERE (link_type = 'supersedes'::text)",
"idx_links_to": "CREATE INDEX idx_links_to ON public.links USING btree (to_page_id)",
"idx_mcp_log_agent_time": "CREATE INDEX idx_mcp_log_agent_time ON public.mcp_request_log USING btree (agent_name, created_at DESC)",
"idx_mcp_log_time_agent": "CREATE INDEX idx_mcp_log_time_agent ON public.mcp_request_log USING btree (created_at, token_name)",
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
index 367517a73b..fff8836057 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
@@ -1196,6 +1196,7 @@
"idx_links_from": "CREATE INDEX idx_links_from ON public.links USING btree (from_page_id)",
"idx_links_origin": "CREATE INDEX idx_links_origin ON public.links USING btree (origin_page_id)",
"idx_links_source": "CREATE INDEX idx_links_source ON public.links USING btree (link_source)",
+ "idx_links_supersedes_to": "CREATE INDEX idx_links_supersedes_to ON public.links USING btree (to_page_id) WHERE (link_type = 'supersedes'::text)",
"idx_links_to": "CREATE INDEX idx_links_to ON public.links USING btree (to_page_id)",
"idx_mcp_log_agent_time": "CREATE INDEX idx_mcp_log_agent_time ON public.mcp_request_log USING btree (agent_name, created_at DESC)",
"idx_mcp_log_time_agent": "CREATE INDEX idx_mcp_log_time_agent ON public.mcp_request_log USING btree (created_at, token_name)",
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
index 1bf87c2207..35c80b63e3 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
@@ -1194,6 +1194,7 @@
"idx_links_from": "CREATE INDEX idx_links_from ON public.links USING btree (from_page_id)",
"idx_links_origin": "CREATE INDEX idx_links_origin ON public.links USING btree (origin_page_id)",
"idx_links_source": "CREATE INDEX idx_links_source ON public.links USING btree (link_source)",
+ "idx_links_supersedes_to": "CREATE INDEX idx_links_supersedes_to ON public.links USING btree (to_page_id) WHERE (link_type = 'supersedes'::text)",
"idx_links_to": "CREATE INDEX idx_links_to ON public.links USING btree (to_page_id)",
"idx_mcp_log_agent_time": "CREATE INDEX idx_mcp_log_agent_time ON public.mcp_request_log USING btree (agent_name, created_at DESC)",
"idx_mcp_log_time_agent": "CREATE INDEX idx_mcp_log_time_agent ON public.mcp_request_log USING btree (created_at, token_name)",
diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.json
index 0f07bd305c..aee8a07013 100644
--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json
+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json
@@ -2968,6 +2968,17 @@
"name": "runtime_build_skew",
"status": "ok"
},
+ {
+ "category": "ops",
+ "details": {
+ "docs": "docs/guides/cli-socket.md",
+ "refusals": 0
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "The warm CLI socket refused no CLI call in the last 24 hours.",
+ "name": "cli_socket_refusals",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
diff --git a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
index 7ae0dd23aa..504a795407 100644
--- a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
+++ b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
@@ -1193,6 +1193,7 @@
"idx_links_from": "CREATE INDEX idx_links_from ON public.links USING btree (from_page_id)",
"idx_links_origin": "CREATE INDEX idx_links_origin ON public.links USING btree (origin_page_id)",
"idx_links_source": "CREATE INDEX idx_links_source ON public.links USING btree (link_source)",
+ "idx_links_supersedes_to": "CREATE INDEX idx_links_supersedes_to ON public.links USING btree (to_page_id) WHERE (link_type = 'supersedes'::text)",
"idx_links_to": "CREATE INDEX idx_links_to ON public.links USING btree (to_page_id)",
"idx_mcp_log_agent_time": "CREATE INDEX idx_mcp_log_agent_time ON public.mcp_request_log USING btree (agent_name, created_at DESC)",
"idx_mcp_log_time_agent": "CREATE INDEX idx_mcp_log_time_agent ON public.mcp_request_log USING btree (created_at, token_name)",
diff --git a/test/response-deferral.test.ts b/test/response-deferral.test.ts
new file mode 100644
index 0000000000..0b7d5e10a4
--- /dev/null
+++ b/test/response-deferral.test.ts
@@ -0,0 +1,39 @@
+/**
+ * GBRA-156: search-time writes start after the response inside a request that defers them (the warm CLI socket), and
+ * at once everywhere else (a cold CLI drains them before exit). Fails when: a sink starts mid-request inside a scope,
+ * a write deferred by a scope never starts, or a sink outside any scope waits for a release that never comes.
+ */
+import { describe, expect, test } from 'bun:test';
+import { deferUntilResponse, withResponseDeferral } from '../src/core/background-work.ts';
+import { bumpLastRetrievedAt, BUMP_LAST_RETRIEVED_SQL, _resetTrackRetrievalCacheForTests } from '../src/core/last-retrieved.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+
+describe('response deferral', () => {
+ test('outside a scope a write starts at once; inside one it waits for release, and one deferred after release starts at once', async () => {
+ const started: string[] = [];
+ deferUntilResponse(() => started.push('outside'));
+ expect(started).toEqual(['outside']);
+ const { value, release } = await withResponseDeferral(async () => {
+ deferUntilResponse(() => started.push('first'));
+ await Promise.resolve();
+ deferUntilResponse(() => started.push('second'));
+ expect(started).toEqual(['outside']);
+ return 'answer';
+ });
+ expect(value).toBe('answer');
+ expect(started).toEqual(['outside']);
+ expect(release()).toBe(2);
+ expect(started).toEqual(['outside', 'first', 'second']);
+ });
+
+ test('the page_retrievals bump issued mid-request reaches the database only after release', async () => {
+ _resetTrackRetrievalCacheForTests();
+ const statements: string[] = [];
+ const engine = { getConfig: async () => null, executeRaw: async (sql: string) => { statements.push(sql); return []; } } as unknown as BrainEngine;
+ const { release } = await withResponseDeferral(async () => { bumpLastRetrievedAt(engine, [1, 2]); await new Promise(r => setTimeout(r, 20)); });
+ expect(statements).toEqual([]);
+ release();
+ await new Promise(r => setTimeout(r, 20));
+ expect(statements).toEqual([BUMP_LAST_RETRIEVED_SQL]);
+ });
+});
diff --git a/test/sweep.test.ts b/test/sweep.test.ts
index fef92f5ea5..fab7c3a661 100644
--- a/test/sweep.test.ts
+++ b/test/sweep.test.ts
@@ -27,6 +27,7 @@ import { _resetStdoutRedirectForTests } from '../src/core/console-prefix.ts';
import type { CapabilityReport } from '../src/core/capability.ts';
import { __setChatTransportForTests, type ChatResult } from '../src/core/ai/gateway.ts';
import { runServe, type ServeOptions } from '../src/commands/serve.ts';
+import { beginForegroundRequest, _resetForegroundActivityForTests } from '../src/core/foreground-activity.ts';
import { spoolPath } from './helpers/corpus-spool.ts';
import { withEnv } from './helpers/with-env.ts';
import { runExtract } from '../src/commands/extract.ts';
@@ -851,6 +852,35 @@ describe('serve.ts idle sweep wiring [ENG-5]', () => {
expect(h.timers.cleared).toContain(handle);
});
+ test('a warm CLI socket request (foreground-activity.ts) counts as activity: a tick after one, or during one, skips the sweep', async () => {
+ _resetForegroundActivityForTests();
+ const sweepCalls: BrainEngine[] = [];
+ const h = makeServeHarness({ sweepEnabled: true, sweep: async (e) => { sweepCalls.push(e); } });
+ await runServe(h.engineStub, [], h.serveOpts);
+ const { fn } = h.timers.registered[0];
+ fn(); // attach listener
+ await new Promise(r => setTimeout(r, 5));
+ beginForegroundRequest()();
+ fn();
+ await settle();
+ expect(sweepCalls.length).toBe(0);
+ const finish = beginForegroundRequest();
+ await new Promise(r => setTimeout(r, 5));
+ fn();
+ await settle();
+ expect(sweepCalls.length).toBe(0);
+ finish();
+ await new Promise(r => setTimeout(r, 5));
+ fn(); // the window still saw the request finish
+ await settle();
+ expect(sweepCalls.length).toBe(0);
+ fn(); // a quiet window
+ await settle();
+ expect(sweepCalls.length).toBe(1);
+ h.stdin.emit('end');
+ expect(await h.exited).toBe(0);
+ });
+
test('a rejecting sweep never kills the serve', async () => {
const h = makeServeHarness({
sweepEnabled: true,
diff --git a/test/trust-claim.test.ts b/test/trust-claim.test.ts
index d600c9f0cf..c1f63272cf 100644
--- a/test/trust-claim.test.ts
+++ b/test/trust-claim.test.ts
@@ -25,7 +25,7 @@ import type { BrainEngine } from '../src/core/engine.ts';
import { renderAction, type Action } from '../src/core/agent-output.ts';
import { __setConfirmationIoForTests } from '../src/core/trust/confirm.ts';
import { frontmatterTrustCaps, frontmatterTrustCapsSql } from '../src/core/trust/channel.ts';
-import { claimSourcesFix, listClaimSources, liftClaimedSources, recordSourceClaims, readUnclaimedLegacySources } from '../src/core/trust/claim.ts';
+import { claimSourcesFix, hasUnclaimedLegacySources, listClaimSources, liftClaimedSources, recordSourceClaims, readUnclaimedLegacySources } from '../src/core/trust/claim.ts';
import { TRUST_CLAIM_LIFTED_AT_KEY, TRUST_CLAIMED_AT_KEY } from '../src/core/trust/claim-state.ts';
import { trustClaimUpgradeNotice } from '../src/core/trust/claim-notice.ts';
import { runTrustBackfill } from '../src/core/trust/backfill.ts';
@@ -303,6 +303,18 @@ describe('the asks around claiming', () => {
expect(fix.user_message).toContain('claim');
});
+ test('the claim ask reads row tables only for unclaimed sources, and agrees with the doctor read', async () => {
+ const s = await seed();
+ expect(await hasUnclaimedLegacySources(engine)).toBe(true);
+ expect((await readUnclaimedLegacySources(engine)).unclaimed.map(u => u.id)).toContain(s.src);
+ const seen: string[] = [];
+ const allClaimed = { executeRaw: async (sql: string) => { seen.push(sql); return /FROM sources/.test(sql) ? [{ id: 'a', claimed: true, lifted: true }] as never[] : []; } };
+ expect(await hasUnclaimedLegacySources(allClaimed as never)).toBe(false);
+ expect(await readUnclaimedLegacySources(allClaimed as never)).toEqual({ unclaimed: [], pending: [] });
+ expect(seen.length).toBe(2);
+ expect(seen.some(sql => /\b(pages|facts|takes|timeline_entries)\b/.test(sql))).toBe(false);
+ });
+
test('post-upgrade and the behavior-change notice carry the tell_user_to_run block', async () => {
await seed();
const lines = (await trustClaimUpgradeNotice(engine))!.join('\n');