Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(search): tune --apply reports only config writes that landed (#6939)

time-attackf525d5ccd7e7
diff --git a/docs/architecture/key-files/commands-5.md b/docs/architecture/key-files/commands-5.md
index b498674342..ba3c25ebf5 100644
--- a/docs/architecture/key-files/commands-5.md
+++ b/docs/architecture/key-files/commands-5.md
@@ -17,7 +17,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/search-diagnose.ts` — `gbrain search diagnose "<query>" --target <slug> [--json] [--source <id>]`: Phase-0 retrieval diagnostic. Traces WHERE a target page surfaces (or fails to) across keyword / vector (per-page max-pool) / alias / hybrid layers and names the layer responsible for an incident, so an operator can pin whether the fix is max-pool/innerLimit (vector) vs title/alias. The verdict names the layer that DOES surface the target (or "none"). Pinned by `test/search/search-diagnose.test.ts`.
-- `src/commands/search.ts:gbrain search stats` — `rerank_gate` section (eligible, graded, would_skip and `would_skip_rate` over graded, provider_calls, `by_reason`, `ineligible` by why), read from the reserved `(date, 'rerank_gate', <counter>)` rows of `search_telemetry` (no DDL; diverted out of `total_calls` like the empty-result rows; written only when `search.reranker.gate` is not `off`; cache hits add nothing); human output prints it when anything was graded. `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: 'recorded_on_clean_exit', reason}`; human: a one-line caveat) sourced from `telemetryCoverage()`/`TELEMETRY_COVERAGE_CAVEAT` in `src/core/search/telemetry.ts`: a short-lived CLI call's buffer flushes during the bounded CLI teardown drain, so a CLEAN exit is recorded; hard kills, drains that exceed their bound, and anything buffered when an engine disconnects outside the CLI teardown path still drop — the disclosure is display-only and reads its truth from the telemetry module's single-source constants. Pinned by the coverage-disclosure tests in `test/commands-search.test.ts`.
+- `src/commands/search.ts:gbrain search stats` — `rerank_gate` section (eligible, graded, would_skip and `would_skip_rate` over graded, provider_calls, `by_reason`, `ineligible` by why), read from the reserved `(date, 'rerank_gate', <counter>)` rows of `search_telemetry` (no DDL; diverted out of `total_calls` like the empty-result rows; written only when `search.reranker.gate` is not `off`; cache hits add nothing); human output prints it when anything was graded. `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: 'recorded_on_clean_exit', reason}`; human: a one-line caveat) sourced from `telemetryCoverage()`/`TELEMETRY_COVERAGE_CAVEAT` in `src/core/search/telemetry.ts`: a short-lived CLI call's buffer flushes during the bounded CLI teardown drain, so a CLEAN exit is recorded; hard kills, drains that exceed their bound, and anything buffered when an engine disconnects outside the CLI teardown path still drop — the disclosure is display-only and reads its truth from the telemetry module's single-source constants. Pinned by the coverage-disclosure tests in `test/commands-search.test.ts`. `gbrain search tune --apply` writes in order and stops at the first write that did not land; a thrown write is reconciled by re-reading its key (`applied` when the target value is there, `failed` when not, `outcome_unknown` when the read fails too). JSON lists only landed changes in `applied` and `revert_commands`, adds per-item `results`, `not_applied` and `apply_error`, and the command rethrows the write error (non-zero exit). Tests: `test/search-tune-apply-truthful.serial.test.ts`.
- `src/commands/serve-http-grants.ts` + `admin/src/components/ClientGrant.tsx` — typed admin grant request validation and shared profile/advanced permission editor. Register/rescope/TTL routes in `serve-http-registration.ts`, `serve-http-grants.ts`, and `serve-http-admin-api.ts` use canonical grant validation and audit; legacy response shapes remain available. Registration and permission-edit failures add safe classifications, stage, outcome and inspection remedies; an unacknowledged mutation stays outcome-unknown, while read/preview failures and known refusals remain failed. New UI creation defaults to memory-writer and requires a preview, while edits carry the displayed revision and require a fresh preview after any field change or conflict. Detail/catalog endpoints expose non-secret grants and the shared harness registry. Operation authority snapshots, source sets, delegated tools/namespaces, spend, concurrency, and future TTL are independently reviewable; profile regrant is explicit. `admin/src/pages/Agents.tsx` previews machine/public PKCE/confidential PKCE registration and current permissions, and exposes versioned lifecycle actions. Explicit downloads select machine `HarnessCredentials` or native `OAuthClientSetup`; mixed clients require a flow choice. Loading errors preserve stale rows with Retry and disable creation when required source metadata is missing. Browser downloads and native connection evidence remain distinct. Rebuild committed `admin/dist` and `src/admin-embedded.ts` after SPA edits.
diff --git a/scripts/serial-files.tsv b/scripts/serial-files.tsv
index 4fd6fbeb9b..d80b8f3dbd 100644
--- a/scripts/serial-files.tsv
+++ b/scripts/serial-files.tsv
@@ -434,3 +434,4 @@ test/backup-preflight-6649.serial.test.ts global-state global-state: R3: constru
test/windows-ipc-long-path-6573.serial.test.ts R1 R1: mutates process.env (USERPROFILE) to place the per-user run dir under a non-ASCII profile path; native windows-latest only
test/coordination-lock.serial.test.ts global-state global-state: withEnv holds GBRAIN_HOME and GBRAIN_COORDINATION_HOME across awaited PGLite claims and transfers, and real native lock files are held across them
test/context-assemble-load-warning.serial.test.ts R2 R2: mock.module(../src/core/engine-factory.ts) replaces modules for every file in the process; R1: mutates process.env (GBRAIN_HOME, DATABASE_URL, GBRAIN_DATABASE_URL)
+test/search-tune-apply-truthful.serial.test.ts R2 R2: mock.module(../src/core/search/tune-recommendations.ts) replaces modules for every file in the process
diff --git a/src/commands/search.ts b/src/commands/search.ts
index 7d2dbae82e..8e410b7c60 100644
--- a/src/commands/search.ts
+++ b/src/commands/search.ts
@@ -20,8 +20,11 @@
*
* gbrain search tune [--apply] [--json]
* Recommendation engine. Reads stats + brain size + model tier and
- * prints structured recommendations. --apply mutates config (each
- * change logged loud + paste-ready revert command at the end).
+ * prints structured recommendations. --apply mutates config in order
+ * and reports each change as applied, unsupported, failed,
+ * outcome_unknown or not_attempted; a failed write stops the batch,
+ * the revert commands cover only the changes that landed, and the
+ * command exits non-zero.
*
* The report builders live in core (src/core/search/modes-report.ts,
* tune-recommendations.ts, telemetry.ts) and are shared with the
@@ -328,6 +331,9 @@ async function runTuneSubcommand(engine: BrainEngine, args: string[]): Promise<v
}
if (json) {
+ const outcomes = apply ? await applyRecommendations(engine, recs) : [];
+ const landed = outcomes.filter(o => o.status === 'applied').map(o => o.rec);
+ const failure = outcomes.find(o => o.error !== undefined && o.status !== 'applied');
console.log(JSON.stringify({
schema_version: 2,
status: report.status,
@@ -336,7 +342,18 @@ async function runTuneSubcommand(engine: BrainEngine, args: string[]): Promise<v
active_mode: report.active_mode,
coverage: report.coverage,
recommendations: recs,
- applied: apply ? recs.map(r => r.apply_command) : [],
+ applied: landed.map(r => r.apply_command),
+ ...(apply ? {
+ not_applied: outcomes.filter(o => o.status !== 'applied').map(o => o.rec.apply_command),
+ results: outcomes.map(o => ({
+ command: o.rec.apply_command,
+ status: o.status,
+ ...(o.status === 'applied' ? { revert_command: buildRevertCommand(o.rec) } : {}),
+ ...(o.error !== undefined && o.status !== 'applied' ? { message: errorMessage(o.error) } : {}),
+ })),
+ revert_commands: landed.map(buildRevertCommand),
+ ...(failure ? { apply_error: { command: failure.rec.apply_command, message: errorMessage(failure.error) } } : {}),
+ } : {}),
_meta: {
metric_glossary: {
cache_hit_rate: 'cache_hits / (cache_hits + cache_misses)',
@@ -344,11 +361,7 @@ async function runTuneSubcommand(engine: BrainEngine, args: string[]): Promise<v
},
},
}, null, 2));
- if (apply) {
- for (const r of recs) {
- await maybeApplyRecommendation(engine, r);
- }
- }
+ if (failure) throw failure.error;
return;
}
@@ -371,31 +384,86 @@ async function runTuneSubcommand(engine: BrainEngine, args: string[]): Promise<v
if (apply) {
console.log('Applying recommendations:');
- const reverts: string[] = [];
- for (const r of recs) {
- await maybeApplyRecommendation(engine, r);
- console.log(` ✓ ${r.apply_command}`);
- reverts.push(buildRevertCommand(r));
+ const outcomes = await applyRecommendations(engine, recs);
+ for (const o of outcomes) {
+ if (o.status === 'applied') console.log(` ✓ ${o.rec.apply_command}`);
+ else if (o.status === 'failed') console.log(` ✗ ${o.rec.apply_command} (failed, not written: ${errorMessage(o.error)})`);
+ else if (o.status === 'outcome_unknown') console.log(` ? ${o.rec.apply_command} (outcome unknown: the write failed and re-reading the key failed too; check it with gbrain config get)`);
+ else if (o.status === 'unsupported') console.log(` ✗ ${o.rec.apply_command} (not applied: unrecognized command shape)`);
+ else console.log(` - ${o.rec.apply_command} (not attempted: an earlier change failed)`);
}
- console.log('');
- console.log('To revert these changes:');
- for (const cmd of reverts) console.log(` ${cmd}`);
+ const reverts = outcomes.filter(o => o.status === 'applied').map(o => buildRevertCommand(o.rec));
+ if (reverts.length > 0) {
+ console.log('');
+ console.log('To revert these changes:');
+ for (const cmd of reverts) console.log(` ${cmd}`);
+ }
+ const failure = outcomes.find(o => o.error !== undefined && o.status !== 'applied');
+ if (failure) throw failure.error;
} else {
console.log('Run `gbrain search tune --apply` to apply these changes automatically.');
}
}
-async function maybeApplyRecommendation(engine: BrainEngine, r: TuneRecommendation): Promise<void> {
+interface ApplyOutcome {
+ rec: TuneRecommendation;
+ status: 'applied' | 'unsupported' | 'failed' | 'outcome_unknown' | 'not_attempted';
+ error?: unknown;
+}
+
+/**
+ * Applies in order and stops at the first write that did not land. A thrown
+ * write is reconciled by re-reading its key: the target value means it
+ * committed (applied), the old state means failed, and an unreadable key is
+ * outcome_unknown. Landed writes stay in place (no rollback).
+ */
+async function applyRecommendations(engine: BrainEngine, recs: TuneRecommendation[]): Promise<ApplyOutcome[]> {
+ const outcomes: ApplyOutcome[] = [];
+ let stopped = false;
+ for (const rec of recs) {
+ if (stopped) {
+ outcomes.push({ rec, status: 'not_attempted' });
+ continue;
+ }
+ try {
+ const wrote = await maybeApplyRecommendation(engine, rec);
+ outcomes.push({ rec, status: wrote ? 'applied' : 'unsupported' });
+ } catch (error) {
+ const parts = rec.apply_command.split(/\s+/);
+ const target = parts[2] === 'set' ? parts[4] : null;
+ let status: ApplyOutcome['status'];
+ try {
+ status = (await engine.getConfig(parts[3])) === target ? 'applied' : 'failed';
+ } catch {
+ status = 'outcome_unknown';
+ }
+ outcomes.push({ rec, status, error });
+ if (status !== 'applied') stopped = true;
+ }
+ }
+ return outcomes;
+}
+
+function errorMessage(error: unknown): string {
+ return error instanceof Error ? error.message : String(error);
+}
+
+/** Returns true when a config write ran; false for an unrecognized command shape. */
+async function maybeApplyRecommendation(engine: BrainEngine, r: TuneRecommendation): Promise<boolean> {
// The apply command is the canonical paste-ready string; here we
// re-parse it to call setConfig / unsetConfig directly so the call
// happens in-process.
const parts = r.apply_command.split(/\s+/);
- if (parts[0] !== 'gbrain' || parts[1] !== 'config') return;
+ if (parts[0] !== 'gbrain' || parts[1] !== 'config') return false;
if (parts[2] === 'set' && parts.length === 5) {
await engine.setConfig(parts[3], parts[4]);
- } else if (parts[2] === 'unset' && parts.length === 4) {
+ return true;
+ }
+ if (parts[2] === 'unset' && parts.length === 4) {
await engine.unsetConfig(parts[3]);
+ return true;
}
+ return false;
}
function buildRevertCommand(r: TuneRecommendation): string {
@@ -417,7 +485,10 @@ Subcommands:
modes --reset --mode <mode> Dry-run: list what --reset would change
(--source <mode> is a deprecated alias).
stats [--days N] [--json] Cache hit rate, intent mix, budget pressure.
- tune [--apply] [--json] Print recommendations; --apply mutates config.
+ tune [--apply] [--json] Print recommendations; --apply mutates config in order,
+ stops at the first failed write, reports each change
+ (applied / failed / outcome_unknown / not_attempted)
+ and lists reverts only for changes that landed.
diagnose "<query>" --target <slug> [--json] [--source <id>]
Trace where a target page surfaces across retrieval layers.
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index fb55e4f54f..8b9f942345 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -908,6 +908,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.307.0', text: 'The bundled `gbrain-base-v2` schema pack (the `init` default, also inherited by `company-brain`) is now version 1.5.0 and declares the `code` page type the code importer stamps and the `extract_receipt` page type the extract receipt writer stamps under `extracts/` (#6818), so neither makes doctor `schema_pack_consistency` warn `page_type_undeclared` and `unify-types` no longer retypes those pages to `note`. Existing pages keep their type; no data changes. The active pack identity reads `[email protected]+<hash>`.' },
{ since: '0.60.307.0', text: 'The `advisor` MCP operation now judges the cached backup verdict the way the doctor does: a remote readback older than one hour, a future-dated cache or a degraded compute reports the `backup_coverage_aggregate` warning instead of no finding. It still reads the cache only and names reason counts, never source ids.' },
{ since: '0.60.307.0', text: '`gbrain advisor` (and the `advisor` MCP operation) reports a database read that fails inside the `usage-shape` or `stalled-jobs` check as `collector_failed:<check>` and exits 1, instead of returning no findings for that check and possibly reporting a healthy brain. A brain with no pages, and an older brain without `minion_jobs`, `sources` or `sources.last_sync_at`, still report nothing for those checks.' },
+ { since: '0.60.307.0', text: '`gbrain search tune --apply` now writes before it reports: `--json` lists in `applied` and `revert_commands` only the changes that landed, adds per-item `results` (`applied`, `unsupported`, `failed`, `outcome_unknown`, `not_attempted`), `not_applied` and `apply_error`, and the text output marks a failed or unrecognized change with ✗ instead of ✓. The batch stops at the first write that does not land and the command exits non-zero; changes that already landed stay in place with their revert commands.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/test/helpers/config-reader-registry.ts b/test/helpers/config-reader-registry.ts
index 05c8b6dd0a..fe8efedc31 100644
--- a/test/helpers/config-reader-registry.ts
+++ b/test/helpers/config-reader-registry.ts
@@ -83,6 +83,7 @@ export const UNRESOLVED_CONFIG_READS: readonly UnresolvedConfigRead[] = [
{ file: 'src/commands/doctor/skill-checks.ts', expr: 'key', why: P },
{ file: 'src/commands/init-mode-picker.ts', expr: 'k', why: P },
{ file: 'src/commands/models.ts', expr: 'overrideKey', why: 'per-task model override key from the model-tier table (models.* prefix)' },
+ { file: 'src/commands/search.ts', expr: 'parts[3]', why: 'search tune --apply re-reads the key its recommendation just wrote, to reconcile a thrown write (search.* knobs from tune-recommendations.ts apply_command)' },
{ file: 'src/commands/skillpack/harness.ts', expr: 'key', why: P },
{ file: 'src/core/advisor/collect-setup-smells.ts', expr: 'key', why: P },
{ file: 'src/core/config-db-merge.ts', expr: 'key', why: 'listConfigKeys walk filtered to the cycle. and provider_chat_options. prefixes' },
diff --git a/test/search-tune-apply-truthful.serial.test.ts b/test/search-tune-apply-truthful.serial.test.ts
new file mode 100644
index 0000000000..9e5c810cd5
--- /dev/null
+++ b/test/search-tune-apply-truthful.serial.test.ts
@@ -0,0 +1,297 @@
+/**
+ * `gbrain search tune --apply` must report only the config changes that
+ * actually landed. Before this fix the --json lane printed
+ * `applied: recs.map(apply_command)` BEFORE any write ran, the text lane
+ * printed a checkmark for apply commands the helper silently ignored, and a
+ * mid-batch write failure dropped the revert commands for the changes that
+ * had already been written.
+ *
+ * The recommendation builder is mocked so each case controls the exact
+ * recommendation list; the engine is an in-memory config fake whose writes
+ * can be made to fail on the Nth call. Everything else is the real runSearch
+ * path.
+ */
+import { beforeEach, describe, expect, mock, test } from 'bun:test';
+import type { TuneRecommendation, TuneReport } from '../src/core/search/tune-recommendations.ts';
+
+let report: TuneReport;
+
+mock.module('../src/core/search/tune-recommendations.ts', () => ({
+ TUNE_MIN_CALLS: 20,
+ buildTuneRecommendations: async () => report,
+}));
+
+const { runSearch } = await import('../src/commands/search.ts');
+
+class FakeConfigEngine {
+ config = new Map<string, string>();
+ calls: string[] = [];
+ failOnCall: number | null = null;
+ /** The failing write commits before it throws (a lost acknowledgement). */
+ failAfterCommit = false;
+ /** getConfig throws too, so the failed write cannot be reconciled. */
+ failReads = false;
+
+ private maybeFail(): void {
+ if (this.failOnCall !== null && this.calls.length === this.failOnCall) {
+ throw new Error('synthetic config write failure');
+ }
+ }
+
+ async getConfig(key: string): Promise<string | null> {
+ if (this.failReads) throw new Error('synthetic config read failure');
+ return this.config.get(key) ?? null;
+ }
+ async setConfig(key: string, value: string): Promise<void> {
+ this.calls.push(`set ${key} ${value}`);
+ if (this.failAfterCommit) this.config.set(key, value);
+ this.maybeFail();
+ this.config.set(key, value);
+ }
+ async unsetConfig(key: string): Promise<number> {
+ this.calls.push(`unset ${key}`);
+ if (this.failAfterCommit) this.config.delete(key);
+ this.maybeFail();
+ return this.config.delete(key) ? 1 : 0;
+ }
+}
+
+let engine: FakeConfigEngine;
+
+const SET_MODE: TuneRecommendation = {
+ knob: 'search.mode', current: 'conservative', suggested: 'balanced',
+ reason: 'r1', apply_command: 'gbrain config set search.mode balanced',
+};
+const SET_THRESHOLD: TuneRecommendation = {
+ knob: 'search.cache.similarity_threshold', current: 0.9, suggested: 0.94,
+ reason: 'r2', apply_command: 'gbrain config set search.cache.similarity_threshold 0.94',
+};
+const UNSET_CACHE: TuneRecommendation = {
+ knob: 'search.cache.enabled', current: false, suggested: true,
+ reason: 'r3', apply_command: 'gbrain config unset search.cache.enabled',
+};
+const UNSUPPORTED: TuneRecommendation = {
+ knob: 'search.weird', current: 'a', suggested: 'b',
+ reason: 'r4', apply_command: 'gbrain config set search.weird b extra',
+};
+
+function useRecs(recs: TuneRecommendation[]): void {
+ report = {
+ schema_version: 2,
+ status: recs.length ? 'has_recommendations' : 'no_recommendations',
+ total_calls: 100,
+ cache_hit_rate: 0.5,
+ active_mode: 'conservative',
+ coverage: { cli_invocations: 'recorded_on_clean_exit', reason: 'short-lived CLI' } as TuneReport['coverage'],
+ recommendations: recs,
+ };
+}
+
+beforeEach(() => {
+ engine = new FakeConfigEngine();
+ engine.config.set('search.mode', 'conservative');
+ engine.config.set('search.cache.similarity_threshold', '0.9');
+ engine.config.set('search.cache.enabled', 'false');
+});
+
+async function run(args: string[]): Promise<{ out: string; error: unknown }> {
+ const original = console.log;
+ const captured: string[] = [];
+ console.log = (...a: unknown[]) => { captured.push(a.map(String).join(' ')); };
+ let error: unknown = null;
+ try {
+ await runSearch(engine as never, ['tune', ...args]);
+ } catch (e) {
+ error = e;
+ } finally {
+ console.log = original;
+ }
+ return { out: captured.join('\n'), error };
+}
+
+const revertSection = (out: string) => {
+ const lines = out.split('\n');
+ const at = lines.indexOf('To revert these changes:');
+ return at < 0 ? [] : lines.slice(at + 1).map(l => l.trim()).filter(Boolean);
+};
+const checkmarks = (out: string) => out.split('\n').filter(l => l.includes('✓')).map(l => l.trim());
+
+describe('search tune --apply --json', () => {
+ test('zero recommendations: nothing applied, no writes', async () => {
+ useRecs([]);
+ const { out, error } = await run(['--apply', '--json']);
+ expect(error).toBeNull();
+ expect(JSON.parse(out).applied).toEqual([]);
+ expect(engine.calls).toEqual([]);
+ });
+
+ test('one supported set: applied after the write landed', async () => {
+ useRecs([SET_MODE]);
+ const { out, error } = await run(['--apply', '--json']);
+ expect(error).toBeNull();
+ const r = JSON.parse(out);
+ expect(r.applied).toEqual([SET_MODE.apply_command]);
+ expect(engine.config.get('search.mode')).toBe('balanced');
+ expect(engine.calls).toEqual(['set search.mode balanced']);
+ });
+
+ test('multiple set/unset: each applied exactly once', async () => {
+ useRecs([SET_MODE, SET_THRESHOLD, UNSET_CACHE]);
+ const { out, error } = await run(['--apply', '--json']);
+ expect(error).toBeNull();
+ const r = JSON.parse(out);
+ expect(r.applied).toEqual([SET_MODE.apply_command, SET_THRESHOLD.apply_command, UNSET_CACHE.apply_command]);
+ expect(engine.calls).toEqual([
+ 'set search.mode balanced',
+ 'set search.cache.similarity_threshold 0.94',
+ 'unset search.cache.enabled',
+ ]);
+ expect(engine.config.has('search.cache.enabled')).toBe(false);
+ });
+
+ test('first write fails: JSON reports nothing applied and the error, command still fails', async () => {
+ useRecs([SET_MODE, SET_THRESHOLD]);
+ engine.failOnCall = 1;
+ const { out, error } = await run(['--apply', '--json']);
+ expect((error as Error).message).toBe('synthetic config write failure');
+ const r = JSON.parse(out);
+ expect(r.applied).toEqual([]);
+ expect(r.apply_error).toEqual({ command: SET_MODE.apply_command, message: 'synthetic config write failure' });
+ expect(engine.config.get('search.mode')).toBe('conservative');
+ expect(engine.calls).toEqual(['set search.mode balanced']);
+ });
+
+ test('later write fails: JSON lists only the landed change and its revert', async () => {
+ useRecs([SET_MODE, SET_THRESHOLD, UNSET_CACHE]);
+ engine.failOnCall = 2;
+ const { out, error } = await run(['--apply', '--json']);
+ expect((error as Error).message).toBe('synthetic config write failure');
+ const r = JSON.parse(out);
+ expect(r.applied).toEqual([SET_MODE.apply_command]);
+ expect(r.revert_commands).toEqual(['gbrain config set search.mode conservative']);
+ expect(r.apply_error.command).toBe(SET_THRESHOLD.apply_command);
+ expect(engine.config.get('search.mode')).toBe('balanced');
+ expect(engine.config.get('search.cache.similarity_threshold')).toBe('0.9');
+ expect(engine.calls.length).toBe(2);
+ });
+
+ test('unsupported command shape: not reported as applied', async () => {
+ useRecs([UNSUPPORTED, SET_MODE]);
+ const { out, error } = await run(['--apply', '--json']);
+ expect(error).toBeNull();
+ const r = JSON.parse(out);
+ expect(r.applied).toEqual([SET_MODE.apply_command]);
+ expect(r.not_applied).toEqual([UNSUPPORTED.apply_command]);
+ expect(engine.calls).toEqual(['set search.mode balanced']);
+ });
+
+ test('per-item results name what committed, what failed and what was not attempted', async () => {
+ useRecs([SET_MODE, SET_THRESHOLD, UNSET_CACHE]);
+ engine.failOnCall = 2;
+ const { out } = await run(['--apply', '--json']);
+ expect(JSON.parse(out).results).toEqual([
+ { command: SET_MODE.apply_command, status: 'applied', revert_command: 'gbrain config set search.mode conservative' },
+ { command: SET_THRESHOLD.apply_command, status: 'failed', message: 'synthetic config write failure' },
+ { command: UNSET_CACHE.apply_command, status: 'not_attempted' },
+ ]);
+ });
+
+ test('a write that committed before its error is reconciled as applied and the batch continues', async () => {
+ useRecs([SET_MODE, UNSET_CACHE]);
+ engine.failOnCall = 1;
+ engine.failAfterCommit = true;
+ const { out, error } = await run(['--apply', '--json']);
+ expect(error).toBeNull();
+ const r = JSON.parse(out);
+ expect(r.applied).toEqual([SET_MODE.apply_command, UNSET_CACHE.apply_command]);
+ expect(r.revert_commands).toEqual(['gbrain config set search.mode conservative', 'gbrain config set search.cache.enabled false']);
+ expect(r.apply_error).toBeUndefined();
+ });
+
+ test('a failed write whose key cannot be re-read is outcome_unknown, never applied', async () => {
+ useRecs([SET_MODE, SET_THRESHOLD]);
+ engine.failOnCall = 1;
+ engine.failReads = true;
+ const { out, error } = await run(['--apply', '--json']);
+ expect((error as Error).message).toBe('synthetic config write failure');
+ const r = JSON.parse(out);
+ expect(r.applied).toEqual([]);
+ expect(r.results.map((x: { status: string }) => x.status)).toEqual(['outcome_unknown', 'not_attempted']);
+ expect(r.revert_commands).toEqual([]);
+ });
+
+ test('without --apply: nothing applied, no writes', async () => {
+ useRecs([SET_MODE, UNSET_CACHE]);
+ const { out, error } = await run(['--json']);
+ expect(error).toBeNull();
+ const r = JSON.parse(out);
+ expect(r.applied).toEqual([]);
+ expect(r.recommendations.length).toBe(2);
+ expect(engine.calls).toEqual([]);
+ });
+});
+
+describe('search tune --apply (text)', () => {
+ test('all writes succeed: one checkmark per change and its revert', async () => {
+ useRecs([SET_MODE, UNSET_CACHE]);
+ const { out, error } = await run(['--apply']);
+ expect(error).toBeNull();
+ expect(checkmarks(out)).toEqual([`✓ ${SET_MODE.apply_command}`, `✓ ${UNSET_CACHE.apply_command}`]);
+ expect(out).toContain('To revert these changes:');
+ expect(out).toContain('gbrain config set search.mode conservative');
+ expect(out).toContain('gbrain config set search.cache.enabled false');
+ expect(engine.calls.length).toBe(2);
+ });
+
+ test('later write fails: checkmark only for the landed change, failure shown, its revert kept', async () => {
+ useRecs([SET_MODE, SET_THRESHOLD, UNSET_CACHE]);
+ engine.failOnCall = 2;
+ const { out, error } = await run(['--apply']);
+ expect((error as Error).message).toBe('synthetic config write failure');
+ expect(checkmarks(out)).toEqual([`✓ ${SET_MODE.apply_command}`]);
+ expect(out).toContain(`✗ ${SET_THRESHOLD.apply_command}`);
+ expect(revertSection(out)).toEqual(['gbrain config set search.mode conservative']);
+ expect(engine.calls.length).toBe(2);
+ });
+
+ test('first write fails: no checkmark and no revert section', async () => {
+ useRecs([SET_MODE]);
+ engine.failOnCall = 1;
+ const { out, error } = await run(['--apply']);
+ expect((error as Error).message).toBe('synthetic config write failure');
+ expect(checkmarks(out)).toEqual([]);
+ expect(out).toContain(`✗ ${SET_MODE.apply_command}`);
+ expect(out).not.toContain('To revert these changes:');
+ });
+
+ test('unsupported command shape: no checkmark, reported as not applied', async () => {
+ useRecs([UNSUPPORTED]);
+ const { out, error } = await run(['--apply']);
+ expect(error).toBeNull();
+ expect(checkmarks(out)).toEqual([]);
+ expect(out).toContain(`✗ ${UNSUPPORTED.apply_command}`);
+ expect(out).not.toContain('To revert these changes:');
+ expect(engine.calls).toEqual([]);
+ });
+
+ test('without --apply: no writes, apply hint kept', async () => {
+ useRecs([SET_MODE]);
+ const { out } = await run([]);
+ expect(engine.calls).toEqual([]);
+ expect(out).toContain('Run `gbrain search tune --apply`');
+ });
+
+ test('--help stays read-only', async () => {
+ useRecs([SET_MODE]);
+ const original = console.log;
+ const captured: string[] = [];
+ console.log = (...a: unknown[]) => { captured.push(a.map(String).join(' ')); };
+ try {
+ await runSearch(engine as never, ['tune', '--help']);
+ } finally {
+ console.log = original;
+ }
+ expect(captured.join('\n')).toContain('Usage:');
+ expect(engine.calls).toEqual([]);
+ });
+});