Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(corpus): stamp the session source into every corpus file (#6268)
time-attackc35da6f8c8c2
diff --git a/src/commands/doctor/checks/memory-writeback.ts b/src/commands/doctor/checks/memory-writeback.tsindex ad638530ed..0973ee500c 100644--- a/src/commands/doctor/checks/memory-writeback.ts+++ b/src/commands/doctor/checks/memory-writeback.ts@@ -40,7 +40,8 @@ import { classifyBrainAudience } from '../../../core/facts/writeback-audience.tsimport { readVerbUsage } from '../../../core/verbs/usage-log.ts';import { readClientOpUsage } from '../../../core/mcp-usage.ts';import { readHeartbeatTail } from '../../../core/context/hook-heartbeat.ts';-import { CORPUS_UNINGESTED_RETENTION_FACTOR, corpusBacklog } from '../../../core/context/corpus-segments.ts';+import { CORPUS_UNINGESTED_RETENTION_FACTOR, corpusBacklog, corpusSpoolDir } from '../../../core/context/corpus-segments.ts';+import { listCorpusSourceHolds } from '../../../core/context/corpus-source.ts';import { readHarnessReceiptState } from '../../../core/bootstrap/format.ts';import { mutedFirstRunDecisionsNotice } from '../../../core/onboard/mcp-onboarding.ts';import {@@ -113,13 +114,38 @@ const DAY_MS = 24 * 60 * 60 * 1000;* past plain retention it is on its way to deletion, so the check says so.* Records `details.corpus_backlog`; returns the warning text or null.*/-async function corpusBacklogProblem(engine: BrainEngine, fileCfg: ReturnType<typeof loadConfig>, details: Record<string, unknown>): Promise<string | null> {+async function sessionCorpusDir(engine: BrainEngine, fileCfg: ReturnType<typeof loadConfig>): Promise<string> {const synth = fileCfg?.dream?.synthesize as Record<string, unknown> | undefined;const configured = (await engine.getConfig('dream.synthesize.session_corpus_dir').catch(() => null)) ?? synth?.session_corpus_dir;- const dir = typeof configured === 'string' && isAbsolute(configured) ? configured : join(resolveGbrainHome(), 'transcripts', 'corpus');+ return typeof configured === 'string' && isAbsolute(configured) ? configured : join(resolveGbrainHome(), 'transcripts', 'corpus');+}++/**+ * #6268: captured session files held because nothing proves their source+ * (legacy top-level files on a multi-source brain, or sessions whose source+ * never resolved). Only the operator can say where they belong, so the+ * warning names the preview command. Records `details.corpus_source_holds`.+ */+async function corpusSourceHoldProblem(engine: BrainEngine, fileCfg: ReturnType<typeof loadConfig>, details: Record<string, unknown>): Promise<string | null> {+ const sources = await engine.executeRaw<{ id: string }>('SELECT id FROM sources ORDER BY id LIMIT 2');+ const holds = listCorpusSourceHolds(await sessionCorpusDir(engine, fileCfg), sources.length === 1);+ details.corpus_source_holds = { legacy_unstamped: holds.legacy_unstamped, unresolved: holds.unresolved, sessions: holds.sessions.length };+ const held = holds.legacy_unstamped + holds.unresolved;+ if (held === 0) return null;+ return `${held} captured session file(s) from ${holds.sessions.length} session(s) are held because nothing records which source they belong to `+ + '(written before corpus files carried their source, or the session never resolved one); they are not extracted until mapped. '+ + 'Ask the user which source they belong to, preview with gbrain sweep --assign-corpus <source>, then add --apply';+}++async function corpusBacklogProblem(engine: BrainEngine, fileCfg: ReturnType<typeof loadConfig>, details: Record<string, unknown>): Promise<string | null> {+ const synth = fileCfg?.dream?.synthesize as Record<string, unknown> | undefined;+ const dir = await sessionCorpusDir(engine, fileCfg);const days = typeof synth?.corpus_retention_days === 'number' && synth.corpus_retention_days > 0 ? synth.corpus_retention_days : 30;const now = Date.now();- const backlog = corpusBacklog(dir, days * DAY_MS, now);+ const top = corpusBacklog(dir, days * DAY_MS, now);+ const spool = corpusBacklog(corpusSpoolDir(dir), days * DAY_MS, now);+ const oldest = [top.oldestPendingMtimeMs, spool.oldestPendingMtimeMs].filter((m): m is number => m !== null);+ const backlog = { pending: top.pending + spool.pending, pastRetention: top.pastRetention + spool.pastRetention, oldestPendingMtimeMs: oldest.length ? Math.min(...oldest) : null };const oldestDays = backlog.oldestPendingMtimeMs === null ? null : Math.floor((now - backlog.oldestPendingMtimeMs) / DAY_MS);const purgeDays = days * CORPUS_UNINGESTED_RETENTION_FACTOR;details.corpus_backlog = { pending: backlog.pending, oldest_pending_days: oldestDays, past_retention: backlog.pastRetention, retention_days: days, deleted_after_days: purgeDays };@@ -228,6 +254,9 @@ export async function buildMemoryWritebackCheck(engine: BrainEngine | null): Pro}if (privateRemoteProblem) offProblems.push(privateRemoteProblem);const explicitOff = wb.raw_mode === 'off';+ // Unset (default) off still extracts SessionEnd and compaction files; explicit off retires them.+ const offHoldProblem = explicitOff ? null : await corpusSourceHoldProblem(engine, fileCfg, details).catch(() => null);+ if (offHoldProblem) offProblems.push(offHoldProblem);if (explicitOff) details.restart_after_off = WRITEBACK_RESTART_AFTER_OFF;return {name: MEMORY_WRITEBACK_CHECK_NAME,@@ -244,6 +273,8 @@ export async function buildMemoryWritebackCheck(engine: BrainEngine | null): Proconst problems: string[] = [];const corpusProblem = await corpusBacklogProblem(engine, fileCfg, details).catch(() => null);if (corpusProblem) problems.push(corpusProblem);+ const holdProblem = await corpusSourceHoldProblem(engine, fileCfg, details).catch(() => null);+ if (holdProblem) problems.push(holdProblem);if (!wb.ttl_valid) {problems.push(`memory.auto_writeback_transient_ttl is invalid — using '${wb.transient_ttl}'`);}diff --git a/src/commands/hook.ts b/src/commands/hook.tsindex b2039d5834..cd16fa33d6 100644--- a/src/commands/hook.ts+++ b/src/commands/hook.ts@@ -74,7 +74,11 @@ import {CORPUS_PROGRESS_LOCK_SUFFIX,HARVEST_RECEIPT_SUFFIX,segmentHash,+ CORPUS_UNRESOLVED_STAMP,+ ensureCorpusSpoolDir,+ sessionCorpusFileName,} from '../core/context/corpus-segments.ts';+import { openSessionSource } from '../core/context/corpus-source.ts';import { hookLaneLabel, resolveSeat, seatReasonHint, writeSeatSidecar } from '../core/context/seat.ts';import { gateWritebackTurn, WRITEBACK_SKIP_REASONS } from '../core/facts/writeback-gate.ts';import { resolveWritebackConfigFromFile } from '../core/facts/writeback-config.ts';@@ -539,6 +543,8 @@ async function hookSessionStart(io: HookIo): Promise<number> {// digest above must never be hostage to the brain being down.try {const cfg = loadConfig();+ const startSid = sanitizeSessionId(j?.session_id);+ if (startSid !== 'unknown') await sessionCorpus(io, cfg, startSid, ws); // #6268: the session source freezes at start// Engine-uniform (#4245): same config-keyed socket/secret resolution// as the user-prompt and compact arms (PGLite data dir; Postgres// hash12(database_url) run-dir). Null → silent skip, as before.@@ -1371,13 +1377,14 @@ async function hookCompact(io: HookIo): Promise<number> {// any IPC. Written for EVERY engine config (the sweep backstop harvests it// when serve/IPC is unavailable). Per-step deadline degrades — a scan that// can't finish skips the segment ENTIRELY (never write unscanned content).- const dir = await corpusDir(cfg);+ const { dir, stamp, source } = await sessionCorpus(io, cfg, sessionId, io.cwd ?? (typeof j.cwd === 'string' ? j.cwd : process.cwd()));seatReasons = captureSeat(io, dir, sessionId, transcriptPath);const banked = await bankCompactSegment(dir, sessionId, allTurns, boundaryTurnIndexes, {remainingMs: remaining,minScanMs: SEGMENT_MIN_BUDGET_MS,minWriteMs: SEGMENT_WRITE_MIN_BUDGET_MS,- beforeWrite: (file, text) => { recordCaptureIfOff(cfg, file, text, process.env.GBRAIN_SOURCE); },+ beforeWrite: (file, text) => { recordCaptureIfOff(cfg, file, text, source); },+ stamp,});segment = banked.segment;const flushCorpusFile = banked.flushCorpusFile;@@ -1387,7 +1394,7 @@ async function hookCompact(io: HookIo): Promise<number> {// leftover database_path must not probe the PGLite socket (the resolver// checks engine first); a Postgres brain probes its hash12(database_url)// run-dir socket instead. Null = no keying material → degrade.- const compactSocket = await hookResolveSocketForConfig(cfg, process.env.GBRAIN_SOURCE);+ const compactSocket = await hookResolveSocketForConfig(cfg, source);if (!compactSocket) { outcome = 'degraded'; reason = 'no_pglite_path'; return; }const secret = readIpcSecretForConfig(cfg);if (!secret) { outcome = 'degraded'; reason = 'no_serve'; return; }@@ -1400,7 +1407,7 @@ async function hookCompact(io: HookIo): Promise<number> {bankOnly: true,trigger: 'compact-bank',...(flushCorpusFile ? { flushCorpusFile } : {}),- ...(process.env.GBRAIN_SOURCE ? { sourceId: process.env.GBRAIN_SOURCE } : {}),+ ...(source ? { sourceId: source } : {}),});if (res === IPC_UNAVAILABLE) { outcome = 'degraded'; reason = 'ipc_unavailable'; return; }if ('degraded' in res && res.degraded === 'stale_serve') { outcome = 'degraded'; reason = 'stale_serve'; return; }@@ -1513,21 +1520,17 @@ async function hookStop(io: HookIo): Promise<number> {if (!lastUser || !lastUser.text) return 'no_user_turn';const gated = gateWritebackTurn(lastUser.text);if (!gated.ok) return gated.reason;- const dir = await corpusDir(cfg);+ const { dir, stamp, source } = await sessionCorpus(io, cfg, sid, ws);captureSeat(io, dir, sid, conf.path); // #4618: the seat precedes the banked turn file- const banked = await bankWritebackTurn(- dir, sid, gated.normalized, gated.hash24,- // Bank the session's source IN THE NAME so the sweep fallback files- // the turn into the same source the IPC lane below would have.- process.env.GBRAIN_SOURCE ?? null,- );+ // The session's source rides IN THE NAME so the sweep fallback files the turn where the IPC lane below would.+ const banked = await bankWritebackTurn(dir, sid, gated.normalized, gated.hash24, stamp);if (banked.status !== 'wb_banked' && banked.status !== 'wb_dup') return banked.status;if (banked.status === 'wb_dup') return 'wb_dup';// Prompt-harvest ask over the compact-bank IPC lane — sourceId rides// exactly like the compact call (OV2-9/OV-A6); every failure below is// degraded-not-blocking: the banked file is the durable artifact and// the sweep extracts it when serve is away.- const socket = await hookResolveSocketForConfig(cfg, process.env.GBRAIN_SOURCE);+ const socket = await hookResolveSocketForConfig(cfg, source);if (!socket) return 'no_pglite_path';const secret = readIpcSecretForConfig(cfg);if (!secret) return 'no_serve';@@ -1537,7 +1540,7 @@ async function hookStop(io: HookIo): Promise<number> {bankOnly: true,trigger: 'writeback-bank',...(banked.flushCorpusFile ? { flushCorpusFile: banked.flushCorpusFile } : {}),- ...(process.env.GBRAIN_SOURCE ? { sourceId: process.env.GBRAIN_SOURCE } : {}),+ ...(source ? { sourceId: source } : {}),});if (res === IPC_UNAVAILABLE) return 'ipc_unavailable';if ('degraded' in res && res.degraded === 'stale_serve') return 'stale_serve';@@ -1624,6 +1627,14 @@ async function corpusDir(cfg: GBrainConfig | null): Promise<string> {return ensureDir0700(join(home, 'transcripts', 'corpus'));}+/** #6268: the session's spool dir and frozen source stamp (`source` unset while unresolved). */+async function sessionCorpus(io: HookIo, cfg: GBrainConfig | null, sessionId: string, cwd: string): Promise<{ root: string; dir: string; stamp: string; source?: string }> {+ const root = await corpusDir(cfg);+ const dir = ensureCorpusSpoolDir(root);+ const { stamp } = await openSessionSource(root, sessionId, { cwd, harness: io.harness ?? 'claude-code' });+ return { root, dir, stamp, ...(stamp !== CORPUS_UNRESOLVED_STAMP ? { source: stamp } : {}) };+}+function corpusRetentionDays(cfg: GBrainConfig | null): number {// Key is plan-defined [G15] but not yet in the GBrainConfig type (config.ts// is another lane's file) — read tolerantly.@@ -1747,7 +1758,7 @@ async function hookSessionEnd(io: HookIo): Promise<number> {// Whole-file reads only: a bounded tail of a long agentic run can// legitimately hold assistant turns alone.if (parsed.genuineUserTurnIndexes.length === 0 && bytesN >= conf.size) degrade('no_user_turns');- const dir = await corpusDir(cfg);+ const { root, dir, stamp, source } = await sessionCorpus(io, cfg, sessionId, ws ?? process.cwd());// #4618: the seat is recorded BEFORE any corpus file of this session// is renamed into place, so a sweep never sees one without its seat.deferredReasons.push(...captureSeat(io, dir, sessionId, conf.path));@@ -1791,9 +1802,9 @@ async function hookSessionEnd(io: HookIo): Promise<number> {// the rename so the sweep re-processes the appended transcript (a// resumed session's new turns were being permanently skipped when the// completion sidecar survived the overwrite).- const corpusFile = join(dir, `${sessionId}.txt`);+ const corpusFile = join(dir, sessionCorpusFileName(sessionId, stamp));const tmpCorpus = `${corpusFile}.tmp-${process.pid}`;- recordCaptureIfOff(cfg, corpusFile, text, process.env.GBRAIN_SOURCE); // #6091, before the rename+ recordCaptureIfOff(cfg, corpusFile, text, source); // #6091, before the renamewriteFileSync(tmpCorpus, text, { mode: 0o600 });renameSync(tmpCorpus, corpusFile);// Additive signal for a local third-party consumer (never gbrain@@ -1839,14 +1850,10 @@ async function hookSessionEnd(io: HookIo): Promise<number> {}}const retentionMs = corpusRetentionDays(cfg) * 24 * 60 * 60 * 1000;- gcCorpusTurnFiles(dir, retentionMs); // [G15]; un-ingested turns kept longer (E-N1)- gcCorpusArtifacts(dir, retentionMs, [- CORPUS_INGESTED_SUFFIX,- CORPUS_CLAIM_SUFFIX,- CORPUS_PROGRESS_SUFFIX,- CORPUS_PROGRESS_LOCK_SUFFIX,- HARVEST_RECEIPT_SUFFIX,- ]);+ for (const gcDir of [dir, root]) { // the spool and the legacy top level+ gcCorpusTurnFiles(gcDir, retentionMs); // [G15]; un-ingested turns kept longer (E-N1)+ gcCorpusArtifacts(gcDir, retentionMs, [CORPUS_INGESTED_SUFFIX, CORPUS_CLAIM_SUFFIX, CORPUS_PROGRESS_SUFFIX, CORPUS_PROGRESS_LOCK_SUFFIX, HARVEST_RECEIPT_SUFFIX]);+ }}}} catch (e) {diff --git a/src/commands/sweep.ts b/src/commands/sweep.tsindex b1c637b2e4..e7a71f6bbe 100644--- a/src/commands/sweep.ts+++ b/src/commands/sweep.ts@@ -17,12 +17,15 @@import type { BrainEngine } from '../core/engine.ts';import { runMaintenanceSweep, type SweepReport } from '../core/sweep.ts';-import { setCliExitVerdict } from '../core/cli-force-exit.ts';+import { jsonRequested, setCliExitVerdict } from '../core/cli-force-exit.ts';+import { opError } from '../core/ops/contract.ts';+import { writeCliRefusal } from '../cli/cli-error.ts';export const SWEEP_HELP = `gbrain sweep — run the serve-resident maintenance sweep once, locallyUsage:gbrain sweep --once [--source <id>] [--budget-ms <n>] [--batch-limit <n>] [--json]+ gbrain sweep --assign-corpus <source> [--session <id>] [--apply] [--json]Runs the three bounded sweep passes against the connected brain:1. facts-fence reconciliation (zero-LLM): recently-modified pages with a@@ -41,6 +44,14 @@ Flags:--batch-limit <n> Max pages / corpus files per pass (default 20).--json Print the SweepReport as JSON on stdout.+Held session files (#6268): a captured session file is extracted into the+source its name or its session record carries. Files written before session+files recorded their source (on a brain with more than one source), and+sessions whose source never resolved, are held. --assign-corpus previews+which held sessions would be mapped to <source>; --apply records the+mapping (a session that already names a source is never changed), and the+next sweep extracts them there. --session limits it to one session.+Exit codes: 0 = success or partial (see "skipped" in the report);1 = total failure (every pass errored). Local-only; never runs over MCP.`;@@ -72,6 +83,10 @@ export async function runSweep(engine: BrainEngine, args: string[]): Promise<voiconsole.log(SWEEP_HELP);return;}+ if (args.includes('--assign-corpus')) {+ await runAssignCorpus(engine, args);+ return;+ }if (!args.includes('--once')) {console.error('gbrain sweep: --once is required (one bounded sweep, then exit).');console.error('Run `gbrain sweep --help` for usage.');@@ -130,3 +145,47 @@ export async function runSweep(engine: BrainEngine, args: string[]): Promise<voisetCliExitVerdict(1);}}++/** #6268: preview (default) or apply the operator's source mapping for held session files. */+async function runAssignCorpus(engine: BrainEngine, args: string[]): Promise<void> {+ const json = jsonRequested(args);+ const sourceId = args[args.indexOf('--assign-corpus') + 1];+ const sessionIdx = args.indexOf('--session');+ const onlySession = sessionIdx >= 0 ? args[sessionIdx + 1] : undefined;+ const { isValidSourceId } = await import('../core/source-id.ts');+ const rows = isValidSourceId(sourceId)+ ? await engine.executeRaw<{ archived: boolean }>('SELECT archived FROM sources WHERE id = $1', [sourceId])+ : [];+ if (!rows.length || rows[0].archived) {+ setCliExitVerdict(writeCliRefusal(opError('invalid_source',+ `gbrain sweep --assign-corpus: ${JSON.stringify(sourceId ?? '')} is not an active source of this brain`,+ 'Ask the user which source the held session files belong to; `gbrain sources list` shows the active sources.',+ { why: 'Held session files are mapped only to a source that exists and is not archived.',+ fix: { argv: ['gbrain', 'sources', 'list'], consent: [], actor: 'agent', requires_exclusive: false,+ why: 'Lists the active sources to choose from.', verify: { argv: ['gbrain', 'doctor', '--only', 'memory_writeback', '--json'] } } }),+ 'sweep', { json }));+ return;+ }+ let dir = await engine.getConfig('dream.synthesize.session_corpus_dir');+ if (!dir) {+ const { configDir } = await import('../core/config.ts');+ const { join } = await import('node:path');+ dir = join(configDir(), 'transcripts', 'corpus');+ }+ const { assignCorpusSessions, listCorpusSourceHolds } = await import('../core/context/corpus-source.ts');+ const sources = await engine.executeRaw<{ id: string }>('SELECT id FROM sources ORDER BY id LIMIT 2');+ const holds = listCorpusSourceHolds(dir, sources.length === 1);+ const sessions = holds.sessions.filter(s => onlySession === undefined || s === onlySession);+ const apply = args.includes('--apply');+ const assigned = apply ? assignCorpusSessions(dir, sessions, sourceId) : [];+ const out = { source: sourceId, applied: apply, held_sessions: sessions, assigned_sessions: assigned };+ if (json) {+ console.log(JSON.stringify(out, null, 2));+ } else if (!apply) {+ console.log(`${sessions.length} held session(s) would be mapped to source ${sourceId}:`);+ for (const s of sessions) console.log(` ${s}`);+ if (sessions.length) console.log(`Apply: gbrain sweep --assign-corpus ${sourceId}${onlySession ? ` --session ${onlySession}` : ''} --apply`);+ } else {+ console.log(`Mapped ${assigned.length} held session(s) to source ${sourceId}; the next sweep extracts them (gbrain sweep --once).`);+ }+}diff --git a/src/core/context-engine.ts b/src/core/context-engine.tsindex 5dcb6dd2a3..d3128b0000 100644--- a/src/core/context-engine.ts+++ b/src/core/context-engine.ts@@ -883,8 +883,9 @@ export function createGBrainContextEngine(ctx: {// silently eats that session's next delta window. With bankOnly the// old serve takes the banking arm (no assembly, no cursor advance,// and with no window/entities in this request, no banking either).+ const source = await sessionSourceFor(cfg, sessionId);const res = await ipc.requestContextPack(ipc.resolveSocketPath(cfg.database_path), {- secret, sessionId, manifestOnly: true, bankOnly: true,+ secret, sessionId, manifestOnly: true, bankOnly: true, ...(source ? { sourceId: source } : {}),});if (res === ipc.IPC_UNAVAILABLE || !('ok' in res) || !res.ok || !res.block) return null;// Old-serve capability probe: a response WITHOUT the checkpointLinks@@ -898,7 +899,7 @@ export function createGBrainContextEngine(ctx: {const pg = await getDirectPostgresEngine(cfg);if (!pg) return null;const { resolveSourceId } = await import('./source-resolver.ts');- const sourceId = await resolveSourceId(pg, null, workspaceDir);+ const sourceId = (await sessionSourceFor(cfg, sessionId)) ?? await resolveSourceId(pg, null, workspaceDir);const ss = await import('./context/session-state.ts');return await ss.getCheckpointManifest(pg, sourceId, null, sessionId);} catch {@@ -979,10 +980,15 @@ export function createGBrainContextEngine(ctx: {// Spool FIRST (durability is engine-independent; the sweep is the backstop).const { loadConfig } = await import('./config.ts');const cfg = loadConfig();- const dir = await engineCorpusDir(cfg);+ // #6268: the session's frozen source rides in the segment NAME, inside the spool.+ const root = await engineCorpusDir(cfg);+ const dir = segs.ensureCorpusSpoolDir(root);+ const { stamp } = await (await import('./context/corpus-source.ts')).openSessionSource(root, sessionId, { cwd: workspaceDir, harness: 'openclaw' });+ const source = stamp !== segs.CORPUS_UNRESOLVED_STAMP ? stamp : undefined;+ const segName = (hash: string) => segs.segmentFileName(sessionId, hash, stamp);await recordOpenclawSeat(dir, sessionId, sessionFile);- (await import('./context/capture-consent.ts')).recordCaptureIfOff(cfg, `${dir}/${segs.segmentFileName(sessionId, segs.segmentHash(rendered.text))}`, rendered.text);- const w = segs.writeSegment(dir, sessionId, rendered.text);+ (await import('./context/capture-consent.ts')).recordCaptureIfOff(cfg, `${dir}/${segName(segs.segmentHash(rendered.text))}`, rendered.text, source);+ const w = segs.writeSegment(dir, sessionId, rendered.text, stamp);const ordinal = segs.appendSegmentLedger(dir, sessionId, w.hash);const memo = checkpointMemo.get(sessionId) ?? { links: [], polls: 0, expectSeg: null, settled: false };memo.expectSeg = w.hash;@@ -1028,7 +1034,7 @@ export function createGBrainContextEngine(ctx: {await hb.recordAndRelayReceipt({session_id: sessionId,harness: 'openclaw',- corpus_path: `${dir}/${segs.segmentFileName(sessionId, w.hash)}`,+ corpus_path: `${dir}/${segName(w.hash)}`,content_hash: w.hash,turn_count: windowTurns.length,workspace_root: workspaceDir,@@ -1062,7 +1068,8 @@ export function createGBrainContextEngine(ctx: {window: windowTurns.slice(-COMPACT_BANK_WINDOW_TURNS),bankOnly: true,trigger: 'compact-bank',- flushCorpusFile: segs.segmentFileName(sessionId, w.hash),+ flushCorpusFile: segName(w.hash),+ ...(source ? { sourceId: source } : {}),});if (res === ipc.IPC_UNAVAILABLE) return { status: 'banked', reason: 'ipc_unavailable' };return { status: 'banked' };@@ -1074,7 +1081,7 @@ export function createGBrainContextEngine(ctx: {const pg = await getDirectPostgresEngine(cfg);if (!pg) return { status: 'banked', reason: 'no_engine' };const sweep = await import('./sweep.ts');- const fullPath = `${dir}/${segs.segmentFileName(sessionId, w.hash)}`;+ const fullPath = `${dir}/${segName(w.hash)}`;const claimPath = fullPath + sweep.CORPUS_CLAIM_SUFFIX;if (!(await sweep.acquireCorpusClaim(claimPath))) return { status: 'banked', reason: 'claimed_elsewhere' };try {@@ -1092,8 +1099,10 @@ export function createGBrainContextEngine(ctx: {if (!(await extractionAvailableForEngine(pg))) return { status: 'banked', reason: 'keyless' };const { isFactsExtractionEnabled } = await import('./facts/extract.ts');if (!(await isFactsExtractionEnabled(pg))) return { status: 'banked', reason: 'extraction_disabled' };- const { resolveSourceId } = await import('./source-resolver.ts');- const sourceId = await resolveSourceId(pg, null, workspaceDir);+ // #6268: the segment's stamp, or (unresolved) the brain's chain for this workspace, frozen into the session record.+ const fileSource = await (await import('./context/corpus-source.ts')).resolveCorpusFileSource(pg, root, segName(w.hash), 'spool');+ if (!fileSource.ok) return { status: 'banked', reason: fileSource.reason };+ const sourceId = fileSource.sourceId;if (deadlineHit()) return { status: 'banked', reason: 'deadline' };const { runFactsPipeline } = await import('./facts/backstop.ts');const abort = new AbortController();@@ -1154,6 +1163,13 @@ export function createGBrainContextEngine(ctx: {}}+ /** #6268: the session's frozen corpus source, or undefined while unresolved / unknown. */+ async function sessionSourceFor(cfg: { dream?: { synthesize?: Record<string, unknown> } } | null, sessionId: string): Promise<string | undefined> {+ const { corpusSpoolDir } = await import('./context/corpus-segments.ts');+ const { readSessionSource } = await import('./context/corpus-source.ts');+ return readSessionSource(corpusSpoolDir(await engineCorpusDir(cfg)), sessionId)?.source_id ?? undefined;+ }+/** Corpus dir from FILE config (hook.ts parity — no engine required). */async function engineCorpusDir(cfg: { dream?: { synthesize?: Record<string, unknown> } } | null): Promise<string> {const configured = cfg?.dream?.synthesize?.session_corpus_dir;diff --git a/src/core/context/checkpoint-harvest.ts b/src/core/context/checkpoint-harvest.tsindex ced6058b0f..8f46d9715d 100644--- a/src/core/context/checkpoint-harvest.ts+++ b/src/core/context/checkpoint-harvest.ts@@ -36,7 +36,7 @@ import type { BrainEngine } from '../engine.ts';import type { CapabilityReport } from '../capability.ts';import { acquireCorpusClaim, CORPUS_CLAIM_SUFFIX, CORPUS_INGESTED_SUFFIX } from '../sweep.ts';import { appendCheckpointManifest } from './session-state.ts';-import { corpusFileSessionId, corpusTextForExtraction, readSegmentLedger, selfCaptureSidecarJson, HARVEST_RECEIPT_SUFFIX } from './corpus-segments.ts';+import { corpusFileSessionId, corpusTextForExtraction, parseSegmentFileName, readSegmentLedger, selfCaptureSidecarJson, HARVEST_RECEIPT_SUFFIX } from './corpus-segments.ts';import { corpusFileStat, readCorpusProgress, runCorpusWindows } from './corpus-windows.ts';import { isClaudeCliSelfSessionId } from '../ai/providers/claude-cli-scratch.ts';import { writeHeartbeat } from './hook-heartbeat.ts';@@ -60,7 +60,10 @@ export { HARVEST_RECEIPT_SUFFIX };export interface HarvestJob {engine: BrainEngine;+ /** #6268: the file's resolved source (its stamp or its session's frozen record), never a serve default. */sourceId: string;+ /** #6268: `sources.incarnation` the source resolved to; binds the receipt and window progress. */+ sourceIncarnation?: string;/** Harness session id — manifest lane + fact provenance. */sessionId: string;/** Absolute corpus dir (resolved by the CALLER the serve way). */@@ -89,6 +92,9 @@ interface HarvestReceipt {seg: string;links: string[];ts: string;+ /** #6268: the source + incarnation the links were extracted into; a replay under another is refused. */+ source_id?: string;+ source_incarnation?: string;}const queue: HarvestJob[] = [];@@ -337,10 +343,9 @@ function logFirstHarvestError(job: HarvestJob, reason: string, e: unknown): void+ '(logged once per serve run; later failures with this reason are counted in the hooks heartbeat only)');}-/** `<sessionId>.seg-<hash12>.txt` → hash12 ('' when the name has no hash part). */+/** A segment basename's content hash ('' when the name is not a segment). */function segHashFromName(file: string): string {- const m = /\.seg-([0-9a-f]+)\.txt$/.exec(file);- return m ? m[1] : '';+ return parseSegmentFileName(file)?.hash ?? '';}async function runOne(job: HarvestJob): Promise<{@@ -380,6 +385,10 @@ async function runOne(job: HarvestJob): Promise<{// Receipt retry path (codex round 2): extraction already happened; the// manifest publish failed transiently. Re-publish WITHOUT re-extracting.let receipt = await readReceipt(receiptPath);+ if (receipt?.source_id !== undefined && (receipt.source_id !== job.sourceId+ || (job.sourceIncarnation !== undefined && receipt.source_incarnation !== job.sourceIncarnation))) {+ return { outcome: 'degraded', reason: 'receipt_source_mismatch' };+ }let counts: { inserted: number; duplicate: number } | null = null;// #5887: the harvest extracts window 1 only; when more remains, `.progress`// stands in for `.ingested` and the sweep finishes the tail.@@ -421,6 +430,7 @@ async function runOne(job: HarvestJob): Promise<{// Paste stripping happens per turn inside the window planner (#5812).run = await runCorpusWindows({full, raw, fileStat, maxWindows: 1, overBudget: () => false, signal: abort.signal,+ ...(job.sourceIncarnation ? { source: { id: job.sourceId, incarnation: job.sourceIncarnation } } : {}),extract: (text) => runFactsPipeline(text, {engine: job.engine,sourceId: job.sourceId,@@ -441,6 +451,7 @@ async function runOne(job: HarvestJob): Promise<{// no .ingested, no progress) and releases the claim — fully retryable.if (abort.signal.aborted || run.status === 'aborted') return { outcome: 'degraded', reason: 'aborted' };if (run.status === 'contended') return { outcome: 'degraded', reason: 'claimed_elsewhere' };+ if (run.status === 'source_changed') return { outcome: 'degraded', reason: 'corpus_source_changed' };windowsPending = run.status !== 'complete';const r = run.result;@@ -450,6 +461,8 @@ async function runOne(job: HarvestJob): Promise<{seg: segHashFromName(job.file),links: r.entity_slugs,ts: new Date().toISOString(),+ source_id: job.sourceId,+ ...(job.sourceIncarnation ? { source_incarnation: job.sourceIncarnation } : {}),};await writeFile(receiptPath, JSON.stringify(receipt) + '\n', { mode: 0o600 });}diff --git a/src/core/context/corpus-segments.ts b/src/core/context/corpus-segments.tsindex 29639ee1fa..545d0c4775 100644--- a/src/core/context/corpus-segments.ts+++ b/src/core/context/corpus-segments.ts@@ -30,7 +30,7 @@*/import { createHash } from 'node:crypto';-import { closeSync, existsSync, openSync, readdirSync, readFileSync, readSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';+import { closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';import { basename, join } from 'node:path';import type { WindowTurn } from './entity-salience.ts';import { toCorpusText, type ToolCallRecord } from '../transcripts/claude-code-jsonl.ts';@@ -69,8 +69,55 @@ export function segmentHash(text: string): string {return createHash('sha256').update(text, 'utf8').digest('hex').slice(0, SEGMENT_HASH_LEN);}-export function segmentFileName(sessionId: string, hash: string): string {- return `${safeIdComponent(sessionId)}.seg-${hash.replace(/[^0-9a-f]/g, '')}.txt`;+/**+ * #6268 (R14): the spool subdirectory every source-stamped corpus file lives+ * in. A pre-stamp sweeper reads only the corpus dir's top level and files any+ * non-writeback `.txt` there under its own pass source, so a stamped file it+ * could see would be misfiled; inside this subdirectory it sees nothing.+ * Top-level files are the legacy (unstamped) corpus. No leading dot: dream+ * synthesis walks into it exactly as it walked the top level.+ */+export const CORPUS_SPOOL_SUBDIR = 'sourced';++/**+ * The stamp of a file whose writer could not resolve the session's source.+ * Underscores are never valid in a source id (`SOURCE_ID_RE`), so no real+ * source can be named this.+ */+export const CORPUS_UNRESOLVED_STAMP = '_unresolved';++const SOURCE_STAMP_RE = /^[a-z0-9](?:[a-z0-9-]{0,30}[a-z0-9])?$/;++/** A valid corpus source stamp: a source id or the unresolved marker. */+export function isCorpusSourceStamp(stamp: unknown): stamp is string {+ return typeof stamp === 'string' && (stamp === CORPUS_UNRESOLVED_STAMP || SOURCE_STAMP_RE.test(stamp));+}++export function corpusSpoolDir(corpusDir: string): string {+ return join(corpusDir, CORPUS_SPOOL_SUBDIR);+}++/** The spool dir, created 0700. Throws on fs failure. */+export function ensureCorpusSpoolDir(corpusDir: string): string {+ const dir = corpusSpoolDir(corpusDir);+ mkdirSync(dir, { recursive: true, mode: 0o700 });+ return dir;+}++function stampPart(stamp: string | null | undefined): string {+ if (stamp === undefined || stamp === null) return '';+ if (!isCorpusSourceStamp(stamp)) throw new Error(`invalid corpus source stamp ${JSON.stringify(stamp)}`);+ return `.src-${stamp}`;+}++/** `<sessionId>.seg-<hash>[.src-<stamp>].txt`; spool writers always pass the stamp. */+export function segmentFileName(sessionId: string, hash: string, stamp?: string | null): string {+ return `${safeIdComponent(sessionId)}.seg-${hash.replace(/[^0-9a-f]/g, '')}${stampPart(stamp)}.txt`;+}++/** The session-end corpus file: `<sessionId>[.src-<stamp>].txt`. */+export function sessionCorpusFileName(sessionId: string, stamp?: string | null): string {+ return `${safeIdComponent(sessionId)}${stampPart(stamp)}.txt`;}export function ledgerFileName(sessionId: string): string {@@ -86,6 +133,14 @@ export function seatFileName(sessionId: string): string {return `${safeIdComponent(sessionId)}${SEAT_SIDECAR_SUFFIX}`;}+/** #6268: the per-session source record in the spool (context/corpus-source.ts owns its content and lock). */+export const SESSION_SOURCE_SUFFIX = '.source.json';+export const SESSION_SOURCE_LOCK_SUFFIX = '.source.lock';++export function sessionSourceFileName(sessionId: string): string {+ return `${safeIdComponent(sessionId)}${SESSION_SOURCE_SUFFIX}`;+}+/** A seat sidecar written ahead of its corpus file is never reaped inside* this window (the writer renames the corpus file within seconds). */const SEAT_ORPHAN_GRACE_MS = 10 * 60 * 1000;@@ -112,9 +167,26 @@ export const CORPUS_PROGRESS_LOCK_SUFFIX = '.progress.lock';*/export function parseSegmentFileName(name: string,-): { sessionId: string; hash: string } | null {- const m = /^(.+)\.seg-([0-9a-f]{12,64})\.txt$/.exec(name);- return m ? { sessionId: m[1], hash: m[2] } : null;+): { sessionId: string; hash: string; stamp?: string } | null {+ const m = /^(.+)\.seg-([0-9a-f]{12,64})(?:\.src-([a-z0-9_-]{1,40}))?\.txt$/.exec(name);+ if (!m) return null;+ return { sessionId: m[1], hash: m[2], ...(m[3] && isCorpusSourceStamp(m[3]) ? { stamp: m[3] } : {}) };+}++/** `{sessionId, stamp}` of a stamped session-end file; null for any other name. */+export function parseSessionCorpusFileName(name: string): { sessionId: string; stamp: string } | null {+ if (parseSegmentFileName(name) || parseWbFileName(name)) return null;+ const m = /^(.+)\.src-([a-z0-9_-]{1,40})\.txt$/.exec(name);+ return m && isCorpusSourceStamp(m[2]) ? { sessionId: m[1], stamp: m[2] } : null;+}++/**+ * The source stamp a corpus file NAME carries (any kind), or null. A spool+ * file without one is malformed; at the top level only the legacy+ * writeback grammar ever carried a stamp.+ */+export function corpusFileStamp(name: string): string | null {+ return parseSegmentFileName(name)?.stamp ?? parseWbFileName(name)?.sourceId ?? parseSessionCorpusFileName(name)?.stamp ?? null;}/**@@ -212,9 +284,10 @@ export function writeSegment(dir: string,sessionId: string,text: string,+ stamp?: string | null,): { file: string; hash: string; existed: boolean } {const hash = segmentHash(text);- const file = join(dir, segmentFileName(sessionId, hash));+ const file = join(dir, segmentFileName(sessionId, hash, stamp));if (existsSync(file)) return { file, hash, existed: true };const tmp = `${file}.tmp-${process.pid}`;writeFileSync(tmp, text, { mode: 0o600 });@@ -323,21 +396,21 @@ export function readOpenclawBoundaryTail(/*** Ambient-writeback turn files (WP4) — the Stop-hook backstop's siblings of- * checkpoint segments. `<sessionId>.wb-<hash24>[.src-<sourceId>].txt` where+ * checkpoint segments. `<sessionId>.wb-<hash24>[.src-<stamp>].txt` where* the hash is the GATE's normalized-turn hash (turn identity, computed in* writeback-gate.ts) — a re-fired Stop hook for the same turn re-derives the* same name and short-circuits (requirement 9's deterministic idempotency,- * embedding-free). The optional `.src-` segment banks the session's- * GBRAIN_SOURCE so the SWEEP fallback files the turn into the same source- * the prompt-time IPC lane would have (source-isolation invariant —- * adversarial review, this wave); omitted for the default source, keeping- * default-flow names byte-identical. They end `.txt` ON PURPOSE: the sweep's+ * embedding-free). The `.src-` segment banks the session's source so the+ * SWEEP fallback files the turn into the same source the prompt-time IPC+ * lane would have (source-isolation invariant). #6268: spool writers stamp+ * every file, `default` included; a top-level name without one is a legacy+ * file written before stamps (old writers omitted `default` and an unset+ * GBRAIN_SOURCE alike, so it proves nothing). They end `.txt` ON PURPOSE: the sweep's* corpus pass is the free backstop when serve/IPC is down (the sweep applies* the writeback gate before extracting them — OV2-11).*/-export function wbFileName(sessionId: string, hash24: string, sourceId?: string | null): string {- const src = sourceId && sourceId !== 'default' ? `.src-${safeIdComponent(sourceId)}` : '';- return `${safeIdComponent(sessionId)}.wb-${hash24.replace(/[^0-9a-f]/g, '')}${src}.txt`;+export function wbFileName(sessionId: string, hash24: string, stamp?: string | null): string {+ return `${safeIdComponent(sessionId)}.wb-${hash24.replace(/[^0-9a-f]/g, '')}${stampPart(stamp)}.txt`;}/** `{sessionId, hash, sourceId?}` when `name` is a writeback turn file, else@@ -354,7 +427,8 @@ export function parseWbFileName(name: string): { sessionId: string; hash: string* classify gbrain's own claude-cli sessions (#5413) across every form.*/export function corpusFileSessionId(name: string): string {- return parseSegmentFileName(name)?.sessionId ?? parseWbFileName(name)?.sessionId ?? name.replace(/\.txt$/, '');+ return parseSegmentFileName(name)?.sessionId ?? parseWbFileName(name)?.sessionId+ ?? parseSessionCorpusFileName(name)?.sessionId ?? name.replace(/\.txt$/, '');}/**@@ -394,10 +468,10 @@ export async function bankWritebackTurn(sessionId: string,normalizedTurn: string,hash24: string,- sourceId?: string | null,+ stamp?: string | null,): Promise<{ status: 'wb_banked' | 'wb_dup' | 'wb_scan_unavailable' | 'wb_empty' | `wb_${string}`; flushCorpusFile?: string }> {try {- const name = wbFileName(sessionId, hash24, sourceId);+ const name = wbFileName(sessionId, hash24, stamp);const file = join(dir, name);if (existsSync(file) || existsSync(file + '.ingested')) return { status: 'wb_dup', flushCorpusFile: name };let redacted: string;@@ -436,6 +510,8 @@ export async function bankCompactSegment(remainingMs: () => number; minScanMs: number; minWriteMs: number; maxTurns?: number;/** #6091: runs before the segment is renamed into place (capture-time consent record); a throw banks nothing. */beforeWrite?: (file: string, text: string) => void;+ /** #6268: the session's source stamp (spool writers always pass one). */+ stamp?: string | null;},): Promise<{ segment: string; flushCorpusFile?: string; hash?: string; ordinal?: number }> {try {@@ -448,12 +524,12 @@ export async function bankCompactSegment(if (!rendered) return { segment: 'scan_unavailable' };if (!rendered.text.trim()) return { segment: 'empty_window' };if (opts.remainingMs() < opts.minWriteMs) return { segment: 'deadline_write' };- opts.beforeWrite?.(join(dir, segmentFileName(sessionId, segmentHash(rendered.text))), rendered.text);- const w = writeSegment(dir, sessionId, rendered.text);+ opts.beforeWrite?.(join(dir, segmentFileName(sessionId, segmentHash(rendered.text), opts.stamp)), rendered.text);+ const w = writeSegment(dir, sessionId, rendered.text, opts.stamp);const ordinal = appendSegmentLedger(dir, sessionId, w.hash);return {segment: w.existed ? 'segment_dup' : 'segment_banked',- flushCorpusFile: segmentFileName(sessionId, w.hash),+ flushCorpusFile: segmentFileName(sessionId, w.hash, opts.stamp),hash: w.hash,ordinal,};@@ -583,12 +659,17 @@ export function gcCorpusArtifacts(for (const name of names) {const p = join(dir, name);try {- if (name.endsWith(SEAT_SIDECAR_SUFFIX)) {- if (!liveSessions.has(name.slice(0, -SEAT_SIDECAR_SUFFIX.length)) && statSync(p).mtimeMs < Date.now() - SEAT_ORPHAN_GRACE_MS) {+ const perSession = [SEAT_SIDECAR_SUFFIX, SESSION_SOURCE_SUFFIX].find((suffix) => name.endsWith(suffix));+ if (perSession) {+ if (!liveSessions.has(name.slice(0, -perSession.length)) && statSync(p).mtimeMs < Date.now() - SEAT_ORPHAN_GRACE_MS) {rmSync(p, { force: true });}continue;}+ if (name.endsWith(SESSION_SOURCE_LOCK_SUFFIX)) {+ if (statSync(p).mtimeMs < Date.now() - SEAT_ORPHAN_GRACE_MS) rmSync(p, { force: true });+ continue;+ }const offAt = name.endsWith('.json') ? name.lastIndexOf(CAPTURE_OFF_INFIX) : -1;if (offAt > 0) {// Written BEFORE its corpus file lands: only an orphan past the grace period is reaped (every brain's record alike).diff --git a/src/core/context/corpus-source.ts b/src/core/context/corpus-source.tsnew file mode 100644index 0000000000..90a553cb36--- /dev/null+++ b/src/core/context/corpus-source.ts@@ -0,0 +1,344 @@+/**+ * corpus-source.ts — #6268 (W13 P3.4, R14): the one source a captured+ * session's corpus files belong to.+ *+ * Every corpus writer (the engine-free hook, the OpenClaw context engine)+ * stamps the session's source into each file NAME and writes it into the+ * spool subdirectory (`corpus-segments.ts` CORPUS_SPOOL_SUBDIR). The source+ * is resolved ONCE per session and frozen in `<sessionId>.source.json` beside+ * the session's spool files: later captures of the same session reuse it even+ * when the environment, dotfile or brain config changed in between.+ *+ * Resolution order at write time (engine-free): GBRAIN_SOURCE, then the+ * `.gbrain-source` dotfile walked up from the session's cwd. When neither+ * fires, the record stays unresolved (it keeps the cwd) and files are stamped+ * CORPUS_UNRESOLVED_STAMP; a lane that holds the brain may freeze it later:+ * the serve's own bound source when the hook reaches it over IPC (what an+ * unpinned hook's IPC requests already resolve to), or, at sweep time, the+ * brain's resolution chain for the recorded cwd (tiers 4-6, the client-side+ * tiers already ran). A frozen source is never changed except by nobody: the+ * operator mapping fills only unresolved records.+ *+ * Extraction side (`resolveCorpusFileSource`, engine-holding callers): a+ * spool file uses its stamp (unresolved ⇒ the frozen record); a top-level+ * legacy file is held unless durable evidence names its source (a legacy+ * writeback stamp, a frozen spool record for the same session, or a brain with+ * exactly one source). The source must exist and be active, and the first+ * engine resolution binds the source's incarnation to the session: a source+ * deleted and recreated under the same id holds the session's files.+ *+ * ENGINE-FREE at module load: the engine-side helper takes the engine as an+ * argument and lazy-imports the resolver.+ */++import { mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import type { BrainEngine } from '../engine.ts';+import {+ CORPUS_UNRESOLVED_STAMP,+ SESSION_SOURCE_LOCK_SUFFIX,+ SESSION_SOURCE_SUFFIX,+ corpusFileSessionId,+ corpusFileStamp,+ corpusSpoolDir,+ isCorpusSourceStamp,+ parseWbFileName,+ sessionSourceFileName,+} from './corpus-segments.ts';++export type SessionSourceTier = 'env' | 'dotfile' | 'serve' | 'engine' | 'operator';++export interface SessionSourceRecord {+ version: 1;+ session_id: string;+ /** Null while unresolved. */+ source_id: string | null;+ tier: SessionSourceTier | null;+ /** The session's working directory at first capture (the deferred resolver's input). */+ cwd: string | null;+ harness: string;+ created_at: string;+ resolved_at: string | null;+ /** `sources.incarnation` bound at the first engine-side resolution. */+ source_incarnation: string | null;+}++const LOCK_ATTEMPTS = 40;+const LOCK_RETRY_MS = 25;+const LOCK_STALE_MS = 30_000;++function recordPath(spoolDir: string, sessionId: string): string {+ return join(spoolDir, sessionSourceFileName(sessionId));+}++function isValidRealSource(id: unknown): id is string {+ return isCorpusSourceStamp(id) && id !== CORPUS_UNRESOLVED_STAMP;+}++function parseRecord(raw: string): SessionSourceRecord | null {+ let r: SessionSourceRecord;+ try { r = JSON.parse(raw) as SessionSourceRecord; } catch { return null; }+ if (!r || typeof r !== 'object' || r.version !== 1 || typeof r.session_id !== 'string') return null;+ if (r.source_id !== null && !isValidRealSource(r.source_id)) return null;+ return r;+}++/** The session's record; null when absent or not a valid v1 record (an invalid record is never guessed). */+export function readSessionSource(spoolDir: string, sessionId: string): SessionSourceRecord | null {+ try {+ return parseRecord(readFileSync(recordPath(spoolDir, sessionId), 'utf8'));+ } catch {+ return null;+ }+}++function sleepSync(ms: number): void {+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);+}++/**+ * Compare-and-set under an O_EXCL lock: `next` sees the current record and+ * returns its replacement, or null to keep it. Returns the record that stands+ * afterwards (null when none exists or the lock stayed busy). Never throws.+ */+function updateSessionSource(+ spoolDir: string,+ sessionId: string,+ next: (cur: SessionSourceRecord | null) => SessionSourceRecord | null,+): SessionSourceRecord | null {+ const path = recordPath(spoolDir, sessionId);+ const lock = join(spoolDir, sessionSourceFileName(sessionId).slice(0, -SESSION_SOURCE_SUFFIX.length) + SESSION_SOURCE_LOCK_SUFFIX);+ try { mkdirSync(spoolDir, { recursive: true, mode: 0o700 }); } catch { return null; }+ let locked = false;+ for (let i = 0; i < LOCK_ATTEMPTS && !locked; i++) {+ try {+ writeFileSync(lock, `${process.pid}\n`, { flag: 'wx', mode: 0o600 });+ locked = true;+ } catch (e) {+ if ((e as NodeJS.ErrnoException).code !== 'EEXIST') return readSessionSource(spoolDir, sessionId);+ try {+ if (Date.now() - statSync(lock).mtimeMs > LOCK_STALE_MS) rmSync(lock, { force: true });+ else sleepSync(LOCK_RETRY_MS);+ } catch { /* lock vanished: retry */ }+ }+ }+ if (!locked) return readSessionSource(spoolDir, sessionId);+ try {+ const cur = readSessionSource(spoolDir, sessionId);+ const proposed = next(cur);+ if (!proposed) return cur;+ const tmp = `${path}.tmp-${process.pid}`;+ writeFileSync(tmp, JSON.stringify(proposed) + '\n', { mode: 0o600 });+ renameSync(tmp, path);+ return proposed;+ } catch {+ return readSessionSource(spoolDir, sessionId);+ } finally {+ rmSync(lock, { force: true });+ }+}++function freshRecord(sessionId: string, cwd: string | null, harness: string): SessionSourceRecord {+ return {+ version: 1, session_id: sessionId, source_id: null, tier: null, cwd, harness,+ created_at: new Date().toISOString(), resolved_at: null, source_incarnation: null,+ };+}++/** The engine-free tiers (GBRAIN_SOURCE, then the cwd's dotfile walk); null when neither names a real source. */+async function engineFreeSessionSource(cwd: string | null): Promise<{ sourceId: string; tier: SessionSourceTier } | null> {+ const { resolveSourceIdEngineFree } = await import('../source-resolver.ts');+ let id: string | null;+ try {+ id = resolveSourceIdEngineFree(null, cwd ?? process.cwd());+ } catch {+ return null;+ }+ if (!isValidRealSource(id)) return null;+ const env = process.env.GBRAIN_SOURCE;+ return { sourceId: id, tier: env && env === id ? 'env' : 'dotfile' };+}++/**+ * The session's stamp for its next corpus file, freezing the source on first+ * use. An existing record wins over a fresh resolution (frozen at session+ * start). Never throws: any failure stamps the file unresolved.+ */+export async function openSessionSource(+ corpusDir: string,+ sessionId: string,+ opts: { cwd: string | null; harness: string },+): Promise<{ stamp: string; record: SessionSourceRecord | null }> {+ try {+ const spool = corpusSpoolDir(corpusDir);+ const existing = readSessionSource(spool, sessionId);+ if (existing) return { stamp: existing.source_id ?? CORPUS_UNRESOLVED_STAMP, record: existing };+ const resolved = await engineFreeSessionSource(opts.cwd);+ const record = updateSessionSource(spool, sessionId, (cur) => cur ? null : {+ ...freshRecord(sessionId, opts.cwd, opts.harness),+ ...(resolved ? { source_id: resolved.sourceId, tier: resolved.tier, resolved_at: new Date().toISOString() } : {}),+ });+ return { stamp: record?.source_id ?? CORPUS_UNRESOLVED_STAMP, record };+ } catch {+ return { stamp: CORPUS_UNRESOLVED_STAMP, record: null };+ }+}++/**+ * Freeze an UNRESOLVED (or missing) record to `sourceId`. A record that+ * already names a source keeps it. Returns the record that stands.+ */+export function freezeSessionSource(+ corpusDir: string,+ sessionId: string,+ sourceId: string,+ tier: SessionSourceTier,+ defaults: { cwd?: string | null; harness?: string; onlyExisting?: boolean } = {},+): SessionSourceRecord | null {+ const spool = corpusSpoolDir(corpusDir);+ if (!isValidRealSource(sourceId)) return readSessionSource(spool, sessionId);+ if (defaults.onlyExisting) {+ const existing = readSessionSource(spool, sessionId);+ if (!existing || existing.source_id) return existing;+ }+ return updateSessionSource(spool, sessionId, (cur) => {+ if (cur?.source_id || (defaults.onlyExisting && !cur)) return null;+ return { ...(cur ?? freshRecord(sessionId, defaults.cwd ?? null, defaults.harness ?? 'unknown')), source_id: sourceId, tier, resolved_at: new Date().toISOString() };+ });+}++/** Bind the source incarnation once; a record bound to another incarnation stays as it is. */+function bindIncarnation(spoolDir: string, sessionId: string, sourceId: string, incarnation: string): SessionSourceRecord | null {+ return updateSessionSource(spoolDir, sessionId, (cur) =>+ cur && cur.source_id === sourceId && cur.source_incarnation === null ? { ...cur, source_incarnation: incarnation } : null);+}++export type CorpusFileLocation = 'spool' | 'legacy';++export type CorpusSourceHold =+ | 'corpus_source_unresolved'+ | 'corpus_legacy_unstamped'+ | 'corpus_stamp_missing'+ | 'corpus_source_missing'+ | 'corpus_source_archived'+ | 'corpus_source_incarnation_changed';++export type CorpusFileSource =+ | { ok: true; sourceId: string; incarnation: string; via: 'stamp' | 'session_record' | 'sole_source' }+ | { ok: false; reason: CorpusSourceHold };++/**+ * The source a corpus file's facts, links and manifest belong to, or the+ * typed reason it is held (no sidecar: the file waits for evidence or an+ * operator mapping). Never the caller's pass source.+ */+export async function resolveCorpusFileSource(+ engine: BrainEngine,+ corpusDir: string,+ name: string,+ location: CorpusFileLocation,+): Promise<CorpusFileSource> {+ const spool = corpusSpoolDir(corpusDir);+ const sessionId = corpusFileSessionId(name);+ const stamp = corpusFileStamp(name);+ let record = readSessionSource(spool, sessionId);+ let candidate: string | null = null;+ let via: 'stamp' | 'session_record' | 'sole_source' = 'stamp';++ if (location === 'spool') {+ if (!stamp) return { ok: false, reason: 'corpus_stamp_missing' };+ if (stamp !== CORPUS_UNRESOLVED_STAMP) candidate = stamp;+ else {+ via = 'session_record';+ if (!record?.source_id && record?.cwd) {+ const { resolveSourceId } = await import('../source-resolver.ts');+ const deferred = await resolveSourceId(engine, null, record.cwd, { skipLocalSignals: true }).catch(() => null);+ if (deferred) record = freezeSessionSource(corpusDir, sessionId, deferred, 'engine');+ }+ candidate = record?.source_id ?? null;+ if (!candidate) return { ok: false, reason: 'corpus_source_unresolved' };+ }+ } else {+ const wbStamp = parseWbFileName(name)?.sourceId;+ if (wbStamp && isValidRealSource(wbStamp)) candidate = wbStamp;+ else if (record?.source_id) {+ candidate = record.source_id;+ via = 'session_record';+ } else {+ const ids = await engine.executeRaw<{ id: string }>('SELECT id FROM sources ORDER BY id LIMIT 2');+ if (ids.length !== 1) return { ok: false, reason: 'corpus_legacy_unstamped' };+ candidate = ids[0].id;+ via = 'sole_source';+ }+ }++ const rows = await engine.executeRaw<{ incarnation: string; archived: boolean }>(+ 'SELECT incarnation::text AS incarnation, archived FROM sources WHERE id = $1', [candidate]);+ if (!rows.length) return { ok: false, reason: 'corpus_source_missing' };+ if (rows[0].archived) return { ok: false, reason: 'corpus_source_archived' };+ const incarnation = rows[0].incarnation;+ if (record?.source_id === candidate) {+ const bound = record.source_incarnation ?? bindIncarnation(spool, sessionId, candidate, incarnation)?.source_incarnation ?? incarnation;+ if (bound !== incarnation) return { ok: false, reason: 'corpus_source_incarnation_changed' };+ }+ return { ok: true, sourceId: candidate, incarnation, via };+}++export interface CorpusSourceHolds {+ /** Top-level files with no `.ingested` sidecar and no evidence of their source. */+ legacy_unstamped: number;+ /** Spool files stamped unresolved whose session record still names no source. */+ unresolved: number;+ /** Session ids among both. */+ sessions: string[];+}++/**+ * Doctor/CLI view of the held files that only an operator mapping can+ * release (a multi-source brain's legacy files and unresolved sessions).+ * Engine-free; `soleSource` is the caller's `SELECT id FROM sources` answer.+ */+export function listCorpusSourceHolds(corpusDir: string, soleSource: boolean): CorpusSourceHolds {+ const out: CorpusSourceHolds = { legacy_unstamped: 0, unresolved: 0, sessions: [] };+ const spool = corpusSpoolDir(corpusDir);+ const sessions = new Set<string>();+ const scan = (dir: string, location: CorpusFileLocation) => {+ let names: string[];+ try { names = readdirSync(dir); } catch { return; }+ const present = new Set(names);+ for (const name of names) {+ if (!name.endsWith('.txt') || present.has(name + '.ingested')) continue;+ const sid = corpusFileSessionId(name);+ if (readSessionSource(spool, sid)?.source_id) continue;+ if (location === 'spool') {+ if (corpusFileStamp(name) !== CORPUS_UNRESOLVED_STAMP) continue;+ out.unresolved++;+ } else {+ const wb = parseWbFileName(name)?.sourceId;+ if ((wb && isValidRealSource(wb)) || soleSource) continue;+ out.legacy_unstamped++;+ }+ sessions.add(sid);+ }+ };+ scan(spool, 'spool');+ scan(corpusDir, 'legacy');+ out.sessions = [...sessions].sort();+ return out;+}++/**+ * Operator mapping (`gbrain sweep --assign-corpus`): freeze every held+ * session (or one) to `sourceId`. Frozen records are never changed.+ * Returns the sessions that now name `sourceId` because of this call.+ */+export function assignCorpusSessions(corpusDir: string, sessionIds: string[], sourceId: string): string[] {+ const assigned: string[] = [];+ for (const sid of sessionIds) {+ const before = readSessionSource(corpusSpoolDir(corpusDir), sid);+ if (before?.source_id) continue;+ const after = freezeSessionSource(corpusDir, sid, sourceId, 'operator');+ if (after?.source_id === sourceId && after.tier === 'operator') assigned.push(sid);+ }+ return assigned;+}diff --git a/src/core/context/corpus-windows.ts b/src/core/context/corpus-windows.tsindex e19eba96a7..0a9c225be2 100644--- a/src/core/context/corpus-windows.ts+++ b/src/core/context/corpus-windows.ts@@ -80,11 +80,22 @@ export interface CorpusProgress {skipped_reason?: string;/** #6091: hashes of turns captured or retired under writeback off; never extracted wherever they sit. */retired_turns?: string[];+ /**+ * #6268: the source (and its incarnation) this file's windows were+ * extracted into, bound by the first window run. A resume under another+ * source or a recreated source is refused (`source_changed`).+ */+ source?: CorpusProgressSource | null;lease: { owner: string; at: number } | null;}+export interface CorpusProgressSource {+ id: string;+ incarnation: string;+}+export interface CorpusWindowRun {- status: 'complete' | 'partial' | 'aborted' | 'contended' | 'changed';+ status: 'complete' | 'partial' | 'aborted' | 'contended' | 'changed' | 'source_changed';windowsDone: number;windowsRemaining: number;/** Cumulative across every sweep that worked on this file. */@@ -213,6 +224,7 @@ function parseProgress(text: string): CorpusProgress | null {&& Number.isSafeInteger(p.continuation.stripped_offset))) return null;if (p.finished !== null && !isFileStat(p.finished)) return null;if (!p.totals || !Array.isArray(p.entity_slugs)) return null;+ if (p.source != null && !(typeof p.source.id === 'string' && typeof p.source.incarnation === 'string')) return null;return p;}@@ -435,19 +447,26 @@ export async function runCorpusWindows(opts: {extract: (text: string) => Promise<PipelineResult>;overBudget: () => boolean;signal: AbortSignal;+ /** #6268: the file's resolved source; binds on the first run, refuses a resume under another. */+ source?: CorpusProgressSource;}): Promise<CorpusWindowRun> {- const { full, fileStat, signal } = opts;+ const { full, fileStat, signal, source } = opts;const owner = `${process.pid}:${randomUUID()}`;const now = Date.now();+ let sourceChanged = false;let state = await updateProgress(full, (cur) => {+ if (source && cur?.source && (cur.source.id !== source.id || cur.source.incarnation !== source.incarnation)) {+ sourceChanged = true;+ return null;+ }if (cur?.lease && cur.lease.owner !== owner && now - cur.lease.at < CORPUS_PROGRESS_LEASE_STALE_MS) return null;- return { ...(cur ?? freshProgress()), lease: { owner, at: now } };+ return { ...(cur ?? freshProgress()), ...(source && !cur?.source ? { source } : {}), lease: { owner, at: now } };});const turns = parseCorpusTurns(opts.raw);if (!state) {const cur = await readCorpusProgress(full).catch(() => null);const remaining = planCorpusWindows(turns, resumePoint(turns, cur), MAX_TURN_TEXT_CHARS, retiredTurns(cur)).filter((w) => w.text).length;- return { status: 'contended', windowsDone: 0, windowsRemaining: remaining, result: resultOf(cur ?? { ...freshProgress(), generation: 0 }) };+ return { status: sourceChanged ? 'source_changed' : 'contended', windowsDone: 0, windowsRemaining: remaining, result: resultOf(cur ?? { ...freshProgress(), generation: 0 }) };}let cursor = resumePoint(turns, state);diff --git a/src/core/cycle/transcript-discovery.ts b/src/core/cycle/transcript-discovery.tsindex d3594a5dbd..f41af7bb37 100644--- a/src/core/cycle/transcript-discovery.ts+++ b/src/core/cycle/transcript-discovery.ts@@ -16,7 +16,7 @@ import { join, basename, dirname, sep } from 'node:path';import { createHash } from 'node:crypto';import { pruneDir } from '../sync.ts';import { realpathOrResolve, resolvedPrefixContained } from '../path-confine.ts';-import { corpusFileSessionId } from '../context/corpus-segments.ts';+import { CORPUS_SPOOL_SUBDIR, corpusFileSessionId } from '../context/corpus-segments.ts';import { withoutOffPeriodTurns } from '../context/capture-consent.ts';import { readSeatSidecar } from '../context/seat.ts';import { claudeCliSelfSessionIds } from '../ai/providers/claude-cli-scratch.ts';@@ -307,7 +307,7 @@ export function discoverTranscripts(opts: DiscoverOpts): DiscoveredTranscript[]for (const dir of dirs) {for (const filePath of listTextFiles(dir)) {const ext = filePath.endsWith('.md') ? '.md' : '.txt';- const baseName = basename(filePath, ext);+ const baseName = transcriptBaseName(filePath, ext);const dateMatch = DATE_RE.exec(baseName);const inferredDate = dateMatch ? dateMatch[1] : null;if (!isInDateRange(inferredDate, opts)) continue;@@ -387,7 +387,7 @@ export function readSingleTranscript(if (content.length < minChars) return null;if (isDreamOutput(content, bypass)) {const ext = filePath.endsWith('.md') ? '.md' : '.txt';- const baseName = basename(filePath, ext);+ const baseName = transcriptBaseName(filePath, ext);process.stderr.write(`[dream] readSingleTranscript skipped ${baseName}: dream_generated marker (self-consumption guard)\n`);return null;}@@ -399,7 +399,7 @@ export function readSingleTranscript(return null;}const ext = filePath.endsWith('.md') ? '.md' : '.txt';- const baseName = basename(filePath, ext);+ const baseName = transcriptBaseName(filePath, ext);const dateMatch = DATE_RE.exec(baseName);const seat = transcriptSeat(filePath);return {@@ -412,6 +412,16 @@ export function readSingleTranscript(};}+/**+ * The topic-slug seed of a transcript file. #6268: a spool corpus file's name+ * carries its session's source stamp (`<sid>.src-<id>.txt`); the seed drops+ * it, so a session synthesizes under the same name it had before stamps.+ */+function transcriptBaseName(filePath: string, ext: '.md' | '.txt'): string {+ const base = basename(filePath, ext);+ return ext === '.txt' && basename(dirname(filePath)) === CORPUS_SPOOL_SUBDIR ? base.replace(/\.src-[a-z0-9_-]{1,40}$/, '') : base;+}+/*** #4618: credit each ref to the seat of the transcript it was synthesized* from (the seat sidecar discovery read). The synthesis idempotency key neverdiff --git a/src/core/sweep.ts b/src/core/sweep.tsindex 5d9c398528..c8c4515c5b 100644--- a/src/core/sweep.ts+++ b/src/core/sweep.ts@@ -91,6 +91,7 @@ const CORPUS_WINDOW_SKIP = {contended: 'corpus_in_progress',partial: 'corpus_windows_pending',changed: 'corpus_changed',+ source_changed: 'corpus_source_changed',} as const;export interface SweepOpts {@@ -600,7 +601,7 @@ async function runCorpusIngestPass(log: (msg: string) => void;},): Promise<void> {- const { sourceId, batchLimit, overBudget, signal, report, skip, log } = ctx;+ const { batchLimit, overBudget, signal, report, skip, log } = ctx;// Corpus dir: dream's session corpus (transcripts.ts:66 precedent);// default ~/.gbrain/transcripts/corpus (GBRAIN_HOME-aware via configDir).@@ -610,23 +611,31 @@ async function runCorpusIngestPass(dir = join(configDir(), 'transcripts', 'corpus');}- let entries: string[];- try {- entries = await readdir(dir);- } catch {- return; // no corpus dir = nothing to ingest (not an error)- }-- // ONE readdir feeds both the .txt listing and the sidecar checks (the old- // shape ran two existsSync probes per file on top of the readdir).- const entrySet = new Set(entries);- const txtFiles = entries.filter(n => n.endsWith('.txt')).sort();- if (txtFiles.length === 0) return;-- // #5887: finished files re-enter when changed since their `.progress`.+ // #6268: source-stamped files live in the spool subdirectory (listed+ // first); top-level files are the legacy, unstamped corpus.+ const { CORPUS_SPOOL_SUBDIR, corpusSpoolDir, parseWbFileName, selfCaptureSidecarJson, corpusFileSessionId, corpusTextForExtraction } = await import('./context/corpus-segments.ts');+ const spoolDir = corpusSpoolDir(dir);const windows = await import('./context/corpus-windows.ts');- const { candidates, alreadyIngested } = await windows.selectCorpusCandidates(dir, txtFiles, entrySet, batchLimit, overBudget);- skip('already_ingested', alreadyIngested);+ type Candidate = { base: string; name: string; location: 'spool' | 'legacy'; label: string };+ const candidates: Candidate[] = [];+ for (const [base, location] of [[spoolDir, 'spool'], [dir, 'legacy']] as const) {+ let entries: string[];+ try {+ entries = await readdir(base);+ } catch {+ continue; // no corpus dir = nothing to ingest (not an error)+ }+ // ONE readdir feeds both the .txt listing and the sidecar checks.+ const entrySet = new Set(entries);+ const txtFiles = entries.filter(n => n.endsWith('.txt')).sort();+ if (txtFiles.length === 0) continue;+ // #5887: finished files re-enter when changed since their `.progress`.+ const picked = await windows.selectCorpusCandidates(base, txtFiles, entrySet, batchLimit - candidates.length, overBudget);+ skip('already_ingested', picked.alreadyIngested);+ for (const name of picked.candidates) {+ candidates.push({ base, name, location, label: location === 'spool' ? join(CORPUS_SPOOL_SUBDIR, name) : name });+ }+ }if (candidates.length === 0) return;// #6091: every corpus file answers to the capture gate, resolved once per@@ -639,18 +648,17 @@ async function runCorpusIngestPass(// keyless/kill-switch short-circuits so an operator's OFF retires banked// files even when the brain cannot extract — otherwise they linger eligible// and a later re-enable would extract text the operator already revoked.- const { parseWbFileName, selfCaptureSidecarJson, corpusFileSessionId, corpusTextForExtraction } = await import('./context/corpus-segments.ts');const { applyCaptureGate, captureLaneForFile, resolveCaptureGate } = await import('./context/capture-consent.ts');- const { isValidSourceId } = await import('./source-id.ts');+ const { resolveCorpusFileSource } = await import('./context/corpus-source.ts');const gate = await resolveCaptureGate(engine);const retireCandidatesIfOff = async (): Promise<Set<string>> => {const retired = new Set<string>();- for (const name of candidates) {+ for (const { base, name, label } of candidates) {const decision = gate[captureLaneForFile(name)];if (decision.action !== 'retire') continue;try {- if ((await applyCaptureGate(join(dir, name), decision)).action !== 'retire') continue;- retired.add(name);+ if ((await applyCaptureGate(join(base, name), decision)).action !== 'retire') continue;+ retired.add(label);skip('writeback_off');} catch { /* per-file best effort — the next sweep retries */ }}@@ -690,8 +698,8 @@ async function runCorpusIngestPass(skip('corpus_window_cap', candidates.length - i);break;}- const name = candidates[i];- const full = join(dir, name);+ const { base, name, location, label } = candidates[i];+ const full = join(base, name);// Atomic claim BEFORE any spend — the losing sweep skips, never re-pays.const claimPath = full + CORPUS_CLAIM_SUFFIX;@@ -746,17 +754,18 @@ async function runCorpusIngestPass(continue;}- // Source fidelity (adversarial review, this wave): wb files bank the- // session's GBRAIN_SOURCE in their NAME, so the sweep fallback files- // the turn into the SAME source the prompt-time IPC lane would have —- // never the pass's source. Validated before use (source-isolation- // invariant); a legacy/invalid segment falls back to the pass source.- const wbSourceId = wbMeta?.sourceId && isValidSourceId(wbMeta.sourceId)- ? wbMeta.sourceId- : sourceId;+ // #6268 source fidelity: every corpus file's facts, links and manifest+ // go to the source its NAME (or its session's frozen record) carries,+ // never the pass's source. A file with no evidence of its source is+ // held: no sidecar, a typed skip, an operator mapping releases it.+ const fileSource = await resolveCorpusFileSource(engine, dir, name, location);+ if (!fileSource.ok) {+ skip(fileSource.reason);+ continue;+ }const pipelineCtx: FactsBackstopCtx = {engine,- sourceId: wbMeta ? wbSourceId : sourceId,+ sourceId: fileSource.sourceId,sessionId: wbMeta ? wbMeta.sessionId : `sweep:corpus:${name}`,// Writeback turn files keep their lane's provenance + salient// notability filter so batch-extracted turns are indistinguishable@@ -781,11 +790,12 @@ async function runCorpusIngestPass(} else {const run = await windows.runCorpusWindows({full, raw, fileStat, overBudget, signal,+ source: { id: fileSource.sourceId, incarnation: fileSource.incarnation },maxWindows: Math.min(windows.CORPUS_WINDOWS_PER_SWEEP, windowsLeft),extract: text => runFactsPipeline(text, pipelineCtx),});windowsLeft -= run.windowsDone;- report.corpus_files.push({ file: name, windows_done: run.windowsDone, windows_remaining: run.windowsRemaining });+ report.corpus_files.push({ file: label, windows_done: run.windowsDone, windows_remaining: run.windowsRemaining });if (run.status !== 'complete') {abortLoop = run.status === 'aborted';skip(CORPUS_WINDOW_SKIP[run.status], abortLoop ? candidates.length - i : 1);@@ -821,16 +831,16 @@ async function runCorpusIngestPass(const verified: Array<{ slug: string; title: string }> = [];for (const slug of r.entity_slugs) {try {- const page = await engine.getPage(slug, { sourceId });+ const page = await engine.getPage(slug, { sourceId: fileSource.sourceId });if (page) verified.push({ slug, title: page.title || slug });} catch { /* a non-resolvable link is never banked */ }}if (verified.length) {const ss = await import('./context/session-state.ts');- const ledger = segs.readSegmentLedger(dir, parsed.sessionId);+ const ledger = segs.readSegmentLedger(base, parsed.sessionId);const n = Math.max(1, ledger.findIndex((e) => e.hash === parsed.hash) + 1);const ok = await ss.appendCheckpointManifest(- engine, sourceId, null, parsed.sessionId, verified,+ engine, fileSource.sourceId, null, parsed.sessionId, verified,{ seg: parsed.hash, n },);if (ok) linksBanked = verified.length;@@ -976,9 +986,13 @@ async function corpusHasPendingFiles(engine: BrainEngine): Promise<boolean> {const { configDir } = await import('./config.ts');dir = join(configDir(), 'transcripts', 'corpus');}- const names = await readdir(dir).catch(() => [] as string[]);- const present = new Set(names);- return names.some(n => n.endsWith('.txt') && !present.has(n + CORPUS_INGESTED_SUFFIX));+ const { corpusSpoolDir } = await import('./context/corpus-segments.ts');+ for (const base of [corpusSpoolDir(dir), dir]) {+ const names = await readdir(base).catch(() => [] as string[]);+ const present = new Set(names);+ if (names.some(n => n.endsWith('.txt') && !present.has(n + CORPUS_INGESTED_SUFFIX))) return true;+ }+ return false;}/**diff --git a/src/core/transcripts.ts b/src/core/transcripts.tsindex 49eb6a53c3..7f869930b0 100644--- a/src/core/transcripts.ts+++ b/src/core/transcripts.ts@@ -14,6 +14,7 @@*/import { readFileSync, readdirSync, statSync } from 'node:fs';+import { corpusSpoolDir } from './context/corpus-segments.ts';import { join, basename, dirname } from 'node:path';import type { BrainEngine } from './engine.ts';import type { Action } from './agent-output.ts';@@ -102,7 +103,8 @@ export async function transcriptCorpusDirs(engine: Pick<BrainEngine, 'getConfig'const dirs: string[] = [];const sessionDir = await engine.getConfig('dream.synthesize.session_corpus_dir');const meetingDir = await engine.getConfig('dream.synthesize.meeting_transcripts_dir');- if (sessionDir) dirs.push(sessionDir);+ // #6268: source-stamped session files live in the corpus spool subdirectory.+ if (sessionDir) dirs.push(sessionDir, corpusSpoolDir(sessionDir));if (meetingDir) dirs.push(meetingDir);return dirs;}diff --git a/src/mcp/context-pack-handler.ts b/src/mcp/context-pack-handler.tsindex 2e4dedcd2e..0915d2474b 100644--- a/src/mcp/context-pack-handler.ts+++ b/src/mcp/context-pack-handler.ts@@ -26,7 +26,8 @@ import {upsertSessionContextState,} from '../core/context/session-state.ts';import { scheduleCheckpointHarvest, type HarvestAck } from '../core/context/checkpoint-harvest.ts';-import { parseWbFileName } from '../core/context/corpus-segments.ts';+import { corpusSpoolDir, parseWbFileName } from '../core/context/corpus-segments.ts';+import { freezeSessionSource, resolveCorpusFileSource } from '../core/context/corpus-source.ts';import { loadCoreBlock } from '../core/core-memory.ts';import { coreTrustIdentity } from '../core/context/openclaw-core.ts';import type { TurnContextResult } from '../core/context/turn-context.ts';@@ -86,9 +87,13 @@ export function makeContextPackIpcHandler(const core = await coreForSession(engine, sessionSource);return { ...base, ...(core ? { core } : {}), ...(core && identity !== null ? { coreTrust: { identity, unchanged: false } } : {}) };}+ // #6268: the transport's bound-source check [CX2-10] already refuses a+ // foreign sourceId; the handler refuses too (direct callers), never+ // rerouting a session's manifest, state or harvest to another source.+ if (sessionSource !== defaultSource) throw new Error('source_mismatch');if (req.manifestOnly === true) {const links = sessionId- ? await getCheckpointManifest(engine, defaultSource, null, sessionId)+ ? await getCheckpointManifest(engine, sessionSource, null, sessionId): [];return {text: '', pointers: [], factsCount: 0, mode: 'pack' as const,@@ -106,8 +111,14 @@ export function makeContextPackIpcHandler(fromWindow = extractCandidatesFromWindow(req.window).map((c) => c.query);}} catch { /* extraction is best-effort */ }+ // #6268: an unpinned session (no sourceId) resolves to this serve's own+ // binding; an UNRESOLVED corpus record it already wrote is frozen to it,+ // so its unresolved-stamped files follow the source this lane serves.+ if (sessionId && !req.sourceId) {+ try { freezeSessionSource(await serveCorpusDir(engine), sessionId, sessionSource, 'serve', { onlyExisting: true }); } catch { /* best effort */ }+ }const state = sessionId- ? await getSessionContextState(engine, defaultSource, null, sessionId)+ ? await getSessionContextState(engine, sessionSource, null, sessionId): null;const banked = state?.standing_entities ?? [];const entities = Array.from(new Set([...fromReq, ...fromWindow, ...banked]));@@ -116,7 +127,7 @@ export function makeContextPackIpcHandler(// PreCompact banking: persist the standing set for the post-compaction// SessionStart; no assembly, empty block.if (sessionId && entities.length) {- await upsertSessionContextState(engine, defaultSource, null, sessionId, {+ await upsertSessionContextState(engine, sessionSource, null, sessionId, {standingEntities: entities.slice(0, PUSH_PACK_MAX_ENTITIES * 2),});}@@ -133,8 +144,18 @@ export function makeContextPackIpcHandler(checkpointFlush = { status: 'skipped', reason: 'no_session' };} else {const dir = await serveCorpusDir(engine);- if (!existsSync(join(dir, base))) {+ // #6268: stamped files live in the spool; a pre-stamp hook flushes a top-level name.+ const spool = corpusSpoolDir(dir);+ const location = existsSync(join(spool, base)) ? 'spool' as const : existsSync(join(dir, base)) ? 'legacy' as const : null;+ const fileSource = location ? await resolveCorpusFileSource(engine, dir, base, location).catch(() => null) : null;+ if (!location) {checkpointFlush = { status: 'skipped', reason: 'not_found' };+ } else if (!fileSource || !fileSource.ok) {+ checkpointFlush = { status: 'skipped', reason: fileSource ? fileSource.reason : 'corpus_source_error' };+ } else if (fileSource.sourceId !== sessionSource) {+ // Refuse, never reroute: this serve harvests only its own source;+ // the sweep files the segment under its stamped source.+ checkpointFlush = { status: 'skipped', reason: 'source_mismatch' };} else {// Ambient-writeback turn files ride the SAME bank lane with a// basename-derived lane tag (WP4): `.wb-<hash>` files get the@@ -145,7 +166,8 @@ export function makeContextPackIpcHandler(// compact lane, past the writeback gate.const lane = parseWbFileName(base) !== null ? ('writeback' as const) : ('compact' as const);checkpointFlush = scheduleCheckpointHarvest({- engine, sourceId: defaultSource, sessionId, corpusDir: dir, file: base, lane,+ engine, sourceId: fileSource.sourceId, sourceIncarnation: fileSource.incarnation, sessionId,+ corpusDir: location === 'spool' ? spool : dir, file: base, lane,});}}@@ -157,7 +179,7 @@ export function makeContextPackIpcHandler(}const result = await assembleContextPack(engine, {- sourceId: defaultSource,+ sourceId: sessionSource,entities,sessionId: sessionId ?? undefined,since: state?.last_wake_at ?? undefined,@@ -168,7 +190,7 @@ export function makeContextPackIpcHandler(// post-compaction SessionStart renders them (fail-open []; links that// missed this pack surface on the next boundary — at-least-once)....(sessionId- ? { checkpointLinks: (await getCheckpointManifest(engine, defaultSource, null, sessionId)) ?? [] }+ ? { checkpointLinks: (await getCheckpointManifest(engine, sessionSource, null, sessionId)) ?? [] }: {}),});const core = typeof req.trigger === 'string' && req.trigger.startsWith('session-start') ? await coreForSession(engine, sessionSource) : null;@@ -181,7 +203,7 @@ export function makeContextPackIpcHandler(// known at-most-once edge of the push path; the pull `delta` verb is// the lossless channel.) The cursor upsert is monotonic (GREATEST), so// an interleaved delta advance is never rewound.- await upsertSessionContextState(engine, defaultSource, null, sessionId, {+ await upsertSessionContextState(engine, sessionSource, null, sessionId, {standingEntities: entities.slice(0, PUSH_PACK_MAX_ENTITIES * 2),...(result.degradedReason ? {} : { lastWakeAt: new Date().toISOString() }),});diff --git a/test/bootstrap-hook-under-serve.serial.test.ts b/test/bootstrap-hook-under-serve.serial.test.tsindex 843d48e946..aff3735185 100644--- a/test/bootstrap-hook-under-serve.serial.test.ts+++ b/test/bootstrap-hook-under-serve.serial.test.ts@@ -437,7 +437,7 @@ describe('bootstrap hook under a live serve (serial e2e) [A7]', () => {expect(hb.outcome).toBe('ok'); // IPC round trip reached the serveexpect(hb.segment).toBe('segment_banked');// Durability artifacts on disk, content-addressed, since-boundary only.- const corpusDir = join(tmpParent, '.gbrain', 'transcripts', 'corpus');+ const corpusDir = join(tmpParent, '.gbrain', 'transcripts', 'corpus', 'sourced'); // #6268: the spoolconst segs = readdirSync(corpusDir).filter((f) => f.startsWith('e2e-seg-sess.seg-') && f.endsWith('.txt'));expect(segs).toHaveLength(1);const body = readFileSync(join(corpusDir, segs[0]), 'utf8');diff --git a/test/capture-consent-admission.test.ts b/test/capture-consent-admission.test.tsindex 7ba6671e1b..4fad7adc47 100644--- a/test/capture-consent-admission.test.ts+++ b/test/capture-consent-admission.test.ts@@ -16,11 +16,12 @@** Runs on PGLite; also on Postgres when DATABASE_URL is set (testBackends).*/+import { spoolPath } from './helpers/corpus-spool.ts';import { afterAll, beforeAll, describe, expect, test } from 'bun:test';import { randomUUID } from 'node:crypto';import { appendFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';-import { join } from 'node:path';+import { basename, join } from 'node:path';import type { BrainEngine } from '../src/core/engine.ts';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { claimWorktree } from '../src/core/persistence/ownership.ts';@@ -107,7 +108,8 @@ async function managedCorpus(engine: BrainEngine, dir: string, opts: { drifted?:const pristine = readFileSync(pageFile);if (opts.drifted) appendFileSync(pageFile, '\nA local edit nobody imported.\n');const raw = transcript();- writeFileSync(join(corpusDir, SESSION), raw);+ const sessionFile = spoolPath(corpusDir, SESSION, sourceId);+ writeFileSync(sessionFile, raw);const quiet = () => waitFor(async () => (await engine.executeRaw<{ n: number }>(`SELECT COUNT(*)::int AS n FROM persistence_requests WHERE source_id=$1 AND state IN ('queued','running','recovering')`, [sourceId]))[0].n === 0,{ timeoutMs: 30_000, label: 'fact requests settled' });@@ -120,7 +122,7 @@ async function managedCorpus(engine: BrainEngine, dir: string, opts: { drifted?:const facts = async () => (await engine.executeRaw<{ n: number }>(`SELECT COUNT(*)::int AS n FROM facts WHERE source_id=$1 AND source='sweep:corpus' AND expired_at IS NULL`, [sourceId]))[0].n;// The sweep's own window, for a worker that passed its gate before off landed.- const pipelineCtx: FactsBackstopCtx = { engine, sourceId, sessionId: `sweep:corpus:${SESSION}`, source: 'sweep:corpus', mode: 'inline',+ const pipelineCtx: FactsBackstopCtx = { engine, sourceId, sessionId: `sweep:corpus:${basename(sessionFile)}`, source: 'sweep:corpus', mode: 'inline',remote: false, reAdmitFileRefusals: true };const firstWindow = planCorpusWindows(parseCorpusTurns(raw), { turn: 0, offset: 0 })[0].text;const replay = () => runFactsPipeline(firstWindow, pipelineCtx);diff --git a/test/capture-consent-gate.serial.test.ts b/test/capture-consent-gate.serial.test.tsindex a13bea4c45..44df8ec6e5 100644--- a/test/capture-consent-gate.serial.test.ts+++ b/test/capture-consent-gate.serial.test.ts@@ -232,7 +232,7 @@ describe('durable revocation: a capture under off never extracts later', () => {test('off then on with the worker stopped: the off-period transcript is never extracted', async () => {await setMode('off');await sessionEnd('sess-r1', ['we picked the blue deployment window', 'noted']);- expect(existsSync(join(corpusDir, 'sess-r1.txt'))).toBe(true);+ expect(existsSync(join(corpusDir, 'sourced', 'sess-r1.src-_unresolved.txt'))).toBe(true); // #6268: the hook writes the spoolawait setMode('salient');await sweep();expect(prompts.length).toBe(0);diff --git a/test/codex-rollout-0154.serial.test.ts b/test/codex-rollout-0154.serial.test.tsindex 8a5c4be2de..759f783dd7 100644--- a/test/codex-rollout-0154.serial.test.ts+++ b/test/codex-rollout-0154.serial.test.ts@@ -146,7 +146,7 @@ describe('#5163 hook lane: the SessionEnd parser keeps the typed turn', () => {harness: 'codex',stdin: JSON.stringify({ session_id: 'r-154', transcript_path: rollout, cwd: join(tmp, 'ws') }),})).toBe(0);- const corpus = join(tmp, '.gbrain', 'transcripts', 'corpus', 'r-154.txt');+ const corpus = join(tmp, '.gbrain', 'transcripts', 'corpus', 'sourced', 'r-154.src-_unresolved.txt');expect(existsSync(corpus)).toBe(true);const text = readFileSync(corpus, 'utf8');expect(text).toContain('[user]');@@ -198,7 +198,7 @@ describe('E-N4: assistant turns with no user turn are flagged, never silent', ()})).toBe(0);const hb = (await readHeartbeatTail(1))[0]!;expect(hb).toMatchObject({ event: 'session-end', outcome: 'degraded', reason: 'no_user_turns' });- expect(existsSync(join(tmp, '.gbrain', 'transcripts', 'corpus', 'r-ao.txt'))).toBe(true);+ expect(existsSync(join(tmp, '.gbrain', 'transcripts', 'corpus', 'sourced', 'r-ao.src-_unresolved.txt'))).toBe(true);});describe('ingest', () => {diff --git a/test/context-engine-checkpoint.serial.test.ts b/test/context-engine-checkpoint.serial.test.tsindex f06bdf5730..8b58237511 100644--- a/test/context-engine-checkpoint.serial.test.ts+++ b/test/context-engine-checkpoint.serial.test.ts@@ -67,7 +67,7 @@ describe('checkpoint compaction (cathedral 5)', () => {// is SPOOLED regardless (durability first; sweep is the backstop).expect(bag.gbrain_checkpoint?.status).toBe('banked');expect(bag.gbrain_checkpoint?.reason).toBe('no_engine');- const corpus = join(home!, '.gbrain', 'transcripts', 'corpus');+ const corpus = join(home!, '.gbrain', 'transcripts', 'corpus', 'sourced'); // #6268: the spoolconst segs = readdirSync(corpus).filter((f) => f.startsWith('oc-sess.seg-') && f.endsWith('.txt'));expect(segs).toHaveLength(1);const body = readFileSync(join(corpus, segs[0]), 'utf8');@@ -86,7 +86,7 @@ describe('checkpoint compaction (cathedral 5)', () => {writeFileSync(sessionFile, lines.join('\n') + '\n');const engine = createGBrainContextEngine({ workspaceDir: tmpDir });await engine.compact({ sessionId: 'oc-long', sessionFile });- const corpus = join(home!, '.gbrain', 'transcripts', 'corpus');+ const corpus = join(home!, '.gbrain', 'transcripts', 'corpus', 'sourced'); // #6268: the spoolconst segs = readdirSync(corpus).filter((f) => f.startsWith('oc-long.seg-'));expect(segs).toHaveLength(1);const body = readFileSync(join(corpus, segs[0]), 'utf8');@@ -209,7 +209,7 @@ describe('checkpoint compaction (cathedral 5)', () => {writeFileSync(sessionFile, [sessionLine, msg('window text for the poll pin')].join('\n') + '\n');const engine = createGBrainContextEngine({ workspaceDir: tmpDir });await engine.compact({ sessionId: 'oc-poll', sessionFile });- const corpus = join(home!, '.gbrain', 'transcripts', 'corpus');+ const corpus = join(home!, '.gbrain', 'transcripts', 'corpus', 'sourced'); // #6268: the spoolconst expectSeg = readSegmentLedger(corpus, 'oc-poll')[0]?.hash;expect(expectSeg).toBeTruthy();@@ -288,7 +288,7 @@ describe('checkpoint compaction (cathedral 5)', () => {expect(bag.gbrain_checkpoint?.status).toBe('banked'); // rung 2 IPC acked// The spool landed under the SANITIZED key — never a path-shaped filename.- const corpus = join(home!, '.gbrain', 'transcripts', 'corpus');+ const corpus = join(home!, '.gbrain', 'transcripts', 'corpus', 'sourced'); // #6268: the spoolconst files = readdirSync(corpus);const segs = files.filter((f) => f.startsWith(`${SAFE_ID}.seg-`) && f.endsWith('.txt'));expect(segs).toHaveLength(1);@@ -314,7 +314,7 @@ describe('checkpoint compaction (cathedral 5)', () => {expect(polls.length).toBeGreaterThanOrEqual(1);for (const s of seen) expect(s.sessionId).toBe(SAFE_ID);// The flush ask names the sanitized segment file — same key end to end.- expect(banks[0].flushCorpusFile).toBe(`${SAFE_ID}.seg-${serveSeg}.txt`);+ expect(banks[0].flushCorpusFile).toBe(`${SAFE_ID}.seg-${serveSeg}.src-_unresolved.txt`);});it('F5/CK8: sanitizeEngineSessionId — null for empty/all-dots/non-strings; real charset + clamp pins', () => {diff --git a/test/corpus-retention-uningested.serial.test.ts b/test/corpus-retention-uningested.serial.test.tsindex 14de74f3d1..a37aebd7d1 100644--- a/test/corpus-retention-uningested.serial.test.ts+++ b/test/corpus-retention-uningested.serial.test.ts@@ -66,7 +66,7 @@ describe('E-N1: session-end GC keeps un-ingested corpus files up to 3x retentionconst ceiling = aged('ancient-waiting.txt', 95, false);const fresh = aged('fresh-waiting.txt', 2, false);await sessionEnd();- expect(existsSync(join(corpus(), 'sess-new.txt'))).toBe(true);+ expect(existsSync(join(corpus(), 'sourced', 'sess-new.src-_unresolved.txt'))).toBe(true); // #6268: the spoolexpect(existsSync(extracted)).toBe(false);expect(existsSync(waiting)).toBe(true);expect(existsSync(fresh)).toBe(true);diff --git a/test/corpus-source-stamp.test.ts b/test/corpus-source-stamp.test.tsnew file mode 100644index 0000000000..751f441626--- /dev/null+++ b/test/corpus-source-stamp.test.ts@@ -0,0 +1,314 @@+/**+ * #6268 (W13 P3.4, R14): every corpus file carries the session's source.+ *+ * Before the fix a compaction segment or session-end file carried no source,+ * so the sweep filed its facts under whatever source the PASS ran for. Here a+ * session pinned to `client-a` (GBRAIN_SOURCE) writes its corpus through the+ * real hook entry points, the sweep runs for `default`, and the facts must+ * land in `client-a`. The rest pins the R14 contract: stamped files live in+ * the spool subdirectory an old sweeper never reads, the session source is+ * frozen at the first resolution, a resumed window refuses a source change,+ * legacy unstamped files are held (or adopted only with evidence), and the+ * unresolved marker can never collide with a real source id.+ *+ * Hermetic in-memory PGLite + chat-transport stub (sweep.test.ts harness).+ */+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';++import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { runMaintenanceSweep } from '../src/core/sweep.ts';+import { runHook } from '../src/commands/hook.ts';+import { runSweep } from '../src/commands/sweep.ts';+import {+ CORPUS_SPOOL_SUBDIR, CORPUS_UNRESOLVED_STAMP, corpusFileSessionId, ensureCorpusSpoolDir, isCorpusSourceStamp,+ parseSegmentFileName, parseWbFileName, segmentFileName, sessionCorpusFileName, writeSegment,+} from '../src/core/context/corpus-segments.ts';+import { freezeSessionSource, openSessionSource, readSessionSource, resolveCorpusFileSource } from '../src/core/context/corpus-source.ts';+import { runCorpusWindows, corpusFileStat } from '../src/core/context/corpus-windows.ts';+import { toCorpusText } from '../src/core/transcripts/claude-code-jsonl.ts';+import { isValidSourceId } from '../src/core/source-id.ts';+import { makeContextPackIpcHandler } from '../src/mcp/context-pack-handler.ts';+import { _resetCliExitVerdictForTests } from '../src/core/cli-force-exit.ts';+import { statSync } from 'node:fs';+import { __setChatTransportForTests, resetGateway, type ChatResult } from '../src/core/ai/gateway.ts';+import type { CapabilityReport } from '../src/core/capability.ts';+import { withEnv } from './helpers/with-env.ts';++const KEYED: CapabilityReport = {+ embeddings: { available: false },+ extraction: { available: true, provider: 'anthropic' },+ search: 'keyword-only',+ mode: 'keyed',+};++let engine: PGLiteEngine;+let home: string;+const tmpDirs: string[] = [];++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ await engine.executeRaw("INSERT INTO sources(id,name) VALUES('client-a','client-a') ON CONFLICT DO NOTHING");+}, 120_000);++afterAll(async () => {+ await engine.disconnect();+ for (const d of tmpDirs) rmSync(d, { recursive: true, force: true });+});++const corpus = () => join(home, '.gbrain', 'transcripts', 'corpus');++beforeEach(async () => {+ await engine.executeRaw('DELETE FROM facts').catch(() => {});+ home = mkdtempSync(join(tmpdir(), 'gbrain-corpus-src-'));+ tmpDirs.push(home);+ mkdirSync(join(home, 'ws'), { recursive: true });+ mkdirSync(corpus(), { recursive: true });+ await engine.setConfig('dream.synthesize.session_corpus_dir', corpus());+ __setChatTransportForTests(async (): Promise<ChatResult> => ({+ text: JSON.stringify({ facts: [{ fact: 'Ships the quarterly report on Fridays.', kind: 'fact', entity: null, confidence: 1, notability: 'high' }] }),+ blocks: [], stopReason: 'end',+ usage: { input_tokens: 1, output_tokens: 1, cache_read_tokens: 0, cache_creation_tokens: 0 },+ model: 'anthropic:claude-sonnet-4-6', providerId: 'anthropic',+ }));+});++afterEach(() => {+ __setChatTransportForTests(null);+ resetGateway();+});++const userLine = (text: string) => JSON.stringify({ type: 'user', isSidechain: false, message: { role: 'user', content: text } });+const assistantLine = (text: string) =>+ JSON.stringify({ type: 'assistant', isSidechain: false, message: { role: 'assistant', content: [{ type: 'text', text }] } });+const boundaryLine = () => JSON.stringify({ type: 'system', subtype: 'compact_boundary', content: 'conversation compacted' });++function seedTranscript(name: string, lines: string[]): string {+ const dir = join(home, 'projects', 'p1');+ mkdirSync(dir, { recursive: true });+ const p = join(dir, name);+ writeFileSync(p, lines.join('\n') + '\n');+ return p;+}++async function hook(event: string, sid: string, transcript: string): Promise<void> {+ expect(await runHook([event], {+ stdin: JSON.stringify({ session_id: sid, transcript_path: transcript, cwd: join(home, 'ws') }),+ transcriptRoot: join(home, 'projects'),+ disableTelemetry: true,+ })).toBe(0);+}++async function factSources(): Promise<string[]> {+ const rows = await engine.executeRaw<{ source_id: string }>('SELECT DISTINCT source_id FROM facts ORDER BY source_id');+ return rows.map((r) => r.source_id);+}++describe('#6268 corpus files carry the session source', () => {+ test('issue repro: a client-a session swept under default files its facts in client-a', async () => {+ const transcript = seedTranscript('s.jsonl', [+ userLine('We agreed that Alice ships the quarterly report on Fridays.'),+ assistantLine('Noted, Fridays it is.'),+ boundaryLine(),+ userLine('And the board deck goes out on Mondays.'),+ assistantLine('Got it.'),+ ]);+ await withEnv({ GBRAIN_HOME: home, GBRAIN_SOURCE: 'client-a', GBRAIN_HOOKS: undefined }, async () => {+ await hook('compact', 'sess-client-a', transcript);+ await hook('session-end', 'sess-client-a', transcript);+ });+ const r = await runMaintenanceSweep(engine, { sourceId: 'default', capabilities: KEYED });+ expect(r.corpusIngested).toBeGreaterThan(0);+ expect(await factSources()).toEqual(['client-a']);+ });+});++const spool = () => join(corpus(), CORPUS_SPOOL_SUBDIR);+const txt = (dir: string) => (existsSync(dir) ? readdirSync(dir).filter((n) => n.endsWith('.txt')) : []);+const corpusText = (turns: string[]) => toCorpusText(turns.map((text, i) => ({ role: i % 2 ? 'assistant' as const : 'user' as const, text })));+async function sweepAs(source = 'default') {+ return runMaintenanceSweep(engine, { sourceId: source, capabilities: KEYED, budgetMs: 60_000 });+}+async function addSource(id: string, localPath?: string) {+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2) ON CONFLICT DO NOTHING', [id, localPath ?? null]);+}++describe('#6268 R14: stamps, spool, frozen session source', () => {+ test('explicit default stamp: a default session names default in every file, all inside the spool', async () => {+ const transcript = seedTranscript('d.jsonl', [userLine('We ship the quarterly report on Fridays.'), assistantLine('ok'), boundaryLine(), userLine('more'), assistantLine('ok')]);+ await withEnv({ GBRAIN_HOME: home, GBRAIN_SOURCE: 'default', GBRAIN_HOOKS: undefined }, async () => {+ await hook('compact', 'sess-default', transcript);+ await hook('session-end', 'sess-default', transcript);+ });+ const names = txt(spool());+ expect(names.length).toBeGreaterThanOrEqual(2);+ expect(names.every((n) => n.endsWith('.src-default.txt'))).toBe(true);+ expect(names).toContain(sessionCorpusFileName('sess-default', 'default'));+ await sweepAs('default');+ expect(await factSources()).toEqual(['default']);+ });++ test('new writer, old sweeper: no stamped file lands where a pre-stamp sweeper reads (the top-level .txt listing)', async () => {+ const transcript = seedTranscript('o.jsonl', [userLine('A fact about the Friday report.'), assistantLine('ok')]);+ await withEnv({ GBRAIN_HOME: home, GBRAIN_SOURCE: 'client-a', GBRAIN_HOOKS: undefined }, async () => {+ await hook('session-end', 'sess-old-sweeper', transcript);+ });+ // A pre-stamp sweeper lists `readdir(corpusDir)` `.txt` and files every non-wb one under its pass source.+ expect(txt(corpus())).toEqual([]);+ expect(txt(spool())).toEqual([sessionCorpusFileName('sess-old-sweeper', 'client-a')]);+ });++ test('old writer, new sweeper: legacy names still parse; a legacy wb stamp is honored', () => {+ expect(parseSegmentFileName('s1.seg-0123456789abcdef01234567.txt')).toEqual({ sessionId: 's1', hash: '0123456789abcdef01234567' });+ expect(parseSegmentFileName('s1.seg-0123456789abcdef01234567.src-client-a.txt')).toEqual({ sessionId: 's1', hash: '0123456789abcdef01234567', stamp: 'client-a' });+ expect(parseWbFileName('s1.wb-0123456789abcdef01234567.src-client-a.txt')?.sourceId).toBe('client-a');+ expect(corpusFileSessionId('s1.txt')).toBe('s1');+ expect(corpusFileSessionId('s1.src-client-a.txt')).toBe('s1');+ expect(corpusFileSessionId(segmentFileName('s1', '0123456789abcdef01234567', 'default'))).toBe('s1');+ });++ test('legacy unstamped file on a multi-source brain is held (never the pass source), then mapped explicitly', async () => {+ writeFileSync(join(corpus(), 'sess-legacy.txt'), corpusText(['Alice ships the quarterly report on Fridays.', 'ok']));+ const r1 = await sweepAs('default');+ expect(r1.skipped).toContainEqual({ reason: 'corpus_legacy_unstamped', count: 1 });+ expect(await factSources()).toEqual([]);+ expect(existsSync(join(corpus(), 'sess-legacy.txt.ingested'))).toBe(false);++ _resetCliExitVerdictForTests();+ const log: string[] = [];+ const orig = console.log;+ console.log = (...a: unknown[]) => { log.push(a.join(' ')); };+ try {+ await runSweep(engine, ['--assign-corpus', 'client-a']);+ expect(readSessionSource(spool(), 'sess-legacy')).toBeNull(); // preview writes nothing+ await runSweep(engine, ['--assign-corpus', 'client-a', '--apply']);+ } finally {+ console.log = orig;+ }+ expect(log.join('\n')).toContain('sess-legacy');+ expect(readSessionSource(spool(), 'sess-legacy')).toMatchObject({ source_id: 'client-a', tier: 'operator' });+ await sweepAs('default');+ expect(await factSources()).toEqual(['client-a']);+ });++ test('legacy file adopted with durable session evidence: the same session\'s frozen spool record', async () => {+ writeFileSync(join(corpus(), 'sess-evidence.txt'), corpusText(['Alice ships the quarterly report on Fridays.', 'ok']));+ freezeSessionSource(corpus(), 'sess-evidence', 'client-a', 'env');+ const r = await resolveCorpusFileSource(engine, corpus(), 'sess-evidence.txt', 'legacy');+ expect(r).toMatchObject({ ok: true, sourceId: 'client-a', via: 'session_record' });+ await sweepAs('default');+ expect(await factSources()).toEqual(['client-a']);+ });++ test('session source frozen at session start: a later capture with another GBRAIN_SOURCE keeps the first', async () => {+ await withEnv({ GBRAIN_SOURCE: 'client-a' }, async () => {+ expect((await openSessionSource(corpus(), 'sess-frozen', { cwd: join(home, 'ws'), harness: 'test' })).stamp).toBe('client-a');+ });+ await withEnv({ GBRAIN_SOURCE: 'default' }, async () => {+ expect((await openSessionSource(corpus(), 'sess-frozen', { cwd: join(home, 'ws'), harness: 'test' })).stamp).toBe('client-a');+ });+ });++ test('the unresolved marker cannot collide with a real source named "unresolved"', async () => {+ expect(isValidSourceId(CORPUS_UNRESOLVED_STAMP)).toBe(false);+ expect(isCorpusSourceStamp('unresolved')).toBe(true);+ await addSource('unresolved');+ const dir = ensureCorpusSpoolDir(corpus());+ writeFileSync(join(dir, sessionCorpusFileName('sess-real', 'unresolved')), corpusText(['Alice ships the quarterly report on Fridays.', 'ok']));+ writeFileSync(join(dir, sessionCorpusFileName('sess-marker', CORPUS_UNRESOLVED_STAMP)), corpusText(['Bob ships the board deck on Mondays.', 'ok']));+ const r = await sweepAs('default');+ expect(r.skipped).toContainEqual({ reason: 'corpus_source_unresolved', count: 1 });+ expect(await factSources()).toEqual(['unresolved']);+ });++ test('unresolved session: the brain resolves the recorded cwd (tiers 4-6) once and freezes it', async () => {+ const ws = join(home, 'ws-b');+ mkdirSync(ws, { recursive: true });+ await addSource('client-b', ws);+ const transcript = seedTranscript('u.jsonl', [userLine('Alice ships the quarterly report on Fridays.'), assistantLine('ok')]);+ await withEnv({ GBRAIN_HOME: home, GBRAIN_SOURCE: undefined, GBRAIN_HOOKS: undefined }, async () => {+ expect(await runHook(['session-end'], {+ stdin: JSON.stringify({ session_id: 'sess-unpinned', transcript_path: transcript, cwd: ws }),+ transcriptRoot: join(home, 'projects'), disableTelemetry: true,+ })).toBe(0);+ });+ expect(txt(spool())).toEqual([sessionCorpusFileName('sess-unpinned', CORPUS_UNRESOLVED_STAMP)]);+ await sweepAs('default');+ expect(await factSources()).toEqual(['client-b']);+ expect(readSessionSource(spool(), 'sess-unpinned')).toMatchObject({ source_id: 'client-b', tier: 'engine' });+ });++ test('two-window resume across sources is refused, and so is a recreated source (incarnation)', async () => {+ const dir = ensureCorpusSpoolDir(corpus());+ const full = join(dir, sessionCorpusFileName('sess-resume', 'client-a'));+ const long = 'x'.repeat(7_000);+ writeFileSync(full, corpusText([`first ${long}`, 'ok', `second ${long}`, 'ok']));+ const raw = readFileSync(full, 'utf8');+ const run = (source: { id: string; incarnation: string }) => runCorpusWindows({+ full, raw, fileStat: corpusFileStat(statSync(full)), maxWindows: 1, overBudget: () => false,+ signal: new AbortController().signal, source,+ extract: async () => ({ inserted: 0, duplicate: 0, superseded: 0, fact_ids: [], entity_slugs: [] }),+ });+ const first = await run({ id: 'client-a', incarnation: 'inc-1' });+ expect(first.status).toBe('partial');+ expect((await run({ id: 'default', incarnation: 'inc-0' })).status).toBe('source_changed');+ expect((await run({ id: 'client-a', incarnation: 'inc-2' })).status).toBe('source_changed');+ expect((await run({ id: 'client-a', incarnation: 'inc-1' })).status).toBe('complete');+ });++ test('a session bound to a source incarnation holds its files after the source is deleted and recreated', async () => {+ await addSource('client-c');+ const dir = ensureCorpusSpoolDir(corpus());+ freezeSessionSource(corpus(), 'sess-inc', 'client-c', 'env');+ writeFileSync(join(dir, sessionCorpusFileName('sess-inc', 'client-c')), corpusText(['one', 'ok']));+ expect((await resolveCorpusFileSource(engine, corpus(), sessionCorpusFileName('sess-inc', 'client-c'), 'spool')).ok).toBe(true);+ await engine.executeRaw("DELETE FROM sources WHERE id = 'client-c'");+ await addSource('client-c');+ expect(await resolveCorpusFileSource(engine, corpus(), sessionCorpusFileName('sess-inc', 'client-c'), 'spool'))+ .toEqual({ ok: false, reason: 'corpus_source_incarnation_changed' });+ });++ test('manifest and links publish under the stamped source', async () => {+ const repo = join(home, 'repo-a');+ mkdirSync(join(repo, 'people'), { recursive: true });+ writeFileSync(join(repo, 'people', 'alice-example.md'), '---\ntype: person\ntitle: Alice Example\n---\n\nx\n');+ await engine.executeRaw("UPDATE sources SET local_path = $1 WHERE id = 'client-a'", [repo]);+ await engine.executeRaw("INSERT INTO pages (slug, source_id, type, title, compiled_truth, timeline) VALUES ('people/alice-example', 'client-a', 'person', 'Alice Example', 'x', '') ON CONFLICT DO NOTHING");+ __setChatTransportForTests(async (): Promise<ChatResult> => ({+ text: JSON.stringify({ facts: [{ fact: 'Ships the quarterly report on Fridays.', kind: 'fact', entity: 'people/alice-example', confidence: 1, notability: 'high' }] }),+ blocks: [], stopReason: 'end',+ usage: { input_tokens: 1, output_tokens: 1, cache_read_tokens: 0, cache_creation_tokens: 0 },+ model: 'anthropic:claude-sonnet-4-6', providerId: 'anthropic',+ }));+ const dir = ensureCorpusSpoolDir(corpus());+ const w = writeSegment(dir, 'sess-manifest', corpusText(['Alice Example ships the quarterly report on Fridays.', 'ok']), 'client-a');+ expect(w.file.endsWith('.src-client-a.txt')).toBe(true);+ await sweepAs('default');+ const { getCheckpointManifest } = await import('../src/core/context/session-state.ts');+ expect((await getCheckpointManifest(engine, 'client-a', null, 'sess-manifest'))?.map((l) => l.slug)).toEqual(['people/alice-example']);+ expect((await getCheckpointManifest(engine, 'default', null, 'sess-manifest')) ?? []).toEqual([]);+ await engine.executeRaw("UPDATE sources SET local_path = NULL WHERE id = 'client-a'");+ });++ test('serve IPC: a foreign sourceId and a flush stamped for another source are refused, never rerouted', async () => {+ const handler = makeContextPackIpcHandler(engine, 'default');+ await expect(handler({ protocol: 2, secret: 's', sessionId: 'sess-ipc', sourceId: 'client-a', bankOnly: true } as never)).rejects.toThrow('source_mismatch');+ const dir = ensureCorpusSpoolDir(corpus());+ const name = sessionCorpusFileName('sess-ipc', 'client-a');+ writeFileSync(join(dir, name), corpusText(['x', 'y']));+ const res = await handler({ protocol: 2, secret: 's', sessionId: 'sess-ipc', bankOnly: true, flushCorpusFile: name } as never) as { checkpointFlush?: unknown };+ expect(res.checkpointFlush).toEqual({ status: 'skipped', reason: 'source_mismatch' });+ });++ test('serve IPC: an unpinned session\'s unresolved record freezes to the serve\'s own source', async () => {+ await openSessionSource(corpus(), 'sess-serve', { cwd: null, harness: 'test' });+ expect(readSessionSource(spool(), 'sess-serve')?.source_id).toBeNull();+ const handler = makeContextPackIpcHandler(engine, 'default');+ await handler({ protocol: 2, secret: 's', sessionId: 'sess-serve', bankOnly: true } as never);+ expect(readSessionSource(spool(), 'sess-serve')).toMatchObject({ source_id: 'default', tier: 'serve' });+ });+});diff --git a/test/fix-wave-5-integration.test.ts b/test/fix-wave-5-integration.test.tsindex 76ba5f9c66..21d86d8414 100644--- a/test/fix-wave-5-integration.test.ts+++ b/test/fix-wave-5-integration.test.ts@@ -275,11 +275,13 @@ for (const backend of testBackends()) {}// Session capture: session-end wrote A's transcript to the corpus, and the sweep ingests it.- const corpus = join(hookHome, '.gbrain', 'transcripts', 'corpus');+ // #6268: session files land in the corpus spool, the session's source stamped in the name.+ const corpusRoot = join(hookHome, '.gbrain', 'transcripts', 'corpus');+ const corpus = join(corpusRoot, 'sourced');const files = readdirSync(corpus).filter(name => name.endsWith('.txt'));expect(files.some(name => name.startsWith('sess-a'))).toBe(true);for (const name of files) for (const secret of secrets) expect(readFileSync(join(corpus, name), 'utf8')).not.toContain(secret);- await engine.setConfig('dream.synthesize.session_corpus_dir', corpus);+ await engine.setConfig('dream.synthesize.session_corpus_dir', corpusRoot);const prompts: string[] = [];__setChatTransportForTests(async (req: unknown): Promise<ChatResult> => {const prompt = JSON.stringify(req);diff --git a/test/helpers/corpus-spool.ts b/test/helpers/corpus-spool.tsnew file mode 100644index 0000000000..f00728e734--- /dev/null+++ b/test/helpers/corpus-spool.ts@@ -0,0 +1,14 @@+import { mkdirSync } from 'node:fs';+import { join } from 'node:path';+import { CORPUS_SPOOL_SUBDIR } from '../../src/core/context/corpus-segments.ts';++/**+ * #6268 fixture helper: where a current writer puts a corpus file for+ * `source` — the spool subdirectory, the source stamped into the name+ * (`x.txt` → `sourced/x.src-default.txt`; sidecar names keep their suffix:+ * `x.txt.ingested` → `sourced/x.src-default.txt.ingested`). Creates the spool.+ */+export function spoolPath(corpusDir: string, name: string, source = 'default'): string {+ mkdirSync(join(corpusDir, CORPUS_SPOOL_SUBDIR), { recursive: true });+ return join(corpusDir, CORPUS_SPOOL_SUBDIR, name.replace(/\.txt(?=$|\.)/, `.src-${source}.txt`));+}diff --git a/test/hook-command.serial.test.ts b/test/hook-command.serial.test.tsindex 2a708c2941..0f9019c300 100644--- a/test/hook-command.serial.test.ts+++ b/test/hook-command.serial.test.ts@@ -78,6 +78,8 @@ afterEach(() => {});const home = () => join(tmp, '.gbrain');+/** #6268: where the hook writes a session file (the spool; no GBRAIN_SOURCE or serve here, so the stamp is unresolved). */+const spooled = (name: string): string => join(home(), 'transcripts', 'corpus', 'sourced', name.replace(/\.txt(?=$|\.)/, '.src-_unresolved.txt'));function writePgliteConfig(dataDir: string): void {mkdirSync(home(), { recursive: true });@@ -728,7 +730,7 @@ describe('session-end', () => {transcriptRoot: projRoot,}),).toBe(0);- const corpus = join(home(), 'transcripts', 'corpus', 'sess-red.txt');+ const corpus = spooled('sess-red.txt');expect(existsSync(corpus)).toBe(true);const body = readFileSync(corpus, 'utf8');expect(body).not.toContain(planted);@@ -756,11 +758,11 @@ describe('session-end', () => {stdin: JSON.stringify({ session_id: 'sess-dup', transcript_path: t2, cwd: ws }),transcriptRoot: projRoot,});- const corpusDir = join(home(), 'transcripts', 'corpus');+ const corpusDir = join(home(), 'transcripts', 'corpus', 'sourced');const files = readdirSync(corpusDir).filter((f) => f.startsWith('sess-dup')).sort();- // One corpus file plus the session's one seat sidecar (#4618).- expect(files).toEqual(['sess-dup.seat.json', 'sess-dup.txt']);- expect(readFileSync(join(corpusDir, 'sess-dup.txt'), 'utf8')).toContain('resumed pass content');+ // One corpus file plus the session's one seat sidecar (#4618) and its source record (#6268).+ expect(files).toEqual(['sess-dup.seat.json', 'sess-dup.source.json', 'sess-dup.src-_unresolved.txt']);+ expect(readFileSync(spooled('sess-dup.txt'), 'utf8')).toContain('resumed pass content');});// #5413: a claude-cli scratch session (gbrain's own LLM call) must never@@ -780,8 +782,7 @@ describe('session-end', () => {transcriptRoot: projRoot,}),).toBe(0);- const corpusDir = join(home(), 'transcripts', 'corpus');- expect(existsSync(join(corpusDir, 'sess-self.txt'))).toBe(false);+ expect(existsSync(spooled('sess-self.txt'))).toBe(false);const hb = await lastHeartbeat();expect(hb?.outcome).toBe('ok');expect(hb?.segment).toBe('self_transcript');@@ -798,7 +799,7 @@ describe('session-end', () => {transcriptRoot: projRoot,}),).toBe(0);- expect(existsSync(join(home(), 'transcripts', 'corpus', 'sess-self2.txt'))).toBe(false);+ expect(existsSync(spooled('sess-self2.txt'))).toBe(false);expect((await lastHeartbeat())?.segment).toBe('self_transcript');});@@ -813,8 +814,8 @@ describe('session-end', () => {stdin: JSON.stringify({ session_id: 'sess-resume', transcript_path: t1, cwd: ws }),transcriptRoot: projRoot,});- const corpusDir = join(home(), 'transcripts', 'corpus');- const corpusFile = join(corpusDir, 'sess-resume.txt');+ const corpusDir = join(home(), 'transcripts', 'corpus', 'sourced');+ const corpusFile = spooled('sess-resume.txt');expect(existsSync(corpusFile)).toBe(true);// Simulate the sweep having ingested it (completion sidecar) and a stale@@ -887,7 +888,7 @@ describe('session-end', () => {const status = JSON.parse(readFileSync(await hookStatusPath(), 'utf8'));expect(status.error).toBe('parser_drift');// No corpus file for a drift session.- expect(existsSync(join(home(), 'transcripts', 'corpus', 'sess-drift.txt'))).toBe(false);+ expect(existsSync(spooled('sess-drift.txt'))).toBe(false);});test('confinement rejection: degraded heartbeat, no corpus write [S3#8]', async () => {@@ -900,7 +901,7 @@ describe('session-end', () => {transcriptRoot: join(tmp, 'projects'),});expect((await lastHeartbeat())?.reason).toBe('transcript_outside_projects_dir');- expect(existsSync(join(home(), 'transcripts', 'corpus', 'sess-out.txt'))).toBe(false);+ expect(existsSync(spooled('sess-out.txt'))).toBe(false);});test('GCs this session\'s stop buffer [G15]', async () => {@@ -1484,7 +1485,7 @@ const boundaryLine = () =>JSON.stringify({ type: 'system', subtype: 'compact_boundary', content: 'conversation compacted' });describe('compact segment lane (cathedral 5)', () => {- const corpus = () => join(home(), 'transcripts', 'corpus');+ const corpus = () => join(home(), 'transcripts', 'corpus', 'sourced');test('banks a content-addressed since-last-boundary segment + ledger; heartbeat carries the code', async () => {const projRoot = join(tmp, 'projects');@@ -1581,7 +1582,7 @@ describe('compact segment lane (cathedral 5)', () => {});describe('session-end remainder (cathedral 5 dedup contract)', () => {- const corpus = () => join(home(), 'transcripts', 'corpus');+ const corpus = () => join(home(), 'transcripts', 'corpus', 'sourced');test('remainder-only when the compact-banked segment covers the boundary window', async () => {const projRoot = join(tmp, 'projects');@@ -1606,7 +1607,7 @@ describe('session-end remainder (cathedral 5 dedup contract)', () => {stdin: JSON.stringify({ session_id: 'sess-rem', transcript_path: full, cwd: ws }),transcriptRoot: projRoot,});- const body = readFileSync(join(corpus(), 'sess-rem.txt'), 'utf8');+ const body = readFileSync(spooled('sess-rem.txt'), 'utf8');expect(body).toContain('REMAINDER-TEXT');expect(body).not.toContain('W1-ONLY-TEXT'); // already segment-banked — not re-writtenexpect((await lastHeartbeat())?.segment).toBe('remainder');@@ -1625,7 +1626,7 @@ describe('session-end remainder (cathedral 5 dedup contract)', () => {stdin: JSON.stringify({ session_id: 'sess-fb', transcript_path: full, cwd: ws }),transcriptRoot: projRoot,});- const body = readFileSync(join(corpus(), 'sess-fb.txt'), 'utf8');+ const body = readFileSync(spooled('sess-fb.txt'), 'utf8');expect(body).toContain('W1-TEXT');expect(body).toContain('W2-TEXT');expect((await lastHeartbeat())?.segment).toBe('full_fallback');@@ -1650,7 +1651,7 @@ describe('session-end remainder (cathedral 5 dedup contract)', () => {stdin: JSON.stringify({ session_id: 'sess-skip', transcript_path: full, cwd: ws }),transcriptRoot: projRoot,});- expect(existsSync(join(corpus(), 'sess-skip.txt'))).toBe(false);+ expect(existsSync(spooled('sess-skip.txt'))).toBe(false);expect((await lastHeartbeat())?.segment).toBe('skip_covered');});@@ -1680,7 +1681,7 @@ describe('session-end remainder (cathedral 5 dedup contract)', () => {mkdirSync(corpus(), { recursive: true });writeFileSync(join(corpus(), 'gone.txt.progress'), '{}');writeFileSync(join(corpus(), 'gone.txt.progress.lock'), '');- writeFileSync(join(corpus(), 'sess-prog.txt.progress'), '{"generation":1}');+ writeFileSync(spooled('sess-prog.txt.progress'), '{"generation":1}');const t1 = seedTranscript(join(projRoot, 'p1'), 'r5.jsonl', [userLine('resumed session content')]);await runHook(['session-end'], {stdin: JSON.stringify({ session_id: 'sess-prog', transcript_path: t1, cwd: ws }),@@ -1689,7 +1690,7 @@ describe('session-end remainder (cathedral 5 dedup contract)', () => {const names = readdirSync(corpus());expect(names).not.toContain('gone.txt.progress');expect(names).not.toContain('gone.txt.progress.lock');- expect(names).toContain('sess-prog.txt');- expect(readFileSync(join(corpus(), 'sess-prog.txt.progress'), 'utf8')).toBe('{"generation":1}');+ expect(names).toContain('sess-prog.src-_unresolved.txt');+ expect(readFileSync(spooled('sess-prog.txt.progress'), 'utf8')).toBe('{"generation":1}');});});diff --git a/test/hook-writeback-stop.serial.test.ts b/test/hook-writeback-stop.serial.test.tsindex 8906d7499c..2a0f22bbca 100644--- a/test/hook-writeback-stop.serial.test.ts+++ b/test/hook-writeback-stop.serial.test.ts@@ -42,7 +42,8 @@ afterEach(() => {});const home = () => join(tmp, '.gbrain');-const corpus = () => join(home(), 'transcripts', 'corpus');+// #6268: turn files land in the corpus spool; without GBRAIN_SOURCE or a serve the stamp is unresolved.+const corpus = () => join(home(), 'transcripts', 'corpus', 'sourced');function writeConfig(opts: { writeback?: string; dataDir?: string }): string {mkdirSync(home(), { recursive: true });@@ -188,7 +189,7 @@ describe('hook stop — ambient writeback banking', () => {...io, transcriptRoot: t.root,stdin: JSON.stringify({ session_id: 's-wb', transcript_path: t.path }),})).toBe(0);- const file = readdirSync(corpus()).find((f) => /^s-wb\.wb-[0-9a-f]{24}\.txt$/.test(f));+ const file = readdirSync(corpus()).find((f) => /^s-wb\.wb-[0-9a-f]{24}\.src-_unresolved\.txt$/.test(f));expect(file).toBeDefined();expect(await Bun.file(join(corpus(), file!)).text()).toBe(prompt + '\n');});@@ -201,7 +202,7 @@ describe('hook stop — ambient writeback banking', () => {...io, transcriptRoot: t.root,stdin: JSON.stringify({ session_id: 's-wb', transcript_path: t.path }),})).toBe(0);- const file = readdirSync(corpus()).find((f) => /^s-wb\.wb-[0-9a-f]{24}\.txt$/.test(f));+ const file = readdirSync(corpus()).find((f) => /^s-wb\.wb-[0-9a-f]{24}\.src-_unresolved\.txt$/.test(f));expect(file).toBeDefined();expect(await Bun.file(join(corpus(), file!)).text()).toBe(prompt + '\n');});@@ -223,7 +224,7 @@ describe('hook stop — ambient writeback banking', () => {});expect(code).toBe(0);// The durable artifact exists — the user turn WAS found and banked.- const files = readdirSync(corpus()).filter((f) => /^s-wb\.wb-[0-9a-f]{24}\.txt$/.test(f));+ const files = readdirSync(corpus()).filter((f) => /^s-wb\.wb-[0-9a-f]{24}\.src-_unresolved\.txt$/.test(f));expect(files.length).toBe(1);const hb = await wbHeartbeats();expect(hb.length).toBe(1);@@ -246,7 +247,7 @@ describe('hook stop — ambient writeback banking', () => {stdin: JSON.stringify({ session_id: 's-wb', transcript_path: t.path }),});expect(code).toBe(0);- const files = readdirSync(corpus()).filter((f) => /^s-wb\.wb-[0-9a-f]{24}\.txt$/.test(f));+ const files = readdirSync(corpus()).filter((f) => /^s-wb\.wb-[0-9a-f]{24}\.src-_unresolved\.txt$/.test(f));expect(files.length).toBe(1);const hb = await wbHeartbeats();expect(hb[0].reason).toBe('no_serve');diff --git a/test/managed-sweep-corpus-windows.test.ts b/test/managed-sweep-corpus-windows.test.tsindex 1851a85c77..32b26231f9 100644--- a/test/managed-sweep-corpus-windows.test.ts+++ b/test/managed-sweep-corpus-windows.test.ts@@ -14,6 +14,7 @@** Runs on PGLite; also on Postgres when DATABASE_URL is set (testBackends).*/+import { spoolPath } from './helpers/corpus-spool.ts';import { afterAll, beforeAll, expect, test } from 'bun:test';import { randomUUID } from 'node:crypto';import { mkdirSync, mkdtempSync, renameSync, rmSync, utimesSync, writeFileSync } from 'node:fs';@@ -110,7 +111,7 @@ test('managed: every window commits its own coordinated facts batch; a resume suawait expect(engine.executeRaw(`INSERT INTO facts(source_id,fact,kind,source,visibility) VALUES($1,'uncoordinated','fact','test','private')`,[sourceId])).rejects.toThrow(/writer_coordinator_required/);- const file = join(corpusDir, 'managed-session.txt');+ const file = spoolPath(corpusDir, 'managed-session.txt', sourceId);writeFileSync(file, corpus(3));const sweep = () => runMaintenanceSweep(engine, { sourceId, capabilities: KEYED, budgetMs: 120_000 });const batches = async () => engine.executeRaw<{ n: string }>(@@ -167,7 +168,7 @@ test('managed: facts from a session file written 8 days ago are dated that day',await disposePersistenceConsumer(engine);await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');- const file = join(corpusDir, 'backdated-session.txt');+ const file = spoolPath(corpusDir, 'backdated-session.txt', sourceId);writeFileSync(file, corpus(1));const written = new Date(Date.now() - 8 * 86_400_000);utimesSync(file, written, written);diff --git a/test/managed-sweep-refused-window-retry.test.ts b/test/managed-sweep-refused-window-retry.test.tsindex bb4055bad1..0f8bf7089a 100644--- a/test/managed-sweep-refused-window-retry.test.ts+++ b/test/managed-sweep-refused-window-retry.test.ts@@ -17,6 +17,7 @@** Runs on PGLite; also on Postgres when DATABASE_URL is set (testBackends).*/+import { spoolPath } from './helpers/corpus-spool.ts';import { afterAll, beforeAll, describe, expect, test } from 'bun:test';import { randomUUID } from 'node:crypto';import { appendFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';@@ -118,7 +119,7 @@ async function refusedWindow(engine: BrainEngine, dir: string, pages: Array<typeconst drift = (page: typeof COMPANY) => appendFileSync(fileOf(page), '\nA local edit nobody imported.\n');const repair = (page: typeof COMPANY) => writeFileSync(fileOf(page), pristine.get(page.slug)!);for (const page of drifted) drift(page);- const sessionFile = join(corpusDir, 'example-session.txt');+ const sessionFile = spoolPath(corpusDir, 'example-session.txt', sourceId);writeFileSync(sessionFile, transcript());const logs: string[] = [];const quiet = () => waitFor(async () => (await engine.executeRaw<{ n: number }>(diff --git a/test/session-seat-capture.serial.test.ts b/test/session-seat-capture.serial.test.tsindex 34bb3d9b2c..cb29d7be39 100644--- a/test/session-seat-capture.serial.test.ts+++ b/test/session-seat-capture.serial.test.ts@@ -45,7 +45,8 @@ afterEach(() => {rmSync(tmp, { recursive: true, force: true });});-const corpus = () => join(tmp, '.gbrain', 'transcripts', 'corpus');+// #6268: session files and their seat live in the corpus spool; no GBRAIN_SOURCE or serve here, so stamps are unresolved.+const corpus = () => join(tmp, '.gbrain', 'transcripts', 'corpus', 'sourced');const sidecar = (sid: string) => join(corpus(), `${sid}.seat.json`);const readSeat = (sid: string) => JSON.parse(readFileSync(sidecar(sid), 'utf8')) as Record<string, unknown>;const expectedHomeSeat = (dir: string) =>@@ -80,9 +81,9 @@ describe('seat sidecar on session capture (#4618)', () => {const transcript = seedTranscript(tmp, 's.jsonl', [userLine('a question'), assistantLine('an answer')]);// A directory squatting on the corpus filename makes the corpus rename// fail: whatever exists afterwards was written BEFORE the rename.- mkdirSync(join(corpus(), 'sess-order.txt'), { recursive: true });+ mkdirSync(join(corpus(), 'sess-order.src-_unresolved.txt'), { recursive: true });await sessionEnd('sess-order', tmp, transcript);- expect(statSync(join(corpus(), 'sess-order.txt')).isDirectory()).toBe(true);+ expect(statSync(join(corpus(), 'sess-order.src-_unresolved.txt')).isDirectory()).toBe(true);expect(existsSync(sidecar('sess-order'))).toBe(true);expect(statSync(sidecar('sess-order')).mode & 0o777).toBe(0o600);expect(readSeat('sess-order')).toMatchObject({@@ -92,7 +93,7 @@ describe('seat sidecar on session capture (#4618)', () => {// The ordinary path: corpus file and sidecar side by side, label lowercased.process.env.GBRAIN_SEAT = 'Alice-Desk';await sessionEnd('sess-env', tmp, seedTranscript(tmp, 't.jsonl', [userLine('another question')]));- expect(existsSync(join(corpus(), 'sess-env.txt'))).toBe(true);+ expect(existsSync(join(corpus(), 'sess-env.src-_unresolved.txt'))).toBe(true);expect(readSeat('sess-env')).toMatchObject({ seat: 'alice-desk', seat_source: 'env' });});@@ -124,7 +125,7 @@ describe('seat sidecar on session capture (#4618)', () => {test('GBRAIN_SEAT=off is the opt-out: the corpus is captured with no seat sidecar', async () => {process.env.GBRAIN_SEAT = 'off';await sessionEnd('sess-off', tmp, seedTranscript(tmp, 'off.jsonl', [userLine('no seat please')]));- expect(existsSync(join(corpus(), 'sess-off.txt'))).toBe(true);+ expect(existsSync(join(corpus(), 'sess-off.src-_unresolved.txt'))).toBe(true);expect(existsSync(sidecar('sess-off'))).toBe(false);expect((await lastHeartbeat())?.reason ?? '').not.toMatch(/^seat_/);});@@ -137,7 +138,7 @@ describe('seat sidecar on session capture (#4618)', () => {await sessionEnd('sess-moved', homeB, seedTranscript(homeB, 'm.jsonl', [userLine('started at desk A'), assistantLine('resumed at desk B')]));expect(readFileSync(sidecar('sess-moved'), 'utf8')).toBe(before);expect(readSeat('sess-moved').seat).toBe(expectedHomeSeat(homeA));- expect(readFileSync(join(corpus(), 'sess-moved.txt'), 'utf8')).toContain('resumed at desk B');+ expect(readFileSync(join(corpus(), 'sess-moved.src-_unresolved.txt'), 'utf8')).toContain('resumed at desk B');const hb = await lastHeartbeat();expect(hb?.reason).toBe('seat_conflict');expect(hb?.hint).toContain('first seat is kept');@@ -197,7 +198,7 @@ describe('seat sidecar on session capture (#4618)', () => {write: () => {}, transcriptRoot: join(tmp, 'projects'),stdin: JSON.stringify({ session_id: 'sess-wb', transcript_path: transcript }),})).toBe(0);- expect(readdirSync(corpus()).filter((f) => /^sess-wb\.wb-[0-9a-f]{24}\.txt$/.test(f))).toHaveLength(1);+ expect(readdirSync(corpus()).filter((f) => /^sess-wb\.wb-[0-9a-f]{24}\.src-_unresolved\.txt$/.test(f))).toHaveLength(1);expect(readSeat('sess-wb')).toMatchObject({ seat: 'alice-desk', seat_source: 'env' });});diff --git a/test/sweep-writeback-corpus.test.ts b/test/sweep-writeback-corpus.test.tsindex 62fdaebb5a..7cc830f513 100644--- a/test/sweep-writeback-corpus.test.ts+++ b/test/sweep-writeback-corpus.test.ts@@ -18,7 +18,8 @@ import { tmpdir } from 'node:os';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { runMaintenanceSweep, CORPUS_INGESTED_SUFFIX } from '../src/core/sweep.ts';-import { bankWritebackTurn } from '../src/core/context/corpus-segments.ts';+import { bankWritebackTurn, corpusSpoolDir, ensureCorpusSpoolDir } from '../src/core/context/corpus-segments.ts';+import { spoolPath } from './helpers/corpus-spool.ts';import { gateWritebackTurn } from '../src/core/facts/writeback-gate.ts';import { __setChatTransportForTests, configureGateway, isAvailable, resetGateway, type ChatResult } from '../src/core/ai/gateway.ts';import type { CapabilityReport } from '../src/core/capability.ts';@@ -66,7 +67,7 @@ afterEach(async () => {async function bankWb(sessionId: string, turn: string): Promise<string> {const gated = gateWritebackTurn(turn);if (!gated.ok) throw new Error(`fixture turn gated: ${gated.reason}`);- const banked = await bankWritebackTurn(corpusDir, sessionId, gated.normalized, gated.hash24);+ const banked = await bankWritebackTurn(ensureCorpusSpoolDir(corpusDir), sessionId, gated.normalized, gated.hash24, 'default');if (!banked.flushCorpusFile) throw new Error(`bank failed: ${banked.status}`);return banked.flushCorpusFile;}@@ -91,7 +92,7 @@ describe('runMaintenanceSweep — ambient-writeback turn files (OV2-11)', () =>const file = await bankWb('sess-local-sweep', 'I prefer a local model for my private notes from now on.');const result = await runMaintenanceSweep(engine, { sourceId: 'default' });expect(result.corpusIngested).toBe(1);- expect(existsSync(join(corpusDir, file + CORPUS_INGESTED_SUFFIX))).toBe(true);+ expect(existsSync(join(corpusSpoolDir(corpusDir), file + CORPUS_INGESTED_SUFFIX))).toBe(true);});} finally {await engine.unsetConfig('facts.extraction_model');@@ -110,7 +111,7 @@ describe('runMaintenanceSweep — ambient-writeback turn files (OV2-11)', () =>expect(r.corpusIngested).toBe(0);expect(r.skipped).toContainEqual({ reason: 'writeback_off', count: 1 });expect(chatCalls).toBe(0);- const sidecar = JSON.parse(readFileSync(join(corpusDir, file + CORPUS_INGESTED_SUFFIX), 'utf8'));+ const sidecar = JSON.parse(readFileSync(join(corpusSpoolDir(corpusDir), file + CORPUS_INGESTED_SUFFIX), 'utf8'));expect(sidecar.skipped).toBe('writeback_off');const rows = await engine.executeRaw<{ id: number }>(`SELECT id FROM facts WHERE source = 'hook:writeback'`);expect(rows.length).toBe(0);@@ -140,7 +141,7 @@ describe('runMaintenanceSweep — ambient-writeback turn files (OV2-11)', () =>const r1 = await runMaintenanceSweep(engine, { sourceId: 'default', capabilities: KEYED });expect(r1.corpusIngested).toBe(1);expect(chatCalls).toBe(1);- expect(existsSync(join(corpusDir, file + CORPUS_INGESTED_SUFFIX))).toBe(true);+ expect(existsSync(join(corpusSpoolDir(corpusDir), file + CORPUS_INGESTED_SUFFIX))).toBe(true);const rows = await engine.executeRaw<{ fact: string; source: string; source_session: string }>(`SELECT fact, source, source_session FROM facts WHERE source = 'hook:writeback'`,@@ -175,7 +176,7 @@ describe('runMaintenanceSweep — ambient-writeback turn files (OV2-11)', () =>const file = await bankWb('sess-swpoffkeyless', 'I moved the standing desk into the garden office yesterday.');const r = await runMaintenanceSweep(engine, { sourceId: 'default', capabilities: keyless });expect(r.skipped).toContainEqual({ reason: 'writeback_off', count: 1 });- const sidecar = JSON.parse(readFileSync(join(corpusDir, file + CORPUS_INGESTED_SUFFIX), 'utf8'));+ const sidecar = JSON.parse(readFileSync(join(corpusSpoolDir(corpusDir), file + CORPUS_INGESTED_SUFFIX), 'utf8'));expect(sidecar.skipped).toBe('writeback_off');});@@ -233,8 +234,8 @@ describe('runMaintenanceSweep — ambient-writeback turn files (OV2-11)', () =>expect(r.corpusIngested).toBe(0);expect(r.skipped).toContainEqual({ reason: 'writeback_plane_drift', count: 1 });expect(chatCalls).toBe(0);- expect(existsSync(join(corpusDir, file + CORPUS_INGESTED_SUFFIX))).toBe(false); // NOT terminal- expect(existsSync(join(corpusDir, file))).toBe(true); // survives for re-sync+ expect(existsSync(join(corpusSpoolDir(corpusDir), file + CORPUS_INGESTED_SUFFIX))).toBe(false); // NOT terminal+ expect(existsSync(join(corpusSpoolDir(corpusDir), file))).toBe(true); // survives for re-sync} finally {if (prior !== null) writeFileSync(cfgPath, prior);else rmFile(cfgPath, { force: true });@@ -254,7 +255,7 @@ describe('runMaintenanceSweep — ambient-writeback turn files (OV2-11)', () =>const file = await bankWb('sess-skip', 'I switched my primary editor theme to solarized light last week.');const r = await runMaintenanceSweep(engine, { sourceId: 'default', capabilities: KEYED });expect(r.corpusIngested).toBe(1);- const sidecar = JSON.parse(readFileSync(join(corpusDir, file + CORPUS_INGESTED_SUFFIX), 'utf8'));+ const sidecar = JSON.parse(readFileSync(join(corpusSpoolDir(corpusDir), file + CORPUS_INGESTED_SUFFIX), 'utf8'));expect(sidecar.facts_inserted).toBe(0);expect(typeof sidecar.skipped).toBe('string'); // malformed_output/refusal class — recorded, never a silent zero});@@ -275,7 +276,7 @@ describe('runMaintenanceSweep — pasted content never reaches the extractor (#5const parsed = parseTranscript(join(import.meta.dir, 'fixtures', 'claude-code-paste', 'session.jsonl'));const corpus = toCorpusText(parsed.turns);expect(corpus).toContain('pasted third-party email');- writeFileSync(join(corpusDir, 'sess-paste.txt'), corpus);+ writeFileSync(spoolPath(corpusDir, 'sess-paste.txt'), corpus);const r = await runMaintenanceSweep(engine, { sourceId: 'default', capabilities: KEYED });expect(r.corpusIngested).toBe(1);@@ -284,6 +285,6 @@ describe('runMaintenanceSweep — pasted content never reaches the extractor (#5expect(seen).not.toContain('pasted third-party email');expect(seen).not.toContain('pasted_content');expect(seen).toContain('I prefer dark roast coffee');- expect(readFileSync(join(corpusDir, 'sess-paste.txt'), 'utf8')).toBe(corpus);+ expect(readFileSync(spoolPath(corpusDir, 'sess-paste.txt'), 'utf8')).toBe(corpus);});});diff --git a/test/sweep.test.ts b/test/sweep.test.tsindex 88419751fc..bb15d7b734 100644--- a/test/sweep.test.ts+++ b/test/sweep.test.ts@@ -27,6 +27,7 @@ import { _resetStdoutRedirectForTests } from '../src/core/console-prefix.ts';import type { CapabilityReport } from '../src/core/capability.ts';import { __setChatTransportForTests, type ChatResult } from '../src/core/ai/gateway.ts';import { runServe, type ServeOptions } from '../src/commands/serve.ts';+import { spoolPath } from './helpers/corpus-spool.ts';import { withEnv } from './helpers/with-env.ts';import { runExtract } from '../src/commands/extract.ts';import { _resetWriteThroughCacheForTest } from '../src/core/write-through.ts';@@ -381,7 +382,7 @@ describe('runMaintenanceSweep — watermark progress + link reconciliation (#419describe('runMaintenanceSweep — corpus ingest [CX-P0.1, CX-P0.5]', () => {test('keyless: skipped with reason keyless, sidecar NOT written', async () => {- writeFileSync(join(corpusDir, 'session-1.txt'), 'User said something notable.\n');+ writeFileSync(spoolPath(corpusDir, 'session-1.txt'), 'User said something notable.\n');const r = await runMaintenanceSweep(engine, {sourceId: 'default',@@ -389,7 +390,7 @@ describe('runMaintenanceSweep — corpus ingest [CX-P0.1, CX-P0.5]', () => {});expect(r.corpusIngested).toBe(0);expect(r.skipped).toContainEqual({ reason: 'keyless', count: 1 });- expect(existsSync(join(corpusDir, 'session-1.txt' + CORPUS_INGESTED_SUFFIX))).toBe(false);+ expect(existsSync(spoolPath(corpusDir, 'session-1.txt' + CORPUS_INGESTED_SUFFIX))).toBe(false);});test('keyed: transcript runs through the real pipeline; sidecar written AFTER success; exactly-once', async () => {@@ -397,7 +398,7 @@ describe('runMaintenanceSweep — corpus ingest [CX-P0.1, CX-P0.5]', () => {// operator-set default inside the shared pipeline.await engine.setConfig('facts.default_visibility', 'world');writeFileSync(- join(corpusDir, 'fresh.txt'),+ spoolPath(corpusDir, 'fresh.txt'),'Alice committed to shipping the beta in March.\n',);@@ -429,7 +430,7 @@ describe('runMaintenanceSweep — corpus ingest [CX-P0.1, CX-P0.5]', () => {});expect(r1.corpusIngested).toBe(1);expect(chatCalls).toBe(1);- expect(existsSync(join(corpusDir, 'fresh.txt' + CORPUS_INGESTED_SUFFIX))).toBe(true);+ expect(existsSync(spoolPath(corpusDir, 'fresh.txt' + CORPUS_INGESTED_SUFFIX))).toBe(true);const facts = await engine.executeRaw<{ fact: string; visibility: string; source: string }>(`SELECT fact, visibility, source FROM facts WHERE source = 'sweep:corpus'`,@@ -452,8 +453,8 @@ describe('runMaintenanceSweep — corpus ingest [CX-P0.1, CX-P0.5]', () => {});test('pre-existing sidecar marker → file never touches the pipeline', async () => {- writeFileSync(join(corpusDir, 'done.txt'), 'Already processed content.\n');- writeFileSync(join(corpusDir, 'done.txt' + CORPUS_INGESTED_SUFFIX), '{}\n');+ writeFileSync(spoolPath(corpusDir, 'done.txt'), 'Already processed content.\n');+ writeFileSync(spoolPath(corpusDir, 'done.txt' + CORPUS_INGESTED_SUFFIX), '{}\n');let chatCalls = 0;__setChatTransportForTests(async (): Promise<ChatResult> => {@@ -482,8 +483,8 @@ describe('runMaintenanceSweep — corpus ingest [CX-P0.1, CX-P0.5]', () => {writeFileSync(join(selfProject, `${selfId}.jsonl`), '{"type":"user"}\n');writeFileSync(join(userProject, `${userId}.jsonl`), '{"type":"user"}\n');const selfFiles = [`${selfId}.txt`, `${selfId}.seg-aaaaaaaaaaaa.txt`, `${selfId}.wb-bbbbbbbbbbbbbbbbbbbbbbbb.txt`];- for (const f of selfFiles) writeFileSync(join(corpusDir, f), 'User: <turn>extract facts from this page</turn>\n');- writeFileSync(join(corpusDir, `${userId}.txt`), 'Alice committed to shipping the beta in March.\n');+ for (const f of selfFiles) writeFileSync(spoolPath(corpusDir, f), 'User: <turn>extract facts from this page</turn>\n');+ writeFileSync(spoolPath(corpusDir, `${userId}.txt`), 'Alice committed to shipping the beta in March.\n');let chatCalls = 0;__setChatTransportForTests(async (): Promise<ChatResult> => {@@ -503,8 +504,8 @@ describe('runMaintenanceSweep — corpus ingest [CX-P0.1, CX-P0.5]', () => {expect(chatCalls).toBe(1);expect(r1.corpusIngested).toBe(1);expect(r1.skipped).toContainEqual({ reason: 'self_capture', count: 3 });- for (const f of selfFiles) expect(existsSync(join(corpusDir, f + CORPUS_INGESTED_SUFFIX))).toBe(true);- expect(existsSync(join(corpusDir, `${userId}.txt` + CORPUS_INGESTED_SUFFIX))).toBe(true);+ for (const f of selfFiles) expect(existsSync(spoolPath(corpusDir, f + CORPUS_INGESTED_SUFFIX))).toBe(true);+ expect(existsSync(spoolPath(corpusDir, `${userId}.txt` + CORPUS_INGESTED_SUFFIX))).toBe(true);const r2 = await withEnv({ CLAUDE_CONFIG_DIR: claudeHome }, () =>runMaintenanceSweep(engine, { sourceId: 'default', capabilities: KEYED }));@@ -515,14 +516,14 @@ describe('runMaintenanceSweep — corpus ingest [CX-P0.1, CX-P0.5]', () => {test('extraction_enabled=false spend gate skips without sidecars', async () => {await engine.setConfig('facts.extraction_enabled', 'false');try {- writeFileSync(join(corpusDir, 'gated.txt'), 'Gated content.\n');+ writeFileSync(spoolPath(corpusDir, 'gated.txt'), 'Gated content.\n');const r = await runMaintenanceSweep(engine, {sourceId: 'default',capabilities: KEYED,});expect(r.corpusIngested).toBe(0);expect(r.skipped).toContainEqual({ reason: 'extraction_disabled', count: 1 });- expect(existsSync(join(corpusDir, 'gated.txt' + CORPUS_INGESTED_SUFFIX))).toBe(false);+ expect(existsSync(spoolPath(corpusDir, 'gated.txt' + CORPUS_INGESTED_SUFFIX))).toBe(false);} finally {await engine.setConfig('facts.extraction_enabled', 'true');}@@ -542,8 +543,8 @@ describe('runMaintenanceSweep — corpus claim fencing (concurrent sweeps)', ()});test('two concurrent sweeps on one corpus dir ingest each file exactly once', async () => {- writeFileSync(join(corpusDir, 'race-a.txt'), 'Alice will demo the widget on Monday.\n');- writeFileSync(join(corpusDir, 'race-b.txt'), 'Bob owns the acme-example follow-up.\n');+ writeFileSync(spoolPath(corpusDir, 'race-a.txt'), 'Alice will demo the widget on Monday.\n');+ writeFileSync(spoolPath(corpusDir, 'race-b.txt'), 'Bob owns the acme-example follow-up.\n');let chatCalls = 0;__setChatTransportForTests(async (): Promise<ChatResult> => {@@ -561,16 +562,16 @@ describe('runMaintenanceSweep — corpus claim fencing (concurrent sweeps)', ()// The whole point: one LLM call per FILE, never per (file × sweep).expect(chatCalls).toBe(2);expect(r1.corpusIngested + r2.corpusIngested).toBe(2);- expect(existsSync(join(corpusDir, 'race-a.txt' + CORPUS_INGESTED_SUFFIX))).toBe(true);- expect(existsSync(join(corpusDir, 'race-b.txt' + CORPUS_INGESTED_SUFFIX))).toBe(true);+ expect(existsSync(spoolPath(corpusDir, 'race-a.txt' + CORPUS_INGESTED_SUFFIX))).toBe(true);+ expect(existsSync(spoolPath(corpusDir, 'race-b.txt' + CORPUS_INGESTED_SUFFIX))).toBe(true);// No claim leftovers — success replaces the claim with the .ingested sidecar.- expect(existsSync(join(corpusDir, 'race-a.txt' + CORPUS_CLAIM_SUFFIX))).toBe(false);- expect(existsSync(join(corpusDir, 'race-b.txt' + CORPUS_CLAIM_SUFFIX))).toBe(false);+ expect(existsSync(spoolPath(corpusDir, 'race-a.txt' + CORPUS_CLAIM_SUFFIX))).toBe(false);+ expect(existsSync(spoolPath(corpusDir, 'race-b.txt' + CORPUS_CLAIM_SUFFIX))).toBe(false);});test('a fresh claim held by another sweep skips the file — zero LLM spend, claim untouched', async () => {- writeFileSync(join(corpusDir, 'claimed.txt'), 'Claimed elsewhere.\n');- const claim = join(corpusDir, 'claimed.txt' + CORPUS_CLAIM_SUFFIX);+ writeFileSync(spoolPath(corpusDir, 'claimed.txt'), 'Claimed elsewhere.\n');+ const claim = spoolPath(corpusDir, 'claimed.txt' + CORPUS_CLAIM_SUFFIX);writeFileSync(claim, '{}\n');let chatCalls = 0;@@ -585,12 +586,12 @@ describe('runMaintenanceSweep — corpus claim fencing (concurrent sweeps)', ()expect(r.skipped).toContainEqual({ reason: 'corpus_in_progress', count: 1 });// The live claim belongs to the other sweep — this run must not release it.expect(existsSync(claim)).toBe(true);- expect(existsSync(join(corpusDir, 'claimed.txt' + CORPUS_INGESTED_SUFFIX))).toBe(false);+ expect(existsSync(spoolPath(corpusDir, 'claimed.txt' + CORPUS_INGESTED_SUFFIX))).toBe(false);});test('a stale claim (>1h, dead sweep) is reclaimed and the file ingested', async () => {- writeFileSync(join(corpusDir, 'stale-claim.txt'), 'Left behind by a crashed sweep.\n');- const claim = join(corpusDir, 'stale-claim.txt' + CORPUS_CLAIM_SUFFIX);+ writeFileSync(spoolPath(corpusDir, 'stale-claim.txt'), 'Left behind by a crashed sweep.\n');+ const claim = spoolPath(corpusDir, 'stale-claim.txt' + CORPUS_CLAIM_SUFFIX);writeFileSync(claim, '{}\n');const old = (Date.now() - 2 * 3600 * 1000) / 1000;utimesSync(claim, old, old);@@ -604,7 +605,7 @@ describe('runMaintenanceSweep — corpus claim fencing (concurrent sweeps)', ()const r = await runMaintenanceSweep(engine, { sourceId: 'default', capabilities: KEYED });expect(r.corpusIngested).toBe(1);expect(chatCalls).toBe(1);- expect(existsSync(join(corpusDir, 'stale-claim.txt' + CORPUS_INGESTED_SUFFIX))).toBe(true);+ expect(existsSync(spoolPath(corpusDir, 'stale-claim.txt' + CORPUS_INGESTED_SUFFIX))).toBe(true);expect(existsSync(claim)).toBe(false);});@@ -612,7 +613,7 @@ describe('runMaintenanceSweep — corpus claim fencing (concurrent sweeps)', ()// A directory named like a corpus file: readFile throws EISDIR after the// claim is acquired — a deterministic mid-ingest failure (runFactsPipeline// itself absorbs provider errors, so a throwing transport won't do).- mkdirSync(join(corpusDir, 'flaky.txt'));+ mkdirSync(spoolPath(corpusDir, 'flaky.txt'));__setChatTransportForTests(async (): Promise<ChatResult> => {throw new Error('must not be reached');});@@ -621,8 +622,8 @@ describe('runMaintenanceSweep — corpus claim fencing (concurrent sweeps)', ()expect(r.corpusIngested).toBe(0);expect(r.skipped).toContainEqual({ reason: 'corpus_file_error', count: 1 });// Neither sidecar remains: no .ingested (it failed), no claim (released).- expect(existsSync(join(corpusDir, 'flaky.txt' + CORPUS_CLAIM_SUFFIX))).toBe(false);- expect(existsSync(join(corpusDir, 'flaky.txt' + CORPUS_INGESTED_SUFFIX))).toBe(false);+ expect(existsSync(spoolPath(corpusDir, 'flaky.txt' + CORPUS_CLAIM_SUFFIX))).toBe(false);+ expect(existsSync(spoolPath(corpusDir, 'flaky.txt' + CORPUS_INGESTED_SUFFIX))).toBe(false);});});