Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(wave5-d): address Codex review of lane D

garrytan0a38da85a8c8
diff --git a/src/core/autopilot-paths.ts b/src/core/autopilot-paths.ts
index 7c327b5177..4932b4b52d 100644
--- a/src/core/autopilot-paths.ts
+++ b/src/core/autopilot-paths.ts
@@ -20,7 +20,7 @@
* because that is where the daemon itself writes; a `GBRAIN_HOME` install
* otherwise has readers looking in a different directory than the writer.
*/
-import { existsSync, linkSync, mkdirSync, readFileSync, realpathSync, renameSync, unlinkSync, writeFileSync } from 'fs';
+import { existsSync, linkSync, mkdirSync, readFileSync, realpathSync, renameSync, rmdirSync, statSync, unlinkSync, writeFileSync } from 'fs';
import { homedir } from 'os';
import { dirname, join, resolve } from 'path';
import { randomBytes } from 'crypto';
@@ -152,33 +152,57 @@ function replaceRecord(path: string, rec: InstallIdRecord): void {
renameSync(tmp, path);
}
+/**
+ * One installer at a time decides a move or a copy: without it two installers
+ * of a freshly copied brain could each mint an id, and the one whose record
+ * lost would leave a job nobody can find. A crashed holder's lock is broken
+ * after 30 seconds.
+ */
+function withInstallIdLock<T>(fn: () => T): T {
+ const lock = `${autopilotInstallIdPath()}.lock`;
+ const deadline = Date.now() + 10_000;
+ for (;;) {
+ try {
+ mkdirSync(lock);
+ break;
+ } catch (e) {
+ if ((e as NodeJS.ErrnoException).code !== 'EEXIST') throw e;
+ try { if (Date.now() - statSync(lock).mtimeMs > 30_000) { rmdirSync(lock); continue; } } catch { continue; }
+ if (Date.now() > deadline) throw new Error(`another autopilot install holds ${lock}; retry when it finishes`);
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 25);
+ }
+ }
+ try { return fn(); } finally { try { rmdirSync(lock); } catch { /* already gone */ } }
+}
+
/**
* The install id for this brain, minting or re-homing it as ENG-O11 describes.
* The first record is created exclusively, so concurrent first installs agree on
* one id; a move keeps the id and records the new directory; a copy mints its
- * own id so the original brain's job is never taken over.
+ * own id so the original brain's job is never taken over. Moves and copies are
+ * decided under a lock, so concurrent installers settle on one id.
*/
export function ensureAutopilotInstallId(): string {
mkdirSync(configDir(), { recursive: true });
const path = autopilotInstallIdPath();
const here = canonicalDir(configDir());
- for (let attempt = 0; attempt < 5; attempt++) {
- const current = resolveAutopilotInstallId();
- if (current.relation === 'same') return current.id;
- if (current.relation === 'moved') {
- replaceRecord(path, { id: current.id, realpath: here, created_at: readInstallIdRecord()?.created_at || new Date().toISOString() });
- } else {
- const fresh = { id: randomBytes(16).toString('hex'), realpath: here, created_at: new Date().toISOString() };
- if (current.relation === 'none') {
- if (writeRecordExclusive(path, fresh)) return fresh.id;
- continue;
- }
- replaceRecord(path, fresh);
- }
- const settled = readInstallIdRecord();
- if (settled && settled.realpath === here) return settled.id;
+ const current = resolveAutopilotInstallId();
+ if (current.relation === 'same') return current.id;
+ if (current.relation === 'none') {
+ const fresh = { id: randomBytes(16).toString('hex'), realpath: here, created_at: new Date().toISOString() };
+ if (writeRecordExclusive(path, fresh)) return fresh.id;
}
- throw new Error(`could not settle the autopilot install id at ${path}`);
+ return withInstallIdLock(() => {
+ const locked = resolveAutopilotInstallId();
+ if (locked.relation === 'same') return locked.id;
+ if (locked.relation === 'moved') {
+ replaceRecord(path, { id: locked.id, realpath: here, created_at: readInstallIdRecord()?.created_at || new Date().toISOString() });
+ return locked.id;
+ }
+ const fresh = { id: randomBytes(16).toString('hex'), realpath: here, created_at: new Date().toISOString() };
+ replaceRecord(path, fresh);
+ return fresh.id;
+ });
}
/**
diff --git a/src/core/connectors/item-holds-store.ts b/src/core/connectors/item-holds-store.ts
index a8bf6d84e2..f4a07d1585 100644
--- a/src/core/connectors/item-holds-store.ts
+++ b/src/core/connectors/item-holds-store.ts
@@ -80,55 +80,80 @@ export async function readAllSourceHolds(engine: Exec, opts: { sourceIds?: strin
return out;
}
-export interface HoldCarry { source_id: string; items: number; state_file: string | null; unreadable?: string }
+export interface HoldCarry {
+ source_id: string;
+ /** Held items in the managed checkpoint (0: only stale classic holds are cleared). */
+ items: number;
+ state_file: string | null;
+ unreadable?: string;
+ /** The host that owns the source's worktree when it is not this host. */
+ owner_host?: string;
+}
+
+const CONNECTOR_SOURCES_SQL = "SELECT id,incarnation::text AS incarnation,local_path,config FROM sources WHERE archived IS NOT TRUE AND config->>'kind' IN ('google','github') ORDER BY id";
+
+/** True when the hold cannot be carried from this host: deactivation keeps refusing for it. */
+export function holdCarryBlocked(carry: HoldCarry): boolean {
+ return carry.items > 0 && (!carry.state_file || !!carry.unreadable || !!carry.owner_host);
+}
+
+async function evaluateHoldCarry(engine: Exec, source: ConnectorSourceRow, hostId: string | null): Promise<{ holds: unknown; carry: HoldCarry } | null> {
+ const holds = (await readConnectorCursorState(engine, source, true))?.item_holds;
+ const items = heldItems(holds).length;
+ const file = classicConnectorStateFile(source);
+ let classic: Record<string, unknown> | null = null;
+ let unreadable: string | undefined;
+ if (file && existsSync(file)) {
+ try { classic = JSON.parse(readFileSync(file, 'utf-8')) as Record<string, unknown>; } catch (e) { unreadable = e instanceof Error ? e.message : String(e); }
+ }
+ // Nothing to carry and no copy left behind by an earlier, aborted deactivation.
+ if (!items && !(classic && 'item_holds' in classic)) return null;
+ const [owner] = await engine.executeRaw<{ owner: string | null }>(`SELECT w.owner_host_id::text AS owner FROM persistence_source_bindings b
+ JOIN persistence_worktrees w ON w.id=b.worktree_id WHERE b.source_id=$1 LIMIT 1`, [source.id]);
+ const foreign = owner?.owner && owner.owner !== hostId ? owner.owner : undefined;
+ return { holds, carry: { source_id: source.id, items, state_file: file, ...(unreadable ? { unreadable } : {}), ...(foreign ? { owner_host: foreign } : {}) } };
+}
/**
* Managed holds and where classic mode will read them after `sources writer
* deactivate`: each source's classic state file (`.google-source.json` /
- * `.github-source.json`). A source with no state directory, or whose existing
- * classic state file does not parse, cannot take its holds (`state_file` null
- * or `unreadable` set). Read-only.
+ * `.github-source.json`) on the host that owns the source. A source with no
+ * state directory, an existing classic state file that does not parse, or a
+ * worktree owned by another host cannot take its holds from here
+ * (holdCarryBlocked). Read-only.
*/
-export async function planHoldCarry(engine: Exec): Promise<HoldCarry[]> {
- const sources = await engine.executeRaw<ConnectorSourceRow>(
- "SELECT id,incarnation::text AS incarnation,local_path,config FROM sources WHERE archived IS NOT TRUE AND config->>'kind' IN ('google','github') ORDER BY id");
+export async function planHoldCarry(engine: Exec, hostId: string | null): Promise<HoldCarry[]> {
const out: HoldCarry[] = [];
- for (const source of sources) {
- const held = heldItems((await readConnectorCursorState(engine, source, true))?.item_holds);
- if (!held.length) continue;
- const file = classicConnectorStateFile(source);
- let unreadable: string | undefined;
- if (file && existsSync(file)) {
- try { JSON.parse(readFileSync(file, 'utf-8')); } catch (e) { unreadable = e instanceof Error ? e.message : String(e); }
- }
- out.push({ source_id: source.id, items: held.length, state_file: file, ...(unreadable ? { unreadable } : {}) });
+ for (const source of await engine.executeRaw<ConnectorSourceRow>(CONNECTOR_SOURCES_SQL)) {
+ const evaluated = await evaluateHoldCarry(engine, source, hostId);
+ if (evaluated) out.push(evaluated.carry);
}
return out;
}
/**
- * Copy each source's managed `item_holds` into its classic state file, keeping
- * every other field of that file, so a held item stays held (and keeps being
- * retried and reported) after deactivation. Throws for a source planHoldCarry
- * reports as uncarriable; deactivation refuses those first.
+ * Make each locally owned source's classic state file hold exactly its managed
+ * `item_holds` (every other field kept), so a held item stays held, retried and
+ * reported after deactivation, and a hold copied by an earlier deactivation
+ * that then aborted (and was resolved in managed mode since) is cleared.
+ * Throws for a blocked carry; deactivation refuses those first.
*/
-export async function carryHoldsToClassicState(engine: Exec): Promise<HoldCarry[]> {
- const sources = await engine.executeRaw<ConnectorSourceRow>(
- "SELECT id,incarnation::text AS incarnation,local_path,config FROM sources WHERE archived IS NOT TRUE AND config->>'kind' IN ('google','github') ORDER BY id");
+export async function carryHoldsToClassicState(engine: Exec, hostId: string | null): Promise<HoldCarry[]> {
const carried: HoldCarry[] = [];
- for (const source of sources) {
- const holds = (await readConnectorCursorState(engine, source, true))?.item_holds;
- const held = heldItems(holds);
- if (!held.length) continue;
- const file = classicConnectorStateFile(source);
- if (!file) throw new Error(`connector source ${source.id} has no state directory for its held items`);
- const existing = existsSync(file) ? JSON.parse(readFileSync(file, 'utf-8')) as Record<string, unknown> : {};
+ for (const source of await engine.executeRaw<ConnectorSourceRow>(CONNECTOR_SOURCES_SQL)) {
+ const evaluated = await evaluateHoldCarry(engine, source, hostId);
+ if (!evaluated) continue;
+ const { holds, carry } = evaluated;
+ if (holdCarryBlocked(carry)) throw new Error(`connector source ${carry.source_id} cannot take its held items on this host`);
+ if (!carry.state_file || carry.unreadable || carry.owner_host) continue;
+ const file = carry.state_file;
+ const { item_holds: _previous, ...rest } = existsSync(file) ? JSON.parse(readFileSync(file, 'utf-8')) as Record<string, unknown> : {};
mkdirSync(dirname(file), { recursive: true });
// Deactivation holds the worktree locks and the sources rows, so this write is
// its publication into a root that is still registered as managed.
await withFilesystemPublication([dirname(file)], async () =>
- atomicWriteFileSync(file, JSON.stringify({ ...existing, item_holds: holds }, null, 2)));
- carried.push({ source_id: source.id, items: held.length, state_file: file });
+ atomicWriteFileSync(file, JSON.stringify(carry.items ? { ...rest, item_holds: holds } : rest, null, 2)));
+ if (carry.items) carried.push(carry);
}
return carried;
}
diff --git a/src/core/ops/takes.ts b/src/core/ops/takes.ts
index 39dcee0457..6c47803f9a 100644
--- a/src/core/ops/takes.ts
+++ b/src/core/ops/takes.ts
@@ -24,6 +24,7 @@ import {
TakesWriteError,
} from '../takes-write.ts';
import { embedQuery } from '../embedding.ts';
+import { ALL_SOURCES } from '../source-id.ts';
import { privatePagesFilterFragment } from '../search/private-visibility.ts';
// --- v0.28: Takes ---
@@ -239,7 +240,8 @@ const think: Operation = {
let evidenceInserted = 0;
if (safeSave) {
const persisted = await persistSynthesis(ctx.engine, result, {
- sourceId: ctx.sourceId,
+ // '__all__' is a read scope, not a write destination: an unscoped save keeps the default source.
+ sourceId: ctx.sourceId === ALL_SOURCES ? undefined : ctx.sourceId,
...(thinkScope.allowedSources ? { allowedSources: thinkScope.allowedSources } : {}),
});
savedSlug = persisted.slug;
diff --git a/src/core/persistence/deactivation.ts b/src/core/persistence/deactivation.ts
index b9e9cf06bd..7acf6d65f1 100644
--- a/src/core/persistence/deactivation.ts
+++ b/src/core/persistence/deactivation.ts
@@ -37,7 +37,7 @@ import { managedFilesystemDatastorePath, refreshManagedFilesystemRoots } from '.
import { recordTopologyChange } from './topology-receipts.ts';
import { lockTopologyPrincipal, topologyPrincipal } from './topology-locks.ts';
import { canonicalFilesystemPath } from './root-registry.ts';
-import { carryHoldsToClassicState, planHoldCarry, type HoldCarry } from '../connectors/item-holds-store.ts';
+import { carryHoldsToClassicState, holdCarryBlocked, planHoldCarry, type HoldCarry } from '../connectors/item-holds-store.ts';
import { PHYSICAL_ROOT_MARKER, physicalRootReservationPath } from './physical-root-record.ts';
export const DEACTIVATE_DOCS = 'docs/architecture/topologies.md#deactivate-runbook';
@@ -117,14 +117,18 @@ export async function deactivationBlockers(engine: BrainEngine): Promise<Deactiv
}
// Managed connector holds live in the managed checkpoint, which classic mode does not read. Deactivation copies
// them into each source's classic state file; only a source whose holds have nowhere to go blocks it.
- for (const carry of await planHoldCarry(engine)) {
- if (carry.state_file && !carry.unreadable) continue;
+ for (const carry of await planHoldCarry(engine, existingLocalHostId())) {
+ if (!holdCarryBlocked(carry)) continue;
const resolve = `gbrain sources status ${carry.source_id} names each item's error; fix its cause, then gbrain sources retry-held ${carry.source_id} and gbrain sync --source ${carry.source_id} (a successful re-attempt clears the hold)`;
blockers.push({ kind: 'connector_holds', id: carry.source_id, source_id: carry.source_id,
- detail: carry.state_file
- ? `${carry.items} held item(s); the classic state file ${carry.state_file} does not parse (${carry.unreadable})`
- : `${carry.items} held item(s) and no classic state directory to carry them into`,
- exit: carry.state_file ? `move ${carry.state_file} aside, then rerun deactivate; or ${resolve}` : resolve });
+ detail: carry.owner_host
+ ? `${carry.items} held item(s) on a worktree owned by host ${carry.owner_host}; deactivate cannot write that host's classic state`
+ : carry.state_file
+ ? `${carry.items} held item(s); the classic state file ${carry.state_file} does not parse (${carry.unreadable})`
+ : `${carry.items} held item(s) and no classic state directory to carry them into`,
+ exit: carry.owner_host
+ ? `run deactivate on host ${carry.owner_host}; or ${resolve}`
+ : carry.state_file ? `move ${carry.state_file} aside, then rerun deactivate; or ${resolve}` : resolve });
}
const leases = await engine.executeRaw<{ id: string; holder_host: string; holder_pid: number }>(
'SELECT id, holder_host, holder_pid FROM gbrain_cycle_locks WHERE ttl_expires_at > now() ORDER BY id');
@@ -172,7 +176,7 @@ export async function deactivatePersistence(engine: BrainEngine, opts: { dryRun?
}
const blockers = await deactivationBlockers(engine);
if (opts.dryRun) {
- const carried_holds = (await planHoldCarry(engine)).filter(c => c.state_file && !c.unreadable);
+ const carried_holds = (await planHoldCarry(engine, existingLocalHostId())).filter(c => c.items > 0 && !holdCarryBlocked(c));
return { ...base, mode: 'managed', deactivated: false, mode_epoch: Number(brain.mode_epoch), blockers, carried_holds };
}
if (blockers.length) throw blockedError(blockers);
@@ -207,7 +211,7 @@ export async function deactivatePersistence(engine: BrainEngine, opts: { dryRun?
const inside = await deactivationBlockers(tx);
if (inside.length) throw blockedError(inside);
// Written before commit: if the transaction then fails, the brain stays managed and ignores these files.
- const carried_holds = await carryHoldsToClassicState(tx);
+ const carried_holds = await carryHoldsToClassicState(tx, hostId);
const retired = await retiredTopology(tx);
const [epoch] = await tx.executeRaw<{ mode_epoch: string }>(
'UPDATE persistence_brain SET enabled=false, mode_epoch=mode_epoch+1 WHERE singleton=1 RETURNING mode_epoch::text');
diff --git a/test/autopilot-install-id.test.ts b/test/autopilot-install-id.test.ts
index 419582786c..e58c0cf460 100644
--- a/test/autopilot-install-id.test.ts
+++ b/test/autopilot-install-id.test.ts
@@ -187,6 +187,29 @@ describe('#5195 non-default brains get their own names from the install id', ()
});
}, 60_000);
+ test('concurrent installs of a freshly copied brain settle on one new id', async () => {
+ await withHosts(async (root) => {
+ const original = await withEnv({ GBRAIN_HOME: join(root, 'brain-a') }, () => ensureAutopilotInstallId());
+ cpSync(join(root, 'brain-a'), join(root, 'brain-copy'), { recursive: true });
+ const script = `import { ensureAutopilotInstallId } from ${JSON.stringify(join(REPO, 'src/core/autopilot-paths.ts'))};\nprocess.stdout.write(ensureAutopilotInstallId());\n`;
+ const scriptPath = join(root, 'race-copy.ts');
+ writeFileSync(scriptPath, script);
+ const ids = await Promise.all(Array.from({ length: 6 }, () => new Promise<string>((done, fail) => {
+ const child = spawn(process.execPath, [scriptPath], { env: { ...process.env, GBRAIN_HOME: join(root, 'brain-copy'), HOME: join(root, 'home') } });
+ let out = '';
+ let err = '';
+ child.stdout.on('data', (d) => { out += d; });
+ child.stderr.on('data', (d) => { err += d; });
+ child.on('close', (code) => (code === 0 ? done(out.trim()) : fail(new Error(`exit ${code}: ${err}`))));
+ })));
+ expect(new Set(ids).size).toBe(1);
+ expect(ids[0]).not.toBe(original);
+ const recorded = JSON.parse(readFileSync(join(root, 'brain-copy', '.gbrain', 'autopilot-install-id'), 'utf-8'));
+ expect(recorded.id).toBe(ids[0]);
+ expect(existsSync(join(root, 'brain-copy', '.gbrain', 'autopilot-install-id.lock'))).toBe(false);
+ });
+ }, 60_000);
+
test('the GBRAIN_AUTOPILOT_LABEL test seam still wins over the suffix', async () => {
await withHosts(async (root) => {
await withEnv({ GBRAIN_HOME: join(root, 'brain-a'), GBRAIN_AUTOPILOT_LABEL: 'com.gbrain.autopilot.test.seam' }, () => {
diff --git a/test/hold-carry-classic-state.test.ts b/test/hold-carry-classic-state.test.ts
new file mode 100644
index 0000000000..9bf404100e
--- /dev/null
+++ b/test/hold-carry-classic-state.test.ts
@@ -0,0 +1,90 @@
+/**
+ * Wave-5 follow-up: `sources writer deactivate` carries managed connector holds
+ * into each source's classic state file. These pin the two edges the
+ * integrated scenario (fix-wave-4-integration X6) does not reach:
+ * - a source whose worktree another host owns is not written from here
+ * (its classic state lives on that host); deactivation keeps refusing;
+ * - a hold copied by an earlier deactivation that then aborted, and was
+ * resolved in managed mode since, is cleared on the next carry instead of
+ * coming back as held in classic mode.
+ */
+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs';
+import { join } from 'path';
+import { tmpdir } from 'os';
+import { randomUUID } from 'crypto';
+
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { carryHoldsToClassicState, holdCarryBlocked, planHoldCarry } from '../src/core/connectors/item-holds-store.ts';
+import { carryLegacyFailCounts } from '../src/core/connectors/item-holds.ts';
+import { connectorCheckpointKey, connectorIdentity } from '../src/core/persistence/connector-identity.ts';
+
+let engine: PGLiteEngine;
+let dir: string;
+const config = { kind: 'google', g_account: '[email protected]', g_services: 'gmail', g_access: 'env', g_token_env: 'CONNECTOR_TEST_TOKEN' };
+const HOST = randomUUID();
+const held = () => carryLegacyFailCounts(undefined, { 'thread-1': 3 }, id => id, '2026-10-01T00:00:00.000Z');
+const stateFile = () => join(dir, '.google-source.json');
+
+async function setManagedHolds(holds: unknown): Promise<void> {
+ const [row] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation::text AS incarnation FROM sources WHERE id='gmail-a'");
+ const key = connectorCheckpointKey('gmail-a', row.incarnation, connectorIdentity('google', config, dir));
+ await engine.executeRaw("DELETE FROM op_checkpoints WHERE op='managed-connector'");
+ await engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES('managed-connector',$1,$2::text::jsonb)`,
+ [key, JSON.stringify([{ state: { history_id: 'h1', item_holds: holds } }])]);
+}
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ dir = mkdtempSync(join(tmpdir(), 'gbrain-hold-carry-'));
+ await engine.executeRaw('INSERT INTO sources (id, name, local_path, config) VALUES ($1, $1, $2, $3::text::jsonb)', ['gmail-a', dir, JSON.stringify(config)]);
+}, 60_000);
+
+afterAll(async () => {
+ await engine.disconnect();
+ rmSync(dir, { recursive: true, force: true });
+}, 60_000);
+
+beforeEach(async () => {
+ rmSync(stateFile(), { force: true });
+ await engine.executeRaw('DELETE FROM persistence_source_bindings');
+ await engine.executeRaw('DELETE FROM persistence_worktrees');
+});
+
+describe('carrying connector holds into classic state', () => {
+ test('a locally owned source takes its managed holds, other classic fields kept', async () => {
+ await setManagedHolds(held());
+ writeFileSync(stateFile(), JSON.stringify({ gmail_history_id: 'classic-cursor' }));
+ const carried = await carryHoldsToClassicState(engine, HOST);
+ expect(carried).toEqual([{ source_id: 'gmail-a', items: 1, state_file: stateFile() }]);
+ const classic = JSON.parse(readFileSync(stateFile(), 'utf-8'));
+ expect(classic.gmail_history_id).toBe('classic-cursor');
+ expect(classic.item_holds).toEqual(JSON.parse(JSON.stringify(held())));
+ });
+
+ test('a hold copied by an aborted deactivation and resolved since is cleared, not resurrected', async () => {
+ writeFileSync(stateFile(), JSON.stringify({ gmail_history_id: 'classic-cursor', item_holds: held() }));
+ await setManagedHolds({ version: 1, items: {} });
+ expect(await carryHoldsToClassicState(engine, HOST)).toEqual([]);
+ const classic = JSON.parse(readFileSync(stateFile(), 'utf-8'));
+ expect(classic).toEqual({ gmail_history_id: 'classic-cursor' });
+ });
+
+ test('a source whose worktree another host owns blocks and is never written from here', async () => {
+ await setManagedHolds(held());
+ const [incarnation] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation::text AS incarnation FROM sources WHERE id='gmail-a'");
+ const other = randomUUID();
+ const [worktree] = await engine.executeRaw<{ id: string }>('INSERT INTO persistence_worktrees (owner_host_id) VALUES ($1::uuid) RETURNING id::text', [other]);
+ await engine.executeRaw('INSERT INTO persistence_source_bindings (source_id, source_incarnation, worktree_id) VALUES ($1, $2::uuid, $3::uuid)',
+ ['gmail-a', incarnation.incarnation, worktree.id]);
+ const [plan] = await planHoldCarry(engine, HOST);
+ expect(plan).toMatchObject({ source_id: 'gmail-a', items: 1, owner_host: other });
+ expect(holdCarryBlocked(plan)).toBe(true);
+ await expect(carryHoldsToClassicState(engine, HOST)).rejects.toThrow(/cannot take its held items on this host/);
+ expect(existsSync(stateFile())).toBe(false);
+ // The owning host carries them.
+ expect(holdCarryBlocked((await planHoldCarry(engine, other))[0])).toBe(false);
+ });
+});
diff --git a/test/think-save-source.test.ts b/test/think-save-source.test.ts
index 408a685a40..09b977270f 100644
--- a/test/think-save-source.test.ts
+++ b/test/think-save-source.test.ts
@@ -83,9 +83,10 @@ describe('#5426 think --save persists into the think source', () => {
});
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*sourceId: ctx\.sourceId/);
+ 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 } : {})');
});
});