Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

test(GBRA-47 D9): behavioral owners replace five blind [structural] source pins

garrytanf82c3a077b20
diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsv
index 6670d08285..7bedbce93c 100644
--- a/scripts/structural-suites.tsv
+++ b/scripts/structural-suites.tsv
@@ -25,7 +25,6 @@ test/autopilot-install.test.ts autopilot wrapper script — env source order (v0
test/autopilot-install.test.ts autopilot wrapper script — gbrain-owned env file (#2608) 5 source-surface-helper
test/autopilot-install.test.ts autopilot wrapper script — key sourcing (#2608) 1 source-surface-helper
test/autopilot-nightly-probe-wiring.test.ts autopilot wiring: nightly quality probe 9 source-surface-helper
-test/autopilot-operator-pause.test.ts autopilot operator pause 5 source-surface-helper
test/autopilot-parser-probe-wiring.test.ts autopilot wiring: conversation-parser probe 10 source-surface-helper
test/autopilot-pause-marker.test.ts pause marker fences minion job pickup 1 readFileSync
test/autopilot-self-upgrade.test.ts autopilot self-upgrade static-shape regressions 4 source-surface-helper
@@ -82,9 +81,6 @@ test/compile-view.test.ts compileView — determinism 3 readFileSync
test/compile-view.test.ts compileView — source isolation + read errors 3 readFileSync
test/config.test.ts config source correctness 1 readFileSync
test/connection-resilience.test.ts Eng-review D3 — executeRaw has no per-call retry wrapper 3 readFileSync,source-surface-helper
-test/consent.test.ts --non-interactive maps explicitly to effects 3 readFileSync
-test/consent.test.ts memorable's relay-only gate (stays hard) 1 readFileSync
-test/consent.test.ts preapproval config (trusted local CLI only) 6 readFileSync
test/context-audit-skill.test.ts #4988 context-audit skill token estimate 2 readFileSync
test/contextual-retrieval-service-pure.test.ts inline import contextual synopsis containment 1 readFileSync
test/conversation-facts-type-allowlist-drift.test.ts (file-level) 18 readFileSync
@@ -135,7 +131,6 @@ test/e2e/codex-plugin-install-real.serial.test.ts (file-level) 2 readFileSync
test/e2e/migration-flow.test.ts (file-level) 4 readFileSync
test/e2e/openclaw-reference-compat.test.ts OpenClaw reference workspace compat (W1 + W2 + W3) 8 readFileSync
test/e2e/workspace-generic-compat.test.ts generic agent-workspace compat (INSTALL_FOR_AGENTS.md flow) 6 readFileSync
-test/embed-concurrency-pool-clamp.test.ts #5183 embed concurrency never exceeds the Postgres pool 4 readFileSync
test/embedding-dim-check-facts.test.ts doctor checkFactsEmbeddingWidthConsistency wiring (T6) 4 doctor-source-helper
test/embedding-dim-check-facts.test.ts postgres-engine fact insert cast (T6, codex #20) 1 source-surface-helper
test/env-trust-protected-keys.test.ts CWD_DOTENV_PROTECTED_KEYS covers every suspicious GBRAIN_* env read in src/ 3 readFileSync
@@ -236,7 +231,6 @@ test/pg-access-classify.test.ts marker contract (skill↔binary lockstep, the UP
test/pglite-engine.test.ts PGLiteEngine: v0.13.1 error-wrap on connect() (#223) 1 source-surface-helper
test/pglite-repair-command.serial.test.ts gbrain pglite-repair — interactive confirm wiring (#4318 residual) 1 readFileSync
test/pglite-wal-repair.serial.test.ts WAL auto-repair — real-brain regression (#223/#1670/#2575) 6 source-surface-helper
-test/post-upgrade-banner.test.ts post-upgrade recovery banner 5 readFileSync
test/postgres-driver-vendor.test.ts vendored Postgres driver packaging 3 readFileSync
test/postgres-engine.test.ts postgres-engine / search date filtering 2 source-surface-helper
test/postgres-engine.test.ts postgres-engine / search path timeout isolation 7 source-surface-helper
@@ -332,7 +326,6 @@ test/template-repo-generator.test.ts generateTemplateTree 0 readFileSync
test/template-repo-generator.test.ts renderTemplateReadme 5 readFileSync
test/think-embed-question-wiring.serial.test.ts #3734 — CRAG think escalation wires embedQuestion (source pin) 1 readFileSync
test/think-embed-question-wiring.serial.test.ts #3734 — synthesize verb wires embedQuestion into runThink 1 readFileSync
-test/think-save-source.test.ts #5426 think --save persists into the think source 5 readFileSync
test/timing-safe.test.ts extraction contract 1 source-surface-helper
test/title-fuzzy-index.test.ts findByTitleFuzzy indexed threshold 2 source-surface-helper
test/transcription-injection.test.ts transcription — command injection (#245) 2 readFileSync
diff --git a/test/auto-think-phase.test.ts b/test/auto-think-phase.test.ts
index 4d2d05f62d..31a8bb13a6 100644
--- a/test/auto-think-phase.test.ts
+++ b/test/auto-think-phase.test.ts
@@ -151,6 +151,30 @@ describe('runPhaseAutoThink', () => {
expect(['partial', 'skipped']).toContain(r.status);
await engine.setConfig('dream.auto_think.enabled', 'false');
});
+
+ test('a source-scoped cycle saves its synthesis into that source, not the default', async () => {
+ await engine.executeRaw(`INSERT INTO sources (id, name, config) VALUES ('auto-think-scoped', 'auto-think-scoped', '{}'::jsonb) ON CONFLICT DO NOTHING`);
+ await engine.setConfig('dream.auto_think.enabled', 'true');
+ await engine.setConfig('dream.auto_think.questions', JSON.stringify(['Which scoped founders matter?']));
+ await engine.setConfig('dream.auto_think.max_per_cycle', '1');
+ await engine.setConfig('dream.auto_think.budget', '10.0');
+ await engine.setConfig('dream.auto_think.auto_commit', 'true');
+ await engine.setConfig('dream.auto_think.cooldown_days', '0');
+ await engine.setConfig('dream.auto_think.last_completion_ts', '');
+ const before = await engine.executeRaw<{ id: number }>(`SELECT id FROM pages WHERE slug LIKE 'synthesis/%'`);
+ const r = await runPhaseAutoThink(engine, {
+ dryRun: false,
+ client: makeStubClient('A scoped synthesis about founders.'),
+ auditPath: join(tmpDir, 'b-scoped.jsonl'),
+ sourceId: 'auto-think-scoped',
+ });
+ expect(r.status).toBe('complete');
+ const saved = await engine.executeRaw<{ source_id: string }>(
+ `SELECT source_id FROM pages WHERE slug LIKE 'synthesis/%' AND NOT (id = ANY($1::int[]))`, [before.map(row => row.id)]);
+ expect(saved.map(row => row.source_id)).toEqual(['auto-think-scoped']);
+ await engine.setConfig('dream.auto_think.enabled', 'false');
+ await engine.setConfig('dream.auto_think.auto_commit', 'false');
+ });
});
describe('parseDriftOutput', () => {
diff --git a/test/autopilot-operator-pause.test.ts b/test/autopilot-operator-pause.test.ts
index 7544299248..158310d956 100644
--- a/test/autopilot-operator-pause.test.ts
+++ b/test/autopilot-operator-pause.test.ts
@@ -5,14 +5,17 @@
* clears only it — never a migration or restore hold.
*/
import { describe, expect, test } from 'bun:test';
-import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import { withEnv, emptyHome } from './helpers/with-env.ts';
import { autopilotOperatorPauseMarkerPath, autopilotPaused, autopilotPausedMarkerPath } from '../src/core/autopilot-paths.ts';
import { runAutopilotPauseCommand } from '../src/commands/autopilot-pause.ts';
import { resolveAutopilotPositionals, runAutopilot, runAutopilotStatus } from '../src/commands/autopilot.ts';
-import { surfaceSource } from './helpers/source-surface.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { MinionQueue } from '../src/core/minions/queue.ts';
+import { MinionWorker } from '../src/core/minions/worker.ts';
+import { waitFor } from './helpers/wait-for.ts';
function out(run: () => unknown): string {
const lines: string[] = [];
@@ -80,12 +83,86 @@ describe('autopilot operator pause', () => {
});
});
- test('the daemon loop and job workers consult both markers', () => {
- const root = join(import.meta.dir, '..', 'src');
- // test-reads-source-ok[structural]: no in-process autopilot tick or worker claim harness exists (TODOS: extract a testable tick); pin both markers at the gates.
- const daemon = surfaceSource('autopilot');
- const worker = readFileSync(join(root, 'core', 'minions', 'worker.ts'), 'utf8');
- expect(daemon).toContain('if (autopilotPaused()) {\n // Self-heal an orphan');
- expect(worker.match(/existsSync\(autopilotPausedMarkerPath\(\)\) \|\| existsSync\(autopilotOperatorPauseMarkerPath\(\)\)/g)?.length).toBe(2);
- });
+ test('a job worker claims nothing while the operator pause holds and runs the job after resume', async () => {
+ await withEnv({ GBRAIN_HOME: emptyHome() }, async () => {
+ const engine = new PGLiteEngine();
+ await engine.connect({}); await engine.initSchema();
+ const worker = new MinionWorker(engine, { pollInterval: 25, lockDuration: 30_000 });
+ worker.register('operator-pause-probe', async () => 'ran');
+ let running: Promise<void> | undefined;
+ try {
+ out(() => runAutopilotPauseCommand(['--pause', '--reason', 'upgrade window']));
+ const queue = new MinionQueue(engine);
+ const job = await queue.add('operator-pause-probe', {}, {}, { allowProtectedSubmit: true });
+ const lines: string[] = [];
+ const log = console.log;
+ console.log = (...parts: unknown[]) => { lines.push(parts.map(String).join(' ')); };
+ try {
+ running = worker.start();
+ await waitFor(() => lines.some(line => line.includes('pause marker present')), { timeoutMs: 15_000, label: 'worker parks on the pause' });
+ } finally { console.log = log; }
+ expect((await queue.getJob(job.id))).toMatchObject({ status: 'waiting', attempts_started: 0 });
+ out(() => runAutopilotPauseCommand(['--resume']));
+ await waitFor(async () => (await queue.getJob(job.id))?.status === 'completed', { timeoutMs: 15_000, label: 'job completes after resume' });
+ } finally {
+ worker.stop(); await running; await engine.disconnect();
+ }
+ });
+ }, 60_000);
+
+ test('a job claimed as the operator pause lands is released back to the queue un-run', async () => {
+ await withEnv({ GBRAIN_HOME: emptyHome() }, async () => {
+ const engine = new PGLiteEngine();
+ await engine.connect({}); await engine.initSchema();
+ const worker = new MinionWorker(engine, { pollInterval: 25, lockDuration: 30_000 });
+ let runs = 0;
+ worker.register('operator-pause-probe', async () => { runs++; return 'ran'; });
+ const queue = (worker as unknown as { queue: MinionQueue }).queue;
+ const claim = queue.claim.bind(queue);
+ queue.claim = (async (...args: Parameters<MinionQueue['claim']>) => {
+ const claimed = await claim(...args);
+ if (claimed && runs === 0) out(() => runAutopilotPauseCommand(['--pause', '--reason', 'upgrade window']));
+ return claimed;
+ }) as MinionQueue['claim'];
+ let running: Promise<void> | undefined;
+ try {
+ const job = await new MinionQueue(engine).add('operator-pause-probe', {}, {}, { allowProtectedSubmit: true });
+ const lines: string[] = [];
+ const log = console.log;
+ console.log = (...parts: unknown[]) => { lines.push(parts.map(String).join(' ')); };
+ try {
+ running = worker.start();
+ await waitFor(() => lines.some(line => line.includes('pause marker appeared after claim')), { timeoutMs: 15_000, label: 'worker releases the claimed job' });
+ } finally { console.log = log; }
+ expect(runs).toBe(0);
+ expect(await queue.getJob(job.id)).toMatchObject({ status: 'delayed', lock_token: null });
+ } finally {
+ worker.stop(); await running; await engine.disconnect();
+ }
+ });
+ }, 60_000);
+
+ test('the daemon loop skips cycles while the operator pause holds and resumes when it clears', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-operator-pause-daemon-'));
+ const env = { PATH: process.env.PATH, HOME: home, GBRAIN_HOME: home, GBRAIN_DISABLE_UPDATE_CHECK: '1', GBRAIN_MODEL_DISCOVERY: 'off' };
+ const cli = (...args: string[]) => Bun.spawn([process.execPath, join(import.meta.dir, '..', 'src', 'cli.ts'), ...args],
+ { cwd: home, env, stdout: 'pipe', stderr: 'pipe', stdin: 'ignore' });
+ try {
+ expect(await cli('init', '--pglite', '--no-embedding').exited).toBe(0);
+ mkdirSync(join(home, 'repo'));
+ expect(await cli('autopilot', 'pause', '--reason', 'upgrade window').exited).toBe(0);
+ const daemon = cli('autopilot', '--repo', join(home, 'repo'), '--interval', '1', '--inline');
+ let stdout = '';
+ const reader = (async () => { for await (const chunk of daemon.stdout) stdout += new TextDecoder().decode(chunk); })();
+ try {
+ await waitFor(() => stdout.includes('[autopilot] paused'), { timeoutMs: 30_000, label: 'daemon reports the pause' });
+ expect(stdout).not.toContain('[autopilot] resumed');
+ expect(await cli('autopilot', 'resume').exited).toBe(0);
+ await waitFor(() => stdout.includes('[autopilot] resumed'), { timeoutMs: 30_000, label: 'daemon resumes' });
+ } finally {
+ daemon.kill('SIGTERM');
+ await daemon.exited; await reader;
+ }
+ } finally { rmSync(home, { recursive: true, force: true }); }
+ }, 120_000);
});
diff --git a/test/consent.test.ts b/test/consent.test.ts
index 62b7fb6390..7159be27c8 100644
--- a/test/consent.test.ts
+++ b/test/consent.test.ts
@@ -191,13 +191,9 @@ describe('--non-interactive maps explicitly to effects', () => {
expect(isConsentRefusal(e)).toBe(true);
});
- test("the post-upgrade apply-migrations call authorizes exactly apply-migrations' install", async () => {
- // test-reads-source-ok[structural]: the internal upgrade caller's literal argv is the input under test (pinned by upgrade-no-autopilot too).
- const src = readFileSync(join(import.meta.dir, '..', 'src', 'commands', 'upgrade.ts'), 'utf8');
- const m = src.match(/(?:runApplyMigrations|applyMigrations)\(\[([^\]]*?)(?:,\s*\.\.\.|\])/);
- expect(m).not.toBeNull();
- const args = [...m![1].matchAll(/'([^']+)'/g)].map(x => x[1]);
- expect(args).toEqual(['--yes', '--non-interactive']);
+ test("the post-upgrade apply-migrations argv authorizes exactly apply-migrations' install", async () => {
+ // The argv post-upgrade passes at runtime is asserted in upgrade-no-autopilot.serial.test.ts.
+ const args = ['--yes', '--non-interactive'];
const auth = await requireConsent(req([...NON_INTERACTIVE_AUTHORIZES['apply-migrations']], args, { command: 'apply-migrations' }), env());
expect(auth.consented_effects).toEqual(['persistent_install']);
expect(auth.cap_usd).toBeNull();
diff --git a/test/embed-concurrency-pool-clamp.test.ts b/test/embed-concurrency-pool-clamp.test.ts
index 516fd06dbf..1abdf0dffd 100644
--- a/test/embed-concurrency-pool-clamp.test.ts
+++ b/test/embed-concurrency-pool-clamp.test.ts
@@ -2,12 +2,11 @@
* #5183: `embed --stale` wedged (no progress, no error, 0% CPU) when
* GBRAIN_EMBED_CONCURRENCY (default 20) exceeded the Postgres client pool:
* every worker holds a connection, so extra workers waited on the pool
- * forever. Embed concurrency is now clamped to the pool on Postgres.
+ * forever. Embed concurrency is now clamped to the pool on Postgres. Both
+ * embed loops' worker counts are exercised in embed.serial.test.ts.
*/
import { describe, test, expect, spyOn } from 'bun:test';
-import { readFileSync } from 'fs';
-import { resolve } from 'path';
import { _resetEmbedConcurrencyClampWarningForTest, resolveEmbedConcurrency } from '../src/commands/embed.ts';
@@ -44,11 +43,4 @@ describe('#5183 embed concurrency never exceeds the Postgres pool', () => {
expect(resolveEmbedConcurrency('postgres', 4, {}, 12)).toBe(4);
expect(resolveEmbedConcurrency('postgres', undefined, { GBRAIN_EMBED_CONCURRENCY: 'junk' }, 50)).toBe(20);
});
-
- test('both embed loops use the clamped value', () => {
- // test-reads-source-ok[structural]: both embed loops must take the clamped value; the loops need a live Postgres pool to observe.
- const src = readFileSync(resolve(import.meta.dir, '..', 'src', 'commands', 'embed.ts'), 'utf-8');
- expect(src.match(/const CONCURRENCY = resolveEmbedConcurrency\(engine\.kind, staleOpts\?\.paceMaxConcurrency\);/g)).toHaveLength(2);
- expect(src).not.toMatch(/parseInt\(process\.env\.GBRAIN_EMBED_CONCURRENCY/);
- });
});
diff --git a/test/embed.serial.test.ts b/test/embed.serial.test.ts
index 6f2d55f8ad..54597a1102 100644
--- a/test/embed.serial.test.ts
+++ b/test/embed.serial.test.ts
@@ -107,6 +107,30 @@ describe('runEmbed --all (parallel)', () => {
expect(maxConcurrentEmbedCalls).toBeLessThanOrEqual(10);
});
+ test('#5183: on Postgres neither embed loop runs more workers than the client pool', async () => {
+ const pages = Array.from({ length: 20 }, (_, i) => ({ slug: `pool-${i}`, source_id: 'default' }));
+ const chunks = (slug: string) => [{ chunk_index: 0, chunk_text: `text for ${slug}`, chunk_source: 'compiled_truth', embedded_at: null, token_count: 4 }];
+ const stale = pages.map((p, i) => ({ slug: p.slug, chunk_index: 0, chunk_text: `text for ${p.slug}`, chunk_source: 'compiled_truth' as const,
+ model: null, token_count: null, source_id: 'default', page_id: i + 1 }));
+ const previousPool = process.env.GBRAIN_POOL_SIZE;
+ process.env.GBRAIN_EMBED_CONCURRENCY = '10';
+ process.env.GBRAIN_POOL_SIZE = '3';
+ try {
+ await runEmbed(mockEngine({ kind: 'postgres', listPages: async () => pages, getChunks: async (slug: string) => chunks(slug), upsertChunks: async () => {} }), ['--all']);
+ expect(totalEmbedCalls).toBe(20);
+ expect(maxConcurrentEmbedCalls).toBeGreaterThan(1);
+ expect(maxConcurrentEmbedCalls).toBeLessThanOrEqual(3);
+ totalEmbedCalls = 0; maxConcurrentEmbedCalls = 0;
+ await runEmbedCore(mockEngine({ kind: 'postgres', countStaleChunks: async () => stale.length, listStaleChunks: async () => stale,
+ getChunks: async (slug: string) => chunks(slug) }), { stale: true });
+ expect(totalEmbedCalls).toBe(20);
+ expect(maxConcurrentEmbedCalls).toBeGreaterThan(1);
+ expect(maxConcurrentEmbedCalls).toBeLessThanOrEqual(3);
+ } finally {
+ if (previousPool === undefined) delete process.env.GBRAIN_POOL_SIZE; else process.env.GBRAIN_POOL_SIZE = previousPool;
+ }
+ });
+
test('v0.41.31: stamps embedding_signature after embedding each page (--all)', async () => {
const pages = [{ slug: 'a', source_id: 'default' }, { slug: 'b', source_id: 'default' }];
const chunksBySlug = new Map(
diff --git a/test/post-upgrade-banner.test.ts b/test/post-upgrade-banner.test.ts
index cbfb228cfc..a968fe6f2a 100644
--- a/test/post-upgrade-banner.test.ts
+++ b/test/post-upgrade-banner.test.ts
@@ -9,6 +9,8 @@ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'nod
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { postUpgradeRecoveryBanner } from '../src/commands/doctor/upgrade-banner.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
import { writeSingleFact } from '../src/core/facts/write-single.ts';
import { upsertOpenLoop } from '../src/core/loops/loops-store.ts';
import { managedBrain } from './helpers/managed-brain.ts';
@@ -78,10 +80,39 @@ describe('post-upgrade recovery banner', () => {
});
}, 180_000);
- test('post-upgrade prints the banner and no longer prints an applying safe-chunk advisory', () => {
- // test-reads-source-ok[structural]: runPostUpgrade needs a configured brain plus a full migration run; this pins that it calls the banner and no longer prints the applying advisory.
- const source = readFileSync(join(import.meta.dir, '..', 'src', 'commands', 'upgrade.ts'), 'utf8');
- expect(source).toContain('postUpgradeRecoveryBanner(engine');
- expect(source).not.toContain('safeChunkUpgradeAdvisory');
- });
+ test('gbrain post-upgrade relays the banner for a brain with findings and never an applying advisory', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-banner-cli-'));
+ const claude = selfCaptureHost();
+ const cli = async (...args: string[]) => {
+ const child = Bun.spawn([process.execPath, join(import.meta.dir, '..', 'src', 'cli.ts'), ...args], {
+ cwd: home, stdout: 'pipe', stderr: 'pipe', stdin: 'ignore',
+ env: { PATH: process.env.PATH, HOME: home, GBRAIN_HOME: home, CLAUDE_CONFIG_DIR: claude, GBRAIN_DISABLE_UPDATE_CHECK: '1', GBRAIN_SKIP_REFERENCE_SWEEP: '1' },
+ });
+ const [stdout, stderr, code] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]);
+ return { stdout, stderr, code };
+ };
+ try {
+ const init = await cli('init', '--pglite', '--no-embedding');
+ expect(init.code, init.stderr).toBe(0);
+ const { database_path } = JSON.parse(readFileSync(join(home, '.gbrain', 'config.json'), 'utf8'));
+ await withEnv({ GBRAIN_HOME: home, CLAUDE_CONFIG_DIR: claude }, async () => {
+ const engine = new PGLiteEngine();
+ await engine.connect({ database_path });
+ try {
+ for (const fact of ['Alice Example prefers Rust for systems work', 'Alice Example ships on Fridays']) {
+ await writeSingleFact(engine, 'default', { fact, entity: 'people/alice-example', provenance: 'hook:writeback', sessionId: 'sess-self' });
+ }
+ } finally { await disposePersistenceConsumer(engine); await engine.disconnect(); }
+ });
+ const upgraded = await cli('post-upgrade', '--no-autopilot-install');
+ expect(upgraded.code, upgraded.stderr).toBe(0);
+ expect(upgraded.stdout).toContain('[AGENT] Relay this to your operator');
+ expect(upgraded.stdout).toContain('[AGENT] captured_facts_active: 2 (explicit_kind_required; preview with: gbrain repair captured-facts)');
+ expect(`${upgraded.stdout}${upgraded.stderr}`).not.toMatch(/safe[- ]chunk/i);
+ expect(upgraded.stdout).not.toContain('--apply');
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ rmSync(claude, { recursive: true, force: true });
+ }
+ }, 180_000);
});
diff --git a/test/think-cli-source-flag.serial.test.ts b/test/think-cli-source-flag.serial.test.ts
index e616de293e..5957773cf8 100644
--- a/test/think-cli-source-flag.serial.test.ts
+++ b/test/think-cli-source-flag.serial.test.ts
@@ -14,7 +14,7 @@
*/
import { describe, test, expect, beforeEach, mock } from 'bun:test';
-const captured: { opts: Array<Record<string, unknown>> } = { opts: [] };
+const captured: { opts: Array<Record<string, unknown>>; persist: Array<Record<string, unknown>> } = { opts: [], persist: [] };
const stubResult = {
answer: 'Stub answer.',
@@ -32,7 +32,10 @@ mock.module('../src/core/think/index.ts', () => ({
captured.opts.push(opts);
return JSON.parse(JSON.stringify(stubResult));
},
- persistSynthesis: async () => ({ slug: 'synthesis/stub', evidenceInserted: 0, warnings: [] }),
+ persistSynthesis: async (_engine: unknown, _result: unknown, opts: Record<string, unknown> = {}) => {
+ captured.persist.push(opts);
+ return { slug: 'synthesis/stub', evidenceInserted: 0, warnings: [] };
+ },
stripGapsSection: (s: string) => s,
}));
@@ -105,7 +108,7 @@ async function runCli(args: string[]): Promise<{ code: number; out: string[]; er
}
}
-beforeEach(() => { captured.opts.length = 0; });
+beforeEach(() => { captured.opts.length = 0; captured.persist.length = 0; });
describe('#4508 think --source CLI surface', () => {
test('--source is parsed out of the question and threaded into runThink', async () => {
@@ -190,3 +193,33 @@ describe('#4508 think --source CLI surface', () => {
}
});
});
+
+describe('think --save writes to the resolved source', () => {
+ test('an explicit --source saves into that source only', async () => {
+ const r = await runCli(['plain', 'question', '--source', 'workspace', '--save']);
+ expect(r.code).toBe(0);
+ expect(captured.persist).toEqual([{ sourceId: 'workspace', allowedSources: undefined }]);
+ });
+
+ test('the ambient default saves into the default source, bound to its federated set', async () => {
+ const r = await runCli(['plain', 'question', '--save']);
+ expect(r.code).toBe(0);
+ expect(captured.persist).toEqual([{ sourceId: 'default', allowedSources: ['default', 'team-wiki'] }]);
+ });
+
+ test('--source __all__ is a read scope, so the save carries no source', async () => {
+ const r = await runCli(['plain', 'question', '--source', '__all__', '--save']);
+ expect(r.code).toBe(0);
+ expect(captured.persist).toEqual([{ sourceId: undefined, allowedSources: undefined }]);
+ });
+
+ test('the local think operation saves into the caller source and never into the __all__ sentinel', async () => {
+ const { operationsByName } = await import('../src/core/operations.ts');
+ const engine = { kind: 'pglite', executeRaw: async () => [], getConfig: async () => null } as never;
+ const ctx = (sourceId: string) => ({ engine, remote: false, sourceId, config: { engine: 'pglite' },
+ logger: { info() {}, warn() {}, error() {} } }) as never;
+ await operationsByName.think.handler(ctx('workspace'), { question: 'plain question', save: true });
+ await operationsByName.think.handler(ctx('__all__'), { question: 'plain question', save: true });
+ expect(captured.persist).toEqual([{ sourceId: 'workspace' }, { sourceId: undefined }]);
+ });
+});
diff --git a/test/think-save-source.test.ts b/test/think-save-source.test.ts
index 09b977270f..ec8dbbb21d 100644
--- a/test/think-save-source.test.ts
+++ b/test/think-save-source.test.ts
@@ -3,12 +3,12 @@
* its citations by bare slug, so on a multi-source brain the synthesis landed
* in the wrong source and its evidence could point at a same-slug page in
* another source. persistSynthesis now takes the think's scope from all three
- * callers (CLI think, the think op, auto-think).
+ * callers (CLI think, the think op, auto-think). Each caller's save scope is
+ * exercised in think-cli-source-flag.serial.test.ts (CLI, think op) and
+ * auto-think-phase.test.ts (auto-think).
*/
import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
-import { readFileSync } from 'fs';
-import { resolve } from 'path';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { persistSynthesis, type ThinkResult } from '../src/core/think/index.ts';
@@ -81,12 +81,4 @@ describe('#5426 think --save persists into the think source', () => {
const rows = await engine.executeRaw<{ source_id: string }>(`SELECT source_id FROM pages WHERE slug = $1`, [saved.slug]);
expect(rows.map(r => r.source_id)).toEqual(['default']);
});
-
- test('all three callers pass their scope', () => {
- // test-reads-source-ok[structural]: the three callers need a live LLM synthesis to observe end to end; persistSynthesis itself is tested above.
- const read = (p: string) => readFileSync(resolve(import.meta.dir, '..', p), 'utf-8');
- expect(read('src/commands/think.ts')).toContain('persistSynthesis(engine, result, { sourceId, allowedSources })');
- expect(read('src/core/ops/takes.ts')).toMatch(/persistSynthesis\(ctx\.engine, result, \{[\s\S]*?sourceId: ctx\.sourceId === ALL_SOURCES \? undefined : ctx\.sourceId/);
- expect(read('src/core/cycle/auto-think.ts')).toContain('persistSynthesis(engine, result, opts.sourceId ? { sourceId: opts.sourceId } : {})');
- });
});