Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

tokenmax mode switch: point the banner and prompt at gbrain reindex --synopsis (#8744)

garrytan9b2348995d12
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 09d2b157c4..a420e35ec6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -21,6 +21,7 @@ identifiers and attribution are available in the pre-removal Git revision
| `gbrain doctor` on a brain whose configured tier is `per_chunk_synopsis` | nothing about it | `synopsis_tier_coverage` gives chunk and page coverage, the large pages left on the title tier and the last sweep job; it warns below 50% of chunks and names `gbrain reindex --synopsis`. The remote doctor runs it too, confined to the caller's sources |
| `gbrain search modes` | the configured tier only | one line with the synopsis-tier coverage (local only; the `search_modes` op leaves it out) |
| `gbrain reindex --synopsis` | did not exist | previews pages, chunks, synopsis tokens and dollars on the configured synopsis model plus the re-embed, and spends nothing |
+| `gbrain config set search.mode tokenmax` | the banner named `gbrain reindex --markdown` (which embeds at the title tier) and, on a TTY with a live worker, offered to queue it | the banner names `gbrain reindex --synopsis`; on a TTY it shows the sweep's preview and runs the sweep in that terminal only when you answer yes. Without a TTY it prints the preview command |
| `gbrain reindex --synopsis --yes [--max-usd <usd>]` | did not exist | queues one `contextual_reindex_per_chunk` job per page under one spend cap the worker enforces across them, runs them in-process and reports the new coverage. Running it again resumes: finished pages are skipped and queued jobs are picked up |
Nothing is scheduled automatically and no default changes. Inline pages over 1 MiB keep the title tier, as before. Repo-less brains work the same way: the sweep reads and writes the database only.
diff --git a/skills/migrations/v0.40.3.0.md b/skills/migrations/v0.40.3.0.md
index 363b0e741e..17cadee7ea 100644
--- a/skills/migrations/v0.40.3.0.md
+++ b/skills/migrations/v0.40.3.0.md
@@ -69,9 +69,9 @@ Anthropic's published research, document-heavy benchmarks see a
gbrain config set search.mode tokenmax
```
-The mode-switch banner explains the cost and (on TTY + active Minion
-worker) offers to submit `gbrain reindex --markdown` as a Minion job.
-Non-TTY callers get a paste-ready hint to stderr. Suppress entirely
+The mode-switch banner explains the cost and, on a TTY, previews the
+synopsis sweep and asks before running `gbrain reindex --synopsis --yes`.
+Non-TTY callers get the preview command on stderr. Suppress entirely
with `GBRAIN_NO_MODE_SWITCH_UX=1`.
Import, sync and `gbrain reindex --markdown` embed tokenmax pages at the title
diff --git a/skills/skills.lock.json b/skills/skills.lock.json
index f4dea0a255..af8a638097 100644
--- a/skills/skills.lock.json
+++ b/skills/skills.lock.json
@@ -131,7 +131,7 @@
"migrations/v0.35.7.0.md": "c6d4454bd39e2aa243b3b3d9bc72fe5a4fd25d097be7be2bb14b25604b5c2cc5",
"migrations/v0.36.2.0.md": "18f72475a0c0de1489c518219128d331d8ed6b0cdcacfb329e18fbcc643d9c6e",
"migrations/v0.36.5.0.md": "889f42508c28835c99242ec20b610ab002f20cda821cb99039589a212cac2ce0",
- "migrations/v0.40.3.0.md": "345621da8da253008947128a49ffdf1e170736a4b05b282c808d62ce641196e9",
+ "migrations/v0.40.3.0.md": "8353087813055bb5dd5f176eb242e1169fbe17c58c727168d8bc3e884cce85d8",
"migrations/v0.40.5.md": "92f0fce78502356c0ac5b50d043070b4002455026237004dd3ef7f05584e95b6",
"migrations/v0.41.11.0.md": "75c9741617de4c163052609e64734b4696a1105d3d015ed451097eaf6ea1eb3c",
"migrations/v0.46.3.0.md": "add5bdace741f8f0a75a114e354aa8ea3bcadf4cb54e1823338fdc69a5ae3f5d",
diff --git a/src/commands/config.ts b/src/commands/config.ts
index ade7bb21ad..d3982d8ca0 100644
--- a/src/commands/config.ts
+++ b/src/commands/config.ts
@@ -1471,8 +1471,8 @@ export async function runConfig(engine: BrainEngine, args: string[]) {
newMode: value,
engine,
isTty: Boolean(process.stdout.isTTY && process.stdin.isTTY),
- // CLI doesn't thread --yes here today; reserved for /ship-style
- // automation paths that can opt into auto-submit.
+ // CLI doesn't thread --yes here today; --yes would skip the
+ // prompt and print the preview command (it never spends).
yesFlag: false,
});
} catch (err) {
diff --git a/src/core/search/mode-switch-ux.ts b/src/core/search/mode-switch-ux.ts
index 9eddf37878..6845b78179 100644
--- a/src/core/search/mode-switch-ux.ts
+++ b/src/core/search/mode-switch-ux.ts
@@ -5,36 +5,24 @@
* surfaces a banner explaining the consequences and offers follow-up
* actions.
*
- * Three concerns separated:
- *
* 1. summarizeTransition(old, new) — PURE function that classifies the
* transition (no_change / narrowing / broadening / tokenmax_opt_in)
- * and returns banner lines, reindex requirement, and cost estimate.
- *
- * 2. probeWorkerAvailable(engine) — checks Minion worker heartbeat
- * (mirrors `gbrain doctor`'s queue_health check). Returns active /
- * stale / never_seen with a paste-ready start command.
+ * and returns banner lines, the backfill requirement and cost estimate.
*
- * 3. runModeSwitchUx(opts) — the orchestrator. Calls summarizeTransition,
- * prints the banner, and for tokenmax_opt_in + TTY: prompts to run
- * reindex, calls probeWorkerAvailable, and either submits the
- * reindex job or prints the loud-fail "start a worker first" hint
- * per D3.
+ * 2. runModeSwitchUx(opts) — the orchestrator. Prints the banner, and for
+ * tokenmax_opt_in on a TTY previews the per-chunk synopsis sweep
+ * (`gbrain reindex --synopsis`, #8744: import, sync and
+ * `reindex --markdown` embed at the title tier, so only that sweep
+ * writes synopses) and runs it in this process when the user answers
+ * yes. The yes is the consent; the sweep's spend cap applies.
*
* Suppression: GBRAIN_NO_MODE_SWITCH_UX=1 skips the entire UX for
* scripted operators (CI fixtures, automation). Non-TTY also skips
* interactive prompts; prints paste-ready hints to stderr.
- *
- * The reindex idempotency key is content-stable per codex D12 Bug 1:
- * cr-backfill:<source_id>:<chunker_version>:<corpus_generation_or_mode>
- * NOT timestamp-based. Two retries against the same brain state dedupe
- * via the Minion idempotency_key contract (v0.13.1).
*/
import type { BrainEngine } from '../engine.ts';
import { readLineSafe } from '../../commands/init.ts';
-import { MinionQueue } from '../minions/queue.ts';
-import type { SpendAuthorization } from '../minions/spend-record.ts';
import { isSearchMode, type SearchMode } from './mode.ts';
export type TransitionKind =
@@ -52,34 +40,16 @@ export interface TransitionSummary {
callout_lines: string[];
}
-export type WorkerStatus = 'active' | 'stale' | 'never_seen';
-
-export interface WorkerProbeResult {
- status: WorkerStatus;
- last_heartbeat_iso?: string;
- paste_ready_start_command: string;
-}
-
export interface ModeSwitchOpts {
oldMode: SearchMode | null;
newMode: string;
engine: BrainEngine;
isTty: boolean;
yesFlag?: boolean;
- /** Test seam: injectable worker probe. */
- probeFn?: (engine: BrainEngine) => Promise<WorkerProbeResult>;
- /** Test seam: injectable Minion submitter (avoids real queue in unit tests). */
- submitFn?: (jobName: string, params: Record<string, unknown>, idempotencyKey: string, spendAuthorization?: SpendAuthorization) => Promise<number>;
- /** Test seam: the TTY answer to the reindex prompt. */
+ /** Test seam: the TTY answer to the sweep prompt. */
answerFn?: (prompt: string) => Promise<string>;
}
-/**
- * Worker stale threshold: 2 minutes (matches gbrain doctor's
- * queue_health check semantics for "alive Minion worker").
- */
-export const WORKER_STALE_THRESHOLD_MS = 120_000;
-
/**
* Classify the transition + build banner content. Pure: no engine, no
* file I/O. Test surface for the 5-cell decision matrix below.
@@ -117,19 +87,19 @@ export function summarizeTransition(
};
}
- // tokenmax opt-in wins regardless of old mode. Triggers reindex prompt
- // because per-chunk Haiku synopsis backfill is needed for full quality.
+ // tokenmax opt-in wins regardless of old mode. Offers the synopsis sweep:
+ // existing pages stay on the title tier until it runs (#8744).
if (newMode === 'tokenmax') {
return {
kind: 'tokenmax_opt_in',
reindex_required: true,
- reindex_command: 'gbrain reindex --markdown',
+ reindex_command: 'gbrain reindex --synopsis',
cost_estimate_per_query_cents: 0.06, // ~$0.0006: rerank-3-lite at 50 candidates (gbrain-evals #148)
callout_lines: [
`Switched to tokenmax. Per-chunk Haiku synopsis enabled.`,
`Backfill cost (one-time): ~$1-5 per 10K pages via Anthropic Haiku.`,
`Per-query overhead: ~$0.0006 (reranker + slightly larger payload).`,
- `Run \`gbrain reindex --markdown\` to backfill existing pages.`,
+ `Existing pages stay on the title tier until the synopsis sweep runs: preview it with \`gbrain reindex --synopsis\`, run it with --yes.`,
],
};
}
@@ -175,79 +145,10 @@ function narrowness(mode: SearchMode): number {
}
}
-/**
- * Probe Minion worker heartbeat. Mirrors the queue_health doctor check
- * semantics: a worker that pushed a heartbeat within
- * WORKER_STALE_THRESHOLD_MS is considered active.
- *
- * Best-effort: any error returns `never_seen` so the caller can decide
- * what to do. The paste-ready start command is always populated so the
- * banner can offer a recovery path.
- *
- * The PGLite inline path (`gbrain agent run` with `--follow`) doesn't
- * require a worker; this probe is for the production "spawn a real
- * Minion worker" path.
- */
-export async function probeWorkerAvailable(engine: BrainEngine): Promise<WorkerProbeResult> {
- const startCmd = 'gbrain jobs work';
- try {
- // gbrain doesn't have a minion_workers heartbeat table yet (B7 follow-up
- // from v0.19.1 — see CLAUDE.md). Use a proxy: any minion_jobs row
- // started or finished within WORKER_STALE_THRESHOLD_MS means a worker
- // is doing real work. If only OLDER activity exists, treat as stale
- // (worker likely died). If no activity at all, never_seen.
- const rows = await engine.executeRaw<{ ts: string | null }>(
- `SELECT MAX(GREATEST(
- COALESCE(started_at, '-infinity'::timestamptz),
- COALESCE(finished_at, '-infinity'::timestamptz)
- ))::text AS ts
- FROM minion_jobs
- WHERE COALESCE(started_at, finished_at) > now() - INTERVAL '10 minutes'`,
- );
- const ts = rows[0]?.ts;
- if (!ts) {
- return { status: 'never_seen', paste_ready_start_command: startCmd };
- }
- const ageMs = Date.now() - new Date(ts).getTime();
- if (ageMs <= WORKER_STALE_THRESHOLD_MS) {
- return {
- status: 'active',
- last_heartbeat_iso: ts,
- paste_ready_start_command: startCmd,
- };
- }
- return {
- status: 'stale',
- last_heartbeat_iso: ts,
- paste_ready_start_command: startCmd,
- };
- } catch {
- // Table may not exist on a fresh brain. Treat as never_seen.
- return { status: 'never_seen', paste_ready_start_command: startCmd };
- }
-}
-
-/**
- * Build the content-stable idempotency key for the reindex submission
- * per codex D12 Bug 1. NOT timestamp-based — two retries against the
- * same brain state must produce the SAME key so the Minion dedupes.
- */
-export function buildReindexIdempotencyKey(
- sourceId: string,
- chunkerVersion: number,
- modeOrCorpusGen: string,
-): string {
- return `cr-backfill:${sourceId}:${chunkerVersion}:${modeOrCorpusGen}`;
-}
-
/**
* Orchestrator. Called by `gbrain config set search.mode <X>` after the
- * config write lands. Honors GBRAIN_NO_MODE_SWITCH_UX=1 (full skip),
- * non-TTY (skip prompt, print paste-ready hints), --yes (auto-submit
- * reindex on tokenmax_opt_in transitions).
- *
- * Idempotent: invoking with the same (old, new) twice is harmless; the
- * Minion idempotency_key ensures the reindex doesn't submit twice.
+ * config write lands. Honors GBRAIN_NO_MODE_SWITCH_UX=1 (full skip) and
+ * non-TTY / --yes (no prompt; prints the paste-ready preview command).
*/
export async function runModeSwitchUx(opts: ModeSwitchOpts): Promise<void> {
if (process.env.GBRAIN_NO_MODE_SWITCH_UX === '1') return;
@@ -270,99 +171,21 @@ export async function runModeSwitchUx(opts: ModeSwitchOpts): Promise<void> {
if (!summary.reindex_required) return;
- // Reindex offered only for tokenmax_opt_in (today). Honor --yes /
- // non-TTY by NOT prompting; just print the paste-ready command.
if (!opts.isTty || opts.yesFlag) {
- console.error(`[mode-switch] To backfill now: ${summary.reindex_command}`);
+ console.error(`[mode-switch] Preview the backfill (spends nothing): ${summary.reindex_command}`);
return;
}
- // TTY + interactive: prompt, naming what the reindex re-embeds and costs (W4.5: the yes is stored on the job as its spend authorization).
- const { countPending } = await import('../../commands/reindex.ts');
- const { estimateReindexSpend } = await import('../reindex-consent.ts');
- const plan = await estimateReindexSpend(opts.engine, { type: null, target: await countPending(opts.engine, null, false) });
- const cost = plan.est_usd === null ? 'embedding cost unknown in advance' : `embedding about $${plan.est_usd.toFixed(2)}`;
- const prompt = `Run '${summary.reindex_command}' now? It re-embeds ${plan.pages} page(s) (${cost}, plus a chat call per chunk under tokenmax). [y/N]: `;
+ // TTY: show the sweep's preview (pages, chunks, tokens, dollars), then ask before any spend.
+ const { runReindexSynopsis } = await import('../../commands/reindex-synopsis.ts');
+ const preview = await runReindexSynopsis(opts.engine, ['--synopsis']);
+ if (preview.mode !== 'preview' || !preview.plan || preview.plan.pages.length === 0) return;
+ const cost = preview.plan.est_usd === null ? 'cost unknown in advance' : `up to $${preview.plan.est_usd.toFixed(2)}`;
+ const prompt = `Run '${summary.reindex_command} --yes' now? It writes per-chunk synopses for ${preview.plan.pages.length} page(s) (${cost}) in this terminal; Ctrl-C stops it and the same command resumes. [y/N]: `;
const answer = opts.answerFn ? await opts.answerFn(prompt) : await readLineSafe(prompt, 'n', 60_000);
if (answer.toLowerCase() !== 'y' && answer.toLowerCase() !== 'yes') {
- console.error(`[mode-switch] Skipped. Run \`${summary.reindex_command}\` when ready.`);
- return;
- }
-
- // User opted in. Probe worker availability before submitting.
- const probeFn = opts.probeFn ?? probeWorkerAvailable;
- const worker = await probeFn(opts.engine);
-
- if (worker.status !== 'active') {
- // Loud-fail per D3 to avoid the silent-stall footgun. Caller can
- // still invoke reindex inline (`gbrain reindex --markdown` runs
- // synchronously without a worker on the PGLite inline path).
- console.error(`[mode-switch] No active worker (${worker.status}).`);
- console.error(`[mode-switch] Either run inline: ${summary.reindex_command}`);
- console.error(`[mode-switch] Or start a worker first: ${worker.paste_ready_start_command}`);
+ console.error(`[mode-switch] Skipped. Run \`${summary.reindex_command}\` to preview it again when ready.`);
return;
}
-
- // Submit via Minion queue with content-stable idempotency key.
- const sourceId = await resolveDefaultSourceId(opts.engine);
- const chunkerVersion = await resolveChunkerVersion(opts.engine);
- const idempotencyKey = buildReindexIdempotencyKey(sourceId, chunkerVersion, opts.newMode);
-
- const submitFn = opts.submitFn ?? defaultSubmit;
- const { DEFAULT_PAID_CAP_USD, derivedCapUsd } = await import('../consent.ts');
- const { jobSpendAuthorization } = await import('../minions/spend-authorization.ts');
- const capUsd = Math.max(DEFAULT_PAID_CAP_USD, plan.est_usd === null ? 0 : derivedCapUsd(plan.est_usd));
- const spend = jobSpendAuthorization({ consented_effects: ['paid'], cap_usd: capUsd, cap_source: 'default', via: 'tty_prompt' },
- { command: `config set search.mode ${opts.newMode}`, of: 1, argv: ['gbrain', 'reindex', '--markdown'], ...(plan.est_usd !== null ? { est_usd: plan.est_usd } : {}) });
- try {
- const jobId = await submitFn(
- 'reindex',
- { markdown: true, source_id: sourceId },
- idempotencyKey,
- spend,
- );
- console.error(`[mode-switch] Submitted as job ${jobId}. Watch with: gbrain jobs follow ${jobId}`);
- } catch (err) {
- console.error(`[mode-switch] Submit failed: ${(err as Error).message}`);
- console.error(`[mode-switch] Run inline: ${summary.reindex_command}`);
- }
-
- async function defaultSubmit(
- jobName: string,
- params: Record<string, unknown>,
- idemKey: string,
- spendAuthorization?: SpendAuthorization,
- ): Promise<number> {
- const queue = new MinionQueue(opts.engine);
- const job = await queue.add(
- jobName,
- params,
- { idempotency_key: idemKey },
- { allowProtectedSubmit: true, ...(spendAuthorization ? { spendAuthorization } : {}) },
- );
- return job.id;
- }
-}
-
-async function resolveDefaultSourceId(engine: BrainEngine): Promise<string> {
- try {
- const rows = await engine.executeRaw<{ id: string }>(
- `SELECT id FROM sources WHERE id = 'default' LIMIT 1`,
- );
- return rows[0]?.id ?? 'default';
- } catch {
- return 'default';
- }
-}
-
-async function resolveChunkerVersion(engine: BrainEngine): Promise<number> {
- try {
- const rows = await engine.executeRaw<{ v: string | null }>(
- `SELECT value AS v FROM config WHERE key = 'chunker_version'`,
- );
- const v = Number(rows[0]?.v ?? 0);
- return Number.isFinite(v) ? v : 0;
- } catch {
- return 0;
- }
+ await runReindexSynopsis(opts.engine, ['--synopsis', '--yes']);
}
diff --git a/test/mode-switch-ux.test.ts b/test/mode-switch-ux.test.ts
index d3d96931bd..e0d83b4049 100644
--- a/test/mode-switch-ux.test.ts
+++ b/test/mode-switch-ux.test.ts
@@ -1,30 +1,27 @@
/**
* v0.40.3.0 — mode-switch UX (D3)
*
- * Pure unit tests for the 3 exports:
* - summarizeTransition: 5-cell matrix + invalid fallthrough
- * - probeWorkerAvailable: active / stale / never_seen branches via DI
- * - buildReindexIdempotencyKey: content-stable invariance (codex D12 #1)
+ * - runModeSwitchUx without a TTY: the banner names the synopsis sweep
+ * preview (#8744) and prompts for nothing. The TTY preview-and-ask path
+ * runs against a real brain in test/synopsis-sweep-8744.serial.test.ts.
*/
-import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
-import { PGLiteEngine } from '../src/core/pglite-engine.ts';
-import { resetPgliteState } from './helpers/reset-pglite.ts';
-import {
- summarizeTransition,
- probeWorkerAvailable,
- buildReindexIdempotencyKey,
- WORKER_STALE_THRESHOLD_MS,
-} from '../src/core/search/mode-switch-ux.ts';
+import { describe, expect, test } from 'bun:test';
+import { runModeSwitchUx, summarizeTransition } from '../src/core/search/mode-switch-ux.ts';
+import { withEnv } from './helpers/with-env.ts';
describe('summarizeTransition (5-cell matrix + invalid fallthrough)', () => {
test('any → tokenmax: tokenmax_opt_in with reindex required', () => {
const s = summarizeTransition('balanced', 'tokenmax');
expect(s.kind).toBe('tokenmax_opt_in');
expect(s.reindex_required).toBe(true);
- expect(s.reindex_command).toBe('gbrain reindex --markdown');
+ expect(s.reindex_command).toBe('gbrain reindex --synopsis');
expect(s.cost_estimate_per_query_cents).toBeGreaterThan(0);
expect(s.callout_lines.some((l) => l.includes('tokenmax'))).toBe(true);
+ // #8744: import and reindex --markdown embed at the title tier; only the synopsis sweep backfills.
+ expect(s.callout_lines.some((l) => l.includes('`gbrain reindex --synopsis`'))).toBe(true);
+ expect(s.callout_lines.join('\n')).not.toContain('reindex --markdown');
});
test('first-time any → tokenmax (null → tokenmax)', () => {
@@ -75,92 +72,30 @@ describe('summarizeTransition (5-cell matrix + invalid fallthrough)', () => {
});
});
-describe('probeWorkerAvailable (DI for active/stale/never_seen)', () => {
- let engine: PGLiteEngine;
-
- beforeAll(async () => {
- engine = new PGLiteEngine();
- await engine.connect({});
- await engine.initSchema();
- });
-
- afterAll(async () => {
- await engine.disconnect();
- });
-
- beforeEach(async () => {
- await resetPgliteState(engine);
- });
-
- test('never_seen when minion_jobs has no recent activity', async () => {
- const result = await probeWorkerAvailable(engine);
- expect(result.status).toBe('never_seen');
- expect(result.paste_ready_start_command).toBe('gbrain jobs work');
- expect(result.last_heartbeat_iso).toBeUndefined();
- });
-
- test('active when minion_jobs activity is fresh (<2 min)', async () => {
- // Seed a recently-started job.
- await engine.executeRaw(
- `INSERT INTO minion_jobs (submission_authority, queue, name, data, status, started_at)
- VALUES ('{"version":1,"kind":"application"}'::jsonb, 'default', 'test-job', '{}'::jsonb, 'active', now())`,
- );
- const result = await probeWorkerAvailable(engine);
- expect(result.status).toBe('active');
- expect(result.last_heartbeat_iso).toBeDefined();
- });
-
- test('stale when activity is older than 2 min but within 10-min window', async () => {
- // Seed a 5-minute-old started_at (within 10-min query window, > 2-min stale).
- await engine.executeRaw(
- `INSERT INTO minion_jobs (submission_authority, queue, name, data, status, started_at)
- VALUES ('{"version":1,"kind":"application"}'::jsonb, 'default', 'test-stale-job', '{}'::jsonb, 'completed',
- now() - INTERVAL '5 minutes')`,
- );
- const result = await probeWorkerAvailable(engine);
- expect(result.status).toBe('stale');
- expect(result.last_heartbeat_iso).toBeDefined();
- });
-
- test('threshold constant is 2 minutes (120_000 ms)', () => {
- expect(WORKER_STALE_THRESHOLD_MS).toBe(120_000);
- });
-});
-
-describe('buildReindexIdempotencyKey (codex D12 Bug 1 content-stable invariance)', () => {
- test('same inputs produce identical key', () => {
- const k1 = buildReindexIdempotencyKey('default', 2, 'tokenmax');
- const k2 = buildReindexIdempotencyKey('default', 2, 'tokenmax');
- expect(k1).toBe(k2);
- });
-
- test('key shape matches the canonical pattern', () => {
- const k = buildReindexIdempotencyKey('default', 2, 'tokenmax');
- expect(k).toBe('cr-backfill:default:2:tokenmax');
- });
-
- test('different source_id produces different key', () => {
- const k1 = buildReindexIdempotencyKey('default', 2, 'tokenmax');
- const k2 = buildReindexIdempotencyKey('other-source', 2, 'tokenmax');
- expect(k1).not.toBe(k2);
- });
-
- test('different chunker_version produces different key (re-chunk = new key)', () => {
- const k1 = buildReindexIdempotencyKey('default', 2, 'tokenmax');
- const k2 = buildReindexIdempotencyKey('default', 3, 'tokenmax');
- expect(k1).not.toBe(k2);
- });
-
- test('different mode produces different key', () => {
- const k1 = buildReindexIdempotencyKey('default', 2, 'tokenmax');
- const k2 = buildReindexIdempotencyKey('default', 2, 'balanced');
- expect(k1).not.toBe(k2);
- });
-
- test('NOT timestamp-based: two consecutive runs with same state produce same key', async () => {
- const k1 = buildReindexIdempotencyKey('default', 2, 'tokenmax');
- await new Promise((r) => setTimeout(r, 10));
- const k2 = buildReindexIdempotencyKey('default', 2, 'tokenmax');
- expect(k1).toBe(k2);
+describe('runModeSwitchUx without a TTY', () => {
+ const capture = async (newMode: string) => {
+ const lines: string[] = [];
+ const error = console.error;
+ console.error = (...args: unknown[]) => { lines.push(args.join(' ')); };
+ try {
+ await withEnv({ GBRAIN_NO_MODE_SWITCH_UX: undefined }, () => runModeSwitchUx({ oldMode: 'balanced', newMode, engine: {} as never, isTty: false,
+ answerFn: async () => { throw new Error('no prompt without a TTY'); } }));
+ } finally {
+ console.error = error;
+ }
+ return lines;
+ };
+
+ test('balanced → tokenmax: the banner names the free synopsis sweep preview, not reindex --markdown', async () => {
+ const lines = await capture('tokenmax');
+ expect(lines[0]).toBe('[mode-switch] Switched to tokenmax. Per-chunk Haiku synopsis enabled.');
+ expect(lines.some((l) => l.includes('`gbrain reindex --synopsis`'))).toBe(true);
+ expect(lines.at(-1)).toBe('[mode-switch] Preview the backfill (spends nothing): gbrain reindex --synopsis');
+ expect(lines.join('\n')).not.toContain('reindex --markdown');
+ });
+
+ test('balanced → conservative: no backfill hint', async () => {
+ const lines = await capture('conservative');
+ expect(lines.join('\n')).not.toContain('reindex');
});
});
diff --git a/test/synopsis-sweep-8744.serial.test.ts b/test/synopsis-sweep-8744.serial.test.ts
index 50d7e1c80c..96ecaa8eee 100644
--- a/test/synopsis-sweep-8744.serial.test.ts
+++ b/test/synopsis-sweep-8744.serial.test.ts
@@ -7,6 +7,8 @@
* is not applicable on a balanced brain;
* - the preview's pages, chunks, tokens and dollars on the configured
* synopsis model, and that it queues and spends nothing;
+ * - switching to tokenmax on a TTY previews the sweep and asks before
+ * running `gbrain reindex --synopsis --yes`; a no queues nothing;
* - a --yes run under a cap below one synopsis call is refused by the
* shared spend group and stamps nothing; a later run resumes;
* - --yes queues one contextual_reindex_per_chunk job per page under one
@@ -30,6 +32,7 @@ import { importFromContent } from '../src/core/import-file.ts';
import { __setChatTransportForTests, __setEmbedTransportForTests, configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
import { checkSynopsisTierCoverage } from '../src/commands/doctor/checks/synopsis-coverage.ts';
import { runReindexSynopsis } from '../src/commands/reindex-synopsis.ts';
+import { runModeSwitchUx } from '../src/core/search/mode-switch-ux.ts';
import { estimateSynopsisCallUsd, SYNOPSIS_MAX_TOKENS } from '../src/core/page-summary.ts';
import { reservationCostUsd } from '../src/core/budget/reservation-cost.ts';
import { lookupEmbeddingPrice } from '../src/core/embedding-pricing.ts';
@@ -73,10 +76,12 @@ beforeEach(() => { chatCalls = 0; _resetCliExitVerdictForTests(); });
const body = (title: string, paragraphs: number) => `---\ntype: note\ntitle: ${title}\n---\n\n${Array.from({ length: paragraphs }, (_, i) => `Paragraph ${i} about ${title}. `.repeat(30)).join('\n\n')}\n`;
const quiet = async <T>(fn: () => Promise<T>): Promise<T> => {
const log = console.log;
+ const error = console.error;
const write = process.stderr.write.bind(process.stderr);
console.log = () => {};
+ console.error = () => {};
process.stderr.write = (() => true) as typeof process.stderr.write;
- try { return await fn(); } finally { console.log = log; process.stderr.write = write; }
+ try { return await fn(); } finally { console.log = log; console.error = error; process.stderr.write = write; }
};
for (const kind of testBackends()) describe(`#8744 synopsis sweep (${kind})`, () => {
@@ -159,6 +164,25 @@ for (const kind of testBackends()) describe(`#8744 synopsis sweep (${kind})`, ()
expect(chatCalls).toBe(0);
});
+ test('mode switch to tokenmax on a TTY: previews the sweep and asks before running it; a no queues and spends nothing', async () => {
+ const prompts: string[] = [];
+ const saved = process.env.GBRAIN_NO_MODE_SWITCH_UX;
+ delete process.env.GBRAIN_NO_MODE_SWITCH_UX;
+ try {
+ await quiet(() => runModeSwitchUx({ oldMode: 'balanced', newMode: 'tokenmax', engine, isTty: true,
+ answerFn: async (prompt) => { prompts.push(prompt); return 'n'; } }));
+ } finally {
+ if (saved === undefined) delete process.env.GBRAIN_NO_MODE_SWITCH_UX; else process.env.GBRAIN_NO_MODE_SWITCH_UX = saved;
+ }
+ expect(prompts).toHaveLength(1);
+ expect(prompts[0]).toContain("Run 'gbrain reindex --synopsis --yes' now?");
+ expect(prompts[0]).toContain('for 2 page(s)');
+ expect(prompts[0]).not.toContain('reindex --markdown');
+ const jobs = await engine.executeRaw<{ n: number | string }>(`SELECT count(*)::int AS n FROM minion_jobs`);
+ expect(Number(jobs[0]!.n)).toBe(0);
+ expect(chatCalls).toBe(0);
+ });
+
test('--yes under a cap below one synopsis call: the shared spend cap refuses the work, nothing is stamped, and the run says so', async () => {
const result = await quiet(() => runReindexSynopsis(engine, ['--synopsis', '--yes', '--max-usd', '0.0001'], { pollMs: 100 }));
expect(result.mode).toBe('run');