Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(search): disclose the telemetry coverage gap in search stats/tune (#4079)
Masad941e9f91823
diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.mdindex 6eb4447e8c..cff2e290a7 100644--- a/docs/architecture/KEY_FILES.md+++ b/docs/architecture/KEY_FILES.md@@ -25,7 +25,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `src/core/audit/audit-writer.ts` — shared JSONL audit primitive consolidating the hand-rolled audit modules. Exports `createAuditWriter({kind, recordSchema})` returning `{log, readRecent}` plus shared helpers `computeIsoWeekFilename(kind, now?)` and `resolveAuditDir()` (honors `GBRAIN_AUDIT_DIR`). ISO-week file rotation; best-effort writes (stderr warn on failure, never throws); read-path scans current-week + previous-week files for boundary spans. Refactored onto it for parity: `src/core/rerank-audit.ts`, `src/core/audit-slug-fallback.ts`, `src/core/minions/handlers/shell-audit.ts`, `src/core/minions/handlers/supervisor-audit.ts`, `src/core/facts/phantom-audit.ts` (each module's public API preserved bit-for-bit). The `graph-signals-failures` audit (`logGraphSignalsFailure`) uses the same primitive. One hand-rolled audit remains at `src/core/skillpack/audit.ts`. Pinned by `test/audit/audit-writer.test.ts`.- `src/core/cli-force-exit.ts` (#2084) — single owner of one-shot CLI exit + teardown, designed as a PAIR with the `import.meta.main` seam at the bottom of `src/cli.ts`. `finishCliTeardown({engine, drainTimeoutMs?})` is teardown-ONLY (never exits on the clean path): arms a REF'D backstop (unref'd would let a hung teardown exit naturally, skipping the flush and exiting with whatever PGLite scribbled into `process.exitCode`) whose deadline is COMPUTED from the bounds it guards (`computeTeardownDeadlineMs` = sinks × drainTimeoutMs + facts-abort grace + 2 × pool-end bound + slack, floor 10s; `GBRAIN_TEARDOWN_DEADLINE_MS` env override is the incident escape hatch), drains every background-work sink, disconnects the engine (a throw is warned + swallowed — the exit code reports the OPERATION, not the cleanup), then returns. The exit VERDICT lives in a gbrain-owned channel (`setCliExitVerdict`/`currentExitCode`; mirror-writes `process.exitCode` but NEVER reads it back) because PGLite's Emscripten runtime scribbles its own status into `process.exitCode` at arbitrary points mid-run — every writer that means to set the CLI exit code (op-dispatch catch, reindex, frontmatter, transcripts, brainstorm, autopilot, doctor's FAIL verdict, extract, and cli.ts's swept inner exits — friction, claw-test, smoke-test, the no-DB eval runners, status/status-thin, whoknows-thin) calls `setCliExitVerdict`; `test/cli-exit-verdict-pin.test.ts` greps src/ so the next raw `process.exitCode =` write fails CI instead of silently reporting success on failure. The deadline arms at TEARDOWN start, never before the op handler (the pre-#2084 placement measured handler + teardown combined, so PgBouncer deployments paid a flat 10s force-exit tax on every query and any >10s op was killed mid-run with exit 0). All nine cli.ts disconnect sites route through it; the ONE process exit happens in cli.ts's `main().then/catch` via `flushThenExit(currentExitCode())`, gated by `shouldForceExitAfterMain()` (daemon list: `serve`) — the CLI never waits for Bun's event loop to drain, because `endPoolBounded` deliberately races past stuck PgBouncer sockets that would keep it alive. `flushThenExit(code)` fences stdout+stderr (`write('', cb)` raced with an unref'd guard, EPIPE-safe both sync and async) then holds a REF'D aliveness grace for non-TTY stdio before `process.exit` — Bun delivers queued pipe writes only while the process is alive (no flush API reaches `process.stdout`'s native queue; write callbacks fire on accept, not delivery), so the grace IS the flush (#1959 truncation class). Scope claim is deliberately cli.ts-only: command modules' mid-run engine lifecycles stay local (process-exit semantics inside them would be wrong) and are absorbed by the final explicit exit. Pinned by `test/cli-finish-teardown.test.ts`, `test/flush-then-exit-harness.test.ts` (real spawned-Bun pipe semantics), `test/cli-should-force-exit.test.ts`, `test/cli-pipe-truncation.test.ts` (real-CLI piped --tools-json byte-stable), `test/cli-exit-verdict-pin.test.ts`, the `#2084` describes in `test/fix-wave-structural.test.ts` + `test/e2e/pglite-cli-exit.serial.test.ts`, and `test/e2e/pgbouncer-teardown.test.ts` (CI transaction-mode pooler — the #1972/#2015/#2084 class, finally reproducible in CI).-- `src/commands/search.ts:gbrain search stats` — `graph_signals` section (enabled/source/failures_count/failures_by_reason). JSON envelope adds a `graph_signals` sibling property; `_meta.metric_glossary` adds `graph_signals.enabled` + `graph_signals.failures_by_reason`. Human output prints the section after the existing block. Reads `search.graph_signals` config first, falls back to the mode default. Pinned by `test/search/search-stats-graph-signals.test.ts`.+- `src/commands/search.ts:gbrain search stats` — `graph_signals` section (enabled/source/failures_count/failures_by_reason). JSON envelope adds a `graph_signals` sibling property; `_meta.metric_glossary` adds `graph_signals.enabled` + `graph_signals.failures_by_reason`. Human output prints the section after the existing block. Reads `search.graph_signals` config first, falls back to the mode default. Pinned by `test/search/search-stats-graph-signals.test.ts`. Both `gbrain search stats` and `gbrain search tune` also surface a `coverage` disclosure (JSON: `{cli_invocations: 'typically_not_recorded', reason}`; human: a one-line caveat) sourced from `telemetryCoverage()`/`TELEMETRY_COVERAGE_CAVEAT` in `src/core/search/telemetry.ts`, documenting that the underlying `search_telemetry` buffer favors long-lived processes (serve/MCP/jobs work) and typically drops a lone short-lived CLI search call before its flush timer/threshold fires — display-only, no telemetry behavior change. Pinned by the coverage-disclosure tests in `test/commands-search.test.ts`.- `src/core/engine-factory.ts` — Engine factory with dynamic imports (`'pglite'` | `'postgres'`).- `src/core/pglite-engine.ts` — PGLite (embedded Postgres 17.5 via WASM) implementation, all BrainEngine methods. `listLinkSources({sourceId?, sourceIds?})` returns distinct `link_source` provenances + counts (`ORDER BY count DESC, link_source ASC NULLS LAST`; scalar + federated scoped; parity with postgres-engine.ts) powering `gbrain link-sources`. `addLinksBatch`/`addTimelineEntriesBatch`/`addTakesBatch` pass the whole batch as one JSONB document via `jsonb_to_recordset(($1::jsonb)->'rows')` (bound through `executeRawJsonb` with a `{ rows }` wrapper; rows built by the shared `src/core/batch-rows.ts` helpers, NUL-stripped), and are `batchRetry`-wrapped. `connect()` wraps `PGlite.create()` in a try/catch that classifies the failure and, for the `wasm-abort` verdict on a persistent data dir (torn WAL/checkpoint state after an unclean shutdown — the #223/#1670/#2575 class, historically misdiagnosed as a macOS WASM bug), runs in-place auto-repair via `attemptWalRepairAndRetry` (static import from `pglite-repair.ts`, #3596 engine-live rule; the retry create is `preservingProcessExitCode`-wrapped; success sets the public `walRepairReceipt` field + prints `buildWalRepairNotice` to stderr and returns with the lock held). The seam never throws, so every non-repaired path funnels through the single lock-release-then-throw site; repair refuses when the lock was acquired by reaping (`LockHandle.reaped` → `'possibly-live-writer'`), when disabled (`GBRAIN_PGLITE_WAL_REPAIR=off`), on layout-validation failure, or inside the post-failure cooldown. `searchKeyword`/`searchKeywordChunks` multiply `ts_rank` by the source-factor CASE at chunk grain; `searchVector` is a two-stage CTE — inner CTE keeps `ORDER BY cc.embedding <=> vec` so HNSW stays usable, outer SELECT re-ranks by `raw_score * source_factor`, inner LIMIT scales with offset to preserve pagination. `searchTakes`/`searchTakesVector` take full `SearchOpts` and apply the standard source-scope predicates (federated `sourceIds[]` wins over scalar `sourceId`, via the joined page's `source_id`) alongside the holder allow-list — parity SQL in postgres-engine.ts; pinned by `test/e2e/think-source-isolation-pglite.test.ts`. `initSchema()` calls `applyForwardReferenceBootstrap()` BEFORE replaying SCHEMA_SQL — probes for forward-referenced state the embedded blob needs (`pages.source_id`, `links.link_source`, `links.origin_page_id`, `content_chunks.symbol_name`, `content_chunks.language`, `sources` FK target, plus `files.source_id`, `files.page_id`, `oauth_clients.source_id`, `oauth_clients.federated_read`, `sources.archived`, `sources.archived_at`, `sources.archive_expires_at`, `timeline_entries.event_page_id` — column-only, migration v121 stays the source of truth for its FK + indexes) and adds only what's missing; threads the DDL connection from `initSchema` so probes run inside the advisory-lock scope; no-op on fresh installs and modern brains (closes the upgrade-wedge bug class #239/#243/#266/#357/#366/#374/#375/#378/#395/#396/#1018/#974/#820). `getBrainScore` returns 100/100 with full breakdown (35/25/15/15/10) when `pageCount === 0` (vacuous truth — empty brain has no coverage problem); Pinned by `test/brain-score-breakdown.test.ts` empty-brain assertion + `test/doctor-report-remote.serial.test.ts`. `disconnect()` uses snapshot+early-null (snapshot `_db`/`_lock`, null instance fields BEFORE any `await` so a concurrent `connect()` can't see a partial mid-close state) wrapped in try/finally guaranteeing lock-release even if `db.close()` throws; KEEPS close-then-release order (release-then-close was rejected: it would widen the window where a sibling process connects to a still-closing brain); Pinned by `test/pglite-engine-disconnect.serial.test.ts`. `PGlite.create()` runs inside `preservingProcessExitCode` (#2084): PGLite's Emscripten runtime writes its own status into `process.exitCode` (99 at create; in-memory brains run initdb whose status lands on a later tick; the exit status at close — and assigning `undefined` cannot clear a prior value), which would otherwise silently clobber an errored op's exit 1 back to 0. The wrapper keeps the global tidy for external readers; `db.close()` stays unwrapped (its 0-write is baseline behavior test runners depend on). The CLI's exit verdict is immune either way — it lives in the gbrain-owned channel in `cli-force-exit.ts` and never reads `process.exitCode` back. Exports `classifyPgliteInitError(message): 'bunfs' | 'wasm-abort' | 'corrupt' | 'unknown'` + `buildPgliteInitErrorMessage(verdict, original, platform?, ctx?)` + `stringifyPgliteInitError(err)` + `buildWalRepairNotice(receipt)` + the `PgliteInitRepairContext` type, routing the catch-block hint by failure shape (`bunfs` matches literal `$$bunfs` OR `ENOENT[\s\S]*pglite\.data` co-occurrence, surfaces a paste-ready `bun upgrade` + Node fallback; `corrupt` — 58P01/`internal_load_library`/missing vector type, catalog corruption WAL repair can't fix — stays matched BEFORE the wasm arm and routes to `reinit-pglite`; `wasm-abort` matches the real production shapes `Aborted()`/`RuntimeError`/`unreachable` plus legacy signatures, names the corrupt-WAL root cause + the recovery ladder (`pglite-repair` → rebuild → engine switch) + what auto-repair did per `ctx` incl. the honesty-critical `failed-not-restored` arm, and keeps the #223 link; `unknown` is platform-gated per #2674). `stringifyPgliteInitError` also surfaces message-less Emscripten objects (`ErrnoError (errno N)`) instead of `[object Object]`. Pinned by `test/pglite-init-classifier.test.ts` + `test/pglite-wal-repair.serial.test.ts` + `test/fix-wave-structural.test.ts`. Implements `deletePages(slugs, {sourceId})` + `resolveSlugsByPaths(paths, {sourceId})` via `slug = ANY($1::text[])` array-param binding, caller-chunking primitive throwing when input exceeds `DELETE_BATCH_SIZE`, `deletePages` returns `RETURNING slug` rows so callers filter `pagesAffected` to confirmed deletes. Implements the embedding-signature stale-detection quartet — `sumStaleChunkChars({sourceId?, signature?})`, `setPageEmbeddingSignature(slug, {sourceId?, signature})`, `invalidateStaleSignatureEmbeddings({signature, sourceId?})`, widened `countStaleChunks({sourceId?, signature?})` (the `signature` opt widens via `JOIN pages p ... WHERE cc.embedding IS NULL OR (p.embedding_signature IS NOT NULL AND p.embedding_signature <> $signature)`, NULL grandfathered); parity SQL with postgres-engine.ts. PGLite-specific DDL (pgvector, pg_trgm, triggers). Engine-path helper dependencies (`retry`, ontology, recency decay) avoid dynamic `import()`; the only lazy dynamic imports are `ai/gateway.ts` in `initSchema` and `_upsertChunksOnce`, line-marked because their local catches preserve compiled-default and stored-config fallbacks that eager module evaluation would bypass.- `src/core/pglite-lock.ts` — advisory data-dir lock so two processes never open the same embedded PGLite (single-connection WASM Postgres) at once. Atomic `mkdir` of `.gbrain-lock/` + a `lock` file carrying `{pid, acquired_at, refreshed_at, command, subcommand}`. A held lock HEARTBEATS its `refreshed_at` every 30s (`.unref()`ed timer; informational). A waiting acquirer reaps a holder ONLY when its PID is dead — a LIVE holder is NEVER stolen, regardless of how stale its heartbeat is (#2348). A live `gbrain serve` holder is identified from the parsed `subcommand` and reported immediately with separate CLI-retry and MCP-tool choices; other live holders keep the bounded wait. The heartbeat runs on the JS event loop, which is blocked during long synchronous WASM imports/CHECKPOINTs, so a working `dream`/`embed` holder can look stale while alive; the old steal-on-stale-heartbeat grace let a second OS process open the same data dir and corrupt the catalog + pgvector extension (58P01 / `internal_load_library` / `type "vector" does not exist`), recoverable only by wipe+restore. A wedged-but-alive or PID-reused holder is never stolen: serve-tagged holders report immediately, while other holders time out with a message naming the PID. Each holder carries an ownership token (`<pid>:<acquired_at>`); the heartbeat and `releaseLock` verify the on-disk lock is STILL theirs before touching it. In-memory engines take no lock. There is deliberately NO same-process reentrancy or same-PID special case: a second `acquireLock` from the process that already holds the lock waits out the timeout like any other live holder (#1963 was this shape — a command double-connecting a second engine on the same data dir; the fix is to reuse the connected engine at the dispatch layer, never to soften the lock). `LockHandle.reaped` marks an acquisition that reaped a prior holder's lock (dead-PID reap or corrupt-lock-file removal — the only reaps that exist post-#2348); the WAL auto-repair gate refuses to run surgery on a reaped acquisition since a corrupt lock file cannot prove its holder is dead. A corrupt-lock reap ALSO writes a persisted marker (`<dataDir>.lock-reap.json`, read via exported `msSinceLastReap`) so the NEXT process's clean acquisition is still repair-quarantined for 10 minutes — the in-process flag alone let the reaper's successor run surgery under a possibly-live writer; dead-PID reaps (affirmative ESRCH verdict; EPERM reads as ALIVE) deliberately skip the marker so dead-holder recovery stays one-failed-command-plus-one-re-run. Heartbeat refreshes write via tmp+rename (a torn in-place write could be read mid-flight by a polling acquirer and misclassify a HEALTHY live holder as a corrupt lock). Pinned by `test/pglite-lock.test.ts`. A corrupted store surfaces a `reinit-pglite` recovery hint via `classifyPgliteInitError`'s `corrupt` verdict in `pglite-engine.ts`.diff --git a/src/commands/search.ts b/src/commands/search.tsindex 971010979a..04ccb66ad1 100644--- a/src/commands/search.ts+++ b/src/commands/search.ts@@ -38,7 +38,7 @@ import {type SearchMode,type ModeBundle,} from '../core/search/mode.ts';-import { readSearchStats } from '../core/search/telemetry.ts';+import { readSearchStats, telemetryCoverage, TELEMETRY_COVERAGE_CAVEAT } from '../core/search/telemetry.ts';const KNOB_DESCRIPTIONS: Record<keyof ModeBundle, string> = {cache_enabled: 'Semantic query cache on/off',@@ -225,6 +225,7 @@ async function runStatsSubcommand(engine: BrainEngine, args: string[]): Promise<console.log(JSON.stringify({schema_version: 2,...stats,+ coverage: telemetryCoverage(),graph_signals: gsSection,_meta: {metric_glossary: {@@ -241,11 +242,15 @@ async function runStatsSubcommand(engine: BrainEngine, args: string[]): Promise<}console.log(`Search stats over the last ${stats.window_days} days:`);+ console.log(` Coverage note: ${TELEMETRY_COVERAGE_CAVEAT}`);console.log('');console.log(` Total searches: ${stats.total_calls}`);if (stats.total_calls === 0) {console.log('');- console.log('No telemetry recorded yet. Run a few `gbrain query` calls and re-check.');+ console.log('No telemetry recorded in this window. This can mean no search activity, or');+ console.log('it can reflect the coverage gap above — a lone short-lived CLI call is often');+ console.log('not enough to trigger a flush. `gbrain serve` / an MCP session is more likely');+ console.log('to record counts over time (telemetry stays best-effort either way).');// Still print the graph-signals section since failures are tracked// independently of the search_telemetry table.if (gsSection.enabled || gsSection.failures_count > 0) {@@ -382,6 +387,7 @@ async function runTuneSubcommand(engine: BrainEngine, args: string[]): Promise<vschema_version: 2,status: 'insufficient_data',total_calls: stats.total_calls,+ coverage: telemetryCoverage(),recommendations: [],message: 'Not enough search activity in the last 7 days to tune. Run `gbrain search stats` after some real usage.',}, null, 2));@@ -389,7 +395,8 @@ async function runTuneSubcommand(engine: BrainEngine, args: string[]): Promise<v}console.log('Not enough search activity in the last 7 days to tune.');console.log(`Total searches: ${stats.total_calls} (need >= 20 for confident recommendations).`);- console.log('Run a few `gbrain query` calls, then re-run `gbrain search tune`.');+ console.log(`(${TELEMETRY_COVERAGE_CAVEAT} Low counts can reflect this gap, not just low usage.)`);+ console.log('Use `gbrain serve` or an MCP session for a while, then re-run `gbrain search tune`.');return;}@@ -448,6 +455,7 @@ async function runTuneSubcommand(engine: BrainEngine, args: string[]): Promise<vtotal_calls: stats.total_calls,cache_hit_rate: stats.cache_hit_rate,active_mode: resolved.resolved_mode,+ coverage: telemetryCoverage(),recommendations: recs,applied: apply ? recs.map(r => r.apply_command) : [],_meta: {@@ -466,6 +474,7 @@ async function runTuneSubcommand(engine: BrainEngine, args: string[]): Promise<v}console.log(`Search tune (last 7 days, active mode: ${resolved.resolved_mode}):`);+ console.log(`(${TELEMETRY_COVERAGE_CAVEAT})`);console.log('');if (recs.length === 0) {diff --git a/src/core/search/telemetry.ts b/src/core/search/telemetry.tsindex 679bcd2c73..180fe16710 100644--- a/src/core/search/telemetry.ts+++ b/src/core/search/telemetry.ts@@ -434,6 +434,50 @@ export async function readSearchStats(}}+/**+ * Coverage disclosure for `readSearchStats()` consumers (`gbrain search+ * stats` / `gbrain search tune`). This documents the buffering behavior+ * from the module header above — it changes NO behavior, it only gives+ * display layers a single source of truth for the caveat text instead of+ * each caller re-describing (and risking drift on) the flush mechanics.+ *+ * Short-lived CLI invocations (a single `gbrain query "..."` call) usually+ * exit before the 60s timer or the 100-call threshold fires, so their+ * search is buffered in-memory and then lost with the process — never+ * written to `search_telemetry`. Long-lived processes (`gbrain serve`,+ * stdio/HTTP MCP, `gbrain jobs work`) survive long enough for the periodic+ * flush and are captured reliably. A CLI run that itself issues 100++ * search calls before exiting (e.g. a bulk eval) CAN cross the threshold+ * and flush — hence "typically", not "never".+ */+export const TELEMETRY_COVERAGE_NOTE =+ 'Counts are most complete for long-lived processes (gbrain serve, MCP stdio/HTTP, ' ++ 'gbrain jobs work). A single short-lived CLI invocation typically exits before the ' ++ 'telemetry buffer flushes (60s timer or 100-call threshold), so its search is ' ++ 'usually not recorded here — see search/telemetry.ts for the buffering design.';++/**+ * Short, single-line form of {@link TELEMETRY_COVERAGE_NOTE} for human CLI+ * output (the long form is better suited to `--json`'s `reason` field).+ * Every human-facing caveat in `gbrain search stats`/`gbrain search tune`+ * reuses this literal string instead of paraphrasing it, so the wording+ * cannot drift between call sites.+ */+export const TELEMETRY_COVERAGE_CAVEAT =+ 'Coverage favors long-lived processes (gbrain serve, MCP, jobs work) — a lone ' ++ 'short-lived CLI search call is typically not recorded.';++export interface TelemetryCoverage {+ /** Whether a lone short-lived CLI search call is reliably counted. */+ cli_invocations: 'typically_not_recorded';+ reason: string;+}++/** Machine-readable form of {@link TELEMETRY_COVERAGE_NOTE} for `--json` output. */+export function telemetryCoverage(): TelemetryCoverage {+ return { cli_invocations: 'typically_not_recorded', reason: TELEMETRY_COVERAGE_NOTE };+}+function nowDate(): string {return new Date().toISOString().slice(0, 10);}diff --git a/test/commands-search.test.ts b/test/commands-search.test.tsindex a806755f20..ea01eee1c1 100644--- a/test/commands-search.test.ts+++ b/test/commands-search.test.ts@@ -8,7 +8,7 @@import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { runSearch } from '../src/commands/search.ts';-import { recordSearchTelemetry, _resetTelemetryWriterForTest, getTelemetryWriter } from '../src/core/search/telemetry.ts';+import { recordSearchTelemetry, _resetTelemetryWriterForTest, getTelemetryWriter, TELEMETRY_COVERAGE_CAVEAT } from '../src/core/search/telemetry.ts';import type { HybridSearchMeta } from '../src/core/types.ts';let engine: PGLiteEngine;@@ -165,6 +165,81 @@ describe('gbrain search stats', () => {const outBig = await captureRun(() => runSearch(engine, ['stats', '--days', '9999', '--json']));expect(JSON.parse(outBig).window_days).toBe(365);});++ // Coverage disclosure: short-lived CLI search calls typically don't+ // survive the telemetry flush timer/threshold, so `search stats` must+ // say so instead of presenting the (possibly CLI-blind) count as total.+ test('--json includes a coverage disclosure (empty table)', async () => {+ const out = await captureRun(() => runSearch(engine, ['stats', '--json']));+ const stats = JSON.parse(out);+ expect(stats.coverage).toBeDefined();+ expect(stats.coverage.cli_invocations).toBe('typically_not_recorded');+ // Pin the substance, not just presence — an inaccurate reason string+ // (e.g. "long-lived processes only") must fail this test.+ expect(stats.coverage.reason).toMatch(/short-lived CLI/i);+ expect(stats.coverage.reason).toMatch(/typically.*not recorded|not.*typically recorded/i);+ });++ test('--json includes a coverage disclosure (non-empty table)', async () => {+ const w = getTelemetryWriter();+ w.setEngine(engine);+ recordSearchTelemetry(engine, makeMeta({ cache: { status: 'hit' } }), { results_count: 5 });+ await w.flush();++ const out = await captureRun(() => runSearch(engine, ['stats', '--json']));+ const stats = JSON.parse(out);+ expect(stats.coverage.cli_invocations).toBe('typically_not_recorded');+ });++ // Wording-accuracy pin, independent of the TELEMETRY_COVERAGE_NOTE import:+ // importing the same constant into production code and the assertion+ // would let an inaccurate edit to the constant sail through unnoticed+ // (round-1 review caught exactly this class of bug — "long-lived+ // processes only" overclaimed and dropped `jobs work`). Hardcode the+ // substance here instead of comparing production output to itself.+ test('--json coverage.reason names all three long-lived process kinds + the threshold exception', async () => {+ const out = await captureRun(() => runSearch(engine, ['stats', '--json']));+ const reason: string = JSON.parse(out).coverage.reason;+ expect(reason).toMatch(/gbrain serve/i);+ expect(reason).toMatch(/mcp/i);+ expect(reason).toMatch(/jobs work/i);+ expect(reason).toMatch(/short-lived CLI/i);+ // Must not claim CLI calls are NEVER recorded — a bulk CLI run that+ // itself crosses the 100-call flush threshold before exiting IS+ // captured, so the wording must hedge ("typically"/"usually"), not+ // assert absolute exclusivity ("only"/"never").+ expect(reason).toMatch(/typically|usually/i);+ expect(reason).not.toMatch(/\bonly\b/i);+ expect(reason).not.toMatch(/\bnever\b/i);+ });++ test('human output surfaces the exact coverage caveat (empty table)', async () => {+ const out = await captureRun(() => runSearch(engine, ['stats']));+ // Pin the literal shared constant — proves the display layer isn't+ // paraphrasing (and risking drift on) the buffering caveat.+ expect(out).toContain(TELEMETRY_COVERAGE_CAVEAT);+ expect(out.toLowerCase()).toContain('coverage gap above');+ });++ // Same independent-wording-pin rationale as the --json test above,+ // applied to the short human caveat.+ test('human coverage caveat names long-lived processes + jobs work + the hedge word, independent of the import', async () => {+ const out = await captureRun(() => runSearch(engine, ['stats']));+ expect(out).toMatch(/favors long-lived processes/i);+ expect(out).toMatch(/jobs work/i);+ expect(out).toMatch(/typically not recorded/i);+ expect(out).not.toMatch(/only long-lived processes/i);+ });++ test('human output surfaces the exact coverage caveat (non-empty table)', async () => {+ const w = getTelemetryWriter();+ w.setEngine(engine);+ recordSearchTelemetry(engine, makeMeta({ cache: { status: 'hit' } }), { results_count: 5 });+ await w.flush();++ const out = await captureRun(() => runSearch(engine, ['stats']));+ expect(out).toContain(TELEMETRY_COVERAGE_CAVEAT);+ });});describe('gbrain search tune (recommendations)', () => {@@ -175,6 +250,26 @@ describe('gbrain search tune (recommendations)', () => {expect(r.recommendations).toEqual([]);});+ // Coverage disclosure: `tune`'s recommendations are only as complete as+ // the telemetry they're read from — same caveat as `search stats`.+ test('insufficient data → --json includes coverage disclosure', async () => {+ const out = await captureRun(() => runSearch(engine, ['tune', '--json']));+ const r = JSON.parse(out);+ expect(r.coverage).toBeDefined();+ expect(r.coverage.cli_invocations).toBe('typically_not_recorded');+ expect(r.coverage.reason).toMatch(/short-lived CLI/i);+ });++ test('insufficient data → human output notes the exact coverage caveat', async () => {+ const out = await captureRun(() => runSearch(engine, ['tune']));+ expect(out).toContain(TELEMETRY_COVERAGE_CAVEAT);+ // The old copy told the user to "run a few `gbrain query` calls" to fix+ // a zero count — that's misleading advice given the caveat (a single+ // CLI call is exactly what tends NOT to be recorded). Pin the corrected+ // suggestion instead.+ expect(out).toMatch(/gbrain serve.*or an MCP session/i);+ });+test('conservative + high budget drop rate → recommends balanced', async () => {await engine.setConfig('search.mode', 'conservative');const w = getTelemetryWriter();@@ -194,6 +289,25 @@ describe('gbrain search tune (recommendations)', () => {const modeRec = r.recommendations.find((x: { knob: string }) => x.knob === 'search.mode');expect(modeRec).toBeDefined();expect(modeRec.suggested).toBe('balanced');+ // Coverage disclosure travels with real recommendations too, not just+ // the insufficient-data early-return path.+ expect(r.coverage.cli_invocations).toBe('typically_not_recorded');+ });++ test('has_recommendations → human output notes the exact coverage caveat', async () => {+ await engine.setConfig('search.mode', 'conservative');+ const w = getTelemetryWriter();+ w.setEngine(engine);+ for (let i = 0; i < 30; i++) {+ recordSearchTelemetry(engine, makeMeta({+ mode: 'conservative',+ token_budget: { budget: 4000, used: 4000, kept: 5, dropped: 5 },+ }), { results_count: 5 });+ }+ await w.flush();++ const out = await captureRun(() => runSearch(engine, ['tune']));+ expect(out).toContain(TELEMETRY_COVERAGE_CAVEAT);});test('tokenmax + Haiku subagent → recommends balanced', async () => {